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.

279402 lines
7.5MB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-9 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. /*
  19. This monolithic file contains the entire Juce source tree!
  20. To build an app which uses Juce, all you need to do is to add this
  21. file to your project, and include juce.h in your own cpp files.
  22. */
  23. #ifdef __JUCE_JUCEHEADER__
  24. /* When you add the amalgamated cpp file to your project, you mustn't include it in
  25. a file where you've already included juce.h - just put it inside a file on its own,
  26. possibly with your config flags preceding it, but don't include anything else. */
  27. #error
  28. #endif
  29. /*** Start of inlined file: juce_TargetPlatform.h ***/
  30. #ifndef __JUCE_TARGETPLATFORM_JUCEHEADER__
  31. #define __JUCE_TARGETPLATFORM_JUCEHEADER__
  32. /* This file figures out which platform is being built, and defines some macros
  33. that the rest of the code can use for OS-specific compilation.
  34. Macros that will be set here are:
  35. - One of JUCE_WINDOWS, JUCE_MAC or JUCE_LINUX.
  36. - Either JUCE_32BIT or JUCE_64BIT, depending on the architecture.
  37. - Either JUCE_LITTLE_ENDIAN or JUCE_BIG_ENDIAN.
  38. - Either JUCE_INTEL or JUCE_PPC
  39. - Either JUCE_GCC or JUCE_MSVC
  40. */
  41. #if (defined (_WIN32) || defined (_WIN64))
  42. #define JUCE_WIN32 1
  43. #define JUCE_WINDOWS 1
  44. #elif defined (LINUX) || defined (__linux__)
  45. #define JUCE_LINUX 1
  46. #elif defined(__APPLE_CPP__) || defined(__APPLE_CC__)
  47. #include <CoreFoundation/CoreFoundation.h> // (needed to find out what platform we're using)
  48. #if TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR
  49. #define JUCE_IPHONE 1
  50. #define JUCE_IOS 1
  51. #else
  52. #define JUCE_MAC 1
  53. #endif
  54. #else
  55. #error "Unknown platform!"
  56. #endif
  57. #if JUCE_WINDOWS
  58. #ifdef _MSC_VER
  59. #ifdef _WIN64
  60. #define JUCE_64BIT 1
  61. #else
  62. #define JUCE_32BIT 1
  63. #endif
  64. #endif
  65. #ifdef _DEBUG
  66. #define JUCE_DEBUG 1
  67. #endif
  68. #ifdef __MINGW32__
  69. #define JUCE_MINGW 1
  70. #endif
  71. /** If defined, this indicates that the processor is little-endian. */
  72. #define JUCE_LITTLE_ENDIAN 1
  73. #define JUCE_INTEL 1
  74. #endif
  75. #if JUCE_MAC
  76. #ifndef NDEBUG
  77. #define JUCE_DEBUG 1
  78. #endif
  79. #ifdef __LITTLE_ENDIAN__
  80. #define JUCE_LITTLE_ENDIAN 1
  81. #else
  82. #define JUCE_BIG_ENDIAN 1
  83. #endif
  84. #if defined (__ppc__) || defined (__ppc64__)
  85. #define JUCE_PPC 1
  86. #else
  87. #define JUCE_INTEL 1
  88. #endif
  89. #ifdef __LP64__
  90. #define JUCE_64BIT 1
  91. #else
  92. #define JUCE_32BIT 1
  93. #endif
  94. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4
  95. #error "Building for OSX 10.3 is no longer supported!"
  96. #endif
  97. #ifndef MAC_OS_X_VERSION_10_5
  98. #error "To build with 10.4 compatibility, use a 10.5 or 10.6 SDK and set the deployment target to 10.4"
  99. #endif
  100. #endif
  101. #if JUCE_IOS
  102. #ifndef NDEBUG
  103. #define JUCE_DEBUG 1
  104. #endif
  105. #ifdef __LITTLE_ENDIAN__
  106. #define JUCE_LITTLE_ENDIAN 1
  107. #else
  108. #define JUCE_BIG_ENDIAN 1
  109. #endif
  110. #endif
  111. #if JUCE_LINUX
  112. #ifdef _DEBUG
  113. #define JUCE_DEBUG 1
  114. #endif
  115. // Allow override for big-endian Linux platforms
  116. #ifndef JUCE_BIG_ENDIAN
  117. #define JUCE_LITTLE_ENDIAN 1
  118. #endif
  119. #if defined (__LP64__) || defined (_LP64)
  120. #define JUCE_64BIT 1
  121. #else
  122. #define JUCE_32BIT 1
  123. #endif
  124. #define JUCE_INTEL 1
  125. #endif
  126. // Compiler type macros.
  127. #ifdef __GNUC__
  128. #define JUCE_GCC 1
  129. #elif defined (_MSC_VER)
  130. #define JUCE_MSVC 1
  131. #if _MSC_VER >= 1400
  132. #define JUCE_USE_INTRINSICS 1
  133. #endif
  134. #else
  135. #error unknown compiler
  136. #endif
  137. #endif // __JUCE_TARGETPLATFORM_JUCEHEADER__
  138. /*** End of inlined file: juce_TargetPlatform.h ***/
  139. // FORCE_AMALGAMATOR_INCLUDE
  140. /*** Start of inlined file: juce_Config.h ***/
  141. #ifndef __JUCE_CONFIG_JUCEHEADER__
  142. #define __JUCE_CONFIG_JUCEHEADER__
  143. /*
  144. This file contains macros that enable/disable various JUCE features.
  145. */
  146. /** The name of the namespace that all Juce classes and functions will be
  147. put inside. If this is not defined, no namespace will be used.
  148. */
  149. #ifndef JUCE_NAMESPACE
  150. #define JUCE_NAMESPACE juce
  151. #endif
  152. /** JUCE_FORCE_DEBUG: Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and
  153. project settings, but if you define this value, you can override this to force
  154. it to be true or false.
  155. */
  156. #ifndef JUCE_FORCE_DEBUG
  157. //#define JUCE_FORCE_DEBUG 0
  158. #endif
  159. /** JUCE_LOG_ASSERTIONS: If this flag is enabled, the the jassert and jassertfalse
  160. macros will always use Logger::writeToLog() to write a message when an assertion happens.
  161. Enabling it will also leave this turned on in release builds. When it's disabled,
  162. however, the jassert and jassertfalse macros will not be compiled in a
  163. release build.
  164. @see jassert, jassertfalse, Logger
  165. */
  166. #ifndef JUCE_LOG_ASSERTIONS
  167. #define JUCE_LOG_ASSERTIONS 0
  168. #endif
  169. /** JUCE_ASIO: Enables ASIO audio devices (MS Windows only).
  170. Turning this on means that you'll need to have the Steinberg ASIO SDK installed
  171. on your Windows build machine.
  172. See the comments in the ASIOAudioIODevice class's header file for more
  173. info about this.
  174. */
  175. #ifndef JUCE_ASIO
  176. #define JUCE_ASIO 0
  177. #endif
  178. /** JUCE_WASAPI: Enables WASAPI audio devices (Windows Vista and above).
  179. */
  180. #ifndef JUCE_WASAPI
  181. #define JUCE_WASAPI 0
  182. #endif
  183. /** JUCE_DIRECTSOUND: Enables DirectSound audio (MS Windows only).
  184. */
  185. #ifndef JUCE_DIRECTSOUND
  186. #define JUCE_DIRECTSOUND 1
  187. #endif
  188. /** JUCE_ALSA: Enables ALSA audio devices (Linux only). */
  189. #ifndef JUCE_ALSA
  190. #define JUCE_ALSA 1
  191. #endif
  192. /** JUCE_JACK: Enables JACK audio devices (Linux only). */
  193. #ifndef JUCE_JACK
  194. #define JUCE_JACK 0
  195. #endif
  196. /** JUCE_QUICKTIME: Enables the QuickTimeMovieComponent class (Mac and Windows).
  197. If you're building on Windows, you'll need to have the Apple QuickTime SDK
  198. installed, and its header files will need to be on your include path.
  199. */
  200. #if ! (defined (JUCE_QUICKTIME) || JUCE_LINUX || JUCE_IOS || (JUCE_WINDOWS && ! JUCE_MSVC))
  201. #define JUCE_QUICKTIME 0
  202. #endif
  203. #if (JUCE_IOS || JUCE_LINUX) && JUCE_QUICKTIME
  204. #undef JUCE_QUICKTIME
  205. #endif
  206. /** JUCE_OPENGL: Enables the OpenGLComponent class (available on all platforms).
  207. If you're not using OpenGL, you might want to turn this off to reduce your binary's size.
  208. */
  209. #ifndef JUCE_OPENGL
  210. #define JUCE_OPENGL 1
  211. #endif
  212. /** JUCE_DIRECT2D: Enables the Windows 7 Direct2D renderer.
  213. If you're building on a platform older than Vista, you won't be able to compile with this feature.
  214. */
  215. #ifndef JUCE_DIRECT2D
  216. #define JUCE_DIRECT2D 0
  217. #endif
  218. /** JUCE_USE_FLAC: Enables the FLAC audio codec classes (available on all platforms).
  219. If your app doesn't need to read FLAC files, you might want to disable this to
  220. reduce the size of your codebase and build time.
  221. */
  222. #ifndef JUCE_USE_FLAC
  223. #define JUCE_USE_FLAC 1
  224. #endif
  225. /** JUCE_USE_OGGVORBIS: Enables the Ogg-Vorbis audio codec classes (available on all platforms).
  226. If your app doesn't need to read Ogg-Vorbis files, you might want to disable this to
  227. reduce the size of your codebase and build time.
  228. */
  229. #ifndef JUCE_USE_OGGVORBIS
  230. #define JUCE_USE_OGGVORBIS 1
  231. #endif
  232. /** JUCE_USE_CDBURNER: Enables the audio CD reader code (Mac and Windows only).
  233. Unless you're using CD-burning, you should probably turn this flag off to
  234. reduce code size.
  235. */
  236. #if (! defined (JUCE_USE_CDBURNER)) && ! (JUCE_WINDOWS && ! JUCE_MSVC)
  237. #define JUCE_USE_CDBURNER 1
  238. #endif
  239. /** JUCE_USE_CDREADER: Enables the audio CD reader code (Mac and Windows only).
  240. Unless you're using CD-reading, you should probably turn this flag off to
  241. reduce code size.
  242. */
  243. #ifndef JUCE_USE_CDREADER
  244. #define JUCE_USE_CDREADER 1
  245. #endif
  246. /** JUCE_USE_CAMERA: Enables web-cam support using the CameraDevice class (Mac and Windows).
  247. */
  248. #if (JUCE_QUICKTIME || JUCE_WINDOWS) && ! defined (JUCE_USE_CAMERA)
  249. #define JUCE_USE_CAMERA 0
  250. #endif
  251. /** JUCE_ENABLE_REPAINT_DEBUGGING: If this option is turned on, each area of the screen that
  252. gets repainted will flash in a random colour, so that you can check exactly how much and how
  253. often your components are being drawn.
  254. */
  255. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  256. #define JUCE_ENABLE_REPAINT_DEBUGGING 0
  257. #endif
  258. /** JUCE_USE_XINERAMA: Enables Xinerama multi-monitor support (Linux only).
  259. Unless you specifically want to disable this, it's best to leave this option turned on.
  260. */
  261. #ifndef JUCE_USE_XINERAMA
  262. #define JUCE_USE_XINERAMA 1
  263. #endif
  264. /** JUCE_USE_XSHM: Enables X shared memory for faster rendering on Linux. This is best left
  265. turned on unless you have a good reason to disable it.
  266. */
  267. #ifndef JUCE_USE_XSHM
  268. #define JUCE_USE_XSHM 1
  269. #endif
  270. /** JUCE_USE_XRENDER: Uses XRender to allow semi-transparent windowing on Linux.
  271. */
  272. #ifndef JUCE_USE_XRENDER
  273. #define JUCE_USE_XRENDER 0
  274. #endif
  275. /** JUCE_USE_XCURSOR: Uses XCursor to allow ARGB cursor on Linux. This is best left turned on
  276. unless you have a good reason to disable it.
  277. */
  278. #ifndef JUCE_USE_XCURSOR
  279. #define JUCE_USE_XCURSOR 1
  280. #endif
  281. /** JUCE_PLUGINHOST_VST: Enables the VST audio plugin hosting classes. This requires the
  282. Steinberg VST SDK to be installed on your machine, and should be left turned off unless
  283. you're building a plugin hosting app.
  284. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  285. */
  286. #ifndef JUCE_PLUGINHOST_VST
  287. #define JUCE_PLUGINHOST_VST 0
  288. #endif
  289. /** JUCE_PLUGINHOST_AU: Enables the AudioUnit plugin hosting classes. This is Mac-only,
  290. of course, and should only be enabled if you're building a plugin hosting app.
  291. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  292. */
  293. #ifndef JUCE_PLUGINHOST_AU
  294. #define JUCE_PLUGINHOST_AU 0
  295. #endif
  296. /** JUCE_ONLY_BUILD_CORE_LIBRARY: Enabling this will avoid including any UI classes in the build.
  297. This should be enabled if you're writing a console application.
  298. */
  299. #ifndef JUCE_ONLY_BUILD_CORE_LIBRARY
  300. #define JUCE_ONLY_BUILD_CORE_LIBRARY 0
  301. #endif
  302. /** JUCE_WEB_BROWSER: This lets you disable the WebBrowserComponent class (Mac and Windows).
  303. If you're not using any embedded web-pages, turning this off may reduce your code size.
  304. */
  305. #ifndef JUCE_WEB_BROWSER
  306. #define JUCE_WEB_BROWSER 1
  307. #endif
  308. /** JUCE_SUPPORT_CARBON: Enabling this allows the Mac code to use old Carbon library functions.
  309. Carbon isn't required for a normal app, but may be needed by specialised classes like
  310. plugin-hosts, which support older APIs.
  311. */
  312. #if ! (defined (JUCE_SUPPORT_CARBON) || defined (__LP64__))
  313. #define JUCE_SUPPORT_CARBON 1
  314. #endif
  315. /* JUCE_INCLUDE_ZLIB_CODE: Can be used to disable Juce's embedded 3rd-party zlib code.
  316. You might need to tweak this if you're linking to an external zlib library in your app,
  317. but for normal apps, this option should be left alone.
  318. */
  319. #ifndef JUCE_INCLUDE_ZLIB_CODE
  320. #define JUCE_INCLUDE_ZLIB_CODE 1
  321. #endif
  322. #ifndef JUCE_INCLUDE_FLAC_CODE
  323. #define JUCE_INCLUDE_FLAC_CODE 1
  324. #endif
  325. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  326. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  327. #endif
  328. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  329. #define JUCE_INCLUDE_PNGLIB_CODE 1
  330. #endif
  331. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  332. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  333. #endif
  334. /** JUCE_CHECK_MEMORY_LEAKS: Enables a memory-leak check when an app terminates.
  335. (Currently, this only affects Windows builds in debug mode).
  336. */
  337. #ifndef JUCE_CHECK_MEMORY_LEAKS
  338. #define JUCE_CHECK_MEMORY_LEAKS 1
  339. #endif
  340. /** JUCE_CATCH_UNHANDLED_EXCEPTIONS: Turn on juce's internal catching of exceptions
  341. that are thrown by the message dispatch loop. With it enabled, any unhandled exceptions
  342. are passed to the JUCEApplication::unhandledException() callback for logging.
  343. */
  344. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  345. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  346. #endif
  347. // If only building the core classes, we can explicitly turn off some features to avoid including them:
  348. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  349. #undef JUCE_QUICKTIME
  350. #define JUCE_QUICKTIME 0
  351. #undef JUCE_OPENGL
  352. #define JUCE_OPENGL 0
  353. #undef JUCE_USE_CDBURNER
  354. #define JUCE_USE_CDBURNER 0
  355. #undef JUCE_USE_CDREADER
  356. #define JUCE_USE_CDREADER 0
  357. #undef JUCE_WEB_BROWSER
  358. #define JUCE_WEB_BROWSER 0
  359. #undef JUCE_PLUGINHOST_AU
  360. #define JUCE_PLUGINHOST_AU 0
  361. #undef JUCE_PLUGINHOST_VST
  362. #define JUCE_PLUGINHOST_VST 0
  363. #endif
  364. #endif
  365. /*** End of inlined file: juce_Config.h ***/
  366. // FORCE_AMALGAMATOR_INCLUDE
  367. #ifndef JUCE_BUILD_CORE
  368. #define JUCE_BUILD_CORE 1
  369. #endif
  370. #ifndef JUCE_BUILD_MISC
  371. #define JUCE_BUILD_MISC 1
  372. #endif
  373. #ifndef JUCE_BUILD_GUI
  374. #define JUCE_BUILD_GUI 1
  375. #endif
  376. #ifndef JUCE_BUILD_NATIVE
  377. #define JUCE_BUILD_NATIVE 1
  378. #endif
  379. #if JUCE_ONLY_BUILD_CORE_LIBRARY
  380. #undef JUCE_BUILD_MISC
  381. #undef JUCE_BUILD_GUI
  382. #endif
  383. //==============================================================================
  384. #if JUCE_BUILD_NATIVE || JUCE_BUILD_CORE || (JUCE_BUILD_MISC && (JUCE_PLUGINHOST_VST || JUCE_PLUGINHOST_AU))
  385. #if JUCE_WINDOWS
  386. /*** Start of inlined file: juce_win32_NativeIncludes.h ***/
  387. #ifndef __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  388. #define __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  389. #ifndef STRICT
  390. #define STRICT 1
  391. #endif
  392. #undef WIN32_LEAN_AND_MEAN
  393. #define WIN32_LEAN_AND_MEAN 1
  394. #if JUCE_MSVC
  395. #pragma warning (push)
  396. #pragma warning (disable : 4100 4201 4514 4312 4995)
  397. #endif
  398. #define _WIN32_WINNT 0x0500
  399. #define _UNICODE 1
  400. #define UNICODE 1
  401. #ifndef _WIN32_IE
  402. #define _WIN32_IE 0x0400
  403. #endif
  404. #include <windows.h>
  405. #include <windowsx.h>
  406. #include <commdlg.h>
  407. #include <shellapi.h>
  408. #include <mmsystem.h>
  409. #include <vfw.h>
  410. #include <tchar.h>
  411. #include <stddef.h>
  412. #include <ctime>
  413. #include <wininet.h>
  414. #include <nb30.h>
  415. #include <iphlpapi.h>
  416. #include <mapi.h>
  417. #include <float.h>
  418. #include <process.h>
  419. #include <Exdisp.h>
  420. #include <exdispid.h>
  421. #include <shlobj.h>
  422. #if ! JUCE_MINGW
  423. #include <crtdbg.h>
  424. #include <comutil.h>
  425. #endif
  426. #if JUCE_OPENGL
  427. #include <gl/gl.h>
  428. #endif
  429. #undef PACKED
  430. #if JUCE_ASIO
  431. /*
  432. This is very frustrating - we only need to use a handful of definitions from
  433. a couple of the header files in Steinberg's ASIO SDK, and it'd be easy to copy
  434. about 30 lines of code into this cpp file to create a fully stand-alone ASIO
  435. implementation...
  436. ..unfortunately that would break Steinberg's license agreement for use of
  437. their SDK, so I'm not allowed to do this.
  438. This means that anyone who wants to use JUCE's ASIO abilities will have to:
  439. 1) Agree to Steinberg's licensing terms and download the ASIO SDK
  440. (see www.steinberg.net/Steinberg/Developers.asp).
  441. 2) Rebuild the whole of JUCE, setting the global definition JUCE_ASIO (you
  442. can un-comment the "#define JUCE_ASIO" line in juce_Config.h
  443. if you prefer). Make sure that your header search path will find the
  444. iasiodrv.h file that comes with the SDK. (Only about 2-3 of the SDK header
  445. files are actually needed - so to simplify things, you could just copy
  446. these into your JUCE directory).
  447. If you're compiling and you get an error here because you don't have the
  448. ASIO SDK installed, you can disable ASIO support by commenting-out the
  449. "#define JUCE_ASIO" line in juce_Config.h, and rebuild your Juce library.
  450. */
  451. #include "iasiodrv.h"
  452. #endif
  453. #if JUCE_USE_CDBURNER
  454. /* You'll need the Platform SDK for these headers - if you don't have it and don't
  455. need to use CD-burning, then you might just want to disable the JUCE_USE_CDBURNER
  456. flag in juce_Config.h to avoid these includes.
  457. */
  458. #include <imapi.h>
  459. #include <imapierror.h>
  460. #endif
  461. #if JUCE_USE_CAMERA
  462. /* If you're using the camera classes, you'll need access to a few DirectShow headers.
  463. These files are provided in the normal Windows SDK, but some Microsoft plonker
  464. didn't realise that qedit.h doesn't actually compile without the rest of the DirectShow SDK..
  465. Microsoft's suggested fix for this is to hack their qedit.h file! See:
  466. http://social.msdn.microsoft.com/Forums/en-US/windowssdk/thread/ed097d2c-3d68-4f48-8448-277eaaf68252
  467. .. which is a bit of a bodge, but a lot less hassle than installing the full DShow SDK.
  468. An alternative workaround is to create a dummy dxtrans.h file and put it in your include path.
  469. The dummy file just needs to contain the following content:
  470. #define __IDxtCompositor_INTERFACE_DEFINED__
  471. #define __IDxtAlphaSetter_INTERFACE_DEFINED__
  472. #define __IDxtJpeg_INTERFACE_DEFINED__
  473. #define __IDxtKey_INTERFACE_DEFINED__
  474. ..and that should be enough to convince qedit.h that you have the SDK!
  475. */
  476. #include <dshow.h>
  477. #include <qedit.h>
  478. #include <dshowasf.h>
  479. #endif
  480. #if JUCE_WASAPI
  481. #include <MMReg.h>
  482. #include <mmdeviceapi.h>
  483. #include <Audioclient.h>
  484. #include <Avrt.h>
  485. #include <functiondiscoverykeys.h>
  486. #endif
  487. #if JUCE_QUICKTIME
  488. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  489. add its header directory to your include path.
  490. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  491. flag in juce_Config.h
  492. */
  493. #include <Movies.h>
  494. #include <QTML.h>
  495. #include <QuickTimeComponents.h>
  496. #include <MediaHandlers.h>
  497. #include <ImageCodec.h>
  498. /* If you've got QuickTime 7 installed, then these COM objects should be found in
  499. the "\Program Files\Quicktime" directory. You'll need to add this directory to
  500. your include search path to make these import statements work.
  501. */
  502. #import <QTOLibrary.dll>
  503. #import <QTOControl.dll>
  504. #endif
  505. #if JUCE_MSVC
  506. #pragma warning (pop)
  507. #endif
  508. #if JUCE_DIRECT2D
  509. #include <d2d1.h>
  510. #include <dwrite.h>
  511. #endif
  512. /** A simple COM smart pointer.
  513. Avoids having to include ATL just to get one of these.
  514. */
  515. template <class ComClass>
  516. class ComSmartPtr
  517. {
  518. public:
  519. ComSmartPtr() throw() : p (0) {}
  520. ComSmartPtr (ComClass* const p_) : p (p_) { if (p_ != 0) p_->AddRef(); }
  521. ComSmartPtr (const ComSmartPtr<ComClass>& p_) : p (p_.p) { if (p != 0) p->AddRef(); }
  522. ~ComSmartPtr() { release(); }
  523. operator ComClass*() const throw() { return p; }
  524. ComClass& operator*() const throw() { return *p; }
  525. ComClass* operator->() const throw() { return p; }
  526. ComSmartPtr& operator= (ComClass* const newP)
  527. {
  528. if (newP != 0) newP->AddRef();
  529. release();
  530. p = newP;
  531. return *this;
  532. }
  533. ComSmartPtr& operator= (const ComSmartPtr<ComClass>& newP) { return operator= (newP.p); }
  534. // Releases and nullifies this pointer and returns its address
  535. ComClass** resetAndGetPointerAddress()
  536. {
  537. release();
  538. p = 0;
  539. return &p;
  540. }
  541. HRESULT CoCreateInstance (REFCLSID classUUID, DWORD dwClsContext = CLSCTX_INPROC_SERVER)
  542. {
  543. #ifndef __MINGW32__
  544. return ::CoCreateInstance (classUUID, 0, dwClsContext, __uuidof (ComClass), (void**) resetAndGetPointerAddress());
  545. #else
  546. return E_NOTIMPL;
  547. #endif
  548. }
  549. template <class OtherComClass>
  550. HRESULT QueryInterface (REFCLSID classUUID, ComSmartPtr<OtherComClass>& destObject) const
  551. {
  552. if (p == 0)
  553. return E_POINTER;
  554. return p->QueryInterface (classUUID, (void**) destObject.resetAndGetPointerAddress());
  555. }
  556. private:
  557. ComClass* p;
  558. void release() { if (p != 0) p->Release(); }
  559. ComClass** operator&() throw(); // private to avoid it being used accidentally
  560. };
  561. /** Handy base class for writing COM objects, providing ref-counting and a basic QueryInterface method.
  562. */
  563. template <class ComClass>
  564. class ComBaseClassHelper : public ComClass
  565. {
  566. public:
  567. ComBaseClassHelper() : refCount (1) {}
  568. virtual ~ComBaseClassHelper() {}
  569. HRESULT __stdcall QueryInterface (REFIID refId, void __RPC_FAR* __RPC_FAR* result)
  570. {
  571. #ifndef __MINGW32__
  572. if (refId == __uuidof (ComClass)) { AddRef(); *result = dynamic_cast <ComClass*> (this); return S_OK; }
  573. #endif
  574. if (refId == IID_IUnknown) { AddRef(); *result = dynamic_cast <IUnknown*> (this); return S_OK; }
  575. *result = 0;
  576. return E_NOINTERFACE;
  577. }
  578. ULONG __stdcall AddRef() { return ++refCount; }
  579. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  580. protected:
  581. int refCount;
  582. };
  583. #endif // __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  584. /*** End of inlined file: juce_win32_NativeIncludes.h ***/
  585. #elif JUCE_LINUX
  586. /*** Start of inlined file: juce_linux_NativeIncludes.h ***/
  587. #ifndef __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  588. #define __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  589. /*
  590. This file wraps together all the linux-specific headers, so
  591. that we can include them all just once, and compile all our
  592. platform-specific stuff in one big lump, keeping it out of the
  593. way of the rest of the codebase.
  594. */
  595. #include <sched.h>
  596. #include <pthread.h>
  597. #include <sys/time.h>
  598. #include <errno.h>
  599. #include <sys/stat.h>
  600. #include <sys/dir.h>
  601. #include <sys/ptrace.h>
  602. #include <sys/vfs.h>
  603. #include <sys/wait.h>
  604. #include <fnmatch.h>
  605. #include <utime.h>
  606. #include <pwd.h>
  607. #include <fcntl.h>
  608. #include <dlfcn.h>
  609. #include <netdb.h>
  610. #include <arpa/inet.h>
  611. #include <netinet/in.h>
  612. #include <sys/types.h>
  613. #include <sys/ioctl.h>
  614. #include <sys/socket.h>
  615. #include <net/if.h>
  616. #include <sys/sysinfo.h>
  617. #include <sys/file.h>
  618. #include <signal.h>
  619. /* Got a build error here? You'll need to install the freetype library...
  620. The name of the package to install is "libfreetype6-dev".
  621. */
  622. #include <ft2build.h>
  623. #include FT_FREETYPE_H
  624. #include <X11/Xlib.h>
  625. #include <X11/Xatom.h>
  626. #include <X11/Xresource.h>
  627. #include <X11/Xutil.h>
  628. #include <X11/Xmd.h>
  629. #include <X11/keysym.h>
  630. #include <X11/cursorfont.h>
  631. #if JUCE_USE_XINERAMA
  632. /* If you're trying to use Xinerama, you'll need to install the "libxinerama-dev" package.. */
  633. #include <X11/extensions/Xinerama.h>
  634. #endif
  635. #if JUCE_USE_XSHM
  636. #include <X11/extensions/XShm.h>
  637. #include <sys/shm.h>
  638. #include <sys/ipc.h>
  639. #endif
  640. #if JUCE_USE_XRENDER
  641. // If you're missing these headers, try installing the libxrender-dev and libxcomposite-dev
  642. #include <X11/extensions/Xrender.h>
  643. #include <X11/extensions/Xcomposite.h>
  644. #endif
  645. #if JUCE_USE_XCURSOR
  646. // If you're missing this header, try installing the libxcursor-dev package
  647. #include <X11/Xcursor/Xcursor.h>
  648. #endif
  649. #if JUCE_OPENGL
  650. /* Got an include error here?
  651. If you want to install OpenGL support, the packages to get are "mesa-common-dev"
  652. and "freeglut3-dev".
  653. Alternatively, you can turn off the JUCE_OPENGL flag in juce_Config.h if you
  654. want to disable it.
  655. */
  656. #include <GL/glx.h>
  657. #endif
  658. #undef KeyPress
  659. #if JUCE_ALSA
  660. /* Got an include error here? If so, you've either not got ALSA installed, or you've
  661. not got your paths set up correctly to find its header files.
  662. The package you need to install to get ASLA support is "libasound2-dev".
  663. If you don't have the ALSA library and don't want to build Juce with audio support,
  664. just disable the JUCE_ALSA flag in juce_Config.h
  665. */
  666. #include <alsa/asoundlib.h>
  667. #endif
  668. #if JUCE_JACK
  669. /* Got an include error here? If so, you've either not got jack-audio-connection-kit
  670. installed, or you've not got your paths set up correctly to find its header files.
  671. The package you need to install to get JACK support is "libjack-dev".
  672. If you don't have the jack-audio-connection-kit library and don't want to build
  673. Juce with low latency audio support, just disable the JUCE_JACK flag in juce_Config.h
  674. */
  675. #include <jack/jack.h>
  676. //#include <jack/transport.h>
  677. #endif
  678. #undef SIZEOF
  679. #endif // __JUCE_LINUX_NATIVEINCLUDES_JUCEHEADER__
  680. /*** End of inlined file: juce_linux_NativeIncludes.h ***/
  681. #elif JUCE_MAC || JUCE_IPHONE
  682. /*** Start of inlined file: juce_mac_NativeIncludes.h ***/
  683. #ifndef __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  684. #define __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  685. /*
  686. This file wraps together all the mac-specific code, so that
  687. we can include all the native headers just once, and compile all our
  688. platform-specific stuff in one big lump, keeping it out of the way of
  689. the rest of the codebase.
  690. */
  691. #define USE_COREGRAPHICS_RENDERING 1
  692. #if JUCE_IOS
  693. #import <Foundation/Foundation.h>
  694. #import <UIKit/UIKit.h>
  695. #import <AudioToolbox/AudioToolbox.h>
  696. #import <AVFoundation/AVFoundation.h>
  697. #import <CoreData/CoreData.h>
  698. #import <MobileCoreServices/MobileCoreServices.h>
  699. #import <QuartzCore/QuartzCore.h>
  700. #include <sys/fcntl.h>
  701. #if JUCE_OPENGL
  702. #include <OpenGLES/ES1/gl.h>
  703. #include <OpenGLES/ES1/glext.h>
  704. #endif
  705. #else
  706. #import <Cocoa/Cocoa.h>
  707. #import <CoreAudio/HostTime.h>
  708. #import <CoreAudio/AudioHardware.h>
  709. #import <CoreMIDI/MIDIServices.h>
  710. #import <QTKit/QTKit.h>
  711. #import <WebKit/WebKit.h>
  712. #import <DiscRecording/DiscRecording.h>
  713. #import <IOKit/IOKitLib.h>
  714. #import <IOKit/IOCFPlugIn.h>
  715. #import <IOKit/hid/IOHIDLib.h>
  716. #import <IOKit/hid/IOHIDKeys.h>
  717. #import <IOKit/pwr_mgt/IOPMLib.h>
  718. #include <Carbon/Carbon.h>
  719. #include <sys/dir.h>
  720. #endif
  721. #include <sys/socket.h>
  722. #include <sys/sysctl.h>
  723. #include <sys/stat.h>
  724. #include <sys/param.h>
  725. #include <sys/mount.h>
  726. #include <fnmatch.h>
  727. #include <utime.h>
  728. #include <dlfcn.h>
  729. #include <ifaddrs.h>
  730. #include <net/if_dl.h>
  731. #include <mach/mach_time.h>
  732. #include <mach-o/dyld.h>
  733. #if MACOS_10_4_OR_EARLIER
  734. #include <GLUT/glut.h>
  735. #endif
  736. #if ! CGFLOAT_DEFINED
  737. #define CGFloat float
  738. #endif
  739. #endif // __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  740. /*** End of inlined file: juce_mac_NativeIncludes.h ***/
  741. #else
  742. #error "Unknown platform!"
  743. #endif
  744. #endif
  745. //==============================================================================
  746. #define DONT_SET_USING_JUCE_NAMESPACE 1
  747. #undef max
  748. #undef min
  749. #define NO_DUMMY_DECL
  750. #if JUCE_BUILD_NATIVE
  751. #include "juce_amalgamated.h" // FORCE_AMALGAMATOR_INCLUDE
  752. #endif
  753. #if (defined(_MSC_VER) && (_MSC_VER <= 1200))
  754. #pragma warning (disable: 4309 4305)
  755. #endif
  756. #if JUCE_MAC && JUCE_32BIT && JUCE_SUPPORT_CARBON && JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  757. BEGIN_JUCE_NAMESPACE
  758. /*** Start of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  759. #ifndef __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  760. #define __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  761. /**
  762. Creates a floating carbon window that can be used to hold a carbon UI.
  763. This is a handy class that's designed to be inlined where needed, e.g.
  764. in the audio plugin hosting code.
  765. */
  766. class CarbonViewWrapperComponent : public Component,
  767. public ComponentMovementWatcher,
  768. public Timer
  769. {
  770. public:
  771. CarbonViewWrapperComponent()
  772. : ComponentMovementWatcher (this),
  773. wrapperWindow (0),
  774. carbonWindow (0),
  775. embeddedView (0),
  776. recursiveResize (false)
  777. {
  778. }
  779. virtual ~CarbonViewWrapperComponent()
  780. {
  781. jassert (embeddedView == 0); // must call deleteWindow() in the subclass's destructor!
  782. }
  783. virtual HIViewRef attachView (WindowRef windowRef, HIViewRef rootView) = 0;
  784. virtual void removeView (HIViewRef embeddedView) = 0;
  785. virtual void mouseDown (int, int) {}
  786. virtual void paint() {}
  787. virtual bool getEmbeddedViewSize (int& w, int& h)
  788. {
  789. if (embeddedView == 0)
  790. return false;
  791. HIRect bounds;
  792. HIViewGetBounds (embeddedView, &bounds);
  793. w = jmax (1, roundToInt (bounds.size.width));
  794. h = jmax (1, roundToInt (bounds.size.height));
  795. return true;
  796. }
  797. void createWindow()
  798. {
  799. if (wrapperWindow == 0)
  800. {
  801. Rect r;
  802. r.left = getScreenX();
  803. r.top = getScreenY();
  804. r.right = r.left + getWidth();
  805. r.bottom = r.top + getHeight();
  806. CreateNewWindow (kDocumentWindowClass,
  807. (WindowAttributes) (kWindowStandardHandlerAttribute | kWindowCompositingAttribute
  808. | kWindowNoShadowAttribute | kWindowNoTitleBarAttribute),
  809. &r, &wrapperWindow);
  810. jassert (wrapperWindow != 0);
  811. if (wrapperWindow == 0)
  812. return;
  813. carbonWindow = [[NSWindow alloc] initWithWindowRef: wrapperWindow];
  814. NSWindow* ownerWindow = [((NSView*) getWindowHandle()) window];
  815. [ownerWindow addChildWindow: carbonWindow
  816. ordered: NSWindowAbove];
  817. embeddedView = attachView (wrapperWindow, HIViewGetRoot (wrapperWindow));
  818. EventTypeSpec windowEventTypes[] =
  819. {
  820. { kEventClassWindow, kEventWindowGetClickActivation },
  821. { kEventClassWindow, kEventWindowHandleDeactivate },
  822. { kEventClassWindow, kEventWindowBoundsChanging },
  823. { kEventClassMouse, kEventMouseDown },
  824. { kEventClassMouse, kEventMouseMoved },
  825. { kEventClassMouse, kEventMouseDragged },
  826. { kEventClassMouse, kEventMouseUp},
  827. { kEventClassWindow, kEventWindowDrawContent },
  828. { kEventClassWindow, kEventWindowShown },
  829. { kEventClassWindow, kEventWindowHidden }
  830. };
  831. EventHandlerUPP upp = NewEventHandlerUPP (carbonEventCallback);
  832. InstallWindowEventHandler (wrapperWindow, upp,
  833. sizeof (windowEventTypes) / sizeof (EventTypeSpec),
  834. windowEventTypes, this, &eventHandlerRef);
  835. setOurSizeToEmbeddedViewSize();
  836. setEmbeddedWindowToOurSize();
  837. creationTime = Time::getCurrentTime();
  838. }
  839. }
  840. void deleteWindow()
  841. {
  842. removeView (embeddedView);
  843. embeddedView = 0;
  844. if (wrapperWindow != 0)
  845. {
  846. RemoveEventHandler (eventHandlerRef);
  847. DisposeWindow (wrapperWindow);
  848. wrapperWindow = 0;
  849. }
  850. }
  851. void setOurSizeToEmbeddedViewSize()
  852. {
  853. int w, h;
  854. if (getEmbeddedViewSize (w, h))
  855. {
  856. if (w != getWidth() || h != getHeight())
  857. {
  858. startTimer (50);
  859. setSize (w, h);
  860. if (getParentComponent() != 0)
  861. getParentComponent()->setSize (w, h);
  862. }
  863. else
  864. {
  865. startTimer (jlimit (50, 500, getTimerInterval() + 20));
  866. }
  867. }
  868. else
  869. {
  870. stopTimer();
  871. }
  872. }
  873. void setEmbeddedWindowToOurSize()
  874. {
  875. if (! recursiveResize)
  876. {
  877. recursiveResize = true;
  878. if (embeddedView != 0)
  879. {
  880. HIRect r;
  881. r.origin.x = 0;
  882. r.origin.y = 0;
  883. r.size.width = (float) getWidth();
  884. r.size.height = (float) getHeight();
  885. HIViewSetFrame (embeddedView, &r);
  886. }
  887. if (wrapperWindow != 0)
  888. {
  889. Rect wr;
  890. wr.left = getScreenX();
  891. wr.top = getScreenY();
  892. wr.right = wr.left + getWidth();
  893. wr.bottom = wr.top + getHeight();
  894. SetWindowBounds (wrapperWindow, kWindowContentRgn, &wr);
  895. ShowWindow (wrapperWindow);
  896. }
  897. recursiveResize = false;
  898. }
  899. }
  900. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  901. {
  902. setEmbeddedWindowToOurSize();
  903. }
  904. void componentPeerChanged()
  905. {
  906. deleteWindow();
  907. createWindow();
  908. }
  909. void componentVisibilityChanged (Component&)
  910. {
  911. if (isShowing())
  912. createWindow();
  913. else
  914. deleteWindow();
  915. setEmbeddedWindowToOurSize();
  916. }
  917. static void recursiveHIViewRepaint (HIViewRef view)
  918. {
  919. HIViewSetNeedsDisplay (view, true);
  920. HIViewRef child = HIViewGetFirstSubview (view);
  921. while (child != 0)
  922. {
  923. recursiveHIViewRepaint (child);
  924. child = HIViewGetNextView (child);
  925. }
  926. }
  927. void timerCallback()
  928. {
  929. setOurSizeToEmbeddedViewSize();
  930. // To avoid strange overpainting problems when the UI is first opened, we'll
  931. // repaint it a few times during the first second that it's on-screen..
  932. if ((Time::getCurrentTime() - creationTime).inMilliseconds() < 1000)
  933. recursiveHIViewRepaint (HIViewGetRoot (wrapperWindow));
  934. }
  935. OSStatus carbonEventHandler (EventHandlerCallRef /*nextHandlerRef*/, EventRef event)
  936. {
  937. switch (GetEventKind (event))
  938. {
  939. case kEventWindowHandleDeactivate:
  940. ActivateWindow (wrapperWindow, TRUE);
  941. return noErr;
  942. case kEventWindowGetClickActivation:
  943. {
  944. getTopLevelComponent()->toFront (false);
  945. [carbonWindow makeKeyAndOrderFront: nil];
  946. ClickActivationResult howToHandleClick = kActivateAndHandleClick;
  947. SetEventParameter (event, kEventParamClickActivation, typeClickActivationResult,
  948. sizeof (ClickActivationResult), &howToHandleClick);
  949. HIViewSetNeedsDisplay (embeddedView, true);
  950. return noErr;
  951. }
  952. }
  953. return eventNotHandledErr;
  954. }
  955. static pascal OSStatus carbonEventCallback (EventHandlerCallRef nextHandlerRef, EventRef event, void* userData)
  956. {
  957. return ((CarbonViewWrapperComponent*) userData)->carbonEventHandler (nextHandlerRef, event);
  958. }
  959. protected:
  960. WindowRef wrapperWindow;
  961. NSWindow* carbonWindow;
  962. HIViewRef embeddedView;
  963. bool recursiveResize;
  964. Time creationTime;
  965. EventHandlerRef eventHandlerRef;
  966. };
  967. #endif // __JUCE_MAC_CARBONVIEWWRAPPERCOMPONENT_JUCEHEADER__
  968. /*** End of inlined file: juce_mac_CarbonViewWrapperComponent.h ***/
  969. END_JUCE_NAMESPACE
  970. #endif
  971. #define JUCE_AMALGAMATED_TEMPLATE 1
  972. //==============================================================================
  973. #if JUCE_BUILD_CORE
  974. /*** Start of inlined file: juce_FileLogger.cpp ***/
  975. BEGIN_JUCE_NAMESPACE
  976. FileLogger::FileLogger (const File& logFile_,
  977. const String& welcomeMessage,
  978. const int maxInitialFileSizeBytes)
  979. : logFile (logFile_)
  980. {
  981. if (maxInitialFileSizeBytes >= 0)
  982. trimFileSize (maxInitialFileSizeBytes);
  983. if (! logFile_.exists())
  984. {
  985. // do this so that the parent directories get created..
  986. logFile_.create();
  987. }
  988. String welcome;
  989. welcome << "\r\n**********************************************************\r\n"
  990. << welcomeMessage
  991. << "\r\nLog started: " << Time::getCurrentTime().toString (true, true)
  992. << "\r\n";
  993. logMessage (welcome);
  994. }
  995. FileLogger::~FileLogger()
  996. {
  997. }
  998. void FileLogger::logMessage (const String& message)
  999. {
  1000. DBG (message);
  1001. const ScopedLock sl (logLock);
  1002. FileOutputStream out (logFile, 256);
  1003. out << message << "\r\n";
  1004. }
  1005. void FileLogger::trimFileSize (int maxFileSizeBytes) const
  1006. {
  1007. if (maxFileSizeBytes <= 0)
  1008. {
  1009. logFile.deleteFile();
  1010. }
  1011. else
  1012. {
  1013. const int64 fileSize = logFile.getSize();
  1014. if (fileSize > maxFileSizeBytes)
  1015. {
  1016. ScopedPointer <FileInputStream> in (logFile.createInputStream());
  1017. jassert (in != 0);
  1018. if (in != 0)
  1019. {
  1020. in->setPosition (fileSize - maxFileSizeBytes);
  1021. String content;
  1022. {
  1023. MemoryBlock contentToSave;
  1024. contentToSave.setSize (maxFileSizeBytes + 4);
  1025. contentToSave.fillWith (0);
  1026. in->read (contentToSave.getData(), maxFileSizeBytes);
  1027. in = 0;
  1028. content = contentToSave.toString();
  1029. }
  1030. int newStart = 0;
  1031. while (newStart < fileSize
  1032. && content[newStart] != '\n'
  1033. && content[newStart] != '\r')
  1034. ++newStart;
  1035. logFile.deleteFile();
  1036. logFile.appendText (content.substring (newStart), false, false);
  1037. }
  1038. }
  1039. }
  1040. }
  1041. FileLogger* FileLogger::createDefaultAppLogger (const String& logFileSubDirectoryName,
  1042. const String& logFileName,
  1043. const String& welcomeMessage,
  1044. const int maxInitialFileSizeBytes)
  1045. {
  1046. #if JUCE_MAC
  1047. File logFile ("~/Library/Logs");
  1048. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1049. .getChildFile (logFileName);
  1050. #else
  1051. File logFile (File::getSpecialLocation (File::userApplicationDataDirectory));
  1052. if (logFile.isDirectory())
  1053. {
  1054. logFile = logFile.getChildFile (logFileSubDirectoryName)
  1055. .getChildFile (logFileName);
  1056. }
  1057. #endif
  1058. return new FileLogger (logFile, welcomeMessage, maxInitialFileSizeBytes);
  1059. }
  1060. END_JUCE_NAMESPACE
  1061. /*** End of inlined file: juce_FileLogger.cpp ***/
  1062. /*** Start of inlined file: juce_Logger.cpp ***/
  1063. BEGIN_JUCE_NAMESPACE
  1064. Logger::Logger()
  1065. {
  1066. }
  1067. Logger::~Logger()
  1068. {
  1069. }
  1070. Logger* Logger::currentLogger = 0;
  1071. void Logger::setCurrentLogger (Logger* const newLogger,
  1072. const bool deleteOldLogger)
  1073. {
  1074. Logger* const oldLogger = currentLogger;
  1075. currentLogger = newLogger;
  1076. if (deleteOldLogger)
  1077. delete oldLogger;
  1078. }
  1079. void Logger::writeToLog (const String& message)
  1080. {
  1081. if (currentLogger != 0)
  1082. currentLogger->logMessage (message);
  1083. else
  1084. outputDebugString (message);
  1085. }
  1086. #if JUCE_LOG_ASSERTIONS
  1087. void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw()
  1088. {
  1089. String m ("JUCE Assertion failure in ");
  1090. m << filename << ", line " << lineNum;
  1091. Logger::writeToLog (m);
  1092. }
  1093. #endif
  1094. END_JUCE_NAMESPACE
  1095. /*** End of inlined file: juce_Logger.cpp ***/
  1096. /*** Start of inlined file: juce_Random.cpp ***/
  1097. BEGIN_JUCE_NAMESPACE
  1098. Random::Random (const int64 seedValue) throw()
  1099. : seed (seedValue)
  1100. {
  1101. }
  1102. Random::~Random() throw()
  1103. {
  1104. }
  1105. void Random::setSeed (const int64 newSeed) throw()
  1106. {
  1107. seed = newSeed;
  1108. }
  1109. void Random::combineSeed (const int64 seedValue) throw()
  1110. {
  1111. seed ^= nextInt64() ^ seedValue;
  1112. }
  1113. void Random::setSeedRandomly()
  1114. {
  1115. combineSeed ((int64) (pointer_sized_int) this);
  1116. combineSeed (Time::getMillisecondCounter());
  1117. combineSeed (Time::getHighResolutionTicks());
  1118. combineSeed (Time::getHighResolutionTicksPerSecond());
  1119. combineSeed (Time::currentTimeMillis());
  1120. }
  1121. int Random::nextInt() throw()
  1122. {
  1123. seed = (seed * literal64bit (0x5deece66d) + 11) & literal64bit (0xffffffffffff);
  1124. return (int) (seed >> 16);
  1125. }
  1126. int Random::nextInt (const int maxValue) throw()
  1127. {
  1128. jassert (maxValue > 0);
  1129. return (nextInt() & 0x7fffffff) % maxValue;
  1130. }
  1131. int64 Random::nextInt64() throw()
  1132. {
  1133. return (((int64) nextInt()) << 32) | (int64) (uint64) (uint32) nextInt();
  1134. }
  1135. bool Random::nextBool() throw()
  1136. {
  1137. return (nextInt() & 0x80000000) != 0;
  1138. }
  1139. float Random::nextFloat() throw()
  1140. {
  1141. return static_cast <uint32> (nextInt()) / (float) 0xffffffff;
  1142. }
  1143. double Random::nextDouble() throw()
  1144. {
  1145. return static_cast <uint32> (nextInt()) / (double) 0xffffffff;
  1146. }
  1147. const BigInteger Random::nextLargeNumber (const BigInteger& maximumValue)
  1148. {
  1149. BigInteger n;
  1150. do
  1151. {
  1152. fillBitsRandomly (n, 0, maximumValue.getHighestBit() + 1);
  1153. }
  1154. while (n >= maximumValue);
  1155. return n;
  1156. }
  1157. void Random::fillBitsRandomly (BigInteger& arrayToChange, int startBit, int numBits)
  1158. {
  1159. arrayToChange.setBit (startBit + numBits - 1, true); // to force the array to pre-allocate space
  1160. while ((startBit & 31) != 0 && numBits > 0)
  1161. {
  1162. arrayToChange.setBit (startBit++, nextBool());
  1163. --numBits;
  1164. }
  1165. while (numBits >= 32)
  1166. {
  1167. arrayToChange.setBitRangeAsInt (startBit, 32, (unsigned int) nextInt());
  1168. startBit += 32;
  1169. numBits -= 32;
  1170. }
  1171. while (--numBits >= 0)
  1172. arrayToChange.setBit (startBit + numBits, nextBool());
  1173. }
  1174. Random& Random::getSystemRandom() throw()
  1175. {
  1176. static Random sysRand (1);
  1177. return sysRand;
  1178. }
  1179. END_JUCE_NAMESPACE
  1180. /*** End of inlined file: juce_Random.cpp ***/
  1181. /*** Start of inlined file: juce_RelativeTime.cpp ***/
  1182. BEGIN_JUCE_NAMESPACE
  1183. RelativeTime::RelativeTime (const double seconds_) throw()
  1184. : seconds (seconds_)
  1185. {
  1186. }
  1187. RelativeTime::RelativeTime (const RelativeTime& other) throw()
  1188. : seconds (other.seconds)
  1189. {
  1190. }
  1191. RelativeTime::~RelativeTime() throw()
  1192. {
  1193. }
  1194. const RelativeTime RelativeTime::milliseconds (const int milliseconds) throw()
  1195. {
  1196. return RelativeTime (milliseconds * 0.001);
  1197. }
  1198. const RelativeTime RelativeTime::milliseconds (const int64 milliseconds) throw()
  1199. {
  1200. return RelativeTime (milliseconds * 0.001);
  1201. }
  1202. const RelativeTime RelativeTime::minutes (const double numberOfMinutes) throw()
  1203. {
  1204. return RelativeTime (numberOfMinutes * 60.0);
  1205. }
  1206. const RelativeTime RelativeTime::hours (const double numberOfHours) throw()
  1207. {
  1208. return RelativeTime (numberOfHours * (60.0 * 60.0));
  1209. }
  1210. const RelativeTime RelativeTime::days (const double numberOfDays) throw()
  1211. {
  1212. return RelativeTime (numberOfDays * (60.0 * 60.0 * 24.0));
  1213. }
  1214. const RelativeTime RelativeTime::weeks (const double numberOfWeeks) throw()
  1215. {
  1216. return RelativeTime (numberOfWeeks * (60.0 * 60.0 * 24.0 * 7.0));
  1217. }
  1218. int64 RelativeTime::inMilliseconds() const throw()
  1219. {
  1220. return (int64) (seconds * 1000.0);
  1221. }
  1222. double RelativeTime::inMinutes() const throw()
  1223. {
  1224. return seconds / 60.0;
  1225. }
  1226. double RelativeTime::inHours() const throw()
  1227. {
  1228. return seconds / (60.0 * 60.0);
  1229. }
  1230. double RelativeTime::inDays() const throw()
  1231. {
  1232. return seconds / (60.0 * 60.0 * 24.0);
  1233. }
  1234. double RelativeTime::inWeeks() const throw()
  1235. {
  1236. return seconds / (60.0 * 60.0 * 24.0 * 7.0);
  1237. }
  1238. const String RelativeTime::getDescription (const String& returnValueForZeroTime) const
  1239. {
  1240. if (seconds < 0.001 && seconds > -0.001)
  1241. return returnValueForZeroTime;
  1242. String result;
  1243. if (seconds < 0)
  1244. result = "-";
  1245. int fieldsShown = 0;
  1246. int n = abs ((int) inWeeks());
  1247. if (n > 0)
  1248. {
  1249. result << n << ((n == 1) ? TRANS(" week ")
  1250. : TRANS(" weeks "));
  1251. ++fieldsShown;
  1252. }
  1253. n = abs ((int) inDays()) % 7;
  1254. if (n > 0)
  1255. {
  1256. result << n << ((n == 1) ? TRANS(" day ")
  1257. : TRANS(" days "));
  1258. ++fieldsShown;
  1259. }
  1260. if (fieldsShown < 2)
  1261. {
  1262. n = abs ((int) inHours()) % 24;
  1263. if (n > 0)
  1264. {
  1265. result << n << ((n == 1) ? TRANS(" hr ")
  1266. : TRANS(" hrs "));
  1267. ++fieldsShown;
  1268. }
  1269. if (fieldsShown < 2)
  1270. {
  1271. n = abs ((int) inMinutes()) % 60;
  1272. if (n > 0)
  1273. {
  1274. result << n << ((n == 1) ? TRANS(" min ")
  1275. : TRANS(" mins "));
  1276. ++fieldsShown;
  1277. }
  1278. if (fieldsShown < 2)
  1279. {
  1280. n = abs ((int) inSeconds()) % 60;
  1281. if (n > 0)
  1282. {
  1283. result << n << ((n == 1) ? TRANS(" sec ")
  1284. : TRANS(" secs "));
  1285. ++fieldsShown;
  1286. }
  1287. if (fieldsShown < 1)
  1288. {
  1289. n = abs ((int) inMilliseconds()) % 1000;
  1290. if (n > 0)
  1291. {
  1292. result << n << TRANS(" ms");
  1293. ++fieldsShown;
  1294. }
  1295. }
  1296. }
  1297. }
  1298. }
  1299. return result.trimEnd();
  1300. }
  1301. RelativeTime& RelativeTime::operator= (const RelativeTime& other) throw()
  1302. {
  1303. seconds = other.seconds;
  1304. return *this;
  1305. }
  1306. bool RelativeTime::operator== (const RelativeTime& other) const throw() { return seconds == other.seconds; }
  1307. bool RelativeTime::operator!= (const RelativeTime& other) const throw() { return seconds != other.seconds; }
  1308. bool RelativeTime::operator> (const RelativeTime& other) const throw() { return seconds > other.seconds; }
  1309. bool RelativeTime::operator< (const RelativeTime& other) const throw() { return seconds < other.seconds; }
  1310. bool RelativeTime::operator>= (const RelativeTime& other) const throw() { return seconds >= other.seconds; }
  1311. bool RelativeTime::operator<= (const RelativeTime& other) const throw() { return seconds <= other.seconds; }
  1312. const RelativeTime RelativeTime::operator+ (const RelativeTime& timeToAdd) const throw()
  1313. {
  1314. return RelativeTime (seconds + timeToAdd.seconds);
  1315. }
  1316. const RelativeTime RelativeTime::operator- (const RelativeTime& timeToSubtract) const throw()
  1317. {
  1318. return RelativeTime (seconds - timeToSubtract.seconds);
  1319. }
  1320. const RelativeTime RelativeTime::operator+ (const double secondsToAdd) const throw()
  1321. {
  1322. return RelativeTime (seconds + secondsToAdd);
  1323. }
  1324. const RelativeTime RelativeTime::operator- (const double secondsToSubtract) const throw()
  1325. {
  1326. return RelativeTime (seconds - secondsToSubtract);
  1327. }
  1328. const RelativeTime& RelativeTime::operator+= (const RelativeTime& timeToAdd) throw()
  1329. {
  1330. seconds += timeToAdd.seconds;
  1331. return *this;
  1332. }
  1333. const RelativeTime& RelativeTime::operator-= (const RelativeTime& timeToSubtract) throw()
  1334. {
  1335. seconds -= timeToSubtract.seconds;
  1336. return *this;
  1337. }
  1338. const RelativeTime& RelativeTime::operator+= (const double secondsToAdd) throw()
  1339. {
  1340. seconds += secondsToAdd;
  1341. return *this;
  1342. }
  1343. const RelativeTime& RelativeTime::operator-= (const double secondsToSubtract) throw()
  1344. {
  1345. seconds -= secondsToSubtract;
  1346. return *this;
  1347. }
  1348. END_JUCE_NAMESPACE
  1349. /*** End of inlined file: juce_RelativeTime.cpp ***/
  1350. /*** Start of inlined file: juce_SystemStats.cpp ***/
  1351. BEGIN_JUCE_NAMESPACE
  1352. SystemStats::CPUFlags SystemStats::cpuFlags;
  1353. const String SystemStats::getJUCEVersion()
  1354. {
  1355. return "JUCE v" + String (JUCE_MAJOR_VERSION)
  1356. + "." + String (JUCE_MINOR_VERSION)
  1357. + "." + String (JUCE_BUILDNUMBER);
  1358. }
  1359. const StringArray SystemStats::getMACAddressStrings()
  1360. {
  1361. int64 macAddresses [16];
  1362. const int numAddresses = getMACAddresses (macAddresses, numElementsInArray (macAddresses), false);
  1363. StringArray s;
  1364. for (int i = 0; i < numAddresses; ++i)
  1365. {
  1366. s.add (String::toHexString (0xff & (int) (macAddresses [i] >> 40)).paddedLeft ('0', 2)
  1367. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 32)).paddedLeft ('0', 2)
  1368. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 24)).paddedLeft ('0', 2)
  1369. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 16)).paddedLeft ('0', 2)
  1370. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 8)).paddedLeft ('0', 2)
  1371. + "-" + String::toHexString (0xff & (int) (macAddresses [i] >> 0)).paddedLeft ('0', 2));
  1372. }
  1373. return s;
  1374. }
  1375. #ifdef JUCE_DLL
  1376. void* juce_Malloc (const int size)
  1377. {
  1378. return malloc (size);
  1379. }
  1380. void* juce_Calloc (const int size)
  1381. {
  1382. return calloc (1, size);
  1383. }
  1384. void* juce_Realloc (void* const block, const int size)
  1385. {
  1386. return realloc (block, size);
  1387. }
  1388. void juce_Free (void* const block)
  1389. {
  1390. free (block);
  1391. }
  1392. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  1393. void* juce_DebugMalloc (const int size, const char* file, const int line)
  1394. {
  1395. return _malloc_dbg (size, _NORMAL_BLOCK, file, line);
  1396. }
  1397. void* juce_DebugCalloc (const int size, const char* file, const int line)
  1398. {
  1399. return _calloc_dbg (1, size, _NORMAL_BLOCK, file, line);
  1400. }
  1401. void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line)
  1402. {
  1403. return _realloc_dbg (block, size, _NORMAL_BLOCK, file, line);
  1404. }
  1405. void juce_DebugFree (void* const block)
  1406. {
  1407. _free_dbg (block, _NORMAL_BLOCK);
  1408. }
  1409. #endif
  1410. #endif
  1411. END_JUCE_NAMESPACE
  1412. /*** End of inlined file: juce_SystemStats.cpp ***/
  1413. /*** Start of inlined file: juce_Time.cpp ***/
  1414. #if JUCE_MSVC
  1415. #pragma warning (push)
  1416. #pragma warning (disable: 4514)
  1417. #endif
  1418. #ifndef JUCE_WINDOWS
  1419. #include <sys/time.h>
  1420. #else
  1421. #include <ctime>
  1422. #endif
  1423. #include <sys/timeb.h>
  1424. #if JUCE_MSVC
  1425. #pragma warning (pop)
  1426. #ifdef _INC_TIME_INL
  1427. #define USE_NEW_SECURE_TIME_FNS
  1428. #endif
  1429. #endif
  1430. BEGIN_JUCE_NAMESPACE
  1431. namespace TimeHelpers
  1432. {
  1433. static struct tm millisToLocal (const int64 millis) throw()
  1434. {
  1435. struct tm result;
  1436. const int64 seconds = millis / 1000;
  1437. if (seconds < literal64bit (86400) || seconds >= literal64bit (2145916800))
  1438. {
  1439. // use extended maths for dates beyond 1970 to 2037..
  1440. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000);
  1441. const int64 jdm = seconds + timeZoneAdjustment + literal64bit (210866803200);
  1442. const int days = (int) (jdm / literal64bit (86400));
  1443. const int a = 32044 + days;
  1444. const int b = (4 * a + 3) / 146097;
  1445. const int c = a - (b * 146097) / 4;
  1446. const int d = (4 * c + 3) / 1461;
  1447. const int e = c - (d * 1461) / 4;
  1448. const int m = (5 * e + 2) / 153;
  1449. result.tm_mday = e - (153 * m + 2) / 5 + 1;
  1450. result.tm_mon = m + 2 - 12 * (m / 10);
  1451. result.tm_year = b * 100 + d - 6700 + (m / 10);
  1452. result.tm_wday = (days + 1) % 7;
  1453. result.tm_yday = -1;
  1454. int t = (int) (jdm % literal64bit (86400));
  1455. result.tm_hour = t / 3600;
  1456. t %= 3600;
  1457. result.tm_min = t / 60;
  1458. result.tm_sec = t % 60;
  1459. result.tm_isdst = -1;
  1460. }
  1461. else
  1462. {
  1463. time_t now = static_cast <time_t> (seconds);
  1464. #if JUCE_WINDOWS
  1465. #ifdef USE_NEW_SECURE_TIME_FNS
  1466. if (now >= 0 && now <= 0x793406fff)
  1467. localtime_s (&result, &now);
  1468. else
  1469. zeromem (&result, sizeof (result));
  1470. #else
  1471. result = *localtime (&now);
  1472. #endif
  1473. #else
  1474. // more thread-safe
  1475. localtime_r (&now, &result);
  1476. #endif
  1477. }
  1478. return result;
  1479. }
  1480. static int extendedModulo (const int64 value, const int modulo) throw()
  1481. {
  1482. return (int) (value >= 0 ? (value % modulo)
  1483. : (value - ((value / modulo) + 1) * modulo));
  1484. }
  1485. static uint32 lastMSCounterValue = 0;
  1486. }
  1487. Time::Time() throw()
  1488. : millisSinceEpoch (0)
  1489. {
  1490. }
  1491. Time::Time (const Time& other) throw()
  1492. : millisSinceEpoch (other.millisSinceEpoch)
  1493. {
  1494. }
  1495. Time::Time (const int64 ms) throw()
  1496. : millisSinceEpoch (ms)
  1497. {
  1498. }
  1499. Time::Time (const int year,
  1500. const int month,
  1501. const int day,
  1502. const int hours,
  1503. const int minutes,
  1504. const int seconds,
  1505. const int milliseconds,
  1506. const bool useLocalTime) throw()
  1507. {
  1508. jassert (year > 100); // year must be a 4-digit version
  1509. if (year < 1971 || year >= 2038 || ! useLocalTime)
  1510. {
  1511. // use extended maths for dates beyond 1970 to 2037..
  1512. const int timeZoneAdjustment = useLocalTime ? (31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000))
  1513. : 0;
  1514. const int a = (13 - month) / 12;
  1515. const int y = year + 4800 - a;
  1516. const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5
  1517. + (y * 365) + (y / 4) - (y / 100) + (y / 400)
  1518. - 32045;
  1519. const int64 s = ((int64) jd) * literal64bit (86400) - literal64bit (210866803200);
  1520. millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment))
  1521. + milliseconds;
  1522. }
  1523. else
  1524. {
  1525. struct tm t;
  1526. t.tm_year = year - 1900;
  1527. t.tm_mon = month;
  1528. t.tm_mday = day;
  1529. t.tm_hour = hours;
  1530. t.tm_min = minutes;
  1531. t.tm_sec = seconds;
  1532. t.tm_isdst = -1;
  1533. millisSinceEpoch = 1000 * (int64) mktime (&t);
  1534. if (millisSinceEpoch < 0)
  1535. millisSinceEpoch = 0;
  1536. else
  1537. millisSinceEpoch += milliseconds;
  1538. }
  1539. }
  1540. Time::~Time() throw()
  1541. {
  1542. }
  1543. Time& Time::operator= (const Time& other) throw()
  1544. {
  1545. millisSinceEpoch = other.millisSinceEpoch;
  1546. return *this;
  1547. }
  1548. int64 Time::currentTimeMillis() throw()
  1549. {
  1550. static uint32 lastCounterResult = 0xffffffff;
  1551. static int64 correction = 0;
  1552. const uint32 now = getMillisecondCounter();
  1553. // check the counter hasn't wrapped (also triggered the first time this function is called)
  1554. if (now < lastCounterResult)
  1555. {
  1556. // double-check it's actually wrapped, in case multi-cpu machines have timers that drift a bit.
  1557. if (lastCounterResult == 0xffffffff || now < lastCounterResult - 10)
  1558. {
  1559. // get the time once using normal library calls, and store the difference needed to
  1560. // turn the millisecond counter into a real time.
  1561. #if JUCE_WINDOWS
  1562. struct _timeb t;
  1563. #ifdef USE_NEW_SECURE_TIME_FNS
  1564. _ftime_s (&t);
  1565. #else
  1566. _ftime (&t);
  1567. #endif
  1568. correction = (((int64) t.time) * 1000 + t.millitm) - now;
  1569. #else
  1570. struct timeval tv;
  1571. struct timezone tz;
  1572. gettimeofday (&tv, &tz);
  1573. correction = (((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000) - now;
  1574. #endif
  1575. }
  1576. }
  1577. lastCounterResult = now;
  1578. return correction + now;
  1579. }
  1580. uint32 juce_millisecondsSinceStartup() throw();
  1581. uint32 Time::getMillisecondCounter() throw()
  1582. {
  1583. const uint32 now = juce_millisecondsSinceStartup();
  1584. if (now < TimeHelpers::lastMSCounterValue)
  1585. {
  1586. // in multi-threaded apps this might be called concurrently, so
  1587. // make sure that our last counter value only increases and doesn't
  1588. // go backwards..
  1589. if (now < TimeHelpers::lastMSCounterValue - 1000)
  1590. TimeHelpers::lastMSCounterValue = now;
  1591. }
  1592. else
  1593. {
  1594. TimeHelpers::lastMSCounterValue = now;
  1595. }
  1596. return now;
  1597. }
  1598. uint32 Time::getApproximateMillisecondCounter() throw()
  1599. {
  1600. jassert (TimeHelpers::lastMSCounterValue != 0);
  1601. return TimeHelpers::lastMSCounterValue;
  1602. }
  1603. void Time::waitForMillisecondCounter (const uint32 targetTime) throw()
  1604. {
  1605. for (;;)
  1606. {
  1607. const uint32 now = getMillisecondCounter();
  1608. if (now >= targetTime)
  1609. break;
  1610. const int toWait = targetTime - now;
  1611. if (toWait > 2)
  1612. {
  1613. Thread::sleep (jmin (20, toWait >> 1));
  1614. }
  1615. else
  1616. {
  1617. // xxx should consider using mutex_pause on the mac as it apparently
  1618. // makes it seem less like a spinlock and avoids lowering the thread pri.
  1619. for (int i = 10; --i >= 0;)
  1620. Thread::yield();
  1621. }
  1622. }
  1623. }
  1624. double Time::highResolutionTicksToSeconds (const int64 ticks) throw()
  1625. {
  1626. return ticks / (double) getHighResolutionTicksPerSecond();
  1627. }
  1628. int64 Time::secondsToHighResolutionTicks (const double seconds) throw()
  1629. {
  1630. return (int64) (seconds * (double) getHighResolutionTicksPerSecond());
  1631. }
  1632. const Time JUCE_CALLTYPE Time::getCurrentTime() throw()
  1633. {
  1634. return Time (currentTimeMillis());
  1635. }
  1636. const String Time::toString (const bool includeDate,
  1637. const bool includeTime,
  1638. const bool includeSeconds,
  1639. const bool use24HourClock) const throw()
  1640. {
  1641. String result;
  1642. if (includeDate)
  1643. {
  1644. result << getDayOfMonth() << ' '
  1645. << getMonthName (true) << ' '
  1646. << getYear();
  1647. if (includeTime)
  1648. result << ' ';
  1649. }
  1650. if (includeTime)
  1651. {
  1652. const int mins = getMinutes();
  1653. result << (use24HourClock ? getHours() : getHoursInAmPmFormat())
  1654. << (mins < 10 ? ":0" : ":") << mins;
  1655. if (includeSeconds)
  1656. {
  1657. const int secs = getSeconds();
  1658. result << (secs < 10 ? ":0" : ":") << secs;
  1659. }
  1660. if (! use24HourClock)
  1661. result << (isAfternoon() ? "pm" : "am");
  1662. }
  1663. return result.trimEnd();
  1664. }
  1665. const String Time::formatted (const String& format) const
  1666. {
  1667. String buffer;
  1668. int bufferSize = 128;
  1669. buffer.preallocateStorage (bufferSize);
  1670. struct tm t (TimeHelpers::millisToLocal (millisSinceEpoch));
  1671. while (CharacterFunctions::ftime (static_cast <juce_wchar*> (buffer), bufferSize, format, &t) <= 0)
  1672. {
  1673. bufferSize += 128;
  1674. buffer.preallocateStorage (bufferSize);
  1675. }
  1676. return buffer;
  1677. }
  1678. int Time::getYear() const throw()
  1679. {
  1680. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_year + 1900;
  1681. }
  1682. int Time::getMonth() const throw()
  1683. {
  1684. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mon;
  1685. }
  1686. int Time::getDayOfMonth() const throw()
  1687. {
  1688. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_mday;
  1689. }
  1690. int Time::getDayOfWeek() const throw()
  1691. {
  1692. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_wday;
  1693. }
  1694. int Time::getHours() const throw()
  1695. {
  1696. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_hour;
  1697. }
  1698. int Time::getHoursInAmPmFormat() const throw()
  1699. {
  1700. const int hours = getHours();
  1701. if (hours == 0)
  1702. return 12;
  1703. else if (hours <= 12)
  1704. return hours;
  1705. else
  1706. return hours - 12;
  1707. }
  1708. bool Time::isAfternoon() const throw()
  1709. {
  1710. return getHours() >= 12;
  1711. }
  1712. int Time::getMinutes() const throw()
  1713. {
  1714. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_min;
  1715. }
  1716. int Time::getSeconds() const throw()
  1717. {
  1718. return TimeHelpers::extendedModulo (millisSinceEpoch / 1000, 60);
  1719. }
  1720. int Time::getMilliseconds() const throw()
  1721. {
  1722. return TimeHelpers::extendedModulo (millisSinceEpoch, 1000);
  1723. }
  1724. bool Time::isDaylightSavingTime() const throw()
  1725. {
  1726. return TimeHelpers::millisToLocal (millisSinceEpoch).tm_isdst != 0;
  1727. }
  1728. const String Time::getTimeZone() const throw()
  1729. {
  1730. String zone[2];
  1731. #if JUCE_WINDOWS
  1732. _tzset();
  1733. #ifdef USE_NEW_SECURE_TIME_FNS
  1734. {
  1735. char name [128];
  1736. size_t length;
  1737. for (int i = 0; i < 2; ++i)
  1738. {
  1739. zeromem (name, sizeof (name));
  1740. _get_tzname (&length, name, 127, i);
  1741. zone[i] = name;
  1742. }
  1743. }
  1744. #else
  1745. const char** const zonePtr = (const char**) _tzname;
  1746. zone[0] = zonePtr[0];
  1747. zone[1] = zonePtr[1];
  1748. #endif
  1749. #else
  1750. tzset();
  1751. const char** const zonePtr = (const char**) tzname;
  1752. zone[0] = zonePtr[0];
  1753. zone[1] = zonePtr[1];
  1754. #endif
  1755. if (isDaylightSavingTime())
  1756. {
  1757. zone[0] = zone[1];
  1758. if (zone[0].length() > 3
  1759. && zone[0].containsIgnoreCase ("daylight")
  1760. && zone[0].contains ("GMT"))
  1761. zone[0] = "BST";
  1762. }
  1763. return zone[0].substring (0, 3);
  1764. }
  1765. const String Time::getMonthName (const bool threeLetterVersion) const
  1766. {
  1767. return getMonthName (getMonth(), threeLetterVersion);
  1768. }
  1769. const String Time::getWeekdayName (const bool threeLetterVersion) const
  1770. {
  1771. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  1772. }
  1773. const String Time::getMonthName (int monthNumber, const bool threeLetterVersion)
  1774. {
  1775. const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1776. const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  1777. monthNumber %= 12;
  1778. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  1779. : longMonthNames [monthNumber]);
  1780. }
  1781. const String Time::getWeekdayName (int day, const bool threeLetterVersion)
  1782. {
  1783. const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1784. const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  1785. day %= 7;
  1786. return TRANS (threeLetterVersion ? shortDayNames [day]
  1787. : longDayNames [day]);
  1788. }
  1789. END_JUCE_NAMESPACE
  1790. /*** End of inlined file: juce_Time.cpp ***/
  1791. /*** Start of inlined file: juce_Initialisation.cpp ***/
  1792. BEGIN_JUCE_NAMESPACE
  1793. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1794. #endif
  1795. #if JUCE_WINDOWS
  1796. extern void juce_shutdownWin32Sockets(); // (defined in the sockets code)
  1797. #endif
  1798. #if JUCE_DEBUG
  1799. extern void juce_CheckForDanglingStreams(); // (in juce_OutputStream.cpp)
  1800. #endif
  1801. static bool juceInitialisedNonGUI = false;
  1802. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI()
  1803. {
  1804. if (! juceInitialisedNonGUI)
  1805. {
  1806. juceInitialisedNonGUI = true;
  1807. JUCE_AUTORELEASEPOOL
  1808. DBG (SystemStats::getJUCEVersion());
  1809. SystemStats::initialiseStats();
  1810. Random::getSystemRandom().setSeedRandomly(); // (mustn't call this before initialiseStats() because it relies on the time being set up)
  1811. }
  1812. // Some basic tests, to keep an eye on things and make sure these types work ok
  1813. // on all platforms. Let me know if any of these assertions fail on your system!
  1814. static_jassert (sizeof (pointer_sized_int) == sizeof (void*));
  1815. static_jassert (sizeof (int8) == 1);
  1816. static_jassert (sizeof (uint8) == 1);
  1817. static_jassert (sizeof (int16) == 2);
  1818. static_jassert (sizeof (uint16) == 2);
  1819. static_jassert (sizeof (int32) == 4);
  1820. static_jassert (sizeof (uint32) == 4);
  1821. static_jassert (sizeof (int64) == 8);
  1822. static_jassert (sizeof (uint64) == 8);
  1823. }
  1824. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI()
  1825. {
  1826. if (juceInitialisedNonGUI)
  1827. {
  1828. juceInitialisedNonGUI = false;
  1829. JUCE_AUTORELEASEPOOL
  1830. LocalisedStrings::setCurrentMappings (0);
  1831. Thread::stopAllThreads (3000);
  1832. #if JUCE_WINDOWS
  1833. juce_shutdownWin32Sockets();
  1834. #endif
  1835. #if JUCE_DEBUG
  1836. juce_CheckForDanglingStreams();
  1837. #endif
  1838. }
  1839. }
  1840. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  1841. void juce_setCurrentThreadName (const String& name);
  1842. static bool juceInitialisedGUI = false;
  1843. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI()
  1844. {
  1845. if (! juceInitialisedGUI)
  1846. {
  1847. juceInitialisedGUI = true;
  1848. JUCE_AUTORELEASEPOOL
  1849. initialiseJuce_NonGUI();
  1850. MessageManager::getInstance();
  1851. LookAndFeel::setDefaultLookAndFeel (0);
  1852. juce_setCurrentThreadName ("Juce Message Thread");
  1853. #if JUCE_DEBUG
  1854. // This section is just for catching people who mess up their project settings and
  1855. // turn RTTI off..
  1856. try
  1857. {
  1858. TextButton tb (String::empty);
  1859. Component* c = &tb;
  1860. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  1861. c = dynamic_cast <Button*> (c);
  1862. }
  1863. catch (...)
  1864. {
  1865. // Ended up here? If so, TURN ON RTTI in your compiler settings!!
  1866. jassertfalse;
  1867. }
  1868. #endif
  1869. }
  1870. }
  1871. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI()
  1872. {
  1873. if (juceInitialisedGUI)
  1874. {
  1875. juceInitialisedGUI = false;
  1876. JUCE_AUTORELEASEPOOL
  1877. DeletedAtShutdown::deleteAll();
  1878. LookAndFeel::clearDefaultLookAndFeel();
  1879. delete MessageManager::getInstance();
  1880. shutdownJuce_NonGUI();
  1881. }
  1882. }
  1883. #endif
  1884. #if JUCE_UNIT_TESTS
  1885. class AtomicTests : public UnitTest
  1886. {
  1887. public:
  1888. AtomicTests() : UnitTest ("Atomics") {}
  1889. void runTest()
  1890. {
  1891. beginTest ("Misc");
  1892. char a1[7];
  1893. expect (numElementsInArray(a1) == 7);
  1894. int a2[3];
  1895. expect (numElementsInArray(a2) == 3);
  1896. expect (ByteOrder::swap ((uint16) 0x1122) == 0x2211);
  1897. expect (ByteOrder::swap ((uint32) 0x11223344) == 0x44332211);
  1898. expect (ByteOrder::swap ((uint64) literal64bit (0x1122334455667788)) == literal64bit (0x8877665544332211));
  1899. beginTest ("Atomic types");
  1900. AtomicTester <int>::testInteger (*this);
  1901. AtomicTester <unsigned int>::testInteger (*this);
  1902. AtomicTester <int32>::testInteger (*this);
  1903. AtomicTester <uint32>::testInteger (*this);
  1904. AtomicTester <long>::testInteger (*this);
  1905. AtomicTester <void*>::testInteger (*this);
  1906. AtomicTester <int*>::testInteger (*this);
  1907. AtomicTester <float>::testFloat (*this);
  1908. #if ! JUCE_64BIT_ATOMICS_UNAVAILABLE // 64-bit intrinsics aren't available on some old platforms
  1909. AtomicTester <int64>::testInteger (*this);
  1910. AtomicTester <uint64>::testInteger (*this);
  1911. AtomicTester <double>::testFloat (*this);
  1912. #endif
  1913. }
  1914. template <typename Type>
  1915. class AtomicTester
  1916. {
  1917. public:
  1918. AtomicTester() {}
  1919. static void testInteger (UnitTest& test)
  1920. {
  1921. Atomic<Type> a, b;
  1922. a.set ((Type) 10);
  1923. a += (Type) 15;
  1924. a.memoryBarrier();
  1925. a -= (Type) 5;
  1926. ++a; ++a; --a;
  1927. a.memoryBarrier();
  1928. testFloat (test);
  1929. }
  1930. static void testFloat (UnitTest& test)
  1931. {
  1932. Atomic<Type> a, b;
  1933. a = (Type) 21;
  1934. a.memoryBarrier();
  1935. /* These are some simple test cases to check the atomics - let me know
  1936. if any of these assertions fail on your system!
  1937. */
  1938. test.expect (a.get() == (Type) 21);
  1939. test.expect (a.compareAndSetValue ((Type) 100, (Type) 50) == (Type) 21);
  1940. test.expect (a.get() == (Type) 21);
  1941. test.expect (a.compareAndSetValue ((Type) 101, a.get()) == (Type) 21);
  1942. test.expect (a.get() == (Type) 101);
  1943. test.expect (! a.compareAndSetBool ((Type) 300, (Type) 200));
  1944. test.expect (a.get() == (Type) 101);
  1945. test.expect (a.compareAndSetBool ((Type) 200, a.get()));
  1946. test.expect (a.get() == (Type) 200);
  1947. test.expect (a.exchange ((Type) 300) == (Type) 200);
  1948. test.expect (a.get() == (Type) 300);
  1949. b = a;
  1950. test.expect (b.get() == a.get());
  1951. }
  1952. };
  1953. };
  1954. static AtomicTests atomicUnitTests;
  1955. #endif
  1956. END_JUCE_NAMESPACE
  1957. /*** End of inlined file: juce_Initialisation.cpp ***/
  1958. /*** Start of inlined file: juce_AbstractFifo.cpp ***/
  1959. BEGIN_JUCE_NAMESPACE
  1960. AbstractFifo::AbstractFifo (const int capacity) throw()
  1961. : bufferSize (capacity)
  1962. {
  1963. jassert (bufferSize > 0);
  1964. }
  1965. AbstractFifo::~AbstractFifo() {}
  1966. int AbstractFifo::getTotalSize() const throw() { return bufferSize; }
  1967. int AbstractFifo::getFreeSpace() const throw() { return bufferSize - getNumReady(); }
  1968. int AbstractFifo::getNumReady() const throw() { return validEnd.get() - validStart.get(); }
  1969. void AbstractFifo::reset() throw()
  1970. {
  1971. validEnd = 0;
  1972. validStart = 0;
  1973. }
  1974. void AbstractFifo::setTotalSize (int newSize) throw()
  1975. {
  1976. jassert (newSize > 0);
  1977. reset();
  1978. bufferSize = newSize;
  1979. }
  1980. void AbstractFifo::prepareToWrite (int numToWrite, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw()
  1981. {
  1982. const int vs = validStart.get();
  1983. const int ve = validEnd.get();
  1984. const int freeSpace = bufferSize - (ve - vs);
  1985. numToWrite = jmin (numToWrite, freeSpace);
  1986. if (numToWrite <= 0)
  1987. {
  1988. startIndex1 = 0;
  1989. startIndex2 = 0;
  1990. blockSize1 = 0;
  1991. blockSize2 = 0;
  1992. }
  1993. else
  1994. {
  1995. startIndex1 = (int) (ve % bufferSize);
  1996. startIndex2 = 0;
  1997. blockSize1 = jmin (bufferSize - startIndex1, numToWrite);
  1998. numToWrite -= blockSize1;
  1999. blockSize2 = numToWrite <= 0 ? 0 : jmin (numToWrite, (int) (vs % bufferSize));
  2000. }
  2001. }
  2002. void AbstractFifo::finishedWrite (int numWritten) throw()
  2003. {
  2004. jassert (numWritten >= 0 && numWritten < bufferSize);
  2005. validEnd += numWritten;
  2006. }
  2007. void AbstractFifo::prepareToRead (int numWanted, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw()
  2008. {
  2009. const int vs = validStart.get();
  2010. const int ve = validEnd.get();
  2011. const int numReady = ve - vs;
  2012. numWanted = jmin (numWanted, numReady);
  2013. if (numWanted <= 0)
  2014. {
  2015. startIndex1 = 0;
  2016. startIndex2 = 0;
  2017. blockSize1 = 0;
  2018. blockSize2 = 0;
  2019. }
  2020. else
  2021. {
  2022. startIndex1 = (int) (vs % bufferSize);
  2023. startIndex2 = 0;
  2024. blockSize1 = jmin (bufferSize - startIndex1, numWanted);
  2025. numWanted -= blockSize1;
  2026. blockSize2 = numWanted <= 0 ? 0 : jmin (numWanted, (int) (ve % bufferSize));
  2027. }
  2028. }
  2029. void AbstractFifo::finishedRead (int numRead) throw()
  2030. {
  2031. jassert (numRead >= 0 && numRead < bufferSize);
  2032. validStart += numRead;
  2033. }
  2034. END_JUCE_NAMESPACE
  2035. /*** End of inlined file: juce_AbstractFifo.cpp ***/
  2036. /*** Start of inlined file: juce_BigInteger.cpp ***/
  2037. BEGIN_JUCE_NAMESPACE
  2038. BigInteger::BigInteger()
  2039. : numValues (4),
  2040. highestBit (-1),
  2041. negative (false)
  2042. {
  2043. values.calloc (numValues + 1);
  2044. }
  2045. BigInteger::BigInteger (const int value)
  2046. : numValues (4),
  2047. highestBit (31),
  2048. negative (value < 0)
  2049. {
  2050. values.calloc (numValues + 1);
  2051. values[0] = abs (value);
  2052. highestBit = getHighestBit();
  2053. }
  2054. BigInteger::BigInteger (int64 value)
  2055. : numValues (4),
  2056. highestBit (63),
  2057. negative (value < 0)
  2058. {
  2059. values.calloc (numValues + 1);
  2060. if (value < 0)
  2061. value = -value;
  2062. values[0] = (unsigned int) value;
  2063. values[1] = (unsigned int) (value >> 32);
  2064. highestBit = getHighestBit();
  2065. }
  2066. BigInteger::BigInteger (const unsigned int value)
  2067. : numValues (4),
  2068. highestBit (31),
  2069. negative (false)
  2070. {
  2071. values.calloc (numValues + 1);
  2072. values[0] = value;
  2073. highestBit = getHighestBit();
  2074. }
  2075. BigInteger::BigInteger (const BigInteger& other)
  2076. : numValues (jmax (4, (other.highestBit >> 5) + 1)),
  2077. highestBit (other.getHighestBit()),
  2078. negative (other.negative)
  2079. {
  2080. values.malloc (numValues + 1);
  2081. memcpy (values, other.values, sizeof (unsigned int) * (numValues + 1));
  2082. }
  2083. BigInteger::~BigInteger()
  2084. {
  2085. }
  2086. void BigInteger::swapWith (BigInteger& other) throw()
  2087. {
  2088. values.swapWith (other.values);
  2089. swapVariables (numValues, other.numValues);
  2090. swapVariables (highestBit, other.highestBit);
  2091. swapVariables (negative, other.negative);
  2092. }
  2093. BigInteger& BigInteger::operator= (const BigInteger& other)
  2094. {
  2095. if (this != &other)
  2096. {
  2097. highestBit = other.getHighestBit();
  2098. numValues = jmax (4, (highestBit >> 5) + 1);
  2099. negative = other.negative;
  2100. values.malloc (numValues + 1);
  2101. memcpy (values, other.values, sizeof (unsigned int) * (numValues + 1));
  2102. }
  2103. return *this;
  2104. }
  2105. void BigInteger::ensureSize (const int numVals)
  2106. {
  2107. if (numVals + 2 >= numValues)
  2108. {
  2109. int oldSize = numValues;
  2110. numValues = ((numVals + 2) * 3) / 2;
  2111. values.realloc (numValues + 1);
  2112. while (oldSize < numValues)
  2113. values [oldSize++] = 0;
  2114. }
  2115. }
  2116. bool BigInteger::operator[] (const int bit) const throw()
  2117. {
  2118. return bit <= highestBit && bit >= 0
  2119. && ((values [bit >> 5] & (1 << (bit & 31))) != 0);
  2120. }
  2121. int BigInteger::toInteger() const throw()
  2122. {
  2123. const int n = (int) (values[0] & 0x7fffffff);
  2124. return negative ? -n : n;
  2125. }
  2126. const BigInteger BigInteger::getBitRange (int startBit, int numBits) const
  2127. {
  2128. BigInteger r;
  2129. numBits = jmin (numBits, getHighestBit() + 1 - startBit);
  2130. r.ensureSize (numBits >> 5);
  2131. r.highestBit = numBits;
  2132. int i = 0;
  2133. while (numBits > 0)
  2134. {
  2135. r.values[i++] = getBitRangeAsInt (startBit, jmin (32, numBits));
  2136. numBits -= 32;
  2137. startBit += 32;
  2138. }
  2139. r.highestBit = r.getHighestBit();
  2140. return r;
  2141. }
  2142. int BigInteger::getBitRangeAsInt (const int startBit, int numBits) const throw()
  2143. {
  2144. if (numBits > 32)
  2145. {
  2146. jassertfalse; // use getBitRange() if you need more than 32 bits..
  2147. numBits = 32;
  2148. }
  2149. numBits = jmin (numBits, highestBit + 1 - startBit);
  2150. if (numBits <= 0)
  2151. return 0;
  2152. const int pos = startBit >> 5;
  2153. const int offset = startBit & 31;
  2154. const int endSpace = 32 - numBits;
  2155. uint32 n = ((uint32) values [pos]) >> offset;
  2156. if (offset > endSpace)
  2157. n |= ((uint32) values [pos + 1]) << (32 - offset);
  2158. return (int) (n & (((uint32) 0xffffffff) >> endSpace));
  2159. }
  2160. void BigInteger::setBitRangeAsInt (const int startBit, int numBits, unsigned int valueToSet)
  2161. {
  2162. if (numBits > 32)
  2163. {
  2164. jassertfalse;
  2165. numBits = 32;
  2166. }
  2167. for (int i = 0; i < numBits; ++i)
  2168. {
  2169. setBit (startBit + i, (valueToSet & 1) != 0);
  2170. valueToSet >>= 1;
  2171. }
  2172. }
  2173. void BigInteger::clear()
  2174. {
  2175. if (numValues > 16)
  2176. {
  2177. numValues = 4;
  2178. values.calloc (numValues + 1);
  2179. }
  2180. else
  2181. {
  2182. zeromem (values, sizeof (unsigned int) * (numValues + 1));
  2183. }
  2184. highestBit = -1;
  2185. negative = false;
  2186. }
  2187. void BigInteger::setBit (const int bit)
  2188. {
  2189. if (bit >= 0)
  2190. {
  2191. if (bit > highestBit)
  2192. {
  2193. ensureSize (bit >> 5);
  2194. highestBit = bit;
  2195. }
  2196. values [bit >> 5] |= (1 << (bit & 31));
  2197. }
  2198. }
  2199. void BigInteger::setBit (const int bit, const bool shouldBeSet)
  2200. {
  2201. if (shouldBeSet)
  2202. setBit (bit);
  2203. else
  2204. clearBit (bit);
  2205. }
  2206. void BigInteger::clearBit (const int bit) throw()
  2207. {
  2208. if (bit >= 0 && bit <= highestBit)
  2209. values [bit >> 5] &= ~(1 << (bit & 31));
  2210. }
  2211. void BigInteger::setRange (int startBit, int numBits, const bool shouldBeSet)
  2212. {
  2213. while (--numBits >= 0)
  2214. setBit (startBit++, shouldBeSet);
  2215. }
  2216. void BigInteger::insertBit (const int bit, const bool shouldBeSet)
  2217. {
  2218. if (bit >= 0)
  2219. shiftBits (1, bit);
  2220. setBit (bit, shouldBeSet);
  2221. }
  2222. bool BigInteger::isZero() const throw()
  2223. {
  2224. return getHighestBit() < 0;
  2225. }
  2226. bool BigInteger::isOne() const throw()
  2227. {
  2228. return getHighestBit() == 0 && ! negative;
  2229. }
  2230. bool BigInteger::isNegative() const throw()
  2231. {
  2232. return negative && ! isZero();
  2233. }
  2234. void BigInteger::setNegative (const bool neg) throw()
  2235. {
  2236. negative = neg;
  2237. }
  2238. void BigInteger::negate() throw()
  2239. {
  2240. negative = (! negative) && ! isZero();
  2241. }
  2242. int BigInteger::countNumberOfSetBits() const throw()
  2243. {
  2244. int total = 0;
  2245. for (int i = (highestBit >> 5) + 1; --i >= 0;)
  2246. {
  2247. unsigned int n = values[i];
  2248. if (n == 0xffffffff)
  2249. {
  2250. total += 32;
  2251. }
  2252. else
  2253. {
  2254. while (n != 0)
  2255. {
  2256. total += (n & 1);
  2257. n >>= 1;
  2258. }
  2259. }
  2260. }
  2261. return total;
  2262. }
  2263. int BigInteger::getHighestBit() const throw()
  2264. {
  2265. for (int i = highestBit + 1; --i >= 0;)
  2266. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2267. return i;
  2268. return -1;
  2269. }
  2270. int BigInteger::findNextSetBit (int i) const throw()
  2271. {
  2272. for (; i <= highestBit; ++i)
  2273. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2274. return i;
  2275. return -1;
  2276. }
  2277. int BigInteger::findNextClearBit (int i) const throw()
  2278. {
  2279. for (; i <= highestBit; ++i)
  2280. if ((values [i >> 5] & (1 << (i & 31))) == 0)
  2281. break;
  2282. return i;
  2283. }
  2284. BigInteger& BigInteger::operator+= (const BigInteger& other)
  2285. {
  2286. if (other.isNegative())
  2287. return operator-= (-other);
  2288. if (isNegative())
  2289. {
  2290. if (compareAbsolute (other) < 0)
  2291. {
  2292. BigInteger temp (*this);
  2293. temp.negate();
  2294. *this = other;
  2295. operator-= (temp);
  2296. }
  2297. else
  2298. {
  2299. negate();
  2300. operator-= (other);
  2301. negate();
  2302. }
  2303. }
  2304. else
  2305. {
  2306. if (other.highestBit > highestBit)
  2307. highestBit = other.highestBit;
  2308. ++highestBit;
  2309. const int numInts = (highestBit >> 5) + 1;
  2310. ensureSize (numInts);
  2311. int64 remainder = 0;
  2312. for (int i = 0; i <= numInts; ++i)
  2313. {
  2314. if (i < numValues)
  2315. remainder += values[i];
  2316. if (i < other.numValues)
  2317. remainder += other.values[i];
  2318. values[i] = (unsigned int) remainder;
  2319. remainder >>= 32;
  2320. }
  2321. jassert (remainder == 0);
  2322. highestBit = getHighestBit();
  2323. }
  2324. return *this;
  2325. }
  2326. BigInteger& BigInteger::operator-= (const BigInteger& other)
  2327. {
  2328. if (other.isNegative())
  2329. return operator+= (-other);
  2330. if (! isNegative())
  2331. {
  2332. if (compareAbsolute (other) < 0)
  2333. {
  2334. BigInteger temp (other);
  2335. swapWith (temp);
  2336. operator-= (temp);
  2337. negate();
  2338. return *this;
  2339. }
  2340. }
  2341. else
  2342. {
  2343. negate();
  2344. operator+= (other);
  2345. negate();
  2346. return *this;
  2347. }
  2348. const int numInts = (highestBit >> 5) + 1;
  2349. const int maxOtherInts = (other.highestBit >> 5) + 1;
  2350. int64 amountToSubtract = 0;
  2351. for (int i = 0; i <= numInts; ++i)
  2352. {
  2353. if (i <= maxOtherInts)
  2354. amountToSubtract += (int64) other.values[i];
  2355. if (values[i] >= amountToSubtract)
  2356. {
  2357. values[i] = (unsigned int) (values[i] - amountToSubtract);
  2358. amountToSubtract = 0;
  2359. }
  2360. else
  2361. {
  2362. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  2363. values[i] = (unsigned int) n;
  2364. amountToSubtract = 1;
  2365. }
  2366. }
  2367. return *this;
  2368. }
  2369. BigInteger& BigInteger::operator*= (const BigInteger& other)
  2370. {
  2371. BigInteger total;
  2372. highestBit = getHighestBit();
  2373. const bool wasNegative = isNegative();
  2374. setNegative (false);
  2375. for (int i = 0; i <= highestBit; ++i)
  2376. {
  2377. if (operator[](i))
  2378. {
  2379. BigInteger n (other);
  2380. n.setNegative (false);
  2381. n <<= i;
  2382. total += n;
  2383. }
  2384. }
  2385. total.setNegative (wasNegative ^ other.isNegative());
  2386. swapWith (total);
  2387. return *this;
  2388. }
  2389. void BigInteger::divideBy (const BigInteger& divisor, BigInteger& remainder)
  2390. {
  2391. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  2392. const int divHB = divisor.getHighestBit();
  2393. const int ourHB = getHighestBit();
  2394. if (divHB < 0 || ourHB < 0)
  2395. {
  2396. // division by zero
  2397. remainder.clear();
  2398. clear();
  2399. }
  2400. else
  2401. {
  2402. const bool wasNegative = isNegative();
  2403. swapWith (remainder);
  2404. remainder.setNegative (false);
  2405. clear();
  2406. BigInteger temp (divisor);
  2407. temp.setNegative (false);
  2408. int leftShift = ourHB - divHB;
  2409. temp <<= leftShift;
  2410. while (leftShift >= 0)
  2411. {
  2412. if (remainder.compareAbsolute (temp) >= 0)
  2413. {
  2414. remainder -= temp;
  2415. setBit (leftShift);
  2416. }
  2417. if (--leftShift >= 0)
  2418. temp >>= 1;
  2419. }
  2420. negative = wasNegative ^ divisor.isNegative();
  2421. remainder.setNegative (wasNegative);
  2422. }
  2423. }
  2424. BigInteger& BigInteger::operator/= (const BigInteger& other)
  2425. {
  2426. BigInteger remainder;
  2427. divideBy (other, remainder);
  2428. return *this;
  2429. }
  2430. BigInteger& BigInteger::operator|= (const BigInteger& other)
  2431. {
  2432. // this operation doesn't take into account negative values..
  2433. jassert (isNegative() == other.isNegative());
  2434. if (other.highestBit >= 0)
  2435. {
  2436. ensureSize (other.highestBit >> 5);
  2437. int n = (other.highestBit >> 5) + 1;
  2438. while (--n >= 0)
  2439. values[n] |= other.values[n];
  2440. if (other.highestBit > highestBit)
  2441. highestBit = other.highestBit;
  2442. highestBit = getHighestBit();
  2443. }
  2444. return *this;
  2445. }
  2446. BigInteger& BigInteger::operator&= (const BigInteger& other)
  2447. {
  2448. // this operation doesn't take into account negative values..
  2449. jassert (isNegative() == other.isNegative());
  2450. int n = numValues;
  2451. while (n > other.numValues)
  2452. values[--n] = 0;
  2453. while (--n >= 0)
  2454. values[n] &= other.values[n];
  2455. if (other.highestBit < highestBit)
  2456. highestBit = other.highestBit;
  2457. highestBit = getHighestBit();
  2458. return *this;
  2459. }
  2460. BigInteger& BigInteger::operator^= (const BigInteger& other)
  2461. {
  2462. // this operation will only work with the absolute values
  2463. jassert (isNegative() == other.isNegative());
  2464. if (other.highestBit >= 0)
  2465. {
  2466. ensureSize (other.highestBit >> 5);
  2467. int n = (other.highestBit >> 5) + 1;
  2468. while (--n >= 0)
  2469. values[n] ^= other.values[n];
  2470. if (other.highestBit > highestBit)
  2471. highestBit = other.highestBit;
  2472. highestBit = getHighestBit();
  2473. }
  2474. return *this;
  2475. }
  2476. BigInteger& BigInteger::operator%= (const BigInteger& divisor)
  2477. {
  2478. BigInteger remainder;
  2479. divideBy (divisor, remainder);
  2480. swapWith (remainder);
  2481. return *this;
  2482. }
  2483. BigInteger& BigInteger::operator<<= (int numBitsToShift)
  2484. {
  2485. shiftBits (numBitsToShift, 0);
  2486. return *this;
  2487. }
  2488. BigInteger& BigInteger::operator>>= (int numBitsToShift)
  2489. {
  2490. return operator<<= (-numBitsToShift);
  2491. }
  2492. BigInteger& BigInteger::operator++() { return operator+= (1); }
  2493. BigInteger& BigInteger::operator--() { return operator-= (1); }
  2494. const BigInteger BigInteger::operator++ (int) { const BigInteger old (*this); operator+= (1); return old; }
  2495. const BigInteger BigInteger::operator-- (int) { const BigInteger old (*this); operator-= (1); return old; }
  2496. const BigInteger BigInteger::operator+ (const BigInteger& other) const { BigInteger b (*this); return b += other; }
  2497. const BigInteger BigInteger::operator- (const BigInteger& other) const { BigInteger b (*this); return b -= other; }
  2498. const BigInteger BigInteger::operator* (const BigInteger& other) const { BigInteger b (*this); return b *= other; }
  2499. const BigInteger BigInteger::operator/ (const BigInteger& other) const { BigInteger b (*this); return b /= other; }
  2500. const BigInteger BigInteger::operator| (const BigInteger& other) const { BigInteger b (*this); return b |= other; }
  2501. const BigInteger BigInteger::operator& (const BigInteger& other) const { BigInteger b (*this); return b &= other; }
  2502. const BigInteger BigInteger::operator^ (const BigInteger& other) const { BigInteger b (*this); return b ^= other; }
  2503. const BigInteger BigInteger::operator% (const BigInteger& other) const { BigInteger b (*this); return b %= other; }
  2504. const BigInteger BigInteger::operator<< (const int numBits) const { BigInteger b (*this); return b <<= numBits; }
  2505. const BigInteger BigInteger::operator>> (const int numBits) const { BigInteger b (*this); return b >>= numBits; }
  2506. const BigInteger BigInteger::operator-() const { BigInteger b (*this); b.negate(); return b; }
  2507. int BigInteger::compare (const BigInteger& other) const throw()
  2508. {
  2509. if (isNegative() == other.isNegative())
  2510. {
  2511. const int absComp = compareAbsolute (other);
  2512. return isNegative() ? -absComp : absComp;
  2513. }
  2514. else
  2515. {
  2516. return isNegative() ? -1 : 1;
  2517. }
  2518. }
  2519. int BigInteger::compareAbsolute (const BigInteger& other) const throw()
  2520. {
  2521. const int h1 = getHighestBit();
  2522. const int h2 = other.getHighestBit();
  2523. if (h1 > h2)
  2524. return 1;
  2525. else if (h1 < h2)
  2526. return -1;
  2527. for (int i = (h1 >> 5) + 1; --i >= 0;)
  2528. if (values[i] != other.values[i])
  2529. return (values[i] > other.values[i]) ? 1 : -1;
  2530. return 0;
  2531. }
  2532. bool BigInteger::operator== (const BigInteger& other) const throw() { return compare (other) == 0; }
  2533. bool BigInteger::operator!= (const BigInteger& other) const throw() { return compare (other) != 0; }
  2534. bool BigInteger::operator< (const BigInteger& other) const throw() { return compare (other) < 0; }
  2535. bool BigInteger::operator<= (const BigInteger& other) const throw() { return compare (other) <= 0; }
  2536. bool BigInteger::operator> (const BigInteger& other) const throw() { return compare (other) > 0; }
  2537. bool BigInteger::operator>= (const BigInteger& other) const throw() { return compare (other) >= 0; }
  2538. void BigInteger::shiftBits (int bits, const int startBit)
  2539. {
  2540. if (highestBit < 0)
  2541. return;
  2542. if (startBit > 0)
  2543. {
  2544. if (bits < 0)
  2545. {
  2546. // right shift
  2547. for (int i = startBit; i <= highestBit; ++i)
  2548. setBit (i, operator[] (i - bits));
  2549. highestBit = getHighestBit();
  2550. }
  2551. else if (bits > 0)
  2552. {
  2553. // left shift
  2554. for (int i = highestBit + 1; --i >= startBit;)
  2555. setBit (i + bits, operator[] (i));
  2556. while (--bits >= 0)
  2557. clearBit (bits + startBit);
  2558. }
  2559. }
  2560. else
  2561. {
  2562. if (bits < 0)
  2563. {
  2564. // right shift
  2565. bits = -bits;
  2566. if (bits > highestBit)
  2567. {
  2568. clear();
  2569. }
  2570. else
  2571. {
  2572. const int wordsToMove = bits >> 5;
  2573. int top = 1 + (highestBit >> 5) - wordsToMove;
  2574. highestBit -= bits;
  2575. if (wordsToMove > 0)
  2576. {
  2577. int i;
  2578. for (i = 0; i < top; ++i)
  2579. values [i] = values [i + wordsToMove];
  2580. for (i = 0; i < wordsToMove; ++i)
  2581. values [top + i] = 0;
  2582. bits &= 31;
  2583. }
  2584. if (bits != 0)
  2585. {
  2586. const int invBits = 32 - bits;
  2587. --top;
  2588. for (int i = 0; i < top; ++i)
  2589. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  2590. values[top] = (values[top] >> bits);
  2591. }
  2592. highestBit = getHighestBit();
  2593. }
  2594. }
  2595. else if (bits > 0)
  2596. {
  2597. // left shift
  2598. ensureSize (((highestBit + bits) >> 5) + 1);
  2599. const int wordsToMove = bits >> 5;
  2600. int top = 1 + (highestBit >> 5);
  2601. highestBit += bits;
  2602. if (wordsToMove > 0)
  2603. {
  2604. int i;
  2605. for (i = top; --i >= 0;)
  2606. values [i + wordsToMove] = values [i];
  2607. for (i = 0; i < wordsToMove; ++i)
  2608. values [i] = 0;
  2609. bits &= 31;
  2610. }
  2611. if (bits != 0)
  2612. {
  2613. const int invBits = 32 - bits;
  2614. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  2615. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  2616. values [wordsToMove] = values [wordsToMove] << bits;
  2617. }
  2618. highestBit = getHighestBit();
  2619. }
  2620. }
  2621. }
  2622. const BigInteger BigInteger::simpleGCD (BigInteger* m, BigInteger* n)
  2623. {
  2624. while (! m->isZero())
  2625. {
  2626. if (n->compareAbsolute (*m) > 0)
  2627. swapVariables (m, n);
  2628. *m -= *n;
  2629. }
  2630. return *n;
  2631. }
  2632. const BigInteger BigInteger::findGreatestCommonDivisor (BigInteger n) const
  2633. {
  2634. BigInteger m (*this);
  2635. while (! n.isZero())
  2636. {
  2637. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  2638. return simpleGCD (&m, &n);
  2639. BigInteger temp1 (m), temp2;
  2640. temp1.divideBy (n, temp2);
  2641. m = n;
  2642. n = temp2;
  2643. }
  2644. return m;
  2645. }
  2646. void BigInteger::exponentModulo (const BigInteger& exponent, const BigInteger& modulus)
  2647. {
  2648. BigInteger exp (exponent);
  2649. exp %= modulus;
  2650. BigInteger value (1);
  2651. swapWith (value);
  2652. value %= modulus;
  2653. while (! exp.isZero())
  2654. {
  2655. if (exp [0])
  2656. {
  2657. operator*= (value);
  2658. operator%= (modulus);
  2659. }
  2660. value *= value;
  2661. value %= modulus;
  2662. exp >>= 1;
  2663. }
  2664. }
  2665. void BigInteger::inverseModulo (const BigInteger& modulus)
  2666. {
  2667. if (modulus.isOne() || modulus.isNegative())
  2668. {
  2669. clear();
  2670. return;
  2671. }
  2672. if (isNegative() || compareAbsolute (modulus) >= 0)
  2673. operator%= (modulus);
  2674. if (isOne())
  2675. return;
  2676. if (! (*this)[0])
  2677. {
  2678. // not invertible
  2679. clear();
  2680. return;
  2681. }
  2682. BigInteger a1 (modulus);
  2683. BigInteger a2 (*this);
  2684. BigInteger b1 (modulus);
  2685. BigInteger b2 (1);
  2686. while (! a2.isOne())
  2687. {
  2688. BigInteger temp1, temp2, multiplier (a1);
  2689. multiplier.divideBy (a2, temp1);
  2690. temp1 = a2;
  2691. temp1 *= multiplier;
  2692. temp2 = a1;
  2693. temp2 -= temp1;
  2694. a1 = a2;
  2695. a2 = temp2;
  2696. temp1 = b2;
  2697. temp1 *= multiplier;
  2698. temp2 = b1;
  2699. temp2 -= temp1;
  2700. b1 = b2;
  2701. b2 = temp2;
  2702. }
  2703. while (b2.isNegative())
  2704. b2 += modulus;
  2705. b2 %= modulus;
  2706. swapWith (b2);
  2707. }
  2708. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value)
  2709. {
  2710. return stream << value.toString (10);
  2711. }
  2712. const String BigInteger::toString (const int base, const int minimumNumCharacters) const
  2713. {
  2714. String s;
  2715. BigInteger v (*this);
  2716. if (base == 2 || base == 8 || base == 16)
  2717. {
  2718. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2719. static const char* const hexDigits = "0123456789abcdef";
  2720. for (;;)
  2721. {
  2722. const int remainder = v.getBitRangeAsInt (0, bits);
  2723. v >>= bits;
  2724. if (remainder == 0 && v.isZero())
  2725. break;
  2726. s = String::charToString (hexDigits [remainder]) + s;
  2727. }
  2728. }
  2729. else if (base == 10)
  2730. {
  2731. const BigInteger ten (10);
  2732. BigInteger remainder;
  2733. for (;;)
  2734. {
  2735. v.divideBy (ten, remainder);
  2736. if (remainder.isZero() && v.isZero())
  2737. break;
  2738. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  2739. }
  2740. }
  2741. else
  2742. {
  2743. jassertfalse; // can't do the specified base!
  2744. return String::empty;
  2745. }
  2746. s = s.paddedLeft ('0', minimumNumCharacters);
  2747. return isNegative() ? "-" + s : s;
  2748. }
  2749. void BigInteger::parseString (const String& text, const int base)
  2750. {
  2751. clear();
  2752. const juce_wchar* t = text;
  2753. if (base == 2 || base == 8 || base == 16)
  2754. {
  2755. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2756. for (;;)
  2757. {
  2758. const juce_wchar c = *t++;
  2759. const int digit = CharacterFunctions::getHexDigitValue (c);
  2760. if (((unsigned int) digit) < (unsigned int) base)
  2761. {
  2762. operator<<= (bits);
  2763. operator+= (digit);
  2764. }
  2765. else if (c == 0)
  2766. {
  2767. break;
  2768. }
  2769. }
  2770. }
  2771. else if (base == 10)
  2772. {
  2773. const BigInteger ten ((unsigned int) 10);
  2774. for (;;)
  2775. {
  2776. const juce_wchar c = *t++;
  2777. if (c >= '0' && c <= '9')
  2778. {
  2779. operator*= (ten);
  2780. operator+= ((int) (c - '0'));
  2781. }
  2782. else if (c == 0)
  2783. {
  2784. break;
  2785. }
  2786. }
  2787. }
  2788. setNegative (text.trimStart().startsWithChar ('-'));
  2789. }
  2790. const MemoryBlock BigInteger::toMemoryBlock() const
  2791. {
  2792. const int numBytes = (getHighestBit() + 8) >> 3;
  2793. MemoryBlock mb ((size_t) numBytes);
  2794. for (int i = 0; i < numBytes; ++i)
  2795. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  2796. return mb;
  2797. }
  2798. void BigInteger::loadFromMemoryBlock (const MemoryBlock& data)
  2799. {
  2800. clear();
  2801. for (int i = (int) data.getSize(); --i >= 0;)
  2802. this->setBitRangeAsInt ((int) (i << 3), 8, data [i]);
  2803. }
  2804. END_JUCE_NAMESPACE
  2805. /*** End of inlined file: juce_BigInteger.cpp ***/
  2806. /*** Start of inlined file: juce_MemoryBlock.cpp ***/
  2807. BEGIN_JUCE_NAMESPACE
  2808. MemoryBlock::MemoryBlock() throw()
  2809. : size (0)
  2810. {
  2811. }
  2812. MemoryBlock::MemoryBlock (const size_t initialSize, const bool initialiseToZero)
  2813. {
  2814. if (initialSize > 0)
  2815. {
  2816. size = initialSize;
  2817. data.allocate (initialSize, initialiseToZero);
  2818. }
  2819. else
  2820. {
  2821. size = 0;
  2822. }
  2823. }
  2824. MemoryBlock::MemoryBlock (const MemoryBlock& other)
  2825. : size (other.size)
  2826. {
  2827. if (size > 0)
  2828. {
  2829. jassert (other.data != 0);
  2830. data.malloc (size);
  2831. memcpy (data, other.data, size);
  2832. }
  2833. }
  2834. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom, const size_t sizeInBytes)
  2835. : size (jmax ((size_t) 0, sizeInBytes))
  2836. {
  2837. jassert (sizeInBytes >= 0);
  2838. if (size > 0)
  2839. {
  2840. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  2841. data.malloc (size);
  2842. if (dataToInitialiseFrom != 0)
  2843. memcpy (data, dataToInitialiseFrom, size);
  2844. }
  2845. }
  2846. MemoryBlock::~MemoryBlock() throw()
  2847. {
  2848. jassert (size >= 0); // should never happen
  2849. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  2850. }
  2851. MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other)
  2852. {
  2853. if (this != &other)
  2854. {
  2855. setSize (other.size, false);
  2856. memcpy (data, other.data, size);
  2857. }
  2858. return *this;
  2859. }
  2860. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  2861. {
  2862. return matches (other.data, other.size);
  2863. }
  2864. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  2865. {
  2866. return ! operator== (other);
  2867. }
  2868. bool MemoryBlock::matches (const void* dataToCompare, size_t dataSize) const throw()
  2869. {
  2870. return size == dataSize
  2871. && memcmp (data, dataToCompare, size) == 0;
  2872. }
  2873. // this will resize the block to this size
  2874. void MemoryBlock::setSize (const size_t newSize, const bool initialiseToZero)
  2875. {
  2876. if (size != newSize)
  2877. {
  2878. if (newSize <= 0)
  2879. {
  2880. data.free();
  2881. size = 0;
  2882. }
  2883. else
  2884. {
  2885. if (data != 0)
  2886. {
  2887. data.realloc (newSize);
  2888. if (initialiseToZero && (newSize > size))
  2889. zeromem (data + size, newSize - size);
  2890. }
  2891. else
  2892. {
  2893. data.allocate (newSize, initialiseToZero);
  2894. }
  2895. size = newSize;
  2896. }
  2897. }
  2898. }
  2899. void MemoryBlock::ensureSize (const size_t minimumSize, const bool initialiseToZero)
  2900. {
  2901. if (size < minimumSize)
  2902. setSize (minimumSize, initialiseToZero);
  2903. }
  2904. void MemoryBlock::swapWith (MemoryBlock& other) throw()
  2905. {
  2906. swapVariables (size, other.size);
  2907. data.swapWith (other.data);
  2908. }
  2909. void MemoryBlock::fillWith (const uint8 value) throw()
  2910. {
  2911. memset (data, (int) value, size);
  2912. }
  2913. void MemoryBlock::append (const void* const srcData, const size_t numBytes)
  2914. {
  2915. if (numBytes > 0)
  2916. {
  2917. const size_t oldSize = size;
  2918. setSize (size + numBytes);
  2919. memcpy (data + oldSize, srcData, numBytes);
  2920. }
  2921. }
  2922. void MemoryBlock::copyFrom (const void* const src, int offset, size_t num) throw()
  2923. {
  2924. const char* d = static_cast<const char*> (src);
  2925. if (offset < 0)
  2926. {
  2927. d -= offset;
  2928. num -= offset;
  2929. offset = 0;
  2930. }
  2931. if (offset + num > size)
  2932. num = size - offset;
  2933. if (num > 0)
  2934. memcpy (data + offset, d, num);
  2935. }
  2936. void MemoryBlock::copyTo (void* const dst, int offset, size_t num) const throw()
  2937. {
  2938. char* d = static_cast<char*> (dst);
  2939. if (offset < 0)
  2940. {
  2941. zeromem (d, -offset);
  2942. d -= offset;
  2943. num += offset;
  2944. offset = 0;
  2945. }
  2946. if (offset + num > size)
  2947. {
  2948. const size_t newNum = size - offset;
  2949. zeromem (d + newNum, num - newNum);
  2950. num = newNum;
  2951. }
  2952. if (num > 0)
  2953. memcpy (d, data + offset, num);
  2954. }
  2955. void MemoryBlock::removeSection (size_t startByte, size_t numBytesToRemove)
  2956. {
  2957. if (startByte < 0)
  2958. {
  2959. numBytesToRemove += startByte;
  2960. startByte = 0;
  2961. }
  2962. if (startByte + numBytesToRemove >= size)
  2963. {
  2964. setSize (startByte);
  2965. }
  2966. else if (numBytesToRemove > 0)
  2967. {
  2968. memmove (data + startByte,
  2969. data + startByte + numBytesToRemove,
  2970. size - (startByte + numBytesToRemove));
  2971. setSize (size - numBytesToRemove);
  2972. }
  2973. }
  2974. const String MemoryBlock::toString() const
  2975. {
  2976. return String (static_cast <const char*> (getData()), size);
  2977. }
  2978. int MemoryBlock::getBitRange (const size_t bitRangeStart, size_t numBits) const throw()
  2979. {
  2980. int res = 0;
  2981. size_t byte = bitRangeStart >> 3;
  2982. int offsetInByte = (int) bitRangeStart & 7;
  2983. size_t bitsSoFar = 0;
  2984. while (numBits > 0 && (size_t) byte < size)
  2985. {
  2986. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2987. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  2988. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  2989. bitsSoFar += bitsThisTime;
  2990. numBits -= bitsThisTime;
  2991. ++byte;
  2992. offsetInByte = 0;
  2993. }
  2994. return res;
  2995. }
  2996. void MemoryBlock::setBitRange (const size_t bitRangeStart, size_t numBits, int bitsToSet) throw()
  2997. {
  2998. size_t byte = bitRangeStart >> 3;
  2999. int offsetInByte = (int) bitRangeStart & 7;
  3000. unsigned int mask = ~((((unsigned int) 0xffffffff) << (32 - numBits)) >> (32 - numBits));
  3001. while (numBits > 0 && (size_t) byte < size)
  3002. {
  3003. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  3004. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int) 0xffffffff) >> offsetInByte) << offsetInByte);
  3005. const unsigned int tempBits = bitsToSet << offsetInByte;
  3006. data[byte] = (char) ((data[byte] & tempMask) | tempBits);
  3007. ++byte;
  3008. numBits -= bitsThisTime;
  3009. bitsToSet >>= bitsThisTime;
  3010. mask >>= bitsThisTime;
  3011. offsetInByte = 0;
  3012. }
  3013. }
  3014. void MemoryBlock::loadFromHexString (const String& hex)
  3015. {
  3016. ensureSize (hex.length() >> 1);
  3017. char* dest = data;
  3018. int i = 0;
  3019. for (;;)
  3020. {
  3021. int byte = 0;
  3022. for (int loop = 2; --loop >= 0;)
  3023. {
  3024. byte <<= 4;
  3025. for (;;)
  3026. {
  3027. const juce_wchar c = hex [i++];
  3028. if (c >= '0' && c <= '9')
  3029. {
  3030. byte |= c - '0';
  3031. break;
  3032. }
  3033. else if (c >= 'a' && c <= 'z')
  3034. {
  3035. byte |= c - ('a' - 10);
  3036. break;
  3037. }
  3038. else if (c >= 'A' && c <= 'Z')
  3039. {
  3040. byte |= c - ('A' - 10);
  3041. break;
  3042. }
  3043. else if (c == 0)
  3044. {
  3045. setSize (static_cast <size_t> (dest - data));
  3046. return;
  3047. }
  3048. }
  3049. }
  3050. *dest++ = (char) byte;
  3051. }
  3052. }
  3053. const char* const MemoryBlock::encodingTable = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  3054. const String MemoryBlock::toBase64Encoding() const
  3055. {
  3056. const size_t numChars = ((size << 3) + 5) / 6;
  3057. String destString ((unsigned int) size); // store the length, followed by a '.', and then the data.
  3058. const int initialLen = destString.length();
  3059. destString.preallocateStorage (initialLen + 2 + numChars);
  3060. juce_wchar* d = destString;
  3061. d += initialLen;
  3062. *d++ = '.';
  3063. for (size_t i = 0; i < numChars; ++i)
  3064. *d++ = encodingTable [getBitRange (i * 6, 6)];
  3065. *d++ = 0;
  3066. return destString;
  3067. }
  3068. bool MemoryBlock::fromBase64Encoding (const String& s)
  3069. {
  3070. const int startPos = s.indexOfChar ('.') + 1;
  3071. if (startPos <= 0)
  3072. return false;
  3073. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  3074. setSize (numBytesNeeded, true);
  3075. const int numChars = s.length() - startPos;
  3076. const juce_wchar* srcChars = s;
  3077. srcChars += startPos;
  3078. int pos = 0;
  3079. for (int i = 0; i < numChars; ++i)
  3080. {
  3081. const char c = (char) srcChars[i];
  3082. for (int j = 0; j < 64; ++j)
  3083. {
  3084. if (encodingTable[j] == c)
  3085. {
  3086. setBitRange (pos, 6, j);
  3087. pos += 6;
  3088. break;
  3089. }
  3090. }
  3091. }
  3092. return true;
  3093. }
  3094. END_JUCE_NAMESPACE
  3095. /*** End of inlined file: juce_MemoryBlock.cpp ***/
  3096. /*** Start of inlined file: juce_PropertySet.cpp ***/
  3097. BEGIN_JUCE_NAMESPACE
  3098. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames)
  3099. : properties (ignoreCaseOfKeyNames),
  3100. fallbackProperties (0),
  3101. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  3102. {
  3103. }
  3104. PropertySet::PropertySet (const PropertySet& other)
  3105. : properties (other.properties),
  3106. fallbackProperties (other.fallbackProperties),
  3107. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  3108. {
  3109. }
  3110. PropertySet& PropertySet::operator= (const PropertySet& other)
  3111. {
  3112. properties = other.properties;
  3113. fallbackProperties = other.fallbackProperties;
  3114. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  3115. propertyChanged();
  3116. return *this;
  3117. }
  3118. PropertySet::~PropertySet()
  3119. {
  3120. }
  3121. void PropertySet::clear()
  3122. {
  3123. const ScopedLock sl (lock);
  3124. if (properties.size() > 0)
  3125. {
  3126. properties.clear();
  3127. propertyChanged();
  3128. }
  3129. }
  3130. const String PropertySet::getValue (const String& keyName,
  3131. const String& defaultValue) const throw()
  3132. {
  3133. const ScopedLock sl (lock);
  3134. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3135. if (index >= 0)
  3136. return properties.getAllValues() [index];
  3137. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  3138. : defaultValue;
  3139. }
  3140. int PropertySet::getIntValue (const String& keyName,
  3141. const int defaultValue) const throw()
  3142. {
  3143. const ScopedLock sl (lock);
  3144. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3145. if (index >= 0)
  3146. return properties.getAllValues() [index].getIntValue();
  3147. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  3148. : defaultValue;
  3149. }
  3150. double PropertySet::getDoubleValue (const String& keyName,
  3151. const double defaultValue) const throw()
  3152. {
  3153. const ScopedLock sl (lock);
  3154. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3155. if (index >= 0)
  3156. return properties.getAllValues()[index].getDoubleValue();
  3157. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  3158. : defaultValue;
  3159. }
  3160. bool PropertySet::getBoolValue (const String& keyName,
  3161. const bool defaultValue) const throw()
  3162. {
  3163. const ScopedLock sl (lock);
  3164. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3165. if (index >= 0)
  3166. return properties.getAllValues() [index].getIntValue() != 0;
  3167. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  3168. : defaultValue;
  3169. }
  3170. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  3171. {
  3172. XmlDocument doc (getValue (keyName));
  3173. return doc.getDocumentElement();
  3174. }
  3175. void PropertySet::setValue (const String& keyName, const var& v)
  3176. {
  3177. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  3178. if (keyName.isNotEmpty())
  3179. {
  3180. const String value (v.toString());
  3181. const ScopedLock sl (lock);
  3182. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3183. if (index < 0 || properties.getAllValues() [index] != value)
  3184. {
  3185. properties.set (keyName, value);
  3186. propertyChanged();
  3187. }
  3188. }
  3189. }
  3190. void PropertySet::removeValue (const String& keyName)
  3191. {
  3192. if (keyName.isNotEmpty())
  3193. {
  3194. const ScopedLock sl (lock);
  3195. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3196. if (index >= 0)
  3197. {
  3198. properties.remove (keyName);
  3199. propertyChanged();
  3200. }
  3201. }
  3202. }
  3203. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  3204. {
  3205. setValue (keyName, xml == 0 ? var::null
  3206. : var (xml->createDocument (String::empty, true)));
  3207. }
  3208. bool PropertySet::containsKey (const String& keyName) const throw()
  3209. {
  3210. const ScopedLock sl (lock);
  3211. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  3212. }
  3213. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  3214. {
  3215. const ScopedLock sl (lock);
  3216. fallbackProperties = fallbackProperties_;
  3217. }
  3218. XmlElement* PropertySet::createXml (const String& nodeName) const
  3219. {
  3220. const ScopedLock sl (lock);
  3221. XmlElement* const xml = new XmlElement (nodeName);
  3222. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  3223. {
  3224. XmlElement* const e = xml->createNewChildElement ("VALUE");
  3225. e->setAttribute ("name", properties.getAllKeys()[i]);
  3226. e->setAttribute ("val", properties.getAllValues()[i]);
  3227. }
  3228. return xml;
  3229. }
  3230. void PropertySet::restoreFromXml (const XmlElement& xml)
  3231. {
  3232. const ScopedLock sl (lock);
  3233. clear();
  3234. forEachXmlChildElementWithTagName (xml, e, "VALUE")
  3235. {
  3236. if (e->hasAttribute ("name")
  3237. && e->hasAttribute ("val"))
  3238. {
  3239. properties.set (e->getStringAttribute ("name"),
  3240. e->getStringAttribute ("val"));
  3241. }
  3242. }
  3243. if (properties.size() > 0)
  3244. propertyChanged();
  3245. }
  3246. void PropertySet::propertyChanged()
  3247. {
  3248. }
  3249. END_JUCE_NAMESPACE
  3250. /*** End of inlined file: juce_PropertySet.cpp ***/
  3251. /*** Start of inlined file: juce_Identifier.cpp ***/
  3252. BEGIN_JUCE_NAMESPACE
  3253. StringPool& Identifier::getPool()
  3254. {
  3255. static StringPool pool;
  3256. return pool;
  3257. }
  3258. Identifier::Identifier() throw()
  3259. : name (0)
  3260. {
  3261. }
  3262. Identifier::Identifier (const Identifier& other) throw()
  3263. : name (other.name)
  3264. {
  3265. }
  3266. Identifier& Identifier::operator= (const Identifier& other) throw()
  3267. {
  3268. name = other.name;
  3269. return *this;
  3270. }
  3271. Identifier::Identifier (const String& name_)
  3272. : name (Identifier::getPool().getPooledString (name_))
  3273. {
  3274. /* An Identifier string must be suitable for use as a script variable or XML
  3275. attribute, so it can only contain this limited set of characters.. */
  3276. jassert (name_.containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && name_.isNotEmpty());
  3277. }
  3278. Identifier::Identifier (const char* const name_)
  3279. : name (Identifier::getPool().getPooledString (name_))
  3280. {
  3281. /* An Identifier string must be suitable for use as a script variable or XML
  3282. attribute, so it can only contain this limited set of characters.. */
  3283. jassert (toString().containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && toString().isNotEmpty());
  3284. }
  3285. Identifier::~Identifier()
  3286. {
  3287. }
  3288. END_JUCE_NAMESPACE
  3289. /*** End of inlined file: juce_Identifier.cpp ***/
  3290. /*** Start of inlined file: juce_Variant.cpp ***/
  3291. BEGIN_JUCE_NAMESPACE
  3292. class var::VariantType
  3293. {
  3294. public:
  3295. VariantType() {}
  3296. virtual ~VariantType() {}
  3297. virtual int toInt (const ValueUnion&) const { return 0; }
  3298. virtual double toDouble (const ValueUnion&) const { return 0; }
  3299. virtual const String toString (const ValueUnion&) const { return String::empty; }
  3300. virtual bool toBool (const ValueUnion&) const { return false; }
  3301. virtual DynamicObject* toObject (const ValueUnion&) const { return 0; }
  3302. virtual bool isVoid() const throw() { return false; }
  3303. virtual bool isInt() const throw() { return false; }
  3304. virtual bool isBool() const throw() { return false; }
  3305. virtual bool isDouble() const throw() { return false; }
  3306. virtual bool isString() const throw() { return false; }
  3307. virtual bool isObject() const throw() { return false; }
  3308. virtual bool isMethod() const throw() { return false; }
  3309. virtual void cleanUp (ValueUnion&) const throw() {}
  3310. virtual void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest = source; }
  3311. virtual bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw() = 0;
  3312. virtual void writeToStream (const ValueUnion& data, OutputStream& output) const = 0;
  3313. };
  3314. class var::VariantType_Void : public var::VariantType
  3315. {
  3316. public:
  3317. VariantType_Void() {}
  3318. static const VariantType_Void* getInstance() { static const VariantType_Void i; return &i; }
  3319. bool isVoid() const throw() { return true; }
  3320. bool equals (const ValueUnion&, const ValueUnion&, const VariantType& otherType) const throw() { return otherType.isVoid(); }
  3321. void writeToStream (const ValueUnion&, OutputStream& output) const { output.writeCompressedInt (0); }
  3322. };
  3323. class var::VariantType_Int : public var::VariantType
  3324. {
  3325. public:
  3326. VariantType_Int() {}
  3327. static const VariantType_Int* getInstance() { static const VariantType_Int i; return &i; }
  3328. int toInt (const ValueUnion& data) const { return data.intValue; };
  3329. double toDouble (const ValueUnion& data) const { return (double) data.intValue; }
  3330. const String toString (const ValueUnion& data) const { return String (data.intValue); }
  3331. bool toBool (const ValueUnion& data) const { return data.intValue != 0; }
  3332. bool isInt() const throw() { return true; }
  3333. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3334. {
  3335. return otherType.toInt (otherData) == data.intValue;
  3336. }
  3337. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3338. {
  3339. output.writeCompressedInt (5);
  3340. output.writeByte (1);
  3341. output.writeInt (data.intValue);
  3342. }
  3343. };
  3344. class var::VariantType_Double : public var::VariantType
  3345. {
  3346. public:
  3347. VariantType_Double() {}
  3348. static const VariantType_Double* getInstance() { static const VariantType_Double i; return &i; }
  3349. int toInt (const ValueUnion& data) const { return (int) data.doubleValue; };
  3350. double toDouble (const ValueUnion& data) const { return data.doubleValue; }
  3351. const String toString (const ValueUnion& data) const { return String (data.doubleValue); }
  3352. bool toBool (const ValueUnion& data) const { return data.doubleValue != 0; }
  3353. bool isDouble() const throw() { return true; }
  3354. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3355. {
  3356. return otherType.toDouble (otherData) == data.doubleValue;
  3357. }
  3358. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3359. {
  3360. output.writeCompressedInt (9);
  3361. output.writeByte (4);
  3362. output.writeDouble (data.doubleValue);
  3363. }
  3364. };
  3365. class var::VariantType_Bool : public var::VariantType
  3366. {
  3367. public:
  3368. VariantType_Bool() {}
  3369. static const VariantType_Bool* getInstance() { static const VariantType_Bool i; return &i; }
  3370. int toInt (const ValueUnion& data) const { return data.boolValue ? 1 : 0; };
  3371. double toDouble (const ValueUnion& data) const { return data.boolValue ? 1.0 : 0.0; }
  3372. const String toString (const ValueUnion& data) const { return String::charToString (data.boolValue ? '1' : '0'); }
  3373. bool toBool (const ValueUnion& data) const { return data.boolValue; }
  3374. bool isBool() const throw() { return true; }
  3375. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3376. {
  3377. return otherType.toBool (otherData) == data.boolValue;
  3378. }
  3379. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3380. {
  3381. output.writeCompressedInt (1);
  3382. output.writeByte (data.boolValue ? 2 : 3);
  3383. }
  3384. };
  3385. class var::VariantType_String : public var::VariantType
  3386. {
  3387. public:
  3388. VariantType_String() {}
  3389. static const VariantType_String* getInstance() { static const VariantType_String i; return &i; }
  3390. void cleanUp (ValueUnion& data) const throw() { delete data.stringValue; }
  3391. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.stringValue = new String (*source.stringValue); }
  3392. int toInt (const ValueUnion& data) const { return data.stringValue->getIntValue(); };
  3393. double toDouble (const ValueUnion& data) const { return data.stringValue->getDoubleValue(); }
  3394. const String toString (const ValueUnion& data) const { return *data.stringValue; }
  3395. bool toBool (const ValueUnion& data) const { return data.stringValue->getIntValue() != 0
  3396. || data.stringValue->trim().equalsIgnoreCase ("true")
  3397. || data.stringValue->trim().equalsIgnoreCase ("yes"); }
  3398. bool isString() const throw() { return true; }
  3399. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3400. {
  3401. return otherType.toString (otherData) == *data.stringValue;
  3402. }
  3403. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3404. {
  3405. const int len = data.stringValue->getNumBytesAsUTF8() + 1;
  3406. output.writeCompressedInt (len + 1);
  3407. output.writeByte (5);
  3408. HeapBlock<char> temp (len);
  3409. data.stringValue->copyToUTF8 (temp, len);
  3410. output.write (temp, len);
  3411. }
  3412. };
  3413. class var::VariantType_Object : public var::VariantType
  3414. {
  3415. public:
  3416. VariantType_Object() {}
  3417. static const VariantType_Object* getInstance() { static const VariantType_Object i; return &i; }
  3418. void cleanUp (ValueUnion& data) const throw() { if (data.objectValue != 0) data.objectValue->decReferenceCount(); }
  3419. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.objectValue = source.objectValue; if (dest.objectValue != 0) dest.objectValue->incReferenceCount(); }
  3420. const String toString (const ValueUnion& data) const { return "Object 0x" + String::toHexString ((int) (pointer_sized_int) data.objectValue); }
  3421. bool toBool (const ValueUnion& data) const { return data.objectValue != 0; }
  3422. DynamicObject* toObject (const ValueUnion& data) const { return data.objectValue; }
  3423. bool isObject() const throw() { return true; }
  3424. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3425. {
  3426. return otherType.toObject (otherData) == data.objectValue;
  3427. }
  3428. void writeToStream (const ValueUnion&, OutputStream& output) const
  3429. {
  3430. jassertfalse; // Can't write an object to a stream!
  3431. output.writeCompressedInt (0);
  3432. }
  3433. };
  3434. class var::VariantType_Method : public var::VariantType
  3435. {
  3436. public:
  3437. VariantType_Method() {}
  3438. static const VariantType_Method* getInstance() { static const VariantType_Method i; return &i; }
  3439. const String toString (const ValueUnion&) const { return "Method"; }
  3440. bool toBool (const ValueUnion& data) const { return data.methodValue != 0; }
  3441. bool isMethod() const throw() { return true; }
  3442. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3443. {
  3444. return otherType.isMethod() && otherData.methodValue == data.methodValue;
  3445. }
  3446. void writeToStream (const ValueUnion&, OutputStream& output) const
  3447. {
  3448. jassertfalse; // Can't write a method to a stream!
  3449. output.writeCompressedInt (0);
  3450. }
  3451. };
  3452. var::var() throw()
  3453. : type (VariantType_Void::getInstance())
  3454. {
  3455. }
  3456. var::~var() throw()
  3457. {
  3458. type->cleanUp (value);
  3459. }
  3460. const var var::null;
  3461. var::var (const var& valueToCopy) : type (valueToCopy.type)
  3462. {
  3463. type->createCopy (value, valueToCopy.value);
  3464. }
  3465. var::var (const int value_) throw() : type (VariantType_Int::getInstance())
  3466. {
  3467. value.intValue = value_;
  3468. }
  3469. var::var (const bool value_) throw() : type (VariantType_Bool::getInstance())
  3470. {
  3471. value.boolValue = value_;
  3472. }
  3473. var::var (const double value_) throw() : type (VariantType_Double::getInstance())
  3474. {
  3475. value.doubleValue = value_;
  3476. }
  3477. var::var (const String& value_) : type (VariantType_String::getInstance())
  3478. {
  3479. value.stringValue = new String (value_);
  3480. }
  3481. var::var (const char* const value_) : type (VariantType_String::getInstance())
  3482. {
  3483. value.stringValue = new String (value_);
  3484. }
  3485. var::var (const juce_wchar* const value_) : type (VariantType_String::getInstance())
  3486. {
  3487. value.stringValue = new String (value_);
  3488. }
  3489. var::var (DynamicObject* const object) : type (VariantType_Object::getInstance())
  3490. {
  3491. value.objectValue = object;
  3492. if (object != 0)
  3493. object->incReferenceCount();
  3494. }
  3495. var::var (MethodFunction method_) throw() : type (VariantType_Method::getInstance())
  3496. {
  3497. value.methodValue = method_;
  3498. }
  3499. bool var::isVoid() const throw() { return type->isVoid(); }
  3500. bool var::isInt() const throw() { return type->isInt(); }
  3501. bool var::isBool() const throw() { return type->isBool(); }
  3502. bool var::isDouble() const throw() { return type->isDouble(); }
  3503. bool var::isString() const throw() { return type->isString(); }
  3504. bool var::isObject() const throw() { return type->isObject(); }
  3505. bool var::isMethod() const throw() { return type->isMethod(); }
  3506. var::operator int() const { return type->toInt (value); }
  3507. var::operator bool() const { return type->toBool (value); }
  3508. var::operator float() const { return (float) type->toDouble (value); }
  3509. var::operator double() const { return type->toDouble (value); }
  3510. const String var::toString() const { return type->toString (value); }
  3511. var::operator const String() const { return type->toString (value); }
  3512. DynamicObject* var::getObject() const { return type->toObject (value); }
  3513. void var::swapWith (var& other) throw()
  3514. {
  3515. swapVariables (type, other.type);
  3516. swapVariables (value, other.value);
  3517. }
  3518. var& var::operator= (const var& newValue) { type->cleanUp (value); type = newValue.type; type->createCopy (value, newValue.value); return *this; }
  3519. var& var::operator= (int newValue) { var v (newValue); swapWith (v); return *this; }
  3520. var& var::operator= (bool newValue) { var v (newValue); swapWith (v); return *this; }
  3521. var& var::operator= (double newValue) { var v (newValue); swapWith (v); return *this; }
  3522. var& var::operator= (const char* newValue) { var v (newValue); swapWith (v); return *this; }
  3523. var& var::operator= (const juce_wchar* newValue) { var v (newValue); swapWith (v); return *this; }
  3524. var& var::operator= (const String& newValue) { var v (newValue); swapWith (v); return *this; }
  3525. var& var::operator= (DynamicObject* newValue) { var v (newValue); swapWith (v); return *this; }
  3526. var& var::operator= (MethodFunction newValue) { var v (newValue); swapWith (v); return *this; }
  3527. bool var::equals (const var& other) const throw()
  3528. {
  3529. return type->equals (value, other.value, *other.type);
  3530. }
  3531. bool operator== (const var& v1, const var& v2) throw() { return v1.equals (v2); }
  3532. bool operator!= (const var& v1, const var& v2) throw() { return ! v1.equals (v2); }
  3533. bool operator== (const var& v1, const String& v2) throw() { return v1.toString() == v2; }
  3534. bool operator!= (const var& v1, const String& v2) throw() { return v1.toString() != v2; }
  3535. void var::writeToStream (OutputStream& output) const
  3536. {
  3537. type->writeToStream (value, output);
  3538. }
  3539. const var var::readFromStream (InputStream& input)
  3540. {
  3541. const int numBytes = input.readCompressedInt();
  3542. if (numBytes > 0)
  3543. {
  3544. switch (input.readByte())
  3545. {
  3546. case 1: return var (input.readInt());
  3547. case 2: return var (true);
  3548. case 3: return var (false);
  3549. case 4: return var (input.readDouble());
  3550. case 5:
  3551. {
  3552. MemoryOutputStream mo;
  3553. mo.writeFromInputStream (input, numBytes - 1);
  3554. return var (mo.toUTF8());
  3555. }
  3556. default: input.skipNextBytes (numBytes - 1); break;
  3557. }
  3558. }
  3559. return var::null;
  3560. }
  3561. const var var::operator[] (const Identifier& propertyName) const
  3562. {
  3563. DynamicObject* const o = getObject();
  3564. return o != 0 ? o->getProperty (propertyName) : var::null;
  3565. }
  3566. const var var::invoke (const Identifier& method, const var* arguments, int numArguments) const
  3567. {
  3568. DynamicObject* const o = getObject();
  3569. return o != 0 ? o->invokeMethod (method, arguments, numArguments) : var::null;
  3570. }
  3571. const var var::invoke (const var& targetObject, const var* arguments, int numArguments) const
  3572. {
  3573. if (isMethod())
  3574. {
  3575. DynamicObject* const target = targetObject.getObject();
  3576. if (target != 0)
  3577. return (target->*(value.methodValue)) (arguments, numArguments);
  3578. }
  3579. return var::null;
  3580. }
  3581. const var var::call (const Identifier& method) const
  3582. {
  3583. return invoke (method, 0, 0);
  3584. }
  3585. const var var::call (const Identifier& method, const var& arg1) const
  3586. {
  3587. return invoke (method, &arg1, 1);
  3588. }
  3589. const var var::call (const Identifier& method, const var& arg1, const var& arg2) const
  3590. {
  3591. var args[] = { arg1, arg2 };
  3592. return invoke (method, args, 2);
  3593. }
  3594. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3)
  3595. {
  3596. var args[] = { arg1, arg2, arg3 };
  3597. return invoke (method, args, 3);
  3598. }
  3599. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const
  3600. {
  3601. var args[] = { arg1, arg2, arg3, arg4 };
  3602. return invoke (method, args, 4);
  3603. }
  3604. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const
  3605. {
  3606. var args[] = { arg1, arg2, arg3, arg4, arg5 };
  3607. return invoke (method, args, 5);
  3608. }
  3609. END_JUCE_NAMESPACE
  3610. /*** End of inlined file: juce_Variant.cpp ***/
  3611. /*** Start of inlined file: juce_NamedValueSet.cpp ***/
  3612. BEGIN_JUCE_NAMESPACE
  3613. NamedValueSet::NamedValue::NamedValue() throw()
  3614. {
  3615. }
  3616. inline NamedValueSet::NamedValue::NamedValue (const Identifier& name_, const var& value_)
  3617. : name (name_), value (value_)
  3618. {
  3619. }
  3620. bool NamedValueSet::NamedValue::operator== (const NamedValueSet::NamedValue& other) const throw()
  3621. {
  3622. return name == other.name && value == other.value;
  3623. }
  3624. NamedValueSet::NamedValueSet() throw()
  3625. {
  3626. }
  3627. NamedValueSet::NamedValueSet (const NamedValueSet& other)
  3628. : values (other.values)
  3629. {
  3630. }
  3631. NamedValueSet& NamedValueSet::operator= (const NamedValueSet& other)
  3632. {
  3633. values = other.values;
  3634. return *this;
  3635. }
  3636. NamedValueSet::~NamedValueSet()
  3637. {
  3638. }
  3639. bool NamedValueSet::operator== (const NamedValueSet& other) const
  3640. {
  3641. return values == other.values;
  3642. }
  3643. bool NamedValueSet::operator!= (const NamedValueSet& other) const
  3644. {
  3645. return ! operator== (other);
  3646. }
  3647. int NamedValueSet::size() const throw()
  3648. {
  3649. return values.size();
  3650. }
  3651. const var& NamedValueSet::operator[] (const Identifier& name) const
  3652. {
  3653. for (int i = values.size(); --i >= 0;)
  3654. {
  3655. const NamedValue& v = values.getReference(i);
  3656. if (v.name == name)
  3657. return v.value;
  3658. }
  3659. return var::null;
  3660. }
  3661. const var NamedValueSet::getWithDefault (const Identifier& name, const var& defaultReturnValue) const
  3662. {
  3663. const var* v = getItem (name);
  3664. return v != 0 ? *v : defaultReturnValue;
  3665. }
  3666. var* NamedValueSet::getItem (const Identifier& name) const
  3667. {
  3668. for (int i = values.size(); --i >= 0;)
  3669. {
  3670. NamedValue& v = values.getReference(i);
  3671. if (v.name == name)
  3672. return &(v.value);
  3673. }
  3674. return 0;
  3675. }
  3676. bool NamedValueSet::set (const Identifier& name, const var& newValue)
  3677. {
  3678. for (int i = values.size(); --i >= 0;)
  3679. {
  3680. NamedValue& v = values.getReference(i);
  3681. if (v.name == name)
  3682. {
  3683. if (v.value == newValue)
  3684. return false;
  3685. v.value = newValue;
  3686. return true;
  3687. }
  3688. }
  3689. values.add (NamedValue (name, newValue));
  3690. return true;
  3691. }
  3692. bool NamedValueSet::contains (const Identifier& name) const
  3693. {
  3694. return getItem (name) != 0;
  3695. }
  3696. bool NamedValueSet::remove (const Identifier& name)
  3697. {
  3698. for (int i = values.size(); --i >= 0;)
  3699. {
  3700. if (values.getReference(i).name == name)
  3701. {
  3702. values.remove (i);
  3703. return true;
  3704. }
  3705. }
  3706. return false;
  3707. }
  3708. const Identifier NamedValueSet::getName (const int index) const
  3709. {
  3710. jassert (((unsigned int) index) < (unsigned int) values.size());
  3711. return values [index].name;
  3712. }
  3713. const var NamedValueSet::getValueAt (const int index) const
  3714. {
  3715. jassert (((unsigned int) index) < (unsigned int) values.size());
  3716. return values [index].value;
  3717. }
  3718. void NamedValueSet::clear()
  3719. {
  3720. values.clear();
  3721. }
  3722. END_JUCE_NAMESPACE
  3723. /*** End of inlined file: juce_NamedValueSet.cpp ***/
  3724. /*** Start of inlined file: juce_DynamicObject.cpp ***/
  3725. BEGIN_JUCE_NAMESPACE
  3726. DynamicObject::DynamicObject()
  3727. {
  3728. }
  3729. DynamicObject::~DynamicObject()
  3730. {
  3731. }
  3732. bool DynamicObject::hasProperty (const Identifier& propertyName) const
  3733. {
  3734. var* const v = properties.getItem (propertyName);
  3735. return v != 0 && ! v->isMethod();
  3736. }
  3737. const var DynamicObject::getProperty (const Identifier& propertyName) const
  3738. {
  3739. return properties [propertyName];
  3740. }
  3741. void DynamicObject::setProperty (const Identifier& propertyName, const var& newValue)
  3742. {
  3743. properties.set (propertyName, newValue);
  3744. }
  3745. void DynamicObject::removeProperty (const Identifier& propertyName)
  3746. {
  3747. properties.remove (propertyName);
  3748. }
  3749. bool DynamicObject::hasMethod (const Identifier& methodName) const
  3750. {
  3751. return getProperty (methodName).isMethod();
  3752. }
  3753. const var DynamicObject::invokeMethod (const Identifier& methodName,
  3754. const var* parameters,
  3755. int numParameters)
  3756. {
  3757. return properties [methodName].invoke (var (this), parameters, numParameters);
  3758. }
  3759. void DynamicObject::setMethod (const Identifier& name,
  3760. var::MethodFunction methodFunction)
  3761. {
  3762. properties.set (name, var (methodFunction));
  3763. }
  3764. void DynamicObject::clear()
  3765. {
  3766. properties.clear();
  3767. }
  3768. END_JUCE_NAMESPACE
  3769. /*** End of inlined file: juce_DynamicObject.cpp ***/
  3770. /*** Start of inlined file: juce_Expression.cpp ***/
  3771. BEGIN_JUCE_NAMESPACE
  3772. class Expression::Helpers
  3773. {
  3774. public:
  3775. typedef ReferenceCountedObjectPtr<Term> TermPtr;
  3776. class Constant : public Term
  3777. {
  3778. public:
  3779. Constant (const double value_, bool isResolutionTarget_)
  3780. : value (value_), isResolutionTarget (isResolutionTarget_) {}
  3781. Type getType() const throw() { return constantType; }
  3782. Term* clone() const { return new Constant (value, isResolutionTarget); }
  3783. double evaluate (const EvaluationContext&, int) const { return value; }
  3784. int getNumInputs() const { return 0; }
  3785. Term* getInput (int) const { return 0; }
  3786. const TermPtr negated()
  3787. {
  3788. return new Constant (-value, isResolutionTarget);
  3789. }
  3790. const String toString() const
  3791. {
  3792. if (isResolutionTarget)
  3793. return "@" + String (value);
  3794. return String (value);
  3795. }
  3796. double value;
  3797. bool isResolutionTarget;
  3798. };
  3799. class Symbol : public Term
  3800. {
  3801. public:
  3802. explicit Symbol (const String& symbol_)
  3803. : mainSymbol (symbol_.upToFirstOccurrenceOf (".", false, false).trim()),
  3804. member (symbol_.fromFirstOccurrenceOf (".", false, false).trim())
  3805. {}
  3806. Symbol (const String& symbol_, const String& member_)
  3807. : mainSymbol (symbol_),
  3808. member (member_)
  3809. {}
  3810. double evaluate (const EvaluationContext& c, int recursionDepth) const
  3811. {
  3812. if (++recursionDepth > 256)
  3813. throw EvaluationError ("Recursive symbol references");
  3814. try
  3815. {
  3816. return c.getSymbolValue (mainSymbol, member).term->evaluate (c, recursionDepth);
  3817. }
  3818. catch (...)
  3819. {}
  3820. return 0;
  3821. }
  3822. Type getType() const throw() { return symbolType; }
  3823. Term* clone() const { return new Symbol (mainSymbol, member); }
  3824. int getNumInputs() const { return 0; }
  3825. Term* getInput (int) const { return 0; }
  3826. const String getSymbolName() const { return toString(); }
  3827. const String toString() const
  3828. {
  3829. return member.isEmpty() ? mainSymbol
  3830. : mainSymbol + "." + member;
  3831. }
  3832. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3833. {
  3834. if (s == mainSymbol)
  3835. return true;
  3836. if (++recursionDepth > 256)
  3837. throw EvaluationError ("Recursive symbol references");
  3838. try
  3839. {
  3840. return c != 0 && c->getSymbolValue (mainSymbol, member).term->referencesSymbol (s, c, recursionDepth);
  3841. }
  3842. catch (EvaluationError&)
  3843. {
  3844. return false;
  3845. }
  3846. }
  3847. String mainSymbol, member;
  3848. };
  3849. class Function : public Term
  3850. {
  3851. public:
  3852. Function (const String& functionName_, const ReferenceCountedArray<Term>& parameters_)
  3853. : functionName (functionName_), parameters (parameters_)
  3854. {}
  3855. Term* clone() const { return new Function (functionName, parameters); }
  3856. double evaluate (const EvaluationContext& c, int recursionDepth) const
  3857. {
  3858. HeapBlock <double> params (parameters.size());
  3859. for (int i = 0; i < parameters.size(); ++i)
  3860. params[i] = parameters.getUnchecked(i)->evaluate (c, recursionDepth);
  3861. return c.evaluateFunction (functionName, params, parameters.size());
  3862. }
  3863. Type getType() const throw() { return functionType; }
  3864. int getInputIndexFor (const Term* possibleInput) const { return parameters.indexOf (possibleInput); }
  3865. int getNumInputs() const { return parameters.size(); }
  3866. Term* getInput (int i) const { return parameters [i]; }
  3867. const String getFunctionName() const { return functionName; }
  3868. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3869. {
  3870. for (int i = 0; i < parameters.size(); ++i)
  3871. if (parameters.getUnchecked(i)->referencesSymbol (s, c, recursionDepth))
  3872. return true;
  3873. return false;
  3874. }
  3875. const String toString() const
  3876. {
  3877. if (parameters.size() == 0)
  3878. return functionName + "()";
  3879. String s (functionName + " (");
  3880. for (int i = 0; i < parameters.size(); ++i)
  3881. {
  3882. s << parameters.getUnchecked(i)->toString();
  3883. if (i < parameters.size() - 1)
  3884. s << ", ";
  3885. }
  3886. s << ')';
  3887. return s;
  3888. }
  3889. const String functionName;
  3890. ReferenceCountedArray<Term> parameters;
  3891. };
  3892. class Negate : public Term
  3893. {
  3894. public:
  3895. Negate (const TermPtr& input_) : input (input_)
  3896. {
  3897. jassert (input_ != 0);
  3898. }
  3899. Type getType() const throw() { return operatorType; }
  3900. int getInputIndexFor (const Term* possibleInput) const { return possibleInput == input ? 0 : -1; }
  3901. int getNumInputs() const { return 1; }
  3902. Term* getInput (int index) const { return index == 0 ? static_cast<Term*> (input) : 0; }
  3903. Term* clone() const { return new Negate (input->clone()); }
  3904. double evaluate (const EvaluationContext& c, int recursionDepth) const { return -input->evaluate (c, recursionDepth); }
  3905. const String getFunctionName() const { return "-"; }
  3906. const TermPtr negated()
  3907. {
  3908. return input;
  3909. }
  3910. const TermPtr createTermToEvaluateInput (const EvaluationContext& context, const Term* input_, double overallTarget, Term* topLevelTerm) const
  3911. {
  3912. (void) input_;
  3913. jassert (input_ == input);
  3914. const Term* const dest = findDestinationFor (topLevelTerm, this);
  3915. return new Negate (dest == 0 ? new Constant (overallTarget, false)
  3916. : dest->createTermToEvaluateInput (context, this, overallTarget, topLevelTerm));
  3917. }
  3918. const String toString() const
  3919. {
  3920. if (input->getOperatorPrecedence() > 0)
  3921. return "-(" + input->toString() + ")";
  3922. else
  3923. return "-" + input->toString();
  3924. }
  3925. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3926. {
  3927. return input->referencesSymbol (s, c, recursionDepth);
  3928. }
  3929. private:
  3930. const TermPtr input;
  3931. };
  3932. class BinaryTerm : public Term
  3933. {
  3934. public:
  3935. BinaryTerm (Term* const left_, Term* const right_) : left (left_), right (right_)
  3936. {
  3937. jassert (left_ != 0 && right_ != 0);
  3938. }
  3939. int getInputIndexFor (const Term* possibleInput) const
  3940. {
  3941. return possibleInput == left ? 0 : (possibleInput == right ? 1 : -1);
  3942. }
  3943. Type getType() const throw() { return operatorType; }
  3944. int getNumInputs() const { return 2; }
  3945. Term* getInput (int index) const { return index == 0 ? static_cast<Term*> (left) : (index == 1 ? static_cast<Term*> (right) : 0); }
  3946. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3947. {
  3948. return left->referencesSymbol (s, c, recursionDepth)
  3949. || right->referencesSymbol (s, c, recursionDepth);
  3950. }
  3951. const String toString() const
  3952. {
  3953. String s;
  3954. const int ourPrecendence = getOperatorPrecedence();
  3955. if (left->getOperatorPrecedence() > ourPrecendence)
  3956. s << '(' << left->toString() << ')';
  3957. else
  3958. s = left->toString();
  3959. s << ' ' << getFunctionName() << ' ';
  3960. if (right->getOperatorPrecedence() >= ourPrecendence)
  3961. s << '(' << right->toString() << ')';
  3962. else
  3963. s << right->toString();
  3964. return s;
  3965. }
  3966. protected:
  3967. const TermPtr left, right;
  3968. const TermPtr createDestinationTerm (const EvaluationContext& context, const Term* input, double overallTarget, Term* topLevelTerm) const
  3969. {
  3970. jassert (input == left || input == right);
  3971. if (input != left && input != right)
  3972. return 0;
  3973. const Term* const dest = findDestinationFor (topLevelTerm, this);
  3974. if (dest == 0)
  3975. return new Constant (overallTarget, false);
  3976. return dest->createTermToEvaluateInput (context, this, overallTarget, topLevelTerm);
  3977. }
  3978. };
  3979. class Add : public BinaryTerm
  3980. {
  3981. public:
  3982. Add (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  3983. Term* clone() const { return new Add (left->clone(), right->clone()); }
  3984. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) + right->evaluate (c, recursionDepth); }
  3985. int getOperatorPrecedence() const { return 2; }
  3986. const String getFunctionName() const { return "+"; }
  3987. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  3988. {
  3989. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  3990. if (newDest == 0)
  3991. return 0;
  3992. return new Subtract (newDest, (input == left ? right : left)->clone());
  3993. }
  3994. private:
  3995. Add (const Add&);
  3996. Add& operator= (const Add&);
  3997. };
  3998. class Subtract : public BinaryTerm
  3999. {
  4000. public:
  4001. Subtract (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4002. Term* clone() const { return new Subtract (left->clone(), right->clone()); }
  4003. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) - right->evaluate (c, recursionDepth); }
  4004. int getOperatorPrecedence() const { return 2; }
  4005. const String getFunctionName() const { return "-"; }
  4006. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  4007. {
  4008. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  4009. if (newDest == 0)
  4010. return 0;
  4011. if (input == left)
  4012. return new Add (newDest, right->clone());
  4013. else
  4014. return new Subtract (left->clone(), newDest);
  4015. }
  4016. private:
  4017. Subtract (const Subtract&);
  4018. Subtract& operator= (const Subtract&);
  4019. };
  4020. class Multiply : public BinaryTerm
  4021. {
  4022. public:
  4023. Multiply (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4024. Term* clone() const { return new Multiply (left->clone(), right->clone()); }
  4025. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) * right->evaluate (c, recursionDepth); }
  4026. const String getFunctionName() const { return "*"; }
  4027. int getOperatorPrecedence() const { return 1; }
  4028. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  4029. {
  4030. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  4031. if (newDest == 0)
  4032. return 0;
  4033. return new Divide (newDest, (input == left ? right : left)->clone());
  4034. }
  4035. private:
  4036. Multiply (const Multiply&);
  4037. Multiply& operator= (const Multiply&);
  4038. };
  4039. class Divide : public BinaryTerm
  4040. {
  4041. public:
  4042. Divide (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4043. Term* clone() const { return new Divide (left->clone(), right->clone()); }
  4044. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) / right->evaluate (c, recursionDepth); }
  4045. const String getFunctionName() const { return "/"; }
  4046. int getOperatorPrecedence() const { return 1; }
  4047. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  4048. {
  4049. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  4050. if (newDest == 0)
  4051. return 0;
  4052. if (input == left)
  4053. return new Multiply (newDest, right->clone());
  4054. else
  4055. return new Divide (left->clone(), newDest);
  4056. }
  4057. private:
  4058. Divide (const Divide&);
  4059. Divide& operator= (const Divide&);
  4060. };
  4061. static Term* findDestinationFor (Term* const topLevel, const Term* const inputTerm)
  4062. {
  4063. const int inputIndex = topLevel->getInputIndexFor (inputTerm);
  4064. if (inputIndex >= 0)
  4065. return topLevel;
  4066. for (int i = topLevel->getNumInputs(); --i >= 0;)
  4067. {
  4068. Term* t = findDestinationFor (topLevel->getInput (i), inputTerm);
  4069. if (t != 0)
  4070. return t;
  4071. }
  4072. return 0;
  4073. }
  4074. static Constant* findTermToAdjust (Term* const term, const bool mustBeFlagged)
  4075. {
  4076. Constant* c = dynamic_cast<Constant*> (term);
  4077. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4078. return c;
  4079. if (dynamic_cast<Function*> (term) != 0)
  4080. return 0;
  4081. int i;
  4082. const int numIns = term->getNumInputs();
  4083. for (i = 0; i < numIns; ++i)
  4084. {
  4085. Constant* c = dynamic_cast<Constant*> (term->getInput (i));
  4086. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4087. return c;
  4088. }
  4089. for (i = 0; i < numIns; ++i)
  4090. {
  4091. Constant* c = findTermToAdjust (term->getInput (i), mustBeFlagged);
  4092. if (c != 0)
  4093. return c;
  4094. }
  4095. return 0;
  4096. }
  4097. static bool containsAnySymbols (const Term* const t)
  4098. {
  4099. if (dynamic_cast <const Symbol*> (t) != 0)
  4100. return true;
  4101. for (int i = t->getNumInputs(); --i >= 0;)
  4102. if (containsAnySymbols (t->getInput (i)))
  4103. return true;
  4104. return false;
  4105. }
  4106. static bool renameSymbol (Term* const t, const String& oldName, const String& newName)
  4107. {
  4108. Symbol* const sym = dynamic_cast <Symbol*> (t);
  4109. if (sym != 0 && sym->mainSymbol == oldName)
  4110. {
  4111. sym->mainSymbol = newName;
  4112. return true;
  4113. }
  4114. bool anyChanged = false;
  4115. for (int i = t->getNumInputs(); --i >= 0;)
  4116. if (renameSymbol (t->getInput (i), oldName, newName))
  4117. anyChanged = true;
  4118. return anyChanged;
  4119. }
  4120. class Parser
  4121. {
  4122. public:
  4123. Parser (const String& stringToParse, int& textIndex_)
  4124. : textString (stringToParse), textIndex (textIndex_)
  4125. {
  4126. text = textString;
  4127. }
  4128. const TermPtr readExpression()
  4129. {
  4130. TermPtr lhs (readMultiplyOrDivideExpression());
  4131. char opType;
  4132. while (lhs != 0 && readOperator ("+-", &opType))
  4133. {
  4134. TermPtr rhs (readMultiplyOrDivideExpression());
  4135. if (rhs == 0)
  4136. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4137. if (opType == '+')
  4138. lhs = new Add (lhs, rhs);
  4139. else
  4140. lhs = new Subtract (lhs, rhs);
  4141. }
  4142. return lhs;
  4143. }
  4144. private:
  4145. const String textString;
  4146. const juce_wchar* text;
  4147. int& textIndex;
  4148. static inline bool isDecimalDigit (const juce_wchar c) throw()
  4149. {
  4150. return c >= '0' && c <= '9';
  4151. }
  4152. void skipWhitespace (int& i)
  4153. {
  4154. while (CharacterFunctions::isWhitespace (text [i]))
  4155. ++i;
  4156. }
  4157. bool readChar (const juce_wchar required)
  4158. {
  4159. if (text[textIndex] == required)
  4160. {
  4161. ++textIndex;
  4162. return true;
  4163. }
  4164. return false;
  4165. }
  4166. bool readOperator (const char* ops, char* const opType = 0)
  4167. {
  4168. skipWhitespace (textIndex);
  4169. while (*ops != 0)
  4170. {
  4171. if (readChar (*ops))
  4172. {
  4173. if (opType != 0)
  4174. *opType = *ops;
  4175. return true;
  4176. }
  4177. ++ops;
  4178. }
  4179. return false;
  4180. }
  4181. bool readIdentifier (String& identifier)
  4182. {
  4183. skipWhitespace (textIndex);
  4184. int i = textIndex;
  4185. if (CharacterFunctions::isLetter (text[i]) || text[i] == '_')
  4186. {
  4187. ++i;
  4188. while (CharacterFunctions::isLetterOrDigit (text[i]) || text[i] == '_' || text[i] == '.')
  4189. ++i;
  4190. }
  4191. if (i > textIndex)
  4192. {
  4193. identifier = String (text + textIndex, i - textIndex);
  4194. textIndex = i;
  4195. return true;
  4196. }
  4197. return false;
  4198. }
  4199. Term* readNumber()
  4200. {
  4201. skipWhitespace (textIndex);
  4202. int i = textIndex;
  4203. const bool isResolutionTarget = (text[i] == '@');
  4204. if (isResolutionTarget)
  4205. {
  4206. ++i;
  4207. skipWhitespace (i);
  4208. textIndex = i;
  4209. }
  4210. if (text[i] == '-')
  4211. {
  4212. ++i;
  4213. skipWhitespace (i);
  4214. }
  4215. int numDigits = 0;
  4216. while (isDecimalDigit (text[i]))
  4217. {
  4218. ++i;
  4219. ++numDigits;
  4220. }
  4221. const bool hasPoint = (text[i] == '.');
  4222. if (hasPoint)
  4223. {
  4224. ++i;
  4225. while (isDecimalDigit (text[i]))
  4226. {
  4227. ++i;
  4228. ++numDigits;
  4229. }
  4230. }
  4231. if (numDigits == 0)
  4232. return 0;
  4233. juce_wchar c = text[i];
  4234. const bool hasExponent = (c == 'e' || c == 'E');
  4235. if (hasExponent)
  4236. {
  4237. ++i;
  4238. c = text[i];
  4239. if (c == '+' || c == '-')
  4240. ++i;
  4241. int numExpDigits = 0;
  4242. while (isDecimalDigit (text[i]))
  4243. {
  4244. ++i;
  4245. ++numExpDigits;
  4246. }
  4247. if (numExpDigits == 0)
  4248. return 0;
  4249. }
  4250. const int start = textIndex;
  4251. textIndex = i;
  4252. return new Constant (String (text + start, i - start).getDoubleValue(), isResolutionTarget);
  4253. }
  4254. const TermPtr readMultiplyOrDivideExpression()
  4255. {
  4256. TermPtr lhs (readUnaryExpression());
  4257. char opType;
  4258. while (lhs != 0 && readOperator ("*/", &opType))
  4259. {
  4260. TermPtr rhs (readUnaryExpression());
  4261. if (rhs == 0)
  4262. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4263. if (opType == '*')
  4264. lhs = new Multiply (lhs, rhs);
  4265. else
  4266. lhs = new Divide (lhs, rhs);
  4267. }
  4268. return lhs;
  4269. }
  4270. const TermPtr readUnaryExpression()
  4271. {
  4272. char opType;
  4273. if (readOperator ("+-", &opType))
  4274. {
  4275. TermPtr term (readUnaryExpression());
  4276. if (term == 0)
  4277. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4278. if (opType == '-')
  4279. term = term->negated();
  4280. return term;
  4281. }
  4282. return readPrimaryExpression();
  4283. }
  4284. const TermPtr readPrimaryExpression()
  4285. {
  4286. TermPtr e (readParenthesisedExpression());
  4287. if (e != 0)
  4288. return e;
  4289. e = readNumber();
  4290. if (e != 0)
  4291. return e;
  4292. String identifier;
  4293. if (readIdentifier (identifier))
  4294. {
  4295. if (readOperator ("(")) // method call...
  4296. {
  4297. Function* f = new Function (identifier, ReferenceCountedArray<Term>());
  4298. ScopedPointer<Term> func (f); // (can't use ScopedPointer<Function> in MSVC)
  4299. TermPtr param (readExpression());
  4300. if (param == 0)
  4301. {
  4302. if (readOperator (")"))
  4303. return func.release();
  4304. throw ParseError ("Expected parameters after \"" + identifier + " (\"");
  4305. }
  4306. f->parameters.add (param);
  4307. while (readOperator (","))
  4308. {
  4309. param = readExpression();
  4310. if (param == 0)
  4311. throw ParseError ("Expected expression after \",\"");
  4312. f->parameters.add (param);
  4313. }
  4314. if (readOperator (")"))
  4315. return func.release();
  4316. throw ParseError ("Expected \")\"");
  4317. }
  4318. else // just a symbol..
  4319. {
  4320. return new Symbol (identifier);
  4321. }
  4322. }
  4323. return 0;
  4324. }
  4325. const TermPtr readParenthesisedExpression()
  4326. {
  4327. if (! readOperator ("("))
  4328. return 0;
  4329. const TermPtr e (readExpression());
  4330. if (e == 0 || ! readOperator (")"))
  4331. return 0;
  4332. return e;
  4333. }
  4334. Parser (const Parser&);
  4335. Parser& operator= (const Parser&);
  4336. };
  4337. };
  4338. Expression::Expression()
  4339. : term (new Expression::Helpers::Constant (0, false))
  4340. {
  4341. }
  4342. Expression::~Expression()
  4343. {
  4344. }
  4345. Expression::Expression (Term* const term_)
  4346. : term (term_)
  4347. {
  4348. jassert (term != 0);
  4349. }
  4350. Expression::Expression (const double constant)
  4351. : term (new Expression::Helpers::Constant (constant, false))
  4352. {
  4353. }
  4354. Expression::Expression (const Expression& other)
  4355. : term (other.term)
  4356. {
  4357. }
  4358. Expression& Expression::operator= (const Expression& other)
  4359. {
  4360. term = other.term;
  4361. return *this;
  4362. }
  4363. Expression::Expression (const String& stringToParse)
  4364. {
  4365. int i = 0;
  4366. Helpers::Parser parser (stringToParse, i);
  4367. term = parser.readExpression();
  4368. if (term == 0)
  4369. term = new Helpers::Constant (0, false);
  4370. }
  4371. const Expression Expression::parse (const String& stringToParse, int& textIndexToStartFrom)
  4372. {
  4373. Helpers::Parser parser (stringToParse, textIndexToStartFrom);
  4374. const Helpers::TermPtr term (parser.readExpression());
  4375. if (term != 0)
  4376. return Expression (term);
  4377. return Expression();
  4378. }
  4379. double Expression::evaluate() const
  4380. {
  4381. return evaluate (Expression::EvaluationContext());
  4382. }
  4383. double Expression::evaluate (const Expression::EvaluationContext& context) const
  4384. {
  4385. return term->evaluate (context, 0);
  4386. }
  4387. const Expression Expression::operator+ (const Expression& other) const { return Expression (new Helpers::Add (term, other.term)); }
  4388. const Expression Expression::operator- (const Expression& other) const { return Expression (new Helpers::Subtract (term, other.term)); }
  4389. const Expression Expression::operator* (const Expression& other) const { return Expression (new Helpers::Multiply (term, other.term)); }
  4390. const Expression Expression::operator/ (const Expression& other) const { return Expression (new Helpers::Divide (term, other.term)); }
  4391. const Expression Expression::operator-() const { return Expression (term->negated()); }
  4392. const String Expression::toString() const
  4393. {
  4394. return term->toString();
  4395. }
  4396. const Expression Expression::symbol (const String& symbol)
  4397. {
  4398. return Expression (new Helpers::Symbol (symbol));
  4399. }
  4400. const Expression Expression::function (const String& functionName, const Array<Expression>& parameters)
  4401. {
  4402. ReferenceCountedArray<Term> params;
  4403. for (int i = 0; i < parameters.size(); ++i)
  4404. params.add (parameters.getReference(i).term);
  4405. return Expression (new Helpers::Function (functionName, params));
  4406. }
  4407. const Expression Expression::adjustedToGiveNewResult (const double targetValue,
  4408. const Expression::EvaluationContext& context) const
  4409. {
  4410. ScopedPointer<Term> newTerm (term->clone());
  4411. Helpers::Constant* termToAdjust = Helpers::findTermToAdjust (newTerm, true);
  4412. if (termToAdjust == 0)
  4413. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4414. if (termToAdjust == 0)
  4415. {
  4416. newTerm = new Helpers::Add (newTerm.release(), new Helpers::Constant (0, false));
  4417. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4418. }
  4419. jassert (termToAdjust != 0);
  4420. const Term* parent = Helpers::findDestinationFor (newTerm, termToAdjust);
  4421. if (parent == 0)
  4422. {
  4423. termToAdjust->value = targetValue;
  4424. }
  4425. else
  4426. {
  4427. const Helpers::TermPtr reverseTerm (parent->createTermToEvaluateInput (context, termToAdjust, targetValue, newTerm));
  4428. if (reverseTerm == 0)
  4429. return Expression (targetValue);
  4430. termToAdjust->value = reverseTerm->evaluate (context, 0);
  4431. }
  4432. return Expression (newTerm.release());
  4433. }
  4434. const Expression Expression::withRenamedSymbol (const String& oldSymbol, const String& newSymbol) const
  4435. {
  4436. jassert (newSymbol.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  4437. Expression newExpression (term->clone());
  4438. Helpers::renameSymbol (newExpression.term, oldSymbol, newSymbol);
  4439. return newExpression;
  4440. }
  4441. bool Expression::referencesSymbol (const String& symbol, const EvaluationContext* context) const
  4442. {
  4443. return term->referencesSymbol (symbol, context, 0);
  4444. }
  4445. bool Expression::usesAnySymbols() const
  4446. {
  4447. return Helpers::containsAnySymbols (term);
  4448. }
  4449. Expression::Type Expression::getType() const throw()
  4450. {
  4451. return term->getType();
  4452. }
  4453. const String Expression::getSymbol() const
  4454. {
  4455. return term->getSymbolName();
  4456. }
  4457. const String Expression::getFunction() const
  4458. {
  4459. return term->getFunctionName();
  4460. }
  4461. const String Expression::getOperator() const
  4462. {
  4463. return term->getFunctionName();
  4464. }
  4465. int Expression::getNumInputs() const
  4466. {
  4467. return term->getNumInputs();
  4468. }
  4469. const Expression Expression::getInput (int index) const
  4470. {
  4471. return Expression (term->getInput (index));
  4472. }
  4473. int Expression::Term::getOperatorPrecedence() const
  4474. {
  4475. return 0;
  4476. }
  4477. bool Expression::Term::referencesSymbol (const String&, const EvaluationContext*, int) const
  4478. {
  4479. return false;
  4480. }
  4481. int Expression::Term::getInputIndexFor (const Term*) const
  4482. {
  4483. return -1;
  4484. }
  4485. const ReferenceCountedObjectPtr<Expression::Term> Expression::Term::createTermToEvaluateInput (const EvaluationContext&, const Term*, double, Term*) const
  4486. {
  4487. jassertfalse;
  4488. return 0;
  4489. }
  4490. const ReferenceCountedObjectPtr<Expression::Term> Expression::Term::negated()
  4491. {
  4492. return new Helpers::Negate (this);
  4493. }
  4494. const String Expression::Term::getSymbolName() const
  4495. {
  4496. jassertfalse; // You should only call getSymbol() on an expression that's actually a symbol!
  4497. return String::empty;
  4498. }
  4499. const String Expression::Term::getFunctionName() const
  4500. {
  4501. jassertfalse; // You shouldn't call this for an expression that's not actually a function!
  4502. return String::empty;
  4503. }
  4504. Expression::ParseError::ParseError (const String& message)
  4505. : description (message)
  4506. {
  4507. DBG ("Expression::ParseError: " + message);
  4508. }
  4509. Expression::EvaluationError::EvaluationError (const String& message)
  4510. : description (message)
  4511. {
  4512. DBG ("Expression::EvaluationError: " + description);
  4513. }
  4514. Expression::EvaluationError::EvaluationError (const String& symbol, const String& member)
  4515. : description ("Unknown symbol: \"" + symbol + (member.isEmpty() ? "\"" : ("." + member + "\"")))
  4516. {
  4517. DBG ("Expression::EvaluationError: " + description);
  4518. }
  4519. Expression::EvaluationContext::EvaluationContext() {}
  4520. Expression::EvaluationContext::~EvaluationContext() {}
  4521. const Expression Expression::EvaluationContext::getSymbolValue (const String& symbol, const String& member) const
  4522. {
  4523. throw EvaluationError (symbol, member);
  4524. }
  4525. double Expression::EvaluationContext::evaluateFunction (const String& functionName, const double* parameters, int numParams) const
  4526. {
  4527. if (numParams > 0)
  4528. {
  4529. if (functionName == "min")
  4530. {
  4531. double v = parameters[0];
  4532. for (int i = 1; i < numParams; ++i)
  4533. v = jmin (v, parameters[i]);
  4534. return v;
  4535. }
  4536. else if (functionName == "max")
  4537. {
  4538. double v = parameters[0];
  4539. for (int i = 1; i < numParams; ++i)
  4540. v = jmax (v, parameters[i]);
  4541. return v;
  4542. }
  4543. else if (numParams == 1)
  4544. {
  4545. if (functionName == "sin") return sin (parameters[0]);
  4546. else if (functionName == "cos") return cos (parameters[0]);
  4547. else if (functionName == "tan") return tan (parameters[0]);
  4548. else if (functionName == "abs") return std::abs (parameters[0]);
  4549. }
  4550. }
  4551. throw EvaluationError ("Unknown function: \"" + functionName + "\"");
  4552. }
  4553. END_JUCE_NAMESPACE
  4554. /*** End of inlined file: juce_Expression.cpp ***/
  4555. /*** Start of inlined file: juce_BlowFish.cpp ***/
  4556. BEGIN_JUCE_NAMESPACE
  4557. BlowFish::BlowFish (const void* const keyData, const int keyBytes)
  4558. {
  4559. jassert (keyData != 0);
  4560. jassert (keyBytes > 0);
  4561. static const uint32 initialPValues [18] =
  4562. {
  4563. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  4564. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  4565. 0x9216d5d9, 0x8979fb1b
  4566. };
  4567. static const uint32 initialSValues [4 * 256] =
  4568. {
  4569. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  4570. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  4571. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  4572. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  4573. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  4574. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  4575. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  4576. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  4577. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  4578. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  4579. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  4580. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  4581. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  4582. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  4583. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  4584. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  4585. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  4586. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  4587. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  4588. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  4589. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  4590. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  4591. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  4592. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  4593. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  4594. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  4595. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  4596. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  4597. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  4598. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  4599. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  4600. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  4601. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  4602. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  4603. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  4604. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  4605. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  4606. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  4607. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  4608. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  4609. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  4610. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  4611. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  4612. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  4613. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  4614. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  4615. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  4616. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  4617. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  4618. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  4619. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  4620. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  4621. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  4622. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  4623. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  4624. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  4625. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  4626. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  4627. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  4628. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  4629. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  4630. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  4631. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  4632. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  4633. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  4634. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  4635. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  4636. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  4637. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  4638. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  4639. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  4640. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  4641. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  4642. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  4643. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  4644. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  4645. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  4646. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  4647. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  4648. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  4649. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  4650. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  4651. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  4652. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  4653. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  4654. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  4655. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  4656. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  4657. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  4658. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  4659. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  4660. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  4661. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  4662. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  4663. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  4664. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  4665. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  4666. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  4667. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  4668. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  4669. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  4670. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  4671. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  4672. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  4673. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  4674. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  4675. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  4676. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  4677. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  4678. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  4679. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  4680. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  4681. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  4682. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  4683. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  4684. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  4685. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  4686. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  4687. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  4688. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  4689. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  4690. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  4691. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  4692. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  4693. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  4694. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  4695. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  4696. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  4697. };
  4698. memcpy (p, initialPValues, sizeof (p));
  4699. int i, j = 0;
  4700. for (i = 4; --i >= 0;)
  4701. {
  4702. s[i].malloc (256);
  4703. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  4704. }
  4705. for (i = 0; i < 18; ++i)
  4706. {
  4707. uint32 d = 0;
  4708. for (int k = 0; k < 4; ++k)
  4709. {
  4710. d = (d << 8) | static_cast <const uint8*> (keyData)[j];
  4711. if (++j >= keyBytes)
  4712. j = 0;
  4713. }
  4714. p[i] = initialPValues[i] ^ d;
  4715. }
  4716. uint32 l = 0, r = 0;
  4717. for (i = 0; i < 18; i += 2)
  4718. {
  4719. encrypt (l, r);
  4720. p[i] = l;
  4721. p[i + 1] = r;
  4722. }
  4723. for (i = 0; i < 4; ++i)
  4724. {
  4725. for (j = 0; j < 256; j += 2)
  4726. {
  4727. encrypt (l, r);
  4728. s[i][j] = l;
  4729. s[i][j + 1] = r;
  4730. }
  4731. }
  4732. }
  4733. BlowFish::BlowFish (const BlowFish& other)
  4734. {
  4735. for (int i = 4; --i >= 0;)
  4736. s[i].malloc (256);
  4737. operator= (other);
  4738. }
  4739. BlowFish& BlowFish::operator= (const BlowFish& other)
  4740. {
  4741. memcpy (p, other.p, sizeof (p));
  4742. for (int i = 4; --i >= 0;)
  4743. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  4744. return *this;
  4745. }
  4746. BlowFish::~BlowFish()
  4747. {
  4748. }
  4749. uint32 BlowFish::F (const uint32 x) const throw()
  4750. {
  4751. return ((s[0][(x >> 24) & 0xff] + s[1][(x >> 16) & 0xff])
  4752. ^ s[2][(x >> 8) & 0xff]) + s[3][x & 0xff];
  4753. }
  4754. void BlowFish::encrypt (uint32& data1, uint32& data2) const throw()
  4755. {
  4756. uint32 l = data1;
  4757. uint32 r = data2;
  4758. for (int i = 0; i < 16; ++i)
  4759. {
  4760. l ^= p[i];
  4761. r ^= F(l);
  4762. swapVariables (l, r);
  4763. }
  4764. data1 = r ^ p[17];
  4765. data2 = l ^ p[16];
  4766. }
  4767. void BlowFish::decrypt (uint32& data1, uint32& data2) const throw()
  4768. {
  4769. uint32 l = data1;
  4770. uint32 r = data2;
  4771. for (int i = 17; i > 1; --i)
  4772. {
  4773. l ^= p[i];
  4774. r ^= F(l);
  4775. swapVariables (l, r);
  4776. }
  4777. data1 = r ^ p[0];
  4778. data2 = l ^ p[1];
  4779. }
  4780. END_JUCE_NAMESPACE
  4781. /*** End of inlined file: juce_BlowFish.cpp ***/
  4782. /*** Start of inlined file: juce_MD5.cpp ***/
  4783. BEGIN_JUCE_NAMESPACE
  4784. MD5::MD5()
  4785. {
  4786. zerostruct (result);
  4787. }
  4788. MD5::MD5 (const MD5& other)
  4789. {
  4790. memcpy (result, other.result, sizeof (result));
  4791. }
  4792. MD5& MD5::operator= (const MD5& other)
  4793. {
  4794. memcpy (result, other.result, sizeof (result));
  4795. return *this;
  4796. }
  4797. MD5::MD5 (const MemoryBlock& data)
  4798. {
  4799. ProcessContext context;
  4800. context.processBlock (data.getData(), data.getSize());
  4801. context.finish (result);
  4802. }
  4803. MD5::MD5 (const void* data, const size_t numBytes)
  4804. {
  4805. ProcessContext context;
  4806. context.processBlock (data, numBytes);
  4807. context.finish (result);
  4808. }
  4809. MD5::MD5 (const String& text)
  4810. {
  4811. ProcessContext context;
  4812. const int len = text.length();
  4813. const juce_wchar* const t = text;
  4814. for (int i = 0; i < len; ++i)
  4815. {
  4816. // force the string into integer-sized unicode characters, to try to make it
  4817. // get the same results on all platforms + compilers.
  4818. uint32 unicodeChar = ByteOrder::swapIfBigEndian ((uint32) t[i]);
  4819. context.processBlock (&unicodeChar, sizeof (unicodeChar));
  4820. }
  4821. context.finish (result);
  4822. }
  4823. void MD5::processStream (InputStream& input, int64 numBytesToRead)
  4824. {
  4825. ProcessContext context;
  4826. if (numBytesToRead < 0)
  4827. numBytesToRead = std::numeric_limits<int64>::max();
  4828. while (numBytesToRead > 0)
  4829. {
  4830. uint8 tempBuffer [512];
  4831. const int bytesRead = input.read (tempBuffer, (int) jmin (numBytesToRead, (int64) sizeof (tempBuffer)));
  4832. if (bytesRead <= 0)
  4833. break;
  4834. numBytesToRead -= bytesRead;
  4835. context.processBlock (tempBuffer, bytesRead);
  4836. }
  4837. context.finish (result);
  4838. }
  4839. MD5::MD5 (InputStream& input, int64 numBytesToRead)
  4840. {
  4841. processStream (input, numBytesToRead);
  4842. }
  4843. MD5::MD5 (const File& file)
  4844. {
  4845. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  4846. if (fin != 0)
  4847. processStream (*fin, -1);
  4848. else
  4849. zerostruct (result);
  4850. }
  4851. MD5::~MD5()
  4852. {
  4853. }
  4854. namespace MD5Functions
  4855. {
  4856. static void encode (void* const output, const void* const input, const int numBytes) throw()
  4857. {
  4858. for (int i = 0; i < (numBytes >> 2); ++i)
  4859. static_cast<uint32*> (output)[i] = ByteOrder::swapIfBigEndian (static_cast<const uint32*> (input) [i]);
  4860. }
  4861. static inline uint32 F (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & y) | (~x & z); }
  4862. static inline uint32 G (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & z) | (y & ~z); }
  4863. static inline uint32 H (const uint32 x, const uint32 y, const uint32 z) throw() { return x ^ y ^ z; }
  4864. static inline uint32 I (const uint32 x, const uint32 y, const uint32 z) throw() { return y ^ (x | ~z); }
  4865. static inline uint32 rotateLeft (const uint32 x, const uint32 n) throw() { return (x << n) | (x >> (32 - n)); }
  4866. static void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4867. {
  4868. a += F (b, c, d) + x + ac;
  4869. a = rotateLeft (a, s) + b;
  4870. }
  4871. static void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4872. {
  4873. a += G (b, c, d) + x + ac;
  4874. a = rotateLeft (a, s) + b;
  4875. }
  4876. static void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4877. {
  4878. a += H (b, c, d) + x + ac;
  4879. a = rotateLeft (a, s) + b;
  4880. }
  4881. static void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4882. {
  4883. a += I (b, c, d) + x + ac;
  4884. a = rotateLeft (a, s) + b;
  4885. }
  4886. }
  4887. MD5::ProcessContext::ProcessContext()
  4888. {
  4889. state[0] = 0x67452301;
  4890. state[1] = 0xefcdab89;
  4891. state[2] = 0x98badcfe;
  4892. state[3] = 0x10325476;
  4893. count[0] = 0;
  4894. count[1] = 0;
  4895. }
  4896. void MD5::ProcessContext::processBlock (const void* const data, const size_t dataSize)
  4897. {
  4898. int bufferPos = ((count[0] >> 3) & 0x3F);
  4899. count[0] += (uint32) (dataSize << 3);
  4900. if (count[0] < ((uint32) dataSize << 3))
  4901. count[1]++;
  4902. count[1] += (uint32) (dataSize >> 29);
  4903. const size_t spaceLeft = 64 - bufferPos;
  4904. size_t i = 0;
  4905. if (dataSize >= spaceLeft)
  4906. {
  4907. memcpy (buffer + bufferPos, data, spaceLeft);
  4908. transform (buffer);
  4909. for (i = spaceLeft; i + 64 <= dataSize; i += 64)
  4910. transform (static_cast <const char*> (data) + i);
  4911. bufferPos = 0;
  4912. }
  4913. memcpy (buffer + bufferPos, static_cast <const char*> (data) + i, dataSize - i);
  4914. }
  4915. void MD5::ProcessContext::finish (void* const result)
  4916. {
  4917. unsigned char encodedLength[8];
  4918. MD5Functions::encode (encodedLength, count, 8);
  4919. // Pad out to 56 mod 64.
  4920. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  4921. const int paddingLength = (index < 56) ? (56 - index)
  4922. : (120 - index);
  4923. uint8 paddingBuffer [64];
  4924. zeromem (paddingBuffer, paddingLength);
  4925. paddingBuffer [0] = 0x80;
  4926. processBlock (paddingBuffer, paddingLength);
  4927. processBlock (encodedLength, 8);
  4928. MD5Functions::encode (result, state, 16);
  4929. zerostruct (buffer);
  4930. }
  4931. void MD5::ProcessContext::transform (const void* const bufferToTransform)
  4932. {
  4933. using namespace MD5Functions;
  4934. uint32 a = state[0];
  4935. uint32 b = state[1];
  4936. uint32 c = state[2];
  4937. uint32 d = state[3];
  4938. uint32 x[16];
  4939. encode (x, bufferToTransform, 64);
  4940. enum Constants
  4941. {
  4942. S11 = 7, S12 = 12, S13 = 17, S14 = 22, S21 = 5, S22 = 9, S23 = 14, S24 = 20,
  4943. S31 = 4, S32 = 11, S33 = 16, S34 = 23, S41 = 6, S42 = 10, S43 = 15, S44 = 21
  4944. };
  4945. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); FF (d, a, b, c, x[ 1], S12, 0xe8c7b756);
  4946. FF (c, d, a, b, x[ 2], S13, 0x242070db); FF (b, c, d, a, x[ 3], S14, 0xc1bdceee);
  4947. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); FF (d, a, b, c, x[ 5], S12, 0x4787c62a);
  4948. FF (c, d, a, b, x[ 6], S13, 0xa8304613); FF (b, c, d, a, x[ 7], S14, 0xfd469501);
  4949. FF (a, b, c, d, x[ 8], S11, 0x698098d8); FF (d, a, b, c, x[ 9], S12, 0x8b44f7af);
  4950. FF (c, d, a, b, x[10], S13, 0xffff5bb1); FF (b, c, d, a, x[11], S14, 0x895cd7be);
  4951. FF (a, b, c, d, x[12], S11, 0x6b901122); FF (d, a, b, c, x[13], S12, 0xfd987193);
  4952. FF (c, d, a, b, x[14], S13, 0xa679438e); FF (b, c, d, a, x[15], S14, 0x49b40821);
  4953. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); GG (d, a, b, c, x[ 6], S22, 0xc040b340);
  4954. GG (c, d, a, b, x[11], S23, 0x265e5a51); GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa);
  4955. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); GG (d, a, b, c, x[10], S22, 0x02441453);
  4956. GG (c, d, a, b, x[15], S23, 0xd8a1e681); GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8);
  4957. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); GG (d, a, b, c, x[14], S22, 0xc33707d6);
  4958. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); GG (b, c, d, a, x[ 8], S24, 0x455a14ed);
  4959. GG (a, b, c, d, x[13], S21, 0xa9e3e905); GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8);
  4960. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); GG (b, c, d, a, x[12], S24, 0x8d2a4c8a);
  4961. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); HH (d, a, b, c, x[ 8], S32, 0x8771f681);
  4962. HH (c, d, a, b, x[11], S33, 0x6d9d6122); HH (b, c, d, a, x[14], S34, 0xfde5380c);
  4963. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9);
  4964. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); HH (b, c, d, a, x[10], S34, 0xbebfbc70);
  4965. HH (a, b, c, d, x[13], S31, 0x289b7ec6); HH (d, a, b, c, x[ 0], S32, 0xeaa127fa);
  4966. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); HH (b, c, d, a, x[ 6], S34, 0x04881d05);
  4967. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); HH (d, a, b, c, x[12], S32, 0xe6db99e5);
  4968. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); HH (b, c, d, a, x[ 2], S34, 0xc4ac5665);
  4969. II (a, b, c, d, x[ 0], S41, 0xf4292244); II (d, a, b, c, x[ 7], S42, 0x432aff97);
  4970. II (c, d, a, b, x[14], S43, 0xab9423a7); II (b, c, d, a, x[ 5], S44, 0xfc93a039);
  4971. II (a, b, c, d, x[12], S41, 0x655b59c3); II (d, a, b, c, x[ 3], S42, 0x8f0ccc92);
  4972. II (c, d, a, b, x[10], S43, 0xffeff47d); II (b, c, d, a, x[ 1], S44, 0x85845dd1);
  4973. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); II (d, a, b, c, x[15], S42, 0xfe2ce6e0);
  4974. II (c, d, a, b, x[ 6], S43, 0xa3014314); II (b, c, d, a, x[13], S44, 0x4e0811a1);
  4975. II (a, b, c, d, x[ 4], S41, 0xf7537e82); II (d, a, b, c, x[11], S42, 0xbd3af235);
  4976. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); II (b, c, d, a, x[ 9], S44, 0xeb86d391);
  4977. state[0] += a;
  4978. state[1] += b;
  4979. state[2] += c;
  4980. state[3] += d;
  4981. zerostruct (x);
  4982. }
  4983. const MemoryBlock MD5::getRawChecksumData() const
  4984. {
  4985. return MemoryBlock (result, sizeof (result));
  4986. }
  4987. const String MD5::toHexString() const
  4988. {
  4989. return String::toHexString (result, sizeof (result), 0);
  4990. }
  4991. bool MD5::operator== (const MD5& other) const
  4992. {
  4993. return memcmp (result, other.result, sizeof (result)) == 0;
  4994. }
  4995. bool MD5::operator!= (const MD5& other) const
  4996. {
  4997. return ! operator== (other);
  4998. }
  4999. END_JUCE_NAMESPACE
  5000. /*** End of inlined file: juce_MD5.cpp ***/
  5001. /*** Start of inlined file: juce_Primes.cpp ***/
  5002. BEGIN_JUCE_NAMESPACE
  5003. namespace PrimesHelpers
  5004. {
  5005. static void createSmallSieve (const int numBits, BigInteger& result)
  5006. {
  5007. result.setBit (numBits);
  5008. result.clearBit (numBits); // to enlarge the array
  5009. result.setBit (0);
  5010. int n = 2;
  5011. do
  5012. {
  5013. for (int i = n + n; i < numBits; i += n)
  5014. result.setBit (i);
  5015. n = result.findNextClearBit (n + 1);
  5016. }
  5017. while (n <= (numBits >> 1));
  5018. }
  5019. static void bigSieve (const BigInteger& base, const int numBits, BigInteger& result,
  5020. const BigInteger& smallSieve, const int smallSieveSize)
  5021. {
  5022. jassert (! base[0]); // must be even!
  5023. result.setBit (numBits);
  5024. result.clearBit (numBits); // to enlarge the array
  5025. int index = smallSieve.findNextClearBit (0);
  5026. do
  5027. {
  5028. const int prime = (index << 1) + 1;
  5029. BigInteger r (base), remainder;
  5030. r.divideBy (prime, remainder);
  5031. int i = prime - remainder.getBitRangeAsInt (0, 32);
  5032. if (r.isZero())
  5033. i += prime;
  5034. if ((i & 1) == 0)
  5035. i += prime;
  5036. i = (i - 1) >> 1;
  5037. while (i < numBits)
  5038. {
  5039. result.setBit (i);
  5040. i += prime;
  5041. }
  5042. index = smallSieve.findNextClearBit (index + 1);
  5043. }
  5044. while (index < smallSieveSize);
  5045. }
  5046. static bool findCandidate (const BigInteger& base, const BigInteger& sieve,
  5047. const int numBits, BigInteger& result, const int certainty)
  5048. {
  5049. for (int i = 0; i < numBits; ++i)
  5050. {
  5051. if (! sieve[i])
  5052. {
  5053. result = base + (unsigned int) ((i << 1) + 1);
  5054. if (Primes::isProbablyPrime (result, certainty))
  5055. return true;
  5056. }
  5057. }
  5058. return false;
  5059. }
  5060. static bool passesMillerRabin (const BigInteger& n, int iterations)
  5061. {
  5062. const BigInteger one (1), two (2);
  5063. const BigInteger nMinusOne (n - one);
  5064. BigInteger d (nMinusOne);
  5065. const int s = d.findNextSetBit (0);
  5066. d >>= s;
  5067. BigInteger smallPrimes;
  5068. int numBitsInSmallPrimes = 0;
  5069. for (;;)
  5070. {
  5071. numBitsInSmallPrimes += 256;
  5072. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  5073. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  5074. if (numPrimesFound > iterations + 1)
  5075. break;
  5076. }
  5077. int smallPrime = 2;
  5078. while (--iterations >= 0)
  5079. {
  5080. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  5081. BigInteger r (smallPrime);
  5082. r.exponentModulo (d, n);
  5083. if (r != one && r != nMinusOne)
  5084. {
  5085. for (int j = 0; j < s; ++j)
  5086. {
  5087. r.exponentModulo (two, n);
  5088. if (r == nMinusOne)
  5089. break;
  5090. }
  5091. if (r != nMinusOne)
  5092. return false;
  5093. }
  5094. }
  5095. return true;
  5096. }
  5097. }
  5098. const BigInteger Primes::createProbablePrime (const int bitLength,
  5099. const int certainty,
  5100. const int* randomSeeds,
  5101. int numRandomSeeds)
  5102. {
  5103. using namespace PrimesHelpers;
  5104. int defaultSeeds [16];
  5105. if (numRandomSeeds <= 0)
  5106. {
  5107. randomSeeds = defaultSeeds;
  5108. numRandomSeeds = numElementsInArray (defaultSeeds);
  5109. Random r (0);
  5110. for (int j = 10; --j >= 0;)
  5111. {
  5112. r.setSeedRandomly();
  5113. for (int i = numRandomSeeds; --i >= 0;)
  5114. defaultSeeds[i] ^= r.nextInt() ^ Random::getSystemRandom().nextInt();
  5115. }
  5116. }
  5117. BigInteger smallSieve;
  5118. const int smallSieveSize = 15000;
  5119. createSmallSieve (smallSieveSize, smallSieve);
  5120. BigInteger p;
  5121. for (int i = numRandomSeeds; --i >= 0;)
  5122. {
  5123. BigInteger p2;
  5124. Random r (randomSeeds[i]);
  5125. r.fillBitsRandomly (p2, 0, bitLength);
  5126. p ^= p2;
  5127. }
  5128. p.setBit (bitLength - 1);
  5129. p.clearBit (0);
  5130. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  5131. while (p.getHighestBit() < bitLength)
  5132. {
  5133. p += 2 * searchLen;
  5134. BigInteger sieve;
  5135. bigSieve (p, searchLen, sieve,
  5136. smallSieve, smallSieveSize);
  5137. BigInteger candidate;
  5138. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  5139. return candidate;
  5140. }
  5141. jassertfalse;
  5142. return BigInteger();
  5143. }
  5144. bool Primes::isProbablyPrime (const BigInteger& number, const int certainty)
  5145. {
  5146. using namespace PrimesHelpers;
  5147. if (! number[0])
  5148. return false;
  5149. if (number.getHighestBit() <= 10)
  5150. {
  5151. const int num = number.getBitRangeAsInt (0, 10);
  5152. for (int i = num / 2; --i > 1;)
  5153. if (num % i == 0)
  5154. return false;
  5155. return true;
  5156. }
  5157. else
  5158. {
  5159. if (number.findGreatestCommonDivisor (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23) != 1)
  5160. return false;
  5161. return passesMillerRabin (number, certainty);
  5162. }
  5163. }
  5164. END_JUCE_NAMESPACE
  5165. /*** End of inlined file: juce_Primes.cpp ***/
  5166. /*** Start of inlined file: juce_RSAKey.cpp ***/
  5167. BEGIN_JUCE_NAMESPACE
  5168. RSAKey::RSAKey()
  5169. {
  5170. }
  5171. RSAKey::RSAKey (const String& s)
  5172. {
  5173. if (s.containsChar (','))
  5174. {
  5175. part1.parseString (s.upToFirstOccurrenceOf (",", false, false), 16);
  5176. part2.parseString (s.fromFirstOccurrenceOf (",", false, false), 16);
  5177. }
  5178. else
  5179. {
  5180. // the string needs to be two hex numbers, comma-separated..
  5181. jassertfalse;
  5182. }
  5183. }
  5184. RSAKey::~RSAKey()
  5185. {
  5186. }
  5187. bool RSAKey::operator== (const RSAKey& other) const throw()
  5188. {
  5189. return part1 == other.part1 && part2 == other.part2;
  5190. }
  5191. bool RSAKey::operator!= (const RSAKey& other) const throw()
  5192. {
  5193. return ! operator== (other);
  5194. }
  5195. const String RSAKey::toString() const
  5196. {
  5197. return part1.toString (16) + "," + part2.toString (16);
  5198. }
  5199. bool RSAKey::applyToValue (BigInteger& value) const
  5200. {
  5201. if (part1.isZero() || part2.isZero() || value <= 0)
  5202. {
  5203. jassertfalse; // using an uninitialised key
  5204. value.clear();
  5205. return false;
  5206. }
  5207. BigInteger result;
  5208. while (! value.isZero())
  5209. {
  5210. result *= part2;
  5211. BigInteger remainder;
  5212. value.divideBy (part2, remainder);
  5213. remainder.exponentModulo (part1, part2);
  5214. result += remainder;
  5215. }
  5216. value.swapWith (result);
  5217. return true;
  5218. }
  5219. const BigInteger RSAKey::findBestCommonDivisor (const BigInteger& p, const BigInteger& q)
  5220. {
  5221. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  5222. // are fast to divide + multiply
  5223. for (int i = 2; i <= 65536; i *= 2)
  5224. {
  5225. const BigInteger e (1 + i);
  5226. if (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne())
  5227. return e;
  5228. }
  5229. BigInteger e (4);
  5230. while (! (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne()))
  5231. ++e;
  5232. return e;
  5233. }
  5234. void RSAKey::createKeyPair (RSAKey& publicKey, RSAKey& privateKey,
  5235. const int numBits, const int* randomSeeds, const int numRandomSeeds)
  5236. {
  5237. jassert (numBits > 16); // not much point using less than this..
  5238. jassert (numRandomSeeds == 0 || numRandomSeeds >= 2); // you need to provide plenty of seeds here!
  5239. BigInteger p (Primes::createProbablePrime (numBits / 2, 30, randomSeeds, numRandomSeeds / 2));
  5240. BigInteger q (Primes::createProbablePrime (numBits - numBits / 2, 30, randomSeeds == 0 ? 0 : (randomSeeds + numRandomSeeds / 2), numRandomSeeds - numRandomSeeds / 2));
  5241. const BigInteger n (p * q);
  5242. const BigInteger m (--p * --q);
  5243. const BigInteger e (findBestCommonDivisor (p, q));
  5244. BigInteger d (e);
  5245. d.inverseModulo (m);
  5246. publicKey.part1 = e;
  5247. publicKey.part2 = n;
  5248. privateKey.part1 = d;
  5249. privateKey.part2 = n;
  5250. }
  5251. END_JUCE_NAMESPACE
  5252. /*** End of inlined file: juce_RSAKey.cpp ***/
  5253. /*** Start of inlined file: juce_InputStream.cpp ***/
  5254. BEGIN_JUCE_NAMESPACE
  5255. char InputStream::readByte()
  5256. {
  5257. char temp = 0;
  5258. read (&temp, 1);
  5259. return temp;
  5260. }
  5261. bool InputStream::readBool()
  5262. {
  5263. return readByte() != 0;
  5264. }
  5265. short InputStream::readShort()
  5266. {
  5267. char temp[2];
  5268. if (read (temp, 2) == 2)
  5269. return (short) ByteOrder::littleEndianShort (temp);
  5270. return 0;
  5271. }
  5272. short InputStream::readShortBigEndian()
  5273. {
  5274. char temp[2];
  5275. if (read (temp, 2) == 2)
  5276. return (short) ByteOrder::bigEndianShort (temp);
  5277. return 0;
  5278. }
  5279. int InputStream::readInt()
  5280. {
  5281. char temp[4];
  5282. if (read (temp, 4) == 4)
  5283. return (int) ByteOrder::littleEndianInt (temp);
  5284. return 0;
  5285. }
  5286. int InputStream::readIntBigEndian()
  5287. {
  5288. char temp[4];
  5289. if (read (temp, 4) == 4)
  5290. return (int) ByteOrder::bigEndianInt (temp);
  5291. return 0;
  5292. }
  5293. int InputStream::readCompressedInt()
  5294. {
  5295. const unsigned char sizeByte = readByte();
  5296. if (sizeByte == 0)
  5297. return 0;
  5298. const int numBytes = (sizeByte & 0x7f);
  5299. if (numBytes > 4)
  5300. {
  5301. jassertfalse; // trying to read corrupt data - this method must only be used
  5302. // to read data that was written by OutputStream::writeCompressedInt()
  5303. return 0;
  5304. }
  5305. char bytes[4] = { 0, 0, 0, 0 };
  5306. if (read (bytes, numBytes) != numBytes)
  5307. return 0;
  5308. const int num = (int) ByteOrder::littleEndianInt (bytes);
  5309. return (sizeByte >> 7) ? -num : num;
  5310. }
  5311. int64 InputStream::readInt64()
  5312. {
  5313. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5314. if (read (n.asBytes, 8) == 8)
  5315. return (int64) ByteOrder::swapIfBigEndian (n.asInt64);
  5316. return 0;
  5317. }
  5318. int64 InputStream::readInt64BigEndian()
  5319. {
  5320. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5321. if (read (n.asBytes, 8) == 8)
  5322. return (int64) ByteOrder::swapIfLittleEndian (n.asInt64);
  5323. return 0;
  5324. }
  5325. float InputStream::readFloat()
  5326. {
  5327. // the union below relies on these types being the same size...
  5328. static_jassert (sizeof (int32) == sizeof (float));
  5329. union { int32 asInt; float asFloat; } n;
  5330. n.asInt = (int32) readInt();
  5331. return n.asFloat;
  5332. }
  5333. float InputStream::readFloatBigEndian()
  5334. {
  5335. union { int32 asInt; float asFloat; } n;
  5336. n.asInt = (int32) readIntBigEndian();
  5337. return n.asFloat;
  5338. }
  5339. double InputStream::readDouble()
  5340. {
  5341. union { int64 asInt; double asDouble; } n;
  5342. n.asInt = readInt64();
  5343. return n.asDouble;
  5344. }
  5345. double InputStream::readDoubleBigEndian()
  5346. {
  5347. union { int64 asInt; double asDouble; } n;
  5348. n.asInt = readInt64BigEndian();
  5349. return n.asDouble;
  5350. }
  5351. const String InputStream::readString()
  5352. {
  5353. MemoryBlock buffer (256);
  5354. char* data = static_cast<char*> (buffer.getData());
  5355. size_t i = 0;
  5356. while ((data[i] = readByte()) != 0)
  5357. {
  5358. if (++i >= buffer.getSize())
  5359. {
  5360. buffer.setSize (buffer.getSize() + 512);
  5361. data = static_cast<char*> (buffer.getData());
  5362. }
  5363. }
  5364. return String::fromUTF8 (data, (int) i);
  5365. }
  5366. const String InputStream::readNextLine()
  5367. {
  5368. MemoryBlock buffer (256);
  5369. char* data = static_cast<char*> (buffer.getData());
  5370. size_t i = 0;
  5371. while ((data[i] = readByte()) != 0)
  5372. {
  5373. if (data[i] == '\n')
  5374. break;
  5375. if (data[i] == '\r')
  5376. {
  5377. const int64 lastPos = getPosition();
  5378. if (readByte() != '\n')
  5379. setPosition (lastPos);
  5380. break;
  5381. }
  5382. if (++i >= buffer.getSize())
  5383. {
  5384. buffer.setSize (buffer.getSize() + 512);
  5385. data = static_cast<char*> (buffer.getData());
  5386. }
  5387. }
  5388. return String::fromUTF8 (data, (int) i);
  5389. }
  5390. int InputStream::readIntoMemoryBlock (MemoryBlock& block, int numBytes)
  5391. {
  5392. MemoryOutputStream mo (block, true);
  5393. return mo.writeFromInputStream (*this, numBytes);
  5394. }
  5395. const String InputStream::readEntireStreamAsString()
  5396. {
  5397. MemoryOutputStream mo;
  5398. mo.writeFromInputStream (*this, -1);
  5399. return mo.toString();
  5400. }
  5401. void InputStream::skipNextBytes (int64 numBytesToSkip)
  5402. {
  5403. if (numBytesToSkip > 0)
  5404. {
  5405. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  5406. HeapBlock<char> temp (skipBufferSize);
  5407. while (numBytesToSkip > 0 && ! isExhausted())
  5408. numBytesToSkip -= read (temp, (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  5409. }
  5410. }
  5411. END_JUCE_NAMESPACE
  5412. /*** End of inlined file: juce_InputStream.cpp ***/
  5413. /*** Start of inlined file: juce_OutputStream.cpp ***/
  5414. BEGIN_JUCE_NAMESPACE
  5415. #if JUCE_DEBUG
  5416. static Array<void*, CriticalSection> activeStreams;
  5417. void juce_CheckForDanglingStreams()
  5418. {
  5419. /*
  5420. It's always a bad idea to leak any object, but if you're leaking output
  5421. streams, then there's a good chance that you're failing to flush a file
  5422. to disk properly, which could result in corrupted data and other similar
  5423. nastiness..
  5424. */
  5425. jassert (activeStreams.size() == 0);
  5426. };
  5427. #endif
  5428. OutputStream::OutputStream()
  5429. {
  5430. #if JUCE_DEBUG
  5431. activeStreams.add (this);
  5432. #endif
  5433. }
  5434. OutputStream::~OutputStream()
  5435. {
  5436. #if JUCE_DEBUG
  5437. activeStreams.removeValue (this);
  5438. #endif
  5439. }
  5440. void OutputStream::writeBool (const bool b)
  5441. {
  5442. writeByte (b ? (char) 1
  5443. : (char) 0);
  5444. }
  5445. void OutputStream::writeByte (char byte)
  5446. {
  5447. write (&byte, 1);
  5448. }
  5449. void OutputStream::writeShort (short value)
  5450. {
  5451. const unsigned short v = ByteOrder::swapIfBigEndian ((unsigned short) value);
  5452. write (&v, 2);
  5453. }
  5454. void OutputStream::writeShortBigEndian (short value)
  5455. {
  5456. const unsigned short v = ByteOrder::swapIfLittleEndian ((unsigned short) value);
  5457. write (&v, 2);
  5458. }
  5459. void OutputStream::writeInt (int value)
  5460. {
  5461. const unsigned int v = ByteOrder::swapIfBigEndian ((unsigned int) value);
  5462. write (&v, 4);
  5463. }
  5464. void OutputStream::writeIntBigEndian (int value)
  5465. {
  5466. const unsigned int v = ByteOrder::swapIfLittleEndian ((unsigned int) value);
  5467. write (&v, 4);
  5468. }
  5469. void OutputStream::writeCompressedInt (int value)
  5470. {
  5471. unsigned int un = (value < 0) ? (unsigned int) -value
  5472. : (unsigned int) value;
  5473. uint8 data[5];
  5474. int num = 0;
  5475. while (un > 0)
  5476. {
  5477. data[++num] = (uint8) un;
  5478. un >>= 8;
  5479. }
  5480. data[0] = (uint8) num;
  5481. if (value < 0)
  5482. data[0] |= 0x80;
  5483. write (data, num + 1);
  5484. }
  5485. void OutputStream::writeInt64 (int64 value)
  5486. {
  5487. const uint64 v = ByteOrder::swapIfBigEndian ((uint64) value);
  5488. write (&v, 8);
  5489. }
  5490. void OutputStream::writeInt64BigEndian (int64 value)
  5491. {
  5492. const uint64 v = ByteOrder::swapIfLittleEndian ((uint64) value);
  5493. write (&v, 8);
  5494. }
  5495. void OutputStream::writeFloat (float value)
  5496. {
  5497. union { int asInt; float asFloat; } n;
  5498. n.asFloat = value;
  5499. writeInt (n.asInt);
  5500. }
  5501. void OutputStream::writeFloatBigEndian (float value)
  5502. {
  5503. union { int asInt; float asFloat; } n;
  5504. n.asFloat = value;
  5505. writeIntBigEndian (n.asInt);
  5506. }
  5507. void OutputStream::writeDouble (double value)
  5508. {
  5509. union { int64 asInt; double asDouble; } n;
  5510. n.asDouble = value;
  5511. writeInt64 (n.asInt);
  5512. }
  5513. void OutputStream::writeDoubleBigEndian (double value)
  5514. {
  5515. union { int64 asInt; double asDouble; } n;
  5516. n.asDouble = value;
  5517. writeInt64BigEndian (n.asInt);
  5518. }
  5519. void OutputStream::writeString (const String& text)
  5520. {
  5521. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  5522. // if lots of large, persistent strings were to be written to streams).
  5523. const int numBytes = text.getNumBytesAsUTF8() + 1;
  5524. HeapBlock<char> temp (numBytes);
  5525. text.copyToUTF8 (temp, numBytes);
  5526. write (temp, numBytes);
  5527. }
  5528. void OutputStream::writeText (const String& text, const bool asUnicode,
  5529. const bool writeUnicodeHeaderBytes)
  5530. {
  5531. if (asUnicode)
  5532. {
  5533. if (writeUnicodeHeaderBytes)
  5534. write ("\x0ff\x0fe", 2);
  5535. const juce_wchar* src = text;
  5536. bool lastCharWasReturn = false;
  5537. while (*src != 0)
  5538. {
  5539. if (*src == L'\n' && ! lastCharWasReturn)
  5540. writeShort ((short) L'\r');
  5541. lastCharWasReturn = (*src == L'\r');
  5542. writeShort ((short) *src++);
  5543. }
  5544. }
  5545. else
  5546. {
  5547. const char* src = text.toUTF8();
  5548. const char* t = src;
  5549. for (;;)
  5550. {
  5551. if (*t == '\n')
  5552. {
  5553. if (t > src)
  5554. write (src, (int) (t - src));
  5555. write ("\r\n", 2);
  5556. src = t + 1;
  5557. }
  5558. else if (*t == '\r')
  5559. {
  5560. if (t[1] == '\n')
  5561. ++t;
  5562. }
  5563. else if (*t == 0)
  5564. {
  5565. if (t > src)
  5566. write (src, (int) (t - src));
  5567. break;
  5568. }
  5569. ++t;
  5570. }
  5571. }
  5572. }
  5573. int OutputStream::writeFromInputStream (InputStream& source, int64 numBytesToWrite)
  5574. {
  5575. if (numBytesToWrite < 0)
  5576. numBytesToWrite = std::numeric_limits<int64>::max();
  5577. int numWritten = 0;
  5578. while (numBytesToWrite > 0 && ! source.isExhausted())
  5579. {
  5580. char buffer [8192];
  5581. const int num = source.read (buffer, (int) jmin (numBytesToWrite, (int64) sizeof (buffer)));
  5582. if (num <= 0)
  5583. break;
  5584. write (buffer, num);
  5585. numBytesToWrite -= num;
  5586. numWritten += num;
  5587. }
  5588. return numWritten;
  5589. }
  5590. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const int number)
  5591. {
  5592. return stream << String (number);
  5593. }
  5594. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const double number)
  5595. {
  5596. return stream << String (number);
  5597. }
  5598. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char character)
  5599. {
  5600. stream.writeByte (character);
  5601. return stream;
  5602. }
  5603. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* const text)
  5604. {
  5605. stream.write (text, (int) strlen (text));
  5606. return stream;
  5607. }
  5608. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data)
  5609. {
  5610. stream.write (data.getData(), (int) data.getSize());
  5611. return stream;
  5612. }
  5613. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead)
  5614. {
  5615. const ScopedPointer<FileInputStream> in (fileToRead.createInputStream());
  5616. if (in != 0)
  5617. stream.writeFromInputStream (*in, -1);
  5618. return stream;
  5619. }
  5620. END_JUCE_NAMESPACE
  5621. /*** End of inlined file: juce_OutputStream.cpp ***/
  5622. /*** Start of inlined file: juce_DirectoryIterator.cpp ***/
  5623. BEGIN_JUCE_NAMESPACE
  5624. DirectoryIterator::DirectoryIterator (const File& directory,
  5625. bool isRecursive_,
  5626. const String& wildCard_,
  5627. const int whatToLookFor_)
  5628. : fileFinder (directory, isRecursive_ ? "*" : wildCard_),
  5629. wildCard (wildCard_),
  5630. path (File::addTrailingSeparator (directory.getFullPathName())),
  5631. index (-1),
  5632. totalNumFiles (-1),
  5633. whatToLookFor (whatToLookFor_),
  5634. isRecursive (isRecursive_),
  5635. hasBeenAdvanced (false)
  5636. {
  5637. // you have to specify the type of files you're looking for!
  5638. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  5639. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  5640. }
  5641. DirectoryIterator::~DirectoryIterator()
  5642. {
  5643. }
  5644. bool DirectoryIterator::next()
  5645. {
  5646. return next (0, 0, 0, 0, 0, 0);
  5647. }
  5648. bool DirectoryIterator::next (bool* const isDirResult, bool* const isHiddenResult, int64* const fileSize,
  5649. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  5650. {
  5651. hasBeenAdvanced = true;
  5652. if (subIterator != 0)
  5653. {
  5654. if (subIterator->next (isDirResult, isHiddenResult, fileSize, modTime, creationTime, isReadOnly))
  5655. return true;
  5656. subIterator = 0;
  5657. }
  5658. String filename;
  5659. bool isDirectory, isHidden;
  5660. while (fileFinder.next (filename, &isDirectory, &isHidden, fileSize, modTime, creationTime, isReadOnly))
  5661. {
  5662. ++index;
  5663. if (! filename.containsOnly ("."))
  5664. {
  5665. const File fileFound (path + filename, 0);
  5666. bool matches = false;
  5667. if (isDirectory)
  5668. {
  5669. if (isRecursive && ((whatToLookFor & File::ignoreHiddenFiles) == 0 || ! isHidden))
  5670. subIterator = new DirectoryIterator (fileFound, true, wildCard, whatToLookFor);
  5671. matches = (whatToLookFor & File::findDirectories) != 0;
  5672. }
  5673. else
  5674. {
  5675. matches = (whatToLookFor & File::findFiles) != 0;
  5676. }
  5677. // if recursive, we're not relying on the OS iterator to do the wildcard match, so do it now..
  5678. if (matches && isRecursive)
  5679. matches = filename.matchesWildcard (wildCard, ! File::areFileNamesCaseSensitive());
  5680. if (matches && (whatToLookFor & File::ignoreHiddenFiles) != 0)
  5681. matches = ! isHidden;
  5682. if (matches)
  5683. {
  5684. currentFile = fileFound;
  5685. if (isHiddenResult != 0) *isHiddenResult = isHidden;
  5686. if (isDirResult != 0) *isDirResult = isDirectory;
  5687. return true;
  5688. }
  5689. else if (subIterator != 0)
  5690. {
  5691. return next();
  5692. }
  5693. }
  5694. }
  5695. return false;
  5696. }
  5697. const File DirectoryIterator::getFile() const
  5698. {
  5699. if (subIterator != 0 && subIterator->hasBeenAdvanced)
  5700. return subIterator->getFile();
  5701. // You need to call DirectoryIterator::next() before asking it for the file that it found!
  5702. jassert (hasBeenAdvanced);
  5703. return currentFile;
  5704. }
  5705. float DirectoryIterator::getEstimatedProgress() const
  5706. {
  5707. if (totalNumFiles < 0)
  5708. totalNumFiles = File (path).getNumberOfChildFiles (File::findFilesAndDirectories);
  5709. if (totalNumFiles <= 0)
  5710. return 0.0f;
  5711. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  5712. : (float) index;
  5713. return detailedIndex / totalNumFiles;
  5714. }
  5715. END_JUCE_NAMESPACE
  5716. /*** End of inlined file: juce_DirectoryIterator.cpp ***/
  5717. /*** Start of inlined file: juce_File.cpp ***/
  5718. #if ! JUCE_WINDOWS
  5719. #include <pwd.h>
  5720. #endif
  5721. BEGIN_JUCE_NAMESPACE
  5722. File::File (const String& fullPathName)
  5723. : fullPath (parseAbsolutePath (fullPathName))
  5724. {
  5725. }
  5726. File::File (const String& path, int)
  5727. : fullPath (path)
  5728. {
  5729. }
  5730. const File File::createFileWithoutCheckingPath (const String& path)
  5731. {
  5732. return File (path, 0);
  5733. }
  5734. File::File (const File& other)
  5735. : fullPath (other.fullPath)
  5736. {
  5737. }
  5738. File& File::operator= (const String& newPath)
  5739. {
  5740. fullPath = parseAbsolutePath (newPath);
  5741. return *this;
  5742. }
  5743. File& File::operator= (const File& other)
  5744. {
  5745. fullPath = other.fullPath;
  5746. return *this;
  5747. }
  5748. const File File::nonexistent;
  5749. const String File::parseAbsolutePath (const String& p)
  5750. {
  5751. if (p.isEmpty())
  5752. return String::empty;
  5753. #if JUCE_WINDOWS
  5754. // Windows..
  5755. String path (p.replaceCharacter ('/', '\\'));
  5756. if (path.startsWithChar (File::separator))
  5757. {
  5758. if (path[1] != File::separator)
  5759. {
  5760. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5761. If you're trying to parse a string that may be either a relative path or an absolute path,
  5762. you MUST provide a context against which the partial path can be evaluated - you can do
  5763. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5764. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5765. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5766. */
  5767. jassertfalse;
  5768. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  5769. }
  5770. }
  5771. else if (! path.containsChar (':'))
  5772. {
  5773. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5774. If you're trying to parse a string that may be either a relative path or an absolute path,
  5775. you MUST provide a context against which the partial path can be evaluated - you can do
  5776. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5777. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5778. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5779. */
  5780. jassertfalse;
  5781. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  5782. }
  5783. #else
  5784. // Mac or Linux..
  5785. String path (p.replaceCharacter ('\\', '/'));
  5786. if (path.startsWithChar ('~'))
  5787. {
  5788. if (path[1] == File::separator || path[1] == 0)
  5789. {
  5790. // expand a name of the form "~/abc"
  5791. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  5792. + path.substring (1);
  5793. }
  5794. else
  5795. {
  5796. // expand a name of type "~dave/abc"
  5797. const String userName (path.substring (1).upToFirstOccurrenceOf ("/", false, false));
  5798. struct passwd* const pw = getpwnam (userName.toUTF8());
  5799. if (pw != 0)
  5800. path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
  5801. }
  5802. }
  5803. else if (! path.startsWithChar (File::separator))
  5804. {
  5805. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5806. If you're trying to parse a string that may be either a relative path or an absolute path,
  5807. you MUST provide a context against which the partial path can be evaluated - you can do
  5808. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5809. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5810. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5811. */
  5812. jassert (path.startsWith ("./") || path.startsWith ("../")); // (assume that a path "./xyz" is deliberately intended to be relative to the CWD)
  5813. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  5814. }
  5815. #endif
  5816. while (path.endsWithChar (separator) && path != separatorString) // careful not to turn a single "/" into an empty string.
  5817. path = path.dropLastCharacters (1);
  5818. return path;
  5819. }
  5820. const String File::addTrailingSeparator (const String& path)
  5821. {
  5822. return path.endsWithChar (File::separator) ? path
  5823. : path + File::separator;
  5824. }
  5825. #if JUCE_LINUX
  5826. #define NAMES_ARE_CASE_SENSITIVE 1
  5827. #endif
  5828. bool File::areFileNamesCaseSensitive()
  5829. {
  5830. #if NAMES_ARE_CASE_SENSITIVE
  5831. return true;
  5832. #else
  5833. return false;
  5834. #endif
  5835. }
  5836. bool File::operator== (const File& other) const
  5837. {
  5838. #if NAMES_ARE_CASE_SENSITIVE
  5839. return fullPath == other.fullPath;
  5840. #else
  5841. return fullPath.equalsIgnoreCase (other.fullPath);
  5842. #endif
  5843. }
  5844. bool File::operator!= (const File& other) const
  5845. {
  5846. return ! operator== (other);
  5847. }
  5848. bool File::operator< (const File& other) const
  5849. {
  5850. #if NAMES_ARE_CASE_SENSITIVE
  5851. return fullPath < other.fullPath;
  5852. #else
  5853. return fullPath.compareIgnoreCase (other.fullPath) < 0;
  5854. #endif
  5855. }
  5856. bool File::operator> (const File& other) const
  5857. {
  5858. #if NAMES_ARE_CASE_SENSITIVE
  5859. return fullPath > other.fullPath;
  5860. #else
  5861. return fullPath.compareIgnoreCase (other.fullPath) > 0;
  5862. #endif
  5863. }
  5864. bool File::setReadOnly (const bool shouldBeReadOnly,
  5865. const bool applyRecursively) const
  5866. {
  5867. bool worked = true;
  5868. if (applyRecursively && isDirectory())
  5869. {
  5870. Array <File> subFiles;
  5871. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  5872. for (int i = subFiles.size(); --i >= 0;)
  5873. worked = subFiles.getReference(i).setReadOnly (shouldBeReadOnly, true) && worked;
  5874. }
  5875. return setFileReadOnlyInternal (shouldBeReadOnly) && worked;
  5876. }
  5877. bool File::deleteRecursively() const
  5878. {
  5879. bool worked = true;
  5880. if (isDirectory())
  5881. {
  5882. Array<File> subFiles;
  5883. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  5884. for (int i = subFiles.size(); --i >= 0;)
  5885. worked = subFiles.getReference(i).deleteRecursively() && worked;
  5886. }
  5887. return deleteFile() && worked;
  5888. }
  5889. bool File::moveFileTo (const File& newFile) const
  5890. {
  5891. if (newFile.fullPath == fullPath)
  5892. return true;
  5893. #if ! NAMES_ARE_CASE_SENSITIVE
  5894. if (*this != newFile)
  5895. #endif
  5896. if (! newFile.deleteFile())
  5897. return false;
  5898. return moveInternal (newFile);
  5899. }
  5900. bool File::copyFileTo (const File& newFile) const
  5901. {
  5902. return (*this == newFile)
  5903. || (exists() && newFile.deleteFile() && copyInternal (newFile));
  5904. }
  5905. bool File::copyDirectoryTo (const File& newDirectory) const
  5906. {
  5907. if (isDirectory() && newDirectory.createDirectory())
  5908. {
  5909. Array<File> subFiles;
  5910. findChildFiles (subFiles, File::findFiles, false);
  5911. int i;
  5912. for (i = 0; i < subFiles.size(); ++i)
  5913. if (! subFiles.getReference(i).copyFileTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5914. return false;
  5915. subFiles.clear();
  5916. findChildFiles (subFiles, File::findDirectories, false);
  5917. for (i = 0; i < subFiles.size(); ++i)
  5918. if (! subFiles.getReference(i).copyDirectoryTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5919. return false;
  5920. return true;
  5921. }
  5922. return false;
  5923. }
  5924. const String File::getPathUpToLastSlash() const
  5925. {
  5926. const int lastSlash = fullPath.lastIndexOfChar (separator);
  5927. if (lastSlash > 0)
  5928. return fullPath.substring (0, lastSlash);
  5929. else if (lastSlash == 0)
  5930. return separatorString;
  5931. else
  5932. return fullPath;
  5933. }
  5934. const File File::getParentDirectory() const
  5935. {
  5936. return File (getPathUpToLastSlash(), (int) 0);
  5937. }
  5938. const String File::getFileName() const
  5939. {
  5940. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  5941. }
  5942. int File::hashCode() const
  5943. {
  5944. return fullPath.hashCode();
  5945. }
  5946. int64 File::hashCode64() const
  5947. {
  5948. return fullPath.hashCode64();
  5949. }
  5950. const String File::getFileNameWithoutExtension() const
  5951. {
  5952. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  5953. const int lastDot = fullPath.lastIndexOfChar ('.');
  5954. if (lastDot > lastSlash)
  5955. return fullPath.substring (lastSlash, lastDot);
  5956. else
  5957. return fullPath.substring (lastSlash);
  5958. }
  5959. bool File::isAChildOf (const File& potentialParent) const
  5960. {
  5961. if (potentialParent == File::nonexistent)
  5962. return false;
  5963. const String ourPath (getPathUpToLastSlash());
  5964. #if NAMES_ARE_CASE_SENSITIVE
  5965. if (potentialParent.fullPath == ourPath)
  5966. #else
  5967. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  5968. #endif
  5969. {
  5970. return true;
  5971. }
  5972. else if (potentialParent.fullPath.length() >= ourPath.length())
  5973. {
  5974. return false;
  5975. }
  5976. else
  5977. {
  5978. return getParentDirectory().isAChildOf (potentialParent);
  5979. }
  5980. }
  5981. bool File::isAbsolutePath (const String& path)
  5982. {
  5983. return path.startsWithChar ('/') || path.startsWithChar ('\\')
  5984. #if JUCE_WINDOWS
  5985. || (path.isNotEmpty() && path[1] == ':');
  5986. #else
  5987. || path.startsWithChar ('~');
  5988. #endif
  5989. }
  5990. const File File::getChildFile (String relativePath) const
  5991. {
  5992. if (isAbsolutePath (relativePath))
  5993. {
  5994. // the path is really absolute..
  5995. return File (relativePath);
  5996. }
  5997. else
  5998. {
  5999. // it's relative, so remove any ../ or ./ bits at the start.
  6000. String path (fullPath);
  6001. if (relativePath[0] == '.')
  6002. {
  6003. #if JUCE_WINDOWS
  6004. relativePath = relativePath.replaceCharacter ('/', '\\').trimStart();
  6005. #else
  6006. relativePath = relativePath.replaceCharacter ('\\', '/').trimStart();
  6007. #endif
  6008. while (relativePath[0] == '.')
  6009. {
  6010. if (relativePath[1] == '.')
  6011. {
  6012. if (relativePath [2] == 0 || relativePath[2] == separator)
  6013. {
  6014. const int lastSlash = path.lastIndexOfChar (separator);
  6015. if (lastSlash >= 0)
  6016. path = path.substring (0, lastSlash);
  6017. relativePath = relativePath.substring (3);
  6018. }
  6019. else
  6020. {
  6021. break;
  6022. }
  6023. }
  6024. else if (relativePath[1] == separator)
  6025. {
  6026. relativePath = relativePath.substring (2);
  6027. }
  6028. else
  6029. {
  6030. break;
  6031. }
  6032. }
  6033. }
  6034. return File (addTrailingSeparator (path) + relativePath);
  6035. }
  6036. }
  6037. const File File::getSiblingFile (const String& fileName) const
  6038. {
  6039. return getParentDirectory().getChildFile (fileName);
  6040. }
  6041. const String File::descriptionOfSizeInBytes (const int64 bytes)
  6042. {
  6043. if (bytes == 1)
  6044. {
  6045. return "1 byte";
  6046. }
  6047. else if (bytes < 1024)
  6048. {
  6049. return String ((int) bytes) + " bytes";
  6050. }
  6051. else if (bytes < 1024 * 1024)
  6052. {
  6053. return String (bytes / 1024.0, 1) + " KB";
  6054. }
  6055. else if (bytes < 1024 * 1024 * 1024)
  6056. {
  6057. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  6058. }
  6059. else
  6060. {
  6061. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  6062. }
  6063. }
  6064. bool File::create() const
  6065. {
  6066. if (exists())
  6067. return true;
  6068. {
  6069. const File parentDir (getParentDirectory());
  6070. if (parentDir == *this || ! parentDir.createDirectory())
  6071. return false;
  6072. FileOutputStream fo (*this, 8);
  6073. }
  6074. return exists();
  6075. }
  6076. bool File::createDirectory() const
  6077. {
  6078. if (! isDirectory())
  6079. {
  6080. const File parentDir (getParentDirectory());
  6081. if (parentDir == *this || ! parentDir.createDirectory())
  6082. return false;
  6083. createDirectoryInternal (fullPath.trimCharactersAtEnd (separatorString));
  6084. return isDirectory();
  6085. }
  6086. return true;
  6087. }
  6088. const Time File::getCreationTime() const
  6089. {
  6090. int64 m, a, c;
  6091. getFileTimesInternal (m, a, c);
  6092. return Time (c);
  6093. }
  6094. const Time File::getLastModificationTime() const
  6095. {
  6096. int64 m, a, c;
  6097. getFileTimesInternal (m, a, c);
  6098. return Time (m);
  6099. }
  6100. const Time File::getLastAccessTime() const
  6101. {
  6102. int64 m, a, c;
  6103. getFileTimesInternal (m, a, c);
  6104. return Time (a);
  6105. }
  6106. bool File::setLastModificationTime (const Time& t) const { return setFileTimesInternal (t.toMilliseconds(), 0, 0); }
  6107. bool File::setLastAccessTime (const Time& t) const { return setFileTimesInternal (0, t.toMilliseconds(), 0); }
  6108. bool File::setCreationTime (const Time& t) const { return setFileTimesInternal (0, 0, t.toMilliseconds()); }
  6109. bool File::loadFileAsData (MemoryBlock& destBlock) const
  6110. {
  6111. if (! existsAsFile())
  6112. return false;
  6113. FileInputStream in (*this);
  6114. return getSize() == in.readIntoMemoryBlock (destBlock);
  6115. }
  6116. const String File::loadFileAsString() const
  6117. {
  6118. if (! existsAsFile())
  6119. return String::empty;
  6120. FileInputStream in (*this);
  6121. return in.readEntireStreamAsString();
  6122. }
  6123. int File::findChildFiles (Array<File>& results,
  6124. const int whatToLookFor,
  6125. const bool searchRecursively,
  6126. const String& wildCardPattern) const
  6127. {
  6128. DirectoryIterator di (*this, searchRecursively, wildCardPattern, whatToLookFor);
  6129. int total = 0;
  6130. while (di.next())
  6131. {
  6132. results.add (di.getFile());
  6133. ++total;
  6134. }
  6135. return total;
  6136. }
  6137. int File::getNumberOfChildFiles (const int whatToLookFor, const String& wildCardPattern) const
  6138. {
  6139. DirectoryIterator di (*this, false, wildCardPattern, whatToLookFor);
  6140. int total = 0;
  6141. while (di.next())
  6142. ++total;
  6143. return total;
  6144. }
  6145. bool File::containsSubDirectories() const
  6146. {
  6147. if (isDirectory())
  6148. {
  6149. DirectoryIterator di (*this, false, "*", findDirectories);
  6150. return di.next();
  6151. }
  6152. return false;
  6153. }
  6154. const File File::getNonexistentChildFile (const String& prefix_,
  6155. const String& suffix,
  6156. bool putNumbersInBrackets) const
  6157. {
  6158. File f (getChildFile (prefix_ + suffix));
  6159. if (f.exists())
  6160. {
  6161. int num = 2;
  6162. String prefix (prefix_);
  6163. // remove any bracketed numbers that may already be on the end..
  6164. if (prefix.trim().endsWithChar (')'))
  6165. {
  6166. putNumbersInBrackets = true;
  6167. const int openBracks = prefix.lastIndexOfChar ('(');
  6168. const int closeBracks = prefix.lastIndexOfChar (')');
  6169. if (openBracks > 0
  6170. && closeBracks > openBracks
  6171. && prefix.substring (openBracks + 1, closeBracks).containsOnly ("0123456789"))
  6172. {
  6173. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  6174. prefix = prefix.substring (0, openBracks);
  6175. }
  6176. }
  6177. // also use brackets if it ends in a digit.
  6178. putNumbersInBrackets = putNumbersInBrackets
  6179. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  6180. do
  6181. {
  6182. if (putNumbersInBrackets)
  6183. f = getChildFile (prefix + '(' + String (num++) + ')' + suffix);
  6184. else
  6185. f = getChildFile (prefix + String (num++) + suffix);
  6186. } while (f.exists());
  6187. }
  6188. return f;
  6189. }
  6190. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const
  6191. {
  6192. if (exists())
  6193. {
  6194. return getParentDirectory()
  6195. .getNonexistentChildFile (getFileNameWithoutExtension(),
  6196. getFileExtension(),
  6197. putNumbersInBrackets);
  6198. }
  6199. else
  6200. {
  6201. return *this;
  6202. }
  6203. }
  6204. const String File::getFileExtension() const
  6205. {
  6206. String ext;
  6207. if (! isDirectory())
  6208. {
  6209. const int indexOfDot = fullPath.lastIndexOfChar ('.');
  6210. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  6211. ext = fullPath.substring (indexOfDot);
  6212. }
  6213. return ext;
  6214. }
  6215. bool File::hasFileExtension (const String& possibleSuffix) const
  6216. {
  6217. if (possibleSuffix.isEmpty())
  6218. return fullPath.lastIndexOfChar ('.') <= fullPath.lastIndexOfChar (separator);
  6219. const int semicolon = possibleSuffix.indexOfChar (0, ';');
  6220. if (semicolon >= 0)
  6221. {
  6222. return hasFileExtension (possibleSuffix.substring (0, semicolon).trimEnd())
  6223. || hasFileExtension (possibleSuffix.substring (semicolon + 1).trimStart());
  6224. }
  6225. else
  6226. {
  6227. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  6228. {
  6229. if (possibleSuffix.startsWithChar ('.'))
  6230. return true;
  6231. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  6232. if (dotPos >= 0)
  6233. return fullPath [dotPos] == '.';
  6234. }
  6235. }
  6236. return false;
  6237. }
  6238. const File File::withFileExtension (const String& newExtension) const
  6239. {
  6240. if (fullPath.isEmpty())
  6241. return File::nonexistent;
  6242. String filePart (getFileName());
  6243. int i = filePart.lastIndexOfChar ('.');
  6244. if (i >= 0)
  6245. filePart = filePart.substring (0, i);
  6246. if (newExtension.isNotEmpty() && ! newExtension.startsWithChar ('.'))
  6247. filePart << '.';
  6248. return getSiblingFile (filePart + newExtension);
  6249. }
  6250. bool File::startAsProcess (const String& parameters) const
  6251. {
  6252. return exists() && PlatformUtilities::openDocument (fullPath, parameters);
  6253. }
  6254. FileInputStream* File::createInputStream() const
  6255. {
  6256. if (existsAsFile())
  6257. return new FileInputStream (*this);
  6258. return 0;
  6259. }
  6260. FileOutputStream* File::createOutputStream (const int bufferSize) const
  6261. {
  6262. ScopedPointer <FileOutputStream> out (new FileOutputStream (*this, bufferSize));
  6263. if (out->failedToOpen())
  6264. return 0;
  6265. return out.release();
  6266. }
  6267. bool File::appendData (const void* const dataToAppend,
  6268. const int numberOfBytes) const
  6269. {
  6270. if (numberOfBytes > 0)
  6271. {
  6272. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6273. if (out == 0)
  6274. return false;
  6275. out->write (dataToAppend, numberOfBytes);
  6276. }
  6277. return true;
  6278. }
  6279. bool File::replaceWithData (const void* const dataToWrite,
  6280. const int numberOfBytes) const
  6281. {
  6282. jassert (numberOfBytes >= 0); // a negative number of bytes??
  6283. if (numberOfBytes <= 0)
  6284. return deleteFile();
  6285. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6286. tempFile.getFile().appendData (dataToWrite, numberOfBytes);
  6287. return tempFile.overwriteTargetFileWithTemporary();
  6288. }
  6289. bool File::appendText (const String& text,
  6290. const bool asUnicode,
  6291. const bool writeUnicodeHeaderBytes) const
  6292. {
  6293. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6294. if (out != 0)
  6295. {
  6296. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  6297. return true;
  6298. }
  6299. return false;
  6300. }
  6301. bool File::replaceWithText (const String& textToWrite,
  6302. const bool asUnicode,
  6303. const bool writeUnicodeHeaderBytes) const
  6304. {
  6305. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6306. tempFile.getFile().appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes);
  6307. return tempFile.overwriteTargetFileWithTemporary();
  6308. }
  6309. bool File::hasIdenticalContentTo (const File& other) const
  6310. {
  6311. if (other == *this)
  6312. return true;
  6313. if (getSize() == other.getSize() && existsAsFile() && other.existsAsFile())
  6314. {
  6315. FileInputStream in1 (*this), in2 (other);
  6316. const int bufferSize = 4096;
  6317. HeapBlock <char> buffer1, buffer2;
  6318. buffer1.malloc (bufferSize);
  6319. buffer2.malloc (bufferSize);
  6320. for (;;)
  6321. {
  6322. const int num1 = in1.read (buffer1, bufferSize);
  6323. const int num2 = in2.read (buffer2, bufferSize);
  6324. if (num1 != num2)
  6325. break;
  6326. if (num1 <= 0)
  6327. return true;
  6328. if (memcmp (buffer1, buffer2, num1) != 0)
  6329. break;
  6330. }
  6331. }
  6332. return false;
  6333. }
  6334. const String File::createLegalPathName (const String& original)
  6335. {
  6336. String s (original);
  6337. String start;
  6338. if (s[1] == ':')
  6339. {
  6340. start = s.substring (0, 2);
  6341. s = s.substring (2);
  6342. }
  6343. return start + s.removeCharacters ("\"#@,;:<>*^|?")
  6344. .substring (0, 1024);
  6345. }
  6346. const String File::createLegalFileName (const String& original)
  6347. {
  6348. String s (original.removeCharacters ("\"#@,;:<>*^|?\\/"));
  6349. const int maxLength = 128; // only the length of the filename, not the whole path
  6350. const int len = s.length();
  6351. if (len > maxLength)
  6352. {
  6353. const int lastDot = s.lastIndexOfChar ('.');
  6354. if (lastDot > jmax (0, len - 12))
  6355. {
  6356. s = s.substring (0, maxLength - (len - lastDot))
  6357. + s.substring (lastDot);
  6358. }
  6359. else
  6360. {
  6361. s = s.substring (0, maxLength);
  6362. }
  6363. }
  6364. return s;
  6365. }
  6366. const String File::getRelativePathFrom (const File& dir) const
  6367. {
  6368. String thisPath (fullPath);
  6369. {
  6370. int len = thisPath.length();
  6371. while (--len >= 0 && thisPath [len] == File::separator)
  6372. thisPath [len] = 0;
  6373. }
  6374. String dirPath (addTrailingSeparator (dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
  6375. : dir.fullPath));
  6376. const int len = jmin (thisPath.length(), dirPath.length());
  6377. int commonBitLength = 0;
  6378. for (int i = 0; i < len; ++i)
  6379. {
  6380. #if NAMES_ARE_CASE_SENSITIVE
  6381. if (thisPath[i] != dirPath[i])
  6382. #else
  6383. if (CharacterFunctions::toLowerCase (thisPath[i])
  6384. != CharacterFunctions::toLowerCase (dirPath[i]))
  6385. #endif
  6386. {
  6387. break;
  6388. }
  6389. ++commonBitLength;
  6390. }
  6391. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  6392. --commonBitLength;
  6393. // if the only common bit is the root, then just return the full path..
  6394. if (commonBitLength <= 0
  6395. || (commonBitLength == 1 && thisPath [1] == File::separator))
  6396. return fullPath;
  6397. thisPath = thisPath.substring (commonBitLength);
  6398. dirPath = dirPath.substring (commonBitLength);
  6399. while (dirPath.isNotEmpty())
  6400. {
  6401. #if JUCE_WINDOWS
  6402. thisPath = "..\\" + thisPath;
  6403. #else
  6404. thisPath = "../" + thisPath;
  6405. #endif
  6406. const int sep = dirPath.indexOfChar (separator);
  6407. if (sep >= 0)
  6408. dirPath = dirPath.substring (sep + 1);
  6409. else
  6410. dirPath = String::empty;
  6411. }
  6412. return thisPath;
  6413. }
  6414. const File File::createTempFile (const String& fileNameEnding)
  6415. {
  6416. const File tempFile (getSpecialLocation (tempDirectory)
  6417. .getChildFile ("temp_" + String (Random::getSystemRandom().nextInt()))
  6418. .withFileExtension (fileNameEnding));
  6419. if (tempFile.exists())
  6420. return createTempFile (fileNameEnding);
  6421. else
  6422. return tempFile;
  6423. }
  6424. #if JUCE_UNIT_TESTS
  6425. class FileTests : public UnitTest
  6426. {
  6427. public:
  6428. FileTests() : UnitTest ("Files") {}
  6429. void runTest()
  6430. {
  6431. beginTest ("Reading");
  6432. const File home (File::getSpecialLocation (File::userHomeDirectory));
  6433. const File temp (File::getSpecialLocation (File::tempDirectory));
  6434. expect (! File::nonexistent.exists());
  6435. expect (home.isDirectory());
  6436. expect (home.exists());
  6437. expect (! home.existsAsFile());
  6438. expect (File::getSpecialLocation (File::userDocumentsDirectory).isDirectory());
  6439. expect (File::getSpecialLocation (File::userApplicationDataDirectory).isDirectory());
  6440. expect (File::getSpecialLocation (File::currentExecutableFile).exists());
  6441. expect (File::getSpecialLocation (File::currentApplicationFile).exists());
  6442. expect (File::getSpecialLocation (File::invokedExecutableFile).exists());
  6443. expect (home.getVolumeTotalSize() > 1024 * 1024);
  6444. expect (home.getBytesFreeOnVolume() > 0);
  6445. expect (! home.isHidden());
  6446. expect (home.isOnHardDisk());
  6447. expect (! home.isOnCDRomDrive());
  6448. expect (File::getCurrentWorkingDirectory().exists());
  6449. expect (home.setAsCurrentWorkingDirectory());
  6450. expect (File::getCurrentWorkingDirectory() == home);
  6451. {
  6452. Array<File> roots;
  6453. File::findFileSystemRoots (roots);
  6454. expect (roots.size() > 0);
  6455. int numRootsExisting = 0;
  6456. for (int i = 0; i < roots.size(); ++i)
  6457. if (roots[i].exists())
  6458. ++numRootsExisting;
  6459. // (on windows, some of the drives may not contain media, so as long as at least one is ok..)
  6460. expect (numRootsExisting > 0);
  6461. }
  6462. beginTest ("Writing");
  6463. File demoFolder (temp.getChildFile ("Juce UnitTests Temp Folder.folder"));
  6464. expect (demoFolder.deleteRecursively());
  6465. expect (demoFolder.createDirectory());
  6466. expect (demoFolder.isDirectory());
  6467. expect (demoFolder.getParentDirectory() == temp);
  6468. expect (temp.isDirectory());
  6469. {
  6470. Array<File> files;
  6471. temp.findChildFiles (files, File::findFilesAndDirectories, false, "*");
  6472. expect (files.contains (demoFolder));
  6473. }
  6474. {
  6475. Array<File> files;
  6476. temp.findChildFiles (files, File::findDirectories, true, "*.folder");
  6477. expect (files.contains (demoFolder));
  6478. }
  6479. File tempFile (demoFolder.getNonexistentChildFile ("test", ".txt", false));
  6480. expect (tempFile.getFileExtension() == ".txt");
  6481. expect (tempFile.hasFileExtension (".txt"));
  6482. expect (tempFile.hasFileExtension ("txt"));
  6483. expect (tempFile.withFileExtension ("xyz").hasFileExtension (".xyz"));
  6484. expect (tempFile.getSiblingFile ("foo").isAChildOf (temp));
  6485. expect (tempFile.hasWriteAccess());
  6486. {
  6487. FileOutputStream fo (tempFile);
  6488. fo.write ("0123456789", 10);
  6489. }
  6490. expect (tempFile.exists());
  6491. expect (tempFile.getSize() == 10);
  6492. expect (std::abs ((int) (tempFile.getLastModificationTime().toMilliseconds() - Time::getCurrentTime().toMilliseconds())) < 3000);
  6493. expect (tempFile.loadFileAsString() == "0123456789");
  6494. expect (! demoFolder.containsSubDirectories());
  6495. expect (demoFolder.getNumberOfChildFiles (File::findFiles) == 1);
  6496. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 1);
  6497. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 0);
  6498. demoFolder.getNonexistentChildFile ("tempFolder", "", false).createDirectory();
  6499. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 1);
  6500. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 2);
  6501. expect (demoFolder.containsSubDirectories());
  6502. expect (tempFile.hasWriteAccess());
  6503. tempFile.setReadOnly (true);
  6504. expect (! tempFile.hasWriteAccess());
  6505. tempFile.setReadOnly (false);
  6506. expect (tempFile.hasWriteAccess());
  6507. Time t (Time::getCurrentTime());
  6508. tempFile.setLastModificationTime (t);
  6509. Time t2 = tempFile.getLastModificationTime();
  6510. expect (std::abs ((int) (t2.toMilliseconds() - t.toMilliseconds())) <= 1000);
  6511. {
  6512. MemoryBlock mb;
  6513. tempFile.loadFileAsData (mb);
  6514. expect (mb.getSize() == 10);
  6515. expect (mb[0] == '0');
  6516. }
  6517. expect (tempFile.appendData ("abcdefghij", 10));
  6518. expect (tempFile.getSize() == 20);
  6519. expect (tempFile.replaceWithData ("abcdefghij", 10));
  6520. expect (tempFile.getSize() == 10);
  6521. File tempFile2 (tempFile.getNonexistentSibling (false));
  6522. expect (tempFile.copyFileTo (tempFile2));
  6523. expect (tempFile2.exists());
  6524. expect (tempFile2.hasIdenticalContentTo (tempFile));
  6525. expect (tempFile.deleteFile());
  6526. expect (! tempFile.exists());
  6527. expect (tempFile2.moveFileTo (tempFile));
  6528. expect (tempFile.exists());
  6529. expect (! tempFile2.exists());
  6530. expect (demoFolder.deleteRecursively());
  6531. expect (! demoFolder.exists());
  6532. }
  6533. };
  6534. static FileTests fileUnitTests;
  6535. #endif
  6536. END_JUCE_NAMESPACE
  6537. /*** End of inlined file: juce_File.cpp ***/
  6538. /*** Start of inlined file: juce_FileInputStream.cpp ***/
  6539. BEGIN_JUCE_NAMESPACE
  6540. int64 juce_fileSetPosition (void* handle, int64 pos);
  6541. FileInputStream::FileInputStream (const File& f)
  6542. : file (f),
  6543. fileHandle (0),
  6544. currentPosition (0),
  6545. totalSize (0),
  6546. needToSeek (true)
  6547. {
  6548. openHandle();
  6549. }
  6550. FileInputStream::~FileInputStream()
  6551. {
  6552. closeHandle();
  6553. }
  6554. int64 FileInputStream::getTotalLength()
  6555. {
  6556. return totalSize;
  6557. }
  6558. int FileInputStream::read (void* buffer, int bytesToRead)
  6559. {
  6560. int num = 0;
  6561. if (needToSeek)
  6562. {
  6563. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  6564. return 0;
  6565. needToSeek = false;
  6566. }
  6567. num = readInternal (buffer, bytesToRead);
  6568. currentPosition += num;
  6569. return num;
  6570. }
  6571. bool FileInputStream::isExhausted()
  6572. {
  6573. return currentPosition >= totalSize;
  6574. }
  6575. int64 FileInputStream::getPosition()
  6576. {
  6577. return currentPosition;
  6578. }
  6579. bool FileInputStream::setPosition (int64 pos)
  6580. {
  6581. pos = jlimit ((int64) 0, totalSize, pos);
  6582. needToSeek |= (currentPosition != pos);
  6583. currentPosition = pos;
  6584. return true;
  6585. }
  6586. END_JUCE_NAMESPACE
  6587. /*** End of inlined file: juce_FileInputStream.cpp ***/
  6588. /*** Start of inlined file: juce_FileOutputStream.cpp ***/
  6589. BEGIN_JUCE_NAMESPACE
  6590. int64 juce_fileSetPosition (void* handle, int64 pos);
  6591. FileOutputStream::FileOutputStream (const File& f, const int bufferSize_)
  6592. : file (f),
  6593. fileHandle (0),
  6594. currentPosition (0),
  6595. bufferSize (bufferSize_),
  6596. bytesInBuffer (0),
  6597. buffer (jmax (bufferSize_, 16))
  6598. {
  6599. openHandle();
  6600. }
  6601. FileOutputStream::~FileOutputStream()
  6602. {
  6603. flush();
  6604. closeHandle();
  6605. }
  6606. int64 FileOutputStream::getPosition()
  6607. {
  6608. return currentPosition;
  6609. }
  6610. bool FileOutputStream::setPosition (int64 newPosition)
  6611. {
  6612. if (newPosition != currentPosition)
  6613. {
  6614. flush();
  6615. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  6616. }
  6617. return newPosition == currentPosition;
  6618. }
  6619. void FileOutputStream::flush()
  6620. {
  6621. if (bytesInBuffer > 0)
  6622. {
  6623. writeInternal (buffer, bytesInBuffer);
  6624. bytesInBuffer = 0;
  6625. }
  6626. flushInternal();
  6627. }
  6628. bool FileOutputStream::write (const void* const src, const int numBytes)
  6629. {
  6630. if (bytesInBuffer + numBytes < bufferSize)
  6631. {
  6632. memcpy (buffer + bytesInBuffer, src, numBytes);
  6633. bytesInBuffer += numBytes;
  6634. currentPosition += numBytes;
  6635. }
  6636. else
  6637. {
  6638. if (bytesInBuffer > 0)
  6639. {
  6640. // flush the reservoir
  6641. const bool wroteOk = (writeInternal (buffer, bytesInBuffer) == bytesInBuffer);
  6642. bytesInBuffer = 0;
  6643. if (! wroteOk)
  6644. return false;
  6645. }
  6646. if (numBytes < bufferSize)
  6647. {
  6648. memcpy (buffer + bytesInBuffer, src, numBytes);
  6649. bytesInBuffer += numBytes;
  6650. currentPosition += numBytes;
  6651. }
  6652. else
  6653. {
  6654. const int bytesWritten = writeInternal (src, numBytes);
  6655. if (bytesWritten < 0)
  6656. return false;
  6657. currentPosition += bytesWritten;
  6658. return bytesWritten == numBytes;
  6659. }
  6660. }
  6661. return true;
  6662. }
  6663. END_JUCE_NAMESPACE
  6664. /*** End of inlined file: juce_FileOutputStream.cpp ***/
  6665. /*** Start of inlined file: juce_FileSearchPath.cpp ***/
  6666. BEGIN_JUCE_NAMESPACE
  6667. FileSearchPath::FileSearchPath()
  6668. {
  6669. }
  6670. FileSearchPath::FileSearchPath (const String& path)
  6671. {
  6672. init (path);
  6673. }
  6674. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  6675. : directories (other.directories)
  6676. {
  6677. }
  6678. FileSearchPath::~FileSearchPath()
  6679. {
  6680. }
  6681. FileSearchPath& FileSearchPath::operator= (const String& path)
  6682. {
  6683. init (path);
  6684. return *this;
  6685. }
  6686. void FileSearchPath::init (const String& path)
  6687. {
  6688. directories.clear();
  6689. directories.addTokens (path, ";", "\"");
  6690. directories.trim();
  6691. directories.removeEmptyStrings();
  6692. for (int i = directories.size(); --i >= 0;)
  6693. directories.set (i, directories[i].unquoted());
  6694. }
  6695. int FileSearchPath::getNumPaths() const
  6696. {
  6697. return directories.size();
  6698. }
  6699. const File FileSearchPath::operator[] (const int index) const
  6700. {
  6701. return File (directories [index]);
  6702. }
  6703. const String FileSearchPath::toString() const
  6704. {
  6705. StringArray directories2 (directories);
  6706. for (int i = directories2.size(); --i >= 0;)
  6707. if (directories2[i].containsChar (';'))
  6708. directories2.set (i, directories2[i].quoted());
  6709. return directories2.joinIntoString (";");
  6710. }
  6711. void FileSearchPath::add (const File& dir, const int insertIndex)
  6712. {
  6713. directories.insert (insertIndex, dir.getFullPathName());
  6714. }
  6715. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  6716. {
  6717. for (int i = 0; i < directories.size(); ++i)
  6718. if (File (directories[i]) == dir)
  6719. return;
  6720. add (dir);
  6721. }
  6722. void FileSearchPath::remove (const int index)
  6723. {
  6724. directories.remove (index);
  6725. }
  6726. void FileSearchPath::addPath (const FileSearchPath& other)
  6727. {
  6728. for (int i = 0; i < other.getNumPaths(); ++i)
  6729. addIfNotAlreadyThere (other[i]);
  6730. }
  6731. void FileSearchPath::removeRedundantPaths()
  6732. {
  6733. for (int i = directories.size(); --i >= 0;)
  6734. {
  6735. const File d1 (directories[i]);
  6736. for (int j = directories.size(); --j >= 0;)
  6737. {
  6738. const File d2 (directories[j]);
  6739. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  6740. {
  6741. directories.remove (i);
  6742. break;
  6743. }
  6744. }
  6745. }
  6746. }
  6747. void FileSearchPath::removeNonExistentPaths()
  6748. {
  6749. for (int i = directories.size(); --i >= 0;)
  6750. if (! File (directories[i]).isDirectory())
  6751. directories.remove (i);
  6752. }
  6753. int FileSearchPath::findChildFiles (Array<File>& results,
  6754. const int whatToLookFor,
  6755. const bool searchRecursively,
  6756. const String& wildCardPattern) const
  6757. {
  6758. int total = 0;
  6759. for (int i = 0; i < directories.size(); ++i)
  6760. total += operator[] (i).findChildFiles (results,
  6761. whatToLookFor,
  6762. searchRecursively,
  6763. wildCardPattern);
  6764. return total;
  6765. }
  6766. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  6767. const bool checkRecursively) const
  6768. {
  6769. for (int i = directories.size(); --i >= 0;)
  6770. {
  6771. const File d (directories[i]);
  6772. if (checkRecursively)
  6773. {
  6774. if (fileToCheck.isAChildOf (d))
  6775. return true;
  6776. }
  6777. else
  6778. {
  6779. if (fileToCheck.getParentDirectory() == d)
  6780. return true;
  6781. }
  6782. }
  6783. return false;
  6784. }
  6785. END_JUCE_NAMESPACE
  6786. /*** End of inlined file: juce_FileSearchPath.cpp ***/
  6787. /*** Start of inlined file: juce_NamedPipe.cpp ***/
  6788. BEGIN_JUCE_NAMESPACE
  6789. NamedPipe::NamedPipe()
  6790. : internal (0)
  6791. {
  6792. }
  6793. NamedPipe::~NamedPipe()
  6794. {
  6795. close();
  6796. }
  6797. bool NamedPipe::openExisting (const String& pipeName)
  6798. {
  6799. currentPipeName = pipeName;
  6800. return openInternal (pipeName, false);
  6801. }
  6802. bool NamedPipe::createNewPipe (const String& pipeName)
  6803. {
  6804. currentPipeName = pipeName;
  6805. return openInternal (pipeName, true);
  6806. }
  6807. bool NamedPipe::isOpen() const
  6808. {
  6809. return internal != 0;
  6810. }
  6811. const String NamedPipe::getName() const
  6812. {
  6813. return currentPipeName;
  6814. }
  6815. // other methods for this class are implemented in the platform-specific files
  6816. END_JUCE_NAMESPACE
  6817. /*** End of inlined file: juce_NamedPipe.cpp ***/
  6818. /*** Start of inlined file: juce_TemporaryFile.cpp ***/
  6819. BEGIN_JUCE_NAMESPACE
  6820. TemporaryFile::TemporaryFile (const String& suffix, const int optionFlags)
  6821. {
  6822. createTempFile (File::getSpecialLocation (File::tempDirectory),
  6823. "temp_" + String (Random::getSystemRandom().nextInt()),
  6824. suffix,
  6825. optionFlags);
  6826. }
  6827. TemporaryFile::TemporaryFile (const File& targetFile_, const int optionFlags)
  6828. : targetFile (targetFile_)
  6829. {
  6830. // If you use this constructor, you need to give it a valid target file!
  6831. jassert (targetFile != File::nonexistent);
  6832. createTempFile (targetFile.getParentDirectory(),
  6833. targetFile.getFileNameWithoutExtension() + "_temp" + String (Random::getSystemRandom().nextInt()),
  6834. targetFile.getFileExtension(),
  6835. optionFlags);
  6836. }
  6837. void TemporaryFile::createTempFile (const File& parentDirectory, String name,
  6838. const String& suffix, const int optionFlags)
  6839. {
  6840. if ((optionFlags & useHiddenFile) != 0)
  6841. name = "." + name;
  6842. temporaryFile = parentDirectory.getNonexistentChildFile (name, suffix, (optionFlags & putNumbersInBrackets) != 0);
  6843. }
  6844. TemporaryFile::~TemporaryFile()
  6845. {
  6846. if (! deleteTemporaryFile())
  6847. {
  6848. /* Failed to delete our temporary file! The most likely reason for this would be
  6849. that you've not closed an output stream that was being used to write to file.
  6850. If you find that something beyond your control is changing permissions on
  6851. your temporary files and preventing them from being deleted, you may want to
  6852. call TemporaryFile::deleteTemporaryFile() to detect those error cases and
  6853. handle them appropriately.
  6854. */
  6855. jassertfalse;
  6856. }
  6857. }
  6858. bool TemporaryFile::overwriteTargetFileWithTemporary() const
  6859. {
  6860. // This method only works if you created this object with the constructor
  6861. // that takes a target file!
  6862. jassert (targetFile != File::nonexistent);
  6863. if (temporaryFile.exists())
  6864. {
  6865. // Have a few attempts at overwriting the file before giving up..
  6866. for (int i = 5; --i >= 0;)
  6867. {
  6868. if (temporaryFile.moveFileTo (targetFile))
  6869. return true;
  6870. Thread::sleep (100);
  6871. }
  6872. }
  6873. else
  6874. {
  6875. // There's no temporary file to use. If your write failed, you should
  6876. // probably check, and not bother calling this method.
  6877. jassertfalse;
  6878. }
  6879. return false;
  6880. }
  6881. bool TemporaryFile::deleteTemporaryFile() const
  6882. {
  6883. // Have a few attempts at deleting the file before giving up..
  6884. for (int i = 5; --i >= 0;)
  6885. {
  6886. if (temporaryFile.deleteFile())
  6887. return true;
  6888. Thread::sleep (50);
  6889. }
  6890. return false;
  6891. }
  6892. END_JUCE_NAMESPACE
  6893. /*** End of inlined file: juce_TemporaryFile.cpp ***/
  6894. /*** Start of inlined file: juce_Socket.cpp ***/
  6895. #if JUCE_WINDOWS
  6896. #include <winsock2.h>
  6897. #if JUCE_MSVC
  6898. #pragma warning (push)
  6899. #pragma warning (disable : 4127 4389 4018)
  6900. #endif
  6901. #else
  6902. #if JUCE_LINUX
  6903. #include <sys/types.h>
  6904. #include <sys/socket.h>
  6905. #include <sys/errno.h>
  6906. #include <unistd.h>
  6907. #include <netinet/in.h>
  6908. #elif (MACOSX_DEPLOYMENT_TARGET <= MAC_OS_X_VERSION_10_4) && ! JUCE_IOS
  6909. #include <CoreServices/CoreServices.h>
  6910. #endif
  6911. #include <fcntl.h>
  6912. #include <netdb.h>
  6913. #include <arpa/inet.h>
  6914. #include <netinet/tcp.h>
  6915. #endif
  6916. BEGIN_JUCE_NAMESPACE
  6917. #if defined (JUCE_LINUX) || defined (JUCE_MAC) || defined (JUCE_IOS)
  6918. typedef socklen_t juce_socklen_t;
  6919. #else
  6920. typedef int juce_socklen_t;
  6921. #endif
  6922. #if JUCE_WINDOWS
  6923. namespace SocketHelpers
  6924. {
  6925. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  6926. static juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  6927. }
  6928. static void initWin32Sockets()
  6929. {
  6930. static CriticalSection lock;
  6931. const ScopedLock sl (lock);
  6932. if (SocketHelpers::juce_CloseWin32SocketLib == 0)
  6933. {
  6934. WSADATA wsaData;
  6935. const WORD wVersionRequested = MAKEWORD (1, 1);
  6936. WSAStartup (wVersionRequested, &wsaData);
  6937. SocketHelpers::juce_CloseWin32SocketLib = &WSACleanup;
  6938. }
  6939. }
  6940. void juce_shutdownWin32Sockets()
  6941. {
  6942. if (SocketHelpers::juce_CloseWin32SocketLib != 0)
  6943. (*SocketHelpers::juce_CloseWin32SocketLib)();
  6944. }
  6945. #endif
  6946. namespace SocketHelpers
  6947. {
  6948. static bool resetSocketOptions (const int handle, const bool isDatagram, const bool allowBroadcast) throw()
  6949. {
  6950. const int sndBufSize = 65536;
  6951. const int rcvBufSize = 65536;
  6952. const int one = 1;
  6953. return handle > 0
  6954. && setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (rcvBufSize)) == 0
  6955. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (sndBufSize)) == 0
  6956. && (isDatagram ? ((! allowBroadcast) || setsockopt (handle, SOL_SOCKET, SO_BROADCAST, (const char*) &one, sizeof (one)) == 0)
  6957. : (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (one)) == 0));
  6958. }
  6959. static bool bindSocketToPort (const int handle, const int port) throw()
  6960. {
  6961. if (handle <= 0 || port <= 0)
  6962. return false;
  6963. struct sockaddr_in servTmpAddr;
  6964. zerostruct (servTmpAddr);
  6965. servTmpAddr.sin_family = PF_INET;
  6966. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  6967. servTmpAddr.sin_port = htons ((uint16) port);
  6968. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  6969. }
  6970. static int readSocket (const int handle,
  6971. void* const destBuffer, const int maxBytesToRead,
  6972. bool volatile& connected,
  6973. const bool blockUntilSpecifiedAmountHasArrived) throw()
  6974. {
  6975. int bytesRead = 0;
  6976. while (bytesRead < maxBytesToRead)
  6977. {
  6978. int bytesThisTime;
  6979. #if JUCE_WINDOWS
  6980. bytesThisTime = recv (handle, static_cast<char*> (destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  6981. #else
  6982. while ((bytesThisTime = (int) ::read (handle, addBytesToPointer (destBuffer, bytesRead), maxBytesToRead - bytesRead)) < 0
  6983. && errno == EINTR
  6984. && connected)
  6985. {
  6986. }
  6987. #endif
  6988. if (bytesThisTime <= 0 || ! connected)
  6989. {
  6990. if (bytesRead == 0)
  6991. bytesRead = -1;
  6992. break;
  6993. }
  6994. bytesRead += bytesThisTime;
  6995. if (! blockUntilSpecifiedAmountHasArrived)
  6996. break;
  6997. }
  6998. return bytesRead;
  6999. }
  7000. static int waitForReadiness (const int handle, const bool forReading,
  7001. const int timeoutMsecs) throw()
  7002. {
  7003. struct timeval timeout;
  7004. struct timeval* timeoutp;
  7005. if (timeoutMsecs >= 0)
  7006. {
  7007. timeout.tv_sec = timeoutMsecs / 1000;
  7008. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  7009. timeoutp = &timeout;
  7010. }
  7011. else
  7012. {
  7013. timeoutp = 0;
  7014. }
  7015. fd_set rset, wset;
  7016. FD_ZERO (&rset);
  7017. FD_SET (handle, &rset);
  7018. FD_ZERO (&wset);
  7019. FD_SET (handle, &wset);
  7020. fd_set* const prset = forReading ? &rset : 0;
  7021. fd_set* const pwset = forReading ? 0 : &wset;
  7022. #if JUCE_WINDOWS
  7023. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  7024. return -1;
  7025. #else
  7026. {
  7027. int result;
  7028. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  7029. && errno == EINTR)
  7030. {
  7031. }
  7032. if (result < 0)
  7033. return -1;
  7034. }
  7035. #endif
  7036. {
  7037. int opt;
  7038. juce_socklen_t len = sizeof (opt);
  7039. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  7040. || opt != 0)
  7041. return -1;
  7042. }
  7043. if ((forReading && FD_ISSET (handle, &rset))
  7044. || ((! forReading) && FD_ISSET (handle, &wset)))
  7045. return 1;
  7046. return 0;
  7047. }
  7048. static bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  7049. {
  7050. #if JUCE_WINDOWS
  7051. u_long nonBlocking = shouldBlock ? 0 : 1;
  7052. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  7053. return false;
  7054. #else
  7055. int socketFlags = fcntl (handle, F_GETFL, 0);
  7056. if (socketFlags == -1)
  7057. return false;
  7058. if (shouldBlock)
  7059. socketFlags &= ~O_NONBLOCK;
  7060. else
  7061. socketFlags |= O_NONBLOCK;
  7062. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  7063. return false;
  7064. #endif
  7065. return true;
  7066. }
  7067. static bool connectSocket (int volatile& handle,
  7068. const bool isDatagram,
  7069. void** serverAddress,
  7070. const String& hostName,
  7071. const int portNumber,
  7072. const int timeOutMillisecs) throw()
  7073. {
  7074. struct hostent* const hostEnt = gethostbyname (hostName.toUTF8());
  7075. if (hostEnt == 0)
  7076. return false;
  7077. struct in_addr targetAddress;
  7078. memcpy (&targetAddress.s_addr,
  7079. *(hostEnt->h_addr_list),
  7080. sizeof (targetAddress.s_addr));
  7081. struct sockaddr_in servTmpAddr;
  7082. zerostruct (servTmpAddr);
  7083. servTmpAddr.sin_family = PF_INET;
  7084. servTmpAddr.sin_addr = targetAddress;
  7085. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7086. if (handle < 0)
  7087. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  7088. if (handle < 0)
  7089. return false;
  7090. if (isDatagram)
  7091. {
  7092. *serverAddress = new struct sockaddr_in();
  7093. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  7094. return true;
  7095. }
  7096. setSocketBlockingState (handle, false);
  7097. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  7098. if (result < 0)
  7099. {
  7100. #if JUCE_WINDOWS
  7101. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  7102. #else
  7103. if (errno == EINPROGRESS)
  7104. #endif
  7105. {
  7106. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  7107. {
  7108. setSocketBlockingState (handle, true);
  7109. return false;
  7110. }
  7111. }
  7112. }
  7113. setSocketBlockingState (handle, true);
  7114. resetSocketOptions (handle, false, false);
  7115. return true;
  7116. }
  7117. }
  7118. StreamingSocket::StreamingSocket()
  7119. : portNumber (0),
  7120. handle (-1),
  7121. connected (false),
  7122. isListener (false)
  7123. {
  7124. #if JUCE_WINDOWS
  7125. initWin32Sockets();
  7126. #endif
  7127. }
  7128. StreamingSocket::StreamingSocket (const String& hostName_,
  7129. const int portNumber_,
  7130. const int handle_)
  7131. : hostName (hostName_),
  7132. portNumber (portNumber_),
  7133. handle (handle_),
  7134. connected (true),
  7135. isListener (false)
  7136. {
  7137. #if JUCE_WINDOWS
  7138. initWin32Sockets();
  7139. #endif
  7140. SocketHelpers::resetSocketOptions (handle_, false, false);
  7141. }
  7142. StreamingSocket::~StreamingSocket()
  7143. {
  7144. close();
  7145. }
  7146. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7147. {
  7148. return (connected && ! isListener) ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7149. : -1;
  7150. }
  7151. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7152. {
  7153. if (isListener || ! connected)
  7154. return -1;
  7155. #if JUCE_WINDOWS
  7156. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  7157. #else
  7158. int result;
  7159. while ((result = (int) ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  7160. && errno == EINTR)
  7161. {
  7162. }
  7163. return result;
  7164. #endif
  7165. }
  7166. int StreamingSocket::waitUntilReady (const bool readyForReading,
  7167. const int timeoutMsecs) const
  7168. {
  7169. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7170. : -1;
  7171. }
  7172. bool StreamingSocket::bindToPort (const int port)
  7173. {
  7174. return SocketHelpers::bindSocketToPort (handle, port);
  7175. }
  7176. bool StreamingSocket::connect (const String& remoteHostName,
  7177. const int remotePortNumber,
  7178. const int timeOutMillisecs)
  7179. {
  7180. if (isListener)
  7181. {
  7182. jassertfalse; // a listener socket can't connect to another one!
  7183. return false;
  7184. }
  7185. if (connected)
  7186. close();
  7187. hostName = remoteHostName;
  7188. portNumber = remotePortNumber;
  7189. isListener = false;
  7190. connected = SocketHelpers::connectSocket (handle, false, 0, remoteHostName,
  7191. remotePortNumber, timeOutMillisecs);
  7192. if (! (connected && SocketHelpers::resetSocketOptions (handle, false, false)))
  7193. {
  7194. close();
  7195. return false;
  7196. }
  7197. return true;
  7198. }
  7199. void StreamingSocket::close()
  7200. {
  7201. #if JUCE_WINDOWS
  7202. if (handle != SOCKET_ERROR || connected)
  7203. closesocket (handle);
  7204. connected = false;
  7205. #else
  7206. if (connected)
  7207. {
  7208. connected = false;
  7209. if (isListener)
  7210. {
  7211. // need to do this to interrupt the accept() function..
  7212. StreamingSocket temp;
  7213. temp.connect ("localhost", portNumber, 1000);
  7214. }
  7215. }
  7216. if (handle != -1)
  7217. ::close (handle);
  7218. #endif
  7219. hostName = String::empty;
  7220. portNumber = 0;
  7221. handle = -1;
  7222. isListener = false;
  7223. }
  7224. bool StreamingSocket::createListener (const int newPortNumber, const String& localHostName)
  7225. {
  7226. if (connected)
  7227. close();
  7228. hostName = "listener";
  7229. portNumber = newPortNumber;
  7230. isListener = true;
  7231. struct sockaddr_in servTmpAddr;
  7232. zerostruct (servTmpAddr);
  7233. servTmpAddr.sin_family = PF_INET;
  7234. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  7235. if (localHostName.isNotEmpty())
  7236. servTmpAddr.sin_addr.s_addr = ::inet_addr (localHostName.toUTF8());
  7237. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7238. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  7239. if (handle < 0)
  7240. return false;
  7241. const int reuse = 1;
  7242. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  7243. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  7244. || listen (handle, SOMAXCONN) < 0)
  7245. {
  7246. close();
  7247. return false;
  7248. }
  7249. connected = true;
  7250. return true;
  7251. }
  7252. StreamingSocket* StreamingSocket::waitForNextConnection() const
  7253. {
  7254. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  7255. // prepare this socket as a listener.
  7256. if (connected && isListener)
  7257. {
  7258. struct sockaddr address;
  7259. juce_socklen_t len = sizeof (sockaddr);
  7260. const int newSocket = (int) accept (handle, &address, &len);
  7261. if (newSocket >= 0 && connected)
  7262. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7263. portNumber, newSocket);
  7264. }
  7265. return 0;
  7266. }
  7267. bool StreamingSocket::isLocal() const throw()
  7268. {
  7269. return hostName == "127.0.0.1";
  7270. }
  7271. DatagramSocket::DatagramSocket (const int localPortNumber, const bool allowBroadcast_)
  7272. : portNumber (0),
  7273. handle (-1),
  7274. connected (true),
  7275. allowBroadcast (allowBroadcast_),
  7276. serverAddress (0)
  7277. {
  7278. #if JUCE_WINDOWS
  7279. initWin32Sockets();
  7280. #endif
  7281. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  7282. bindToPort (localPortNumber);
  7283. }
  7284. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  7285. const int handle_, const int localPortNumber)
  7286. : hostName (hostName_),
  7287. portNumber (portNumber_),
  7288. handle (handle_),
  7289. connected (true),
  7290. allowBroadcast (false),
  7291. serverAddress (0)
  7292. {
  7293. #if JUCE_WINDOWS
  7294. initWin32Sockets();
  7295. #endif
  7296. SocketHelpers::resetSocketOptions (handle_, true, allowBroadcast);
  7297. bindToPort (localPortNumber);
  7298. }
  7299. DatagramSocket::~DatagramSocket()
  7300. {
  7301. close();
  7302. delete static_cast <struct sockaddr_in*> (serverAddress);
  7303. serverAddress = 0;
  7304. }
  7305. void DatagramSocket::close()
  7306. {
  7307. #if JUCE_WINDOWS
  7308. closesocket (handle);
  7309. connected = false;
  7310. #else
  7311. connected = false;
  7312. ::close (handle);
  7313. #endif
  7314. hostName = String::empty;
  7315. portNumber = 0;
  7316. handle = -1;
  7317. }
  7318. bool DatagramSocket::bindToPort (const int port)
  7319. {
  7320. return SocketHelpers::bindSocketToPort (handle, port);
  7321. }
  7322. bool DatagramSocket::connect (const String& remoteHostName,
  7323. const int remotePortNumber,
  7324. const int timeOutMillisecs)
  7325. {
  7326. if (connected)
  7327. close();
  7328. hostName = remoteHostName;
  7329. portNumber = remotePortNumber;
  7330. connected = SocketHelpers::connectSocket (handle, true, &serverAddress,
  7331. remoteHostName, remotePortNumber,
  7332. timeOutMillisecs);
  7333. if (! (connected && SocketHelpers::resetSocketOptions (handle, true, allowBroadcast)))
  7334. {
  7335. close();
  7336. return false;
  7337. }
  7338. return true;
  7339. }
  7340. DatagramSocket* DatagramSocket::waitForNextConnection() const
  7341. {
  7342. struct sockaddr address;
  7343. juce_socklen_t len = sizeof (sockaddr);
  7344. while (waitUntilReady (true, -1) == 1)
  7345. {
  7346. char buf[1];
  7347. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  7348. {
  7349. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7350. ntohs (((struct sockaddr_in*) &address)->sin_port),
  7351. -1, -1);
  7352. }
  7353. }
  7354. return 0;
  7355. }
  7356. int DatagramSocket::waitUntilReady (const bool readyForReading,
  7357. const int timeoutMsecs) const
  7358. {
  7359. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7360. : -1;
  7361. }
  7362. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7363. {
  7364. return connected ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7365. : -1;
  7366. }
  7367. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7368. {
  7369. // You need to call connect() first to set the server address..
  7370. jassert (serverAddress != 0 && connected);
  7371. return connected ? (int) sendto (handle, (const char*) sourceBuffer,
  7372. numBytesToWrite, 0,
  7373. (const struct sockaddr*) serverAddress,
  7374. sizeof (struct sockaddr_in))
  7375. : -1;
  7376. }
  7377. bool DatagramSocket::isLocal() const throw()
  7378. {
  7379. return hostName == "127.0.0.1";
  7380. }
  7381. #if JUCE_MSVC
  7382. #pragma warning (pop)
  7383. #endif
  7384. END_JUCE_NAMESPACE
  7385. /*** End of inlined file: juce_Socket.cpp ***/
  7386. /*** Start of inlined file: juce_URL.cpp ***/
  7387. BEGIN_JUCE_NAMESPACE
  7388. URL::URL()
  7389. {
  7390. }
  7391. URL::URL (const String& url_)
  7392. : url (url_)
  7393. {
  7394. int i = url.indexOfChar ('?');
  7395. if (i >= 0)
  7396. {
  7397. do
  7398. {
  7399. const int nextAmp = url.indexOfChar (i + 1, '&');
  7400. const int equalsPos = url.indexOfChar (i + 1, '=');
  7401. if (equalsPos > i + 1)
  7402. {
  7403. if (nextAmp < 0)
  7404. {
  7405. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7406. removeEscapeChars (url.substring (equalsPos + 1)));
  7407. }
  7408. else if (nextAmp > 0 && equalsPos < nextAmp)
  7409. {
  7410. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7411. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  7412. }
  7413. }
  7414. i = nextAmp;
  7415. }
  7416. while (i >= 0);
  7417. url = url.upToFirstOccurrenceOf ("?", false, false);
  7418. }
  7419. }
  7420. URL::URL (const URL& other)
  7421. : url (other.url),
  7422. postData (other.postData),
  7423. parameters (other.parameters),
  7424. filesToUpload (other.filesToUpload),
  7425. mimeTypes (other.mimeTypes)
  7426. {
  7427. }
  7428. URL& URL::operator= (const URL& other)
  7429. {
  7430. url = other.url;
  7431. postData = other.postData;
  7432. parameters = other.parameters;
  7433. filesToUpload = other.filesToUpload;
  7434. mimeTypes = other.mimeTypes;
  7435. return *this;
  7436. }
  7437. URL::~URL()
  7438. {
  7439. }
  7440. static const String getMangledParameters (const StringPairArray& parameters)
  7441. {
  7442. String p;
  7443. for (int i = 0; i < parameters.size(); ++i)
  7444. {
  7445. if (i > 0)
  7446. p << '&';
  7447. p << URL::addEscapeChars (parameters.getAllKeys() [i], true)
  7448. << '='
  7449. << URL::addEscapeChars (parameters.getAllValues() [i], true);
  7450. }
  7451. return p;
  7452. }
  7453. const String URL::toString (const bool includeGetParameters) const
  7454. {
  7455. if (includeGetParameters && parameters.size() > 0)
  7456. return url + "?" + getMangledParameters (parameters);
  7457. else
  7458. return url;
  7459. }
  7460. bool URL::isWellFormed() const
  7461. {
  7462. //xxx TODO
  7463. return url.isNotEmpty();
  7464. }
  7465. static int findStartOfDomain (const String& url)
  7466. {
  7467. int i = 0;
  7468. while (CharacterFunctions::isLetterOrDigit (url[i])
  7469. || CharacterFunctions::indexOfChar (L"+-.", url[i], false) >= 0)
  7470. ++i;
  7471. return url[i] == ':' ? i + 1 : 0;
  7472. }
  7473. const String URL::getDomain() const
  7474. {
  7475. int start = findStartOfDomain (url);
  7476. while (url[start] == '/')
  7477. ++start;
  7478. const int end1 = url.indexOfChar (start, '/');
  7479. const int end2 = url.indexOfChar (start, ':');
  7480. const int end = (end1 < 0 || end2 < 0) ? jmax (end1, end2)
  7481. : jmin (end1, end2);
  7482. return url.substring (start, end);
  7483. }
  7484. const String URL::getSubPath() const
  7485. {
  7486. int start = findStartOfDomain (url);
  7487. while (url[start] == '/')
  7488. ++start;
  7489. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7490. return startOfPath <= 0 ? String::empty
  7491. : url.substring (startOfPath);
  7492. }
  7493. const String URL::getScheme() const
  7494. {
  7495. return url.substring (0, findStartOfDomain (url) - 1);
  7496. }
  7497. const URL URL::withNewSubPath (const String& newPath) const
  7498. {
  7499. int start = findStartOfDomain (url);
  7500. while (url[start] == '/')
  7501. ++start;
  7502. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7503. URL u (*this);
  7504. if (startOfPath > 0)
  7505. u.url = url.substring (0, startOfPath);
  7506. if (! u.url.endsWithChar ('/'))
  7507. u.url << '/';
  7508. if (newPath.startsWithChar ('/'))
  7509. u.url << newPath.substring (1);
  7510. else
  7511. u.url << newPath;
  7512. return u;
  7513. }
  7514. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  7515. {
  7516. if (possibleURL.startsWithIgnoreCase ("http:")
  7517. || possibleURL.startsWithIgnoreCase ("ftp:"))
  7518. return true;
  7519. if (possibleURL.startsWithIgnoreCase ("file:")
  7520. || possibleURL.containsChar ('@')
  7521. || possibleURL.endsWithChar ('.')
  7522. || (! possibleURL.containsChar ('.')))
  7523. return false;
  7524. if (possibleURL.startsWithIgnoreCase ("www.")
  7525. && possibleURL.substring (5).containsChar ('.'))
  7526. return true;
  7527. const char* commonTLDs[] = { "com", "net", "org", "uk", "de", "fr", "jp" };
  7528. for (int i = 0; i < numElementsInArray (commonTLDs); ++i)
  7529. if ((possibleURL + "/").containsIgnoreCase ("." + String (commonTLDs[i]) + "/"))
  7530. return true;
  7531. return false;
  7532. }
  7533. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  7534. {
  7535. const int atSign = possibleEmailAddress.indexOfChar ('@');
  7536. return atSign > 0
  7537. && possibleEmailAddress.lastIndexOfChar ('.') > (atSign + 1)
  7538. && (! possibleEmailAddress.endsWithChar ('.'));
  7539. }
  7540. void* juce_openInternetFile (const String& url,
  7541. const String& headers,
  7542. const MemoryBlock& optionalPostData,
  7543. const bool isPost,
  7544. URL::OpenStreamProgressCallback* callback,
  7545. void* callbackContext,
  7546. int timeOutMs);
  7547. void juce_closeInternetFile (void* handle);
  7548. int juce_readFromInternetFile (void* handle, void* dest, int bytesToRead);
  7549. int juce_seekInInternetFile (void* handle, int newPosition);
  7550. int64 juce_getInternetFileContentLength (void* handle);
  7551. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers);
  7552. class WebInputStream : public InputStream
  7553. {
  7554. public:
  7555. WebInputStream (const URL& url,
  7556. const bool isPost_,
  7557. URL::OpenStreamProgressCallback* const progressCallback_,
  7558. void* const progressCallbackContext_,
  7559. const String& extraHeaders,
  7560. const int timeOutMs_,
  7561. StringPairArray* const responseHeaders)
  7562. : position (0),
  7563. finished (false),
  7564. isPost (isPost_),
  7565. progressCallback (progressCallback_),
  7566. progressCallbackContext (progressCallbackContext_),
  7567. timeOutMs (timeOutMs_)
  7568. {
  7569. server = url.toString (! isPost);
  7570. if (isPost_)
  7571. createHeadersAndPostData (url);
  7572. headers += extraHeaders;
  7573. if (! headers.endsWithChar ('\n'))
  7574. headers << "\r\n";
  7575. handle = juce_openInternetFile (server, headers, postData, isPost,
  7576. progressCallback_, progressCallbackContext_,
  7577. timeOutMs);
  7578. if (responseHeaders != 0)
  7579. juce_getInternetFileHeaders (handle, *responseHeaders);
  7580. }
  7581. ~WebInputStream()
  7582. {
  7583. juce_closeInternetFile (handle);
  7584. }
  7585. bool isError() const { return handle == 0; }
  7586. int64 getTotalLength() { return juce_getInternetFileContentLength (handle); }
  7587. bool isExhausted() { return finished; }
  7588. int64 getPosition() { return position; }
  7589. int read (void* dest, int bytes)
  7590. {
  7591. if (finished || isError())
  7592. {
  7593. return 0;
  7594. }
  7595. else
  7596. {
  7597. const int bytesRead = juce_readFromInternetFile (handle, dest, bytes);
  7598. position += bytesRead;
  7599. if (bytesRead == 0)
  7600. finished = true;
  7601. return bytesRead;
  7602. }
  7603. }
  7604. bool setPosition (int64 wantedPos)
  7605. {
  7606. if (wantedPos != position)
  7607. {
  7608. finished = false;
  7609. const int actualPos = juce_seekInInternetFile (handle, (int) wantedPos);
  7610. if (actualPos == wantedPos)
  7611. {
  7612. position = wantedPos;
  7613. }
  7614. else
  7615. {
  7616. if (wantedPos < position)
  7617. {
  7618. juce_closeInternetFile (handle);
  7619. position = 0;
  7620. finished = false;
  7621. handle = juce_openInternetFile (server, headers, postData, isPost,
  7622. progressCallback, progressCallbackContext,
  7623. timeOutMs);
  7624. }
  7625. skipNextBytes (wantedPos - position);
  7626. }
  7627. }
  7628. return true;
  7629. }
  7630. juce_UseDebuggingNewOperator
  7631. private:
  7632. String server, headers;
  7633. MemoryBlock postData;
  7634. int64 position;
  7635. bool finished;
  7636. const bool isPost;
  7637. void* handle;
  7638. URL::OpenStreamProgressCallback* const progressCallback;
  7639. void* const progressCallbackContext;
  7640. const int timeOutMs;
  7641. void createHeadersAndPostData (const URL& url)
  7642. {
  7643. MemoryOutputStream data (postData, false);
  7644. if (url.getFilesToUpload().size() > 0)
  7645. {
  7646. // need to upload some files, so do it as multi-part...
  7647. const String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  7648. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  7649. data << "--" << boundary;
  7650. int i;
  7651. for (i = 0; i < url.getParameters().size(); ++i)
  7652. {
  7653. data << "\r\nContent-Disposition: form-data; name=\""
  7654. << url.getParameters().getAllKeys() [i]
  7655. << "\"\r\n\r\n"
  7656. << url.getParameters().getAllValues() [i]
  7657. << "\r\n--"
  7658. << boundary;
  7659. }
  7660. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  7661. {
  7662. const File file (url.getFilesToUpload().getAllValues() [i]);
  7663. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  7664. data << "\r\nContent-Disposition: form-data; name=\"" << paramName
  7665. << "\"; filename=\"" << file.getFileName() << "\"\r\n";
  7666. const String mimeType (url.getMimeTypesOfUploadFiles()
  7667. .getValue (paramName, String::empty));
  7668. if (mimeType.isNotEmpty())
  7669. data << "Content-Type: " << mimeType << "\r\n";
  7670. data << "Content-Transfer-Encoding: binary\r\n\r\n"
  7671. << file << "\r\n--" << boundary;
  7672. }
  7673. data << "--\r\n";
  7674. data.flush();
  7675. }
  7676. else
  7677. {
  7678. data << getMangledParameters (url.getParameters())
  7679. << url.getPostData();
  7680. data.flush();
  7681. // just a short text attachment, so use simple url encoding..
  7682. headers = "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  7683. + String ((unsigned int) postData.getSize())
  7684. + "\r\n";
  7685. }
  7686. }
  7687. WebInputStream (const WebInputStream&);
  7688. WebInputStream& operator= (const WebInputStream&);
  7689. };
  7690. InputStream* URL::createInputStream (const bool usePostCommand,
  7691. OpenStreamProgressCallback* const progressCallback,
  7692. void* const progressCallbackContext,
  7693. const String& extraHeaders,
  7694. const int timeOutMs,
  7695. StringPairArray* const responseHeaders) const
  7696. {
  7697. ScopedPointer <WebInputStream> wi (new WebInputStream (*this, usePostCommand,
  7698. progressCallback, progressCallbackContext,
  7699. extraHeaders, timeOutMs, responseHeaders));
  7700. return wi->isError() ? 0 : wi.release();
  7701. }
  7702. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  7703. const bool usePostCommand) const
  7704. {
  7705. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7706. if (in != 0)
  7707. {
  7708. in->readIntoMemoryBlock (destData);
  7709. return true;
  7710. }
  7711. return false;
  7712. }
  7713. const String URL::readEntireTextStream (const bool usePostCommand) const
  7714. {
  7715. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7716. if (in != 0)
  7717. return in->readEntireStreamAsString();
  7718. return String::empty;
  7719. }
  7720. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  7721. {
  7722. XmlDocument doc (readEntireTextStream (usePostCommand));
  7723. return doc.getDocumentElement();
  7724. }
  7725. const URL URL::withParameter (const String& parameterName,
  7726. const String& parameterValue) const
  7727. {
  7728. URL u (*this);
  7729. u.parameters.set (parameterName, parameterValue);
  7730. return u;
  7731. }
  7732. const URL URL::withFileToUpload (const String& parameterName,
  7733. const File& fileToUpload,
  7734. const String& mimeType) const
  7735. {
  7736. jassert (mimeType.isNotEmpty()); // You need to supply a mime type!
  7737. URL u (*this);
  7738. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  7739. u.mimeTypes.set (parameterName, mimeType);
  7740. return u;
  7741. }
  7742. const URL URL::withPOSTData (const String& postData_) const
  7743. {
  7744. URL u (*this);
  7745. u.postData = postData_;
  7746. return u;
  7747. }
  7748. const StringPairArray& URL::getParameters() const
  7749. {
  7750. return parameters;
  7751. }
  7752. const StringPairArray& URL::getFilesToUpload() const
  7753. {
  7754. return filesToUpload;
  7755. }
  7756. const StringPairArray& URL::getMimeTypesOfUploadFiles() const
  7757. {
  7758. return mimeTypes;
  7759. }
  7760. const String URL::removeEscapeChars (const String& s)
  7761. {
  7762. String result (s.replaceCharacter ('+', ' '));
  7763. if (! result.containsChar ('%'))
  7764. return result;
  7765. // We need to operate on the string as raw UTF8 chars, and then recombine them into unicode
  7766. // after all the replacements have been made, so that multi-byte chars are handled.
  7767. Array<char> utf8 (result.toUTF8(), result.getNumBytesAsUTF8());
  7768. for (int i = 0; i < utf8.size(); ++i)
  7769. {
  7770. if (utf8.getUnchecked(i) == '%')
  7771. {
  7772. const int hexDigit1 = CharacterFunctions::getHexDigitValue (utf8 [i + 1]);
  7773. const int hexDigit2 = CharacterFunctions::getHexDigitValue (utf8 [i + 2]);
  7774. if (hexDigit1 >= 0 && hexDigit2 >= 0)
  7775. {
  7776. utf8.set (i, (char) ((hexDigit1 << 4) + hexDigit2));
  7777. utf8.removeRange (i + 1, 2);
  7778. }
  7779. }
  7780. }
  7781. return String::fromUTF8 (utf8.getRawDataPointer(), utf8.size());
  7782. }
  7783. const String URL::addEscapeChars (const String& s, const bool isParameter)
  7784. {
  7785. const char* const legalChars = isParameter ? "_-.*!'()"
  7786. : ",$_-.*!'()";
  7787. Array<char> utf8 (s.toUTF8(), s.getNumBytesAsUTF8());
  7788. for (int i = 0; i < utf8.size(); ++i)
  7789. {
  7790. const char c = utf8.getUnchecked(i);
  7791. if (! (CharacterFunctions::isLetterOrDigit (c)
  7792. || CharacterFunctions::indexOfChar (legalChars, c, false) >= 0))
  7793. {
  7794. if (c == ' ')
  7795. {
  7796. utf8.set (i, '+');
  7797. }
  7798. else
  7799. {
  7800. static const char* const hexDigits = "0123456789abcdef";
  7801. utf8.set (i, '%');
  7802. utf8.insert (++i, hexDigits [((uint8) c) >> 4]);
  7803. utf8.insert (++i, hexDigits [c & 15]);
  7804. }
  7805. }
  7806. }
  7807. return String::fromUTF8 (utf8.getRawDataPointer(), utf8.size());
  7808. }
  7809. bool URL::launchInDefaultBrowser() const
  7810. {
  7811. String u (toString (true));
  7812. if (u.containsChar ('@') && ! u.containsChar (':'))
  7813. u = "mailto:" + u;
  7814. return PlatformUtilities::openDocument (u, String::empty);
  7815. }
  7816. END_JUCE_NAMESPACE
  7817. /*** End of inlined file: juce_URL.cpp ***/
  7818. /*** Start of inlined file: juce_BufferedInputStream.cpp ***/
  7819. BEGIN_JUCE_NAMESPACE
  7820. BufferedInputStream::BufferedInputStream (InputStream* const source_,
  7821. const int bufferSize_,
  7822. const bool deleteSourceWhenDestroyed)
  7823. : source (source_),
  7824. sourceToDelete (deleteSourceWhenDestroyed ? source_ : 0),
  7825. bufferSize (jmax (256, bufferSize_)),
  7826. position (source_->getPosition()),
  7827. lastReadPos (0),
  7828. bufferOverlap (128)
  7829. {
  7830. const int sourceSize = (int) source_->getTotalLength();
  7831. if (sourceSize >= 0)
  7832. bufferSize = jmin (jmax (32, sourceSize), bufferSize);
  7833. bufferStart = position;
  7834. buffer.malloc (bufferSize);
  7835. }
  7836. BufferedInputStream::~BufferedInputStream()
  7837. {
  7838. }
  7839. int64 BufferedInputStream::getTotalLength()
  7840. {
  7841. return source->getTotalLength();
  7842. }
  7843. int64 BufferedInputStream::getPosition()
  7844. {
  7845. return position;
  7846. }
  7847. bool BufferedInputStream::setPosition (int64 newPosition)
  7848. {
  7849. position = jmax ((int64) 0, newPosition);
  7850. return true;
  7851. }
  7852. bool BufferedInputStream::isExhausted()
  7853. {
  7854. return (position >= lastReadPos)
  7855. && source->isExhausted();
  7856. }
  7857. void BufferedInputStream::ensureBuffered()
  7858. {
  7859. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  7860. if (position < bufferStart || position >= bufferEndOverlap)
  7861. {
  7862. int bytesRead;
  7863. if (position < lastReadPos
  7864. && position >= bufferEndOverlap
  7865. && position >= bufferStart)
  7866. {
  7867. const int bytesToKeep = (int) (lastReadPos - position);
  7868. memmove (buffer, buffer + (int) (position - bufferStart), bytesToKeep);
  7869. bufferStart = position;
  7870. bytesRead = source->read (buffer + bytesToKeep,
  7871. bufferSize - bytesToKeep);
  7872. lastReadPos += bytesRead;
  7873. bytesRead += bytesToKeep;
  7874. }
  7875. else
  7876. {
  7877. bufferStart = position;
  7878. source->setPosition (bufferStart);
  7879. bytesRead = source->read (buffer, bufferSize);
  7880. lastReadPos = bufferStart + bytesRead;
  7881. }
  7882. while (bytesRead < bufferSize)
  7883. buffer [bytesRead++] = 0;
  7884. }
  7885. }
  7886. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  7887. {
  7888. if (position >= bufferStart
  7889. && position + maxBytesToRead <= lastReadPos)
  7890. {
  7891. memcpy (destBuffer, buffer + (int) (position - bufferStart), maxBytesToRead);
  7892. position += maxBytesToRead;
  7893. return maxBytesToRead;
  7894. }
  7895. else
  7896. {
  7897. if (position < bufferStart || position >= lastReadPos)
  7898. ensureBuffered();
  7899. int bytesRead = 0;
  7900. while (maxBytesToRead > 0)
  7901. {
  7902. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  7903. if (bytesAvailable > 0)
  7904. {
  7905. memcpy (destBuffer, buffer + (int) (position - bufferStart), bytesAvailable);
  7906. maxBytesToRead -= bytesAvailable;
  7907. bytesRead += bytesAvailable;
  7908. position += bytesAvailable;
  7909. destBuffer = static_cast <char*> (destBuffer) + bytesAvailable;
  7910. }
  7911. const int64 oldLastReadPos = lastReadPos;
  7912. ensureBuffered();
  7913. if (oldLastReadPos == lastReadPos)
  7914. break; // if ensureBuffered() failed to read any more data, bail out
  7915. if (isExhausted())
  7916. break;
  7917. }
  7918. return bytesRead;
  7919. }
  7920. }
  7921. const String BufferedInputStream::readString()
  7922. {
  7923. if (position >= bufferStart
  7924. && position < lastReadPos)
  7925. {
  7926. const int maxChars = (int) (lastReadPos - position);
  7927. const char* const src = buffer + (int) (position - bufferStart);
  7928. for (int i = 0; i < maxChars; ++i)
  7929. {
  7930. if (src[i] == 0)
  7931. {
  7932. position += i + 1;
  7933. return String::fromUTF8 (src, i);
  7934. }
  7935. }
  7936. }
  7937. return InputStream::readString();
  7938. }
  7939. END_JUCE_NAMESPACE
  7940. /*** End of inlined file: juce_BufferedInputStream.cpp ***/
  7941. /*** Start of inlined file: juce_FileInputSource.cpp ***/
  7942. BEGIN_JUCE_NAMESPACE
  7943. FileInputSource::FileInputSource (const File& file_)
  7944. : file (file_)
  7945. {
  7946. }
  7947. FileInputSource::~FileInputSource()
  7948. {
  7949. }
  7950. InputStream* FileInputSource::createInputStream()
  7951. {
  7952. return file.createInputStream();
  7953. }
  7954. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  7955. {
  7956. return file.getSiblingFile (relatedItemPath).createInputStream();
  7957. }
  7958. int64 FileInputSource::hashCode() const
  7959. {
  7960. return file.hashCode();
  7961. }
  7962. END_JUCE_NAMESPACE
  7963. /*** End of inlined file: juce_FileInputSource.cpp ***/
  7964. /*** Start of inlined file: juce_MemoryInputStream.cpp ***/
  7965. BEGIN_JUCE_NAMESPACE
  7966. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  7967. const size_t sourceDataSize,
  7968. const bool keepInternalCopy)
  7969. : data (static_cast <const char*> (sourceData)),
  7970. dataSize (sourceDataSize),
  7971. position (0)
  7972. {
  7973. if (keepInternalCopy)
  7974. {
  7975. internalCopy.append (data, sourceDataSize);
  7976. data = static_cast <const char*> (internalCopy.getData());
  7977. }
  7978. }
  7979. MemoryInputStream::MemoryInputStream (const MemoryBlock& sourceData,
  7980. const bool keepInternalCopy)
  7981. : data (static_cast <const char*> (sourceData.getData())),
  7982. dataSize (sourceData.getSize()),
  7983. position (0)
  7984. {
  7985. if (keepInternalCopy)
  7986. {
  7987. internalCopy = sourceData;
  7988. data = static_cast <const char*> (internalCopy.getData());
  7989. }
  7990. }
  7991. MemoryInputStream::~MemoryInputStream()
  7992. {
  7993. }
  7994. int64 MemoryInputStream::getTotalLength()
  7995. {
  7996. return dataSize;
  7997. }
  7998. int MemoryInputStream::read (void* const buffer, const int howMany)
  7999. {
  8000. jassert (howMany >= 0);
  8001. const int num = jmin (howMany, (int) (dataSize - position));
  8002. memcpy (buffer, data + position, num);
  8003. position += num;
  8004. return (int) num;
  8005. }
  8006. bool MemoryInputStream::isExhausted()
  8007. {
  8008. return (position >= dataSize);
  8009. }
  8010. bool MemoryInputStream::setPosition (const int64 pos)
  8011. {
  8012. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  8013. return true;
  8014. }
  8015. int64 MemoryInputStream::getPosition()
  8016. {
  8017. return position;
  8018. }
  8019. #if JUCE_UNIT_TESTS
  8020. class MemoryStreamTests : public UnitTest
  8021. {
  8022. public:
  8023. MemoryStreamTests() : UnitTest ("MemoryInputStream & MemoryOutputStream") {}
  8024. void runTest()
  8025. {
  8026. beginTest ("Basics");
  8027. int randomInt = Random::getSystemRandom().nextInt();
  8028. int64 randomInt64 = Random::getSystemRandom().nextInt64();
  8029. double randomDouble = Random::getSystemRandom().nextDouble();
  8030. String randomString;
  8031. for (int i = 50; --i >= 0;)
  8032. randomString << (juce_wchar) (Random::getSystemRandom().nextInt() & 0xffff);
  8033. MemoryOutputStream mo;
  8034. mo.writeInt (randomInt);
  8035. mo.writeIntBigEndian (randomInt);
  8036. mo.writeCompressedInt (randomInt);
  8037. mo.writeString (randomString);
  8038. mo.writeInt64 (randomInt64);
  8039. mo.writeInt64BigEndian (randomInt64);
  8040. mo.writeDouble (randomDouble);
  8041. mo.writeDoubleBigEndian (randomDouble);
  8042. MemoryInputStream mi (mo.getData(), mo.getDataSize(), false);
  8043. expect (mi.readInt() == randomInt);
  8044. expect (mi.readIntBigEndian() == randomInt);
  8045. expect (mi.readCompressedInt() == randomInt);
  8046. expect (mi.readString() == randomString);
  8047. expect (mi.readInt64() == randomInt64);
  8048. expect (mi.readInt64BigEndian() == randomInt64);
  8049. expect (mi.readDouble() == randomDouble);
  8050. expect (mi.readDoubleBigEndian() == randomDouble);
  8051. }
  8052. };
  8053. static MemoryStreamTests memoryInputStreamUnitTests;
  8054. #endif
  8055. END_JUCE_NAMESPACE
  8056. /*** End of inlined file: juce_MemoryInputStream.cpp ***/
  8057. /*** Start of inlined file: juce_MemoryOutputStream.cpp ***/
  8058. BEGIN_JUCE_NAMESPACE
  8059. MemoryOutputStream::MemoryOutputStream (const size_t initialSize)
  8060. : data (internalBlock),
  8061. position (0),
  8062. size (0)
  8063. {
  8064. internalBlock.setSize (initialSize, false);
  8065. }
  8066. MemoryOutputStream::MemoryOutputStream (MemoryBlock& memoryBlockToWriteTo,
  8067. const bool appendToExistingBlockContent)
  8068. : data (memoryBlockToWriteTo),
  8069. position (0),
  8070. size (0)
  8071. {
  8072. if (appendToExistingBlockContent)
  8073. position = size = memoryBlockToWriteTo.getSize();
  8074. }
  8075. MemoryOutputStream::~MemoryOutputStream()
  8076. {
  8077. flush();
  8078. }
  8079. void MemoryOutputStream::flush()
  8080. {
  8081. if (&data != &internalBlock)
  8082. data.setSize (size, false);
  8083. }
  8084. void MemoryOutputStream::preallocate (const size_t bytesToPreallocate)
  8085. {
  8086. data.ensureSize (bytesToPreallocate + 1);
  8087. }
  8088. void MemoryOutputStream::reset() throw()
  8089. {
  8090. position = 0;
  8091. size = 0;
  8092. }
  8093. bool MemoryOutputStream::write (const void* const buffer, int howMany)
  8094. {
  8095. if (howMany > 0)
  8096. {
  8097. const size_t storageNeeded = position + howMany;
  8098. if (storageNeeded >= data.getSize())
  8099. data.ensureSize ((storageNeeded + jmin (storageNeeded / 2, (size_t) (1024 * 1024)) + 32) & ~31);
  8100. memcpy (static_cast<char*> (data.getData()) + position, buffer, howMany);
  8101. position += howMany;
  8102. size = jmax (size, position);
  8103. }
  8104. return true;
  8105. }
  8106. const void* MemoryOutputStream::getData() const throw()
  8107. {
  8108. void* const d = data.getData();
  8109. if (data.getSize() > size)
  8110. static_cast <char*> (d) [size] = 0;
  8111. return d;
  8112. }
  8113. bool MemoryOutputStream::setPosition (int64 newPosition)
  8114. {
  8115. if (newPosition <= (int64) size)
  8116. {
  8117. // ok to seek backwards
  8118. position = jlimit ((size_t) 0, size, (size_t) newPosition);
  8119. return true;
  8120. }
  8121. else
  8122. {
  8123. // trying to make it bigger isn't a good thing to do..
  8124. return false;
  8125. }
  8126. }
  8127. int MemoryOutputStream::writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite)
  8128. {
  8129. // before writing from an input, see if we can preallocate to make it more efficient..
  8130. int64 availableData = source.getTotalLength() - source.getPosition();
  8131. if (availableData > 0)
  8132. {
  8133. if (maxNumBytesToWrite > 0 && maxNumBytesToWrite < availableData)
  8134. availableData = maxNumBytesToWrite;
  8135. preallocate (data.getSize() + (size_t) maxNumBytesToWrite);
  8136. }
  8137. return OutputStream::writeFromInputStream (source, maxNumBytesToWrite);
  8138. }
  8139. const String MemoryOutputStream::toUTF8() const
  8140. {
  8141. return String (static_cast <const char*> (getData()), getDataSize());
  8142. }
  8143. const String MemoryOutputStream::toString() const
  8144. {
  8145. return String::createStringFromData (getData(), getDataSize());
  8146. }
  8147. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead)
  8148. {
  8149. stream.write (streamToRead.getData(), streamToRead.getDataSize());
  8150. return stream;
  8151. }
  8152. END_JUCE_NAMESPACE
  8153. /*** End of inlined file: juce_MemoryOutputStream.cpp ***/
  8154. /*** Start of inlined file: juce_SubregionStream.cpp ***/
  8155. BEGIN_JUCE_NAMESPACE
  8156. SubregionStream::SubregionStream (InputStream* const sourceStream,
  8157. const int64 startPositionInSourceStream_,
  8158. const int64 lengthOfSourceStream_,
  8159. const bool deleteSourceWhenDestroyed)
  8160. : source (sourceStream),
  8161. startPositionInSourceStream (startPositionInSourceStream_),
  8162. lengthOfSourceStream (lengthOfSourceStream_)
  8163. {
  8164. if (deleteSourceWhenDestroyed)
  8165. sourceToDelete = source;
  8166. setPosition (0);
  8167. }
  8168. SubregionStream::~SubregionStream()
  8169. {
  8170. }
  8171. int64 SubregionStream::getTotalLength()
  8172. {
  8173. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  8174. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  8175. : srcLen;
  8176. }
  8177. int64 SubregionStream::getPosition()
  8178. {
  8179. return source->getPosition() - startPositionInSourceStream;
  8180. }
  8181. bool SubregionStream::setPosition (int64 newPosition)
  8182. {
  8183. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  8184. }
  8185. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  8186. {
  8187. if (lengthOfSourceStream < 0)
  8188. {
  8189. return source->read (destBuffer, maxBytesToRead);
  8190. }
  8191. else
  8192. {
  8193. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  8194. if (maxBytesToRead <= 0)
  8195. return 0;
  8196. return source->read (destBuffer, maxBytesToRead);
  8197. }
  8198. }
  8199. bool SubregionStream::isExhausted()
  8200. {
  8201. if (lengthOfSourceStream >= 0)
  8202. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  8203. else
  8204. return source->isExhausted();
  8205. }
  8206. END_JUCE_NAMESPACE
  8207. /*** End of inlined file: juce_SubregionStream.cpp ***/
  8208. /*** Start of inlined file: juce_PerformanceCounter.cpp ***/
  8209. BEGIN_JUCE_NAMESPACE
  8210. PerformanceCounter::PerformanceCounter (const String& name_,
  8211. int runsPerPrintout,
  8212. const File& loggingFile)
  8213. : name (name_),
  8214. numRuns (0),
  8215. runsPerPrint (runsPerPrintout),
  8216. totalTime (0),
  8217. outputFile (loggingFile)
  8218. {
  8219. if (outputFile != File::nonexistent)
  8220. {
  8221. String s ("**** Counter for \"");
  8222. s << name_ << "\" started at: "
  8223. << Time::getCurrentTime().toString (true, true)
  8224. << "\r\n";
  8225. outputFile.appendText (s, false, false);
  8226. }
  8227. }
  8228. PerformanceCounter::~PerformanceCounter()
  8229. {
  8230. printStatistics();
  8231. }
  8232. void PerformanceCounter::start()
  8233. {
  8234. started = Time::getHighResolutionTicks();
  8235. }
  8236. void PerformanceCounter::stop()
  8237. {
  8238. const int64 now = Time::getHighResolutionTicks();
  8239. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  8240. if (++numRuns == runsPerPrint)
  8241. printStatistics();
  8242. }
  8243. void PerformanceCounter::printStatistics()
  8244. {
  8245. if (numRuns > 0)
  8246. {
  8247. String s ("Performance count for \"");
  8248. s << name << "\" - average over " << numRuns << " run(s) = ";
  8249. const int micros = (int) (totalTime * (1000.0 / numRuns));
  8250. if (micros > 10000)
  8251. s << (micros/1000) << " millisecs";
  8252. else
  8253. s << micros << " microsecs";
  8254. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  8255. Logger::outputDebugString (s);
  8256. s << "\r\n";
  8257. if (outputFile != File::nonexistent)
  8258. outputFile.appendText (s, false, false);
  8259. numRuns = 0;
  8260. totalTime = 0;
  8261. }
  8262. }
  8263. END_JUCE_NAMESPACE
  8264. /*** End of inlined file: juce_PerformanceCounter.cpp ***/
  8265. /*** Start of inlined file: juce_Uuid.cpp ***/
  8266. BEGIN_JUCE_NAMESPACE
  8267. Uuid::Uuid()
  8268. {
  8269. // Mix up any available MAC addresses with some time-based pseudo-random numbers
  8270. // to make it very very unlikely that two UUIDs will ever be the same..
  8271. static int64 macAddresses[2];
  8272. static bool hasCheckedMacAddresses = false;
  8273. if (! hasCheckedMacAddresses)
  8274. {
  8275. hasCheckedMacAddresses = true;
  8276. SystemStats::getMACAddresses (macAddresses, 2);
  8277. }
  8278. value.asInt64[0] = macAddresses[0];
  8279. value.asInt64[1] = macAddresses[1];
  8280. // We'll use both a local RNG that is re-seeded, plus the shared RNG,
  8281. // whose seed will carry over between calls to this method.
  8282. Random r (macAddresses[0] ^ macAddresses[1]
  8283. ^ Random::getSystemRandom().nextInt64());
  8284. for (int i = 4; --i >= 0;)
  8285. {
  8286. r.setSeedRandomly(); // calling this repeatedly improves randomness
  8287. value.asInt[i] ^= r.nextInt();
  8288. value.asInt[i] ^= Random::getSystemRandom().nextInt();
  8289. }
  8290. }
  8291. Uuid::~Uuid() throw()
  8292. {
  8293. }
  8294. Uuid::Uuid (const Uuid& other)
  8295. : value (other.value)
  8296. {
  8297. }
  8298. Uuid& Uuid::operator= (const Uuid& other)
  8299. {
  8300. value = other.value;
  8301. return *this;
  8302. }
  8303. bool Uuid::operator== (const Uuid& other) const
  8304. {
  8305. return value.asInt64[0] == other.value.asInt64[0]
  8306. && value.asInt64[1] == other.value.asInt64[1];
  8307. }
  8308. bool Uuid::operator!= (const Uuid& other) const
  8309. {
  8310. return ! operator== (other);
  8311. }
  8312. bool Uuid::isNull() const throw()
  8313. {
  8314. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  8315. }
  8316. const String Uuid::toString() const
  8317. {
  8318. return String::toHexString (value.asBytes, sizeof (value.asBytes), 0);
  8319. }
  8320. Uuid::Uuid (const String& uuidString)
  8321. {
  8322. operator= (uuidString);
  8323. }
  8324. Uuid& Uuid::operator= (const String& uuidString)
  8325. {
  8326. MemoryBlock mb;
  8327. mb.loadFromHexString (uuidString);
  8328. mb.ensureSize (sizeof (value.asBytes), true);
  8329. mb.copyTo (value.asBytes, 0, sizeof (value.asBytes));
  8330. return *this;
  8331. }
  8332. Uuid::Uuid (const uint8* const rawData)
  8333. {
  8334. operator= (rawData);
  8335. }
  8336. Uuid& Uuid::operator= (const uint8* const rawData)
  8337. {
  8338. if (rawData != 0)
  8339. memcpy (value.asBytes, rawData, sizeof (value.asBytes));
  8340. else
  8341. zeromem (value.asBytes, sizeof (value.asBytes));
  8342. return *this;
  8343. }
  8344. END_JUCE_NAMESPACE
  8345. /*** End of inlined file: juce_Uuid.cpp ***/
  8346. /*** Start of inlined file: juce_ZipFile.cpp ***/
  8347. BEGIN_JUCE_NAMESPACE
  8348. class ZipFile::ZipEntryInfo
  8349. {
  8350. public:
  8351. ZipFile::ZipEntry entry;
  8352. int streamOffset;
  8353. int compressedSize;
  8354. bool compressed;
  8355. };
  8356. class ZipFile::ZipInputStream : public InputStream
  8357. {
  8358. public:
  8359. ZipInputStream (ZipFile& file_, ZipFile::ZipEntryInfo& zei)
  8360. : file (file_),
  8361. zipEntryInfo (zei),
  8362. pos (0),
  8363. headerSize (0),
  8364. inputStream (0)
  8365. {
  8366. inputStream = file_.inputStream;
  8367. if (file_.inputSource != 0)
  8368. {
  8369. inputStream = file.inputSource->createInputStream();
  8370. }
  8371. else
  8372. {
  8373. #if JUCE_DEBUG
  8374. file_.numOpenStreams++;
  8375. #endif
  8376. }
  8377. char buffer [30];
  8378. if (inputStream != 0
  8379. && inputStream->setPosition (zei.streamOffset)
  8380. && inputStream->read (buffer, 30) == 30
  8381. && ByteOrder::littleEndianInt (buffer) == 0x04034b50)
  8382. {
  8383. headerSize = 30 + ByteOrder::littleEndianShort (buffer + 26)
  8384. + ByteOrder::littleEndianShort (buffer + 28);
  8385. }
  8386. }
  8387. ~ZipInputStream()
  8388. {
  8389. #if JUCE_DEBUG
  8390. if (inputStream != 0 && inputStream == file.inputStream)
  8391. file.numOpenStreams--;
  8392. #endif
  8393. if (inputStream != file.inputStream)
  8394. delete inputStream;
  8395. }
  8396. int64 getTotalLength()
  8397. {
  8398. return zipEntryInfo.compressedSize;
  8399. }
  8400. int read (void* buffer, int howMany)
  8401. {
  8402. if (headerSize <= 0)
  8403. return 0;
  8404. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  8405. if (inputStream == 0)
  8406. return 0;
  8407. int num;
  8408. if (inputStream == file.inputStream)
  8409. {
  8410. const ScopedLock sl (file.lock);
  8411. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8412. num = inputStream->read (buffer, howMany);
  8413. }
  8414. else
  8415. {
  8416. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8417. num = inputStream->read (buffer, howMany);
  8418. }
  8419. pos += num;
  8420. return num;
  8421. }
  8422. bool isExhausted()
  8423. {
  8424. return headerSize <= 0 || pos >= zipEntryInfo.compressedSize;
  8425. }
  8426. int64 getPosition()
  8427. {
  8428. return pos;
  8429. }
  8430. bool setPosition (int64 newPos)
  8431. {
  8432. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  8433. return true;
  8434. }
  8435. private:
  8436. ZipFile& file;
  8437. ZipEntryInfo zipEntryInfo;
  8438. int64 pos;
  8439. int headerSize;
  8440. InputStream* inputStream;
  8441. ZipInputStream (const ZipInputStream&);
  8442. ZipInputStream& operator= (const ZipInputStream&);
  8443. };
  8444. ZipFile::ZipFile (InputStream* const source_, const bool deleteStreamWhenDestroyed)
  8445. : inputStream (source_)
  8446. #if JUCE_DEBUG
  8447. , numOpenStreams (0)
  8448. #endif
  8449. {
  8450. if (deleteStreamWhenDestroyed)
  8451. streamToDelete = inputStream;
  8452. init();
  8453. }
  8454. ZipFile::ZipFile (const File& file)
  8455. : inputStream (0)
  8456. #if JUCE_DEBUG
  8457. , numOpenStreams (0)
  8458. #endif
  8459. {
  8460. inputSource = new FileInputSource (file);
  8461. init();
  8462. }
  8463. ZipFile::ZipFile (InputSource* const inputSource_)
  8464. : inputStream (0),
  8465. inputSource (inputSource_)
  8466. #if JUCE_DEBUG
  8467. , numOpenStreams (0)
  8468. #endif
  8469. {
  8470. init();
  8471. }
  8472. ZipFile::~ZipFile()
  8473. {
  8474. #if JUCE_DEBUG
  8475. entries.clear();
  8476. // If you hit this assertion, it means you've created a stream to read
  8477. // one of the items in the zipfile, but you've forgotten to delete that
  8478. // stream object before deleting the file.. Streams can't be kept open
  8479. // after the file is deleted because they need to share the input
  8480. // stream that the file uses to read itself.
  8481. jassert (numOpenStreams == 0);
  8482. #endif
  8483. }
  8484. int ZipFile::getNumEntries() const throw()
  8485. {
  8486. return entries.size();
  8487. }
  8488. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  8489. {
  8490. ZipEntryInfo* const zei = entries [index];
  8491. return zei != 0 ? &(zei->entry) : 0;
  8492. }
  8493. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  8494. {
  8495. for (int i = 0; i < entries.size(); ++i)
  8496. if (entries.getUnchecked (i)->entry.filename == fileName)
  8497. return i;
  8498. return -1;
  8499. }
  8500. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  8501. {
  8502. return getEntry (getIndexOfFileName (fileName));
  8503. }
  8504. InputStream* ZipFile::createStreamForEntry (const int index)
  8505. {
  8506. ZipEntryInfo* const zei = entries[index];
  8507. InputStream* stream = 0;
  8508. if (zei != 0)
  8509. {
  8510. stream = new ZipInputStream (*this, *zei);
  8511. if (zei->compressed)
  8512. {
  8513. stream = new GZIPDecompressorInputStream (stream, true, true,
  8514. zei->entry.uncompressedSize);
  8515. // (much faster to unzip in big blocks using a buffer..)
  8516. stream = new BufferedInputStream (stream, 32768, true);
  8517. }
  8518. }
  8519. return stream;
  8520. }
  8521. class ZipFile::ZipFilenameComparator
  8522. {
  8523. public:
  8524. int compareElements (const ZipFile::ZipEntryInfo* first, const ZipFile::ZipEntryInfo* second)
  8525. {
  8526. return first->entry.filename.compare (second->entry.filename);
  8527. }
  8528. };
  8529. void ZipFile::sortEntriesByFilename()
  8530. {
  8531. ZipFilenameComparator sorter;
  8532. entries.sort (sorter);
  8533. }
  8534. void ZipFile::init()
  8535. {
  8536. ScopedPointer <InputStream> toDelete;
  8537. InputStream* in = inputStream;
  8538. if (inputSource != 0)
  8539. {
  8540. in = inputSource->createInputStream();
  8541. toDelete = in;
  8542. }
  8543. if (in != 0)
  8544. {
  8545. int numEntries = 0;
  8546. int pos = findEndOfZipEntryTable (in, numEntries);
  8547. if (pos >= 0 && pos < in->getTotalLength())
  8548. {
  8549. const int size = (int) (in->getTotalLength() - pos);
  8550. in->setPosition (pos);
  8551. MemoryBlock headerData;
  8552. if (in->readIntoMemoryBlock (headerData, size) == size)
  8553. {
  8554. pos = 0;
  8555. for (int i = 0; i < numEntries; ++i)
  8556. {
  8557. if (pos + 46 > size)
  8558. break;
  8559. const char* const buffer = static_cast <const char*> (headerData.getData()) + pos;
  8560. const int fileNameLen = ByteOrder::littleEndianShort (buffer + 28);
  8561. if (pos + 46 + fileNameLen > size)
  8562. break;
  8563. ZipEntryInfo* const zei = new ZipEntryInfo();
  8564. zei->entry.filename = String::fromUTF8 (buffer + 46, fileNameLen);
  8565. const int time = ByteOrder::littleEndianShort (buffer + 12);
  8566. const int date = ByteOrder::littleEndianShort (buffer + 14);
  8567. const int year = 1980 + (date >> 9);
  8568. const int month = ((date >> 5) & 15) - 1;
  8569. const int day = date & 31;
  8570. const int hours = time >> 11;
  8571. const int minutes = (time >> 5) & 63;
  8572. const int seconds = (time & 31) << 1;
  8573. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  8574. zei->compressed = ByteOrder::littleEndianShort (buffer + 10) != 0;
  8575. zei->compressedSize = ByteOrder::littleEndianInt (buffer + 20);
  8576. zei->entry.uncompressedSize = ByteOrder::littleEndianInt (buffer + 24);
  8577. zei->streamOffset = ByteOrder::littleEndianInt (buffer + 42);
  8578. entries.add (zei);
  8579. pos += 46 + fileNameLen
  8580. + ByteOrder::littleEndianShort (buffer + 30)
  8581. + ByteOrder::littleEndianShort (buffer + 32);
  8582. }
  8583. }
  8584. }
  8585. }
  8586. }
  8587. int ZipFile::findEndOfZipEntryTable (InputStream* input, int& numEntries)
  8588. {
  8589. BufferedInputStream in (input, 8192, false);
  8590. in.setPosition (in.getTotalLength());
  8591. int64 pos = in.getPosition();
  8592. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  8593. char buffer [32];
  8594. zeromem (buffer, sizeof (buffer));
  8595. while (pos > lowestPos)
  8596. {
  8597. in.setPosition (pos - 22);
  8598. pos = in.getPosition();
  8599. memcpy (buffer + 22, buffer, 4);
  8600. if (in.read (buffer, 22) != 22)
  8601. return 0;
  8602. for (int i = 0; i < 22; ++i)
  8603. {
  8604. if (ByteOrder::littleEndianInt (buffer + i) == 0x06054b50)
  8605. {
  8606. in.setPosition (pos + i);
  8607. in.read (buffer, 22);
  8608. numEntries = ByteOrder::littleEndianShort (buffer + 10);
  8609. return ByteOrder::littleEndianInt (buffer + 16);
  8610. }
  8611. }
  8612. }
  8613. return 0;
  8614. }
  8615. bool ZipFile::uncompressTo (const File& targetDirectory,
  8616. const bool shouldOverwriteFiles)
  8617. {
  8618. for (int i = 0; i < entries.size(); ++i)
  8619. if (! uncompressEntry (i, targetDirectory, shouldOverwriteFiles))
  8620. return false;
  8621. return true;
  8622. }
  8623. bool ZipFile::uncompressEntry (const int index,
  8624. const File& targetDirectory,
  8625. bool shouldOverwriteFiles)
  8626. {
  8627. const ZipEntryInfo* zei = entries [index];
  8628. if (zei != 0)
  8629. {
  8630. const File targetFile (targetDirectory.getChildFile (zei->entry.filename));
  8631. if (zei->entry.filename.endsWithChar ('/'))
  8632. {
  8633. return targetFile.createDirectory(); // (entry is a directory, not a file)
  8634. }
  8635. else
  8636. {
  8637. ScopedPointer<InputStream> in (createStreamForEntry (index));
  8638. if (in != 0)
  8639. {
  8640. if (shouldOverwriteFiles && ! targetFile.deleteFile())
  8641. return false;
  8642. if ((! targetFile.exists()) && targetFile.getParentDirectory().createDirectory())
  8643. {
  8644. ScopedPointer<FileOutputStream> out (targetFile.createOutputStream());
  8645. if (out != 0)
  8646. {
  8647. out->writeFromInputStream (*in, -1);
  8648. out = 0;
  8649. targetFile.setCreationTime (zei->entry.fileTime);
  8650. targetFile.setLastModificationTime (zei->entry.fileTime);
  8651. targetFile.setLastAccessTime (zei->entry.fileTime);
  8652. return true;
  8653. }
  8654. }
  8655. }
  8656. }
  8657. }
  8658. return false;
  8659. }
  8660. END_JUCE_NAMESPACE
  8661. /*** End of inlined file: juce_ZipFile.cpp ***/
  8662. /*** Start of inlined file: juce_CharacterFunctions.cpp ***/
  8663. #if JUCE_MSVC
  8664. #pragma warning (push)
  8665. #pragma warning (disable: 4514 4996)
  8666. #endif
  8667. #include <cwctype>
  8668. #include <cctype>
  8669. #include <ctime>
  8670. BEGIN_JUCE_NAMESPACE
  8671. int CharacterFunctions::length (const char* const s) throw()
  8672. {
  8673. return (int) strlen (s);
  8674. }
  8675. int CharacterFunctions::length (const juce_wchar* const s) throw()
  8676. {
  8677. return (int) wcslen (s);
  8678. }
  8679. void CharacterFunctions::copy (char* dest, const char* src, const int maxChars) throw()
  8680. {
  8681. strncpy (dest, src, maxChars);
  8682. }
  8683. void CharacterFunctions::copy (juce_wchar* dest, const juce_wchar* src, int maxChars) throw()
  8684. {
  8685. wcsncpy (dest, src, maxChars);
  8686. }
  8687. void CharacterFunctions::copy (juce_wchar* dest, const char* src, const int maxChars) throw()
  8688. {
  8689. mbstowcs (dest, src, maxChars);
  8690. }
  8691. void CharacterFunctions::copy (char* dest, const juce_wchar* src, const int maxChars) throw()
  8692. {
  8693. wcstombs (dest, src, maxChars);
  8694. }
  8695. int CharacterFunctions::bytesRequiredForCopy (const juce_wchar* src) throw()
  8696. {
  8697. return (int) wcstombs (0, src, 0);
  8698. }
  8699. void CharacterFunctions::append (char* dest, const char* src) throw()
  8700. {
  8701. strcat (dest, src);
  8702. }
  8703. void CharacterFunctions::append (juce_wchar* dest, const juce_wchar* src) throw()
  8704. {
  8705. wcscat (dest, src);
  8706. }
  8707. int CharacterFunctions::compare (const char* const s1, const char* const s2) throw()
  8708. {
  8709. return strcmp (s1, s2);
  8710. }
  8711. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2) throw()
  8712. {
  8713. jassert (s1 != 0 && s2 != 0);
  8714. return wcscmp (s1, s2);
  8715. }
  8716. int CharacterFunctions::compare (const char* const s1, const char* const s2, const int maxChars) throw()
  8717. {
  8718. jassert (s1 != 0 && s2 != 0);
  8719. return strncmp (s1, s2, maxChars);
  8720. }
  8721. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  8722. {
  8723. jassert (s1 != 0 && s2 != 0);
  8724. return wcsncmp (s1, s2, maxChars);
  8725. }
  8726. int CharacterFunctions::compare (const juce_wchar* s1, const char* s2) throw()
  8727. {
  8728. jassert (s1 != 0 && s2 != 0);
  8729. for (;;)
  8730. {
  8731. const int diff = (int) (*s1 - (juce_wchar) (unsigned char) *s2);
  8732. if (diff != 0)
  8733. return diff;
  8734. else if (*s1 == 0)
  8735. break;
  8736. ++s1;
  8737. ++s2;
  8738. }
  8739. return 0;
  8740. }
  8741. int CharacterFunctions::compare (const char* s1, const juce_wchar* s2) throw()
  8742. {
  8743. return -compare (s2, s1);
  8744. }
  8745. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2) throw()
  8746. {
  8747. jassert (s1 != 0 && s2 != 0);
  8748. #if JUCE_WINDOWS
  8749. return stricmp (s1, s2);
  8750. #else
  8751. return strcasecmp (s1, s2);
  8752. #endif
  8753. }
  8754. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw()
  8755. {
  8756. jassert (s1 != 0 && s2 != 0);
  8757. #if JUCE_WINDOWS
  8758. return _wcsicmp (s1, s2);
  8759. #else
  8760. for (;;)
  8761. {
  8762. if (*s1 != *s2)
  8763. {
  8764. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8765. if (diff != 0)
  8766. return diff < 0 ? -1 : 1;
  8767. }
  8768. else if (*s1 == 0)
  8769. break;
  8770. ++s1;
  8771. ++s2;
  8772. }
  8773. return 0;
  8774. #endif
  8775. }
  8776. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const char* s2) throw()
  8777. {
  8778. jassert (s1 != 0 && s2 != 0);
  8779. for (;;)
  8780. {
  8781. if (*s1 != *s2)
  8782. {
  8783. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8784. if (diff != 0)
  8785. return diff < 0 ? -1 : 1;
  8786. }
  8787. else if (*s1 == 0)
  8788. break;
  8789. ++s1;
  8790. ++s2;
  8791. }
  8792. return 0;
  8793. }
  8794. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw()
  8795. {
  8796. jassert (s1 != 0 && s2 != 0);
  8797. #if JUCE_WINDOWS
  8798. return strnicmp (s1, s2, maxChars);
  8799. #else
  8800. return strncasecmp (s1, s2, maxChars);
  8801. #endif
  8802. }
  8803. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  8804. {
  8805. jassert (s1 != 0 && s2 != 0);
  8806. #if JUCE_WINDOWS
  8807. return _wcsnicmp (s1, s2, maxChars);
  8808. #else
  8809. while (--maxChars >= 0)
  8810. {
  8811. if (*s1 != *s2)
  8812. {
  8813. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8814. if (diff != 0)
  8815. return diff < 0 ? -1 : 1;
  8816. }
  8817. else if (*s1 == 0)
  8818. break;
  8819. ++s1;
  8820. ++s2;
  8821. }
  8822. return 0;
  8823. #endif
  8824. }
  8825. const char* CharacterFunctions::find (const char* const haystack, const char* const needle) throw()
  8826. {
  8827. return strstr (haystack, needle);
  8828. }
  8829. const juce_wchar* CharacterFunctions::find (const juce_wchar* haystack, const juce_wchar* const needle) throw()
  8830. {
  8831. return wcsstr (haystack, needle);
  8832. }
  8833. int CharacterFunctions::indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw()
  8834. {
  8835. if (haystack != 0)
  8836. {
  8837. int i = 0;
  8838. if (ignoreCase)
  8839. {
  8840. const char n1 = toLowerCase (needle);
  8841. const char n2 = toUpperCase (needle);
  8842. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  8843. {
  8844. while (haystack[i] != 0)
  8845. {
  8846. if (haystack[i] == n1 || haystack[i] == n2)
  8847. return i;
  8848. ++i;
  8849. }
  8850. return -1;
  8851. }
  8852. jassert (n1 == needle);
  8853. }
  8854. while (haystack[i] != 0)
  8855. {
  8856. if (haystack[i] == needle)
  8857. return i;
  8858. ++i;
  8859. }
  8860. }
  8861. return -1;
  8862. }
  8863. int CharacterFunctions::indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw()
  8864. {
  8865. if (haystack != 0)
  8866. {
  8867. int i = 0;
  8868. if (ignoreCase)
  8869. {
  8870. const juce_wchar n1 = toLowerCase (needle);
  8871. const juce_wchar n2 = toUpperCase (needle);
  8872. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  8873. {
  8874. while (haystack[i] != 0)
  8875. {
  8876. if (haystack[i] == n1 || haystack[i] == n2)
  8877. return i;
  8878. ++i;
  8879. }
  8880. return -1;
  8881. }
  8882. jassert (n1 == needle);
  8883. }
  8884. while (haystack[i] != 0)
  8885. {
  8886. if (haystack[i] == needle)
  8887. return i;
  8888. ++i;
  8889. }
  8890. }
  8891. return -1;
  8892. }
  8893. int CharacterFunctions::indexOfCharFast (const char* const haystack, const char needle) throw()
  8894. {
  8895. jassert (haystack != 0);
  8896. int i = 0;
  8897. while (haystack[i] != 0)
  8898. {
  8899. if (haystack[i] == needle)
  8900. return i;
  8901. ++i;
  8902. }
  8903. return -1;
  8904. }
  8905. int CharacterFunctions::indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw()
  8906. {
  8907. jassert (haystack != 0);
  8908. int i = 0;
  8909. while (haystack[i] != 0)
  8910. {
  8911. if (haystack[i] == needle)
  8912. return i;
  8913. ++i;
  8914. }
  8915. return -1;
  8916. }
  8917. int CharacterFunctions::getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw()
  8918. {
  8919. return allowedChars == 0 ? 0 : (int) strspn (text, allowedChars);
  8920. }
  8921. int CharacterFunctions::getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw()
  8922. {
  8923. if (allowedChars == 0)
  8924. return 0;
  8925. int i = 0;
  8926. for (;;)
  8927. {
  8928. if (indexOfCharFast (allowedChars, text[i]) < 0)
  8929. break;
  8930. ++i;
  8931. }
  8932. return i;
  8933. }
  8934. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  8935. {
  8936. return (int) strftime (dest, maxChars, format, tm);
  8937. }
  8938. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  8939. {
  8940. return (int) wcsftime (dest, maxChars, format, tm);
  8941. }
  8942. int CharacterFunctions::getIntValue (const char* const s) throw()
  8943. {
  8944. return atoi (s);
  8945. }
  8946. int CharacterFunctions::getIntValue (const juce_wchar* s) throw()
  8947. {
  8948. #if JUCE_WINDOWS
  8949. return _wtoi (s);
  8950. #else
  8951. int v = 0;
  8952. while (isWhitespace (*s))
  8953. ++s;
  8954. const bool isNeg = *s == '-';
  8955. if (isNeg)
  8956. ++s;
  8957. for (;;)
  8958. {
  8959. const wchar_t c = *s++;
  8960. if (c >= '0' && c <= '9')
  8961. v = v * 10 + (int) (c - '0');
  8962. else
  8963. break;
  8964. }
  8965. return isNeg ? -v : v;
  8966. #endif
  8967. }
  8968. int64 CharacterFunctions::getInt64Value (const char* s) throw()
  8969. {
  8970. #if JUCE_LINUX
  8971. return atoll (s);
  8972. #elif JUCE_WINDOWS
  8973. return _atoi64 (s);
  8974. #else
  8975. int64 v = 0;
  8976. while (isWhitespace (*s))
  8977. ++s;
  8978. const bool isNeg = *s == '-';
  8979. if (isNeg)
  8980. ++s;
  8981. for (;;)
  8982. {
  8983. const char c = *s++;
  8984. if (c >= '0' && c <= '9')
  8985. v = v * 10 + (int64) (c - '0');
  8986. else
  8987. break;
  8988. }
  8989. return isNeg ? -v : v;
  8990. #endif
  8991. }
  8992. int64 CharacterFunctions::getInt64Value (const juce_wchar* s) throw()
  8993. {
  8994. #if JUCE_WINDOWS
  8995. return _wtoi64 (s);
  8996. #else
  8997. int64 v = 0;
  8998. while (isWhitespace (*s))
  8999. ++s;
  9000. const bool isNeg = *s == '-';
  9001. if (isNeg)
  9002. ++s;
  9003. for (;;)
  9004. {
  9005. const juce_wchar c = *s++;
  9006. if (c >= '0' && c <= '9')
  9007. v = v * 10 + (int64) (c - '0');
  9008. else
  9009. break;
  9010. }
  9011. return isNeg ? -v : v;
  9012. #endif
  9013. }
  9014. static double juce_mulexp10 (const double value, int exponent) throw()
  9015. {
  9016. if (exponent == 0)
  9017. return value;
  9018. if (value == 0)
  9019. return 0;
  9020. const bool negative = (exponent < 0);
  9021. if (negative)
  9022. exponent = -exponent;
  9023. double result = 1.0, power = 10.0;
  9024. for (int bit = 1; exponent != 0; bit <<= 1)
  9025. {
  9026. if ((exponent & bit) != 0)
  9027. {
  9028. exponent ^= bit;
  9029. result *= power;
  9030. if (exponent == 0)
  9031. break;
  9032. }
  9033. power *= power;
  9034. }
  9035. return negative ? (value / result) : (value * result);
  9036. }
  9037. template <class CharType>
  9038. double juce_atof (const CharType* const original) throw()
  9039. {
  9040. double result[3] = { 0, 0, 0 }, accumulator[2] = { 0, 0 };
  9041. int exponentAdjustment[2] = { 0, 0 }, exponentAccumulator[2] = { -1, -1 };
  9042. int exponent = 0, decPointIndex = 0, digit = 0;
  9043. int lastDigit = 0, numSignificantDigits = 0;
  9044. bool isNegative = false, digitsFound = false;
  9045. const int maxSignificantDigits = 15 + 2;
  9046. const CharType* s = original;
  9047. while (CharacterFunctions::isWhitespace (*s))
  9048. ++s;
  9049. switch (*s)
  9050. {
  9051. case '-': isNegative = true; // fall-through..
  9052. case '+': ++s;
  9053. }
  9054. if (*s == 'n' || *s == 'N' || *s == 'i' || *s == 'I')
  9055. return atof (String (original).toUTF8()); // Let the c library deal with NAN and INF
  9056. for (;;)
  9057. {
  9058. if (CharacterFunctions::isDigit (*s))
  9059. {
  9060. lastDigit = digit;
  9061. digit = *s++ - '0';
  9062. digitsFound = true;
  9063. if (decPointIndex != 0)
  9064. exponentAdjustment[1]++;
  9065. if (numSignificantDigits == 0 && digit == 0)
  9066. continue;
  9067. if (++numSignificantDigits > maxSignificantDigits)
  9068. {
  9069. if (digit > 5)
  9070. ++accumulator [decPointIndex];
  9071. else if (digit == 5 && (lastDigit & 1) != 0)
  9072. ++accumulator [decPointIndex];
  9073. if (decPointIndex > 0)
  9074. exponentAdjustment[1]--;
  9075. else
  9076. exponentAdjustment[0]++;
  9077. while (CharacterFunctions::isDigit (*s))
  9078. {
  9079. ++s;
  9080. if (decPointIndex == 0)
  9081. exponentAdjustment[0]++;
  9082. }
  9083. }
  9084. else
  9085. {
  9086. const double maxAccumulatorValue = (double) ((std::numeric_limits<unsigned int>::max() - 9) / 10);
  9087. if (accumulator [decPointIndex] > maxAccumulatorValue)
  9088. {
  9089. result [decPointIndex] = juce_mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex])
  9090. + accumulator [decPointIndex];
  9091. accumulator [decPointIndex] = 0;
  9092. exponentAccumulator [decPointIndex] = 0;
  9093. }
  9094. accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit;
  9095. exponentAccumulator [decPointIndex]++;
  9096. }
  9097. }
  9098. else if (decPointIndex == 0 && *s == '.')
  9099. {
  9100. ++s;
  9101. decPointIndex = 1;
  9102. if (numSignificantDigits > maxSignificantDigits)
  9103. {
  9104. while (CharacterFunctions::isDigit (*s))
  9105. ++s;
  9106. break;
  9107. }
  9108. }
  9109. else
  9110. {
  9111. break;
  9112. }
  9113. }
  9114. result[0] = juce_mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0];
  9115. if (decPointIndex != 0)
  9116. result[1] = juce_mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1];
  9117. if ((*s == 'e' || *s == 'E') && digitsFound)
  9118. {
  9119. bool negativeExponent = false;
  9120. switch (*++s)
  9121. {
  9122. case '-': negativeExponent = true; // fall-through..
  9123. case '+': ++s;
  9124. }
  9125. while (CharacterFunctions::isDigit (*s))
  9126. exponent = (exponent * 10) + (*s++ - '0');
  9127. if (negativeExponent)
  9128. exponent = -exponent;
  9129. }
  9130. double r = juce_mulexp10 (result[0], exponent + exponentAdjustment[0]);
  9131. if (decPointIndex != 0)
  9132. r += juce_mulexp10 (result[1], exponent - exponentAdjustment[1]);
  9133. return isNegative ? -r : r;
  9134. }
  9135. double CharacterFunctions::getDoubleValue (const char* const s) throw()
  9136. {
  9137. return juce_atof <char> (s);
  9138. }
  9139. double CharacterFunctions::getDoubleValue (const juce_wchar* const s) throw()
  9140. {
  9141. return juce_atof <juce_wchar> (s);
  9142. }
  9143. char CharacterFunctions::toUpperCase (const char character) throw()
  9144. {
  9145. return (char) toupper (character);
  9146. }
  9147. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  9148. {
  9149. return towupper (character);
  9150. }
  9151. void CharacterFunctions::toUpperCase (char* s) throw()
  9152. {
  9153. #if JUCE_WINDOWS
  9154. strupr (s);
  9155. #else
  9156. while (*s != 0)
  9157. {
  9158. *s = toUpperCase (*s);
  9159. ++s;
  9160. }
  9161. #endif
  9162. }
  9163. void CharacterFunctions::toUpperCase (juce_wchar* s) throw()
  9164. {
  9165. #if JUCE_WINDOWS
  9166. _wcsupr (s);
  9167. #else
  9168. while (*s != 0)
  9169. {
  9170. *s = toUpperCase (*s);
  9171. ++s;
  9172. }
  9173. #endif
  9174. }
  9175. bool CharacterFunctions::isUpperCase (const char character) throw()
  9176. {
  9177. return isupper (character) != 0;
  9178. }
  9179. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  9180. {
  9181. #if JUCE_WINDOWS
  9182. return iswupper (character) != 0;
  9183. #else
  9184. return toLowerCase (character) != character;
  9185. #endif
  9186. }
  9187. char CharacterFunctions::toLowerCase (const char character) throw()
  9188. {
  9189. return (char) tolower (character);
  9190. }
  9191. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  9192. {
  9193. return towlower (character);
  9194. }
  9195. void CharacterFunctions::toLowerCase (char* s) throw()
  9196. {
  9197. #if JUCE_WINDOWS
  9198. strlwr (s);
  9199. #else
  9200. while (*s != 0)
  9201. {
  9202. *s = toLowerCase (*s);
  9203. ++s;
  9204. }
  9205. #endif
  9206. }
  9207. void CharacterFunctions::toLowerCase (juce_wchar* s) throw()
  9208. {
  9209. #if JUCE_WINDOWS
  9210. _wcslwr (s);
  9211. #else
  9212. while (*s != 0)
  9213. {
  9214. *s = toLowerCase (*s);
  9215. ++s;
  9216. }
  9217. #endif
  9218. }
  9219. bool CharacterFunctions::isLowerCase (const char character) throw()
  9220. {
  9221. return islower (character) != 0;
  9222. }
  9223. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  9224. {
  9225. #if JUCE_WINDOWS
  9226. return iswlower (character) != 0;
  9227. #else
  9228. return toUpperCase (character) != character;
  9229. #endif
  9230. }
  9231. bool CharacterFunctions::isWhitespace (const char character) throw()
  9232. {
  9233. return character == ' ' || (character <= 13 && character >= 9);
  9234. }
  9235. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  9236. {
  9237. return iswspace (character) != 0;
  9238. }
  9239. bool CharacterFunctions::isDigit (const char character) throw()
  9240. {
  9241. return (character >= '0' && character <= '9');
  9242. }
  9243. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  9244. {
  9245. return iswdigit (character) != 0;
  9246. }
  9247. bool CharacterFunctions::isLetter (const char character) throw()
  9248. {
  9249. return (character >= 'a' && character <= 'z')
  9250. || (character >= 'A' && character <= 'Z');
  9251. }
  9252. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  9253. {
  9254. return iswalpha (character) != 0;
  9255. }
  9256. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  9257. {
  9258. return (character >= 'a' && character <= 'z')
  9259. || (character >= 'A' && character <= 'Z')
  9260. || (character >= '0' && character <= '9');
  9261. }
  9262. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  9263. {
  9264. return iswalnum (character) != 0;
  9265. }
  9266. int CharacterFunctions::getHexDigitValue (const juce_wchar digit) throw()
  9267. {
  9268. unsigned int d = digit - '0';
  9269. if (d < (unsigned int) 10)
  9270. return (int) d;
  9271. d += (unsigned int) ('0' - 'a');
  9272. if (d < (unsigned int) 6)
  9273. return (int) d + 10;
  9274. d += (unsigned int) ('a' - 'A');
  9275. if (d < (unsigned int) 6)
  9276. return (int) d + 10;
  9277. return -1;
  9278. }
  9279. #if JUCE_MSVC
  9280. #pragma warning (pop)
  9281. #endif
  9282. END_JUCE_NAMESPACE
  9283. /*** End of inlined file: juce_CharacterFunctions.cpp ***/
  9284. /*** Start of inlined file: juce_LocalisedStrings.cpp ***/
  9285. BEGIN_JUCE_NAMESPACE
  9286. LocalisedStrings::LocalisedStrings (const String& fileContents)
  9287. {
  9288. loadFromText (fileContents);
  9289. }
  9290. LocalisedStrings::LocalisedStrings (const File& fileToLoad)
  9291. {
  9292. loadFromText (fileToLoad.loadFileAsString());
  9293. }
  9294. LocalisedStrings::~LocalisedStrings()
  9295. {
  9296. }
  9297. const String LocalisedStrings::translate (const String& text) const
  9298. {
  9299. return translations.getValue (text, text);
  9300. }
  9301. static int findCloseQuote (const String& text, int startPos)
  9302. {
  9303. juce_wchar lastChar = 0;
  9304. for (;;)
  9305. {
  9306. const juce_wchar c = text [startPos];
  9307. if (c == 0 || (c == '"' && lastChar != '\\'))
  9308. break;
  9309. lastChar = c;
  9310. ++startPos;
  9311. }
  9312. return startPos;
  9313. }
  9314. static const String unescapeString (const String& s)
  9315. {
  9316. return s.replace ("\\\"", "\"")
  9317. .replace ("\\\'", "\'")
  9318. .replace ("\\t", "\t")
  9319. .replace ("\\r", "\r")
  9320. .replace ("\\n", "\n");
  9321. }
  9322. void LocalisedStrings::loadFromText (const String& fileContents)
  9323. {
  9324. StringArray lines;
  9325. lines.addLines (fileContents);
  9326. for (int i = 0; i < lines.size(); ++i)
  9327. {
  9328. String line (lines[i].trim());
  9329. if (line.startsWithChar ('"'))
  9330. {
  9331. int closeQuote = findCloseQuote (line, 1);
  9332. const String originalText (unescapeString (line.substring (1, closeQuote)));
  9333. if (originalText.isNotEmpty())
  9334. {
  9335. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  9336. closeQuote = findCloseQuote (line, openingQuote + 1);
  9337. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  9338. if (newText.isNotEmpty())
  9339. translations.set (originalText, newText);
  9340. }
  9341. }
  9342. else if (line.startsWithIgnoreCase ("language:"))
  9343. {
  9344. languageName = line.substring (9).trim();
  9345. }
  9346. else if (line.startsWithIgnoreCase ("countries:"))
  9347. {
  9348. countryCodes.addTokens (line.substring (10).trim(), true);
  9349. countryCodes.trim();
  9350. countryCodes.removeEmptyStrings();
  9351. }
  9352. }
  9353. }
  9354. void LocalisedStrings::setIgnoresCase (const bool shouldIgnoreCase)
  9355. {
  9356. translations.setIgnoresCase (shouldIgnoreCase);
  9357. }
  9358. static CriticalSection currentMappingsLock;
  9359. static LocalisedStrings* currentMappings = 0;
  9360. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations)
  9361. {
  9362. const ScopedLock sl (currentMappingsLock);
  9363. delete currentMappings;
  9364. currentMappings = newTranslations;
  9365. }
  9366. LocalisedStrings* LocalisedStrings::getCurrentMappings()
  9367. {
  9368. return currentMappings;
  9369. }
  9370. const String LocalisedStrings::translateWithCurrentMappings (const String& text)
  9371. {
  9372. const ScopedLock sl (currentMappingsLock);
  9373. if (currentMappings != 0)
  9374. return currentMappings->translate (text);
  9375. return text;
  9376. }
  9377. const String LocalisedStrings::translateWithCurrentMappings (const char* text)
  9378. {
  9379. return translateWithCurrentMappings (String (text));
  9380. }
  9381. END_JUCE_NAMESPACE
  9382. /*** End of inlined file: juce_LocalisedStrings.cpp ***/
  9383. /*** Start of inlined file: juce_String.cpp ***/
  9384. #if JUCE_MSVC
  9385. #pragma warning (push)
  9386. #pragma warning (disable: 4514)
  9387. #endif
  9388. #include <locale>
  9389. BEGIN_JUCE_NAMESPACE
  9390. #if JUCE_MSVC
  9391. #pragma warning (pop)
  9392. #endif
  9393. #if defined (JUCE_STRINGS_ARE_UNICODE) && ! JUCE_STRINGS_ARE_UNICODE
  9394. #error "JUCE_STRINGS_ARE_UNICODE is deprecated! All strings are now unicode by default."
  9395. #endif
  9396. class StringHolder
  9397. {
  9398. public:
  9399. StringHolder()
  9400. : refCount (0x3fffffff), allocatedNumChars (0)
  9401. {
  9402. text[0] = 0;
  9403. }
  9404. static juce_wchar* createUninitialised (const size_t numChars)
  9405. {
  9406. StringHolder* const s = reinterpret_cast <StringHolder*> (new char [sizeof (StringHolder) + numChars * sizeof (juce_wchar)]);
  9407. s->refCount.value = 0;
  9408. s->allocatedNumChars = numChars;
  9409. return &(s->text[0]);
  9410. }
  9411. static juce_wchar* createCopy (const juce_wchar* const src, const size_t numChars)
  9412. {
  9413. juce_wchar* const dest = createUninitialised (numChars);
  9414. copyChars (dest, src, numChars);
  9415. return dest;
  9416. }
  9417. static juce_wchar* createCopy (const char* const src, const size_t numChars)
  9418. {
  9419. juce_wchar* const dest = createUninitialised (numChars);
  9420. CharacterFunctions::copy (dest, src, (int) numChars);
  9421. dest [numChars] = 0;
  9422. return dest;
  9423. }
  9424. static inline juce_wchar* getEmpty() throw()
  9425. {
  9426. return &(empty.text[0]);
  9427. }
  9428. static void retain (juce_wchar* const text) throw()
  9429. {
  9430. ++(bufferFromText (text)->refCount);
  9431. }
  9432. static inline void release (StringHolder* const b) throw()
  9433. {
  9434. if (--(b->refCount) == -1 && b != &empty)
  9435. delete[] reinterpret_cast <char*> (b);
  9436. }
  9437. static void release (juce_wchar* const text) throw()
  9438. {
  9439. release (bufferFromText (text));
  9440. }
  9441. static juce_wchar* makeUnique (juce_wchar* const text)
  9442. {
  9443. StringHolder* const b = bufferFromText (text);
  9444. if (b->refCount.get() <= 0)
  9445. return text;
  9446. juce_wchar* const newText = createCopy (text, b->allocatedNumChars);
  9447. release (b);
  9448. return newText;
  9449. }
  9450. static juce_wchar* makeUniqueWithSize (juce_wchar* const text, size_t numChars)
  9451. {
  9452. StringHolder* const b = bufferFromText (text);
  9453. if (b->refCount.get() <= 0 && b->allocatedNumChars >= numChars)
  9454. return text;
  9455. juce_wchar* const newText = createUninitialised (jmax (b->allocatedNumChars, numChars));
  9456. copyChars (newText, text, b->allocatedNumChars);
  9457. release (b);
  9458. return newText;
  9459. }
  9460. static size_t getAllocatedNumChars (juce_wchar* const text) throw()
  9461. {
  9462. return bufferFromText (text)->allocatedNumChars;
  9463. }
  9464. static void copyChars (juce_wchar* const dest, const juce_wchar* const src, const size_t numChars) throw()
  9465. {
  9466. jassert (src != 0 && dest != 0);
  9467. memcpy (dest, src, numChars * sizeof (juce_wchar));
  9468. dest [numChars] = 0;
  9469. }
  9470. Atomic<int> refCount;
  9471. size_t allocatedNumChars;
  9472. juce_wchar text[1];
  9473. static StringHolder empty;
  9474. private:
  9475. static inline StringHolder* bufferFromText (void* const text) throw()
  9476. {
  9477. // (Can't use offsetof() here because of warnings about this not being a POD)
  9478. return reinterpret_cast <StringHolder*> (static_cast <char*> (text)
  9479. - (reinterpret_cast <size_t> (reinterpret_cast <StringHolder*> (1)->text) - 1));
  9480. }
  9481. };
  9482. StringHolder StringHolder::empty;
  9483. const String String::empty;
  9484. void String::createInternal (const juce_wchar* const t, const size_t numChars)
  9485. {
  9486. jassert (t[numChars] == 0); // must have a null terminator
  9487. text = StringHolder::createCopy (t, numChars);
  9488. }
  9489. void String::appendInternal (const juce_wchar* const newText, const int numExtraChars)
  9490. {
  9491. if (numExtraChars > 0)
  9492. {
  9493. const int oldLen = length();
  9494. const int newTotalLen = oldLen + numExtraChars;
  9495. text = StringHolder::makeUniqueWithSize (text, newTotalLen);
  9496. StringHolder::copyChars (text + oldLen, newText, numExtraChars);
  9497. }
  9498. }
  9499. void String::preallocateStorage (const size_t numChars)
  9500. {
  9501. text = StringHolder::makeUniqueWithSize (text, numChars);
  9502. }
  9503. String::String() throw()
  9504. : text (StringHolder::getEmpty())
  9505. {
  9506. }
  9507. String::~String() throw()
  9508. {
  9509. StringHolder::release (text);
  9510. }
  9511. String::String (const String& other) throw()
  9512. : text (other.text)
  9513. {
  9514. StringHolder::retain (text);
  9515. }
  9516. void String::swapWith (String& other) throw()
  9517. {
  9518. swapVariables (text, other.text);
  9519. }
  9520. String& String::operator= (const String& other) throw()
  9521. {
  9522. juce_wchar* const newText = other.text;
  9523. StringHolder::retain (newText);
  9524. StringHolder::release (reinterpret_cast <Atomic<juce_wchar*>*> (&text)->exchange (newText));
  9525. return *this;
  9526. }
  9527. String::String (const size_t numChars, const int /*dummyVariable*/)
  9528. : text (StringHolder::createUninitialised (numChars))
  9529. {
  9530. }
  9531. String::String (const String& stringToCopy, const size_t charsToAllocate)
  9532. {
  9533. const size_t otherSize = StringHolder::getAllocatedNumChars (stringToCopy.text);
  9534. text = StringHolder::createUninitialised (jmax (charsToAllocate, otherSize));
  9535. StringHolder::copyChars (text, stringToCopy.text, otherSize);
  9536. }
  9537. String::String (const char* const t)
  9538. {
  9539. if (t != 0 && *t != 0)
  9540. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  9541. else
  9542. text = StringHolder::getEmpty();
  9543. }
  9544. String::String (const juce_wchar* const t)
  9545. {
  9546. if (t != 0 && *t != 0)
  9547. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  9548. else
  9549. text = StringHolder::getEmpty();
  9550. }
  9551. String::String (const char* const t, const size_t maxChars)
  9552. {
  9553. int i;
  9554. for (i = 0; (size_t) i < maxChars; ++i)
  9555. if (t[i] == 0)
  9556. break;
  9557. if (i > 0)
  9558. text = StringHolder::createCopy (t, i);
  9559. else
  9560. text = StringHolder::getEmpty();
  9561. }
  9562. String::String (const juce_wchar* const t, const size_t maxChars)
  9563. {
  9564. int i;
  9565. for (i = 0; (size_t) i < maxChars; ++i)
  9566. if (t[i] == 0)
  9567. break;
  9568. if (i > 0)
  9569. text = StringHolder::createCopy (t, i);
  9570. else
  9571. text = StringHolder::getEmpty();
  9572. }
  9573. const String String::charToString (const juce_wchar character)
  9574. {
  9575. String result ((size_t) 1, (int) 0);
  9576. result.text[0] = character;
  9577. result.text[1] = 0;
  9578. return result;
  9579. }
  9580. namespace NumberToStringConverters
  9581. {
  9582. // pass in a pointer to the END of a buffer..
  9583. static juce_wchar* int64ToString (juce_wchar* t, const int64 n) throw()
  9584. {
  9585. *--t = 0;
  9586. int64 v = (n >= 0) ? n : -n;
  9587. do
  9588. {
  9589. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9590. v /= 10;
  9591. } while (v > 0);
  9592. if (n < 0)
  9593. *--t = '-';
  9594. return t;
  9595. }
  9596. static juce_wchar* uint64ToString (juce_wchar* t, int64 v) throw()
  9597. {
  9598. *--t = 0;
  9599. do
  9600. {
  9601. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9602. v /= 10;
  9603. } while (v > 0);
  9604. return t;
  9605. }
  9606. static juce_wchar* intToString (juce_wchar* t, const int n) throw()
  9607. {
  9608. if (n == (int) 0x80000000) // (would cause an overflow)
  9609. return int64ToString (t, n);
  9610. *--t = 0;
  9611. int v = abs (n);
  9612. do
  9613. {
  9614. *--t = (juce_wchar) ('0' + (v % 10));
  9615. v /= 10;
  9616. } while (v > 0);
  9617. if (n < 0)
  9618. *--t = '-';
  9619. return t;
  9620. }
  9621. static juce_wchar* uintToString (juce_wchar* t, unsigned int v) throw()
  9622. {
  9623. *--t = 0;
  9624. do
  9625. {
  9626. *--t = (juce_wchar) ('0' + (v % 10));
  9627. v /= 10;
  9628. } while (v > 0);
  9629. return t;
  9630. }
  9631. static juce_wchar getDecimalPoint()
  9632. {
  9633. #if JUCE_MSVC && _MSC_VER < 1400
  9634. static juce_wchar dp = std::_USE (std::locale(), std::numpunct <wchar_t>).decimal_point();
  9635. #else
  9636. static juce_wchar dp = std::use_facet <std::numpunct <wchar_t> > (std::locale()).decimal_point();
  9637. #endif
  9638. return dp;
  9639. }
  9640. static juce_wchar* doubleToString (juce_wchar* buffer, int numChars, double n, int numDecPlaces, size_t& len) throw()
  9641. {
  9642. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  9643. {
  9644. juce_wchar* const end = buffer + numChars;
  9645. juce_wchar* t = end;
  9646. int64 v = (int64) (pow (10.0, numDecPlaces) * std::abs (n) + 0.5);
  9647. *--t = (juce_wchar) 0;
  9648. while (numDecPlaces >= 0 || v > 0)
  9649. {
  9650. if (numDecPlaces == 0)
  9651. *--t = getDecimalPoint();
  9652. *--t = (juce_wchar) ('0' + (v % 10));
  9653. v /= 10;
  9654. --numDecPlaces;
  9655. }
  9656. if (n < 0)
  9657. *--t = '-';
  9658. len = end - t - 1;
  9659. return t;
  9660. }
  9661. else
  9662. {
  9663. #if JUCE_WINDOWS
  9664. #if JUCE_MSVC && _MSC_VER <= 1400
  9665. len = _snwprintf (buffer, numChars, L"%.9g", n);
  9666. #else
  9667. len = _snwprintf_s (buffer, numChars, _TRUNCATE, L"%.9g", n);
  9668. #endif
  9669. #else
  9670. len = swprintf (buffer, numChars, L"%.9g", n);
  9671. #endif
  9672. return buffer;
  9673. }
  9674. }
  9675. }
  9676. String::String (const int number)
  9677. {
  9678. juce_wchar buffer [16];
  9679. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9680. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  9681. createInternal (start, end - start - 1);
  9682. }
  9683. String::String (const unsigned int number)
  9684. {
  9685. juce_wchar buffer [16];
  9686. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9687. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  9688. createInternal (start, end - start - 1);
  9689. }
  9690. String::String (const short number)
  9691. {
  9692. juce_wchar buffer [16];
  9693. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9694. juce_wchar* const start = NumberToStringConverters::intToString (end, (int) number);
  9695. createInternal (start, end - start - 1);
  9696. }
  9697. String::String (const unsigned short number)
  9698. {
  9699. juce_wchar buffer [16];
  9700. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9701. juce_wchar* const start = NumberToStringConverters::uintToString (end, (unsigned int) number);
  9702. createInternal (start, end - start - 1);
  9703. }
  9704. String::String (const int64 number)
  9705. {
  9706. juce_wchar buffer [32];
  9707. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9708. juce_wchar* const start = NumberToStringConverters::int64ToString (end, number);
  9709. createInternal (start, end - start - 1);
  9710. }
  9711. String::String (const uint64 number)
  9712. {
  9713. juce_wchar buffer [32];
  9714. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9715. juce_wchar* const start = NumberToStringConverters::uint64ToString (end, number);
  9716. createInternal (start, end - start - 1);
  9717. }
  9718. String::String (const float number, const int numberOfDecimalPlaces)
  9719. {
  9720. juce_wchar buffer [48];
  9721. size_t len;
  9722. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), (double) number, numberOfDecimalPlaces, len);
  9723. createInternal (start, len);
  9724. }
  9725. String::String (const double number, const int numberOfDecimalPlaces)
  9726. {
  9727. juce_wchar buffer [48];
  9728. size_t len;
  9729. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), number, numberOfDecimalPlaces, len);
  9730. createInternal (start, len);
  9731. }
  9732. int String::length() const throw()
  9733. {
  9734. return CharacterFunctions::length (text);
  9735. }
  9736. int String::hashCode() const throw()
  9737. {
  9738. const juce_wchar* t = text;
  9739. int result = 0;
  9740. while (*t != (juce_wchar) 0)
  9741. result = 31 * result + *t++;
  9742. return result;
  9743. }
  9744. int64 String::hashCode64() const throw()
  9745. {
  9746. const juce_wchar* t = text;
  9747. int64 result = 0;
  9748. while (*t != (juce_wchar) 0)
  9749. result = 101 * result + *t++;
  9750. return result;
  9751. }
  9752. bool JUCE_PUBLIC_FUNCTION operator== (const String& string1, const String& string2) throw()
  9753. {
  9754. return string1.compare (string2) == 0;
  9755. }
  9756. bool JUCE_PUBLIC_FUNCTION operator== (const String& string1, const char* string2) throw()
  9757. {
  9758. return string1.compare (string2) == 0;
  9759. }
  9760. bool JUCE_PUBLIC_FUNCTION operator== (const String& string1, const juce_wchar* string2) throw()
  9761. {
  9762. return string1.compare (string2) == 0;
  9763. }
  9764. bool JUCE_PUBLIC_FUNCTION operator!= (const String& string1, const String& string2) throw()
  9765. {
  9766. return string1.compare (string2) != 0;
  9767. }
  9768. bool JUCE_PUBLIC_FUNCTION operator!= (const String& string1, const char* string2) throw()
  9769. {
  9770. return string1.compare (string2) != 0;
  9771. }
  9772. bool JUCE_PUBLIC_FUNCTION operator!= (const String& string1, const juce_wchar* string2) throw()
  9773. {
  9774. return string1.compare (string2) != 0;
  9775. }
  9776. bool JUCE_PUBLIC_FUNCTION operator> (const String& string1, const String& string2) throw()
  9777. {
  9778. return string1.compare (string2) > 0;
  9779. }
  9780. bool JUCE_PUBLIC_FUNCTION operator< (const String& string1, const String& string2) throw()
  9781. {
  9782. return string1.compare (string2) < 0;
  9783. }
  9784. bool JUCE_PUBLIC_FUNCTION operator>= (const String& string1, const String& string2) throw()
  9785. {
  9786. return string1.compare (string2) >= 0;
  9787. }
  9788. bool JUCE_PUBLIC_FUNCTION operator<= (const String& string1, const String& string2) throw()
  9789. {
  9790. return string1.compare (string2) <= 0;
  9791. }
  9792. bool String::equalsIgnoreCase (const juce_wchar* t) const throw()
  9793. {
  9794. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  9795. : isEmpty();
  9796. }
  9797. bool String::equalsIgnoreCase (const char* t) const throw()
  9798. {
  9799. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  9800. : isEmpty();
  9801. }
  9802. bool String::equalsIgnoreCase (const String& other) const throw()
  9803. {
  9804. return text == other.text
  9805. || CharacterFunctions::compareIgnoreCase (text, other.text) == 0;
  9806. }
  9807. int String::compare (const String& other) const throw()
  9808. {
  9809. return (text == other.text) ? 0 : CharacterFunctions::compare (text, other.text);
  9810. }
  9811. int String::compare (const char* other) const throw()
  9812. {
  9813. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  9814. }
  9815. int String::compare (const juce_wchar* other) const throw()
  9816. {
  9817. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  9818. }
  9819. int String::compareIgnoreCase (const String& other) const throw()
  9820. {
  9821. return (text == other.text) ? 0 : CharacterFunctions::compareIgnoreCase (text, other.text);
  9822. }
  9823. int String::compareLexicographically (const String& other) const throw()
  9824. {
  9825. const juce_wchar* s1 = text;
  9826. while (*s1 != 0 && ! CharacterFunctions::isLetterOrDigit (*s1))
  9827. ++s1;
  9828. const juce_wchar* s2 = other.text;
  9829. while (*s2 != 0 && ! CharacterFunctions::isLetterOrDigit (*s2))
  9830. ++s2;
  9831. return CharacterFunctions::compareIgnoreCase (s1, s2);
  9832. }
  9833. String& String::operator+= (const juce_wchar* const t)
  9834. {
  9835. if (t != 0)
  9836. appendInternal (t, CharacterFunctions::length (t));
  9837. return *this;
  9838. }
  9839. String& String::operator+= (const String& other)
  9840. {
  9841. if (isEmpty())
  9842. operator= (other);
  9843. else
  9844. appendInternal (other.text, other.length());
  9845. return *this;
  9846. }
  9847. String& String::operator+= (const char ch)
  9848. {
  9849. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  9850. return operator+= (static_cast <const juce_wchar*> (asString));
  9851. }
  9852. String& String::operator+= (const juce_wchar ch)
  9853. {
  9854. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  9855. return operator+= (static_cast <const juce_wchar*> (asString));
  9856. }
  9857. String& String::operator+= (const int number)
  9858. {
  9859. juce_wchar buffer [16];
  9860. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9861. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  9862. appendInternal (start, (int) (end - start));
  9863. return *this;
  9864. }
  9865. String& String::operator+= (const unsigned int number)
  9866. {
  9867. juce_wchar buffer [16];
  9868. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9869. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  9870. appendInternal (start, (int) (end - start));
  9871. return *this;
  9872. }
  9873. void String::append (const juce_wchar* const other, const int howMany)
  9874. {
  9875. if (howMany > 0)
  9876. {
  9877. int i;
  9878. for (i = 0; i < howMany; ++i)
  9879. if (other[i] == 0)
  9880. break;
  9881. appendInternal (other, i);
  9882. }
  9883. }
  9884. const String JUCE_PUBLIC_FUNCTION operator+ (const char* const string1, const String& string2)
  9885. {
  9886. String s (string1);
  9887. return s += string2;
  9888. }
  9889. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar* const string1, const String& string2)
  9890. {
  9891. String s (string1);
  9892. return s += string2;
  9893. }
  9894. const String JUCE_PUBLIC_FUNCTION operator+ (const char string1, const String& string2)
  9895. {
  9896. return String::charToString (string1) + string2;
  9897. }
  9898. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar string1, const String& string2)
  9899. {
  9900. return String::charToString (string1) + string2;
  9901. }
  9902. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const String& string2)
  9903. {
  9904. return string1 += string2;
  9905. }
  9906. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const char* const string2)
  9907. {
  9908. return string1 += string2;
  9909. }
  9910. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const juce_wchar* const string2)
  9911. {
  9912. return string1 += string2;
  9913. }
  9914. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const char string2)
  9915. {
  9916. return string1 += string2;
  9917. }
  9918. const String JUCE_PUBLIC_FUNCTION operator+ (String string1, const juce_wchar string2)
  9919. {
  9920. return string1 += string2;
  9921. }
  9922. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const char characterToAppend)
  9923. {
  9924. return string1 += characterToAppend;
  9925. }
  9926. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const juce_wchar characterToAppend)
  9927. {
  9928. return string1 += characterToAppend;
  9929. }
  9930. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const char* const string2)
  9931. {
  9932. return string1 += string2;
  9933. }
  9934. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const juce_wchar* const string2)
  9935. {
  9936. return string1 += string2;
  9937. }
  9938. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const String& string2)
  9939. {
  9940. return string1 += string2;
  9941. }
  9942. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const short number)
  9943. {
  9944. return string1 += (int) number;
  9945. }
  9946. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const int number)
  9947. {
  9948. return string1 += number;
  9949. }
  9950. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const unsigned int number)
  9951. {
  9952. return string1 += number;
  9953. }
  9954. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const long number)
  9955. {
  9956. return string1 += (int) number;
  9957. }
  9958. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const unsigned long number)
  9959. {
  9960. return string1 += (unsigned int) number;
  9961. }
  9962. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const float number)
  9963. {
  9964. return string1 += String (number);
  9965. }
  9966. String& JUCE_PUBLIC_FUNCTION operator<< (String& string1, const double number)
  9967. {
  9968. return string1 += String (number);
  9969. }
  9970. OutputStream& JUCE_PUBLIC_FUNCTION operator<< (OutputStream& stream, const String& text)
  9971. {
  9972. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  9973. // if lots of large, persistent strings were to be written to streams).
  9974. const int numBytes = text.getNumBytesAsUTF8();
  9975. HeapBlock<char> temp (numBytes + 1);
  9976. text.copyToUTF8 (temp, numBytes + 1);
  9977. stream.write (temp, numBytes);
  9978. return stream;
  9979. }
  9980. int String::indexOfChar (const juce_wchar character) const throw()
  9981. {
  9982. const juce_wchar* t = text;
  9983. for (;;)
  9984. {
  9985. if (*t == character)
  9986. return (int) (t - text);
  9987. if (*t++ == 0)
  9988. return -1;
  9989. }
  9990. }
  9991. int String::lastIndexOfChar (const juce_wchar character) const throw()
  9992. {
  9993. for (int i = length(); --i >= 0;)
  9994. if (text[i] == character)
  9995. return i;
  9996. return -1;
  9997. }
  9998. int String::indexOf (const String& t) const throw()
  9999. {
  10000. const juce_wchar* const r = CharacterFunctions::find (text, t.text);
  10001. return r == 0 ? -1 : (int) (r - text);
  10002. }
  10003. int String::indexOfChar (const int startIndex,
  10004. const juce_wchar character) const throw()
  10005. {
  10006. if (startIndex > 0 && startIndex >= length())
  10007. return -1;
  10008. const juce_wchar* t = text + jmax (0, startIndex);
  10009. for (;;)
  10010. {
  10011. if (*t == character)
  10012. return (int) (t - text);
  10013. if (*t == 0)
  10014. return -1;
  10015. ++t;
  10016. }
  10017. }
  10018. int String::indexOfAnyOf (const String& charactersToLookFor,
  10019. const int startIndex,
  10020. const bool ignoreCase) const throw()
  10021. {
  10022. if (startIndex > 0 && startIndex >= length())
  10023. return -1;
  10024. const juce_wchar* t = text + jmax (0, startIndex);
  10025. while (*t != 0)
  10026. {
  10027. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, *t, ignoreCase) >= 0)
  10028. return (int) (t - text);
  10029. ++t;
  10030. }
  10031. return -1;
  10032. }
  10033. int String::indexOf (const int startIndex, const String& other) const throw()
  10034. {
  10035. if (startIndex > 0 && startIndex >= length())
  10036. return -1;
  10037. const juce_wchar* const found = CharacterFunctions::find (text + jmax (0, startIndex), other.text);
  10038. return found == 0 ? -1 : (int) (found - text);
  10039. }
  10040. int String::indexOfIgnoreCase (const String& other) const throw()
  10041. {
  10042. if (other.isNotEmpty())
  10043. {
  10044. const int len = other.length();
  10045. const int end = length() - len;
  10046. for (int i = 0; i <= end; ++i)
  10047. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  10048. return i;
  10049. }
  10050. return -1;
  10051. }
  10052. int String::indexOfIgnoreCase (const int startIndex, const String& other) const throw()
  10053. {
  10054. if (other.isNotEmpty())
  10055. {
  10056. const int len = other.length();
  10057. const int end = length() - len;
  10058. for (int i = jmax (0, startIndex); i <= end; ++i)
  10059. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  10060. return i;
  10061. }
  10062. return -1;
  10063. }
  10064. int String::lastIndexOf (const String& other) const throw()
  10065. {
  10066. if (other.isNotEmpty())
  10067. {
  10068. const int len = other.length();
  10069. int i = length() - len;
  10070. if (i >= 0)
  10071. {
  10072. const juce_wchar* n = text + i;
  10073. while (i >= 0)
  10074. {
  10075. if (CharacterFunctions::compare (n--, other.text, len) == 0)
  10076. return i;
  10077. --i;
  10078. }
  10079. }
  10080. }
  10081. return -1;
  10082. }
  10083. int String::lastIndexOfIgnoreCase (const String& other) const throw()
  10084. {
  10085. if (other.isNotEmpty())
  10086. {
  10087. const int len = other.length();
  10088. int i = length() - len;
  10089. if (i >= 0)
  10090. {
  10091. const juce_wchar* n = text + i;
  10092. while (i >= 0)
  10093. {
  10094. if (CharacterFunctions::compareIgnoreCase (n--, other.text, len) == 0)
  10095. return i;
  10096. --i;
  10097. }
  10098. }
  10099. }
  10100. return -1;
  10101. }
  10102. int String::lastIndexOfAnyOf (const String& charactersToLookFor, const bool ignoreCase) const throw()
  10103. {
  10104. for (int i = length(); --i >= 0;)
  10105. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, text[i], ignoreCase) >= 0)
  10106. return i;
  10107. return -1;
  10108. }
  10109. bool String::contains (const String& other) const throw()
  10110. {
  10111. return indexOf (other) >= 0;
  10112. }
  10113. bool String::containsChar (const juce_wchar character) const throw()
  10114. {
  10115. const juce_wchar* t = text;
  10116. for (;;)
  10117. {
  10118. if (*t == 0)
  10119. return false;
  10120. if (*t == character)
  10121. return true;
  10122. ++t;
  10123. }
  10124. }
  10125. bool String::containsIgnoreCase (const String& t) const throw()
  10126. {
  10127. return indexOfIgnoreCase (t) >= 0;
  10128. }
  10129. int String::indexOfWholeWord (const String& word) const throw()
  10130. {
  10131. if (word.isNotEmpty())
  10132. {
  10133. const int wordLen = word.length();
  10134. const int end = length() - wordLen;
  10135. const juce_wchar* t = text;
  10136. for (int i = 0; i <= end; ++i)
  10137. {
  10138. if (CharacterFunctions::compare (t, word.text, wordLen) == 0
  10139. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  10140. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  10141. {
  10142. return i;
  10143. }
  10144. ++t;
  10145. }
  10146. }
  10147. return -1;
  10148. }
  10149. int String::indexOfWholeWordIgnoreCase (const String& word) const throw()
  10150. {
  10151. if (word.isNotEmpty())
  10152. {
  10153. const int wordLen = word.length();
  10154. const int end = length() - wordLen;
  10155. const juce_wchar* t = text;
  10156. for (int i = 0; i <= end; ++i)
  10157. {
  10158. if (CharacterFunctions::compareIgnoreCase (t, word.text, wordLen) == 0
  10159. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  10160. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  10161. {
  10162. return i;
  10163. }
  10164. ++t;
  10165. }
  10166. }
  10167. return -1;
  10168. }
  10169. bool String::containsWholeWord (const String& wordToLookFor) const throw()
  10170. {
  10171. return indexOfWholeWord (wordToLookFor) >= 0;
  10172. }
  10173. bool String::containsWholeWordIgnoreCase (const String& wordToLookFor) const throw()
  10174. {
  10175. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  10176. }
  10177. static int indexOfMatch (const juce_wchar* const wildcard,
  10178. const juce_wchar* const test,
  10179. const bool ignoreCase) throw()
  10180. {
  10181. int start = 0;
  10182. while (test [start] != 0)
  10183. {
  10184. int i = 0;
  10185. for (;;)
  10186. {
  10187. const juce_wchar wc = wildcard [i];
  10188. const juce_wchar c = test [i + start];
  10189. if (wc == c
  10190. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  10191. || (wc == '?' && c != 0))
  10192. {
  10193. if (wc == 0)
  10194. return start;
  10195. ++i;
  10196. }
  10197. else
  10198. {
  10199. if (wc == '*' && (wildcard [i + 1] == 0
  10200. || indexOfMatch (wildcard + i + 1, test + start + i, ignoreCase) >= 0))
  10201. {
  10202. return start;
  10203. }
  10204. break;
  10205. }
  10206. }
  10207. ++start;
  10208. }
  10209. return -1;
  10210. }
  10211. bool String::matchesWildcard (const String& wildcard, const bool ignoreCase) const throw()
  10212. {
  10213. int i = 0;
  10214. for (;;)
  10215. {
  10216. const juce_wchar wc = wildcard.text [i];
  10217. const juce_wchar c = text [i];
  10218. if (wc == c
  10219. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  10220. || (wc == '?' && c != 0))
  10221. {
  10222. if (wc == 0)
  10223. return true;
  10224. ++i;
  10225. }
  10226. else
  10227. {
  10228. return wc == '*' && (wildcard [i + 1] == 0
  10229. || indexOfMatch (wildcard.text + i + 1, text + i, ignoreCase) >= 0);
  10230. }
  10231. }
  10232. }
  10233. const String String::repeatedString (const String& stringToRepeat, int numberOfTimesToRepeat)
  10234. {
  10235. const int len = stringToRepeat.length();
  10236. String result ((size_t) (len * numberOfTimesToRepeat + 1), (int) 0);
  10237. juce_wchar* n = result.text;
  10238. *n = 0;
  10239. while (--numberOfTimesToRepeat >= 0)
  10240. {
  10241. StringHolder::copyChars (n, stringToRepeat.text, len);
  10242. n += len;
  10243. }
  10244. return result;
  10245. }
  10246. const String String::paddedLeft (const juce_wchar padCharacter, int minimumLength) const
  10247. {
  10248. jassert (padCharacter != 0);
  10249. const int len = length();
  10250. if (len >= minimumLength || padCharacter == 0)
  10251. return *this;
  10252. String result ((size_t) minimumLength + 1, (int) 0);
  10253. juce_wchar* n = result.text;
  10254. minimumLength -= len;
  10255. while (--minimumLength >= 0)
  10256. *n++ = padCharacter;
  10257. StringHolder::copyChars (n, text, len);
  10258. return result;
  10259. }
  10260. const String String::paddedRight (const juce_wchar padCharacter, int minimumLength) const
  10261. {
  10262. jassert (padCharacter != 0);
  10263. const int len = length();
  10264. if (len >= minimumLength || padCharacter == 0)
  10265. return *this;
  10266. String result (*this, (size_t) minimumLength);
  10267. juce_wchar* n = result.text + len;
  10268. minimumLength -= len;
  10269. while (--minimumLength >= 0)
  10270. *n++ = padCharacter;
  10271. *n = 0;
  10272. return result;
  10273. }
  10274. const String String::replaceSection (int index, int numCharsToReplace, const String& stringToInsert) const
  10275. {
  10276. if (index < 0)
  10277. {
  10278. // a negative index to replace from?
  10279. jassertfalse;
  10280. index = 0;
  10281. }
  10282. if (numCharsToReplace < 0)
  10283. {
  10284. // replacing a negative number of characters?
  10285. numCharsToReplace = 0;
  10286. jassertfalse;
  10287. }
  10288. const int len = length();
  10289. if (index + numCharsToReplace > len)
  10290. {
  10291. if (index > len)
  10292. {
  10293. // replacing beyond the end of the string?
  10294. index = len;
  10295. jassertfalse;
  10296. }
  10297. numCharsToReplace = len - index;
  10298. }
  10299. const int newStringLen = stringToInsert.length();
  10300. const int newTotalLen = len + newStringLen - numCharsToReplace;
  10301. if (newTotalLen <= 0)
  10302. return String::empty;
  10303. String result ((size_t) newTotalLen, (int) 0);
  10304. StringHolder::copyChars (result.text, text, index);
  10305. if (newStringLen > 0)
  10306. StringHolder::copyChars (result.text + index, stringToInsert.text, newStringLen);
  10307. const int endStringLen = newTotalLen - (index + newStringLen);
  10308. if (endStringLen > 0)
  10309. StringHolder::copyChars (result.text + (index + newStringLen),
  10310. text + (index + numCharsToReplace),
  10311. endStringLen);
  10312. return result;
  10313. }
  10314. const String String::replace (const String& stringToReplace, const String& stringToInsert, const bool ignoreCase) const
  10315. {
  10316. const int stringToReplaceLen = stringToReplace.length();
  10317. const int stringToInsertLen = stringToInsert.length();
  10318. int i = 0;
  10319. String result (*this);
  10320. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  10321. : result.indexOf (i, stringToReplace))) >= 0)
  10322. {
  10323. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  10324. i += stringToInsertLen;
  10325. }
  10326. return result;
  10327. }
  10328. const String String::replaceCharacter (const juce_wchar charToReplace, const juce_wchar charToInsert) const
  10329. {
  10330. const int index = indexOfChar (charToReplace);
  10331. if (index < 0)
  10332. return *this;
  10333. String result (*this, size_t());
  10334. juce_wchar* t = result.text + index;
  10335. while (*t != 0)
  10336. {
  10337. if (*t == charToReplace)
  10338. *t = charToInsert;
  10339. ++t;
  10340. }
  10341. return result;
  10342. }
  10343. const String String::replaceCharacters (const String& charactersToReplace,
  10344. const String& charactersToInsertInstead) const
  10345. {
  10346. String result (*this, size_t());
  10347. juce_wchar* t = result.text;
  10348. const int len2 = charactersToInsertInstead.length();
  10349. // the two strings passed in are supposed to be the same length!
  10350. jassert (len2 == charactersToReplace.length());
  10351. while (*t != 0)
  10352. {
  10353. const int index = charactersToReplace.indexOfChar (*t);
  10354. if (((unsigned int) index) < (unsigned int) len2)
  10355. *t = charactersToInsertInstead [index];
  10356. ++t;
  10357. }
  10358. return result;
  10359. }
  10360. bool String::startsWith (const String& other) const throw()
  10361. {
  10362. return CharacterFunctions::compare (text, other.text, other.length()) == 0;
  10363. }
  10364. bool String::startsWithIgnoreCase (const String& other) const throw()
  10365. {
  10366. return CharacterFunctions::compareIgnoreCase (text, other.text, other.length()) == 0;
  10367. }
  10368. bool String::startsWithChar (const juce_wchar character) const throw()
  10369. {
  10370. jassert (character != 0); // strings can't contain a null character!
  10371. return text[0] == character;
  10372. }
  10373. bool String::endsWithChar (const juce_wchar character) const throw()
  10374. {
  10375. jassert (character != 0); // strings can't contain a null character!
  10376. return text[0] != 0
  10377. && text [length() - 1] == character;
  10378. }
  10379. bool String::endsWith (const String& other) const throw()
  10380. {
  10381. const int thisLen = length();
  10382. const int otherLen = other.length();
  10383. return thisLen >= otherLen
  10384. && CharacterFunctions::compare (text + thisLen - otherLen, other.text) == 0;
  10385. }
  10386. bool String::endsWithIgnoreCase (const String& other) const throw()
  10387. {
  10388. const int thisLen = length();
  10389. const int otherLen = other.length();
  10390. return thisLen >= otherLen
  10391. && CharacterFunctions::compareIgnoreCase (text + thisLen - otherLen, other.text) == 0;
  10392. }
  10393. const String String::toUpperCase() const
  10394. {
  10395. String result (*this, size_t());
  10396. CharacterFunctions::toUpperCase (result.text);
  10397. return result;
  10398. }
  10399. const String String::toLowerCase() const
  10400. {
  10401. String result (*this, size_t());
  10402. CharacterFunctions::toLowerCase (result.text);
  10403. return result;
  10404. }
  10405. juce_wchar& String::operator[] (const int index)
  10406. {
  10407. jassert (((unsigned int) index) <= (unsigned int) length());
  10408. text = StringHolder::makeUnique (text);
  10409. return text [index];
  10410. }
  10411. juce_wchar String::getLastCharacter() const throw()
  10412. {
  10413. return isEmpty() ? juce_wchar() : text [length() - 1];
  10414. }
  10415. const String String::substring (int start, int end) const
  10416. {
  10417. if (start < 0)
  10418. start = 0;
  10419. else if (end <= start)
  10420. return empty;
  10421. int len = 0;
  10422. while (len <= end && text [len] != 0)
  10423. ++len;
  10424. if (end >= len)
  10425. {
  10426. if (start == 0)
  10427. return *this;
  10428. end = len;
  10429. }
  10430. return String (text + start, end - start);
  10431. }
  10432. const String String::substring (const int start) const
  10433. {
  10434. if (start <= 0)
  10435. return *this;
  10436. const int len = length();
  10437. if (start >= len)
  10438. return empty;
  10439. return String (text + start, len - start);
  10440. }
  10441. const String String::dropLastCharacters (const int numberToDrop) const
  10442. {
  10443. return String (text, jmax (0, length() - numberToDrop));
  10444. }
  10445. const String String::getLastCharacters (const int numCharacters) const
  10446. {
  10447. return String (text + jmax (0, length() - jmax (0, numCharacters)));
  10448. }
  10449. const String String::fromFirstOccurrenceOf (const String& sub,
  10450. const bool includeSubString,
  10451. const bool ignoreCase) const
  10452. {
  10453. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10454. : indexOf (sub);
  10455. if (i < 0)
  10456. return empty;
  10457. return substring (includeSubString ? i : i + sub.length());
  10458. }
  10459. const String String::fromLastOccurrenceOf (const String& sub,
  10460. const bool includeSubString,
  10461. const bool ignoreCase) const
  10462. {
  10463. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10464. : lastIndexOf (sub);
  10465. if (i < 0)
  10466. return *this;
  10467. return substring (includeSubString ? i : i + sub.length());
  10468. }
  10469. const String String::upToFirstOccurrenceOf (const String& sub,
  10470. const bool includeSubString,
  10471. const bool ignoreCase) const
  10472. {
  10473. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10474. : indexOf (sub);
  10475. if (i < 0)
  10476. return *this;
  10477. return substring (0, includeSubString ? i + sub.length() : i);
  10478. }
  10479. const String String::upToLastOccurrenceOf (const String& sub,
  10480. const bool includeSubString,
  10481. const bool ignoreCase) const
  10482. {
  10483. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10484. : lastIndexOf (sub);
  10485. if (i < 0)
  10486. return *this;
  10487. return substring (0, includeSubString ? i + sub.length() : i);
  10488. }
  10489. bool String::isQuotedString() const
  10490. {
  10491. const String trimmed (trimStart());
  10492. return trimmed[0] == '"'
  10493. || trimmed[0] == '\'';
  10494. }
  10495. const String String::unquoted() const
  10496. {
  10497. String s (*this);
  10498. if (s.text[0] == '"' || s.text[0] == '\'')
  10499. s = s.substring (1);
  10500. const int lastCharIndex = s.length() - 1;
  10501. if (lastCharIndex >= 0
  10502. && (s [lastCharIndex] == '"' || s[lastCharIndex] == '\''))
  10503. s [lastCharIndex] = 0;
  10504. return s;
  10505. }
  10506. const String String::quoted (const juce_wchar quoteCharacter) const
  10507. {
  10508. if (isEmpty())
  10509. return charToString (quoteCharacter) + quoteCharacter;
  10510. String t (*this);
  10511. if (! t.startsWithChar (quoteCharacter))
  10512. t = charToString (quoteCharacter) + t;
  10513. if (! t.endsWithChar (quoteCharacter))
  10514. t += quoteCharacter;
  10515. return t;
  10516. }
  10517. const String String::trim() const
  10518. {
  10519. if (isEmpty())
  10520. return empty;
  10521. int start = 0;
  10522. while (CharacterFunctions::isWhitespace (text [start]))
  10523. ++start;
  10524. const int len = length();
  10525. int end = len - 1;
  10526. while ((end >= start) && CharacterFunctions::isWhitespace (text [end]))
  10527. --end;
  10528. ++end;
  10529. if (end <= start)
  10530. return empty;
  10531. else if (start > 0 || end < len)
  10532. return String (text + start, end - start);
  10533. return *this;
  10534. }
  10535. const String String::trimStart() const
  10536. {
  10537. if (isEmpty())
  10538. return empty;
  10539. const juce_wchar* t = text;
  10540. while (CharacterFunctions::isWhitespace (*t))
  10541. ++t;
  10542. if (t == text)
  10543. return *this;
  10544. return String (t);
  10545. }
  10546. const String String::trimEnd() const
  10547. {
  10548. if (isEmpty())
  10549. return empty;
  10550. const juce_wchar* endT = text + (length() - 1);
  10551. while ((endT >= text) && CharacterFunctions::isWhitespace (*endT))
  10552. --endT;
  10553. return String (text, (int) (++endT - text));
  10554. }
  10555. const String String::trimCharactersAtStart (const String& charactersToTrim) const
  10556. {
  10557. const juce_wchar* t = text;
  10558. while (charactersToTrim.containsChar (*t))
  10559. ++t;
  10560. return t == text ? *this : String (t);
  10561. }
  10562. const String String::trimCharactersAtEnd (const String& charactersToTrim) const
  10563. {
  10564. if (isEmpty())
  10565. return empty;
  10566. const int len = length();
  10567. const juce_wchar* endT = text + (len - 1);
  10568. int numToRemove = 0;
  10569. while (numToRemove < len && charactersToTrim.containsChar (*endT))
  10570. {
  10571. ++numToRemove;
  10572. --endT;
  10573. }
  10574. return numToRemove > 0 ? String (text, len - numToRemove) : *this;
  10575. }
  10576. const String String::retainCharacters (const String& charactersToRetain) const
  10577. {
  10578. if (isEmpty())
  10579. return empty;
  10580. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  10581. juce_wchar* dst = result.text;
  10582. const juce_wchar* src = text;
  10583. while (*src != 0)
  10584. {
  10585. if (charactersToRetain.containsChar (*src))
  10586. *dst++ = *src;
  10587. ++src;
  10588. }
  10589. *dst = 0;
  10590. return result;
  10591. }
  10592. const String String::removeCharacters (const String& charactersToRemove) const
  10593. {
  10594. if (isEmpty())
  10595. return empty;
  10596. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  10597. juce_wchar* dst = result.text;
  10598. const juce_wchar* src = text;
  10599. while (*src != 0)
  10600. {
  10601. if (! charactersToRemove.containsChar (*src))
  10602. *dst++ = *src;
  10603. ++src;
  10604. }
  10605. *dst = 0;
  10606. return result;
  10607. }
  10608. const String String::initialSectionContainingOnly (const String& permittedCharacters) const
  10609. {
  10610. int i = 0;
  10611. for (;;)
  10612. {
  10613. if (! permittedCharacters.containsChar (text[i]))
  10614. break;
  10615. ++i;
  10616. }
  10617. return substring (0, i);
  10618. }
  10619. const String String::initialSectionNotContaining (const String& charactersToStopAt) const
  10620. {
  10621. const juce_wchar* const t = text;
  10622. int i = 0;
  10623. while (t[i] != 0)
  10624. {
  10625. if (charactersToStopAt.containsChar (t[i]))
  10626. return String (text, i);
  10627. ++i;
  10628. }
  10629. return empty;
  10630. }
  10631. bool String::containsOnly (const String& chars) const throw()
  10632. {
  10633. const juce_wchar* t = text;
  10634. while (*t != 0)
  10635. if (! chars.containsChar (*t++))
  10636. return false;
  10637. return true;
  10638. }
  10639. bool String::containsAnyOf (const String& chars) const throw()
  10640. {
  10641. const juce_wchar* t = text;
  10642. while (*t != 0)
  10643. if (chars.containsChar (*t++))
  10644. return true;
  10645. return false;
  10646. }
  10647. bool String::containsNonWhitespaceChars() const throw()
  10648. {
  10649. const juce_wchar* t = text;
  10650. while (*t != 0)
  10651. if (! CharacterFunctions::isWhitespace (*t++))
  10652. return true;
  10653. return false;
  10654. }
  10655. const String String::formatted (const juce_wchar* const pf, ... )
  10656. {
  10657. jassert (pf != 0);
  10658. va_list args;
  10659. va_start (args, pf);
  10660. size_t bufferSize = 256;
  10661. String result (bufferSize, (int) 0);
  10662. result.text[0] = 0;
  10663. for (;;)
  10664. {
  10665. #if JUCE_LINUX && JUCE_64BIT
  10666. va_list tempArgs;
  10667. va_copy (tempArgs, args);
  10668. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, tempArgs);
  10669. va_end (tempArgs);
  10670. #elif JUCE_WINDOWS
  10671. #if JUCE_MSVC
  10672. #pragma warning (push)
  10673. #pragma warning (disable: 4996)
  10674. #endif
  10675. const int num = (int) _vsnwprintf (result.text, bufferSize - 1, pf, args);
  10676. #if JUCE_MSVC
  10677. #pragma warning (pop)
  10678. #endif
  10679. #else
  10680. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, args);
  10681. #endif
  10682. if (num > 0)
  10683. return result;
  10684. bufferSize += 256;
  10685. if (num == 0 || bufferSize > 65536) // the upper limit is a sanity check to avoid situations where vprintf repeatedly
  10686. break; // returns -1 because of an error rather than because it needs more space.
  10687. result.preallocateStorage (bufferSize);
  10688. }
  10689. return empty;
  10690. }
  10691. int String::getIntValue() const throw()
  10692. {
  10693. return CharacterFunctions::getIntValue (text);
  10694. }
  10695. int String::getTrailingIntValue() const throw()
  10696. {
  10697. int n = 0;
  10698. int mult = 1;
  10699. const juce_wchar* t = text + length();
  10700. while (--t >= text)
  10701. {
  10702. const juce_wchar c = *t;
  10703. if (! CharacterFunctions::isDigit (c))
  10704. {
  10705. if (c == '-')
  10706. n = -n;
  10707. break;
  10708. }
  10709. n += mult * (c - '0');
  10710. mult *= 10;
  10711. }
  10712. return n;
  10713. }
  10714. int64 String::getLargeIntValue() const throw()
  10715. {
  10716. return CharacterFunctions::getInt64Value (text);
  10717. }
  10718. float String::getFloatValue() const throw()
  10719. {
  10720. return (float) CharacterFunctions::getDoubleValue (text);
  10721. }
  10722. double String::getDoubleValue() const throw()
  10723. {
  10724. return CharacterFunctions::getDoubleValue (text);
  10725. }
  10726. static const juce_wchar* const hexDigits = JUCE_T("0123456789abcdef");
  10727. const String String::toHexString (const int number)
  10728. {
  10729. juce_wchar buffer[32];
  10730. juce_wchar* const end = buffer + 32;
  10731. juce_wchar* t = end;
  10732. *--t = 0;
  10733. unsigned int v = (unsigned int) number;
  10734. do
  10735. {
  10736. *--t = hexDigits [v & 15];
  10737. v >>= 4;
  10738. } while (v != 0);
  10739. return String (t, (int) (((char*) end) - (char*) t) - 1);
  10740. }
  10741. const String String::toHexString (const int64 number)
  10742. {
  10743. juce_wchar buffer[32];
  10744. juce_wchar* const end = buffer + 32;
  10745. juce_wchar* t = end;
  10746. *--t = 0;
  10747. uint64 v = (uint64) number;
  10748. do
  10749. {
  10750. *--t = hexDigits [(int) (v & 15)];
  10751. v >>= 4;
  10752. } while (v != 0);
  10753. return String (t, (int) (((char*) end) - (char*) t));
  10754. }
  10755. const String String::toHexString (const short number)
  10756. {
  10757. return toHexString ((int) (unsigned short) number);
  10758. }
  10759. const String String::toHexString (const unsigned char* data,
  10760. const int size,
  10761. const int groupSize)
  10762. {
  10763. if (size <= 0)
  10764. return empty;
  10765. int numChars = (size * 2) + 2;
  10766. if (groupSize > 0)
  10767. numChars += size / groupSize;
  10768. String s ((size_t) numChars, (int) 0);
  10769. juce_wchar* d = s.text;
  10770. for (int i = 0; i < size; ++i)
  10771. {
  10772. *d++ = hexDigits [(*data) >> 4];
  10773. *d++ = hexDigits [(*data) & 0xf];
  10774. ++data;
  10775. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  10776. *d++ = ' ';
  10777. }
  10778. *d = 0;
  10779. return s;
  10780. }
  10781. int String::getHexValue32() const throw()
  10782. {
  10783. int result = 0;
  10784. const juce_wchar* c = text;
  10785. for (;;)
  10786. {
  10787. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  10788. if (hexValue >= 0)
  10789. result = (result << 4) | hexValue;
  10790. else if (*c == 0)
  10791. break;
  10792. ++c;
  10793. }
  10794. return result;
  10795. }
  10796. int64 String::getHexValue64() const throw()
  10797. {
  10798. int64 result = 0;
  10799. const juce_wchar* c = text;
  10800. for (;;)
  10801. {
  10802. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  10803. if (hexValue >= 0)
  10804. result = (result << 4) | hexValue;
  10805. else if (*c == 0)
  10806. break;
  10807. ++c;
  10808. }
  10809. return result;
  10810. }
  10811. const String String::createStringFromData (const void* const data_, const int size)
  10812. {
  10813. const char* const data = static_cast <const char*> (data_);
  10814. if (size <= 0 || data == 0)
  10815. {
  10816. return empty;
  10817. }
  10818. else if (size < 2)
  10819. {
  10820. return charToString (data[0]);
  10821. }
  10822. else if ((data[0] == (char)-2 && data[1] == (char)-1)
  10823. || (data[0] == (char)-1 && data[1] == (char)-2))
  10824. {
  10825. // assume it's 16-bit unicode
  10826. const bool bigEndian = (data[0] == (char)-2);
  10827. const int numChars = size / 2 - 1;
  10828. String result;
  10829. result.preallocateStorage (numChars + 2);
  10830. const uint16* const src = (const uint16*) (data + 2);
  10831. juce_wchar* const dst = const_cast <juce_wchar*> (static_cast <const juce_wchar*> (result));
  10832. if (bigEndian)
  10833. {
  10834. for (int i = 0; i < numChars; ++i)
  10835. dst[i] = (juce_wchar) ByteOrder::swapIfLittleEndian (src[i]);
  10836. }
  10837. else
  10838. {
  10839. for (int i = 0; i < numChars; ++i)
  10840. dst[i] = (juce_wchar) ByteOrder::swapIfBigEndian (src[i]);
  10841. }
  10842. dst [numChars] = 0;
  10843. return result;
  10844. }
  10845. else
  10846. {
  10847. return String::fromUTF8 (data, size);
  10848. }
  10849. }
  10850. const char* String::toUTF8() const
  10851. {
  10852. if (isEmpty())
  10853. {
  10854. return reinterpret_cast <const char*> (text);
  10855. }
  10856. else
  10857. {
  10858. const int currentLen = length() + 1;
  10859. const int utf8BytesNeeded = getNumBytesAsUTF8();
  10860. String* const mutableThis = const_cast <String*> (this);
  10861. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, currentLen + 1 + utf8BytesNeeded / sizeof (juce_wchar));
  10862. char* const otherCopy = reinterpret_cast <char*> (mutableThis->text + currentLen);
  10863. #if JUCE_DEBUG // (This just avoids spurious warnings from valgrind about the uninitialised bytes at the end of the buffer..)
  10864. *(juce_wchar*) (otherCopy + (utf8BytesNeeded & ~(sizeof (juce_wchar) - 1))) = 0;
  10865. #endif
  10866. copyToUTF8 (otherCopy, std::numeric_limits<int>::max());
  10867. return otherCopy;
  10868. }
  10869. }
  10870. int String::copyToUTF8 (char* const buffer, const int maxBufferSizeBytes) const throw()
  10871. {
  10872. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  10873. int num = 0, index = 0;
  10874. for (;;)
  10875. {
  10876. const uint32 c = (uint32) text [index++];
  10877. if (c >= 0x80)
  10878. {
  10879. int numExtraBytes = 1;
  10880. if (c >= 0x800)
  10881. {
  10882. ++numExtraBytes;
  10883. if (c >= 0x10000)
  10884. {
  10885. ++numExtraBytes;
  10886. if (c >= 0x200000)
  10887. {
  10888. ++numExtraBytes;
  10889. if (c >= 0x4000000)
  10890. ++numExtraBytes;
  10891. }
  10892. }
  10893. }
  10894. if (buffer != 0)
  10895. {
  10896. if (num + numExtraBytes >= maxBufferSizeBytes)
  10897. {
  10898. buffer [num++] = 0;
  10899. break;
  10900. }
  10901. else
  10902. {
  10903. buffer [num++] = (uint8) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  10904. while (--numExtraBytes >= 0)
  10905. buffer [num++] = (uint8) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  10906. }
  10907. }
  10908. else
  10909. {
  10910. num += numExtraBytes + 1;
  10911. }
  10912. }
  10913. else
  10914. {
  10915. if (buffer != 0)
  10916. {
  10917. if (num + 1 >= maxBufferSizeBytes)
  10918. {
  10919. buffer [num++] = 0;
  10920. break;
  10921. }
  10922. buffer [num] = (uint8) c;
  10923. }
  10924. ++num;
  10925. }
  10926. if (c == 0)
  10927. break;
  10928. }
  10929. return num;
  10930. }
  10931. int String::getNumBytesAsUTF8() const throw()
  10932. {
  10933. int num = 0;
  10934. const juce_wchar* t = text;
  10935. for (;;)
  10936. {
  10937. const uint32 c = (uint32) *t;
  10938. if (c >= 0x80)
  10939. {
  10940. ++num;
  10941. if (c >= 0x800)
  10942. {
  10943. ++num;
  10944. if (c >= 0x10000)
  10945. {
  10946. ++num;
  10947. if (c >= 0x200000)
  10948. {
  10949. ++num;
  10950. if (c >= 0x4000000)
  10951. ++num;
  10952. }
  10953. }
  10954. }
  10955. }
  10956. else if (c == 0)
  10957. break;
  10958. ++num;
  10959. ++t;
  10960. }
  10961. return num;
  10962. }
  10963. const String String::fromUTF8 (const char* const buffer, int bufferSizeBytes)
  10964. {
  10965. if (buffer == 0)
  10966. return empty;
  10967. if (bufferSizeBytes < 0)
  10968. bufferSizeBytes = std::numeric_limits<int>::max();
  10969. size_t numBytes;
  10970. for (numBytes = 0; numBytes < (size_t) bufferSizeBytes; ++numBytes)
  10971. if (buffer [numBytes] == 0)
  10972. break;
  10973. String result ((size_t) numBytes + 1, (int) 0);
  10974. juce_wchar* dest = result.text;
  10975. size_t i = 0;
  10976. while (i < numBytes)
  10977. {
  10978. const char c = buffer [i++];
  10979. if (c < 0)
  10980. {
  10981. unsigned int mask = 0x7f;
  10982. int bit = 0x40;
  10983. int numExtraValues = 0;
  10984. while (bit != 0 && (c & bit) != 0)
  10985. {
  10986. bit >>= 1;
  10987. mask >>= 1;
  10988. ++numExtraValues;
  10989. }
  10990. int n = (mask & (unsigned char) c);
  10991. while (--numExtraValues >= 0 && i < (size_t) bufferSizeBytes)
  10992. {
  10993. const char nextByte = buffer[i];
  10994. if ((nextByte & 0xc0) != 0x80)
  10995. break;
  10996. n <<= 6;
  10997. n |= (nextByte & 0x3f);
  10998. ++i;
  10999. }
  11000. *dest++ = (juce_wchar) n;
  11001. }
  11002. else
  11003. {
  11004. *dest++ = (juce_wchar) c;
  11005. }
  11006. }
  11007. *dest = 0;
  11008. return result;
  11009. }
  11010. const char* String::toCString() const
  11011. {
  11012. if (isEmpty())
  11013. {
  11014. return reinterpret_cast <const char*> (text);
  11015. }
  11016. else
  11017. {
  11018. const int len = length();
  11019. String* const mutableThis = const_cast <String*> (this);
  11020. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, (len + 1) * 2);
  11021. char* otherCopy = reinterpret_cast <char*> (mutableThis->text + len + 1);
  11022. CharacterFunctions::copy (otherCopy, text, len);
  11023. otherCopy [len] = 0;
  11024. return otherCopy;
  11025. }
  11026. }
  11027. #if JUCE_MSVC
  11028. #pragma warning (push)
  11029. #pragma warning (disable: 4514 4996)
  11030. #endif
  11031. int String::getNumBytesAsCString() const throw()
  11032. {
  11033. return (int) wcstombs (0, text, 0);
  11034. }
  11035. int String::copyToCString (char* destBuffer, const int maxBufferSizeBytes) const throw()
  11036. {
  11037. const int numBytes = (int) wcstombs (destBuffer, text, maxBufferSizeBytes);
  11038. if (destBuffer != 0 && numBytes >= 0)
  11039. destBuffer [numBytes] = 0;
  11040. return numBytes;
  11041. }
  11042. #if JUCE_MSVC
  11043. #pragma warning (pop)
  11044. #endif
  11045. void String::copyToUnicode (juce_wchar* const destBuffer, const int maxCharsToCopy) const throw()
  11046. {
  11047. jassert (destBuffer != 0 && maxCharsToCopy >= 0);
  11048. if (destBuffer != 0 && maxCharsToCopy >= 0)
  11049. StringHolder::copyChars (destBuffer, text, jmin (maxCharsToCopy, length()));
  11050. }
  11051. String::Concatenator::Concatenator (String& stringToAppendTo)
  11052. : result (stringToAppendTo),
  11053. nextIndex (stringToAppendTo.length())
  11054. {
  11055. }
  11056. String::Concatenator::~Concatenator()
  11057. {
  11058. }
  11059. void String::Concatenator::append (const String& s)
  11060. {
  11061. const int len = s.length();
  11062. if (len > 0)
  11063. {
  11064. result.preallocateStorage (nextIndex + len);
  11065. s.copyToUnicode (static_cast <juce_wchar*> (result) + nextIndex, len);
  11066. nextIndex += len;
  11067. }
  11068. }
  11069. #if JUCE_UNIT_TESTS
  11070. class StringTests : public UnitTest
  11071. {
  11072. public:
  11073. StringTests() : UnitTest ("String class") {}
  11074. void runTest()
  11075. {
  11076. {
  11077. beginTest ("Basics");
  11078. expect (String().length() == 0);
  11079. expect (String() == String::empty);
  11080. String s1, s2 ("abcd");
  11081. expect (s1.isEmpty() && ! s1.isNotEmpty());
  11082. expect (s2.isNotEmpty() && ! s2.isEmpty());
  11083. expect (s2.length() == 4);
  11084. s1 = "abcd";
  11085. expect (s2 == s1 && s1 == s2);
  11086. expect (s1 == "abcd" && s1 == L"abcd");
  11087. expect (String ("abcd") == String (L"abcd"));
  11088. expect (String ("abcdefg", 4) == L"abcd");
  11089. expect (String ("abcdefg", 4) == String (L"abcdefg", 4));
  11090. expect (String::charToString ('x') == "x");
  11091. expect (String::charToString (0) == String::empty);
  11092. expect (s2 + "e" == "abcde" && s2 + 'e' == "abcde");
  11093. expect (s2 + L'e' == "abcde" && s2 + L"e" == "abcde");
  11094. expect (s1.equalsIgnoreCase ("abcD") && s1 < "abce" && s1 > "abbb");
  11095. expect (s1.startsWith ("ab") && s1.startsWith ("abcd") && ! s1.startsWith ("abcde"));
  11096. expect (s1.startsWithIgnoreCase ("aB") && s1.endsWithIgnoreCase ("CD"));
  11097. expect (s1.endsWith ("bcd") && ! s1.endsWith ("aabcd"));
  11098. expect (s1.indexOf (String::empty) == 0);
  11099. expect (s1.startsWith (String::empty) && s1.endsWith (String::empty) && s1.contains (String::empty));
  11100. expect (s1.contains ("cd") && s1.contains ("ab") && s1.contains ("abcd"));
  11101. expect (s1.containsChar ('a') && ! s1.containsChar (0));
  11102. expect (String ("abc foo bar").containsWholeWord ("abc") && String ("abc foo bar").containsWholeWord ("abc"));
  11103. }
  11104. {
  11105. beginTest ("Operations");
  11106. String s ("012345678");
  11107. expect (s.hashCode() != 0);
  11108. expect (s.hashCode64() != 0);
  11109. expect (s.hashCode() != (s + s).hashCode());
  11110. expect (s.hashCode64() != (s + s).hashCode64());
  11111. expect (s.compare (String ("012345678")) == 0);
  11112. expect (s.compare (String ("012345679")) < 0);
  11113. expect (s.compare (String ("012345676")) > 0);
  11114. expect (s.substring (2, 3) == String::charToString (s[2]));
  11115. expect (s.substring (0, 1) == String::charToString (s[0]));
  11116. expect (s.getLastCharacter() == s [s.length() - 1]);
  11117. expect (String::charToString (s.getLastCharacter()) == s.getLastCharacters (1));
  11118. expect (s.substring (0, 3) == L"012");
  11119. expect (s.substring (0, 100) == s);
  11120. expect (s.substring (-1, 100) == s);
  11121. expect (s.substring (3) == "345678");
  11122. expect (s.indexOf (L"45") == 4);
  11123. expect (String ("444445").indexOf ("45") == 4);
  11124. expect (String ("444445").lastIndexOfChar ('4') == 4);
  11125. expect (String ("45454545x").lastIndexOf (L"45") == 6);
  11126. expect (String ("45454545x").lastIndexOfAnyOf ("456") == 7);
  11127. expect (String ("45454545x").lastIndexOfAnyOf (L"456x") == 8);
  11128. expect (String ("abABaBaBa").lastIndexOfIgnoreCase ("Ab") == 6);
  11129. expect (s.indexOfChar (L'4') == 4);
  11130. expect (s + s == "012345678012345678");
  11131. expect (s.startsWith (s));
  11132. expect (s.startsWith (s.substring (0, 4)));
  11133. expect (s.startsWith (s.dropLastCharacters (4)));
  11134. expect (s.endsWith (s.substring (5)));
  11135. expect (s.endsWith (s));
  11136. expect (s.contains (s.substring (3, 6)));
  11137. expect (s.contains (s.substring (3)));
  11138. expect (s.startsWithChar (s[0]));
  11139. expect (s.endsWithChar (s.getLastCharacter()));
  11140. expect (s [s.length()] == 0);
  11141. expect (String ("abcdEFGH").toLowerCase() == String ("abcdefgh"));
  11142. expect (String ("abcdEFGH").toUpperCase() == String ("ABCDEFGH"));
  11143. String s2 ("123");
  11144. s2 << ((int) 4) << ((short) 5) << "678" << L"9" << '0';
  11145. s2 += "xyz";
  11146. expect (s2 == "1234567890xyz");
  11147. beginTest ("Numeric conversions");
  11148. expect (String::empty.getIntValue() == 0);
  11149. expect (String::empty.getDoubleValue() == 0.0);
  11150. expect (String::empty.getFloatValue() == 0.0f);
  11151. expect (s.getIntValue() == 12345678);
  11152. expect (s.getLargeIntValue() == (int64) 12345678);
  11153. expect (s.getDoubleValue() == 12345678.0);
  11154. expect (s.getFloatValue() == 12345678.0f);
  11155. expect (String (-1234).getIntValue() == -1234);
  11156. expect (String ((int64) -1234).getLargeIntValue() == -1234);
  11157. expect (String (-1234.56).getDoubleValue() == -1234.56);
  11158. expect (String (-1234.56f).getFloatValue() == -1234.56f);
  11159. expect (("xyz" + s).getTrailingIntValue() == s.getIntValue());
  11160. expect (s.getHexValue32() == 0x12345678);
  11161. expect (s.getHexValue64() == (int64) 0x12345678);
  11162. expect (String::toHexString (0x1234abcd).equalsIgnoreCase ("1234abcd"));
  11163. expect (String::toHexString ((int64) 0x1234abcd).equalsIgnoreCase ("1234abcd"));
  11164. expect (String::toHexString ((short) 0x12ab).equalsIgnoreCase ("12ab"));
  11165. unsigned char data[] = { 1, 2, 3, 4, 0xa, 0xb, 0xc, 0xd };
  11166. expect (String::toHexString (data, 8, 0).equalsIgnoreCase ("010203040a0b0c0d"));
  11167. expect (String::toHexString (data, 8, 1).equalsIgnoreCase ("01 02 03 04 0a 0b 0c 0d"));
  11168. expect (String::toHexString (data, 8, 2).equalsIgnoreCase ("0102 0304 0a0b 0c0d"));
  11169. beginTest ("Subsections");
  11170. String s3;
  11171. s3 = "abcdeFGHIJ";
  11172. expect (s3.equalsIgnoreCase ("ABCdeFGhiJ"));
  11173. expect (s3.compareIgnoreCase (L"ABCdeFGhiJ") == 0);
  11174. expect (s3.containsIgnoreCase (s3.substring (3)));
  11175. expect (s3.indexOfAnyOf ("xyzf", 2, true) == 5);
  11176. expect (s3.indexOfAnyOf (L"xyzf", 2, false) == -1);
  11177. expect (s3.indexOfAnyOf ("xyzF", 2, false) == 5);
  11178. expect (s3.containsAnyOf (L"zzzFs"));
  11179. expect (s3.startsWith ("abcd"));
  11180. expect (s3.startsWithIgnoreCase (L"abCD"));
  11181. expect (s3.startsWith (String::empty));
  11182. expect (s3.startsWithChar ('a'));
  11183. expect (s3.endsWith (String ("HIJ")));
  11184. expect (s3.endsWithIgnoreCase (L"Hij"));
  11185. expect (s3.endsWith (String::empty));
  11186. expect (s3.endsWithChar (L'J'));
  11187. expect (s3.indexOf ("HIJ") == 7);
  11188. expect (s3.indexOf (L"HIJK") == -1);
  11189. expect (s3.indexOfIgnoreCase ("hij") == 7);
  11190. expect (s3.indexOfIgnoreCase (L"hijk") == -1);
  11191. String s4 (s3);
  11192. s4.append (String ("xyz123"), 3);
  11193. expect (s4 == s3 + "xyz");
  11194. expect (String (1234) < String (1235));
  11195. expect (String (1235) > String (1234));
  11196. expect (String (1234) >= String (1234));
  11197. expect (String (1234) <= String (1234));
  11198. expect (String (1235) >= String (1234));
  11199. expect (String (1234) <= String (1235));
  11200. String s5 ("word word2 word3");
  11201. expect (s5.containsWholeWord (String ("word2")));
  11202. expect (s5.indexOfWholeWord ("word2") == 5);
  11203. expect (s5.containsWholeWord (L"word"));
  11204. expect (s5.containsWholeWord ("word3"));
  11205. expect (s5.containsWholeWord (s5));
  11206. expect (s5.containsWholeWordIgnoreCase (L"Word2"));
  11207. expect (s5.indexOfWholeWordIgnoreCase ("Word2") == 5);
  11208. expect (s5.containsWholeWordIgnoreCase (L"Word"));
  11209. expect (s5.containsWholeWordIgnoreCase ("Word3"));
  11210. expect (! s5.containsWholeWordIgnoreCase (L"Wordx"));
  11211. expect (!s5.containsWholeWordIgnoreCase ("xWord2"));
  11212. expect (s5.containsNonWhitespaceChars());
  11213. expect (! String (" \n\r\t").containsNonWhitespaceChars());
  11214. expect (s5.matchesWildcard (L"wor*", false));
  11215. expect (s5.matchesWildcard ("wOr*", true));
  11216. expect (s5.matchesWildcard (L"*word3", true));
  11217. expect (s5.matchesWildcard ("*word?", true));
  11218. expect (s5.matchesWildcard (L"Word*3", true));
  11219. expect (s5.fromFirstOccurrenceOf (String::empty, true, false) == s5);
  11220. expect (s5.fromFirstOccurrenceOf ("xword2", true, false) == s5.substring (100));
  11221. expect (s5.fromFirstOccurrenceOf (L"word2", true, false) == s5.substring (5));
  11222. expect (s5.fromFirstOccurrenceOf ("Word2", true, true) == s5.substring (5));
  11223. expect (s5.fromFirstOccurrenceOf ("word2", false, false) == s5.getLastCharacters (6));
  11224. expect (s5.fromFirstOccurrenceOf (L"Word2", false, true) == s5.getLastCharacters (6));
  11225. expect (s5.fromLastOccurrenceOf (String::empty, true, false) == s5);
  11226. expect (s5.fromLastOccurrenceOf (L"wordx", true, false) == s5);
  11227. expect (s5.fromLastOccurrenceOf ("word", true, false) == s5.getLastCharacters (5));
  11228. expect (s5.fromLastOccurrenceOf (L"worD", true, true) == s5.getLastCharacters (5));
  11229. expect (s5.fromLastOccurrenceOf ("word", false, false) == s5.getLastCharacters (1));
  11230. expect (s5.fromLastOccurrenceOf (L"worD", false, true) == s5.getLastCharacters (1));
  11231. expect (s5.upToFirstOccurrenceOf (String::empty, true, false).isEmpty());
  11232. expect (s5.upToFirstOccurrenceOf ("word4", true, false) == s5);
  11233. expect (s5.upToFirstOccurrenceOf (L"word2", true, false) == s5.substring (0, 10));
  11234. expect (s5.upToFirstOccurrenceOf ("Word2", true, true) == s5.substring (0, 10));
  11235. expect (s5.upToFirstOccurrenceOf (L"word2", false, false) == s5.substring (0, 5));
  11236. expect (s5.upToFirstOccurrenceOf ("Word2", false, true) == s5.substring (0, 5));
  11237. expect (s5.upToLastOccurrenceOf (String::empty, true, false) == s5);
  11238. expect (s5.upToLastOccurrenceOf ("zword", true, false) == s5);
  11239. expect (s5.upToLastOccurrenceOf ("word", true, false) == s5.dropLastCharacters (1));
  11240. expect (s5.dropLastCharacters(1).upToLastOccurrenceOf ("word", true, false) == s5.dropLastCharacters (1));
  11241. expect (s5.upToLastOccurrenceOf ("Word", true, true) == s5.dropLastCharacters (1));
  11242. expect (s5.upToLastOccurrenceOf ("word", false, false) == s5.dropLastCharacters (5));
  11243. expect (s5.upToLastOccurrenceOf ("Word", false, true) == s5.dropLastCharacters (5));
  11244. expect (s5.replace ("word", L"xyz", false) == String ("xyz xyz2 xyz3"));
  11245. expect (s5.replace (L"Word", "xyz", true) == "xyz xyz2 xyz3");
  11246. expect (s5.dropLastCharacters (1).replace ("Word", String ("xyz"), true) == L"xyz xyz2 xyz");
  11247. expect (s5.replace ("Word", "", true) == " 2 3");
  11248. expect (s5.replace ("Word2", L"xyz", true) == String ("word xyz word3"));
  11249. expect (s5.replaceCharacter (L'w', 'x') != s5);
  11250. expect (s5.replaceCharacter ('w', L'x').replaceCharacter ('x', 'w') == s5);
  11251. expect (s5.replaceCharacters ("wo", "xy") != s5);
  11252. expect (s5.replaceCharacters ("wo", "xy").replaceCharacters ("xy", L"wo") == s5);
  11253. expect (s5.retainCharacters ("1wordxya") == String ("wordwordword"));
  11254. expect (s5.retainCharacters (String::empty).isEmpty());
  11255. expect (s5.removeCharacters ("1wordxya") == " 2 3");
  11256. expect (s5.removeCharacters (String::empty) == s5);
  11257. expect (s5.initialSectionContainingOnly ("word") == L"word");
  11258. expect (s5.initialSectionNotContaining (String ("xyz ")) == String ("word"));
  11259. expect (! s5.isQuotedString());
  11260. expect (s5.quoted().isQuotedString());
  11261. expect (! s5.quoted().unquoted().isQuotedString());
  11262. expect (! String ("x'").isQuotedString());
  11263. expect (String ("'x").isQuotedString());
  11264. String s6 (" \t xyz \t\r\n");
  11265. expect (s6.trim() == String ("xyz"));
  11266. expect (s6.trim().trim() == "xyz");
  11267. expect (s5.trim() == s5);
  11268. expect (s6.trimStart().trimEnd() == s6.trim());
  11269. expect (s6.trimStart().trimEnd() == s6.trimEnd().trimStart());
  11270. expect (s6.trimStart().trimStart().trimEnd().trimEnd() == s6.trimEnd().trimStart());
  11271. expect (s6.trimStart() != s6.trimEnd());
  11272. expect (("\t\r\n " + s6 + "\t\n \r").trim() == s6.trim());
  11273. expect (String::repeatedString ("xyz", 3) == L"xyzxyzxyz");
  11274. }
  11275. {
  11276. beginTest ("UTF8");
  11277. String s ("word word2 word3");
  11278. {
  11279. char buffer [100];
  11280. memset (buffer, 0xff, sizeof (buffer));
  11281. s.copyToUTF8 (buffer, 100);
  11282. expect (String::fromUTF8 (buffer, 100) == s);
  11283. juce_wchar bufferUnicode [100];
  11284. memset (bufferUnicode, 0xff, sizeof (bufferUnicode));
  11285. s.copyToUnicode (bufferUnicode, 100);
  11286. expect (String (bufferUnicode, 100) == s);
  11287. }
  11288. {
  11289. juce_wchar wideBuffer [50];
  11290. zerostruct (wideBuffer);
  11291. for (int i = 0; i < numElementsInArray (wideBuffer) - 1; ++i)
  11292. wideBuffer[i] = (juce_wchar) (1 + Random::getSystemRandom().nextInt (std::numeric_limits<juce_wchar>::max() - 1));
  11293. String wide (wideBuffer);
  11294. expect (wide == (const juce_wchar*) wideBuffer);
  11295. expect (wide.length() == numElementsInArray (wideBuffer) - 1);
  11296. expect (String::fromUTF8 (wide.toUTF8()) == wide);
  11297. expect (String::fromUTF8 (wide.toUTF8()) == wideBuffer);
  11298. }
  11299. }
  11300. }
  11301. };
  11302. static StringTests stringUnitTests;
  11303. #endif
  11304. END_JUCE_NAMESPACE
  11305. /*** End of inlined file: juce_String.cpp ***/
  11306. /*** Start of inlined file: juce_StringArray.cpp ***/
  11307. BEGIN_JUCE_NAMESPACE
  11308. StringArray::StringArray() throw()
  11309. {
  11310. }
  11311. StringArray::StringArray (const StringArray& other)
  11312. : strings (other.strings)
  11313. {
  11314. }
  11315. StringArray::StringArray (const String& firstValue)
  11316. {
  11317. strings.add (firstValue);
  11318. }
  11319. StringArray::StringArray (const juce_wchar* const* const initialStrings,
  11320. const int numberOfStrings)
  11321. {
  11322. for (int i = 0; i < numberOfStrings; ++i)
  11323. strings.add (initialStrings [i]);
  11324. }
  11325. StringArray::StringArray (const char* const* const initialStrings,
  11326. const int numberOfStrings)
  11327. {
  11328. for (int i = 0; i < numberOfStrings; ++i)
  11329. strings.add (initialStrings [i]);
  11330. }
  11331. StringArray::StringArray (const juce_wchar* const* const initialStrings)
  11332. {
  11333. int i = 0;
  11334. while (initialStrings[i] != 0)
  11335. strings.add (initialStrings [i++]);
  11336. }
  11337. StringArray::StringArray (const char* const* const initialStrings)
  11338. {
  11339. int i = 0;
  11340. while (initialStrings[i] != 0)
  11341. strings.add (initialStrings [i++]);
  11342. }
  11343. StringArray& StringArray::operator= (const StringArray& other)
  11344. {
  11345. strings = other.strings;
  11346. return *this;
  11347. }
  11348. StringArray::~StringArray()
  11349. {
  11350. }
  11351. bool StringArray::operator== (const StringArray& other) const throw()
  11352. {
  11353. if (other.size() != size())
  11354. return false;
  11355. for (int i = size(); --i >= 0;)
  11356. if (other.strings.getReference(i) != strings.getReference(i))
  11357. return false;
  11358. return true;
  11359. }
  11360. bool StringArray::operator!= (const StringArray& other) const throw()
  11361. {
  11362. return ! operator== (other);
  11363. }
  11364. void StringArray::clear()
  11365. {
  11366. strings.clear();
  11367. }
  11368. const String& StringArray::operator[] (const int index) const throw()
  11369. {
  11370. if (((unsigned int) index) < (unsigned int) strings.size())
  11371. return strings.getReference (index);
  11372. return String::empty;
  11373. }
  11374. String& StringArray::getReference (const int index) throw()
  11375. {
  11376. jassert (((unsigned int) index) < (unsigned int) strings.size());
  11377. return strings.getReference (index);
  11378. }
  11379. void StringArray::add (const String& newString)
  11380. {
  11381. strings.add (newString);
  11382. }
  11383. void StringArray::insert (const int index, const String& newString)
  11384. {
  11385. strings.insert (index, newString);
  11386. }
  11387. void StringArray::addIfNotAlreadyThere (const String& newString, const bool ignoreCase)
  11388. {
  11389. if (! contains (newString, ignoreCase))
  11390. add (newString);
  11391. }
  11392. void StringArray::addArray (const StringArray& otherArray, int startIndex, int numElementsToAdd)
  11393. {
  11394. if (startIndex < 0)
  11395. {
  11396. jassertfalse;
  11397. startIndex = 0;
  11398. }
  11399. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  11400. numElementsToAdd = otherArray.size() - startIndex;
  11401. while (--numElementsToAdd >= 0)
  11402. strings.add (otherArray.strings.getReference (startIndex++));
  11403. }
  11404. void StringArray::set (const int index, const String& newString)
  11405. {
  11406. strings.set (index, newString);
  11407. }
  11408. bool StringArray::contains (const String& stringToLookFor, const bool ignoreCase) const
  11409. {
  11410. if (ignoreCase)
  11411. {
  11412. for (int i = size(); --i >= 0;)
  11413. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  11414. return true;
  11415. }
  11416. else
  11417. {
  11418. for (int i = size(); --i >= 0;)
  11419. if (stringToLookFor == strings.getReference(i))
  11420. return true;
  11421. }
  11422. return false;
  11423. }
  11424. int StringArray::indexOf (const String& stringToLookFor, const bool ignoreCase, int i) const
  11425. {
  11426. if (i < 0)
  11427. i = 0;
  11428. const int numElements = size();
  11429. if (ignoreCase)
  11430. {
  11431. while (i < numElements)
  11432. {
  11433. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  11434. return i;
  11435. ++i;
  11436. }
  11437. }
  11438. else
  11439. {
  11440. while (i < numElements)
  11441. {
  11442. if (stringToLookFor == strings.getReference (i))
  11443. return i;
  11444. ++i;
  11445. }
  11446. }
  11447. return -1;
  11448. }
  11449. void StringArray::remove (const int index)
  11450. {
  11451. strings.remove (index);
  11452. }
  11453. void StringArray::removeString (const String& stringToRemove,
  11454. const bool ignoreCase)
  11455. {
  11456. if (ignoreCase)
  11457. {
  11458. for (int i = size(); --i >= 0;)
  11459. if (strings.getReference(i).equalsIgnoreCase (stringToRemove))
  11460. strings.remove (i);
  11461. }
  11462. else
  11463. {
  11464. for (int i = size(); --i >= 0;)
  11465. if (stringToRemove == strings.getReference (i))
  11466. strings.remove (i);
  11467. }
  11468. }
  11469. void StringArray::removeRange (int startIndex, int numberToRemove)
  11470. {
  11471. strings.removeRange (startIndex, numberToRemove);
  11472. }
  11473. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings)
  11474. {
  11475. if (removeWhitespaceStrings)
  11476. {
  11477. for (int i = size(); --i >= 0;)
  11478. if (! strings.getReference(i).containsNonWhitespaceChars())
  11479. strings.remove (i);
  11480. }
  11481. else
  11482. {
  11483. for (int i = size(); --i >= 0;)
  11484. if (strings.getReference(i).isEmpty())
  11485. strings.remove (i);
  11486. }
  11487. }
  11488. void StringArray::trim()
  11489. {
  11490. for (int i = size(); --i >= 0;)
  11491. {
  11492. String& s = strings.getReference(i);
  11493. s = s.trim();
  11494. }
  11495. }
  11496. class InternalStringArrayComparator_CaseSensitive
  11497. {
  11498. public:
  11499. static int compareElements (String& first, String& second) { return first.compare (second); }
  11500. };
  11501. class InternalStringArrayComparator_CaseInsensitive
  11502. {
  11503. public:
  11504. static int compareElements (String& first, String& second) { return first.compareIgnoreCase (second); }
  11505. };
  11506. void StringArray::sort (const bool ignoreCase)
  11507. {
  11508. if (ignoreCase)
  11509. {
  11510. InternalStringArrayComparator_CaseInsensitive comp;
  11511. strings.sort (comp);
  11512. }
  11513. else
  11514. {
  11515. InternalStringArrayComparator_CaseSensitive comp;
  11516. strings.sort (comp);
  11517. }
  11518. }
  11519. void StringArray::move (const int currentIndex, int newIndex) throw()
  11520. {
  11521. strings.move (currentIndex, newIndex);
  11522. }
  11523. const String StringArray::joinIntoString (const String& separator, int start, int numberToJoin) const
  11524. {
  11525. const int last = (numberToJoin < 0) ? size()
  11526. : jmin (size(), start + numberToJoin);
  11527. if (start < 0)
  11528. start = 0;
  11529. if (start >= last)
  11530. return String::empty;
  11531. if (start == last - 1)
  11532. return strings.getReference (start);
  11533. const int separatorLen = separator.length();
  11534. int charsNeeded = separatorLen * (last - start - 1);
  11535. for (int i = start; i < last; ++i)
  11536. charsNeeded += strings.getReference(i).length();
  11537. String result;
  11538. result.preallocateStorage (charsNeeded);
  11539. juce_wchar* dest = result;
  11540. while (start < last)
  11541. {
  11542. const String& s = strings.getReference (start);
  11543. const int len = s.length();
  11544. if (len > 0)
  11545. {
  11546. s.copyToUnicode (dest, len);
  11547. dest += len;
  11548. }
  11549. if (++start < last && separatorLen > 0)
  11550. {
  11551. separator.copyToUnicode (dest, separatorLen);
  11552. dest += separatorLen;
  11553. }
  11554. }
  11555. *dest = 0;
  11556. return result;
  11557. }
  11558. int StringArray::addTokens (const String& text, const bool preserveQuotedStrings)
  11559. {
  11560. return addTokens (text, " \n\r\t", preserveQuotedStrings ? "\"" : "");
  11561. }
  11562. int StringArray::addTokens (const String& text, const String& breakCharacters, const String& quoteCharacters)
  11563. {
  11564. int num = 0;
  11565. if (text.isNotEmpty())
  11566. {
  11567. bool insideQuotes = false;
  11568. juce_wchar currentQuoteChar = 0;
  11569. int i = 0;
  11570. int tokenStart = 0;
  11571. for (;;)
  11572. {
  11573. const juce_wchar c = text[i];
  11574. const bool isBreak = (c == 0) || ((! insideQuotes) && breakCharacters.containsChar (c));
  11575. if (! isBreak)
  11576. {
  11577. if (quoteCharacters.containsChar (c))
  11578. {
  11579. if (insideQuotes)
  11580. {
  11581. // only break out of quotes-mode if we find a matching quote to the
  11582. // one that we opened with..
  11583. if (currentQuoteChar == c)
  11584. insideQuotes = false;
  11585. }
  11586. else
  11587. {
  11588. insideQuotes = true;
  11589. currentQuoteChar = c;
  11590. }
  11591. }
  11592. }
  11593. else
  11594. {
  11595. add (String (static_cast <const juce_wchar*> (text) + tokenStart, i - tokenStart));
  11596. ++num;
  11597. tokenStart = i + 1;
  11598. }
  11599. if (c == 0)
  11600. break;
  11601. ++i;
  11602. }
  11603. }
  11604. return num;
  11605. }
  11606. int StringArray::addLines (const String& sourceText)
  11607. {
  11608. int numLines = 0;
  11609. const juce_wchar* text = sourceText;
  11610. while (*text != 0)
  11611. {
  11612. const juce_wchar* const startOfLine = text;
  11613. while (*text != 0)
  11614. {
  11615. if (*text == '\r')
  11616. {
  11617. ++text;
  11618. if (*text == '\n')
  11619. ++text;
  11620. break;
  11621. }
  11622. if (*text == '\n')
  11623. {
  11624. ++text;
  11625. break;
  11626. }
  11627. ++text;
  11628. }
  11629. const juce_wchar* endOfLine = text;
  11630. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  11631. --endOfLine;
  11632. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  11633. --endOfLine;
  11634. add (String (startOfLine, jmax (0, (int) (endOfLine - startOfLine))));
  11635. ++numLines;
  11636. }
  11637. return numLines;
  11638. }
  11639. void StringArray::removeDuplicates (const bool ignoreCase)
  11640. {
  11641. for (int i = 0; i < size() - 1; ++i)
  11642. {
  11643. const String s (strings.getReference(i));
  11644. int nextIndex = i + 1;
  11645. for (;;)
  11646. {
  11647. nextIndex = indexOf (s, ignoreCase, nextIndex);
  11648. if (nextIndex < 0)
  11649. break;
  11650. strings.remove (nextIndex);
  11651. }
  11652. }
  11653. }
  11654. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  11655. const bool appendNumberToFirstInstance,
  11656. const juce_wchar* preNumberString,
  11657. const juce_wchar* postNumberString)
  11658. {
  11659. if (preNumberString == 0)
  11660. preNumberString = L" (";
  11661. if (postNumberString == 0)
  11662. postNumberString = L")";
  11663. for (int i = 0; i < size() - 1; ++i)
  11664. {
  11665. String& s = strings.getReference(i);
  11666. int nextIndex = indexOf (s, ignoreCase, i + 1);
  11667. if (nextIndex >= 0)
  11668. {
  11669. const String original (s);
  11670. int number = 0;
  11671. if (appendNumberToFirstInstance)
  11672. s = original + preNumberString + String (++number) + postNumberString;
  11673. else
  11674. ++number;
  11675. while (nextIndex >= 0)
  11676. {
  11677. set (nextIndex, (*this)[nextIndex] + preNumberString + String (++number) + postNumberString);
  11678. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  11679. }
  11680. }
  11681. }
  11682. }
  11683. void StringArray::minimiseStorageOverheads()
  11684. {
  11685. strings.minimiseStorageOverheads();
  11686. }
  11687. END_JUCE_NAMESPACE
  11688. /*** End of inlined file: juce_StringArray.cpp ***/
  11689. /*** Start of inlined file: juce_StringPairArray.cpp ***/
  11690. BEGIN_JUCE_NAMESPACE
  11691. StringPairArray::StringPairArray (const bool ignoreCase_)
  11692. : ignoreCase (ignoreCase_)
  11693. {
  11694. }
  11695. StringPairArray::StringPairArray (const StringPairArray& other)
  11696. : keys (other.keys),
  11697. values (other.values),
  11698. ignoreCase (other.ignoreCase)
  11699. {
  11700. }
  11701. StringPairArray::~StringPairArray()
  11702. {
  11703. }
  11704. StringPairArray& StringPairArray::operator= (const StringPairArray& other)
  11705. {
  11706. keys = other.keys;
  11707. values = other.values;
  11708. return *this;
  11709. }
  11710. bool StringPairArray::operator== (const StringPairArray& other) const
  11711. {
  11712. for (int i = keys.size(); --i >= 0;)
  11713. if (other [keys[i]] != values[i])
  11714. return false;
  11715. return true;
  11716. }
  11717. bool StringPairArray::operator!= (const StringPairArray& other) const
  11718. {
  11719. return ! operator== (other);
  11720. }
  11721. const String& StringPairArray::operator[] (const String& key) const
  11722. {
  11723. return values [keys.indexOf (key, ignoreCase)];
  11724. }
  11725. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  11726. {
  11727. const int i = keys.indexOf (key, ignoreCase);
  11728. if (i >= 0)
  11729. return values[i];
  11730. return defaultReturnValue;
  11731. }
  11732. void StringPairArray::set (const String& key, const String& value)
  11733. {
  11734. const int i = keys.indexOf (key, ignoreCase);
  11735. if (i >= 0)
  11736. {
  11737. values.set (i, value);
  11738. }
  11739. else
  11740. {
  11741. keys.add (key);
  11742. values.add (value);
  11743. }
  11744. }
  11745. void StringPairArray::addArray (const StringPairArray& other)
  11746. {
  11747. for (int i = 0; i < other.size(); ++i)
  11748. set (other.keys[i], other.values[i]);
  11749. }
  11750. void StringPairArray::clear()
  11751. {
  11752. keys.clear();
  11753. values.clear();
  11754. }
  11755. void StringPairArray::remove (const String& key)
  11756. {
  11757. remove (keys.indexOf (key, ignoreCase));
  11758. }
  11759. void StringPairArray::remove (const int index)
  11760. {
  11761. keys.remove (index);
  11762. values.remove (index);
  11763. }
  11764. void StringPairArray::setIgnoresCase (const bool shouldIgnoreCase)
  11765. {
  11766. ignoreCase = shouldIgnoreCase;
  11767. }
  11768. const String StringPairArray::getDescription() const
  11769. {
  11770. String s;
  11771. for (int i = 0; i < keys.size(); ++i)
  11772. {
  11773. s << keys[i] << " = " << values[i];
  11774. if (i < keys.size())
  11775. s << ", ";
  11776. }
  11777. return s;
  11778. }
  11779. void StringPairArray::minimiseStorageOverheads()
  11780. {
  11781. keys.minimiseStorageOverheads();
  11782. values.minimiseStorageOverheads();
  11783. }
  11784. END_JUCE_NAMESPACE
  11785. /*** End of inlined file: juce_StringPairArray.cpp ***/
  11786. /*** Start of inlined file: juce_StringPool.cpp ***/
  11787. BEGIN_JUCE_NAMESPACE
  11788. StringPool::StringPool() throw() {}
  11789. StringPool::~StringPool() {}
  11790. template <class StringType>
  11791. static const juce_wchar* getPooledStringFromArray (Array<String>& strings, StringType newString)
  11792. {
  11793. int start = 0;
  11794. int end = strings.size();
  11795. for (;;)
  11796. {
  11797. if (start >= end)
  11798. {
  11799. jassert (start <= end);
  11800. strings.insert (start, newString);
  11801. return strings.getReference (start);
  11802. }
  11803. else
  11804. {
  11805. const String& startString = strings.getReference (start);
  11806. if (startString == newString)
  11807. return startString;
  11808. const int halfway = (start + end) >> 1;
  11809. if (halfway == start)
  11810. {
  11811. if (startString.compare (newString) < 0)
  11812. ++start;
  11813. strings.insert (start, newString);
  11814. return strings.getReference (start);
  11815. }
  11816. const int comp = strings.getReference (halfway).compare (newString);
  11817. if (comp == 0)
  11818. return strings.getReference (halfway);
  11819. else if (comp < 0)
  11820. start = halfway;
  11821. else
  11822. end = halfway;
  11823. }
  11824. }
  11825. }
  11826. const juce_wchar* StringPool::getPooledString (const String& s)
  11827. {
  11828. if (s.isEmpty())
  11829. return String::empty;
  11830. return getPooledStringFromArray (strings, s);
  11831. }
  11832. const juce_wchar* StringPool::getPooledString (const char* const s)
  11833. {
  11834. if (s == 0 || *s == 0)
  11835. return String::empty;
  11836. return getPooledStringFromArray (strings, s);
  11837. }
  11838. const juce_wchar* StringPool::getPooledString (const juce_wchar* const s)
  11839. {
  11840. if (s == 0 || *s == 0)
  11841. return String::empty;
  11842. return getPooledStringFromArray (strings, s);
  11843. }
  11844. int StringPool::size() const throw()
  11845. {
  11846. return strings.size();
  11847. }
  11848. const juce_wchar* StringPool::operator[] (const int index) const throw()
  11849. {
  11850. return strings [index];
  11851. }
  11852. END_JUCE_NAMESPACE
  11853. /*** End of inlined file: juce_StringPool.cpp ***/
  11854. /*** Start of inlined file: juce_XmlDocument.cpp ***/
  11855. BEGIN_JUCE_NAMESPACE
  11856. XmlDocument::XmlDocument (const String& documentText)
  11857. : originalText (documentText),
  11858. ignoreEmptyTextElements (true)
  11859. {
  11860. }
  11861. XmlDocument::XmlDocument (const File& file)
  11862. : ignoreEmptyTextElements (true)
  11863. {
  11864. inputSource = new FileInputSource (file);
  11865. }
  11866. XmlDocument::~XmlDocument()
  11867. {
  11868. }
  11869. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  11870. {
  11871. inputSource = newSource;
  11872. }
  11873. void XmlDocument::setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw()
  11874. {
  11875. ignoreEmptyTextElements = shouldBeIgnored;
  11876. }
  11877. bool XmlDocument::isXmlIdentifierCharSlow (const juce_wchar c) throw()
  11878. {
  11879. return CharacterFunctions::isLetterOrDigit (c)
  11880. || c == '_' || c == '-' || c == ':' || c == '.';
  11881. }
  11882. inline bool XmlDocument::isXmlIdentifierChar (const juce_wchar c) const throw()
  11883. {
  11884. return (c > 0 && c <= 127) ? identifierLookupTable [(int) c]
  11885. : isXmlIdentifierCharSlow (c);
  11886. }
  11887. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  11888. {
  11889. String textToParse (originalText);
  11890. if (textToParse.isEmpty() && inputSource != 0)
  11891. {
  11892. ScopedPointer <InputStream> in (inputSource->createInputStream());
  11893. if (in != 0)
  11894. {
  11895. MemoryOutputStream data;
  11896. data.writeFromInputStream (*in, onlyReadOuterDocumentElement ? 8192 : -1);
  11897. textToParse = data.toString();
  11898. if (! onlyReadOuterDocumentElement)
  11899. originalText = textToParse;
  11900. }
  11901. }
  11902. input = textToParse;
  11903. lastError = String::empty;
  11904. errorOccurred = false;
  11905. outOfData = false;
  11906. needToLoadDTD = true;
  11907. for (int i = 0; i < 128; ++i)
  11908. identifierLookupTable[i] = isXmlIdentifierCharSlow ((juce_wchar) i);
  11909. if (textToParse.isEmpty())
  11910. {
  11911. lastError = "not enough input";
  11912. }
  11913. else
  11914. {
  11915. skipHeader();
  11916. if (input != 0)
  11917. {
  11918. ScopedPointer <XmlElement> result (readNextElement (! onlyReadOuterDocumentElement));
  11919. if (! errorOccurred)
  11920. return result.release();
  11921. }
  11922. else
  11923. {
  11924. lastError = "incorrect xml header";
  11925. }
  11926. }
  11927. return 0;
  11928. }
  11929. const String& XmlDocument::getLastParseError() const throw()
  11930. {
  11931. return lastError;
  11932. }
  11933. void XmlDocument::setLastError (const String& desc, const bool carryOn)
  11934. {
  11935. lastError = desc;
  11936. errorOccurred = ! carryOn;
  11937. }
  11938. const String XmlDocument::getFileContents (const String& filename) const
  11939. {
  11940. if (inputSource != 0)
  11941. {
  11942. const ScopedPointer <InputStream> in (inputSource->createInputStreamFor (filename.trim().unquoted()));
  11943. if (in != 0)
  11944. return in->readEntireStreamAsString();
  11945. }
  11946. return String::empty;
  11947. }
  11948. juce_wchar XmlDocument::readNextChar() throw()
  11949. {
  11950. if (*input != 0)
  11951. {
  11952. return *input++;
  11953. }
  11954. else
  11955. {
  11956. outOfData = true;
  11957. return 0;
  11958. }
  11959. }
  11960. int XmlDocument::findNextTokenLength() throw()
  11961. {
  11962. int len = 0;
  11963. juce_wchar c = *input;
  11964. while (isXmlIdentifierChar (c))
  11965. c = input [++len];
  11966. return len;
  11967. }
  11968. void XmlDocument::skipHeader()
  11969. {
  11970. const juce_wchar* const found = CharacterFunctions::find (input, JUCE_T("<?xml"));
  11971. if (found != 0)
  11972. {
  11973. input = found;
  11974. input = CharacterFunctions::find (input, JUCE_T("?>"));
  11975. if (input == 0)
  11976. return;
  11977. input += 2;
  11978. }
  11979. skipNextWhiteSpace();
  11980. const juce_wchar* docType = CharacterFunctions::find (input, JUCE_T("<!DOCTYPE"));
  11981. if (docType == 0)
  11982. return;
  11983. input = docType + 9;
  11984. int n = 1;
  11985. while (n > 0)
  11986. {
  11987. const juce_wchar c = readNextChar();
  11988. if (outOfData)
  11989. return;
  11990. if (c == '<')
  11991. ++n;
  11992. else if (c == '>')
  11993. --n;
  11994. }
  11995. docType += 9;
  11996. dtdText = String (docType, (int) (input - (docType + 1))).trim();
  11997. }
  11998. void XmlDocument::skipNextWhiteSpace()
  11999. {
  12000. for (;;)
  12001. {
  12002. juce_wchar c = *input;
  12003. while (CharacterFunctions::isWhitespace (c))
  12004. c = *++input;
  12005. if (c == 0)
  12006. {
  12007. outOfData = true;
  12008. break;
  12009. }
  12010. else if (c == '<')
  12011. {
  12012. if (input[1] == '!'
  12013. && input[2] == '-'
  12014. && input[3] == '-')
  12015. {
  12016. const juce_wchar* const closeComment = CharacterFunctions::find (input, JUCE_T("-->"));
  12017. if (closeComment == 0)
  12018. {
  12019. outOfData = true;
  12020. break;
  12021. }
  12022. input = closeComment + 3;
  12023. continue;
  12024. }
  12025. else if (input[1] == '?')
  12026. {
  12027. const juce_wchar* const closeBracket = CharacterFunctions::find (input, JUCE_T("?>"));
  12028. if (closeBracket == 0)
  12029. {
  12030. outOfData = true;
  12031. break;
  12032. }
  12033. input = closeBracket + 2;
  12034. continue;
  12035. }
  12036. }
  12037. break;
  12038. }
  12039. }
  12040. void XmlDocument::readQuotedString (String& result)
  12041. {
  12042. const juce_wchar quote = readNextChar();
  12043. while (! outOfData)
  12044. {
  12045. const juce_wchar c = readNextChar();
  12046. if (c == quote)
  12047. break;
  12048. if (c == '&')
  12049. {
  12050. --input;
  12051. readEntity (result);
  12052. }
  12053. else
  12054. {
  12055. --input;
  12056. const juce_wchar* const start = input;
  12057. for (;;)
  12058. {
  12059. const juce_wchar character = *input;
  12060. if (character == quote)
  12061. {
  12062. result.append (start, (int) (input - start));
  12063. ++input;
  12064. return;
  12065. }
  12066. else if (character == '&')
  12067. {
  12068. result.append (start, (int) (input - start));
  12069. break;
  12070. }
  12071. else if (character == 0)
  12072. {
  12073. outOfData = true;
  12074. setLastError ("unmatched quotes", false);
  12075. break;
  12076. }
  12077. ++input;
  12078. }
  12079. }
  12080. }
  12081. }
  12082. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements)
  12083. {
  12084. XmlElement* node = 0;
  12085. skipNextWhiteSpace();
  12086. if (outOfData)
  12087. return 0;
  12088. input = CharacterFunctions::find (input, JUCE_T("<"));
  12089. if (input != 0)
  12090. {
  12091. ++input;
  12092. int tagLen = findNextTokenLength();
  12093. if (tagLen == 0)
  12094. {
  12095. // no tag name - but allow for a gap after the '<' before giving an error
  12096. skipNextWhiteSpace();
  12097. tagLen = findNextTokenLength();
  12098. if (tagLen == 0)
  12099. {
  12100. setLastError ("tag name missing", false);
  12101. return node;
  12102. }
  12103. }
  12104. node = new XmlElement (String (input, tagLen));
  12105. input += tagLen;
  12106. XmlElement::XmlAttributeNode* lastAttribute = 0;
  12107. // look for attributes
  12108. for (;;)
  12109. {
  12110. skipNextWhiteSpace();
  12111. const juce_wchar c = *input;
  12112. // empty tag..
  12113. if (c == '/' && input[1] == '>')
  12114. {
  12115. input += 2;
  12116. break;
  12117. }
  12118. // parse the guts of the element..
  12119. if (c == '>')
  12120. {
  12121. ++input;
  12122. if (alsoParseSubElements)
  12123. readChildElements (node);
  12124. break;
  12125. }
  12126. // get an attribute..
  12127. if (isXmlIdentifierChar (c))
  12128. {
  12129. const int attNameLen = findNextTokenLength();
  12130. if (attNameLen > 0)
  12131. {
  12132. const juce_wchar* attNameStart = input;
  12133. input += attNameLen;
  12134. skipNextWhiteSpace();
  12135. if (readNextChar() == '=')
  12136. {
  12137. skipNextWhiteSpace();
  12138. const juce_wchar nextChar = *input;
  12139. if (nextChar == '"' || nextChar == '\'')
  12140. {
  12141. XmlElement::XmlAttributeNode* const newAtt
  12142. = new XmlElement::XmlAttributeNode (String (attNameStart, attNameLen),
  12143. String::empty);
  12144. readQuotedString (newAtt->value);
  12145. if (lastAttribute == 0)
  12146. node->attributes = newAtt;
  12147. else
  12148. lastAttribute->next = newAtt;
  12149. lastAttribute = newAtt;
  12150. continue;
  12151. }
  12152. }
  12153. }
  12154. }
  12155. else
  12156. {
  12157. if (! outOfData)
  12158. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  12159. }
  12160. break;
  12161. }
  12162. }
  12163. return node;
  12164. }
  12165. void XmlDocument::readChildElements (XmlElement* parent)
  12166. {
  12167. XmlElement* lastChildNode = 0;
  12168. for (;;)
  12169. {
  12170. const juce_wchar* const preWhitespaceInput = input;
  12171. skipNextWhiteSpace();
  12172. if (outOfData)
  12173. {
  12174. setLastError ("unmatched tags", false);
  12175. break;
  12176. }
  12177. if (*input == '<')
  12178. {
  12179. if (input[1] == '/')
  12180. {
  12181. // our close tag..
  12182. input = CharacterFunctions::find (input, JUCE_T(">"));
  12183. ++input;
  12184. break;
  12185. }
  12186. else if (input[1] == '!'
  12187. && input[2] == '['
  12188. && input[3] == 'C'
  12189. && input[4] == 'D'
  12190. && input[5] == 'A'
  12191. && input[6] == 'T'
  12192. && input[7] == 'A'
  12193. && input[8] == '[')
  12194. {
  12195. input += 9;
  12196. const juce_wchar* const inputStart = input;
  12197. int len = 0;
  12198. for (;;)
  12199. {
  12200. if (*input == 0)
  12201. {
  12202. setLastError ("unterminated CDATA section", false);
  12203. outOfData = true;
  12204. break;
  12205. }
  12206. else if (input[0] == ']'
  12207. && input[1] == ']'
  12208. && input[2] == '>')
  12209. {
  12210. input += 3;
  12211. break;
  12212. }
  12213. ++input;
  12214. ++len;
  12215. }
  12216. XmlElement* const e = XmlElement::createTextElement (String (inputStart, len));
  12217. if (lastChildNode != 0)
  12218. lastChildNode->nextElement = e;
  12219. else
  12220. parent->addChildElement (e);
  12221. lastChildNode = e;
  12222. }
  12223. else
  12224. {
  12225. // this is some other element, so parse and add it..
  12226. XmlElement* const n = readNextElement (true);
  12227. if (n != 0)
  12228. {
  12229. if (lastChildNode == 0)
  12230. parent->addChildElement (n);
  12231. else
  12232. lastChildNode->nextElement = n;
  12233. lastChildNode = n;
  12234. }
  12235. else
  12236. {
  12237. return;
  12238. }
  12239. }
  12240. }
  12241. else // must be a character block
  12242. {
  12243. input = preWhitespaceInput; // roll back to include the leading whitespace
  12244. String textElementContent;
  12245. for (;;)
  12246. {
  12247. const juce_wchar c = *input;
  12248. if (c == '<')
  12249. break;
  12250. if (c == 0)
  12251. {
  12252. setLastError ("unmatched tags", false);
  12253. outOfData = true;
  12254. return;
  12255. }
  12256. if (c == '&')
  12257. {
  12258. String entity;
  12259. readEntity (entity);
  12260. if (entity.startsWithChar ('<') && entity [1] != 0)
  12261. {
  12262. const juce_wchar* const oldInput = input;
  12263. const bool oldOutOfData = outOfData;
  12264. input = entity;
  12265. outOfData = false;
  12266. for (;;)
  12267. {
  12268. XmlElement* const n = readNextElement (true);
  12269. if (n == 0)
  12270. break;
  12271. if (lastChildNode == 0)
  12272. parent->addChildElement (n);
  12273. else
  12274. lastChildNode->nextElement = n;
  12275. lastChildNode = n;
  12276. }
  12277. input = oldInput;
  12278. outOfData = oldOutOfData;
  12279. }
  12280. else
  12281. {
  12282. textElementContent += entity;
  12283. }
  12284. }
  12285. else
  12286. {
  12287. const juce_wchar* start = input;
  12288. int len = 0;
  12289. for (;;)
  12290. {
  12291. const juce_wchar nextChar = *input;
  12292. if (nextChar == '<' || nextChar == '&')
  12293. {
  12294. break;
  12295. }
  12296. else if (nextChar == 0)
  12297. {
  12298. setLastError ("unmatched tags", false);
  12299. outOfData = true;
  12300. return;
  12301. }
  12302. ++input;
  12303. ++len;
  12304. }
  12305. textElementContent.append (start, len);
  12306. }
  12307. }
  12308. if ((! ignoreEmptyTextElements) || textElementContent.containsNonWhitespaceChars())
  12309. {
  12310. XmlElement* const textElement = XmlElement::createTextElement (textElementContent);
  12311. if (lastChildNode != 0)
  12312. lastChildNode->nextElement = textElement;
  12313. else
  12314. parent->addChildElement (textElement);
  12315. lastChildNode = textElement;
  12316. }
  12317. }
  12318. }
  12319. }
  12320. void XmlDocument::readEntity (String& result)
  12321. {
  12322. // skip over the ampersand
  12323. ++input;
  12324. if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("amp;"), 4) == 0)
  12325. {
  12326. input += 4;
  12327. result += '&';
  12328. }
  12329. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("quot;"), 5) == 0)
  12330. {
  12331. input += 5;
  12332. result += '"';
  12333. }
  12334. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("apos;"), 5) == 0)
  12335. {
  12336. input += 5;
  12337. result += '\'';
  12338. }
  12339. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("lt;"), 3) == 0)
  12340. {
  12341. input += 3;
  12342. result += '<';
  12343. }
  12344. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("gt;"), 3) == 0)
  12345. {
  12346. input += 3;
  12347. result += '>';
  12348. }
  12349. else if (*input == '#')
  12350. {
  12351. int charCode = 0;
  12352. ++input;
  12353. if (*input == 'x' || *input == 'X')
  12354. {
  12355. ++input;
  12356. int numChars = 0;
  12357. while (input[0] != ';')
  12358. {
  12359. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  12360. if (hexValue < 0 || ++numChars > 8)
  12361. {
  12362. setLastError ("illegal escape sequence", true);
  12363. break;
  12364. }
  12365. charCode = (charCode << 4) | hexValue;
  12366. ++input;
  12367. }
  12368. ++input;
  12369. }
  12370. else if (input[0] >= '0' && input[0] <= '9')
  12371. {
  12372. int numChars = 0;
  12373. while (input[0] != ';')
  12374. {
  12375. if (++numChars > 12)
  12376. {
  12377. setLastError ("illegal escape sequence", true);
  12378. break;
  12379. }
  12380. charCode = charCode * 10 + (input[0] - '0');
  12381. ++input;
  12382. }
  12383. ++input;
  12384. }
  12385. else
  12386. {
  12387. setLastError ("illegal escape sequence", true);
  12388. result += '&';
  12389. return;
  12390. }
  12391. result << (juce_wchar) charCode;
  12392. }
  12393. else
  12394. {
  12395. const juce_wchar* const entityNameStart = input;
  12396. const juce_wchar* const closingSemiColon = CharacterFunctions::find (input, JUCE_T(";"));
  12397. if (closingSemiColon == 0)
  12398. {
  12399. outOfData = true;
  12400. result += '&';
  12401. }
  12402. else
  12403. {
  12404. input = closingSemiColon + 1;
  12405. result += expandExternalEntity (String (entityNameStart,
  12406. (int) (closingSemiColon - entityNameStart)));
  12407. }
  12408. }
  12409. }
  12410. const String XmlDocument::expandEntity (const String& ent)
  12411. {
  12412. if (ent.equalsIgnoreCase ("amp"))
  12413. return String::charToString ('&');
  12414. if (ent.equalsIgnoreCase ("quot"))
  12415. return String::charToString ('"');
  12416. if (ent.equalsIgnoreCase ("apos"))
  12417. return String::charToString ('\'');
  12418. if (ent.equalsIgnoreCase ("lt"))
  12419. return String::charToString ('<');
  12420. if (ent.equalsIgnoreCase ("gt"))
  12421. return String::charToString ('>');
  12422. if (ent[0] == '#')
  12423. {
  12424. if (ent[1] == 'x' || ent[1] == 'X')
  12425. return String::charToString (static_cast <juce_wchar> (ent.substring (2).getHexValue32()));
  12426. if (ent[1] >= '0' && ent[1] <= '9')
  12427. return String::charToString (static_cast <juce_wchar> (ent.substring (1).getIntValue()));
  12428. setLastError ("illegal escape sequence", false);
  12429. return String::charToString ('&');
  12430. }
  12431. return expandExternalEntity (ent);
  12432. }
  12433. const String XmlDocument::expandExternalEntity (const String& entity)
  12434. {
  12435. if (needToLoadDTD)
  12436. {
  12437. if (dtdText.isNotEmpty())
  12438. {
  12439. dtdText = dtdText.trimCharactersAtEnd (">");
  12440. tokenisedDTD.addTokens (dtdText, true);
  12441. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase ("system")
  12442. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  12443. {
  12444. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  12445. tokenisedDTD.clear();
  12446. tokenisedDTD.addTokens (getFileContents (fn), true);
  12447. }
  12448. else
  12449. {
  12450. tokenisedDTD.clear();
  12451. const int openBracket = dtdText.indexOfChar ('[');
  12452. if (openBracket > 0)
  12453. {
  12454. const int closeBracket = dtdText.lastIndexOfChar (']');
  12455. if (closeBracket > openBracket)
  12456. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  12457. closeBracket), true);
  12458. }
  12459. }
  12460. for (int i = tokenisedDTD.size(); --i >= 0;)
  12461. {
  12462. if (tokenisedDTD[i].startsWithChar ('%')
  12463. && tokenisedDTD[i].endsWithChar (';'))
  12464. {
  12465. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  12466. StringArray newToks;
  12467. newToks.addTokens (parsed, true);
  12468. tokenisedDTD.remove (i);
  12469. for (int j = newToks.size(); --j >= 0;)
  12470. tokenisedDTD.insert (i, newToks[j]);
  12471. }
  12472. }
  12473. }
  12474. needToLoadDTD = false;
  12475. }
  12476. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12477. {
  12478. if (tokenisedDTD[i] == entity)
  12479. {
  12480. if (tokenisedDTD[i - 1].equalsIgnoreCase ("<!entity"))
  12481. {
  12482. String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">").trim().unquoted());
  12483. // check for sub-entities..
  12484. int ampersand = ent.indexOfChar ('&');
  12485. while (ampersand >= 0)
  12486. {
  12487. const int semiColon = ent.indexOf (i + 1, ";");
  12488. if (semiColon < 0)
  12489. {
  12490. setLastError ("entity without terminating semi-colon", false);
  12491. break;
  12492. }
  12493. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  12494. ent = ent.substring (0, ampersand)
  12495. + resolved
  12496. + ent.substring (semiColon + 1);
  12497. ampersand = ent.indexOfChar (semiColon + 1, '&');
  12498. }
  12499. return ent;
  12500. }
  12501. }
  12502. }
  12503. setLastError ("unknown entity", true);
  12504. return entity;
  12505. }
  12506. const String XmlDocument::getParameterEntity (const String& entity)
  12507. {
  12508. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12509. {
  12510. if (tokenisedDTD[i] == entity)
  12511. {
  12512. if (tokenisedDTD [i - 1] == "%"
  12513. && tokenisedDTD [i - 2].equalsIgnoreCase ("<!entity"))
  12514. {
  12515. const String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">"));
  12516. if (ent.equalsIgnoreCase ("system"))
  12517. return getFileContents (tokenisedDTD [i + 2].trimCharactersAtEnd (">"));
  12518. else
  12519. return ent.trim().unquoted();
  12520. }
  12521. }
  12522. }
  12523. return entity;
  12524. }
  12525. END_JUCE_NAMESPACE
  12526. /*** End of inlined file: juce_XmlDocument.cpp ***/
  12527. /*** Start of inlined file: juce_XmlElement.cpp ***/
  12528. BEGIN_JUCE_NAMESPACE
  12529. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  12530. : name (other.name),
  12531. value (other.value),
  12532. next (0)
  12533. {
  12534. }
  12535. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_, const String& value_) throw()
  12536. : name (name_),
  12537. value (value_),
  12538. next (0)
  12539. {
  12540. }
  12541. XmlElement::XmlElement (const String& tagName_) throw()
  12542. : tagName (tagName_),
  12543. firstChildElement (0),
  12544. nextElement (0),
  12545. attributes (0)
  12546. {
  12547. // the tag name mustn't be empty, or it'll look like a text element!
  12548. jassert (tagName_.containsNonWhitespaceChars())
  12549. // The tag can't contain spaces or other characters that would create invalid XML!
  12550. jassert (! tagName_.containsAnyOf (" <>/&"));
  12551. }
  12552. XmlElement::XmlElement (int /*dummy*/) throw()
  12553. : firstChildElement (0),
  12554. nextElement (0),
  12555. attributes (0)
  12556. {
  12557. }
  12558. XmlElement::XmlElement (const XmlElement& other)
  12559. : tagName (other.tagName),
  12560. firstChildElement (0),
  12561. nextElement (0),
  12562. attributes (0)
  12563. {
  12564. copyChildrenAndAttributesFrom (other);
  12565. }
  12566. XmlElement& XmlElement::operator= (const XmlElement& other)
  12567. {
  12568. if (this != &other)
  12569. {
  12570. removeAllAttributes();
  12571. deleteAllChildElements();
  12572. tagName = other.tagName;
  12573. copyChildrenAndAttributesFrom (other);
  12574. }
  12575. return *this;
  12576. }
  12577. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other)
  12578. {
  12579. XmlElement* child = other.firstChildElement;
  12580. XmlElement* lastChild = 0;
  12581. while (child != 0)
  12582. {
  12583. XmlElement* const copiedChild = new XmlElement (*child);
  12584. if (lastChild != 0)
  12585. lastChild->nextElement = copiedChild;
  12586. else
  12587. firstChildElement = copiedChild;
  12588. lastChild = copiedChild;
  12589. child = child->nextElement;
  12590. }
  12591. const XmlAttributeNode* att = other.attributes;
  12592. XmlAttributeNode* lastAtt = 0;
  12593. while (att != 0)
  12594. {
  12595. XmlAttributeNode* const newAtt = new XmlAttributeNode (*att);
  12596. if (lastAtt != 0)
  12597. lastAtt->next = newAtt;
  12598. else
  12599. attributes = newAtt;
  12600. lastAtt = newAtt;
  12601. att = att->next;
  12602. }
  12603. }
  12604. XmlElement::~XmlElement() throw()
  12605. {
  12606. XmlElement* child = firstChildElement;
  12607. while (child != 0)
  12608. {
  12609. XmlElement* const nextChild = child->nextElement;
  12610. delete child;
  12611. child = nextChild;
  12612. }
  12613. XmlAttributeNode* att = attributes;
  12614. while (att != 0)
  12615. {
  12616. XmlAttributeNode* const nextAtt = att->next;
  12617. delete att;
  12618. att = nextAtt;
  12619. }
  12620. }
  12621. namespace XmlOutputFunctions
  12622. {
  12623. /*static bool isLegalXmlCharSlow (const juce_wchar character) throw()
  12624. {
  12625. if ((character >= 'a' && character <= 'z')
  12626. || (character >= 'A' && character <= 'Z')
  12627. || (character >= '0' && character <= '9'))
  12628. return true;
  12629. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}$|";
  12630. do
  12631. {
  12632. if (((juce_wchar) (uint8) *t) == character)
  12633. return true;
  12634. }
  12635. while (*++t != 0);
  12636. return false;
  12637. }
  12638. static void generateLegalCharConstants()
  12639. {
  12640. uint8 n[32];
  12641. zerostruct (n);
  12642. for (int i = 0; i < 256; ++i)
  12643. if (isLegalXmlCharSlow (i))
  12644. n[i >> 3] |= (1 << (i & 7));
  12645. String s;
  12646. for (int i = 0; i < 32; ++i)
  12647. s << (int) n[i] << ", ";
  12648. DBG (s);
  12649. }*/
  12650. static bool isLegalXmlChar (const uint32 c) throw()
  12651. {
  12652. static const unsigned char legalChars[] = { 0, 0, 0, 0, 187, 255, 255, 175, 255, 255, 255, 191, 254, 255, 255, 127 };
  12653. return c < sizeof (legalChars) * 8
  12654. && (legalChars [c >> 3] & (1 << (c & 7))) != 0;
  12655. }
  12656. static void escapeIllegalXmlChars (OutputStream& outputStream, const String& text, const bool changeNewLines)
  12657. {
  12658. const juce_wchar* t = text;
  12659. for (;;)
  12660. {
  12661. const juce_wchar character = *t++;
  12662. if (character == 0)
  12663. break;
  12664. if (isLegalXmlChar ((uint32) character))
  12665. {
  12666. outputStream << (char) character;
  12667. }
  12668. else
  12669. {
  12670. switch (character)
  12671. {
  12672. case '&': outputStream << "&amp;"; break;
  12673. case '"': outputStream << "&quot;"; break;
  12674. case '>': outputStream << "&gt;"; break;
  12675. case '<': outputStream << "&lt;"; break;
  12676. case '\n':
  12677. if (changeNewLines)
  12678. outputStream << "&#10;";
  12679. else
  12680. outputStream << (char) character;
  12681. break;
  12682. case '\r':
  12683. if (changeNewLines)
  12684. outputStream << "&#13;";
  12685. else
  12686. outputStream << (char) character;
  12687. break;
  12688. default:
  12689. outputStream << "&#" << ((int) (unsigned int) character) << ';';
  12690. break;
  12691. }
  12692. }
  12693. }
  12694. }
  12695. static void writeSpaces (OutputStream& out, int numSpaces)
  12696. {
  12697. if (numSpaces > 0)
  12698. {
  12699. const char blanks[] = " ";
  12700. const int blankSize = (int) numElementsInArray (blanks) - 1;
  12701. while (numSpaces > blankSize)
  12702. {
  12703. out.write (blanks, blankSize);
  12704. numSpaces -= blankSize;
  12705. }
  12706. out.write (blanks, numSpaces);
  12707. }
  12708. }
  12709. static void writeNewLine (OutputStream& out)
  12710. {
  12711. out.write ("\r\n", 2);
  12712. }
  12713. }
  12714. void XmlElement::writeElementAsText (OutputStream& outputStream,
  12715. const int indentationLevel,
  12716. const int lineWrapLength) const
  12717. {
  12718. using namespace XmlOutputFunctions;
  12719. writeSpaces (outputStream, indentationLevel);
  12720. if (! isTextElement())
  12721. {
  12722. outputStream.writeByte ('<');
  12723. outputStream << tagName;
  12724. {
  12725. const int attIndent = indentationLevel + tagName.length() + 1;
  12726. int lineLen = 0;
  12727. const XmlAttributeNode* att = attributes;
  12728. while (att != 0)
  12729. {
  12730. if (lineLen > lineWrapLength && indentationLevel >= 0)
  12731. {
  12732. writeNewLine (outputStream);
  12733. writeSpaces (outputStream, attIndent);
  12734. lineLen = 0;
  12735. }
  12736. const int64 startPos = outputStream.getPosition();
  12737. outputStream.writeByte (' ');
  12738. outputStream << att->name;
  12739. outputStream.write ("=\"", 2);
  12740. escapeIllegalXmlChars (outputStream, att->value, true);
  12741. outputStream.writeByte ('"');
  12742. lineLen += (int) (outputStream.getPosition() - startPos);
  12743. att = att->next;
  12744. }
  12745. }
  12746. if (firstChildElement != 0)
  12747. {
  12748. outputStream.writeByte ('>');
  12749. XmlElement* child = firstChildElement;
  12750. bool lastWasTextNode = false;
  12751. while (child != 0)
  12752. {
  12753. if (child->isTextElement())
  12754. {
  12755. escapeIllegalXmlChars (outputStream, child->getText(), false);
  12756. lastWasTextNode = true;
  12757. }
  12758. else
  12759. {
  12760. if (indentationLevel >= 0 && ! lastWasTextNode)
  12761. writeNewLine (outputStream);
  12762. child->writeElementAsText (outputStream,
  12763. lastWasTextNode ? 0 : (indentationLevel + (indentationLevel >= 0 ? 2 : 0)), lineWrapLength);
  12764. lastWasTextNode = false;
  12765. }
  12766. child = child->nextElement;
  12767. }
  12768. if (indentationLevel >= 0 && ! lastWasTextNode)
  12769. {
  12770. writeNewLine (outputStream);
  12771. writeSpaces (outputStream, indentationLevel);
  12772. }
  12773. outputStream.write ("</", 2);
  12774. outputStream << tagName;
  12775. outputStream.writeByte ('>');
  12776. }
  12777. else
  12778. {
  12779. outputStream.write ("/>", 2);
  12780. }
  12781. }
  12782. else
  12783. {
  12784. escapeIllegalXmlChars (outputStream, getText(), false);
  12785. }
  12786. }
  12787. const String XmlElement::createDocument (const String& dtdToUse,
  12788. const bool allOnOneLine,
  12789. const bool includeXmlHeader,
  12790. const String& encodingType,
  12791. const int lineWrapLength) const
  12792. {
  12793. MemoryOutputStream mem (2048);
  12794. writeToStream (mem, dtdToUse, allOnOneLine, includeXmlHeader, encodingType, lineWrapLength);
  12795. return mem.toUTF8();
  12796. }
  12797. void XmlElement::writeToStream (OutputStream& output,
  12798. const String& dtdToUse,
  12799. const bool allOnOneLine,
  12800. const bool includeXmlHeader,
  12801. const String& encodingType,
  12802. const int lineWrapLength) const
  12803. {
  12804. using namespace XmlOutputFunctions;
  12805. if (includeXmlHeader)
  12806. {
  12807. output << "<?xml version=\"1.0\" encoding=\"" << encodingType << "\"?>";
  12808. if (allOnOneLine)
  12809. {
  12810. output.writeByte (' ');
  12811. }
  12812. else
  12813. {
  12814. writeNewLine (output);
  12815. writeNewLine (output);
  12816. }
  12817. }
  12818. if (dtdToUse.isNotEmpty())
  12819. {
  12820. output << dtdToUse;
  12821. if (allOnOneLine)
  12822. output.writeByte (' ');
  12823. else
  12824. writeNewLine (output);
  12825. }
  12826. writeElementAsText (output, allOnOneLine ? -1 : 0, lineWrapLength);
  12827. if (! allOnOneLine)
  12828. writeNewLine (output);
  12829. }
  12830. bool XmlElement::writeToFile (const File& file,
  12831. const String& dtdToUse,
  12832. const String& encodingType,
  12833. const int lineWrapLength) const
  12834. {
  12835. if (file.hasWriteAccess())
  12836. {
  12837. TemporaryFile tempFile (file);
  12838. ScopedPointer <FileOutputStream> out (tempFile.getFile().createOutputStream());
  12839. if (out != 0)
  12840. {
  12841. writeToStream (*out, dtdToUse, false, true, encodingType, lineWrapLength);
  12842. out = 0;
  12843. return tempFile.overwriteTargetFileWithTemporary();
  12844. }
  12845. }
  12846. return false;
  12847. }
  12848. bool XmlElement::hasTagName (const String& tagNameWanted) const throw()
  12849. {
  12850. #if JUCE_DEBUG
  12851. // if debugging, check that the case is actually the same, because
  12852. // valid xml is case-sensitive, and although this lets it pass, it's
  12853. // better not to..
  12854. if (tagName.equalsIgnoreCase (tagNameWanted))
  12855. {
  12856. jassert (tagName == tagNameWanted);
  12857. return true;
  12858. }
  12859. else
  12860. {
  12861. return false;
  12862. }
  12863. #else
  12864. return tagName.equalsIgnoreCase (tagNameWanted);
  12865. #endif
  12866. }
  12867. XmlElement* XmlElement::getNextElementWithTagName (const String& requiredTagName) const
  12868. {
  12869. XmlElement* e = nextElement;
  12870. while (e != 0 && ! e->hasTagName (requiredTagName))
  12871. e = e->nextElement;
  12872. return e;
  12873. }
  12874. int XmlElement::getNumAttributes() const throw()
  12875. {
  12876. const XmlAttributeNode* att = attributes;
  12877. int count = 0;
  12878. while (att != 0)
  12879. {
  12880. att = att->next;
  12881. ++count;
  12882. }
  12883. return count;
  12884. }
  12885. const String& XmlElement::getAttributeName (const int index) const throw()
  12886. {
  12887. const XmlAttributeNode* att = attributes;
  12888. int count = 0;
  12889. while (att != 0)
  12890. {
  12891. if (count == index)
  12892. return att->name;
  12893. att = att->next;
  12894. ++count;
  12895. }
  12896. return String::empty;
  12897. }
  12898. const String& XmlElement::getAttributeValue (const int index) const throw()
  12899. {
  12900. const XmlAttributeNode* att = attributes;
  12901. int count = 0;
  12902. while (att != 0)
  12903. {
  12904. if (count == index)
  12905. return att->value;
  12906. att = att->next;
  12907. ++count;
  12908. }
  12909. return String::empty;
  12910. }
  12911. bool XmlElement::hasAttribute (const String& attributeName) const throw()
  12912. {
  12913. const XmlAttributeNode* att = attributes;
  12914. while (att != 0)
  12915. {
  12916. if (att->name.equalsIgnoreCase (attributeName))
  12917. return true;
  12918. att = att->next;
  12919. }
  12920. return false;
  12921. }
  12922. const String& XmlElement::getStringAttribute (const String& attributeName) const throw()
  12923. {
  12924. const XmlAttributeNode* att = attributes;
  12925. while (att != 0)
  12926. {
  12927. if (att->name.equalsIgnoreCase (attributeName))
  12928. return att->value;
  12929. att = att->next;
  12930. }
  12931. return String::empty;
  12932. }
  12933. const String XmlElement::getStringAttribute (const String& attributeName, const String& defaultReturnValue) const
  12934. {
  12935. const XmlAttributeNode* att = attributes;
  12936. while (att != 0)
  12937. {
  12938. if (att->name.equalsIgnoreCase (attributeName))
  12939. return att->value;
  12940. att = att->next;
  12941. }
  12942. return defaultReturnValue;
  12943. }
  12944. int XmlElement::getIntAttribute (const String& attributeName, const int defaultReturnValue) const
  12945. {
  12946. const XmlAttributeNode* att = attributes;
  12947. while (att != 0)
  12948. {
  12949. if (att->name.equalsIgnoreCase (attributeName))
  12950. return att->value.getIntValue();
  12951. att = att->next;
  12952. }
  12953. return defaultReturnValue;
  12954. }
  12955. double XmlElement::getDoubleAttribute (const String& attributeName, const double defaultReturnValue) const
  12956. {
  12957. const XmlAttributeNode* att = attributes;
  12958. while (att != 0)
  12959. {
  12960. if (att->name.equalsIgnoreCase (attributeName))
  12961. return att->value.getDoubleValue();
  12962. att = att->next;
  12963. }
  12964. return defaultReturnValue;
  12965. }
  12966. bool XmlElement::getBoolAttribute (const String& attributeName, const bool defaultReturnValue) const
  12967. {
  12968. const XmlAttributeNode* att = attributes;
  12969. while (att != 0)
  12970. {
  12971. if (att->name.equalsIgnoreCase (attributeName))
  12972. {
  12973. juce_wchar firstChar = att->value[0];
  12974. if (CharacterFunctions::isWhitespace (firstChar))
  12975. firstChar = att->value.trimStart() [0];
  12976. return firstChar == '1'
  12977. || firstChar == 't'
  12978. || firstChar == 'y'
  12979. || firstChar == 'T'
  12980. || firstChar == 'Y';
  12981. }
  12982. att = att->next;
  12983. }
  12984. return defaultReturnValue;
  12985. }
  12986. bool XmlElement::compareAttribute (const String& attributeName,
  12987. const String& stringToCompareAgainst,
  12988. const bool ignoreCase) const throw()
  12989. {
  12990. const XmlAttributeNode* att = attributes;
  12991. while (att != 0)
  12992. {
  12993. if (att->name.equalsIgnoreCase (attributeName))
  12994. {
  12995. if (ignoreCase)
  12996. return att->value.equalsIgnoreCase (stringToCompareAgainst);
  12997. else
  12998. return att->value == stringToCompareAgainst;
  12999. }
  13000. att = att->next;
  13001. }
  13002. return false;
  13003. }
  13004. void XmlElement::setAttribute (const String& attributeName, const String& value)
  13005. {
  13006. #if JUCE_DEBUG
  13007. // check the identifier being passed in is legal..
  13008. const juce_wchar* t = attributeName;
  13009. while (*t != 0)
  13010. {
  13011. jassert (CharacterFunctions::isLetterOrDigit (*t)
  13012. || *t == '_'
  13013. || *t == '-'
  13014. || *t == ':');
  13015. ++t;
  13016. }
  13017. #endif
  13018. if (attributes == 0)
  13019. {
  13020. attributes = new XmlAttributeNode (attributeName, value);
  13021. }
  13022. else
  13023. {
  13024. XmlAttributeNode* att = attributes;
  13025. for (;;)
  13026. {
  13027. if (att->name.equalsIgnoreCase (attributeName))
  13028. {
  13029. att->value = value;
  13030. break;
  13031. }
  13032. else if (att->next == 0)
  13033. {
  13034. att->next = new XmlAttributeNode (attributeName, value);
  13035. break;
  13036. }
  13037. att = att->next;
  13038. }
  13039. }
  13040. }
  13041. void XmlElement::setAttribute (const String& attributeName, const int number)
  13042. {
  13043. setAttribute (attributeName, String (number));
  13044. }
  13045. void XmlElement::setAttribute (const String& attributeName, const double number)
  13046. {
  13047. setAttribute (attributeName, String (number));
  13048. }
  13049. void XmlElement::removeAttribute (const String& attributeName) throw()
  13050. {
  13051. XmlAttributeNode* att = attributes;
  13052. XmlAttributeNode* lastAtt = 0;
  13053. while (att != 0)
  13054. {
  13055. if (att->name.equalsIgnoreCase (attributeName))
  13056. {
  13057. if (lastAtt == 0)
  13058. attributes = att->next;
  13059. else
  13060. lastAtt->next = att->next;
  13061. delete att;
  13062. break;
  13063. }
  13064. lastAtt = att;
  13065. att = att->next;
  13066. }
  13067. }
  13068. void XmlElement::removeAllAttributes() throw()
  13069. {
  13070. while (attributes != 0)
  13071. {
  13072. XmlAttributeNode* const nextAtt = attributes->next;
  13073. delete attributes;
  13074. attributes = nextAtt;
  13075. }
  13076. }
  13077. int XmlElement::getNumChildElements() const throw()
  13078. {
  13079. int count = 0;
  13080. const XmlElement* child = firstChildElement;
  13081. while (child != 0)
  13082. {
  13083. ++count;
  13084. child = child->nextElement;
  13085. }
  13086. return count;
  13087. }
  13088. XmlElement* XmlElement::getChildElement (const int index) const throw()
  13089. {
  13090. int count = 0;
  13091. XmlElement* child = firstChildElement;
  13092. while (child != 0 && count < index)
  13093. {
  13094. child = child->nextElement;
  13095. ++count;
  13096. }
  13097. return child;
  13098. }
  13099. XmlElement* XmlElement::getChildByName (const String& childName) const throw()
  13100. {
  13101. XmlElement* child = firstChildElement;
  13102. while (child != 0)
  13103. {
  13104. if (child->hasTagName (childName))
  13105. break;
  13106. child = child->nextElement;
  13107. }
  13108. return child;
  13109. }
  13110. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  13111. {
  13112. if (newNode != 0)
  13113. {
  13114. if (firstChildElement == 0)
  13115. {
  13116. firstChildElement = newNode;
  13117. }
  13118. else
  13119. {
  13120. XmlElement* child = firstChildElement;
  13121. while (child->nextElement != 0)
  13122. child = child->nextElement;
  13123. child->nextElement = newNode;
  13124. // if this is non-zero, then something's probably
  13125. // gone wrong..
  13126. jassert (newNode->nextElement == 0);
  13127. }
  13128. }
  13129. }
  13130. void XmlElement::insertChildElement (XmlElement* const newNode,
  13131. int indexToInsertAt) throw()
  13132. {
  13133. if (newNode != 0)
  13134. {
  13135. removeChildElement (newNode, false);
  13136. if (indexToInsertAt == 0)
  13137. {
  13138. newNode->nextElement = firstChildElement;
  13139. firstChildElement = newNode;
  13140. }
  13141. else
  13142. {
  13143. if (firstChildElement == 0)
  13144. {
  13145. firstChildElement = newNode;
  13146. }
  13147. else
  13148. {
  13149. if (indexToInsertAt < 0)
  13150. indexToInsertAt = std::numeric_limits<int>::max();
  13151. XmlElement* child = firstChildElement;
  13152. while (child->nextElement != 0 && --indexToInsertAt > 0)
  13153. child = child->nextElement;
  13154. newNode->nextElement = child->nextElement;
  13155. child->nextElement = newNode;
  13156. }
  13157. }
  13158. }
  13159. }
  13160. XmlElement* XmlElement::createNewChildElement (const String& childTagName)
  13161. {
  13162. XmlElement* const newElement = new XmlElement (childTagName);
  13163. addChildElement (newElement);
  13164. return newElement;
  13165. }
  13166. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  13167. XmlElement* const newNode) throw()
  13168. {
  13169. if (newNode != 0)
  13170. {
  13171. XmlElement* child = firstChildElement;
  13172. XmlElement* previousNode = 0;
  13173. while (child != 0)
  13174. {
  13175. if (child == currentChildElement)
  13176. {
  13177. if (child != newNode)
  13178. {
  13179. if (previousNode == 0)
  13180. firstChildElement = newNode;
  13181. else
  13182. previousNode->nextElement = newNode;
  13183. newNode->nextElement = child->nextElement;
  13184. delete child;
  13185. }
  13186. return true;
  13187. }
  13188. previousNode = child;
  13189. child = child->nextElement;
  13190. }
  13191. }
  13192. return false;
  13193. }
  13194. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  13195. const bool shouldDeleteTheChild) throw()
  13196. {
  13197. if (childToRemove != 0)
  13198. {
  13199. if (firstChildElement == childToRemove)
  13200. {
  13201. firstChildElement = childToRemove->nextElement;
  13202. childToRemove->nextElement = 0;
  13203. }
  13204. else
  13205. {
  13206. XmlElement* child = firstChildElement;
  13207. XmlElement* last = 0;
  13208. while (child != 0)
  13209. {
  13210. if (child == childToRemove)
  13211. {
  13212. if (last == 0)
  13213. firstChildElement = child->nextElement;
  13214. else
  13215. last->nextElement = child->nextElement;
  13216. childToRemove->nextElement = 0;
  13217. break;
  13218. }
  13219. last = child;
  13220. child = child->nextElement;
  13221. }
  13222. }
  13223. if (shouldDeleteTheChild)
  13224. delete childToRemove;
  13225. }
  13226. }
  13227. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  13228. const bool ignoreOrderOfAttributes) const throw()
  13229. {
  13230. if (this != other)
  13231. {
  13232. if (other == 0 || tagName != other->tagName)
  13233. return false;
  13234. if (ignoreOrderOfAttributes)
  13235. {
  13236. int totalAtts = 0;
  13237. const XmlAttributeNode* att = attributes;
  13238. while (att != 0)
  13239. {
  13240. if (! other->compareAttribute (att->name, att->value))
  13241. return false;
  13242. att = att->next;
  13243. ++totalAtts;
  13244. }
  13245. if (totalAtts != other->getNumAttributes())
  13246. return false;
  13247. }
  13248. else
  13249. {
  13250. const XmlAttributeNode* thisAtt = attributes;
  13251. const XmlAttributeNode* otherAtt = other->attributes;
  13252. for (;;)
  13253. {
  13254. if (thisAtt == 0 || otherAtt == 0)
  13255. {
  13256. if (thisAtt == otherAtt) // both 0, so it's a match
  13257. break;
  13258. return false;
  13259. }
  13260. if (thisAtt->name != otherAtt->name
  13261. || thisAtt->value != otherAtt->value)
  13262. {
  13263. return false;
  13264. }
  13265. thisAtt = thisAtt->next;
  13266. otherAtt = otherAtt->next;
  13267. }
  13268. }
  13269. const XmlElement* thisChild = firstChildElement;
  13270. const XmlElement* otherChild = other->firstChildElement;
  13271. for (;;)
  13272. {
  13273. if (thisChild == 0 || otherChild == 0)
  13274. {
  13275. if (thisChild == otherChild) // both 0, so it's a match
  13276. break;
  13277. return false;
  13278. }
  13279. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  13280. return false;
  13281. thisChild = thisChild->nextElement;
  13282. otherChild = otherChild->nextElement;
  13283. }
  13284. }
  13285. return true;
  13286. }
  13287. void XmlElement::deleteAllChildElements() throw()
  13288. {
  13289. while (firstChildElement != 0)
  13290. {
  13291. XmlElement* const nextChild = firstChildElement->nextElement;
  13292. delete firstChildElement;
  13293. firstChildElement = nextChild;
  13294. }
  13295. }
  13296. void XmlElement::deleteAllChildElementsWithTagName (const String& name) throw()
  13297. {
  13298. XmlElement* child = firstChildElement;
  13299. while (child != 0)
  13300. {
  13301. if (child->hasTagName (name))
  13302. {
  13303. XmlElement* const nextChild = child->nextElement;
  13304. removeChildElement (child, true);
  13305. child = nextChild;
  13306. }
  13307. else
  13308. {
  13309. child = child->nextElement;
  13310. }
  13311. }
  13312. }
  13313. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  13314. {
  13315. const XmlElement* child = firstChildElement;
  13316. while (child != 0)
  13317. {
  13318. if (child == possibleChild)
  13319. return true;
  13320. child = child->nextElement;
  13321. }
  13322. return false;
  13323. }
  13324. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  13325. {
  13326. if (this == elementToLookFor || elementToLookFor == 0)
  13327. return 0;
  13328. XmlElement* child = firstChildElement;
  13329. while (child != 0)
  13330. {
  13331. if (elementToLookFor == child)
  13332. return this;
  13333. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  13334. if (found != 0)
  13335. return found;
  13336. child = child->nextElement;
  13337. }
  13338. return 0;
  13339. }
  13340. void XmlElement::getChildElementsAsArray (XmlElement** elems) const throw()
  13341. {
  13342. XmlElement* e = firstChildElement;
  13343. while (e != 0)
  13344. {
  13345. *elems++ = e;
  13346. e = e->nextElement;
  13347. }
  13348. }
  13349. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  13350. {
  13351. XmlElement* e = firstChildElement = elems[0];
  13352. for (int i = 1; i < num; ++i)
  13353. {
  13354. e->nextElement = elems[i];
  13355. e = e->nextElement;
  13356. }
  13357. e->nextElement = 0;
  13358. }
  13359. bool XmlElement::isTextElement() const throw()
  13360. {
  13361. return tagName.isEmpty();
  13362. }
  13363. static const juce_wchar* const juce_xmltextContentAttributeName = L"text";
  13364. const String& XmlElement::getText() const throw()
  13365. {
  13366. jassert (isTextElement()); // you're trying to get the text from an element that
  13367. // isn't actually a text element.. If this contains text sub-nodes, you
  13368. // probably want to use getAllSubText instead.
  13369. return getStringAttribute (juce_xmltextContentAttributeName);
  13370. }
  13371. void XmlElement::setText (const String& newText)
  13372. {
  13373. if (isTextElement())
  13374. setAttribute (juce_xmltextContentAttributeName, newText);
  13375. else
  13376. jassertfalse; // you can only change the text in a text element, not a normal one.
  13377. }
  13378. const String XmlElement::getAllSubText() const
  13379. {
  13380. if (isTextElement())
  13381. return getText();
  13382. String result;
  13383. String::Concatenator concatenator (result);
  13384. const XmlElement* child = firstChildElement;
  13385. while (child != 0)
  13386. {
  13387. concatenator.append (child->getAllSubText());
  13388. child = child->nextElement;
  13389. }
  13390. return result;
  13391. }
  13392. const String XmlElement::getChildElementAllSubText (const String& childTagName,
  13393. const String& defaultReturnValue) const
  13394. {
  13395. const XmlElement* const child = getChildByName (childTagName);
  13396. if (child != 0)
  13397. return child->getAllSubText();
  13398. return defaultReturnValue;
  13399. }
  13400. XmlElement* XmlElement::createTextElement (const String& text)
  13401. {
  13402. XmlElement* const e = new XmlElement ((int) 0);
  13403. e->setAttribute (juce_xmltextContentAttributeName, text);
  13404. return e;
  13405. }
  13406. void XmlElement::addTextElement (const String& text)
  13407. {
  13408. addChildElement (createTextElement (text));
  13409. }
  13410. void XmlElement::deleteAllTextElements() throw()
  13411. {
  13412. XmlElement* child = firstChildElement;
  13413. while (child != 0)
  13414. {
  13415. XmlElement* const next = child->nextElement;
  13416. if (child->isTextElement())
  13417. removeChildElement (child, true);
  13418. child = next;
  13419. }
  13420. }
  13421. END_JUCE_NAMESPACE
  13422. /*** End of inlined file: juce_XmlElement.cpp ***/
  13423. /*** Start of inlined file: juce_ReadWriteLock.cpp ***/
  13424. BEGIN_JUCE_NAMESPACE
  13425. ReadWriteLock::ReadWriteLock() throw()
  13426. : numWaitingWriters (0),
  13427. numWriters (0),
  13428. writerThreadId (0)
  13429. {
  13430. }
  13431. ReadWriteLock::~ReadWriteLock() throw()
  13432. {
  13433. jassert (readerThreads.size() == 0);
  13434. jassert (numWriters == 0);
  13435. }
  13436. void ReadWriteLock::enterRead() const throw()
  13437. {
  13438. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13439. const ScopedLock sl (accessLock);
  13440. for (;;)
  13441. {
  13442. jassert (readerThreads.size() % 2 == 0);
  13443. int i;
  13444. for (i = 0; i < readerThreads.size(); i += 2)
  13445. if (readerThreads.getUnchecked(i) == threadId)
  13446. break;
  13447. if (i < readerThreads.size()
  13448. || numWriters + numWaitingWriters == 0
  13449. || (threadId == writerThreadId && numWriters > 0))
  13450. {
  13451. if (i < readerThreads.size())
  13452. {
  13453. readerThreads.set (i + 1, (Thread::ThreadID) (1 + (pointer_sized_int) readerThreads.getUnchecked (i + 1)));
  13454. }
  13455. else
  13456. {
  13457. readerThreads.add (threadId);
  13458. readerThreads.add ((Thread::ThreadID) 1);
  13459. }
  13460. return;
  13461. }
  13462. const ScopedUnlock ul (accessLock);
  13463. waitEvent.wait (100);
  13464. }
  13465. }
  13466. void ReadWriteLock::exitRead() const throw()
  13467. {
  13468. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13469. const ScopedLock sl (accessLock);
  13470. for (int i = 0; i < readerThreads.size(); i += 2)
  13471. {
  13472. if (readerThreads.getUnchecked(i) == threadId)
  13473. {
  13474. const pointer_sized_int newCount = ((pointer_sized_int) readerThreads.getUnchecked (i + 1)) - 1;
  13475. if (newCount == 0)
  13476. {
  13477. readerThreads.removeRange (i, 2);
  13478. waitEvent.signal();
  13479. }
  13480. else
  13481. {
  13482. readerThreads.set (i + 1, (Thread::ThreadID) newCount);
  13483. }
  13484. return;
  13485. }
  13486. }
  13487. jassertfalse; // unlocking a lock that wasn't locked..
  13488. }
  13489. void ReadWriteLock::enterWrite() const throw()
  13490. {
  13491. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13492. const ScopedLock sl (accessLock);
  13493. for (;;)
  13494. {
  13495. if (readerThreads.size() + numWriters == 0
  13496. || threadId == writerThreadId
  13497. || (readerThreads.size() == 2
  13498. && readerThreads.getUnchecked(0) == threadId))
  13499. {
  13500. writerThreadId = threadId;
  13501. ++numWriters;
  13502. break;
  13503. }
  13504. ++numWaitingWriters;
  13505. accessLock.exit();
  13506. waitEvent.wait (100);
  13507. accessLock.enter();
  13508. --numWaitingWriters;
  13509. }
  13510. }
  13511. bool ReadWriteLock::tryEnterWrite() const throw()
  13512. {
  13513. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13514. const ScopedLock sl (accessLock);
  13515. if (readerThreads.size() + numWriters == 0
  13516. || threadId == writerThreadId
  13517. || (readerThreads.size() == 2
  13518. && readerThreads.getUnchecked(0) == threadId))
  13519. {
  13520. writerThreadId = threadId;
  13521. ++numWriters;
  13522. return true;
  13523. }
  13524. return false;
  13525. }
  13526. void ReadWriteLock::exitWrite() const throw()
  13527. {
  13528. const ScopedLock sl (accessLock);
  13529. // check this thread actually had the lock..
  13530. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  13531. if (--numWriters == 0)
  13532. {
  13533. writerThreadId = 0;
  13534. waitEvent.signal();
  13535. }
  13536. }
  13537. END_JUCE_NAMESPACE
  13538. /*** End of inlined file: juce_ReadWriteLock.cpp ***/
  13539. /*** Start of inlined file: juce_Thread.cpp ***/
  13540. BEGIN_JUCE_NAMESPACE
  13541. // these functions are implemented in the platform-specific code.
  13542. void* juce_createThread (void* userData);
  13543. void juce_killThread (void* handle);
  13544. bool juce_setThreadPriority (void* handle, int priority);
  13545. void juce_setCurrentThreadName (const String& name);
  13546. #if JUCE_WINDOWS
  13547. void juce_CloseThreadHandle (void* handle);
  13548. #endif
  13549. void Thread::threadEntryPoint (Thread* const thread)
  13550. {
  13551. {
  13552. const ScopedLock sl (runningThreadsLock);
  13553. runningThreads.add (thread);
  13554. }
  13555. JUCE_TRY
  13556. {
  13557. thread->threadId_ = Thread::getCurrentThreadId();
  13558. if (thread->threadName_.isNotEmpty())
  13559. juce_setCurrentThreadName (thread->threadName_);
  13560. if (thread->startSuspensionEvent_.wait (10000))
  13561. {
  13562. if (thread->affinityMask_ != 0)
  13563. setCurrentThreadAffinityMask (thread->affinityMask_);
  13564. thread->run();
  13565. }
  13566. }
  13567. JUCE_CATCH_ALL_ASSERT
  13568. {
  13569. const ScopedLock sl (runningThreadsLock);
  13570. jassert (runningThreads.contains (thread));
  13571. runningThreads.removeValue (thread);
  13572. }
  13573. #if JUCE_WINDOWS
  13574. juce_CloseThreadHandle (thread->threadHandle_);
  13575. #endif
  13576. thread->threadHandle_ = 0;
  13577. thread->threadId_ = 0;
  13578. }
  13579. // used to wrap the incoming call from the platform-specific code
  13580. void JUCE_API juce_threadEntryPoint (void* userData)
  13581. {
  13582. Thread::threadEntryPoint (static_cast <Thread*> (userData));
  13583. }
  13584. Thread::Thread (const String& threadName)
  13585. : threadName_ (threadName),
  13586. threadHandle_ (0),
  13587. threadPriority_ (5),
  13588. threadId_ (0),
  13589. affinityMask_ (0),
  13590. threadShouldExit_ (false)
  13591. {
  13592. }
  13593. Thread::~Thread()
  13594. {
  13595. stopThread (100);
  13596. }
  13597. void Thread::startThread()
  13598. {
  13599. const ScopedLock sl (startStopLock);
  13600. threadShouldExit_ = false;
  13601. if (threadHandle_ == 0)
  13602. {
  13603. threadHandle_ = juce_createThread (this);
  13604. juce_setThreadPriority (threadHandle_, threadPriority_);
  13605. startSuspensionEvent_.signal();
  13606. }
  13607. }
  13608. void Thread::startThread (const int priority)
  13609. {
  13610. const ScopedLock sl (startStopLock);
  13611. if (threadHandle_ == 0)
  13612. {
  13613. threadPriority_ = priority;
  13614. startThread();
  13615. }
  13616. else
  13617. {
  13618. setPriority (priority);
  13619. }
  13620. }
  13621. bool Thread::isThreadRunning() const
  13622. {
  13623. return threadHandle_ != 0;
  13624. }
  13625. void Thread::signalThreadShouldExit()
  13626. {
  13627. threadShouldExit_ = true;
  13628. }
  13629. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const
  13630. {
  13631. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  13632. jassert (getThreadId() != getCurrentThreadId());
  13633. const int sleepMsPerIteration = 5;
  13634. int count = timeOutMilliseconds / sleepMsPerIteration;
  13635. while (isThreadRunning())
  13636. {
  13637. if (timeOutMilliseconds > 0 && --count < 0)
  13638. return false;
  13639. sleep (sleepMsPerIteration);
  13640. }
  13641. return true;
  13642. }
  13643. void Thread::stopThread (const int timeOutMilliseconds)
  13644. {
  13645. // agh! You can't stop the thread that's calling this method! How on earth
  13646. // would that work??
  13647. jassert (getCurrentThreadId() != getThreadId());
  13648. const ScopedLock sl (startStopLock);
  13649. if (isThreadRunning())
  13650. {
  13651. signalThreadShouldExit();
  13652. notify();
  13653. if (timeOutMilliseconds != 0)
  13654. waitForThreadToExit (timeOutMilliseconds);
  13655. if (isThreadRunning())
  13656. {
  13657. // very bad karma if this point is reached, as
  13658. // there are bound to be locks and events left in
  13659. // silly states when a thread is killed by force..
  13660. jassertfalse;
  13661. Logger::writeToLog ("!! killing thread by force !!");
  13662. juce_killThread (threadHandle_);
  13663. threadHandle_ = 0;
  13664. threadId_ = 0;
  13665. const ScopedLock sl2 (runningThreadsLock);
  13666. runningThreads.removeValue (this);
  13667. }
  13668. }
  13669. }
  13670. bool Thread::setPriority (const int priority)
  13671. {
  13672. const ScopedLock sl (startStopLock);
  13673. const bool worked = juce_setThreadPriority (threadHandle_, priority);
  13674. if (worked)
  13675. threadPriority_ = priority;
  13676. return worked;
  13677. }
  13678. bool Thread::setCurrentThreadPriority (const int priority)
  13679. {
  13680. return juce_setThreadPriority (0, priority);
  13681. }
  13682. void Thread::setAffinityMask (const uint32 affinityMask)
  13683. {
  13684. affinityMask_ = affinityMask;
  13685. }
  13686. bool Thread::wait (const int timeOutMilliseconds) const
  13687. {
  13688. return defaultEvent_.wait (timeOutMilliseconds);
  13689. }
  13690. void Thread::notify() const
  13691. {
  13692. defaultEvent_.signal();
  13693. }
  13694. int Thread::getNumRunningThreads()
  13695. {
  13696. return runningThreads.size();
  13697. }
  13698. Thread* Thread::getCurrentThread()
  13699. {
  13700. const ThreadID thisId = getCurrentThreadId();
  13701. const ScopedLock sl (runningThreadsLock);
  13702. for (int i = runningThreads.size(); --i >= 0;)
  13703. {
  13704. Thread* const t = runningThreads.getUnchecked(i);
  13705. if (t->threadId_ == thisId)
  13706. return t;
  13707. }
  13708. return 0;
  13709. }
  13710. void Thread::stopAllThreads (const int timeOutMilliseconds)
  13711. {
  13712. {
  13713. const ScopedLock sl (runningThreadsLock);
  13714. for (int i = runningThreads.size(); --i >= 0;)
  13715. runningThreads.getUnchecked(i)->signalThreadShouldExit();
  13716. }
  13717. for (;;)
  13718. {
  13719. Thread* firstThread;
  13720. {
  13721. const ScopedLock sl (runningThreadsLock);
  13722. firstThread = runningThreads.getFirst();
  13723. }
  13724. if (firstThread == 0)
  13725. break;
  13726. firstThread->stopThread (timeOutMilliseconds);
  13727. }
  13728. }
  13729. Array<Thread*> Thread::runningThreads;
  13730. CriticalSection Thread::runningThreadsLock;
  13731. END_JUCE_NAMESPACE
  13732. /*** End of inlined file: juce_Thread.cpp ***/
  13733. /*** Start of inlined file: juce_ThreadPool.cpp ***/
  13734. BEGIN_JUCE_NAMESPACE
  13735. ThreadPoolJob::ThreadPoolJob (const String& name)
  13736. : jobName (name),
  13737. pool (0),
  13738. shouldStop (false),
  13739. isActive (false),
  13740. shouldBeDeleted (false)
  13741. {
  13742. }
  13743. ThreadPoolJob::~ThreadPoolJob()
  13744. {
  13745. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  13746. // to remove it first!
  13747. jassert (pool == 0 || ! pool->contains (this));
  13748. }
  13749. const String ThreadPoolJob::getJobName() const
  13750. {
  13751. return jobName;
  13752. }
  13753. void ThreadPoolJob::setJobName (const String& newName)
  13754. {
  13755. jobName = newName;
  13756. }
  13757. void ThreadPoolJob::signalJobShouldExit()
  13758. {
  13759. shouldStop = true;
  13760. }
  13761. class ThreadPool::ThreadPoolThread : public Thread
  13762. {
  13763. public:
  13764. ThreadPoolThread (ThreadPool& pool_)
  13765. : Thread ("Pool"),
  13766. pool (pool_),
  13767. busy (false)
  13768. {
  13769. }
  13770. ~ThreadPoolThread()
  13771. {
  13772. }
  13773. void run()
  13774. {
  13775. while (! threadShouldExit())
  13776. {
  13777. if (! pool.runNextJob())
  13778. wait (500);
  13779. }
  13780. }
  13781. private:
  13782. ThreadPool& pool;
  13783. bool volatile busy;
  13784. ThreadPoolThread (const ThreadPoolThread&);
  13785. ThreadPoolThread& operator= (const ThreadPoolThread&);
  13786. };
  13787. ThreadPool::ThreadPool (const int numThreads,
  13788. const bool startThreadsOnlyWhenNeeded,
  13789. const int stopThreadsWhenNotUsedTimeoutMs)
  13790. : threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  13791. priority (5)
  13792. {
  13793. jassert (numThreads > 0); // not much point having one of these with no threads in it.
  13794. for (int i = jmax (1, numThreads); --i >= 0;)
  13795. threads.add (new ThreadPoolThread (*this));
  13796. if (! startThreadsOnlyWhenNeeded)
  13797. for (int i = threads.size(); --i >= 0;)
  13798. threads.getUnchecked(i)->startThread (priority);
  13799. }
  13800. ThreadPool::~ThreadPool()
  13801. {
  13802. removeAllJobs (true, 4000);
  13803. int i;
  13804. for (i = threads.size(); --i >= 0;)
  13805. threads.getUnchecked(i)->signalThreadShouldExit();
  13806. for (i = threads.size(); --i >= 0;)
  13807. threads.getUnchecked(i)->stopThread (500);
  13808. }
  13809. void ThreadPool::addJob (ThreadPoolJob* const job)
  13810. {
  13811. jassert (job != 0);
  13812. jassert (job->pool == 0);
  13813. if (job->pool == 0)
  13814. {
  13815. job->pool = this;
  13816. job->shouldStop = false;
  13817. job->isActive = false;
  13818. {
  13819. const ScopedLock sl (lock);
  13820. jobs.add (job);
  13821. int numRunning = 0;
  13822. for (int i = threads.size(); --i >= 0;)
  13823. if (threads.getUnchecked(i)->isThreadRunning() && ! threads.getUnchecked(i)->threadShouldExit())
  13824. ++numRunning;
  13825. if (numRunning < threads.size())
  13826. {
  13827. bool startedOne = false;
  13828. int n = 1000;
  13829. while (--n >= 0 && ! startedOne)
  13830. {
  13831. for (int i = threads.size(); --i >= 0;)
  13832. {
  13833. if (! threads.getUnchecked(i)->isThreadRunning())
  13834. {
  13835. threads.getUnchecked(i)->startThread (priority);
  13836. startedOne = true;
  13837. break;
  13838. }
  13839. }
  13840. if (! startedOne)
  13841. Thread::sleep (2);
  13842. }
  13843. }
  13844. }
  13845. for (int i = threads.size(); --i >= 0;)
  13846. threads.getUnchecked(i)->notify();
  13847. }
  13848. }
  13849. int ThreadPool::getNumJobs() const
  13850. {
  13851. return jobs.size();
  13852. }
  13853. ThreadPoolJob* ThreadPool::getJob (const int index) const
  13854. {
  13855. const ScopedLock sl (lock);
  13856. return jobs [index];
  13857. }
  13858. bool ThreadPool::contains (const ThreadPoolJob* const job) const
  13859. {
  13860. const ScopedLock sl (lock);
  13861. return jobs.contains (const_cast <ThreadPoolJob*> (job));
  13862. }
  13863. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  13864. {
  13865. const ScopedLock sl (lock);
  13866. return jobs.contains (const_cast <ThreadPoolJob*> (job)) && job->isActive;
  13867. }
  13868. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  13869. const int timeOutMs) const
  13870. {
  13871. if (job != 0)
  13872. {
  13873. const uint32 start = Time::getMillisecondCounter();
  13874. while (contains (job))
  13875. {
  13876. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13877. return false;
  13878. jobFinishedSignal.wait (2);
  13879. }
  13880. }
  13881. return true;
  13882. }
  13883. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  13884. const bool interruptIfRunning,
  13885. const int timeOutMs)
  13886. {
  13887. bool dontWait = true;
  13888. if (job != 0)
  13889. {
  13890. const ScopedLock sl (lock);
  13891. if (jobs.contains (job))
  13892. {
  13893. if (job->isActive)
  13894. {
  13895. if (interruptIfRunning)
  13896. job->signalJobShouldExit();
  13897. dontWait = false;
  13898. }
  13899. else
  13900. {
  13901. jobs.removeValue (job);
  13902. job->pool = 0;
  13903. }
  13904. }
  13905. }
  13906. return dontWait || waitForJobToFinish (job, timeOutMs);
  13907. }
  13908. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  13909. const int timeOutMs,
  13910. const bool deleteInactiveJobs,
  13911. ThreadPool::JobSelector* selectedJobsToRemove)
  13912. {
  13913. Array <ThreadPoolJob*> jobsToWaitFor;
  13914. {
  13915. const ScopedLock sl (lock);
  13916. for (int i = jobs.size(); --i >= 0;)
  13917. {
  13918. ThreadPoolJob* const job = jobs.getUnchecked(i);
  13919. if (selectedJobsToRemove == 0 || selectedJobsToRemove->isJobSuitable (job))
  13920. {
  13921. if (job->isActive)
  13922. {
  13923. jobsToWaitFor.add (job);
  13924. if (interruptRunningJobs)
  13925. job->signalJobShouldExit();
  13926. }
  13927. else
  13928. {
  13929. jobs.remove (i);
  13930. if (deleteInactiveJobs)
  13931. delete job;
  13932. else
  13933. job->pool = 0;
  13934. }
  13935. }
  13936. }
  13937. }
  13938. const uint32 start = Time::getMillisecondCounter();
  13939. for (;;)
  13940. {
  13941. for (int i = jobsToWaitFor.size(); --i >= 0;)
  13942. if (! isJobRunning (jobsToWaitFor.getUnchecked (i)))
  13943. jobsToWaitFor.remove (i);
  13944. if (jobsToWaitFor.size() == 0)
  13945. break;
  13946. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13947. return false;
  13948. jobFinishedSignal.wait (20);
  13949. }
  13950. return true;
  13951. }
  13952. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  13953. {
  13954. StringArray s;
  13955. const ScopedLock sl (lock);
  13956. for (int i = 0; i < jobs.size(); ++i)
  13957. {
  13958. const ThreadPoolJob* const job = jobs.getUnchecked(i);
  13959. if (job->isActive || ! onlyReturnActiveJobs)
  13960. s.add (job->getJobName());
  13961. }
  13962. return s;
  13963. }
  13964. bool ThreadPool::setThreadPriorities (const int newPriority)
  13965. {
  13966. bool ok = true;
  13967. if (priority != newPriority)
  13968. {
  13969. priority = newPriority;
  13970. for (int i = threads.size(); --i >= 0;)
  13971. if (! threads.getUnchecked(i)->setPriority (newPriority))
  13972. ok = false;
  13973. }
  13974. return ok;
  13975. }
  13976. bool ThreadPool::runNextJob()
  13977. {
  13978. ThreadPoolJob* job = 0;
  13979. {
  13980. const ScopedLock sl (lock);
  13981. for (int i = 0; i < jobs.size(); ++i)
  13982. {
  13983. job = jobs[i];
  13984. if (job != 0 && ! (job->isActive || job->shouldStop))
  13985. break;
  13986. job = 0;
  13987. }
  13988. if (job != 0)
  13989. job->isActive = true;
  13990. }
  13991. if (job != 0)
  13992. {
  13993. JUCE_TRY
  13994. {
  13995. ThreadPoolJob::JobStatus result = job->runJob();
  13996. lastJobEndTime = Time::getApproximateMillisecondCounter();
  13997. const ScopedLock sl (lock);
  13998. if (jobs.contains (job))
  13999. {
  14000. job->isActive = false;
  14001. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  14002. {
  14003. job->pool = 0;
  14004. job->shouldStop = true;
  14005. jobs.removeValue (job);
  14006. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  14007. delete job;
  14008. jobFinishedSignal.signal();
  14009. }
  14010. else
  14011. {
  14012. // move the job to the end of the queue if it wants another go
  14013. jobs.move (jobs.indexOf (job), -1);
  14014. }
  14015. }
  14016. }
  14017. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  14018. catch (...)
  14019. {
  14020. const ScopedLock sl (lock);
  14021. jobs.removeValue (job);
  14022. }
  14023. #endif
  14024. }
  14025. else
  14026. {
  14027. if (threadStopTimeout > 0
  14028. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  14029. {
  14030. const ScopedLock sl (lock);
  14031. if (jobs.size() == 0)
  14032. for (int i = threads.size(); --i >= 0;)
  14033. threads.getUnchecked(i)->signalThreadShouldExit();
  14034. }
  14035. else
  14036. {
  14037. return false;
  14038. }
  14039. }
  14040. return true;
  14041. }
  14042. END_JUCE_NAMESPACE
  14043. /*** End of inlined file: juce_ThreadPool.cpp ***/
  14044. /*** Start of inlined file: juce_TimeSliceThread.cpp ***/
  14045. BEGIN_JUCE_NAMESPACE
  14046. TimeSliceThread::TimeSliceThread (const String& threadName)
  14047. : Thread (threadName),
  14048. index (0),
  14049. clientBeingCalled (0),
  14050. clientsChanged (false)
  14051. {
  14052. }
  14053. TimeSliceThread::~TimeSliceThread()
  14054. {
  14055. stopThread (2000);
  14056. }
  14057. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client)
  14058. {
  14059. const ScopedLock sl (listLock);
  14060. clients.addIfNotAlreadyThere (client);
  14061. clientsChanged = true;
  14062. notify();
  14063. }
  14064. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  14065. {
  14066. const ScopedLock sl1 (listLock);
  14067. clientsChanged = true;
  14068. // if there's a chance we're in the middle of calling this client, we need to
  14069. // also lock the outer lock..
  14070. if (clientBeingCalled == client)
  14071. {
  14072. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  14073. const ScopedLock sl2 (callbackLock);
  14074. const ScopedLock sl3 (listLock);
  14075. clients.removeValue (client);
  14076. }
  14077. else
  14078. {
  14079. clients.removeValue (client);
  14080. }
  14081. }
  14082. int TimeSliceThread::getNumClients() const
  14083. {
  14084. return clients.size();
  14085. }
  14086. TimeSliceClient* TimeSliceThread::getClient (const int i) const
  14087. {
  14088. const ScopedLock sl (listLock);
  14089. return clients [i];
  14090. }
  14091. void TimeSliceThread::run()
  14092. {
  14093. int numCallsSinceBusy = 0;
  14094. while (! threadShouldExit())
  14095. {
  14096. int timeToWait = 500;
  14097. {
  14098. const ScopedLock sl (callbackLock);
  14099. {
  14100. const ScopedLock sl2 (listLock);
  14101. if (clients.size() > 0)
  14102. {
  14103. index = (index + 1) % clients.size();
  14104. clientBeingCalled = clients [index];
  14105. }
  14106. else
  14107. {
  14108. index = 0;
  14109. clientBeingCalled = 0;
  14110. }
  14111. if (clientsChanged)
  14112. {
  14113. clientsChanged = false;
  14114. numCallsSinceBusy = 0;
  14115. }
  14116. }
  14117. if (clientBeingCalled != 0)
  14118. {
  14119. if (clientBeingCalled->useTimeSlice())
  14120. numCallsSinceBusy = 0;
  14121. else
  14122. ++numCallsSinceBusy;
  14123. if (numCallsSinceBusy >= clients.size())
  14124. timeToWait = 500;
  14125. else if (index == 0)
  14126. timeToWait = 1; // throw in an occasional pause, to stop everything locking up
  14127. else
  14128. timeToWait = 0;
  14129. }
  14130. }
  14131. if (timeToWait > 0)
  14132. wait (timeToWait);
  14133. }
  14134. }
  14135. END_JUCE_NAMESPACE
  14136. /*** End of inlined file: juce_TimeSliceThread.cpp ***/
  14137. /*** Start of inlined file: juce_DeletedAtShutdown.cpp ***/
  14138. BEGIN_JUCE_NAMESPACE
  14139. DeletedAtShutdown::DeletedAtShutdown()
  14140. {
  14141. const ScopedLock sl (getLock());
  14142. getObjects().add (this);
  14143. }
  14144. DeletedAtShutdown::~DeletedAtShutdown()
  14145. {
  14146. const ScopedLock sl (getLock());
  14147. getObjects().removeValue (this);
  14148. }
  14149. void DeletedAtShutdown::deleteAll()
  14150. {
  14151. // make a local copy of the array, so it can't get into a loop if something
  14152. // creates another DeletedAtShutdown object during its destructor.
  14153. Array <DeletedAtShutdown*> localCopy;
  14154. {
  14155. const ScopedLock sl (getLock());
  14156. localCopy = getObjects();
  14157. }
  14158. for (int i = localCopy.size(); --i >= 0;)
  14159. {
  14160. JUCE_TRY
  14161. {
  14162. DeletedAtShutdown* deletee = localCopy.getUnchecked(i);
  14163. // double-check that it's not already been deleted during another object's destructor.
  14164. {
  14165. const ScopedLock sl (getLock());
  14166. if (! getObjects().contains (deletee))
  14167. deletee = 0;
  14168. }
  14169. delete deletee;
  14170. }
  14171. JUCE_CATCH_EXCEPTION
  14172. }
  14173. // if no objects got re-created during shutdown, this should have been emptied by their
  14174. // destructors
  14175. jassert (getObjects().size() == 0);
  14176. getObjects().clear(); // just to make sure the array doesn't have any memory still allocated
  14177. }
  14178. CriticalSection& DeletedAtShutdown::getLock()
  14179. {
  14180. static CriticalSection lock;
  14181. return lock;
  14182. }
  14183. Array <DeletedAtShutdown*>& DeletedAtShutdown::getObjects()
  14184. {
  14185. static Array <DeletedAtShutdown*> objects;
  14186. return objects;
  14187. }
  14188. END_JUCE_NAMESPACE
  14189. /*** End of inlined file: juce_DeletedAtShutdown.cpp ***/
  14190. /*** Start of inlined file: juce_UnitTest.cpp ***/
  14191. BEGIN_JUCE_NAMESPACE
  14192. UnitTest::UnitTest (const String& name_)
  14193. : name (name_), runner (0)
  14194. {
  14195. getAllTests().add (this);
  14196. }
  14197. UnitTest::~UnitTest()
  14198. {
  14199. getAllTests().removeValue (this);
  14200. }
  14201. Array<UnitTest*>& UnitTest::getAllTests()
  14202. {
  14203. static Array<UnitTest*> tests;
  14204. return tests;
  14205. }
  14206. void UnitTest::performTest (UnitTestRunner* const runner_)
  14207. {
  14208. jassert (runner_ != 0);
  14209. runner = runner_;
  14210. runTest();
  14211. }
  14212. void UnitTest::logMessage (const String& message)
  14213. {
  14214. runner->logMessage (message);
  14215. }
  14216. void UnitTest::beginTest (const String& testName)
  14217. {
  14218. runner->beginNewTest (this, testName);
  14219. }
  14220. void UnitTest::expect (const bool result, const String& failureMessage)
  14221. {
  14222. if (result)
  14223. runner->addPass();
  14224. else
  14225. runner->addFail (failureMessage);
  14226. }
  14227. UnitTestRunner::UnitTestRunner()
  14228. : currentTest (0), assertOnFailure (false)
  14229. {
  14230. }
  14231. UnitTestRunner::~UnitTestRunner()
  14232. {
  14233. }
  14234. void UnitTestRunner::resultsUpdated()
  14235. {
  14236. }
  14237. void UnitTestRunner::runTests (const Array<UnitTest*>& tests, const bool assertOnFailure_)
  14238. {
  14239. results.clear();
  14240. assertOnFailure = assertOnFailure_;
  14241. resultsUpdated();
  14242. for (int i = 0; i < tests.size(); ++i)
  14243. {
  14244. try
  14245. {
  14246. tests.getUnchecked(i)->performTest (this);
  14247. }
  14248. catch (...)
  14249. {
  14250. addFail ("An unhandled exception was thrown!");
  14251. }
  14252. }
  14253. endTest();
  14254. }
  14255. void UnitTestRunner::runAllTests (const bool assertOnFailure_)
  14256. {
  14257. runTests (UnitTest::getAllTests(), assertOnFailure_);
  14258. }
  14259. void UnitTestRunner::logMessage (const String& message)
  14260. {
  14261. Logger::writeToLog (message);
  14262. }
  14263. void UnitTestRunner::beginNewTest (UnitTest* const test, const String& subCategory)
  14264. {
  14265. endTest();
  14266. currentTest = test;
  14267. TestResult* const r = new TestResult();
  14268. r->unitTestName = test->getName();
  14269. r->subcategoryName = subCategory;
  14270. r->passes = 0;
  14271. r->failures = 0;
  14272. results.add (r);
  14273. logMessage ("-----------------------------------------------------------------");
  14274. logMessage ("Starting test: " + r->unitTestName + " / " + subCategory + "...");
  14275. resultsUpdated();
  14276. }
  14277. void UnitTestRunner::endTest()
  14278. {
  14279. if (results.size() > 0)
  14280. {
  14281. TestResult* const r = results.getLast();
  14282. if (r->failures > 0)
  14283. {
  14284. String m ("FAILED!!");
  14285. m << r->failures << (r->failures == 1 ? "test" : "tests")
  14286. << " failed, out of a total of " << (r->passes + r->failures);
  14287. logMessage (String::empty);
  14288. logMessage (m);
  14289. logMessage (String::empty);
  14290. }
  14291. else
  14292. {
  14293. logMessage ("All tests completed successfully");
  14294. }
  14295. }
  14296. }
  14297. void UnitTestRunner::addPass()
  14298. {
  14299. {
  14300. const ScopedLock sl (results.getLock());
  14301. TestResult* const r = results.getLast();
  14302. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  14303. r->passes++;
  14304. String message ("Test ");
  14305. message << (r->failures + r->passes) << " passed";
  14306. logMessage (message);
  14307. }
  14308. resultsUpdated();
  14309. }
  14310. void UnitTestRunner::addFail (const String& failureMessage)
  14311. {
  14312. {
  14313. const ScopedLock sl (results.getLock());
  14314. TestResult* const r = results.getLast();
  14315. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  14316. r->failures++;
  14317. String message ("!!! Test ");
  14318. message << (r->failures + r->passes) << " failed";
  14319. if (failureMessage.isNotEmpty())
  14320. message << ": " << failureMessage;
  14321. r->messages.add (message);
  14322. logMessage (message);
  14323. }
  14324. resultsUpdated();
  14325. if (assertOnFailure) { jassertfalse }
  14326. }
  14327. END_JUCE_NAMESPACE
  14328. /*** End of inlined file: juce_UnitTest.cpp ***/
  14329. #endif
  14330. #if JUCE_BUILD_MISC
  14331. /*** Start of inlined file: juce_ValueTree.cpp ***/
  14332. BEGIN_JUCE_NAMESPACE
  14333. class ValueTree::SetPropertyAction : public UndoableAction
  14334. {
  14335. public:
  14336. SetPropertyAction (const SharedObjectPtr& target_, const Identifier& name_,
  14337. const var& newValue_, const var& oldValue_,
  14338. const bool isAddingNewProperty_, const bool isDeletingProperty_)
  14339. : target (target_), name (name_), newValue (newValue_), oldValue (oldValue_),
  14340. isAddingNewProperty (isAddingNewProperty_), isDeletingProperty (isDeletingProperty_)
  14341. {
  14342. }
  14343. ~SetPropertyAction() {}
  14344. bool perform()
  14345. {
  14346. jassert (! (isAddingNewProperty && target->hasProperty (name)));
  14347. if (isDeletingProperty)
  14348. target->removeProperty (name, 0);
  14349. else
  14350. target->setProperty (name, newValue, 0);
  14351. return true;
  14352. }
  14353. bool undo()
  14354. {
  14355. if (isAddingNewProperty)
  14356. target->removeProperty (name, 0);
  14357. else
  14358. target->setProperty (name, oldValue, 0);
  14359. return true;
  14360. }
  14361. int getSizeInUnits()
  14362. {
  14363. return (int) sizeof (*this); //xxx should be more accurate
  14364. }
  14365. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  14366. {
  14367. if (! (isAddingNewProperty || isDeletingProperty))
  14368. {
  14369. SetPropertyAction* next = dynamic_cast <SetPropertyAction*> (nextAction);
  14370. if (next != 0 && next->target == target && next->name == name
  14371. && ! (next->isAddingNewProperty || next->isDeletingProperty))
  14372. {
  14373. return new SetPropertyAction (target, name, next->newValue, oldValue, false, false);
  14374. }
  14375. }
  14376. return 0;
  14377. }
  14378. private:
  14379. const SharedObjectPtr target;
  14380. const Identifier name;
  14381. const var newValue;
  14382. var oldValue;
  14383. const bool isAddingNewProperty : 1, isDeletingProperty : 1;
  14384. SetPropertyAction (const SetPropertyAction&);
  14385. SetPropertyAction& operator= (const SetPropertyAction&);
  14386. };
  14387. class ValueTree::AddOrRemoveChildAction : public UndoableAction
  14388. {
  14389. public:
  14390. AddOrRemoveChildAction (const SharedObjectPtr& target_, const int childIndex_,
  14391. const SharedObjectPtr& newChild_)
  14392. : target (target_),
  14393. child (newChild_ != 0 ? newChild_ : target_->children [childIndex_]),
  14394. childIndex (childIndex_),
  14395. isDeleting (newChild_ == 0)
  14396. {
  14397. jassert (child != 0);
  14398. }
  14399. ~AddOrRemoveChildAction() {}
  14400. bool perform()
  14401. {
  14402. if (isDeleting)
  14403. target->removeChild (childIndex, 0);
  14404. else
  14405. target->addChild (child, childIndex, 0);
  14406. return true;
  14407. }
  14408. bool undo()
  14409. {
  14410. if (isDeleting)
  14411. {
  14412. target->addChild (child, childIndex, 0);
  14413. }
  14414. else
  14415. {
  14416. // If you hit this, it seems that your object's state is getting confused - probably
  14417. // because you've interleaved some undoable and non-undoable operations?
  14418. jassert (childIndex < target->children.size());
  14419. target->removeChild (childIndex, 0);
  14420. }
  14421. return true;
  14422. }
  14423. int getSizeInUnits()
  14424. {
  14425. return (int) sizeof (*this); //xxx should be more accurate
  14426. }
  14427. private:
  14428. const SharedObjectPtr target, child;
  14429. const int childIndex;
  14430. const bool isDeleting;
  14431. AddOrRemoveChildAction (const AddOrRemoveChildAction&);
  14432. AddOrRemoveChildAction& operator= (const AddOrRemoveChildAction&);
  14433. };
  14434. class ValueTree::MoveChildAction : public UndoableAction
  14435. {
  14436. public:
  14437. MoveChildAction (const SharedObjectPtr& parent_,
  14438. const int startIndex_, const int endIndex_)
  14439. : parent (parent_),
  14440. startIndex (startIndex_),
  14441. endIndex (endIndex_)
  14442. {
  14443. }
  14444. ~MoveChildAction() {}
  14445. bool perform()
  14446. {
  14447. parent->moveChild (startIndex, endIndex, 0);
  14448. return true;
  14449. }
  14450. bool undo()
  14451. {
  14452. parent->moveChild (endIndex, startIndex, 0);
  14453. return true;
  14454. }
  14455. int getSizeInUnits()
  14456. {
  14457. return (int) sizeof (*this); //xxx should be more accurate
  14458. }
  14459. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  14460. {
  14461. MoveChildAction* next = dynamic_cast <MoveChildAction*> (nextAction);
  14462. if (next != 0 && next->parent == parent && next->startIndex == endIndex)
  14463. return new MoveChildAction (parent, startIndex, next->endIndex);
  14464. return 0;
  14465. }
  14466. private:
  14467. const SharedObjectPtr parent;
  14468. const int startIndex, endIndex;
  14469. MoveChildAction (const MoveChildAction&);
  14470. MoveChildAction& operator= (const MoveChildAction&);
  14471. };
  14472. ValueTree::SharedObject::SharedObject (const Identifier& type_)
  14473. : type (type_), parent (0)
  14474. {
  14475. }
  14476. ValueTree::SharedObject::SharedObject (const SharedObject& other)
  14477. : type (other.type), properties (other.properties), parent (0)
  14478. {
  14479. for (int i = 0; i < other.children.size(); ++i)
  14480. {
  14481. SharedObject* const child = new SharedObject (*other.children.getUnchecked(i));
  14482. child->parent = this;
  14483. children.add (child);
  14484. }
  14485. }
  14486. ValueTree::SharedObject::~SharedObject()
  14487. {
  14488. jassert (parent == 0); // this should never happen unless something isn't obeying the ref-counting!
  14489. for (int i = children.size(); --i >= 0;)
  14490. {
  14491. const SharedObjectPtr c (children.getUnchecked(i));
  14492. c->parent = 0;
  14493. children.remove (i);
  14494. c->sendParentChangeMessage();
  14495. }
  14496. }
  14497. void ValueTree::SharedObject::sendPropertyChangeMessage (ValueTree& tree, const Identifier& property)
  14498. {
  14499. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14500. {
  14501. ValueTree* const v = valueTreesWithListeners[i];
  14502. if (v != 0)
  14503. v->listeners.call (&ValueTree::Listener::valueTreePropertyChanged, tree, property);
  14504. }
  14505. }
  14506. void ValueTree::SharedObject::sendPropertyChangeMessage (const Identifier& property)
  14507. {
  14508. ValueTree tree (this);
  14509. ValueTree::SharedObject* t = this;
  14510. while (t != 0)
  14511. {
  14512. t->sendPropertyChangeMessage (tree, property);
  14513. t = t->parent;
  14514. }
  14515. }
  14516. void ValueTree::SharedObject::sendChildChangeMessage (ValueTree& tree)
  14517. {
  14518. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14519. {
  14520. ValueTree* const v = valueTreesWithListeners[i];
  14521. if (v != 0)
  14522. v->listeners.call (&ValueTree::Listener::valueTreeChildrenChanged, tree);
  14523. }
  14524. }
  14525. void ValueTree::SharedObject::sendChildChangeMessage()
  14526. {
  14527. ValueTree tree (this);
  14528. ValueTree::SharedObject* t = this;
  14529. while (t != 0)
  14530. {
  14531. t->sendChildChangeMessage (tree);
  14532. t = t->parent;
  14533. }
  14534. }
  14535. void ValueTree::SharedObject::sendParentChangeMessage()
  14536. {
  14537. ValueTree tree (this);
  14538. int i;
  14539. for (i = children.size(); --i >= 0;)
  14540. {
  14541. SharedObject* const t = children[i];
  14542. if (t != 0)
  14543. t->sendParentChangeMessage();
  14544. }
  14545. for (i = valueTreesWithListeners.size(); --i >= 0;)
  14546. {
  14547. ValueTree* const v = valueTreesWithListeners[i];
  14548. if (v != 0)
  14549. v->listeners.call (&ValueTree::Listener::valueTreeParentChanged, tree);
  14550. }
  14551. }
  14552. const var& ValueTree::SharedObject::getProperty (const Identifier& name) const
  14553. {
  14554. return properties [name];
  14555. }
  14556. const var ValueTree::SharedObject::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14557. {
  14558. return properties.getWithDefault (name, defaultReturnValue);
  14559. }
  14560. void ValueTree::SharedObject::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14561. {
  14562. if (undoManager == 0)
  14563. {
  14564. if (properties.set (name, newValue))
  14565. sendPropertyChangeMessage (name);
  14566. }
  14567. else
  14568. {
  14569. var* const existingValue = properties.getItem (name);
  14570. if (existingValue != 0)
  14571. {
  14572. if (*existingValue != newValue)
  14573. undoManager->perform (new SetPropertyAction (this, name, newValue, properties [name], false, false));
  14574. }
  14575. else
  14576. {
  14577. undoManager->perform (new SetPropertyAction (this, name, newValue, var::null, true, false));
  14578. }
  14579. }
  14580. }
  14581. bool ValueTree::SharedObject::hasProperty (const Identifier& name) const
  14582. {
  14583. return properties.contains (name);
  14584. }
  14585. void ValueTree::SharedObject::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14586. {
  14587. if (undoManager == 0)
  14588. {
  14589. if (properties.remove (name))
  14590. sendPropertyChangeMessage (name);
  14591. }
  14592. else
  14593. {
  14594. if (properties.contains (name))
  14595. undoManager->perform (new SetPropertyAction (this, name, var::null, properties [name], false, true));
  14596. }
  14597. }
  14598. void ValueTree::SharedObject::removeAllProperties (UndoManager* const undoManager)
  14599. {
  14600. if (undoManager == 0)
  14601. {
  14602. while (properties.size() > 0)
  14603. {
  14604. const Identifier name (properties.getName (properties.size() - 1));
  14605. properties.remove (name);
  14606. sendPropertyChangeMessage (name);
  14607. }
  14608. }
  14609. else
  14610. {
  14611. for (int i = properties.size(); --i >= 0;)
  14612. undoManager->perform (new SetPropertyAction (this, properties.getName(i), var::null, properties.getValueAt(i), false, true));
  14613. }
  14614. }
  14615. ValueTree ValueTree::SharedObject::getChildWithName (const Identifier& typeToMatch) const
  14616. {
  14617. for (int i = 0; i < children.size(); ++i)
  14618. if (children.getUnchecked(i)->type == typeToMatch)
  14619. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14620. return ValueTree::invalid;
  14621. }
  14622. ValueTree ValueTree::SharedObject::getOrCreateChildWithName (const Identifier& typeToMatch, UndoManager* undoManager)
  14623. {
  14624. for (int i = 0; i < children.size(); ++i)
  14625. if (children.getUnchecked(i)->type == typeToMatch)
  14626. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14627. SharedObject* const newObject = new SharedObject (typeToMatch);
  14628. addChild (newObject, -1, undoManager);
  14629. return ValueTree (newObject);
  14630. }
  14631. ValueTree ValueTree::SharedObject::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14632. {
  14633. for (int i = 0; i < children.size(); ++i)
  14634. if (children.getUnchecked(i)->getProperty (propertyName) == propertyValue)
  14635. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14636. return ValueTree::invalid;
  14637. }
  14638. bool ValueTree::SharedObject::isAChildOf (const SharedObject* const possibleParent) const
  14639. {
  14640. const SharedObject* p = parent;
  14641. while (p != 0)
  14642. {
  14643. if (p == possibleParent)
  14644. return true;
  14645. p = p->parent;
  14646. }
  14647. return false;
  14648. }
  14649. int ValueTree::SharedObject::indexOf (const ValueTree& child) const
  14650. {
  14651. return children.indexOf (child.object);
  14652. }
  14653. void ValueTree::SharedObject::addChild (SharedObject* child, int index, UndoManager* const undoManager)
  14654. {
  14655. if (child != 0 && child->parent != this)
  14656. {
  14657. if (child != this && ! isAChildOf (child))
  14658. {
  14659. // You should always make sure that a child is removed from its previous parent before
  14660. // adding it somewhere else - otherwise, it's ambiguous as to whether a different
  14661. // undomanager should be used when removing it from its current parent..
  14662. jassert (child->parent == 0);
  14663. if (child->parent != 0)
  14664. {
  14665. jassert (child->parent->children.indexOf (child) >= 0);
  14666. child->parent->removeChild (child->parent->children.indexOf (child), undoManager);
  14667. }
  14668. if (undoManager == 0)
  14669. {
  14670. children.insert (index, child);
  14671. child->parent = this;
  14672. sendChildChangeMessage();
  14673. child->sendParentChangeMessage();
  14674. }
  14675. else
  14676. {
  14677. if (index < 0)
  14678. index = children.size();
  14679. undoManager->perform (new AddOrRemoveChildAction (this, index, child));
  14680. }
  14681. }
  14682. else
  14683. {
  14684. // You're attempting to create a recursive loop! A node
  14685. // can't be a child of one of its own children!
  14686. jassertfalse;
  14687. }
  14688. }
  14689. }
  14690. void ValueTree::SharedObject::removeChild (const int childIndex, UndoManager* const undoManager)
  14691. {
  14692. const SharedObjectPtr child (children [childIndex]);
  14693. if (child != 0)
  14694. {
  14695. if (undoManager == 0)
  14696. {
  14697. children.remove (childIndex);
  14698. child->parent = 0;
  14699. sendChildChangeMessage();
  14700. child->sendParentChangeMessage();
  14701. }
  14702. else
  14703. {
  14704. undoManager->perform (new AddOrRemoveChildAction (this, childIndex, 0));
  14705. }
  14706. }
  14707. }
  14708. void ValueTree::SharedObject::removeAllChildren (UndoManager* const undoManager)
  14709. {
  14710. while (children.size() > 0)
  14711. removeChild (children.size() - 1, undoManager);
  14712. }
  14713. void ValueTree::SharedObject::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14714. {
  14715. // The source index must be a valid index!
  14716. jassert (((unsigned int) currentIndex) < (unsigned int) children.size());
  14717. if (currentIndex != newIndex
  14718. && ((unsigned int) currentIndex) < (unsigned int) children.size())
  14719. {
  14720. if (undoManager == 0)
  14721. {
  14722. children.move (currentIndex, newIndex);
  14723. sendChildChangeMessage();
  14724. }
  14725. else
  14726. {
  14727. if (((unsigned int) newIndex) >= (unsigned int) children.size())
  14728. newIndex = children.size() - 1;
  14729. undoManager->perform (new MoveChildAction (this, currentIndex, newIndex));
  14730. }
  14731. }
  14732. }
  14733. bool ValueTree::SharedObject::isEquivalentTo (const SharedObject& other) const
  14734. {
  14735. if (type != other.type
  14736. || properties.size() != other.properties.size()
  14737. || children.size() != other.children.size()
  14738. || properties != other.properties)
  14739. return false;
  14740. for (int i = 0; i < children.size(); ++i)
  14741. if (! children.getUnchecked(i)->isEquivalentTo (*other.children.getUnchecked(i)))
  14742. return false;
  14743. return true;
  14744. }
  14745. ValueTree::ValueTree() throw()
  14746. : object (0)
  14747. {
  14748. }
  14749. const ValueTree ValueTree::invalid;
  14750. ValueTree::ValueTree (const Identifier& type_)
  14751. : object (new ValueTree::SharedObject (type_))
  14752. {
  14753. jassert (type_.toString().isNotEmpty()); // All objects should be given a sensible type name!
  14754. }
  14755. ValueTree::ValueTree (SharedObject* const object_)
  14756. : object (object_)
  14757. {
  14758. }
  14759. ValueTree::ValueTree (const ValueTree& other)
  14760. : object (other.object)
  14761. {
  14762. }
  14763. ValueTree& ValueTree::operator= (const ValueTree& other)
  14764. {
  14765. if (listeners.size() > 0)
  14766. {
  14767. if (object != 0)
  14768. object->valueTreesWithListeners.removeValue (this);
  14769. if (other.object != 0)
  14770. other.object->valueTreesWithListeners.add (this);
  14771. }
  14772. object = other.object;
  14773. return *this;
  14774. }
  14775. ValueTree::~ValueTree()
  14776. {
  14777. if (listeners.size() > 0 && object != 0)
  14778. object->valueTreesWithListeners.removeValue (this);
  14779. }
  14780. bool ValueTree::operator== (const ValueTree& other) const throw()
  14781. {
  14782. return object == other.object;
  14783. }
  14784. bool ValueTree::operator!= (const ValueTree& other) const throw()
  14785. {
  14786. return object != other.object;
  14787. }
  14788. bool ValueTree::isEquivalentTo (const ValueTree& other) const
  14789. {
  14790. return object == other.object
  14791. || (object != 0 && other.object != 0 && object->isEquivalentTo (*other.object));
  14792. }
  14793. ValueTree ValueTree::createCopy() const
  14794. {
  14795. return ValueTree (object != 0 ? new SharedObject (*object) : 0);
  14796. }
  14797. bool ValueTree::hasType (const Identifier& typeName) const
  14798. {
  14799. return object != 0 && object->type == typeName;
  14800. }
  14801. const Identifier ValueTree::getType() const
  14802. {
  14803. return object != 0 ? object->type : Identifier();
  14804. }
  14805. ValueTree ValueTree::getParent() const
  14806. {
  14807. return ValueTree (object != 0 ? object->parent : (SharedObject*) 0);
  14808. }
  14809. ValueTree ValueTree::getSibling (const int delta) const
  14810. {
  14811. if (object == 0 || object->parent == 0)
  14812. return invalid;
  14813. const int index = object->parent->indexOf (*this) + delta;
  14814. return ValueTree (static_cast <SharedObject*> (object->parent->children [index]));
  14815. }
  14816. const var& ValueTree::operator[] (const Identifier& name) const
  14817. {
  14818. return object == 0 ? var::null : object->getProperty (name);
  14819. }
  14820. const var& ValueTree::getProperty (const Identifier& name) const
  14821. {
  14822. return object == 0 ? var::null : object->getProperty (name);
  14823. }
  14824. const var ValueTree::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14825. {
  14826. return object == 0 ? defaultReturnValue : object->getProperty (name, defaultReturnValue);
  14827. }
  14828. void ValueTree::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14829. {
  14830. jassert (name.toString().isNotEmpty());
  14831. if (object != 0 && name.toString().isNotEmpty())
  14832. object->setProperty (name, newValue, undoManager);
  14833. }
  14834. bool ValueTree::hasProperty (const Identifier& name) const
  14835. {
  14836. return object != 0 && object->hasProperty (name);
  14837. }
  14838. void ValueTree::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14839. {
  14840. if (object != 0)
  14841. object->removeProperty (name, undoManager);
  14842. }
  14843. void ValueTree::removeAllProperties (UndoManager* const undoManager)
  14844. {
  14845. if (object != 0)
  14846. object->removeAllProperties (undoManager);
  14847. }
  14848. int ValueTree::getNumProperties() const
  14849. {
  14850. return object == 0 ? 0 : object->properties.size();
  14851. }
  14852. const Identifier ValueTree::getPropertyName (const int index) const
  14853. {
  14854. return object == 0 ? Identifier()
  14855. : object->properties.getName (index);
  14856. }
  14857. class ValueTreePropertyValueSource : public Value::ValueSource,
  14858. public ValueTree::Listener
  14859. {
  14860. public:
  14861. ValueTreePropertyValueSource (const ValueTree& tree_,
  14862. const Identifier& property_,
  14863. UndoManager* const undoManager_)
  14864. : tree (tree_),
  14865. property (property_),
  14866. undoManager (undoManager_)
  14867. {
  14868. tree.addListener (this);
  14869. }
  14870. ~ValueTreePropertyValueSource()
  14871. {
  14872. tree.removeListener (this);
  14873. }
  14874. const var getValue() const
  14875. {
  14876. return tree [property];
  14877. }
  14878. void setValue (const var& newValue)
  14879. {
  14880. tree.setProperty (property, newValue, undoManager);
  14881. }
  14882. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const Identifier& changedProperty)
  14883. {
  14884. if (tree == treeWhosePropertyHasChanged && property == changedProperty)
  14885. sendChangeMessage (false);
  14886. }
  14887. void valueTreeChildrenChanged (ValueTree&) {}
  14888. void valueTreeParentChanged (ValueTree&) {}
  14889. private:
  14890. ValueTree tree;
  14891. const Identifier property;
  14892. UndoManager* const undoManager;
  14893. ValueTreePropertyValueSource& operator= (const ValueTreePropertyValueSource&);
  14894. };
  14895. Value ValueTree::getPropertyAsValue (const Identifier& name, UndoManager* const undoManager) const
  14896. {
  14897. return Value (new ValueTreePropertyValueSource (*this, name, undoManager));
  14898. }
  14899. int ValueTree::getNumChildren() const
  14900. {
  14901. return object == 0 ? 0 : object->children.size();
  14902. }
  14903. ValueTree ValueTree::getChild (int index) const
  14904. {
  14905. return ValueTree (object != 0 ? (SharedObject*) object->children [index] : (SharedObject*) 0);
  14906. }
  14907. ValueTree ValueTree::getChildWithName (const Identifier& type) const
  14908. {
  14909. return object != 0 ? object->getChildWithName (type) : ValueTree::invalid;
  14910. }
  14911. ValueTree ValueTree::getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager)
  14912. {
  14913. return object != 0 ? object->getOrCreateChildWithName (type, undoManager) : ValueTree::invalid;
  14914. }
  14915. ValueTree ValueTree::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14916. {
  14917. return object != 0 ? object->getChildWithProperty (propertyName, propertyValue) : ValueTree::invalid;
  14918. }
  14919. bool ValueTree::isAChildOf (const ValueTree& possibleParent) const
  14920. {
  14921. return object != 0 && object->isAChildOf (possibleParent.object);
  14922. }
  14923. int ValueTree::indexOf (const ValueTree& child) const
  14924. {
  14925. return object != 0 ? object->indexOf (child) : -1;
  14926. }
  14927. void ValueTree::addChild (const ValueTree& child, int index, UndoManager* const undoManager)
  14928. {
  14929. if (object != 0)
  14930. object->addChild (child.object, index, undoManager);
  14931. }
  14932. void ValueTree::removeChild (const int childIndex, UndoManager* const undoManager)
  14933. {
  14934. if (object != 0)
  14935. object->removeChild (childIndex, undoManager);
  14936. }
  14937. void ValueTree::removeChild (const ValueTree& child, UndoManager* const undoManager)
  14938. {
  14939. if (object != 0)
  14940. object->removeChild (object->children.indexOf (child.object), undoManager);
  14941. }
  14942. void ValueTree::removeAllChildren (UndoManager* const undoManager)
  14943. {
  14944. if (object != 0)
  14945. object->removeAllChildren (undoManager);
  14946. }
  14947. void ValueTree::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14948. {
  14949. if (object != 0)
  14950. object->moveChild (currentIndex, newIndex, undoManager);
  14951. }
  14952. void ValueTree::addListener (Listener* listener)
  14953. {
  14954. if (listener != 0)
  14955. {
  14956. if (listeners.size() == 0 && object != 0)
  14957. object->valueTreesWithListeners.add (this);
  14958. listeners.add (listener);
  14959. }
  14960. }
  14961. void ValueTree::removeListener (Listener* listener)
  14962. {
  14963. listeners.remove (listener);
  14964. if (listeners.size() == 0 && object != 0)
  14965. object->valueTreesWithListeners.removeValue (this);
  14966. }
  14967. XmlElement* ValueTree::SharedObject::createXml() const
  14968. {
  14969. XmlElement* xml = new XmlElement (type.toString());
  14970. int i;
  14971. for (i = 0; i < properties.size(); ++i)
  14972. {
  14973. Identifier name (properties.getName(i));
  14974. const var& v = properties [name];
  14975. jassert (! v.isObject()); // DynamicObjects can't be stored as XML!
  14976. xml->setAttribute (name.toString(), v.toString());
  14977. }
  14978. for (i = 0; i < children.size(); ++i)
  14979. xml->addChildElement (children.getUnchecked(i)->createXml());
  14980. return xml;
  14981. }
  14982. XmlElement* ValueTree::createXml() const
  14983. {
  14984. return object != 0 ? object->createXml() : 0;
  14985. }
  14986. ValueTree ValueTree::fromXml (const XmlElement& xml)
  14987. {
  14988. ValueTree v (xml.getTagName());
  14989. const int numAtts = xml.getNumAttributes(); // xxx inefficient - should write an att iterator..
  14990. for (int i = 0; i < numAtts; ++i)
  14991. v.setProperty (xml.getAttributeName (i), var (xml.getAttributeValue (i)), 0);
  14992. forEachXmlChildElement (xml, e)
  14993. {
  14994. v.addChild (fromXml (*e), -1, 0);
  14995. }
  14996. return v;
  14997. }
  14998. void ValueTree::writeToStream (OutputStream& output)
  14999. {
  15000. output.writeString (getType().toString());
  15001. const int numProps = getNumProperties();
  15002. output.writeCompressedInt (numProps);
  15003. int i;
  15004. for (i = 0; i < numProps; ++i)
  15005. {
  15006. const Identifier name (getPropertyName(i));
  15007. output.writeString (name.toString());
  15008. getProperty(name).writeToStream (output);
  15009. }
  15010. const int numChildren = getNumChildren();
  15011. output.writeCompressedInt (numChildren);
  15012. for (i = 0; i < numChildren; ++i)
  15013. getChild (i).writeToStream (output);
  15014. }
  15015. ValueTree ValueTree::readFromStream (InputStream& input)
  15016. {
  15017. const String type (input.readString());
  15018. if (type.isEmpty())
  15019. return ValueTree::invalid;
  15020. ValueTree v (type);
  15021. const int numProps = input.readCompressedInt();
  15022. if (numProps < 0)
  15023. {
  15024. jassertfalse; // trying to read corrupted data!
  15025. return v;
  15026. }
  15027. int i;
  15028. for (i = 0; i < numProps; ++i)
  15029. {
  15030. const String name (input.readString());
  15031. jassert (name.isNotEmpty());
  15032. const var value (var::readFromStream (input));
  15033. v.setProperty (name, value, 0);
  15034. }
  15035. const int numChildren = input.readCompressedInt();
  15036. for (i = 0; i < numChildren; ++i)
  15037. v.addChild (readFromStream (input), -1, 0);
  15038. return v;
  15039. }
  15040. ValueTree ValueTree::readFromData (const void* const data, const size_t numBytes)
  15041. {
  15042. MemoryInputStream in (data, numBytes, false);
  15043. return readFromStream (in);
  15044. }
  15045. END_JUCE_NAMESPACE
  15046. /*** End of inlined file: juce_ValueTree.cpp ***/
  15047. /*** Start of inlined file: juce_Value.cpp ***/
  15048. BEGIN_JUCE_NAMESPACE
  15049. Value::ValueSource::ValueSource()
  15050. {
  15051. }
  15052. Value::ValueSource::~ValueSource()
  15053. {
  15054. }
  15055. void Value::ValueSource::sendChangeMessage (const bool synchronous)
  15056. {
  15057. if (synchronous)
  15058. {
  15059. for (int i = valuesWithListeners.size(); --i >= 0;)
  15060. {
  15061. Value* const v = valuesWithListeners[i];
  15062. if (v != 0)
  15063. v->callListeners();
  15064. }
  15065. }
  15066. else
  15067. {
  15068. triggerAsyncUpdate();
  15069. }
  15070. }
  15071. void Value::ValueSource::handleAsyncUpdate()
  15072. {
  15073. sendChangeMessage (true);
  15074. }
  15075. class SimpleValueSource : public Value::ValueSource
  15076. {
  15077. public:
  15078. SimpleValueSource()
  15079. {
  15080. }
  15081. SimpleValueSource (const var& initialValue)
  15082. : value (initialValue)
  15083. {
  15084. }
  15085. ~SimpleValueSource()
  15086. {
  15087. }
  15088. const var getValue() const
  15089. {
  15090. return value;
  15091. }
  15092. void setValue (const var& newValue)
  15093. {
  15094. if (newValue != value)
  15095. {
  15096. value = newValue;
  15097. sendChangeMessage (false);
  15098. }
  15099. }
  15100. private:
  15101. var value;
  15102. SimpleValueSource (const SimpleValueSource&);
  15103. SimpleValueSource& operator= (const SimpleValueSource&);
  15104. };
  15105. Value::Value()
  15106. : value (new SimpleValueSource())
  15107. {
  15108. }
  15109. Value::Value (ValueSource* const value_)
  15110. : value (value_)
  15111. {
  15112. jassert (value_ != 0);
  15113. }
  15114. Value::Value (const var& initialValue)
  15115. : value (new SimpleValueSource (initialValue))
  15116. {
  15117. }
  15118. Value::Value (const Value& other)
  15119. : value (other.value)
  15120. {
  15121. }
  15122. Value& Value::operator= (const Value& other)
  15123. {
  15124. value = other.value;
  15125. return *this;
  15126. }
  15127. Value::~Value()
  15128. {
  15129. if (listeners.size() > 0)
  15130. value->valuesWithListeners.removeValue (this);
  15131. }
  15132. const var Value::getValue() const
  15133. {
  15134. return value->getValue();
  15135. }
  15136. Value::operator const var() const
  15137. {
  15138. return getValue();
  15139. }
  15140. void Value::setValue (const var& newValue)
  15141. {
  15142. value->setValue (newValue);
  15143. }
  15144. const String Value::toString() const
  15145. {
  15146. return value->getValue().toString();
  15147. }
  15148. Value& Value::operator= (const var& newValue)
  15149. {
  15150. value->setValue (newValue);
  15151. return *this;
  15152. }
  15153. void Value::referTo (const Value& valueToReferTo)
  15154. {
  15155. if (valueToReferTo.value != value)
  15156. {
  15157. if (listeners.size() > 0)
  15158. {
  15159. value->valuesWithListeners.removeValue (this);
  15160. valueToReferTo.value->valuesWithListeners.add (this);
  15161. }
  15162. value = valueToReferTo.value;
  15163. callListeners();
  15164. }
  15165. }
  15166. bool Value::refersToSameSourceAs (const Value& other) const
  15167. {
  15168. return value == other.value;
  15169. }
  15170. bool Value::operator== (const Value& other) const
  15171. {
  15172. return value == other.value || value->getValue() == other.getValue();
  15173. }
  15174. bool Value::operator!= (const Value& other) const
  15175. {
  15176. return value != other.value && value->getValue() != other.getValue();
  15177. }
  15178. void Value::addListener (Listener* const listener)
  15179. {
  15180. if (listener != 0)
  15181. {
  15182. if (listeners.size() == 0)
  15183. value->valuesWithListeners.add (this);
  15184. listeners.add (listener);
  15185. }
  15186. }
  15187. void Value::removeListener (Listener* const listener)
  15188. {
  15189. listeners.remove (listener);
  15190. if (listeners.size() == 0)
  15191. value->valuesWithListeners.removeValue (this);
  15192. }
  15193. void Value::callListeners()
  15194. {
  15195. Value v (*this); // (create a copy in case this gets deleted by a callback)
  15196. listeners.call (&Value::Listener::valueChanged, v);
  15197. }
  15198. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value)
  15199. {
  15200. return stream << value.toString();
  15201. }
  15202. END_JUCE_NAMESPACE
  15203. /*** End of inlined file: juce_Value.cpp ***/
  15204. /*** Start of inlined file: juce_Application.cpp ***/
  15205. BEGIN_JUCE_NAMESPACE
  15206. #if JUCE_MAC
  15207. extern void juce_initialiseMacMainMenu();
  15208. #endif
  15209. JUCEApplication::JUCEApplication()
  15210. : appReturnValue (0),
  15211. stillInitialising (true)
  15212. {
  15213. jassert (isStandaloneApp() && appInstance == 0);
  15214. appInstance = this;
  15215. }
  15216. JUCEApplication::~JUCEApplication()
  15217. {
  15218. if (appLock != 0)
  15219. {
  15220. appLock->exit();
  15221. appLock = 0;
  15222. }
  15223. jassert (appInstance == this);
  15224. appInstance = 0;
  15225. }
  15226. JUCEApplication::CreateInstanceFunction JUCEApplication::createInstance = 0;
  15227. JUCEApplication* JUCEApplication::appInstance = 0;
  15228. bool JUCEApplication::moreThanOneInstanceAllowed()
  15229. {
  15230. return true;
  15231. }
  15232. void JUCEApplication::anotherInstanceStarted (const String&)
  15233. {
  15234. }
  15235. void JUCEApplication::systemRequestedQuit()
  15236. {
  15237. quit();
  15238. }
  15239. void JUCEApplication::quit()
  15240. {
  15241. MessageManager::getInstance()->stopDispatchLoop();
  15242. }
  15243. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  15244. {
  15245. appReturnValue = newReturnValue;
  15246. }
  15247. void JUCEApplication::actionListenerCallback (const String& message)
  15248. {
  15249. if (message.startsWith (getApplicationName() + "/"))
  15250. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  15251. }
  15252. void JUCEApplication::unhandledException (const std::exception*,
  15253. const String&,
  15254. const int)
  15255. {
  15256. jassertfalse;
  15257. }
  15258. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  15259. const char* const sourceFile,
  15260. const int lineNumber)
  15261. {
  15262. if (appInstance != 0)
  15263. appInstance->unhandledException (e, sourceFile, lineNumber);
  15264. }
  15265. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  15266. {
  15267. return 0;
  15268. }
  15269. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  15270. {
  15271. commands.add (StandardApplicationCommandIDs::quit);
  15272. }
  15273. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  15274. {
  15275. if (commandID == StandardApplicationCommandIDs::quit)
  15276. {
  15277. result.setInfo (TRANS("Quit"),
  15278. TRANS("Quits the application"),
  15279. "Application",
  15280. 0);
  15281. result.defaultKeypresses.add (KeyPress ('q', ModifierKeys::commandModifier, 0));
  15282. }
  15283. }
  15284. bool JUCEApplication::perform (const InvocationInfo& info)
  15285. {
  15286. if (info.commandID == StandardApplicationCommandIDs::quit)
  15287. {
  15288. systemRequestedQuit();
  15289. return true;
  15290. }
  15291. return false;
  15292. }
  15293. bool JUCEApplication::initialiseApp (const String& commandLine)
  15294. {
  15295. commandLineParameters = commandLine.trim();
  15296. #if ! JUCE_IOS
  15297. jassert (appLock == 0); // initialiseApp must only be called once!
  15298. if (! moreThanOneInstanceAllowed())
  15299. {
  15300. appLock = new InterProcessLock ("juceAppLock_" + getApplicationName());
  15301. if (! appLock->enter(0))
  15302. {
  15303. appLock = 0;
  15304. MessageManager::broadcastMessage (getApplicationName() + "/" + commandLineParameters);
  15305. DBG ("Another instance is running - quitting...");
  15306. return false;
  15307. }
  15308. }
  15309. #endif
  15310. // let the app do its setting-up..
  15311. initialise (commandLineParameters);
  15312. #if JUCE_MAC
  15313. juce_initialiseMacMainMenu(); // needs to be called after the app object has created, to get its name
  15314. #endif
  15315. // register for broadcast new app messages
  15316. MessageManager::getInstance()->registerBroadcastListener (this);
  15317. stillInitialising = false;
  15318. return true;
  15319. }
  15320. int JUCEApplication::shutdownApp()
  15321. {
  15322. jassert (appInstance == this);
  15323. MessageManager::getInstance()->deregisterBroadcastListener (this);
  15324. JUCE_TRY
  15325. {
  15326. // give the app a chance to clean up..
  15327. shutdown();
  15328. }
  15329. JUCE_CATCH_EXCEPTION
  15330. return getApplicationReturnValue();
  15331. }
  15332. // This is called on the Mac and iOS where the OS doesn't allow the stack to unwind on shutdown..
  15333. void JUCEApplication::appWillTerminateByForce()
  15334. {
  15335. {
  15336. const ScopedPointer<JUCEApplication> app (JUCEApplication::getInstance());
  15337. if (app != 0)
  15338. app->shutdownApp();
  15339. }
  15340. shutdownJuce_GUI();
  15341. }
  15342. int JUCEApplication::main (const String& commandLine)
  15343. {
  15344. ScopedJuceInitialiser_GUI libraryInitialiser;
  15345. jassert (createInstance != 0);
  15346. int returnCode = 0;
  15347. {
  15348. const ScopedPointer<JUCEApplication> app (createInstance());
  15349. if (! app->initialiseApp (commandLine))
  15350. return 0;
  15351. JUCE_TRY
  15352. {
  15353. // loop until a quit message is received..
  15354. MessageManager::getInstance()->runDispatchLoop();
  15355. }
  15356. JUCE_CATCH_EXCEPTION
  15357. returnCode = app->shutdownApp();
  15358. }
  15359. return returnCode;
  15360. }
  15361. #if JUCE_IOS
  15362. extern int juce_iOSMain (int argc, const char* argv[]);
  15363. #endif
  15364. #if ! JUCE_WINDOWS
  15365. extern const char* juce_Argv0;
  15366. #endif
  15367. int JUCEApplication::main (int argc, const char* argv[])
  15368. {
  15369. JUCE_AUTORELEASEPOOL
  15370. #if ! JUCE_WINDOWS
  15371. jassert (createInstance != 0);
  15372. juce_Argv0 = argv[0];
  15373. #endif
  15374. #if JUCE_IOS
  15375. return juce_iOSMain (argc, argv);
  15376. #else
  15377. String cmd;
  15378. for (int i = 1; i < argc; ++i)
  15379. cmd << argv[i] << ' ';
  15380. return JUCEApplication::main (cmd);
  15381. #endif
  15382. }
  15383. END_JUCE_NAMESPACE
  15384. /*** End of inlined file: juce_Application.cpp ***/
  15385. /*** Start of inlined file: juce_ApplicationCommandInfo.cpp ***/
  15386. BEGIN_JUCE_NAMESPACE
  15387. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  15388. : commandID (commandID_),
  15389. flags (0)
  15390. {
  15391. }
  15392. void ApplicationCommandInfo::setInfo (const String& shortName_,
  15393. const String& description_,
  15394. const String& categoryName_,
  15395. const int flags_) throw()
  15396. {
  15397. shortName = shortName_;
  15398. description = description_;
  15399. categoryName = categoryName_;
  15400. flags = flags_;
  15401. }
  15402. void ApplicationCommandInfo::setActive (const bool b) throw()
  15403. {
  15404. if (b)
  15405. flags &= ~isDisabled;
  15406. else
  15407. flags |= isDisabled;
  15408. }
  15409. void ApplicationCommandInfo::setTicked (const bool b) throw()
  15410. {
  15411. if (b)
  15412. flags |= isTicked;
  15413. else
  15414. flags &= ~isTicked;
  15415. }
  15416. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  15417. {
  15418. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  15419. }
  15420. END_JUCE_NAMESPACE
  15421. /*** End of inlined file: juce_ApplicationCommandInfo.cpp ***/
  15422. /*** Start of inlined file: juce_ApplicationCommandManager.cpp ***/
  15423. BEGIN_JUCE_NAMESPACE
  15424. ApplicationCommandManager::ApplicationCommandManager()
  15425. : firstTarget (0)
  15426. {
  15427. keyMappings = new KeyPressMappingSet (this);
  15428. Desktop::getInstance().addFocusChangeListener (this);
  15429. }
  15430. ApplicationCommandManager::~ApplicationCommandManager()
  15431. {
  15432. Desktop::getInstance().removeFocusChangeListener (this);
  15433. keyMappings = 0;
  15434. }
  15435. void ApplicationCommandManager::clearCommands()
  15436. {
  15437. commands.clear();
  15438. keyMappings->clearAllKeyPresses();
  15439. triggerAsyncUpdate();
  15440. }
  15441. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  15442. {
  15443. // zero isn't a valid command ID!
  15444. jassert (newCommand.commandID != 0);
  15445. // the name isn't optional!
  15446. jassert (newCommand.shortName.isNotEmpty());
  15447. if (getCommandForID (newCommand.commandID) == 0)
  15448. {
  15449. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  15450. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  15451. commands.add (newInfo);
  15452. keyMappings->resetToDefaultMapping (newCommand.commandID);
  15453. triggerAsyncUpdate();
  15454. }
  15455. else
  15456. {
  15457. // trying to re-register the same command with different parameters?
  15458. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  15459. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  15460. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  15461. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  15462. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  15463. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  15464. }
  15465. }
  15466. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  15467. {
  15468. if (target != 0)
  15469. {
  15470. Array <CommandID> commandIDs;
  15471. target->getAllCommands (commandIDs);
  15472. for (int i = 0; i < commandIDs.size(); ++i)
  15473. {
  15474. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  15475. target->getCommandInfo (info.commandID, info);
  15476. registerCommand (info);
  15477. }
  15478. }
  15479. }
  15480. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  15481. {
  15482. for (int i = commands.size(); --i >= 0;)
  15483. {
  15484. if (commands.getUnchecked (i)->commandID == commandID)
  15485. {
  15486. commands.remove (i);
  15487. triggerAsyncUpdate();
  15488. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  15489. for (int j = keys.size(); --j >= 0;)
  15490. keyMappings->removeKeyPress (keys.getReference (j));
  15491. }
  15492. }
  15493. }
  15494. void ApplicationCommandManager::commandStatusChanged()
  15495. {
  15496. triggerAsyncUpdate();
  15497. }
  15498. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  15499. {
  15500. for (int i = commands.size(); --i >= 0;)
  15501. if (commands.getUnchecked(i)->commandID == commandID)
  15502. return commands.getUnchecked(i);
  15503. return 0;
  15504. }
  15505. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  15506. {
  15507. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  15508. return (ci != 0) ? ci->shortName : String::empty;
  15509. }
  15510. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  15511. {
  15512. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  15513. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  15514. : String::empty;
  15515. }
  15516. const StringArray ApplicationCommandManager::getCommandCategories() const
  15517. {
  15518. StringArray s;
  15519. for (int i = 0; i < commands.size(); ++i)
  15520. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  15521. return s;
  15522. }
  15523. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const
  15524. {
  15525. Array <CommandID> results;
  15526. for (int i = 0; i < commands.size(); ++i)
  15527. if (commands.getUnchecked(i)->categoryName == categoryName)
  15528. results.add (commands.getUnchecked(i)->commandID);
  15529. return results;
  15530. }
  15531. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15532. {
  15533. ApplicationCommandTarget::InvocationInfo info (commandID);
  15534. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15535. return invoke (info, asynchronously);
  15536. }
  15537. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  15538. {
  15539. // This call isn't thread-safe for use from a non-UI thread without locking the message
  15540. // manager first..
  15541. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  15542. ApplicationCommandTarget* const target = getFirstCommandTarget (info_.commandID);
  15543. if (target == 0)
  15544. return false;
  15545. ApplicationCommandInfo commandInfo (0);
  15546. target->getCommandInfo (info_.commandID, commandInfo);
  15547. ApplicationCommandTarget::InvocationInfo info (info_);
  15548. info.commandFlags = commandInfo.flags;
  15549. sendListenerInvokeCallback (info);
  15550. const bool ok = target->invoke (info, asynchronously);
  15551. commandStatusChanged();
  15552. return ok;
  15553. }
  15554. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  15555. {
  15556. return firstTarget != 0 ? firstTarget
  15557. : findDefaultComponentTarget();
  15558. }
  15559. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  15560. {
  15561. firstTarget = newTarget;
  15562. }
  15563. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  15564. ApplicationCommandInfo& upToDateInfo)
  15565. {
  15566. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  15567. if (target == 0)
  15568. target = JUCEApplication::getInstance();
  15569. if (target != 0)
  15570. target = target->getTargetForCommand (commandID);
  15571. if (target != 0)
  15572. target->getCommandInfo (commandID, upToDateInfo);
  15573. return target;
  15574. }
  15575. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  15576. {
  15577. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  15578. if (target == 0 && c != 0)
  15579. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15580. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15581. return target;
  15582. }
  15583. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  15584. {
  15585. Component* c = Component::getCurrentlyFocusedComponent();
  15586. if (c == 0)
  15587. {
  15588. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  15589. if (activeWindow != 0)
  15590. {
  15591. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  15592. if (c == 0)
  15593. c = activeWindow;
  15594. }
  15595. }
  15596. if (c == 0 && Process::isForegroundProcess())
  15597. {
  15598. // getting a bit desperate now - try all desktop comps..
  15599. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  15600. {
  15601. ApplicationCommandTarget* const target
  15602. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  15603. ->getPeer()->getLastFocusedSubcomponent());
  15604. if (target != 0)
  15605. return target;
  15606. }
  15607. }
  15608. if (c != 0)
  15609. {
  15610. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  15611. // if we're focused on a ResizableWindow, chances are that it's the content
  15612. // component that really should get the event. And if not, the event will
  15613. // still be passed up to the top level window anyway, so let's send it to the
  15614. // content comp.
  15615. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  15616. c = resizableWindow->getContentComponent();
  15617. ApplicationCommandTarget* const target = findTargetForComponent (c);
  15618. if (target != 0)
  15619. return target;
  15620. }
  15621. return JUCEApplication::getInstance();
  15622. }
  15623. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener)
  15624. {
  15625. listeners.add (listener);
  15626. }
  15627. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener)
  15628. {
  15629. listeners.remove (listener);
  15630. }
  15631. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info)
  15632. {
  15633. listeners.call (&ApplicationCommandManagerListener::applicationCommandInvoked, info);
  15634. }
  15635. void ApplicationCommandManager::handleAsyncUpdate()
  15636. {
  15637. listeners.call (&ApplicationCommandManagerListener::applicationCommandListChanged);
  15638. }
  15639. void ApplicationCommandManager::globalFocusChanged (Component*)
  15640. {
  15641. commandStatusChanged();
  15642. }
  15643. END_JUCE_NAMESPACE
  15644. /*** End of inlined file: juce_ApplicationCommandManager.cpp ***/
  15645. /*** Start of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15646. BEGIN_JUCE_NAMESPACE
  15647. ApplicationCommandTarget::ApplicationCommandTarget()
  15648. {
  15649. }
  15650. ApplicationCommandTarget::~ApplicationCommandTarget()
  15651. {
  15652. messageInvoker = 0;
  15653. }
  15654. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  15655. {
  15656. if (isCommandActive (info.commandID))
  15657. {
  15658. if (async)
  15659. {
  15660. if (messageInvoker == 0)
  15661. messageInvoker = new CommandTargetMessageInvoker (this);
  15662. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  15663. return true;
  15664. }
  15665. else
  15666. {
  15667. const bool success = perform (info);
  15668. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  15669. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  15670. // returns the command's info.
  15671. return success;
  15672. }
  15673. }
  15674. return false;
  15675. }
  15676. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  15677. {
  15678. Component* c = dynamic_cast <Component*> (this);
  15679. if (c != 0)
  15680. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15681. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15682. return 0;
  15683. }
  15684. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  15685. {
  15686. ApplicationCommandTarget* target = this;
  15687. int depth = 0;
  15688. while (target != 0)
  15689. {
  15690. Array <CommandID> commandIDs;
  15691. target->getAllCommands (commandIDs);
  15692. if (commandIDs.contains (commandID))
  15693. return target;
  15694. target = target->getNextCommandTarget();
  15695. ++depth;
  15696. jassert (depth < 100); // could be a recursive command chain??
  15697. jassert (target != this); // definitely a recursive command chain!
  15698. if (depth > 100 || target == this)
  15699. break;
  15700. }
  15701. if (target == 0)
  15702. {
  15703. target = JUCEApplication::getInstance();
  15704. if (target != 0)
  15705. {
  15706. Array <CommandID> commandIDs;
  15707. target->getAllCommands (commandIDs);
  15708. if (commandIDs.contains (commandID))
  15709. return target;
  15710. }
  15711. }
  15712. return 0;
  15713. }
  15714. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  15715. {
  15716. ApplicationCommandInfo info (commandID);
  15717. info.flags = ApplicationCommandInfo::isDisabled;
  15718. getCommandInfo (commandID, info);
  15719. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  15720. }
  15721. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  15722. {
  15723. ApplicationCommandTarget* target = this;
  15724. int depth = 0;
  15725. while (target != 0)
  15726. {
  15727. if (target->tryToInvoke (info, async))
  15728. return true;
  15729. target = target->getNextCommandTarget();
  15730. ++depth;
  15731. jassert (depth < 100); // could be a recursive command chain??
  15732. jassert (target != this); // definitely a recursive command chain!
  15733. if (depth > 100 || target == this)
  15734. break;
  15735. }
  15736. if (target == 0)
  15737. {
  15738. target = JUCEApplication::getInstance();
  15739. if (target != 0)
  15740. return target->tryToInvoke (info, async);
  15741. }
  15742. return false;
  15743. }
  15744. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15745. {
  15746. ApplicationCommandTarget::InvocationInfo info (commandID);
  15747. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15748. return invoke (info, asynchronously);
  15749. }
  15750. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_)
  15751. : commandID (commandID_),
  15752. commandFlags (0),
  15753. invocationMethod (direct),
  15754. originatingComponent (0),
  15755. isKeyDown (false),
  15756. millisecsSinceKeyPressed (0)
  15757. {
  15758. }
  15759. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  15760. : owner (owner_)
  15761. {
  15762. }
  15763. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  15764. {
  15765. }
  15766. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  15767. {
  15768. const ScopedPointer <InvocationInfo> info (static_cast <InvocationInfo*> (message.pointerParameter));
  15769. owner->tryToInvoke (*info, false);
  15770. }
  15771. END_JUCE_NAMESPACE
  15772. /*** End of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15773. /*** Start of inlined file: juce_ApplicationProperties.cpp ***/
  15774. BEGIN_JUCE_NAMESPACE
  15775. juce_ImplementSingleton (ApplicationProperties)
  15776. ApplicationProperties::ApplicationProperties()
  15777. : msBeforeSaving (3000),
  15778. options (PropertiesFile::storeAsBinary),
  15779. commonSettingsAreReadOnly (0),
  15780. processLock (0)
  15781. {
  15782. }
  15783. ApplicationProperties::~ApplicationProperties()
  15784. {
  15785. closeFiles();
  15786. clearSingletonInstance();
  15787. }
  15788. void ApplicationProperties::setStorageParameters (const String& applicationName,
  15789. const String& fileNameSuffix,
  15790. const String& folderName_,
  15791. const int millisecondsBeforeSaving,
  15792. const int propertiesFileOptions,
  15793. InterProcessLock* processLock_)
  15794. {
  15795. appName = applicationName;
  15796. fileSuffix = fileNameSuffix;
  15797. folderName = folderName_;
  15798. msBeforeSaving = millisecondsBeforeSaving;
  15799. options = propertiesFileOptions;
  15800. processLock = processLock_;
  15801. }
  15802. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  15803. const bool testCommonSettings,
  15804. const bool showWarningDialogOnFailure)
  15805. {
  15806. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  15807. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  15808. if (! (userOk && commonOk))
  15809. {
  15810. if (showWarningDialogOnFailure)
  15811. {
  15812. String filenames;
  15813. if (userProps != 0 && ! userOk)
  15814. filenames << '\n' << userProps->getFile().getFullPathName();
  15815. if (commonProps != 0 && ! commonOk)
  15816. filenames << '\n' << commonProps->getFile().getFullPathName();
  15817. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  15818. appName + TRANS(" - Unable to save settings"),
  15819. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  15820. + appName + TRANS(" needs to be able to write to the following files:\n")
  15821. + filenames
  15822. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  15823. }
  15824. return false;
  15825. }
  15826. return true;
  15827. }
  15828. void ApplicationProperties::openFiles()
  15829. {
  15830. // You need to call setStorageParameters() before trying to get hold of the
  15831. // properties!
  15832. jassert (appName.isNotEmpty());
  15833. if (appName.isNotEmpty())
  15834. {
  15835. if (userProps == 0)
  15836. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15837. false, msBeforeSaving, options, processLock);
  15838. if (commonProps == 0)
  15839. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15840. true, msBeforeSaving, options, processLock);
  15841. userProps->setFallbackPropertySet (commonProps);
  15842. }
  15843. }
  15844. PropertiesFile* ApplicationProperties::getUserSettings()
  15845. {
  15846. if (userProps == 0)
  15847. openFiles();
  15848. return userProps;
  15849. }
  15850. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly)
  15851. {
  15852. if (commonProps == 0)
  15853. openFiles();
  15854. if (returnUserPropsIfReadOnly)
  15855. {
  15856. if (commonSettingsAreReadOnly == 0)
  15857. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  15858. if (commonSettingsAreReadOnly > 0)
  15859. return userProps;
  15860. }
  15861. return commonProps;
  15862. }
  15863. bool ApplicationProperties::saveIfNeeded()
  15864. {
  15865. return (userProps == 0 || userProps->saveIfNeeded())
  15866. && (commonProps == 0 || commonProps->saveIfNeeded());
  15867. }
  15868. void ApplicationProperties::closeFiles()
  15869. {
  15870. userProps = 0;
  15871. commonProps = 0;
  15872. }
  15873. END_JUCE_NAMESPACE
  15874. /*** End of inlined file: juce_ApplicationProperties.cpp ***/
  15875. /*** Start of inlined file: juce_PropertiesFile.cpp ***/
  15876. BEGIN_JUCE_NAMESPACE
  15877. namespace PropertyFileConstants
  15878. {
  15879. static const int magicNumber = (int) ByteOrder::littleEndianInt ("PROP");
  15880. static const int magicNumberCompressed = (int) ByteOrder::littleEndianInt ("CPRP");
  15881. static const char* const fileTag = "PROPERTIES";
  15882. static const char* const valueTag = "VALUE";
  15883. static const char* const nameAttribute = "name";
  15884. static const char* const valueAttribute = "val";
  15885. }
  15886. PropertiesFile::PropertiesFile (const File& f, const int millisecondsBeforeSaving,
  15887. const int options_, InterProcessLock* const processLock_)
  15888. : PropertySet (ignoreCaseOfKeyNames),
  15889. file (f),
  15890. timerInterval (millisecondsBeforeSaving),
  15891. options (options_),
  15892. loadedOk (false),
  15893. needsWriting (false),
  15894. processLock (processLock_)
  15895. {
  15896. // You need to correctly specify just one storage format for the file
  15897. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  15898. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  15899. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  15900. ProcessScopedLock pl (createProcessLock());
  15901. if (pl != 0 && ! pl->isLocked())
  15902. return; // locking failure..
  15903. ScopedPointer<InputStream> fileStream (f.createInputStream());
  15904. if (fileStream != 0)
  15905. {
  15906. int magicNumber = fileStream->readInt();
  15907. if (magicNumber == PropertyFileConstants::magicNumberCompressed)
  15908. {
  15909. fileStream = new GZIPDecompressorInputStream (new SubregionStream (fileStream.release(), 4, -1, true), true);
  15910. magicNumber = PropertyFileConstants::magicNumber;
  15911. }
  15912. if (magicNumber == PropertyFileConstants::magicNumber)
  15913. {
  15914. loadedOk = true;
  15915. BufferedInputStream in (fileStream.release(), 2048, true);
  15916. int numValues = in.readInt();
  15917. while (--numValues >= 0 && ! in.isExhausted())
  15918. {
  15919. const String key (in.readString());
  15920. const String value (in.readString());
  15921. jassert (key.isNotEmpty());
  15922. if (key.isNotEmpty())
  15923. getAllProperties().set (key, value);
  15924. }
  15925. }
  15926. else
  15927. {
  15928. // Not a binary props file - let's see if it's XML..
  15929. fileStream = 0;
  15930. XmlDocument parser (f);
  15931. ScopedPointer<XmlElement> doc (parser.getDocumentElement (true));
  15932. if (doc != 0 && doc->hasTagName (PropertyFileConstants::fileTag))
  15933. {
  15934. doc = parser.getDocumentElement();
  15935. if (doc != 0)
  15936. {
  15937. loadedOk = true;
  15938. forEachXmlChildElementWithTagName (*doc, e, PropertyFileConstants::valueTag)
  15939. {
  15940. const String name (e->getStringAttribute (PropertyFileConstants::nameAttribute));
  15941. if (name.isNotEmpty())
  15942. {
  15943. getAllProperties().set (name,
  15944. e->getFirstChildElement() != 0
  15945. ? e->getFirstChildElement()->createDocument (String::empty, true)
  15946. : e->getStringAttribute (PropertyFileConstants::valueAttribute));
  15947. }
  15948. }
  15949. }
  15950. else
  15951. {
  15952. // must be a pretty broken XML file we're trying to parse here,
  15953. // or a sign that this object needs an InterProcessLock,
  15954. // or just a failure reading the file. This last reason is why
  15955. // we don't jassertfalse here.
  15956. }
  15957. }
  15958. }
  15959. }
  15960. else
  15961. {
  15962. loadedOk = ! f.exists();
  15963. }
  15964. }
  15965. PropertiesFile::~PropertiesFile()
  15966. {
  15967. if (! saveIfNeeded())
  15968. jassertfalse;
  15969. }
  15970. InterProcessLock::ScopedLockType* PropertiesFile::createProcessLock() const
  15971. {
  15972. return processLock != 0 ? new InterProcessLock::ScopedLockType (*processLock) : 0;
  15973. }
  15974. bool PropertiesFile::saveIfNeeded()
  15975. {
  15976. const ScopedLock sl (getLock());
  15977. return (! needsWriting) || save();
  15978. }
  15979. bool PropertiesFile::needsToBeSaved() const
  15980. {
  15981. const ScopedLock sl (getLock());
  15982. return needsWriting;
  15983. }
  15984. void PropertiesFile::setNeedsToBeSaved (const bool needsToBeSaved_)
  15985. {
  15986. const ScopedLock sl (getLock());
  15987. needsWriting = needsToBeSaved_;
  15988. }
  15989. bool PropertiesFile::save()
  15990. {
  15991. const ScopedLock sl (getLock());
  15992. stopTimer();
  15993. if (file == File::nonexistent
  15994. || file.isDirectory()
  15995. || ! file.getParentDirectory().createDirectory())
  15996. return false;
  15997. if ((options & storeAsXML) != 0)
  15998. {
  15999. XmlElement doc (PropertyFileConstants::fileTag);
  16000. for (int i = 0; i < getAllProperties().size(); ++i)
  16001. {
  16002. XmlElement* const e = doc.createNewChildElement (PropertyFileConstants::valueTag);
  16003. e->setAttribute (PropertyFileConstants::nameAttribute, getAllProperties().getAllKeys() [i]);
  16004. // if the value seems to contain xml, store it as such..
  16005. XmlDocument xmlContent (getAllProperties().getAllValues() [i]);
  16006. XmlElement* const childElement = xmlContent.getDocumentElement();
  16007. if (childElement != 0)
  16008. e->addChildElement (childElement);
  16009. else
  16010. e->setAttribute (PropertyFileConstants::valueAttribute,
  16011. getAllProperties().getAllValues() [i]);
  16012. }
  16013. ProcessScopedLock pl (createProcessLock());
  16014. if (pl != 0 && ! pl->isLocked())
  16015. return false; // locking failure..
  16016. if (doc.writeToFile (file, String::empty))
  16017. {
  16018. needsWriting = false;
  16019. return true;
  16020. }
  16021. }
  16022. else
  16023. {
  16024. ProcessScopedLock pl (createProcessLock());
  16025. if (pl != 0 && ! pl->isLocked())
  16026. return false; // locking failure..
  16027. TemporaryFile tempFile (file);
  16028. ScopedPointer <OutputStream> out (tempFile.getFile().createOutputStream());
  16029. if (out != 0)
  16030. {
  16031. if ((options & storeAsCompressedBinary) != 0)
  16032. {
  16033. out->writeInt (PropertyFileConstants::magicNumberCompressed);
  16034. out->flush();
  16035. out = new GZIPCompressorOutputStream (out.release(), 9, true);
  16036. }
  16037. else
  16038. {
  16039. // have you set up the storage option flags correctly?
  16040. jassert ((options & storeAsBinary) != 0);
  16041. out->writeInt (PropertyFileConstants::magicNumber);
  16042. }
  16043. const int numProperties = getAllProperties().size();
  16044. out->writeInt (numProperties);
  16045. for (int i = 0; i < numProperties; ++i)
  16046. {
  16047. out->writeString (getAllProperties().getAllKeys() [i]);
  16048. out->writeString (getAllProperties().getAllValues() [i]);
  16049. }
  16050. out = 0;
  16051. if (tempFile.overwriteTargetFileWithTemporary())
  16052. {
  16053. needsWriting = false;
  16054. return true;
  16055. }
  16056. }
  16057. }
  16058. return false;
  16059. }
  16060. void PropertiesFile::timerCallback()
  16061. {
  16062. saveIfNeeded();
  16063. }
  16064. void PropertiesFile::propertyChanged()
  16065. {
  16066. sendChangeMessage (this);
  16067. needsWriting = true;
  16068. if (timerInterval > 0)
  16069. startTimer (timerInterval);
  16070. else if (timerInterval == 0)
  16071. saveIfNeeded();
  16072. }
  16073. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  16074. const String& fileNameSuffix,
  16075. const String& folderName,
  16076. const bool commonToAllUsers)
  16077. {
  16078. // mustn't have illegal characters in this name..
  16079. jassert (applicationName == File::createLegalFileName (applicationName));
  16080. #if JUCE_MAC || JUCE_IOS
  16081. File dir (commonToAllUsers ? "/Library/Preferences"
  16082. : "~/Library/Preferences");
  16083. if (folderName.isNotEmpty())
  16084. dir = dir.getChildFile (folderName);
  16085. #endif
  16086. #ifdef JUCE_LINUX
  16087. const File dir ((commonToAllUsers ? "/var/" : "~/")
  16088. + (folderName.isNotEmpty() ? folderName
  16089. : ("." + applicationName)));
  16090. #endif
  16091. #if JUCE_WINDOWS
  16092. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  16093. : File::userApplicationDataDirectory));
  16094. if (dir == File::nonexistent)
  16095. return File::nonexistent;
  16096. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  16097. : applicationName);
  16098. #endif
  16099. return dir.getChildFile (applicationName)
  16100. .withFileExtension (fileNameSuffix);
  16101. }
  16102. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  16103. const String& fileNameSuffix,
  16104. const String& folderName,
  16105. const bool commonToAllUsers,
  16106. const int millisecondsBeforeSaving,
  16107. const int propertiesFileOptions,
  16108. InterProcessLock* processLock_)
  16109. {
  16110. const File file (getDefaultAppSettingsFile (applicationName,
  16111. fileNameSuffix,
  16112. folderName,
  16113. commonToAllUsers));
  16114. jassert (file != File::nonexistent);
  16115. if (file == File::nonexistent)
  16116. return 0;
  16117. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions,processLock_);
  16118. }
  16119. END_JUCE_NAMESPACE
  16120. /*** End of inlined file: juce_PropertiesFile.cpp ***/
  16121. /*** Start of inlined file: juce_FileBasedDocument.cpp ***/
  16122. BEGIN_JUCE_NAMESPACE
  16123. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  16124. const String& fileWildcard_,
  16125. const String& openFileDialogTitle_,
  16126. const String& saveFileDialogTitle_)
  16127. : changedSinceSave (false),
  16128. fileExtension (fileExtension_),
  16129. fileWildcard (fileWildcard_),
  16130. openFileDialogTitle (openFileDialogTitle_),
  16131. saveFileDialogTitle (saveFileDialogTitle_)
  16132. {
  16133. }
  16134. FileBasedDocument::~FileBasedDocument()
  16135. {
  16136. }
  16137. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  16138. {
  16139. if (changedSinceSave != hasChanged)
  16140. {
  16141. changedSinceSave = hasChanged;
  16142. sendChangeMessage (this);
  16143. }
  16144. }
  16145. void FileBasedDocument::changed()
  16146. {
  16147. changedSinceSave = true;
  16148. sendChangeMessage (this);
  16149. }
  16150. void FileBasedDocument::setFile (const File& newFile)
  16151. {
  16152. if (documentFile != newFile)
  16153. {
  16154. documentFile = newFile;
  16155. changed();
  16156. }
  16157. }
  16158. bool FileBasedDocument::loadFrom (const File& newFile,
  16159. const bool showMessageOnFailure)
  16160. {
  16161. MouseCursor::showWaitCursor();
  16162. const File oldFile (documentFile);
  16163. documentFile = newFile;
  16164. String error;
  16165. if (newFile.existsAsFile())
  16166. {
  16167. error = loadDocument (newFile);
  16168. if (error.isEmpty())
  16169. {
  16170. setChangedFlag (false);
  16171. MouseCursor::hideWaitCursor();
  16172. setLastDocumentOpened (newFile);
  16173. return true;
  16174. }
  16175. }
  16176. else
  16177. {
  16178. error = "The file doesn't exist";
  16179. }
  16180. documentFile = oldFile;
  16181. MouseCursor::hideWaitCursor();
  16182. if (showMessageOnFailure)
  16183. {
  16184. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  16185. TRANS("Failed to open file..."),
  16186. TRANS("There was an error while trying to load the file:\n\n")
  16187. + newFile.getFullPathName()
  16188. + "\n\n"
  16189. + error);
  16190. }
  16191. return false;
  16192. }
  16193. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  16194. {
  16195. FileChooser fc (openFileDialogTitle,
  16196. getLastDocumentOpened(),
  16197. fileWildcard);
  16198. if (fc.browseForFileToOpen())
  16199. return loadFrom (fc.getResult(), showMessageOnFailure);
  16200. return false;
  16201. }
  16202. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  16203. const bool showMessageOnFailure)
  16204. {
  16205. return saveAs (documentFile,
  16206. false,
  16207. askUserForFileIfNotSpecified,
  16208. showMessageOnFailure);
  16209. }
  16210. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  16211. const bool warnAboutOverwritingExistingFiles,
  16212. const bool askUserForFileIfNotSpecified,
  16213. const bool showMessageOnFailure)
  16214. {
  16215. if (newFile == File::nonexistent)
  16216. {
  16217. if (askUserForFileIfNotSpecified)
  16218. {
  16219. return saveAsInteractive (true);
  16220. }
  16221. else
  16222. {
  16223. // can't save to an unspecified file
  16224. jassertfalse;
  16225. return failedToWriteToFile;
  16226. }
  16227. }
  16228. if (warnAboutOverwritingExistingFiles && newFile.exists())
  16229. {
  16230. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  16231. TRANS("File already exists"),
  16232. TRANS("There's already a file called:\n\n")
  16233. + newFile.getFullPathName()
  16234. + TRANS("\n\nAre you sure you want to overwrite it?"),
  16235. TRANS("overwrite"),
  16236. TRANS("cancel")))
  16237. {
  16238. return userCancelledSave;
  16239. }
  16240. }
  16241. MouseCursor::showWaitCursor();
  16242. const File oldFile (documentFile);
  16243. documentFile = newFile;
  16244. String error (saveDocument (newFile));
  16245. if (error.isEmpty())
  16246. {
  16247. setChangedFlag (false);
  16248. MouseCursor::hideWaitCursor();
  16249. return savedOk;
  16250. }
  16251. documentFile = oldFile;
  16252. MouseCursor::hideWaitCursor();
  16253. if (showMessageOnFailure)
  16254. {
  16255. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  16256. TRANS("Error writing to file..."),
  16257. TRANS("An error occurred while trying to save \"")
  16258. + getDocumentTitle()
  16259. + TRANS("\" to the file:\n\n")
  16260. + newFile.getFullPathName()
  16261. + "\n\n"
  16262. + error);
  16263. }
  16264. return failedToWriteToFile;
  16265. }
  16266. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  16267. {
  16268. if (! hasChangedSinceSaved())
  16269. return savedOk;
  16270. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  16271. TRANS("Closing document..."),
  16272. TRANS("Do you want to save the changes to \"")
  16273. + getDocumentTitle() + "\"?",
  16274. TRANS("save"),
  16275. TRANS("discard changes"),
  16276. TRANS("cancel"));
  16277. if (r == 1)
  16278. {
  16279. // save changes
  16280. return save (true, true);
  16281. }
  16282. else if (r == 2)
  16283. {
  16284. // discard changes
  16285. return savedOk;
  16286. }
  16287. return userCancelledSave;
  16288. }
  16289. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  16290. {
  16291. File f;
  16292. if (documentFile.existsAsFile())
  16293. f = documentFile;
  16294. else
  16295. f = getLastDocumentOpened();
  16296. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  16297. if (legalFilename.isEmpty())
  16298. legalFilename = "unnamed";
  16299. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  16300. f = f.getSiblingFile (legalFilename);
  16301. else
  16302. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  16303. f = f.withFileExtension (fileExtension)
  16304. .getNonexistentSibling (true);
  16305. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  16306. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  16307. {
  16308. File chosen (fc.getResult());
  16309. if (chosen.getFileExtension().isEmpty())
  16310. {
  16311. chosen = chosen.withFileExtension (fileExtension);
  16312. if (chosen.exists())
  16313. {
  16314. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  16315. TRANS("File already exists"),
  16316. TRANS("There's already a file called:")
  16317. + "\n\n" + chosen.getFullPathName()
  16318. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  16319. TRANS("overwrite"),
  16320. TRANS("cancel")))
  16321. {
  16322. return userCancelledSave;
  16323. }
  16324. }
  16325. }
  16326. setLastDocumentOpened (chosen);
  16327. return saveAs (chosen, false, false, true);
  16328. }
  16329. return userCancelledSave;
  16330. }
  16331. END_JUCE_NAMESPACE
  16332. /*** End of inlined file: juce_FileBasedDocument.cpp ***/
  16333. /*** Start of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  16334. BEGIN_JUCE_NAMESPACE
  16335. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  16336. : maxNumberOfItems (10)
  16337. {
  16338. }
  16339. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  16340. {
  16341. }
  16342. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  16343. {
  16344. maxNumberOfItems = jmax (1, newMaxNumber);
  16345. while (getNumFiles() > maxNumberOfItems)
  16346. files.remove (getNumFiles() - 1);
  16347. }
  16348. int RecentlyOpenedFilesList::getNumFiles() const
  16349. {
  16350. return files.size();
  16351. }
  16352. const File RecentlyOpenedFilesList::getFile (const int index) const
  16353. {
  16354. return File (files [index]);
  16355. }
  16356. void RecentlyOpenedFilesList::clear()
  16357. {
  16358. files.clear();
  16359. }
  16360. void RecentlyOpenedFilesList::addFile (const File& file)
  16361. {
  16362. const String path (file.getFullPathName());
  16363. files.removeString (path, true);
  16364. files.insert (0, path);
  16365. setMaxNumberOfItems (maxNumberOfItems);
  16366. }
  16367. void RecentlyOpenedFilesList::removeNonExistentFiles()
  16368. {
  16369. for (int i = getNumFiles(); --i >= 0;)
  16370. if (! getFile(i).exists())
  16371. files.remove (i);
  16372. }
  16373. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  16374. const int baseItemId,
  16375. const bool showFullPaths,
  16376. const bool dontAddNonExistentFiles,
  16377. const File** filesToAvoid)
  16378. {
  16379. int num = 0;
  16380. for (int i = 0; i < getNumFiles(); ++i)
  16381. {
  16382. const File f (getFile(i));
  16383. if ((! dontAddNonExistentFiles) || f.exists())
  16384. {
  16385. bool needsAvoiding = false;
  16386. if (filesToAvoid != 0)
  16387. {
  16388. const File** avoid = filesToAvoid;
  16389. while (*avoid != 0)
  16390. {
  16391. if (f == **avoid)
  16392. {
  16393. needsAvoiding = true;
  16394. break;
  16395. }
  16396. ++avoid;
  16397. }
  16398. }
  16399. if (! needsAvoiding)
  16400. {
  16401. menuToAddTo.addItem (baseItemId + i,
  16402. showFullPaths ? f.getFullPathName()
  16403. : f.getFileName());
  16404. ++num;
  16405. }
  16406. }
  16407. }
  16408. return num;
  16409. }
  16410. const String RecentlyOpenedFilesList::toString() const
  16411. {
  16412. return files.joinIntoString ("\n");
  16413. }
  16414. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  16415. {
  16416. clear();
  16417. files.addLines (stringifiedVersion);
  16418. setMaxNumberOfItems (maxNumberOfItems);
  16419. }
  16420. END_JUCE_NAMESPACE
  16421. /*** End of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  16422. /*** Start of inlined file: juce_UndoManager.cpp ***/
  16423. BEGIN_JUCE_NAMESPACE
  16424. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  16425. const int minimumTransactions)
  16426. : totalUnitsStored (0),
  16427. nextIndex (0),
  16428. newTransaction (true),
  16429. reentrancyCheck (false)
  16430. {
  16431. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  16432. minimumTransactions);
  16433. }
  16434. UndoManager::~UndoManager()
  16435. {
  16436. clearUndoHistory();
  16437. }
  16438. void UndoManager::clearUndoHistory()
  16439. {
  16440. transactions.clear();
  16441. transactionNames.clear();
  16442. totalUnitsStored = 0;
  16443. nextIndex = 0;
  16444. sendChangeMessage (this);
  16445. }
  16446. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  16447. {
  16448. return totalUnitsStored;
  16449. }
  16450. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  16451. const int minimumTransactions)
  16452. {
  16453. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  16454. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  16455. }
  16456. bool UndoManager::perform (UndoableAction* const command_, const String& actionName)
  16457. {
  16458. if (command_ != 0)
  16459. {
  16460. ScopedPointer<UndoableAction> command (command_);
  16461. if (actionName.isNotEmpty())
  16462. currentTransactionName = actionName;
  16463. if (reentrancyCheck)
  16464. {
  16465. jassertfalse; // don't call perform() recursively from the UndoableAction::perform() or
  16466. // undo() methods, or else these actions won't actually get done.
  16467. return false;
  16468. }
  16469. else if (command->perform())
  16470. {
  16471. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  16472. if (commandSet != 0 && ! newTransaction)
  16473. {
  16474. UndoableAction* lastAction = commandSet->getLast();
  16475. if (lastAction != 0)
  16476. {
  16477. UndoableAction* coalescedAction = lastAction->createCoalescedAction (command);
  16478. if (coalescedAction != 0)
  16479. {
  16480. command = coalescedAction;
  16481. totalUnitsStored -= lastAction->getSizeInUnits();
  16482. commandSet->removeLast();
  16483. }
  16484. }
  16485. }
  16486. else
  16487. {
  16488. commandSet = new OwnedArray<UndoableAction>();
  16489. transactions.insert (nextIndex, commandSet);
  16490. transactionNames.insert (nextIndex, currentTransactionName);
  16491. ++nextIndex;
  16492. }
  16493. totalUnitsStored += command->getSizeInUnits();
  16494. commandSet->add (command.release());
  16495. newTransaction = false;
  16496. while (nextIndex < transactions.size())
  16497. {
  16498. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  16499. for (int i = lastSet->size(); --i >= 0;)
  16500. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  16501. transactions.removeLast();
  16502. transactionNames.remove (transactionNames.size() - 1);
  16503. }
  16504. while (nextIndex > 0
  16505. && totalUnitsStored > maxNumUnitsToKeep
  16506. && transactions.size() > minimumTransactionsToKeep)
  16507. {
  16508. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  16509. for (int i = firstSet->size(); --i >= 0;)
  16510. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  16511. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  16512. transactions.remove (0);
  16513. transactionNames.remove (0);
  16514. --nextIndex;
  16515. }
  16516. sendChangeMessage (this);
  16517. return true;
  16518. }
  16519. }
  16520. return false;
  16521. }
  16522. void UndoManager::beginNewTransaction (const String& actionName)
  16523. {
  16524. newTransaction = true;
  16525. currentTransactionName = actionName;
  16526. }
  16527. void UndoManager::setCurrentTransactionName (const String& newName)
  16528. {
  16529. currentTransactionName = newName;
  16530. }
  16531. bool UndoManager::canUndo() const
  16532. {
  16533. return nextIndex > 0;
  16534. }
  16535. bool UndoManager::canRedo() const
  16536. {
  16537. return nextIndex < transactions.size();
  16538. }
  16539. const String UndoManager::getUndoDescription() const
  16540. {
  16541. return transactionNames [nextIndex - 1];
  16542. }
  16543. const String UndoManager::getRedoDescription() const
  16544. {
  16545. return transactionNames [nextIndex];
  16546. }
  16547. bool UndoManager::undo()
  16548. {
  16549. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16550. if (commandSet == 0)
  16551. return false;
  16552. reentrancyCheck = true;
  16553. bool failed = false;
  16554. for (int i = commandSet->size(); --i >= 0;)
  16555. {
  16556. if (! commandSet->getUnchecked(i)->undo())
  16557. {
  16558. jassertfalse;
  16559. failed = true;
  16560. break;
  16561. }
  16562. }
  16563. reentrancyCheck = false;
  16564. if (failed)
  16565. clearUndoHistory();
  16566. else
  16567. --nextIndex;
  16568. beginNewTransaction();
  16569. sendChangeMessage (this);
  16570. return true;
  16571. }
  16572. bool UndoManager::redo()
  16573. {
  16574. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  16575. if (commandSet == 0)
  16576. return false;
  16577. reentrancyCheck = true;
  16578. bool failed = false;
  16579. for (int i = 0; i < commandSet->size(); ++i)
  16580. {
  16581. if (! commandSet->getUnchecked(i)->perform())
  16582. {
  16583. jassertfalse;
  16584. failed = true;
  16585. break;
  16586. }
  16587. }
  16588. reentrancyCheck = false;
  16589. if (failed)
  16590. clearUndoHistory();
  16591. else
  16592. ++nextIndex;
  16593. beginNewTransaction();
  16594. sendChangeMessage (this);
  16595. return true;
  16596. }
  16597. bool UndoManager::undoCurrentTransactionOnly()
  16598. {
  16599. return newTransaction ? false : undo();
  16600. }
  16601. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  16602. {
  16603. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16604. if (commandSet != 0 && ! newTransaction)
  16605. {
  16606. for (int i = 0; i < commandSet->size(); ++i)
  16607. actionsFound.add (commandSet->getUnchecked(i));
  16608. }
  16609. }
  16610. int UndoManager::getNumActionsInCurrentTransaction() const
  16611. {
  16612. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16613. if (commandSet != 0 && ! newTransaction)
  16614. return commandSet->size();
  16615. return 0;
  16616. }
  16617. END_JUCE_NAMESPACE
  16618. /*** End of inlined file: juce_UndoManager.cpp ***/
  16619. /*** Start of inlined file: juce_AiffAudioFormat.cpp ***/
  16620. BEGIN_JUCE_NAMESPACE
  16621. static const char* const aiffFormatName = "AIFF file";
  16622. static const char* const aiffExtensions[] = { ".aiff", ".aif", 0 };
  16623. class AiffAudioFormatReader : public AudioFormatReader
  16624. {
  16625. public:
  16626. int bytesPerFrame;
  16627. int64 dataChunkStart;
  16628. bool littleEndian;
  16629. AiffAudioFormatReader (InputStream* in)
  16630. : AudioFormatReader (in, TRANS (aiffFormatName))
  16631. {
  16632. if (input->readInt() == chunkName ("FORM"))
  16633. {
  16634. const int len = input->readIntBigEndian();
  16635. const int64 end = input->getPosition() + len;
  16636. const int nextType = input->readInt();
  16637. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  16638. {
  16639. bool hasGotVer = false;
  16640. bool hasGotData = false;
  16641. bool hasGotType = false;
  16642. while (input->getPosition() < end)
  16643. {
  16644. const int type = input->readInt();
  16645. const uint32 length = (uint32) input->readIntBigEndian();
  16646. const int64 chunkEnd = input->getPosition() + length;
  16647. if (type == chunkName ("FVER"))
  16648. {
  16649. hasGotVer = true;
  16650. const int ver = input->readIntBigEndian();
  16651. if (ver != 0 && ver != (int) 0xa2805140)
  16652. break;
  16653. }
  16654. else if (type == chunkName ("COMM"))
  16655. {
  16656. hasGotType = true;
  16657. numChannels = (unsigned int) input->readShortBigEndian();
  16658. lengthInSamples = input->readIntBigEndian();
  16659. bitsPerSample = input->readShortBigEndian();
  16660. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  16661. unsigned char sampleRateBytes[10];
  16662. input->read (sampleRateBytes, 10);
  16663. const int byte0 = sampleRateBytes[0];
  16664. if ((byte0 & 0x80) != 0
  16665. || byte0 <= 0x3F || byte0 > 0x40
  16666. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  16667. break;
  16668. unsigned int sampRate = ByteOrder::bigEndianInt (sampleRateBytes + 2);
  16669. sampRate >>= (16414 - ByteOrder::bigEndianShort (sampleRateBytes));
  16670. sampleRate = (int) sampRate;
  16671. if (length <= 18)
  16672. {
  16673. // some types don't have a chunk large enough to include a compression
  16674. // type, so assume it's just big-endian pcm
  16675. littleEndian = false;
  16676. }
  16677. else
  16678. {
  16679. const int compType = input->readInt();
  16680. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  16681. {
  16682. littleEndian = false;
  16683. }
  16684. else if (compType == chunkName ("sowt"))
  16685. {
  16686. littleEndian = true;
  16687. }
  16688. else
  16689. {
  16690. sampleRate = 0;
  16691. break;
  16692. }
  16693. }
  16694. }
  16695. else if (type == chunkName ("SSND"))
  16696. {
  16697. hasGotData = true;
  16698. const int offset = input->readIntBigEndian();
  16699. dataChunkStart = input->getPosition() + 4 + offset;
  16700. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  16701. }
  16702. else if ((hasGotVer && hasGotData && hasGotType)
  16703. || chunkEnd < input->getPosition()
  16704. || input->isExhausted())
  16705. {
  16706. break;
  16707. }
  16708. input->setPosition (chunkEnd);
  16709. }
  16710. }
  16711. }
  16712. }
  16713. ~AiffAudioFormatReader()
  16714. {
  16715. }
  16716. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16717. int64 startSampleInFile, int numSamples)
  16718. {
  16719. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  16720. if (samplesAvailable < numSamples)
  16721. {
  16722. for (int i = numDestChannels; --i >= 0;)
  16723. if (destSamples[i] != 0)
  16724. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  16725. numSamples = (int) samplesAvailable;
  16726. }
  16727. if (numSamples <= 0)
  16728. return true;
  16729. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  16730. while (numSamples > 0)
  16731. {
  16732. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  16733. char tempBuffer [tempBufSize];
  16734. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  16735. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  16736. if (bytesRead < numThisTime * bytesPerFrame)
  16737. {
  16738. jassert (bytesRead >= 0);
  16739. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  16740. }
  16741. jassert (! usesFloatingPointData); // (would need to add support for this if it's possible)
  16742. if (littleEndian)
  16743. {
  16744. switch (bitsPerSample)
  16745. {
  16746. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16747. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16748. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16749. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16750. default: jassertfalse; break;
  16751. }
  16752. }
  16753. else
  16754. {
  16755. switch (bitsPerSample)
  16756. {
  16757. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16758. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16759. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16760. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16761. default: jassertfalse; break;
  16762. }
  16763. }
  16764. startOffsetInDestBuffer += numThisTime;
  16765. numSamples -= numThisTime;
  16766. }
  16767. return true;
  16768. }
  16769. juce_UseDebuggingNewOperator
  16770. private:
  16771. AiffAudioFormatReader (const AiffAudioFormatReader&);
  16772. AiffAudioFormatReader& operator= (const AiffAudioFormatReader&);
  16773. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16774. };
  16775. class AiffAudioFormatWriter : public AudioFormatWriter
  16776. {
  16777. public:
  16778. AiffAudioFormatWriter (OutputStream* out, double sampleRate_, unsigned int numChans, int bits)
  16779. : AudioFormatWriter (out, TRANS (aiffFormatName), sampleRate_, numChans, bits),
  16780. lengthInSamples (0),
  16781. bytesWritten (0),
  16782. writeFailed (false)
  16783. {
  16784. headerPosition = out->getPosition();
  16785. writeHeader();
  16786. }
  16787. ~AiffAudioFormatWriter()
  16788. {
  16789. if ((bytesWritten & 1) != 0)
  16790. output->writeByte (0);
  16791. writeHeader();
  16792. }
  16793. bool write (const int** data, int numSamples)
  16794. {
  16795. jassert (data != 0 && *data != 0); // the input must contain at least one channel!
  16796. if (writeFailed)
  16797. return false;
  16798. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  16799. tempBlock.ensureSize (bytes, false);
  16800. switch (bitsPerSample)
  16801. {
  16802. case 8: WriteHelper<AudioData::Int8, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16803. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16804. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16805. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16806. default: jassertfalse; break;
  16807. }
  16808. if (bytesWritten + bytes >= (uint32) 0xfff00000
  16809. || ! output->write (tempBlock.getData(), bytes))
  16810. {
  16811. // failed to write to disk, so let's try writing the header.
  16812. // If it's just run out of disk space, then if it does manage
  16813. // to write the header, we'll still have a useable file..
  16814. writeHeader();
  16815. writeFailed = true;
  16816. return false;
  16817. }
  16818. else
  16819. {
  16820. bytesWritten += bytes;
  16821. lengthInSamples += numSamples;
  16822. return true;
  16823. }
  16824. }
  16825. juce_UseDebuggingNewOperator
  16826. private:
  16827. MemoryBlock tempBlock;
  16828. uint32 lengthInSamples, bytesWritten;
  16829. int64 headerPosition;
  16830. bool writeFailed;
  16831. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16832. AiffAudioFormatWriter (const AiffAudioFormatWriter&);
  16833. AiffAudioFormatWriter& operator= (const AiffAudioFormatWriter&);
  16834. void writeHeader()
  16835. {
  16836. const bool couldSeekOk = output->setPosition (headerPosition);
  16837. (void) couldSeekOk;
  16838. // if this fails, you've given it an output stream that can't seek! It needs
  16839. // to be able to seek back to write the header
  16840. jassert (couldSeekOk);
  16841. const int headerLen = 54;
  16842. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  16843. audioBytes += (audioBytes & 1);
  16844. output->writeInt (chunkName ("FORM"));
  16845. output->writeIntBigEndian (headerLen + audioBytes - 8);
  16846. output->writeInt (chunkName ("AIFF"));
  16847. output->writeInt (chunkName ("COMM"));
  16848. output->writeIntBigEndian (18);
  16849. output->writeShortBigEndian ((short) numChannels);
  16850. output->writeIntBigEndian (lengthInSamples);
  16851. output->writeShortBigEndian ((short) bitsPerSample);
  16852. uint8 sampleRateBytes[10];
  16853. zeromem (sampleRateBytes, 10);
  16854. if (sampleRate <= 1)
  16855. {
  16856. sampleRateBytes[0] = 0x3f;
  16857. sampleRateBytes[1] = 0xff;
  16858. sampleRateBytes[2] = 0x80;
  16859. }
  16860. else
  16861. {
  16862. int mask = 0x40000000;
  16863. sampleRateBytes[0] = 0x40;
  16864. if (sampleRate >= mask)
  16865. {
  16866. jassertfalse;
  16867. sampleRateBytes[1] = 0x1d;
  16868. }
  16869. else
  16870. {
  16871. int n = (int) sampleRate;
  16872. int i;
  16873. for (i = 0; i <= 32 ; ++i)
  16874. {
  16875. if ((n & mask) != 0)
  16876. break;
  16877. mask >>= 1;
  16878. }
  16879. n = n << (i + 1);
  16880. sampleRateBytes[1] = (uint8) (29 - i);
  16881. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  16882. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  16883. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  16884. sampleRateBytes[5] = (uint8) (n & 0xff);
  16885. }
  16886. }
  16887. output->write (sampleRateBytes, 10);
  16888. output->writeInt (chunkName ("SSND"));
  16889. output->writeIntBigEndian (audioBytes + 8);
  16890. output->writeInt (0);
  16891. output->writeInt (0);
  16892. jassert (output->getPosition() == headerLen);
  16893. }
  16894. };
  16895. AiffAudioFormat::AiffAudioFormat()
  16896. : AudioFormat (TRANS (aiffFormatName), StringArray (aiffExtensions))
  16897. {
  16898. }
  16899. AiffAudioFormat::~AiffAudioFormat()
  16900. {
  16901. }
  16902. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  16903. {
  16904. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  16905. return Array <int> (rates);
  16906. }
  16907. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  16908. {
  16909. const int depths[] = { 8, 16, 24, 0 };
  16910. return Array <int> (depths);
  16911. }
  16912. bool AiffAudioFormat::canDoStereo() { return true; }
  16913. bool AiffAudioFormat::canDoMono() { return true; }
  16914. #if JUCE_MAC
  16915. bool AiffAudioFormat::canHandleFile (const File& f)
  16916. {
  16917. if (AudioFormat::canHandleFile (f))
  16918. return true;
  16919. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  16920. return type == 'AIFF' || type == 'AIFC'
  16921. || type == 'aiff' || type == 'aifc';
  16922. }
  16923. #endif
  16924. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream, const bool deleteStreamIfOpeningFails)
  16925. {
  16926. ScopedPointer <AiffAudioFormatReader> w (new AiffAudioFormatReader (sourceStream));
  16927. if (w->sampleRate != 0)
  16928. return w.release();
  16929. if (! deleteStreamIfOpeningFails)
  16930. w->input = 0;
  16931. return 0;
  16932. }
  16933. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  16934. double sampleRate,
  16935. unsigned int numberOfChannels,
  16936. int bitsPerSample,
  16937. const StringPairArray& /*metadataValues*/,
  16938. int /*qualityOptionIndex*/)
  16939. {
  16940. if (getPossibleBitDepths().contains (bitsPerSample))
  16941. return new AiffAudioFormatWriter (out, sampleRate, numberOfChannels, bitsPerSample);
  16942. return 0;
  16943. }
  16944. END_JUCE_NAMESPACE
  16945. /*** End of inlined file: juce_AiffAudioFormat.cpp ***/
  16946. /*** Start of inlined file: juce_AudioFormat.cpp ***/
  16947. BEGIN_JUCE_NAMESPACE
  16948. AudioFormat::AudioFormat (const String& name, const StringArray& extensions)
  16949. : formatName (name),
  16950. fileExtensions (extensions)
  16951. {
  16952. }
  16953. AudioFormat::~AudioFormat()
  16954. {
  16955. }
  16956. bool AudioFormat::canHandleFile (const File& f)
  16957. {
  16958. for (int i = 0; i < fileExtensions.size(); ++i)
  16959. if (f.hasFileExtension (fileExtensions[i]))
  16960. return true;
  16961. return false;
  16962. }
  16963. const String& AudioFormat::getFormatName() const { return formatName; }
  16964. const StringArray& AudioFormat::getFileExtensions() const { return fileExtensions; }
  16965. bool AudioFormat::isCompressed() { return false; }
  16966. const StringArray AudioFormat::getQualityOptions() { return StringArray(); }
  16967. END_JUCE_NAMESPACE
  16968. /*** End of inlined file: juce_AudioFormat.cpp ***/
  16969. /*** Start of inlined file: juce_AudioFormatReader.cpp ***/
  16970. BEGIN_JUCE_NAMESPACE
  16971. AudioFormatReader::AudioFormatReader (InputStream* const in,
  16972. const String& formatName_)
  16973. : sampleRate (0),
  16974. bitsPerSample (0),
  16975. lengthInSamples (0),
  16976. numChannels (0),
  16977. usesFloatingPointData (false),
  16978. input (in),
  16979. formatName (formatName_)
  16980. {
  16981. }
  16982. AudioFormatReader::~AudioFormatReader()
  16983. {
  16984. delete input;
  16985. }
  16986. bool AudioFormatReader::read (int* const* destSamples,
  16987. int numDestChannels,
  16988. int64 startSampleInSource,
  16989. int numSamplesToRead,
  16990. const bool fillLeftoverChannelsWithCopies)
  16991. {
  16992. jassert (numDestChannels > 0); // you have to actually give this some channels to work with!
  16993. int startOffsetInDestBuffer = 0;
  16994. if (startSampleInSource < 0)
  16995. {
  16996. const int silence = (int) jmin (-startSampleInSource, (int64) numSamplesToRead);
  16997. for (int i = numDestChannels; --i >= 0;)
  16998. if (destSamples[i] != 0)
  16999. zeromem (destSamples[i], sizeof (int) * silence);
  17000. startOffsetInDestBuffer += silence;
  17001. numSamplesToRead -= silence;
  17002. startSampleInSource = 0;
  17003. }
  17004. if (numSamplesToRead <= 0)
  17005. return true;
  17006. if (! readSamples (const_cast<int**> (destSamples),
  17007. jmin ((int) numChannels, numDestChannels), startOffsetInDestBuffer,
  17008. startSampleInSource, numSamplesToRead))
  17009. return false;
  17010. if (numDestChannels > (int) numChannels)
  17011. {
  17012. if (fillLeftoverChannelsWithCopies)
  17013. {
  17014. int* lastFullChannel = destSamples[0];
  17015. for (int i = (int) numChannels; --i > 0;)
  17016. {
  17017. if (destSamples[i] != 0)
  17018. {
  17019. lastFullChannel = destSamples[i];
  17020. break;
  17021. }
  17022. }
  17023. if (lastFullChannel != 0)
  17024. for (int i = numChannels; i < numDestChannels; ++i)
  17025. if (destSamples[i] != 0)
  17026. memcpy (destSamples[i], lastFullChannel, sizeof (int) * numSamplesToRead);
  17027. }
  17028. else
  17029. {
  17030. for (int i = numChannels; i < numDestChannels; ++i)
  17031. if (destSamples[i] != 0)
  17032. zeromem (destSamples[i], sizeof (int) * numSamplesToRead);
  17033. }
  17034. }
  17035. return true;
  17036. }
  17037. static void findAudioBufferMaxMin (const float* const buffer, const int num, float& maxVal, float& minVal) throw()
  17038. {
  17039. float mn = buffer[0];
  17040. float mx = mn;
  17041. for (int i = 1; i < num; ++i)
  17042. {
  17043. const float s = buffer[i];
  17044. if (s > mx) mx = s;
  17045. if (s < mn) mn = s;
  17046. }
  17047. maxVal = mx;
  17048. minVal = mn;
  17049. }
  17050. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  17051. int64 numSamples,
  17052. float& lowestLeft, float& highestLeft,
  17053. float& lowestRight, float& highestRight)
  17054. {
  17055. if (numSamples <= 0)
  17056. {
  17057. lowestLeft = 0;
  17058. lowestRight = 0;
  17059. highestLeft = 0;
  17060. highestRight = 0;
  17061. return;
  17062. }
  17063. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  17064. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  17065. int* tempBuffer[3];
  17066. tempBuffer[0] = tempSpace.getData();
  17067. tempBuffer[1] = tempSpace.getData() + bufferSize;
  17068. tempBuffer[2] = 0;
  17069. if (usesFloatingPointData)
  17070. {
  17071. float lmin = 1.0e6f;
  17072. float lmax = -lmin;
  17073. float rmin = lmin;
  17074. float rmax = lmax;
  17075. while (numSamples > 0)
  17076. {
  17077. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  17078. read (tempBuffer, 2, startSampleInFile, numToDo, false);
  17079. numSamples -= numToDo;
  17080. startSampleInFile += numToDo;
  17081. float bufmin, bufmax;
  17082. findAudioBufferMaxMin (reinterpret_cast<float*> (tempBuffer[0]), numToDo, bufmax, bufmin);
  17083. lmin = jmin (lmin, bufmin);
  17084. lmax = jmax (lmax, bufmax);
  17085. if (numChannels > 1)
  17086. {
  17087. findAudioBufferMaxMin (reinterpret_cast<float*> (tempBuffer[1]), numToDo, bufmax, bufmin);
  17088. rmin = jmin (rmin, bufmin);
  17089. rmax = jmax (rmax, bufmax);
  17090. }
  17091. }
  17092. if (numChannels <= 1)
  17093. {
  17094. rmax = lmax;
  17095. rmin = lmin;
  17096. }
  17097. lowestLeft = lmin;
  17098. highestLeft = lmax;
  17099. lowestRight = rmin;
  17100. highestRight = rmax;
  17101. }
  17102. else
  17103. {
  17104. int lmax = std::numeric_limits<int>::min();
  17105. int lmin = std::numeric_limits<int>::max();
  17106. int rmax = std::numeric_limits<int>::min();
  17107. int rmin = std::numeric_limits<int>::max();
  17108. while (numSamples > 0)
  17109. {
  17110. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  17111. read (tempBuffer, 2, startSampleInFile, numToDo, false);
  17112. numSamples -= numToDo;
  17113. startSampleInFile += numToDo;
  17114. for (int j = numChannels; --j >= 0;)
  17115. {
  17116. int bufMax = std::numeric_limits<int>::min();
  17117. int bufMin = std::numeric_limits<int>::max();
  17118. const int* const b = tempBuffer[j];
  17119. for (int i = 0; i < numToDo; ++i)
  17120. {
  17121. const int samp = b[i];
  17122. if (samp < bufMin)
  17123. bufMin = samp;
  17124. if (samp > bufMax)
  17125. bufMax = samp;
  17126. }
  17127. if (j == 0)
  17128. {
  17129. lmax = jmax (lmax, bufMax);
  17130. lmin = jmin (lmin, bufMin);
  17131. }
  17132. else
  17133. {
  17134. rmax = jmax (rmax, bufMax);
  17135. rmin = jmin (rmin, bufMin);
  17136. }
  17137. }
  17138. }
  17139. if (numChannels <= 1)
  17140. {
  17141. rmax = lmax;
  17142. rmin = lmin;
  17143. }
  17144. lowestLeft = lmin / (float) std::numeric_limits<int>::max();
  17145. highestLeft = lmax / (float) std::numeric_limits<int>::max();
  17146. lowestRight = rmin / (float) std::numeric_limits<int>::max();
  17147. highestRight = rmax / (float) std::numeric_limits<int>::max();
  17148. }
  17149. }
  17150. int64 AudioFormatReader::searchForLevel (int64 startSample,
  17151. int64 numSamplesToSearch,
  17152. const double magnitudeRangeMinimum,
  17153. const double magnitudeRangeMaximum,
  17154. const int minimumConsecutiveSamples)
  17155. {
  17156. if (numSamplesToSearch == 0)
  17157. return -1;
  17158. const int bufferSize = 4096;
  17159. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  17160. int* tempBuffer[3];
  17161. tempBuffer[0] = tempSpace.getData();
  17162. tempBuffer[1] = tempSpace.getData() + bufferSize;
  17163. tempBuffer[2] = 0;
  17164. int consecutive = 0;
  17165. int64 firstMatchPos = -1;
  17166. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  17167. const double doubleMin = jlimit (0.0, (double) std::numeric_limits<int>::max(), magnitudeRangeMinimum * std::numeric_limits<int>::max());
  17168. const double doubleMax = jlimit (doubleMin, (double) std::numeric_limits<int>::max(), magnitudeRangeMaximum * std::numeric_limits<int>::max());
  17169. const int intMagnitudeRangeMinimum = roundToInt (doubleMin);
  17170. const int intMagnitudeRangeMaximum = roundToInt (doubleMax);
  17171. while (numSamplesToSearch != 0)
  17172. {
  17173. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  17174. int64 bufferStart = startSample;
  17175. if (numSamplesToSearch < 0)
  17176. bufferStart -= numThisTime;
  17177. if (bufferStart >= (int) lengthInSamples)
  17178. break;
  17179. read (tempBuffer, 2, bufferStart, numThisTime, false);
  17180. int num = numThisTime;
  17181. while (--num >= 0)
  17182. {
  17183. if (numSamplesToSearch < 0)
  17184. --startSample;
  17185. bool matches = false;
  17186. const int index = (int) (startSample - bufferStart);
  17187. if (usesFloatingPointData)
  17188. {
  17189. const float sample1 = std::abs (((float*) tempBuffer[0]) [index]);
  17190. if (sample1 >= magnitudeRangeMinimum
  17191. && sample1 <= magnitudeRangeMaximum)
  17192. {
  17193. matches = true;
  17194. }
  17195. else if (numChannels > 1)
  17196. {
  17197. const float sample2 = std::abs (((float*) tempBuffer[1]) [index]);
  17198. matches = (sample2 >= magnitudeRangeMinimum
  17199. && sample2 <= magnitudeRangeMaximum);
  17200. }
  17201. }
  17202. else
  17203. {
  17204. const int sample1 = abs (tempBuffer[0] [index]);
  17205. if (sample1 >= intMagnitudeRangeMinimum
  17206. && sample1 <= intMagnitudeRangeMaximum)
  17207. {
  17208. matches = true;
  17209. }
  17210. else if (numChannels > 1)
  17211. {
  17212. const int sample2 = abs (tempBuffer[1][index]);
  17213. matches = (sample2 >= intMagnitudeRangeMinimum
  17214. && sample2 <= intMagnitudeRangeMaximum);
  17215. }
  17216. }
  17217. if (matches)
  17218. {
  17219. if (firstMatchPos < 0)
  17220. firstMatchPos = startSample;
  17221. if (++consecutive >= minimumConsecutiveSamples)
  17222. {
  17223. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  17224. return -1;
  17225. return firstMatchPos;
  17226. }
  17227. }
  17228. else
  17229. {
  17230. consecutive = 0;
  17231. firstMatchPos = -1;
  17232. }
  17233. if (numSamplesToSearch > 0)
  17234. ++startSample;
  17235. }
  17236. if (numSamplesToSearch > 0)
  17237. numSamplesToSearch -= numThisTime;
  17238. else
  17239. numSamplesToSearch += numThisTime;
  17240. }
  17241. return -1;
  17242. }
  17243. END_JUCE_NAMESPACE
  17244. /*** End of inlined file: juce_AudioFormatReader.cpp ***/
  17245. /*** Start of inlined file: juce_AudioFormatWriter.cpp ***/
  17246. BEGIN_JUCE_NAMESPACE
  17247. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  17248. const String& formatName_,
  17249. const double rate,
  17250. const unsigned int numChannels_,
  17251. const unsigned int bitsPerSample_)
  17252. : sampleRate (rate),
  17253. numChannels (numChannels_),
  17254. bitsPerSample (bitsPerSample_),
  17255. usesFloatingPointData (false),
  17256. output (out),
  17257. formatName (formatName_)
  17258. {
  17259. }
  17260. AudioFormatWriter::~AudioFormatWriter()
  17261. {
  17262. delete output;
  17263. }
  17264. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  17265. int64 startSample,
  17266. int64 numSamplesToRead)
  17267. {
  17268. const int bufferSize = 16384;
  17269. AudioSampleBuffer tempBuffer (numChannels, bufferSize);
  17270. int* buffers [128];
  17271. zerostruct (buffers);
  17272. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  17273. buffers[i] = reinterpret_cast<int*> (tempBuffer.getSampleData (i, 0));
  17274. if (numSamplesToRead < 0)
  17275. numSamplesToRead = reader.lengthInSamples;
  17276. while (numSamplesToRead > 0)
  17277. {
  17278. const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);
  17279. if (! reader.read (buffers, numChannels, startSample, numToDo, false))
  17280. return false;
  17281. if (reader.usesFloatingPointData != isFloatingPoint())
  17282. {
  17283. int** bufferChan = buffers;
  17284. while (*bufferChan != 0)
  17285. {
  17286. int* b = *bufferChan++;
  17287. if (isFloatingPoint())
  17288. {
  17289. // int -> float
  17290. const double factor = 1.0 / std::numeric_limits<int>::max();
  17291. for (int i = 0; i < numToDo; ++i)
  17292. ((float*) b)[i] = (float) (factor * b[i]);
  17293. }
  17294. else
  17295. {
  17296. // float -> int
  17297. for (int i = 0; i < numToDo; ++i)
  17298. {
  17299. const double samp = *(const float*) b;
  17300. if (samp <= -1.0)
  17301. *b++ = std::numeric_limits<int>::min();
  17302. else if (samp >= 1.0)
  17303. *b++ = std::numeric_limits<int>::max();
  17304. else
  17305. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  17306. }
  17307. }
  17308. }
  17309. }
  17310. if (! write (const_cast<const int**> (buffers), numToDo))
  17311. return false;
  17312. numSamplesToRead -= numToDo;
  17313. startSample += numToDo;
  17314. }
  17315. return true;
  17316. }
  17317. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source, int numSamplesToRead, const int samplesPerBlock)
  17318. {
  17319. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  17320. while (numSamplesToRead > 0)
  17321. {
  17322. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  17323. AudioSourceChannelInfo info;
  17324. info.buffer = &tempBuffer;
  17325. info.startSample = 0;
  17326. info.numSamples = numToDo;
  17327. info.clearActiveBufferRegion();
  17328. source.getNextAudioBlock (info);
  17329. if (! writeFromAudioSampleBuffer (tempBuffer, 0, numToDo))
  17330. return false;
  17331. numSamplesToRead -= numToDo;
  17332. }
  17333. return true;
  17334. }
  17335. bool AudioFormatWriter::writeFromAudioSampleBuffer (const AudioSampleBuffer& source, int startSample, int numSamples)
  17336. {
  17337. jassert (startSample >= 0 && startSample + numSamples <= source.getNumSamples() && source.getNumChannels() > 0);
  17338. if (numSamples <= 0)
  17339. return true;
  17340. HeapBlock<int> tempBuffer;
  17341. HeapBlock<int*> chans (numChannels + 1);
  17342. chans [numChannels] = 0;
  17343. if (isFloatingPoint())
  17344. {
  17345. for (int i = numChannels; --i >= 0;)
  17346. chans[i] = reinterpret_cast<int*> (source.getSampleData (i, startSample));
  17347. }
  17348. else
  17349. {
  17350. tempBuffer.malloc (numSamples * numChannels);
  17351. for (unsigned int i = 0; i < numChannels; ++i)
  17352. {
  17353. typedef AudioData::Pointer <AudioData::Int32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestSampleType;
  17354. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceSampleType;
  17355. DestSampleType destData (chans[i] = tempBuffer + i * numSamples);
  17356. SourceSampleType sourceData (source.getSampleData (i, startSample));
  17357. destData.convertSamples (sourceData, numSamples);
  17358. }
  17359. }
  17360. return write ((const int**) chans.getData(), numSamples);
  17361. }
  17362. class AudioFormatWriter::ThreadedWriter::Buffer : public TimeSliceClient,
  17363. public AbstractFifo
  17364. {
  17365. public:
  17366. Buffer (TimeSliceThread& timeSliceThread_, AudioFormatWriter* writer_, int numChannels, int bufferSize)
  17367. : AbstractFifo (bufferSize),
  17368. buffer (numChannels, bufferSize),
  17369. timeSliceThread (timeSliceThread_),
  17370. writer (writer_), isRunning (true)
  17371. {
  17372. timeSliceThread.addTimeSliceClient (this);
  17373. }
  17374. ~Buffer()
  17375. {
  17376. isRunning = false;
  17377. timeSliceThread.removeTimeSliceClient (this);
  17378. while (useTimeSlice())
  17379. {}
  17380. }
  17381. bool write (const float** data, int numSamples)
  17382. {
  17383. if (numSamples <= 0 || ! isRunning)
  17384. return true;
  17385. jassert (timeSliceThread.isThreadRunning()); // you need to get your thread running before pumping data into this!
  17386. int start1, size1, start2, size2;
  17387. prepareToWrite (numSamples, start1, size1, start2, size2);
  17388. if (size1 + size2 < numSamples)
  17389. return false;
  17390. for (int i = buffer.getNumChannels(); --i >= 0;)
  17391. {
  17392. buffer.copyFrom (i, start1, data[i], size1);
  17393. buffer.copyFrom (i, start2, data[i] + size1, size2);
  17394. }
  17395. finishedWrite (size1 + size2);
  17396. timeSliceThread.notify();
  17397. return true;
  17398. }
  17399. bool useTimeSlice()
  17400. {
  17401. const int numToDo = getTotalSize() / 4;
  17402. int start1, size1, start2, size2;
  17403. prepareToRead (numToDo, start1, size1, start2, size2);
  17404. if (size1 <= 0)
  17405. return false;
  17406. writer->writeFromAudioSampleBuffer (buffer, start1, size1);
  17407. if (size2 > 0)
  17408. writer->writeFromAudioSampleBuffer (buffer, start2, size2);
  17409. finishedRead (size1 + size2);
  17410. return true;
  17411. }
  17412. private:
  17413. AudioSampleBuffer buffer;
  17414. TimeSliceThread& timeSliceThread;
  17415. ScopedPointer<AudioFormatWriter> writer;
  17416. volatile bool isRunning;
  17417. Buffer (const Buffer&);
  17418. Buffer& operator= (const Buffer&);
  17419. };
  17420. AudioFormatWriter::ThreadedWriter::ThreadedWriter (AudioFormatWriter* writer, TimeSliceThread& backgroundThread, int numSamplesToBuffer)
  17421. : buffer (new AudioFormatWriter::ThreadedWriter::Buffer (backgroundThread, writer, writer->numChannels, numSamplesToBuffer))
  17422. {
  17423. }
  17424. AudioFormatWriter::ThreadedWriter::~ThreadedWriter()
  17425. {
  17426. }
  17427. bool AudioFormatWriter::ThreadedWriter::write (const float** data, int numSamples)
  17428. {
  17429. return buffer->write (data, numSamples);
  17430. }
  17431. END_JUCE_NAMESPACE
  17432. /*** End of inlined file: juce_AudioFormatWriter.cpp ***/
  17433. /*** Start of inlined file: juce_AudioFormatManager.cpp ***/
  17434. BEGIN_JUCE_NAMESPACE
  17435. AudioFormatManager::AudioFormatManager()
  17436. : defaultFormatIndex (0)
  17437. {
  17438. }
  17439. AudioFormatManager::~AudioFormatManager()
  17440. {
  17441. clearFormats();
  17442. clearSingletonInstance();
  17443. }
  17444. juce_ImplementSingleton (AudioFormatManager);
  17445. void AudioFormatManager::registerFormat (AudioFormat* newFormat,
  17446. const bool makeThisTheDefaultFormat)
  17447. {
  17448. jassert (newFormat != 0);
  17449. if (newFormat != 0)
  17450. {
  17451. #if JUCE_DEBUG
  17452. for (int i = getNumKnownFormats(); --i >= 0;)
  17453. {
  17454. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  17455. {
  17456. jassertfalse; // trying to add the same format twice!
  17457. }
  17458. }
  17459. #endif
  17460. if (makeThisTheDefaultFormat)
  17461. defaultFormatIndex = getNumKnownFormats();
  17462. knownFormats.add (newFormat);
  17463. }
  17464. }
  17465. void AudioFormatManager::registerBasicFormats()
  17466. {
  17467. #if JUCE_MAC
  17468. registerFormat (new AiffAudioFormat(), true);
  17469. registerFormat (new WavAudioFormat(), false);
  17470. #else
  17471. registerFormat (new WavAudioFormat(), true);
  17472. registerFormat (new AiffAudioFormat(), false);
  17473. #endif
  17474. #if JUCE_USE_FLAC
  17475. registerFormat (new FlacAudioFormat(), false);
  17476. #endif
  17477. #if JUCE_USE_OGGVORBIS
  17478. registerFormat (new OggVorbisAudioFormat(), false);
  17479. #endif
  17480. }
  17481. void AudioFormatManager::clearFormats()
  17482. {
  17483. knownFormats.clear();
  17484. defaultFormatIndex = 0;
  17485. }
  17486. int AudioFormatManager::getNumKnownFormats() const
  17487. {
  17488. return knownFormats.size();
  17489. }
  17490. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  17491. {
  17492. return knownFormats [index];
  17493. }
  17494. AudioFormat* AudioFormatManager::getDefaultFormat() const
  17495. {
  17496. return getKnownFormat (defaultFormatIndex);
  17497. }
  17498. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  17499. {
  17500. String e (fileExtension);
  17501. if (! e.startsWithChar ('.'))
  17502. e = "." + e;
  17503. for (int i = 0; i < getNumKnownFormats(); ++i)
  17504. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  17505. return getKnownFormat(i);
  17506. return 0;
  17507. }
  17508. const String AudioFormatManager::getWildcardForAllFormats() const
  17509. {
  17510. StringArray allExtensions;
  17511. int i;
  17512. for (i = 0; i < getNumKnownFormats(); ++i)
  17513. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  17514. allExtensions.trim();
  17515. allExtensions.removeEmptyStrings();
  17516. String s;
  17517. for (i = 0; i < allExtensions.size(); ++i)
  17518. {
  17519. s << '*';
  17520. if (! allExtensions[i].startsWithChar ('.'))
  17521. s << '.';
  17522. s << allExtensions[i];
  17523. if (i < allExtensions.size() - 1)
  17524. s << ';';
  17525. }
  17526. return s;
  17527. }
  17528. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  17529. {
  17530. // you need to actually register some formats before the manager can
  17531. // use them to open a file!
  17532. jassert (getNumKnownFormats() > 0);
  17533. for (int i = 0; i < getNumKnownFormats(); ++i)
  17534. {
  17535. AudioFormat* const af = getKnownFormat(i);
  17536. if (af->canHandleFile (file))
  17537. {
  17538. InputStream* const in = file.createInputStream();
  17539. if (in != 0)
  17540. {
  17541. AudioFormatReader* const r = af->createReaderFor (in, true);
  17542. if (r != 0)
  17543. return r;
  17544. }
  17545. }
  17546. }
  17547. return 0;
  17548. }
  17549. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* audioFileStream)
  17550. {
  17551. // you need to actually register some formats before the manager can
  17552. // use them to open a file!
  17553. jassert (getNumKnownFormats() > 0);
  17554. ScopedPointer <InputStream> in (audioFileStream);
  17555. if (in != 0)
  17556. {
  17557. const int64 originalStreamPos = in->getPosition();
  17558. for (int i = 0; i < getNumKnownFormats(); ++i)
  17559. {
  17560. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  17561. if (r != 0)
  17562. {
  17563. in.release();
  17564. return r;
  17565. }
  17566. in->setPosition (originalStreamPos);
  17567. // the stream that is passed-in must be capable of being repositioned so
  17568. // that all the formats can have a go at opening it.
  17569. jassert (in->getPosition() == originalStreamPos);
  17570. }
  17571. }
  17572. return 0;
  17573. }
  17574. END_JUCE_NAMESPACE
  17575. /*** End of inlined file: juce_AudioFormatManager.cpp ***/
  17576. /*** Start of inlined file: juce_AudioSubsectionReader.cpp ***/
  17577. BEGIN_JUCE_NAMESPACE
  17578. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  17579. const int64 startSample_,
  17580. const int64 length_,
  17581. const bool deleteSourceWhenDeleted_)
  17582. : AudioFormatReader (0, source_->getFormatName()),
  17583. source (source_),
  17584. startSample (startSample_),
  17585. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  17586. {
  17587. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  17588. sampleRate = source->sampleRate;
  17589. bitsPerSample = source->bitsPerSample;
  17590. lengthInSamples = length;
  17591. numChannels = source->numChannels;
  17592. usesFloatingPointData = source->usesFloatingPointData;
  17593. }
  17594. AudioSubsectionReader::~AudioSubsectionReader()
  17595. {
  17596. if (deleteSourceWhenDeleted)
  17597. delete source;
  17598. }
  17599. bool AudioSubsectionReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17600. int64 startSampleInFile, int numSamples)
  17601. {
  17602. if (startSampleInFile + numSamples > length)
  17603. {
  17604. for (int i = numDestChannels; --i >= 0;)
  17605. if (destSamples[i] != 0)
  17606. zeromem (destSamples[i], sizeof (int) * numSamples);
  17607. numSamples = jmin (numSamples, (int) (length - startSampleInFile));
  17608. if (numSamples <= 0)
  17609. return true;
  17610. }
  17611. return source->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer,
  17612. startSampleInFile + startSample, numSamples);
  17613. }
  17614. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  17615. int64 numSamples,
  17616. float& lowestLeft,
  17617. float& highestLeft,
  17618. float& lowestRight,
  17619. float& highestRight)
  17620. {
  17621. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  17622. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  17623. source->readMaxLevels (startSampleInFile + startSample,
  17624. numSamples,
  17625. lowestLeft,
  17626. highestLeft,
  17627. lowestRight,
  17628. highestRight);
  17629. }
  17630. END_JUCE_NAMESPACE
  17631. /*** End of inlined file: juce_AudioSubsectionReader.cpp ***/
  17632. /*** Start of inlined file: juce_AudioThumbnail.cpp ***/
  17633. BEGIN_JUCE_NAMESPACE
  17634. AudioThumbnail::AudioThumbnail (const int orginalSamplesPerThumbnailSample_,
  17635. AudioFormatManager& formatManagerToUse_,
  17636. AudioThumbnailCache& cacheToUse)
  17637. : formatManagerToUse (formatManagerToUse_),
  17638. cache (cacheToUse),
  17639. orginalSamplesPerThumbnailSample (orginalSamplesPerThumbnailSample_),
  17640. timeBeforeDeletingReader (2000)
  17641. {
  17642. clear();
  17643. }
  17644. AudioThumbnail::~AudioThumbnail()
  17645. {
  17646. cache.removeThumbnail (this);
  17647. const ScopedLock sl (readerLock);
  17648. reader = 0;
  17649. }
  17650. AudioThumbnail::DataFormat* AudioThumbnail::getData() const throw()
  17651. {
  17652. jassert (data.getData() != 0);
  17653. return static_cast <DataFormat*> (data.getData());
  17654. }
  17655. void AudioThumbnail::setSource (InputSource* const newSource)
  17656. {
  17657. cache.removeThumbnail (this);
  17658. timerCallback(); // stops the timer and deletes the reader
  17659. source = newSource;
  17660. clear();
  17661. if (newSource != 0
  17662. && ! (cache.loadThumb (*this, newSource->hashCode())
  17663. && isFullyLoaded()))
  17664. {
  17665. {
  17666. const ScopedLock sl (readerLock);
  17667. reader = createReader();
  17668. }
  17669. if (reader != 0)
  17670. {
  17671. initialiseFromAudioFile (*reader);
  17672. cache.addThumbnail (this);
  17673. }
  17674. }
  17675. sendChangeMessage (this);
  17676. }
  17677. bool AudioThumbnail::useTimeSlice()
  17678. {
  17679. const ScopedLock sl (readerLock);
  17680. if (isFullyLoaded())
  17681. {
  17682. if (reader != 0)
  17683. startTimer (timeBeforeDeletingReader);
  17684. cache.removeThumbnail (this);
  17685. return false;
  17686. }
  17687. if (reader == 0)
  17688. reader = createReader();
  17689. if (reader != 0)
  17690. {
  17691. readNextBlockFromAudioFile (*reader);
  17692. stopTimer();
  17693. sendChangeMessage (this);
  17694. const bool justFinished = isFullyLoaded();
  17695. if (justFinished)
  17696. cache.storeThumb (*this, source->hashCode());
  17697. return ! justFinished;
  17698. }
  17699. return false;
  17700. }
  17701. AudioFormatReader* AudioThumbnail::createReader() const
  17702. {
  17703. if (source != 0)
  17704. {
  17705. InputStream* const audioFileStream = source->createInputStream();
  17706. if (audioFileStream != 0)
  17707. return formatManagerToUse.createReaderFor (audioFileStream);
  17708. }
  17709. return 0;
  17710. }
  17711. void AudioThumbnail::timerCallback()
  17712. {
  17713. stopTimer();
  17714. const ScopedLock sl (readerLock);
  17715. reader = 0;
  17716. }
  17717. void AudioThumbnail::clear()
  17718. {
  17719. data.setSize (sizeof (DataFormat) + 3);
  17720. DataFormat* const d = getData();
  17721. d->thumbnailMagic[0] = 'j';
  17722. d->thumbnailMagic[1] = 'a';
  17723. d->thumbnailMagic[2] = 't';
  17724. d->thumbnailMagic[3] = 'm';
  17725. d->samplesPerThumbSample = orginalSamplesPerThumbnailSample;
  17726. d->totalSamples = 0;
  17727. d->numFinishedSamples = 0;
  17728. d->numThumbnailSamples = 0;
  17729. d->numChannels = 0;
  17730. d->sampleRate = 0;
  17731. numSamplesCached = 0;
  17732. cacheNeedsRefilling = true;
  17733. }
  17734. void AudioThumbnail::loadFrom (InputStream& input)
  17735. {
  17736. const ScopedLock sl (readerLock);
  17737. data.setSize (0);
  17738. input.readIntoMemoryBlock (data);
  17739. DataFormat* const d = getData();
  17740. d->flipEndiannessIfBigEndian();
  17741. if (! (d->thumbnailMagic[0] == 'j'
  17742. && d->thumbnailMagic[1] == 'a'
  17743. && d->thumbnailMagic[2] == 't'
  17744. && d->thumbnailMagic[3] == 'm'))
  17745. {
  17746. clear();
  17747. }
  17748. numSamplesCached = 0;
  17749. cacheNeedsRefilling = true;
  17750. }
  17751. void AudioThumbnail::saveTo (OutputStream& output) const
  17752. {
  17753. const ScopedLock sl (readerLock);
  17754. DataFormat* const d = getData();
  17755. d->flipEndiannessIfBigEndian();
  17756. output.write (d, (int) data.getSize());
  17757. d->flipEndiannessIfBigEndian();
  17758. }
  17759. bool AudioThumbnail::initialiseFromAudioFile (AudioFormatReader& fileReader)
  17760. {
  17761. DataFormat* d = getData();
  17762. d->totalSamples = fileReader.lengthInSamples;
  17763. d->numChannels = jmin ((uint32) 2, fileReader.numChannels);
  17764. d->numFinishedSamples = 0;
  17765. d->sampleRate = roundToInt (fileReader.sampleRate);
  17766. d->numThumbnailSamples = (int) (d->totalSamples / d->samplesPerThumbSample) + 1;
  17767. data.setSize (sizeof (DataFormat) + 3 + d->numThumbnailSamples * d->numChannels * 2);
  17768. d = getData();
  17769. zeromem (d->data, d->numThumbnailSamples * d->numChannels * 2);
  17770. return d->totalSamples > 0;
  17771. }
  17772. bool AudioThumbnail::readNextBlockFromAudioFile (AudioFormatReader& fileReader)
  17773. {
  17774. DataFormat* const d = getData();
  17775. if (d->numFinishedSamples < d->totalSamples)
  17776. {
  17777. const int numToDo = (int) jmin ((int64) 65536, d->totalSamples - d->numFinishedSamples);
  17778. generateSection (fileReader,
  17779. d->numFinishedSamples,
  17780. numToDo);
  17781. d->numFinishedSamples += numToDo;
  17782. }
  17783. cacheNeedsRefilling = true;
  17784. return d->numFinishedSamples < d->totalSamples;
  17785. }
  17786. int AudioThumbnail::getNumChannels() const throw()
  17787. {
  17788. return getData()->numChannels;
  17789. }
  17790. double AudioThumbnail::getTotalLength() const throw()
  17791. {
  17792. const DataFormat* const d = getData();
  17793. if (d->sampleRate > 0)
  17794. return d->totalSamples / (double) d->sampleRate;
  17795. else
  17796. return 0.0;
  17797. }
  17798. void AudioThumbnail::generateSection (AudioFormatReader& fileReader,
  17799. int64 startSample,
  17800. int numSamples)
  17801. {
  17802. DataFormat* const d = getData();
  17803. const int firstDataPos = (int) (startSample / d->samplesPerThumbSample);
  17804. const int lastDataPos = (int) ((startSample + numSamples) / d->samplesPerThumbSample);
  17805. char* const l = getChannelData (0);
  17806. char* const r = getChannelData (1);
  17807. for (int i = firstDataPos; i < lastDataPos; ++i)
  17808. {
  17809. const int sourceStart = i * d->samplesPerThumbSample;
  17810. const int sourceEnd = sourceStart + d->samplesPerThumbSample;
  17811. float lowestLeft, highestLeft, lowestRight, highestRight;
  17812. fileReader.readMaxLevels (sourceStart,
  17813. sourceEnd - sourceStart,
  17814. lowestLeft,
  17815. highestLeft,
  17816. lowestRight,
  17817. highestRight);
  17818. int n = i * 2;
  17819. if (r != 0)
  17820. {
  17821. l [n] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  17822. r [n++] = (char) jlimit (-128.0f, 127.0f, lowestRight * 127.0f);
  17823. l [n] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  17824. r [n++] = (char) jlimit (-128.0f, 127.0f, highestRight * 127.0f);
  17825. }
  17826. else
  17827. {
  17828. l [n++] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  17829. l [n++] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  17830. }
  17831. }
  17832. }
  17833. char* AudioThumbnail::getChannelData (int channel) const
  17834. {
  17835. DataFormat* const d = getData();
  17836. if (channel >= 0 && channel < d->numChannels)
  17837. return d->data + (channel * 2 * d->numThumbnailSamples);
  17838. return 0;
  17839. }
  17840. bool AudioThumbnail::isFullyLoaded() const throw()
  17841. {
  17842. const DataFormat* const d = getData();
  17843. return d->numFinishedSamples >= d->totalSamples;
  17844. }
  17845. void AudioThumbnail::refillCache (const int numSamples,
  17846. double startTime,
  17847. const double timePerPixel)
  17848. {
  17849. const DataFormat* const d = getData();
  17850. if (numSamples <= 0
  17851. || timePerPixel <= 0.0
  17852. || d->sampleRate <= 0)
  17853. {
  17854. numSamplesCached = 0;
  17855. cacheNeedsRefilling = true;
  17856. return;
  17857. }
  17858. if (numSamples == numSamplesCached
  17859. && numChannelsCached == d->numChannels
  17860. && startTime == cachedStart
  17861. && timePerPixel == cachedTimePerPixel
  17862. && ! cacheNeedsRefilling)
  17863. {
  17864. return;
  17865. }
  17866. numSamplesCached = numSamples;
  17867. numChannelsCached = d->numChannels;
  17868. cachedStart = startTime;
  17869. cachedTimePerPixel = timePerPixel;
  17870. cachedLevels.ensureSize (2 * numChannelsCached * numSamples);
  17871. const bool needExtraDetail = (timePerPixel * d->sampleRate <= d->samplesPerThumbSample);
  17872. const ScopedLock sl (readerLock);
  17873. cacheNeedsRefilling = false;
  17874. if (needExtraDetail && reader == 0)
  17875. reader = createReader();
  17876. if (reader != 0 && timePerPixel * d->sampleRate <= d->samplesPerThumbSample)
  17877. {
  17878. startTimer (timeBeforeDeletingReader);
  17879. char* cacheData = static_cast <char*> (cachedLevels.getData());
  17880. int sample = roundToInt (startTime * d->sampleRate);
  17881. for (int i = numSamples; --i >= 0;)
  17882. {
  17883. const int nextSample = roundToInt ((startTime + timePerPixel) * d->sampleRate);
  17884. if (sample >= 0)
  17885. {
  17886. if (sample >= reader->lengthInSamples)
  17887. break;
  17888. float lmin, lmax, rmin, rmax;
  17889. reader->readMaxLevels (sample,
  17890. jmax (1, nextSample - sample),
  17891. lmin, lmax, rmin, rmax);
  17892. cacheData[0] = (char) jlimit (-128, 127, roundFloatToInt (lmin * 127.0f));
  17893. cacheData[1] = (char) jlimit (-128, 127, roundFloatToInt (lmax * 127.0f));
  17894. if (numChannelsCached > 1)
  17895. {
  17896. cacheData[2] = (char) jlimit (-128, 127, roundFloatToInt (rmin * 127.0f));
  17897. cacheData[3] = (char) jlimit (-128, 127, roundFloatToInt (rmax * 127.0f));
  17898. }
  17899. cacheData += 2 * numChannelsCached;
  17900. }
  17901. startTime += timePerPixel;
  17902. sample = nextSample;
  17903. }
  17904. }
  17905. else
  17906. {
  17907. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  17908. {
  17909. char* const channelData = getChannelData (channelNum);
  17910. char* cacheData = static_cast <char*> (cachedLevels.getData()) + channelNum * 2;
  17911. const double timeToThumbSampleFactor = d->sampleRate / (double) d->samplesPerThumbSample;
  17912. startTime = cachedStart;
  17913. int sample = roundToInt (startTime * timeToThumbSampleFactor);
  17914. const int numFinished = (int) (d->numFinishedSamples / d->samplesPerThumbSample);
  17915. for (int i = numSamples; --i >= 0;)
  17916. {
  17917. const int nextSample = roundToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  17918. if (sample >= 0 && channelData != 0)
  17919. {
  17920. char mx = -128;
  17921. char mn = 127;
  17922. while (sample <= nextSample)
  17923. {
  17924. if (sample >= numFinished)
  17925. break;
  17926. const int n = sample << 1;
  17927. const char sampMin = channelData [n];
  17928. const char sampMax = channelData [n + 1];
  17929. if (sampMin < mn)
  17930. mn = sampMin;
  17931. if (sampMax > mx)
  17932. mx = sampMax;
  17933. ++sample;
  17934. }
  17935. if (mn <= mx)
  17936. {
  17937. cacheData[0] = mn;
  17938. cacheData[1] = mx;
  17939. }
  17940. else
  17941. {
  17942. cacheData[0] = 1;
  17943. cacheData[1] = 0;
  17944. }
  17945. }
  17946. else
  17947. {
  17948. cacheData[0] = 1;
  17949. cacheData[1] = 0;
  17950. }
  17951. cacheData += numChannelsCached * 2;
  17952. startTime += timePerPixel;
  17953. sample = nextSample;
  17954. }
  17955. }
  17956. }
  17957. }
  17958. void AudioThumbnail::drawChannel (Graphics& g,
  17959. int x, int y, int w, int h,
  17960. double startTime,
  17961. double endTime,
  17962. int channelNum,
  17963. const float verticalZoomFactor)
  17964. {
  17965. refillCache (w, startTime, (endTime - startTime) / w);
  17966. if (numSamplesCached >= w
  17967. && channelNum >= 0
  17968. && channelNum < numChannelsCached)
  17969. {
  17970. const float topY = (float) y;
  17971. const float bottomY = topY + h;
  17972. const float midY = topY + h * 0.5f;
  17973. const float vscale = verticalZoomFactor * h / 256.0f;
  17974. const Rectangle<int> clip (g.getClipBounds());
  17975. const int skipLeft = jlimit (0, w, clip.getX() - x);
  17976. w -= skipLeft;
  17977. x += skipLeft;
  17978. const char* cacheData = static_cast <const char*> (cachedLevels.getData())
  17979. + (channelNum << 1)
  17980. + skipLeft * (numChannelsCached << 1);
  17981. while (--w >= 0)
  17982. {
  17983. const char mn = cacheData[0];
  17984. const char mx = cacheData[1];
  17985. cacheData += numChannelsCached << 1;
  17986. if (mn <= mx) // if the wrong way round, signifies that the sample's not yet known
  17987. g.drawVerticalLine (x, jmax (midY - mx * vscale - 0.3f, topY),
  17988. jmin (midY - mn * vscale + 0.3f, bottomY));
  17989. if (++x >= clip.getRight())
  17990. break;
  17991. }
  17992. }
  17993. }
  17994. void AudioThumbnail::DataFormat::flipEndiannessIfBigEndian() throw()
  17995. {
  17996. #if JUCE_BIG_ENDIAN
  17997. struct Flipper
  17998. {
  17999. static void flip (int32& n) { n = (int32) ByteOrder::swap ((uint32) n); }
  18000. static void flip (int64& n) { n = (int64) ByteOrder::swap ((uint64) n); }
  18001. };
  18002. Flipper::flip (samplesPerThumbSample);
  18003. Flipper::flip (totalSamples);
  18004. Flipper::flip (numFinishedSamples);
  18005. Flipper::flip (numThumbnailSamples);
  18006. Flipper::flip (numChannels);
  18007. Flipper::flip (sampleRate);
  18008. #endif
  18009. }
  18010. END_JUCE_NAMESPACE
  18011. /*** End of inlined file: juce_AudioThumbnail.cpp ***/
  18012. /*** Start of inlined file: juce_AudioThumbnailCache.cpp ***/
  18013. BEGIN_JUCE_NAMESPACE
  18014. struct ThumbnailCacheEntry
  18015. {
  18016. int64 hash;
  18017. uint32 lastUsed;
  18018. MemoryBlock data;
  18019. juce_UseDebuggingNewOperator
  18020. };
  18021. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  18022. : TimeSliceThread ("thumb cache"),
  18023. maxNumThumbsToStore (maxNumThumbsToStore_)
  18024. {
  18025. startThread (2);
  18026. }
  18027. AudioThumbnailCache::~AudioThumbnailCache()
  18028. {
  18029. }
  18030. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  18031. {
  18032. for (int i = thumbs.size(); --i >= 0;)
  18033. {
  18034. if (thumbs[i]->hash == hashCode)
  18035. {
  18036. MemoryInputStream in (thumbs[i]->data, false);
  18037. thumb.loadFrom (in);
  18038. thumbs[i]->lastUsed = Time::getMillisecondCounter();
  18039. return true;
  18040. }
  18041. }
  18042. return false;
  18043. }
  18044. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  18045. const int64 hashCode)
  18046. {
  18047. MemoryOutputStream out;
  18048. thumb.saveTo (out);
  18049. ThumbnailCacheEntry* te = 0;
  18050. for (int i = thumbs.size(); --i >= 0;)
  18051. {
  18052. if (thumbs[i]->hash == hashCode)
  18053. {
  18054. te = thumbs[i];
  18055. break;
  18056. }
  18057. }
  18058. if (te == 0)
  18059. {
  18060. te = new ThumbnailCacheEntry();
  18061. te->hash = hashCode;
  18062. if (thumbs.size() < maxNumThumbsToStore)
  18063. {
  18064. thumbs.add (te);
  18065. }
  18066. else
  18067. {
  18068. int oldest = 0;
  18069. unsigned int oldestTime = Time::getMillisecondCounter() + 1;
  18070. int i;
  18071. for (i = thumbs.size(); --i >= 0;)
  18072. if (thumbs[i]->lastUsed < oldestTime)
  18073. oldest = i;
  18074. thumbs.set (i, te);
  18075. }
  18076. }
  18077. te->lastUsed = Time::getMillisecondCounter();
  18078. te->data.setSize (0);
  18079. te->data.append (out.getData(), out.getDataSize());
  18080. }
  18081. void AudioThumbnailCache::clear()
  18082. {
  18083. thumbs.clear();
  18084. }
  18085. void AudioThumbnailCache::addThumbnail (AudioThumbnail* const thumb)
  18086. {
  18087. addTimeSliceClient (thumb);
  18088. }
  18089. void AudioThumbnailCache::removeThumbnail (AudioThumbnail* const thumb)
  18090. {
  18091. removeTimeSliceClient (thumb);
  18092. }
  18093. END_JUCE_NAMESPACE
  18094. /*** End of inlined file: juce_AudioThumbnailCache.cpp ***/
  18095. /*** Start of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  18096. #if JUCE_QUICKTIME && ! (JUCE_64BIT || JUCE_IOS)
  18097. #if ! JUCE_WINDOWS
  18098. #include <QuickTime/Movies.h>
  18099. #include <QuickTime/QTML.h>
  18100. #include <QuickTime/QuickTimeComponents.h>
  18101. #include <QuickTime/MediaHandlers.h>
  18102. #include <QuickTime/ImageCodec.h>
  18103. #else
  18104. #if JUCE_MSVC
  18105. #pragma warning (push)
  18106. #pragma warning (disable : 4100)
  18107. #endif
  18108. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  18109. add its header directory to your include path.
  18110. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  18111. flag in juce_Config.h
  18112. */
  18113. #include <Movies.h>
  18114. #include <QTML.h>
  18115. #include <QuickTimeComponents.h>
  18116. #include <MediaHandlers.h>
  18117. #include <ImageCodec.h>
  18118. #if JUCE_MSVC
  18119. #pragma warning (pop)
  18120. #endif
  18121. #endif
  18122. BEGIN_JUCE_NAMESPACE
  18123. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  18124. static const char* const quickTimeFormatName = "QuickTime file";
  18125. static const char* const quickTimeExtensions[] = { ".mov", ".mp3", ".mp4", ".m4a", 0 };
  18126. class QTAudioReader : public AudioFormatReader
  18127. {
  18128. public:
  18129. QTAudioReader (InputStream* const input_, const int trackNum_)
  18130. : AudioFormatReader (input_, TRANS (quickTimeFormatName)),
  18131. ok (false),
  18132. movie (0),
  18133. trackNum (trackNum_),
  18134. lastSampleRead (0),
  18135. lastThreadId (0),
  18136. extractor (0),
  18137. dataHandle (0)
  18138. {
  18139. JUCE_AUTORELEASEPOOL
  18140. bufferList.calloc (256, 1);
  18141. #if JUCE_WINDOWS
  18142. if (InitializeQTML (0) != noErr)
  18143. return;
  18144. #endif
  18145. if (EnterMovies() != noErr)
  18146. return;
  18147. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  18148. if (! opened)
  18149. return;
  18150. {
  18151. const int numTracks = GetMovieTrackCount (movie);
  18152. int trackCount = 0;
  18153. for (int i = 1; i <= numTracks; ++i)
  18154. {
  18155. track = GetMovieIndTrack (movie, i);
  18156. media = GetTrackMedia (track);
  18157. OSType mediaType;
  18158. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  18159. if (mediaType == SoundMediaType
  18160. && trackCount++ == trackNum_)
  18161. {
  18162. ok = true;
  18163. break;
  18164. }
  18165. }
  18166. }
  18167. if (! ok)
  18168. return;
  18169. ok = false;
  18170. lengthInSamples = GetMediaDecodeDuration (media);
  18171. usesFloatingPointData = false;
  18172. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  18173. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  18174. / GetMediaTimeScale (media);
  18175. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  18176. unsigned long output_layout_size;
  18177. err = MovieAudioExtractionGetPropertyInfo (extractor,
  18178. kQTPropertyClass_MovieAudioExtraction_Audio,
  18179. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18180. 0, &output_layout_size, 0);
  18181. if (err != noErr)
  18182. return;
  18183. HeapBlock <AudioChannelLayout> qt_audio_channel_layout;
  18184. qt_audio_channel_layout.calloc (output_layout_size, 1);
  18185. err = MovieAudioExtractionGetProperty (extractor,
  18186. kQTPropertyClass_MovieAudioExtraction_Audio,
  18187. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18188. output_layout_size, qt_audio_channel_layout, 0);
  18189. qt_audio_channel_layout[0].mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  18190. err = MovieAudioExtractionSetProperty (extractor,
  18191. kQTPropertyClass_MovieAudioExtraction_Audio,
  18192. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18193. output_layout_size,
  18194. qt_audio_channel_layout);
  18195. err = MovieAudioExtractionGetProperty (extractor,
  18196. kQTPropertyClass_MovieAudioExtraction_Audio,
  18197. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  18198. sizeof (inputStreamDesc),
  18199. &inputStreamDesc, 0);
  18200. if (err != noErr)
  18201. return;
  18202. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  18203. | kAudioFormatFlagIsPacked
  18204. | kAudioFormatFlagsNativeEndian;
  18205. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  18206. inputStreamDesc.mChannelsPerFrame = jmin ((UInt32) 2, inputStreamDesc.mChannelsPerFrame);
  18207. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  18208. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  18209. err = MovieAudioExtractionSetProperty (extractor,
  18210. kQTPropertyClass_MovieAudioExtraction_Audio,
  18211. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  18212. sizeof (inputStreamDesc),
  18213. &inputStreamDesc);
  18214. if (err != noErr)
  18215. return;
  18216. Boolean allChannelsDiscrete = false;
  18217. err = MovieAudioExtractionSetProperty (extractor,
  18218. kQTPropertyClass_MovieAudioExtraction_Movie,
  18219. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  18220. sizeof (allChannelsDiscrete),
  18221. &allChannelsDiscrete);
  18222. if (err != noErr)
  18223. return;
  18224. bufferList->mNumberBuffers = 1;
  18225. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  18226. bufferList->mBuffers[0].mDataByteSize = jmax ((UInt32) 4096, (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16);
  18227. dataBuffer.malloc (bufferList->mBuffers[0].mDataByteSize);
  18228. bufferList->mBuffers[0].mData = dataBuffer;
  18229. sampleRate = inputStreamDesc.mSampleRate;
  18230. bitsPerSample = 16;
  18231. numChannels = inputStreamDesc.mChannelsPerFrame;
  18232. detachThread();
  18233. ok = true;
  18234. }
  18235. ~QTAudioReader()
  18236. {
  18237. JUCE_AUTORELEASEPOOL
  18238. checkThreadIsAttached();
  18239. if (dataHandle != 0)
  18240. DisposeHandle (dataHandle);
  18241. if (extractor != 0)
  18242. {
  18243. MovieAudioExtractionEnd (extractor);
  18244. extractor = 0;
  18245. }
  18246. DisposeMovie (movie);
  18247. #if JUCE_MAC
  18248. ExitMoviesOnThread ();
  18249. #endif
  18250. }
  18251. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18252. int64 startSampleInFile, int numSamples)
  18253. {
  18254. JUCE_AUTORELEASEPOOL
  18255. checkThreadIsAttached();
  18256. bool ok = true;
  18257. while (numSamples > 0)
  18258. {
  18259. if (lastSampleRead != startSampleInFile)
  18260. {
  18261. TimeRecord time;
  18262. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  18263. time.base = 0;
  18264. time.value.hi = 0;
  18265. time.value.lo = (UInt32) startSampleInFile;
  18266. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  18267. kQTPropertyClass_MovieAudioExtraction_Movie,
  18268. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  18269. sizeof (time), &time);
  18270. if (err != noErr)
  18271. {
  18272. ok = false;
  18273. break;
  18274. }
  18275. }
  18276. int framesToDo = jmin (numSamples, (int) (bufferList->mBuffers[0].mDataByteSize / inputStreamDesc.mBytesPerFrame));
  18277. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * framesToDo;
  18278. UInt32 outFlags = 0;
  18279. UInt32 actualNumFrames = framesToDo;
  18280. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumFrames, bufferList, &outFlags);
  18281. if (err != noErr)
  18282. {
  18283. ok = false;
  18284. break;
  18285. }
  18286. lastSampleRead = startSampleInFile + actualNumFrames;
  18287. const int samplesReceived = actualNumFrames;
  18288. for (int j = numDestChannels; --j >= 0;)
  18289. {
  18290. if (destSamples[j] != 0)
  18291. {
  18292. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  18293. for (int i = 0; i < samplesReceived; ++i)
  18294. destSamples[j][startOffsetInDestBuffer + i] = src [i << 1] << 16;
  18295. }
  18296. }
  18297. startOffsetInDestBuffer += samplesReceived;
  18298. startSampleInFile += samplesReceived;
  18299. numSamples -= samplesReceived;
  18300. if ((outFlags & kQTMovieAudioExtractionComplete) != 0 && numSamples > 0)
  18301. {
  18302. for (int j = numDestChannels; --j >= 0;)
  18303. if (destSamples[j] != 0)
  18304. zeromem (destSamples[j] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18305. break;
  18306. }
  18307. }
  18308. detachThread();
  18309. return ok;
  18310. }
  18311. juce_UseDebuggingNewOperator
  18312. bool ok;
  18313. private:
  18314. Movie movie;
  18315. Media media;
  18316. Track track;
  18317. const int trackNum;
  18318. double trackUnitsPerFrame;
  18319. int samplesPerFrame;
  18320. int64 lastSampleRead;
  18321. Thread::ThreadID lastThreadId;
  18322. MovieAudioExtractionRef extractor;
  18323. AudioStreamBasicDescription inputStreamDesc;
  18324. HeapBlock <AudioBufferList> bufferList;
  18325. HeapBlock <char> dataBuffer;
  18326. Handle dataHandle;
  18327. void checkThreadIsAttached()
  18328. {
  18329. #if JUCE_MAC
  18330. if (Thread::getCurrentThreadId() != lastThreadId)
  18331. EnterMoviesOnThread (0);
  18332. AttachMovieToCurrentThread (movie);
  18333. #endif
  18334. }
  18335. void detachThread()
  18336. {
  18337. #if JUCE_MAC
  18338. DetachMovieFromCurrentThread (movie);
  18339. #endif
  18340. }
  18341. QTAudioReader (const QTAudioReader&);
  18342. QTAudioReader& operator= (const QTAudioReader&);
  18343. };
  18344. QuickTimeAudioFormat::QuickTimeAudioFormat()
  18345. : AudioFormat (TRANS (quickTimeFormatName), StringArray (quickTimeExtensions))
  18346. {
  18347. }
  18348. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  18349. {
  18350. }
  18351. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates() { return Array<int>(); }
  18352. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths() { return Array<int>(); }
  18353. bool QuickTimeAudioFormat::canDoStereo() { return true; }
  18354. bool QuickTimeAudioFormat::canDoMono() { return true; }
  18355. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  18356. const bool deleteStreamIfOpeningFails)
  18357. {
  18358. ScopedPointer <QTAudioReader> r (new QTAudioReader (sourceStream, 0));
  18359. if (r->ok)
  18360. return r.release();
  18361. if (! deleteStreamIfOpeningFails)
  18362. r->input = 0;
  18363. return 0;
  18364. }
  18365. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  18366. double /*sampleRateToUse*/,
  18367. unsigned int /*numberOfChannels*/,
  18368. int /*bitsPerSample*/,
  18369. const StringPairArray& /*metadataValues*/,
  18370. int /*qualityOptionIndex*/)
  18371. {
  18372. jassertfalse; // not yet implemented!
  18373. return 0;
  18374. }
  18375. END_JUCE_NAMESPACE
  18376. #endif
  18377. /*** End of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  18378. /*** Start of inlined file: juce_WavAudioFormat.cpp ***/
  18379. BEGIN_JUCE_NAMESPACE
  18380. static const char* const wavFormatName = "WAV file";
  18381. static const char* const wavExtensions[] = { ".wav", ".bwf", 0 };
  18382. const char* const WavAudioFormat::bwavDescription = "bwav description";
  18383. const char* const WavAudioFormat::bwavOriginator = "bwav originator";
  18384. const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref";
  18385. const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date";
  18386. const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time";
  18387. const char* const WavAudioFormat::bwavTimeReference = "bwav time reference";
  18388. const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history";
  18389. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  18390. const String& originator,
  18391. const String& originatorRef,
  18392. const Time& date,
  18393. const int64 timeReferenceSamples,
  18394. const String& codingHistory)
  18395. {
  18396. StringPairArray m;
  18397. m.set (bwavDescription, description);
  18398. m.set (bwavOriginator, originator);
  18399. m.set (bwavOriginatorRef, originatorRef);
  18400. m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d"));
  18401. m.set (bwavOriginationTime, date.formatted ("%H:%M:%S"));
  18402. m.set (bwavTimeReference, String (timeReferenceSamples));
  18403. m.set (bwavCodingHistory, codingHistory);
  18404. return m;
  18405. }
  18406. #if JUCE_MSVC
  18407. #pragma pack (push, 1)
  18408. #define PACKED
  18409. #elif JUCE_GCC
  18410. #define PACKED __attribute__((packed))
  18411. #else
  18412. #define PACKED
  18413. #endif
  18414. struct BWAVChunk
  18415. {
  18416. char description [256];
  18417. char originator [32];
  18418. char originatorRef [32];
  18419. char originationDate [10];
  18420. char originationTime [8];
  18421. uint32 timeRefLow;
  18422. uint32 timeRefHigh;
  18423. uint16 version;
  18424. uint8 umid[64];
  18425. uint8 reserved[190];
  18426. char codingHistory[1];
  18427. void copyTo (StringPairArray& values) const
  18428. {
  18429. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  18430. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  18431. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  18432. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  18433. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  18434. const uint32 timeLow = ByteOrder::swapIfBigEndian (timeRefLow);
  18435. const uint32 timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh);
  18436. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  18437. values.set (WavAudioFormat::bwavTimeReference, String (time));
  18438. values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory));
  18439. }
  18440. static MemoryBlock createFrom (const StringPairArray& values)
  18441. {
  18442. const size_t sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8();
  18443. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18444. data.fillWith (0);
  18445. BWAVChunk* b = (BWAVChunk*) data.getData();
  18446. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18447. // as they get called in the right order..
  18448. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  18449. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  18450. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  18451. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  18452. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  18453. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  18454. b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff));
  18455. b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32));
  18456. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff);
  18457. if (b->description[0] != 0
  18458. || b->originator[0] != 0
  18459. || b->originationDate[0] != 0
  18460. || b->originationTime[0] != 0
  18461. || b->codingHistory[0] != 0
  18462. || time != 0)
  18463. {
  18464. return data;
  18465. }
  18466. return MemoryBlock();
  18467. }
  18468. } PACKED;
  18469. struct SMPLChunk
  18470. {
  18471. struct SampleLoop
  18472. {
  18473. uint32 identifier;
  18474. uint32 type;
  18475. uint32 start;
  18476. uint32 end;
  18477. uint32 fraction;
  18478. uint32 playCount;
  18479. } PACKED;
  18480. uint32 manufacturer;
  18481. uint32 product;
  18482. uint32 samplePeriod;
  18483. uint32 midiUnityNote;
  18484. uint32 midiPitchFraction;
  18485. uint32 smpteFormat;
  18486. uint32 smpteOffset;
  18487. uint32 numSampleLoops;
  18488. uint32 samplerData;
  18489. SampleLoop loops[1];
  18490. void copyTo (StringPairArray& values, const int totalSize) const
  18491. {
  18492. values.set ("Manufacturer", String (ByteOrder::swapIfBigEndian (manufacturer)));
  18493. values.set ("Product", String (ByteOrder::swapIfBigEndian (product)));
  18494. values.set ("SamplePeriod", String (ByteOrder::swapIfBigEndian (samplePeriod)));
  18495. values.set ("MidiUnityNote", String (ByteOrder::swapIfBigEndian (midiUnityNote)));
  18496. values.set ("MidiPitchFraction", String (ByteOrder::swapIfBigEndian (midiPitchFraction)));
  18497. values.set ("SmpteFormat", String (ByteOrder::swapIfBigEndian (smpteFormat)));
  18498. values.set ("SmpteOffset", String (ByteOrder::swapIfBigEndian (smpteOffset)));
  18499. values.set ("NumSampleLoops", String (ByteOrder::swapIfBigEndian (numSampleLoops)));
  18500. values.set ("SamplerData", String (ByteOrder::swapIfBigEndian (samplerData)));
  18501. for (uint32 i = 0; i < numSampleLoops; ++i)
  18502. {
  18503. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  18504. break;
  18505. const String prefix ("Loop" + String(i));
  18506. values.set (prefix + "Identifier", String (ByteOrder::swapIfBigEndian (loops[i].identifier)));
  18507. values.set (prefix + "Type", String (ByteOrder::swapIfBigEndian (loops[i].type)));
  18508. values.set (prefix + "Start", String (ByteOrder::swapIfBigEndian (loops[i].start)));
  18509. values.set (prefix + "End", String (ByteOrder::swapIfBigEndian (loops[i].end)));
  18510. values.set (prefix + "Fraction", String (ByteOrder::swapIfBigEndian (loops[i].fraction)));
  18511. values.set (prefix + "PlayCount", String (ByteOrder::swapIfBigEndian (loops[i].playCount)));
  18512. }
  18513. }
  18514. static MemoryBlock createFrom (const StringPairArray& values)
  18515. {
  18516. const int numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue());
  18517. if (numLoops <= 0)
  18518. return MemoryBlock();
  18519. const size_t sizeNeeded = sizeof (SMPLChunk) + (numLoops - 1) * sizeof (SampleLoop);
  18520. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18521. data.fillWith (0);
  18522. SMPLChunk* s = (SMPLChunk*) data.getData();
  18523. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18524. // as they get called in the right order..
  18525. s->manufacturer = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Manufacturer", "0").getIntValue());
  18526. s->product = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Product", "0").getIntValue());
  18527. s->samplePeriod = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplePeriod", "0").getIntValue());
  18528. s->midiUnityNote = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiUnityNote", "60").getIntValue());
  18529. s->midiPitchFraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiPitchFraction", "0").getIntValue());
  18530. s->smpteFormat = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteFormat", "0").getIntValue());
  18531. s->smpteOffset = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteOffset", "0").getIntValue());
  18532. s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops);
  18533. s->samplerData = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplerData", "0").getIntValue());
  18534. for (int i = 0; i < numLoops; ++i)
  18535. {
  18536. const String prefix ("Loop" + String(i));
  18537. s->loops[i].identifier = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Identifier", "0").getIntValue());
  18538. s->loops[i].type = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Type", "0").getIntValue());
  18539. s->loops[i].start = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Start", "0").getIntValue());
  18540. s->loops[i].end = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "End", "0").getIntValue());
  18541. s->loops[i].fraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Fraction", "0").getIntValue());
  18542. s->loops[i].playCount = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "PlayCount", "0").getIntValue());
  18543. }
  18544. return data;
  18545. }
  18546. } PACKED;
  18547. struct ExtensibleWavSubFormat
  18548. {
  18549. uint32 data1;
  18550. uint16 data2;
  18551. uint16 data3;
  18552. uint8 data4[8];
  18553. } PACKED;
  18554. #if JUCE_MSVC
  18555. #pragma pack (pop)
  18556. #endif
  18557. #undef PACKED
  18558. class WavAudioFormatReader : public AudioFormatReader
  18559. {
  18560. public:
  18561. WavAudioFormatReader (InputStream* const in)
  18562. : AudioFormatReader (in, TRANS (wavFormatName)),
  18563. dataLength (0),
  18564. bwavChunkStart (0),
  18565. bwavSize (0)
  18566. {
  18567. if (input->readInt() == chunkName ("RIFF"))
  18568. {
  18569. const uint32 len = (uint32) input->readInt();
  18570. const int64 end = input->getPosition() + len;
  18571. bool hasGotType = false;
  18572. bool hasGotData = false;
  18573. if (input->readInt() == chunkName ("WAVE"))
  18574. {
  18575. while (input->getPosition() < end
  18576. && ! input->isExhausted())
  18577. {
  18578. const int chunkType = input->readInt();
  18579. uint32 length = (uint32) input->readInt();
  18580. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  18581. if (chunkType == chunkName ("fmt "))
  18582. {
  18583. // read the format chunk
  18584. const unsigned short format = input->readShort();
  18585. const short numChans = input->readShort();
  18586. sampleRate = input->readInt();
  18587. const int bytesPerSec = input->readInt();
  18588. numChannels = numChans;
  18589. bytesPerFrame = bytesPerSec / (int)sampleRate;
  18590. bitsPerSample = 8 * bytesPerFrame / numChans;
  18591. if (format == 3)
  18592. {
  18593. usesFloatingPointData = true;
  18594. }
  18595. else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/)
  18596. {
  18597. if (length < 40) // too short
  18598. {
  18599. bytesPerFrame = 0;
  18600. }
  18601. else
  18602. {
  18603. input->skipNextBytes (12); // skip over blockAlign, bitsPerSample and speakerPosition mask
  18604. ExtensibleWavSubFormat subFormat;
  18605. subFormat.data1 = input->readInt();
  18606. subFormat.data2 = input->readShort();
  18607. subFormat.data3 = input->readShort();
  18608. input->read (subFormat.data4, sizeof (subFormat.data4));
  18609. const ExtensibleWavSubFormat pcmFormat
  18610. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  18611. if (memcmp (&subFormat, &pcmFormat, sizeof (subFormat)) != 0)
  18612. {
  18613. const ExtensibleWavSubFormat ambisonicFormat
  18614. = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  18615. if (memcmp (&subFormat, &ambisonicFormat, sizeof (subFormat)) != 0)
  18616. bytesPerFrame = 0;
  18617. }
  18618. }
  18619. }
  18620. else if (format != 1)
  18621. {
  18622. bytesPerFrame = 0;
  18623. }
  18624. hasGotType = true;
  18625. }
  18626. else if (chunkType == chunkName ("data"))
  18627. {
  18628. // get the data chunk's position
  18629. dataLength = length;
  18630. dataChunkStart = input->getPosition();
  18631. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  18632. hasGotData = true;
  18633. }
  18634. else if (chunkType == chunkName ("bext"))
  18635. {
  18636. bwavChunkStart = input->getPosition();
  18637. bwavSize = length;
  18638. // Broadcast-wav extension chunk..
  18639. HeapBlock <BWAVChunk> bwav;
  18640. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  18641. input->read (bwav, length);
  18642. bwav->copyTo (metadataValues);
  18643. }
  18644. else if (chunkType == chunkName ("smpl"))
  18645. {
  18646. HeapBlock <SMPLChunk> smpl;
  18647. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  18648. input->read (smpl, length);
  18649. smpl->copyTo (metadataValues, length);
  18650. }
  18651. else if (chunkEnd <= input->getPosition())
  18652. {
  18653. break;
  18654. }
  18655. input->setPosition (chunkEnd);
  18656. }
  18657. }
  18658. }
  18659. }
  18660. ~WavAudioFormatReader()
  18661. {
  18662. }
  18663. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18664. int64 startSampleInFile, int numSamples)
  18665. {
  18666. jassert (destSamples != 0);
  18667. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  18668. if (samplesAvailable < numSamples)
  18669. {
  18670. for (int i = numDestChannels; --i >= 0;)
  18671. if (destSamples[i] != 0)
  18672. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18673. numSamples = (int) samplesAvailable;
  18674. }
  18675. if (numSamples <= 0)
  18676. return true;
  18677. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  18678. while (numSamples > 0)
  18679. {
  18680. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  18681. char tempBuffer [tempBufSize];
  18682. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  18683. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  18684. if (bytesRead < numThisTime * bytesPerFrame)
  18685. {
  18686. jassert (bytesRead >= 0);
  18687. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  18688. }
  18689. switch (bitsPerSample)
  18690. {
  18691. case 8: ReadHelper<AudioData::Int32, AudioData::UInt8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18692. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18693. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18694. case 32: if (usesFloatingPointData) ReadHelper<AudioData::Float32, AudioData::Float32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime);
  18695. else ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18696. default: jassertfalse; break;
  18697. }
  18698. startOffsetInDestBuffer += numThisTime;
  18699. numSamples -= numThisTime;
  18700. }
  18701. return true;
  18702. }
  18703. int64 bwavChunkStart, bwavSize;
  18704. juce_UseDebuggingNewOperator
  18705. private:
  18706. ScopedPointer<AudioData::Converter> converter;
  18707. int bytesPerFrame;
  18708. int64 dataChunkStart, dataLength;
  18709. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  18710. WavAudioFormatReader (const WavAudioFormatReader&);
  18711. WavAudioFormatReader& operator= (const WavAudioFormatReader&);
  18712. };
  18713. class WavAudioFormatWriter : public AudioFormatWriter
  18714. {
  18715. public:
  18716. WavAudioFormatWriter (OutputStream* const out,
  18717. const double sampleRate_,
  18718. const unsigned int numChannels_,
  18719. const int bits,
  18720. const StringPairArray& metadataValues)
  18721. : AudioFormatWriter (out,
  18722. TRANS (wavFormatName),
  18723. sampleRate_,
  18724. numChannels_,
  18725. bits),
  18726. lengthInSamples (0),
  18727. bytesWritten (0),
  18728. writeFailed (false)
  18729. {
  18730. if (metadataValues.size() > 0)
  18731. {
  18732. bwavChunk = BWAVChunk::createFrom (metadataValues);
  18733. smplChunk = SMPLChunk::createFrom (metadataValues);
  18734. }
  18735. headerPosition = out->getPosition();
  18736. writeHeader();
  18737. }
  18738. ~WavAudioFormatWriter()
  18739. {
  18740. writeHeader();
  18741. }
  18742. bool write (const int** data, int numSamples)
  18743. {
  18744. jassert (data != 0 && *data != 0); // the input must contain at least one channel!
  18745. if (writeFailed)
  18746. return false;
  18747. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  18748. tempBlock.ensureSize (bytes, false);
  18749. switch (bitsPerSample)
  18750. {
  18751. case 8: WriteHelper<AudioData::UInt8, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18752. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18753. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18754. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18755. default: jassertfalse; break;
  18756. }
  18757. if (bytesWritten + bytes >= (uint32) 0xfff00000
  18758. || ! output->write (tempBlock.getData(), bytes))
  18759. {
  18760. // failed to write to disk, so let's try writing the header.
  18761. // If it's just run out of disk space, then if it does manage
  18762. // to write the header, we'll still have a useable file..
  18763. writeHeader();
  18764. writeFailed = true;
  18765. return false;
  18766. }
  18767. else
  18768. {
  18769. bytesWritten += bytes;
  18770. lengthInSamples += numSamples;
  18771. return true;
  18772. }
  18773. }
  18774. juce_UseDebuggingNewOperator
  18775. private:
  18776. ScopedPointer<AudioData::Converter> converter;
  18777. MemoryBlock tempBlock, bwavChunk, smplChunk;
  18778. uint32 lengthInSamples, bytesWritten;
  18779. int64 headerPosition;
  18780. bool writeFailed;
  18781. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  18782. void writeHeader()
  18783. {
  18784. const bool seekedOk = output->setPosition (headerPosition);
  18785. (void) seekedOk;
  18786. // if this fails, you've given it an output stream that can't seek! It needs
  18787. // to be able to seek back to write the header
  18788. jassert (seekedOk);
  18789. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  18790. output->writeInt (chunkName ("RIFF"));
  18791. output->writeInt ((int) (lengthInSamples * bytesPerFrame
  18792. + ((bwavChunk.getSize() > 0) ? (44 + bwavChunk.getSize()) : 36)));
  18793. output->writeInt (chunkName ("WAVE"));
  18794. output->writeInt (chunkName ("fmt "));
  18795. output->writeInt (16);
  18796. output->writeShort ((bitsPerSample < 32) ? (short) 1 /*WAVE_FORMAT_PCM*/
  18797. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  18798. output->writeShort ((short) numChannels);
  18799. output->writeInt ((int) sampleRate);
  18800. output->writeInt (bytesPerFrame * (int) sampleRate);
  18801. output->writeShort ((short) bytesPerFrame);
  18802. output->writeShort ((short) bitsPerSample);
  18803. if (bwavChunk.getSize() > 0)
  18804. {
  18805. output->writeInt (chunkName ("bext"));
  18806. output->writeInt ((int) bwavChunk.getSize());
  18807. output->write (bwavChunk.getData(), (int) bwavChunk.getSize());
  18808. }
  18809. if (smplChunk.getSize() > 0)
  18810. {
  18811. output->writeInt (chunkName ("smpl"));
  18812. output->writeInt ((int) smplChunk.getSize());
  18813. output->write (smplChunk.getData(), (int) smplChunk.getSize());
  18814. }
  18815. output->writeInt (chunkName ("data"));
  18816. output->writeInt (lengthInSamples * bytesPerFrame);
  18817. usesFloatingPointData = (bitsPerSample == 32);
  18818. }
  18819. WavAudioFormatWriter (const WavAudioFormatWriter&);
  18820. WavAudioFormatWriter& operator= (const WavAudioFormatWriter&);
  18821. };
  18822. WavAudioFormat::WavAudioFormat()
  18823. : AudioFormat (TRANS (wavFormatName), StringArray (wavExtensions))
  18824. {
  18825. }
  18826. WavAudioFormat::~WavAudioFormat()
  18827. {
  18828. }
  18829. const Array <int> WavAudioFormat::getPossibleSampleRates()
  18830. {
  18831. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  18832. return Array <int> (rates);
  18833. }
  18834. const Array <int> WavAudioFormat::getPossibleBitDepths()
  18835. {
  18836. const int depths[] = { 8, 16, 24, 32, 0 };
  18837. return Array <int> (depths);
  18838. }
  18839. bool WavAudioFormat::canDoStereo() { return true; }
  18840. bool WavAudioFormat::canDoMono() { return true; }
  18841. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  18842. const bool deleteStreamIfOpeningFails)
  18843. {
  18844. ScopedPointer <WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  18845. if (r->sampleRate != 0)
  18846. return r.release();
  18847. if (! deleteStreamIfOpeningFails)
  18848. r->input = 0;
  18849. return 0;
  18850. }
  18851. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  18852. double sampleRate,
  18853. unsigned int numChannels,
  18854. int bitsPerSample,
  18855. const StringPairArray& metadataValues,
  18856. int /*qualityOptionIndex*/)
  18857. {
  18858. if (getPossibleBitDepths().contains (bitsPerSample))
  18859. {
  18860. return new WavAudioFormatWriter (out,
  18861. sampleRate,
  18862. numChannels,
  18863. bitsPerSample,
  18864. metadataValues);
  18865. }
  18866. return 0;
  18867. }
  18868. static bool juce_slowCopyOfWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  18869. {
  18870. TemporaryFile tempFile (file);
  18871. WavAudioFormat wav;
  18872. ScopedPointer <AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true));
  18873. if (reader != 0)
  18874. {
  18875. ScopedPointer <OutputStream> outStream (tempFile.getFile().createOutputStream());
  18876. if (outStream != 0)
  18877. {
  18878. ScopedPointer <AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate,
  18879. reader->numChannels, reader->bitsPerSample,
  18880. metadata, 0));
  18881. if (writer != 0)
  18882. {
  18883. outStream.release();
  18884. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  18885. writer = 0;
  18886. reader = 0;
  18887. return ok && tempFile.overwriteTargetFileWithTemporary();
  18888. }
  18889. }
  18890. }
  18891. return false;
  18892. }
  18893. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  18894. {
  18895. ScopedPointer <WavAudioFormatReader> reader ((WavAudioFormatReader*) createReaderFor (wavFile.createInputStream(), true));
  18896. if (reader != 0)
  18897. {
  18898. const int64 bwavPos = reader->bwavChunkStart;
  18899. const int64 bwavSize = reader->bwavSize;
  18900. reader = 0;
  18901. if (bwavSize > 0)
  18902. {
  18903. MemoryBlock chunk = BWAVChunk::createFrom (newMetadata);
  18904. if (chunk.getSize() <= (size_t) bwavSize)
  18905. {
  18906. // the new one will fit in the space available, so write it directly..
  18907. const int64 oldSize = wavFile.getSize();
  18908. {
  18909. ScopedPointer <FileOutputStream> out (wavFile.createOutputStream());
  18910. out->setPosition (bwavPos);
  18911. out->write (chunk.getData(), (int) chunk.getSize());
  18912. out->setPosition (oldSize);
  18913. }
  18914. jassert (wavFile.getSize() == oldSize);
  18915. return true;
  18916. }
  18917. }
  18918. }
  18919. return juce_slowCopyOfWavFileWithNewMetadata (wavFile, newMetadata);
  18920. }
  18921. END_JUCE_NAMESPACE
  18922. /*** End of inlined file: juce_WavAudioFormat.cpp ***/
  18923. /*** Start of inlined file: juce_AudioCDReader.cpp ***/
  18924. #if JUCE_USE_CDREADER
  18925. BEGIN_JUCE_NAMESPACE
  18926. int AudioCDReader::getNumTracks() const
  18927. {
  18928. return trackStartSamples.size() - 1;
  18929. }
  18930. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  18931. {
  18932. return trackStartSamples [trackNum];
  18933. }
  18934. const Array<int>& AudioCDReader::getTrackOffsets() const
  18935. {
  18936. return trackStartSamples;
  18937. }
  18938. int AudioCDReader::getCDDBId()
  18939. {
  18940. int checksum = 0;
  18941. const int numTracks = getNumTracks();
  18942. for (int i = 0; i < numTracks; ++i)
  18943. for (int offset = (trackStartSamples.getUnchecked(i) + 88200) / 44100; offset > 0; offset /= 10)
  18944. checksum += offset % 10;
  18945. const int length = (trackStartSamples.getLast() - trackStartSamples.getFirst()) / 44100;
  18946. // CCLLLLTT: checksum, length, tracks
  18947. return ((checksum & 0xff) << 24) | (length << 8) | numTracks;
  18948. }
  18949. END_JUCE_NAMESPACE
  18950. #endif
  18951. /*** End of inlined file: juce_AudioCDReader.cpp ***/
  18952. /*** Start of inlined file: juce_AudioFormatReaderSource.cpp ***/
  18953. BEGIN_JUCE_NAMESPACE
  18954. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  18955. const bool deleteReaderWhenThisIsDeleted)
  18956. : reader (reader_),
  18957. deleteReader (deleteReaderWhenThisIsDeleted),
  18958. nextPlayPos (0),
  18959. looping (false)
  18960. {
  18961. jassert (reader != 0);
  18962. }
  18963. AudioFormatReaderSource::~AudioFormatReaderSource()
  18964. {
  18965. releaseResources();
  18966. if (deleteReader)
  18967. delete reader;
  18968. }
  18969. void AudioFormatReaderSource::setNextReadPosition (int newPosition)
  18970. {
  18971. nextPlayPos = newPosition;
  18972. }
  18973. void AudioFormatReaderSource::setLooping (bool shouldLoop)
  18974. {
  18975. looping = shouldLoop;
  18976. }
  18977. int AudioFormatReaderSource::getNextReadPosition() const
  18978. {
  18979. return (looping) ? (nextPlayPos % (int) reader->lengthInSamples)
  18980. : nextPlayPos;
  18981. }
  18982. int AudioFormatReaderSource::getTotalLength() const
  18983. {
  18984. return (int) reader->lengthInSamples;
  18985. }
  18986. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  18987. double /*sampleRate*/)
  18988. {
  18989. }
  18990. void AudioFormatReaderSource::releaseResources()
  18991. {
  18992. }
  18993. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  18994. {
  18995. if (info.numSamples > 0)
  18996. {
  18997. const int start = nextPlayPos;
  18998. if (looping)
  18999. {
  19000. const int newStart = start % (int) reader->lengthInSamples;
  19001. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  19002. if (newEnd > newStart)
  19003. {
  19004. info.buffer->readFromAudioReader (reader,
  19005. info.startSample,
  19006. newEnd - newStart,
  19007. newStart,
  19008. true, true);
  19009. }
  19010. else
  19011. {
  19012. const int endSamps = (int) reader->lengthInSamples - newStart;
  19013. info.buffer->readFromAudioReader (reader,
  19014. info.startSample,
  19015. endSamps,
  19016. newStart,
  19017. true, true);
  19018. info.buffer->readFromAudioReader (reader,
  19019. info.startSample + endSamps,
  19020. newEnd,
  19021. 0,
  19022. true, true);
  19023. }
  19024. nextPlayPos = newEnd;
  19025. }
  19026. else
  19027. {
  19028. info.buffer->readFromAudioReader (reader,
  19029. info.startSample,
  19030. info.numSamples,
  19031. start,
  19032. true, true);
  19033. nextPlayPos += info.numSamples;
  19034. }
  19035. }
  19036. }
  19037. END_JUCE_NAMESPACE
  19038. /*** End of inlined file: juce_AudioFormatReaderSource.cpp ***/
  19039. /*** Start of inlined file: juce_AudioSourcePlayer.cpp ***/
  19040. BEGIN_JUCE_NAMESPACE
  19041. AudioSourcePlayer::AudioSourcePlayer()
  19042. : source (0),
  19043. sampleRate (0),
  19044. bufferSize (0),
  19045. tempBuffer (2, 8),
  19046. lastGain (1.0f),
  19047. gain (1.0f)
  19048. {
  19049. }
  19050. AudioSourcePlayer::~AudioSourcePlayer()
  19051. {
  19052. setSource (0);
  19053. }
  19054. void AudioSourcePlayer::setSource (AudioSource* newSource)
  19055. {
  19056. if (source != newSource)
  19057. {
  19058. AudioSource* const oldSource = source;
  19059. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  19060. newSource->prepareToPlay (bufferSize, sampleRate);
  19061. {
  19062. const ScopedLock sl (readLock);
  19063. source = newSource;
  19064. }
  19065. if (oldSource != 0)
  19066. oldSource->releaseResources();
  19067. }
  19068. }
  19069. void AudioSourcePlayer::setGain (const float newGain) throw()
  19070. {
  19071. gain = newGain;
  19072. }
  19073. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  19074. int totalNumInputChannels,
  19075. float** outputChannelData,
  19076. int totalNumOutputChannels,
  19077. int numSamples)
  19078. {
  19079. // these should have been prepared by audioDeviceAboutToStart()...
  19080. jassert (sampleRate > 0 && bufferSize > 0);
  19081. const ScopedLock sl (readLock);
  19082. if (source != 0)
  19083. {
  19084. AudioSourceChannelInfo info;
  19085. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  19086. // messy stuff needed to compact the channels down into an array
  19087. // of non-zero pointers..
  19088. for (i = 0; i < totalNumInputChannels; ++i)
  19089. {
  19090. if (inputChannelData[i] != 0)
  19091. {
  19092. inputChans [numInputs++] = inputChannelData[i];
  19093. if (numInputs >= numElementsInArray (inputChans))
  19094. break;
  19095. }
  19096. }
  19097. for (i = 0; i < totalNumOutputChannels; ++i)
  19098. {
  19099. if (outputChannelData[i] != 0)
  19100. {
  19101. outputChans [numOutputs++] = outputChannelData[i];
  19102. if (numOutputs >= numElementsInArray (outputChans))
  19103. break;
  19104. }
  19105. }
  19106. if (numInputs > numOutputs)
  19107. {
  19108. // if there aren't enough output channels for the number of
  19109. // inputs, we need to create some temporary extra ones (can't
  19110. // use the input data in case it gets written to)
  19111. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  19112. false, false, true);
  19113. for (i = 0; i < numOutputs; ++i)
  19114. {
  19115. channels[numActiveChans] = outputChans[i];
  19116. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19117. ++numActiveChans;
  19118. }
  19119. for (i = numOutputs; i < numInputs; ++i)
  19120. {
  19121. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  19122. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19123. ++numActiveChans;
  19124. }
  19125. }
  19126. else
  19127. {
  19128. for (i = 0; i < numInputs; ++i)
  19129. {
  19130. channels[numActiveChans] = outputChans[i];
  19131. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19132. ++numActiveChans;
  19133. }
  19134. for (i = numInputs; i < numOutputs; ++i)
  19135. {
  19136. channels[numActiveChans] = outputChans[i];
  19137. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  19138. ++numActiveChans;
  19139. }
  19140. }
  19141. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  19142. info.buffer = &buffer;
  19143. info.startSample = 0;
  19144. info.numSamples = numSamples;
  19145. source->getNextAudioBlock (info);
  19146. for (i = info.buffer->getNumChannels(); --i >= 0;)
  19147. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  19148. lastGain = gain;
  19149. }
  19150. else
  19151. {
  19152. for (int i = 0; i < totalNumOutputChannels; ++i)
  19153. if (outputChannelData[i] != 0)
  19154. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  19155. }
  19156. }
  19157. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  19158. {
  19159. sampleRate = device->getCurrentSampleRate();
  19160. bufferSize = device->getCurrentBufferSizeSamples();
  19161. zeromem (channels, sizeof (channels));
  19162. if (source != 0)
  19163. source->prepareToPlay (bufferSize, sampleRate);
  19164. }
  19165. void AudioSourcePlayer::audioDeviceStopped()
  19166. {
  19167. if (source != 0)
  19168. source->releaseResources();
  19169. sampleRate = 0.0;
  19170. bufferSize = 0;
  19171. tempBuffer.setSize (2, 8);
  19172. }
  19173. END_JUCE_NAMESPACE
  19174. /*** End of inlined file: juce_AudioSourcePlayer.cpp ***/
  19175. /*** Start of inlined file: juce_AudioTransportSource.cpp ***/
  19176. BEGIN_JUCE_NAMESPACE
  19177. AudioTransportSource::AudioTransportSource()
  19178. : source (0),
  19179. resamplerSource (0),
  19180. bufferingSource (0),
  19181. positionableSource (0),
  19182. masterSource (0),
  19183. gain (1.0f),
  19184. lastGain (1.0f),
  19185. playing (false),
  19186. stopped (true),
  19187. sampleRate (44100.0),
  19188. sourceSampleRate (0.0),
  19189. blockSize (128),
  19190. readAheadBufferSize (0),
  19191. isPrepared (false),
  19192. inputStreamEOF (false)
  19193. {
  19194. }
  19195. AudioTransportSource::~AudioTransportSource()
  19196. {
  19197. setSource (0);
  19198. releaseResources();
  19199. }
  19200. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  19201. int readAheadBufferSize_,
  19202. double sourceSampleRateToCorrectFor)
  19203. {
  19204. if (source == newSource)
  19205. {
  19206. if (source == 0)
  19207. return;
  19208. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  19209. }
  19210. readAheadBufferSize = readAheadBufferSize_;
  19211. sourceSampleRate = sourceSampleRateToCorrectFor;
  19212. ResamplingAudioSource* newResamplerSource = 0;
  19213. BufferingAudioSource* newBufferingSource = 0;
  19214. PositionableAudioSource* newPositionableSource = 0;
  19215. AudioSource* newMasterSource = 0;
  19216. ScopedPointer <ResamplingAudioSource> oldResamplerSource (resamplerSource);
  19217. ScopedPointer <BufferingAudioSource> oldBufferingSource (bufferingSource);
  19218. AudioSource* oldMasterSource = masterSource;
  19219. if (newSource != 0)
  19220. {
  19221. newPositionableSource = newSource;
  19222. if (readAheadBufferSize_ > 0)
  19223. newPositionableSource = newBufferingSource
  19224. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  19225. newPositionableSource->setNextReadPosition (0);
  19226. if (sourceSampleRateToCorrectFor != 0)
  19227. newMasterSource = newResamplerSource
  19228. = new ResamplingAudioSource (newPositionableSource, false);
  19229. else
  19230. newMasterSource = newPositionableSource;
  19231. if (isPrepared)
  19232. {
  19233. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  19234. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19235. newMasterSource->prepareToPlay (blockSize, sampleRate);
  19236. }
  19237. }
  19238. {
  19239. const ScopedLock sl (callbackLock);
  19240. source = newSource;
  19241. resamplerSource = newResamplerSource;
  19242. bufferingSource = newBufferingSource;
  19243. masterSource = newMasterSource;
  19244. positionableSource = newPositionableSource;
  19245. playing = false;
  19246. }
  19247. if (oldMasterSource != 0)
  19248. oldMasterSource->releaseResources();
  19249. }
  19250. void AudioTransportSource::start()
  19251. {
  19252. if ((! playing) && masterSource != 0)
  19253. {
  19254. {
  19255. const ScopedLock sl (callbackLock);
  19256. playing = true;
  19257. stopped = false;
  19258. inputStreamEOF = false;
  19259. }
  19260. sendChangeMessage (this);
  19261. }
  19262. }
  19263. void AudioTransportSource::stop()
  19264. {
  19265. if (playing)
  19266. {
  19267. {
  19268. const ScopedLock sl (callbackLock);
  19269. playing = false;
  19270. }
  19271. int n = 500;
  19272. while (--n >= 0 && ! stopped)
  19273. Thread::sleep (2);
  19274. sendChangeMessage (this);
  19275. }
  19276. }
  19277. void AudioTransportSource::setPosition (double newPosition)
  19278. {
  19279. if (sampleRate > 0.0)
  19280. setNextReadPosition (roundToInt (newPosition * sampleRate));
  19281. }
  19282. double AudioTransportSource::getCurrentPosition() const
  19283. {
  19284. if (sampleRate > 0.0)
  19285. return getNextReadPosition() / sampleRate;
  19286. else
  19287. return 0.0;
  19288. }
  19289. void AudioTransportSource::setNextReadPosition (int newPosition)
  19290. {
  19291. if (positionableSource != 0)
  19292. {
  19293. if (sampleRate > 0 && sourceSampleRate > 0)
  19294. newPosition = roundToInt (newPosition * sourceSampleRate / sampleRate);
  19295. positionableSource->setNextReadPosition (newPosition);
  19296. }
  19297. }
  19298. int AudioTransportSource::getNextReadPosition() const
  19299. {
  19300. if (positionableSource != 0)
  19301. {
  19302. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19303. return roundToInt (positionableSource->getNextReadPosition() * ratio);
  19304. }
  19305. return 0;
  19306. }
  19307. int AudioTransportSource::getTotalLength() const
  19308. {
  19309. const ScopedLock sl (callbackLock);
  19310. if (positionableSource != 0)
  19311. {
  19312. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19313. return roundToInt (positionableSource->getTotalLength() * ratio);
  19314. }
  19315. return 0;
  19316. }
  19317. bool AudioTransportSource::isLooping() const
  19318. {
  19319. const ScopedLock sl (callbackLock);
  19320. return positionableSource != 0
  19321. && positionableSource->isLooping();
  19322. }
  19323. void AudioTransportSource::setGain (const float newGain) throw()
  19324. {
  19325. gain = newGain;
  19326. }
  19327. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  19328. double sampleRate_)
  19329. {
  19330. const ScopedLock sl (callbackLock);
  19331. sampleRate = sampleRate_;
  19332. blockSize = samplesPerBlockExpected;
  19333. if (masterSource != 0)
  19334. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19335. if (resamplerSource != 0 && sourceSampleRate != 0)
  19336. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19337. isPrepared = true;
  19338. }
  19339. void AudioTransportSource::releaseResources()
  19340. {
  19341. const ScopedLock sl (callbackLock);
  19342. if (masterSource != 0)
  19343. masterSource->releaseResources();
  19344. isPrepared = false;
  19345. }
  19346. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19347. {
  19348. const ScopedLock sl (callbackLock);
  19349. inputStreamEOF = false;
  19350. if (masterSource != 0 && ! stopped)
  19351. {
  19352. masterSource->getNextAudioBlock (info);
  19353. if (! playing)
  19354. {
  19355. // just stopped playing, so fade out the last block..
  19356. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19357. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  19358. if (info.numSamples > 256)
  19359. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  19360. }
  19361. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  19362. && ! positionableSource->isLooping())
  19363. {
  19364. playing = false;
  19365. inputStreamEOF = true;
  19366. sendChangeMessage (this);
  19367. }
  19368. stopped = ! playing;
  19369. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19370. {
  19371. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  19372. lastGain, gain);
  19373. }
  19374. }
  19375. else
  19376. {
  19377. info.clearActiveBufferRegion();
  19378. stopped = true;
  19379. }
  19380. lastGain = gain;
  19381. }
  19382. END_JUCE_NAMESPACE
  19383. /*** End of inlined file: juce_AudioTransportSource.cpp ***/
  19384. /*** Start of inlined file: juce_BufferingAudioSource.cpp ***/
  19385. BEGIN_JUCE_NAMESPACE
  19386. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  19387. public Thread,
  19388. private Timer
  19389. {
  19390. public:
  19391. SharedBufferingAudioSourceThread()
  19392. : Thread ("Audio Buffer")
  19393. {
  19394. }
  19395. ~SharedBufferingAudioSourceThread()
  19396. {
  19397. stopThread (10000);
  19398. clearSingletonInstance();
  19399. }
  19400. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  19401. void addSource (BufferingAudioSource* source)
  19402. {
  19403. const ScopedLock sl (lock);
  19404. if (! sources.contains (source))
  19405. {
  19406. sources.add (source);
  19407. startThread();
  19408. stopTimer();
  19409. }
  19410. notify();
  19411. }
  19412. void removeSource (BufferingAudioSource* source)
  19413. {
  19414. const ScopedLock sl (lock);
  19415. sources.removeValue (source);
  19416. if (sources.size() == 0)
  19417. startTimer (5000);
  19418. }
  19419. private:
  19420. Array <BufferingAudioSource*> sources;
  19421. CriticalSection lock;
  19422. void run()
  19423. {
  19424. while (! threadShouldExit())
  19425. {
  19426. bool busy = false;
  19427. for (int i = sources.size(); --i >= 0;)
  19428. {
  19429. if (threadShouldExit())
  19430. return;
  19431. const ScopedLock sl (lock);
  19432. BufferingAudioSource* const b = sources[i];
  19433. if (b != 0 && b->readNextBufferChunk())
  19434. busy = true;
  19435. }
  19436. if (! busy)
  19437. wait (500);
  19438. }
  19439. }
  19440. void timerCallback()
  19441. {
  19442. stopTimer();
  19443. if (sources.size() == 0)
  19444. deleteInstance();
  19445. }
  19446. SharedBufferingAudioSourceThread (const SharedBufferingAudioSourceThread&);
  19447. SharedBufferingAudioSourceThread& operator= (const SharedBufferingAudioSourceThread&);
  19448. };
  19449. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  19450. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  19451. const bool deleteSourceWhenDeleted_,
  19452. int numberOfSamplesToBuffer_)
  19453. : source (source_),
  19454. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19455. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  19456. buffer (2, 0),
  19457. bufferValidStart (0),
  19458. bufferValidEnd (0),
  19459. nextPlayPos (0),
  19460. wasSourceLooping (false)
  19461. {
  19462. jassert (source_ != 0);
  19463. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  19464. // not using a larger buffer..
  19465. }
  19466. BufferingAudioSource::~BufferingAudioSource()
  19467. {
  19468. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19469. if (thread != 0)
  19470. thread->removeSource (this);
  19471. if (deleteSourceWhenDeleted)
  19472. delete source;
  19473. }
  19474. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  19475. {
  19476. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  19477. sampleRate = sampleRate_;
  19478. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  19479. buffer.clear();
  19480. bufferValidStart = 0;
  19481. bufferValidEnd = 0;
  19482. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  19483. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  19484. buffer.getNumSamples() / 2))
  19485. {
  19486. SharedBufferingAudioSourceThread::getInstance()->notify();
  19487. Thread::sleep (5);
  19488. }
  19489. }
  19490. void BufferingAudioSource::releaseResources()
  19491. {
  19492. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19493. if (thread != 0)
  19494. thread->removeSource (this);
  19495. buffer.setSize (2, 0);
  19496. source->releaseResources();
  19497. }
  19498. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19499. {
  19500. const ScopedLock sl (bufferStartPosLock);
  19501. const int validStart = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos;
  19502. const int validEnd = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos;
  19503. if (validStart == validEnd)
  19504. {
  19505. // total cache miss
  19506. info.clearActiveBufferRegion();
  19507. }
  19508. else
  19509. {
  19510. if (validStart > 0)
  19511. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  19512. if (validEnd < info.numSamples)
  19513. info.buffer->clear (info.startSample + validEnd,
  19514. info.numSamples - validEnd); // partial cache miss at end
  19515. if (validStart < validEnd)
  19516. {
  19517. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  19518. {
  19519. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  19520. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  19521. if (startBufferIndex < endBufferIndex)
  19522. {
  19523. info.buffer->copyFrom (chan, info.startSample + validStart,
  19524. buffer,
  19525. chan, startBufferIndex,
  19526. validEnd - validStart);
  19527. }
  19528. else
  19529. {
  19530. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  19531. info.buffer->copyFrom (chan, info.startSample + validStart,
  19532. buffer,
  19533. chan, startBufferIndex,
  19534. initialSize);
  19535. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  19536. buffer,
  19537. chan, 0,
  19538. (validEnd - validStart) - initialSize);
  19539. }
  19540. }
  19541. }
  19542. nextPlayPos += info.numSamples;
  19543. if (source->isLooping() && nextPlayPos > 0)
  19544. nextPlayPos %= source->getTotalLength();
  19545. }
  19546. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19547. if (thread != 0)
  19548. thread->notify();
  19549. }
  19550. int BufferingAudioSource::getNextReadPosition() const
  19551. {
  19552. return (source->isLooping() && nextPlayPos > 0)
  19553. ? nextPlayPos % source->getTotalLength()
  19554. : nextPlayPos;
  19555. }
  19556. void BufferingAudioSource::setNextReadPosition (int newPosition)
  19557. {
  19558. const ScopedLock sl (bufferStartPosLock);
  19559. nextPlayPos = newPosition;
  19560. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19561. if (thread != 0)
  19562. thread->notify();
  19563. }
  19564. bool BufferingAudioSource::readNextBufferChunk()
  19565. {
  19566. int newBVS, newBVE, sectionToReadStart, sectionToReadEnd;
  19567. {
  19568. const ScopedLock sl (bufferStartPosLock);
  19569. if (wasSourceLooping != isLooping())
  19570. {
  19571. wasSourceLooping = isLooping();
  19572. bufferValidStart = 0;
  19573. bufferValidEnd = 0;
  19574. }
  19575. newBVS = jmax (0, nextPlayPos);
  19576. newBVE = newBVS + buffer.getNumSamples() - 4;
  19577. sectionToReadStart = 0;
  19578. sectionToReadEnd = 0;
  19579. const int maxChunkSize = 2048;
  19580. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  19581. {
  19582. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  19583. sectionToReadStart = newBVS;
  19584. sectionToReadEnd = newBVE;
  19585. bufferValidStart = 0;
  19586. bufferValidEnd = 0;
  19587. }
  19588. else if (abs (newBVS - bufferValidStart) > 512
  19589. || abs (newBVE - bufferValidEnd) > 512)
  19590. {
  19591. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  19592. sectionToReadStart = bufferValidEnd;
  19593. sectionToReadEnd = newBVE;
  19594. bufferValidStart = newBVS;
  19595. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  19596. }
  19597. }
  19598. if (sectionToReadStart != sectionToReadEnd)
  19599. {
  19600. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  19601. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  19602. if (bufferIndexStart < bufferIndexEnd)
  19603. {
  19604. readBufferSection (sectionToReadStart,
  19605. sectionToReadEnd - sectionToReadStart,
  19606. bufferIndexStart);
  19607. }
  19608. else
  19609. {
  19610. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  19611. readBufferSection (sectionToReadStart,
  19612. initialSize,
  19613. bufferIndexStart);
  19614. readBufferSection (sectionToReadStart + initialSize,
  19615. (sectionToReadEnd - sectionToReadStart) - initialSize,
  19616. 0);
  19617. }
  19618. const ScopedLock sl2 (bufferStartPosLock);
  19619. bufferValidStart = newBVS;
  19620. bufferValidEnd = newBVE;
  19621. return true;
  19622. }
  19623. else
  19624. {
  19625. return false;
  19626. }
  19627. }
  19628. void BufferingAudioSource::readBufferSection (int start, int length, int bufferOffset)
  19629. {
  19630. if (source->getNextReadPosition() != start)
  19631. source->setNextReadPosition (start);
  19632. AudioSourceChannelInfo info;
  19633. info.buffer = &buffer;
  19634. info.startSample = bufferOffset;
  19635. info.numSamples = length;
  19636. source->getNextAudioBlock (info);
  19637. }
  19638. END_JUCE_NAMESPACE
  19639. /*** End of inlined file: juce_BufferingAudioSource.cpp ***/
  19640. /*** Start of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19641. BEGIN_JUCE_NAMESPACE
  19642. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  19643. const bool deleteSourceWhenDeleted_)
  19644. : requiredNumberOfChannels (2),
  19645. source (source_),
  19646. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19647. buffer (2, 16)
  19648. {
  19649. remappedInfo.buffer = &buffer;
  19650. remappedInfo.startSample = 0;
  19651. }
  19652. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  19653. {
  19654. if (deleteSourceWhenDeleted)
  19655. delete source;
  19656. }
  19657. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_)
  19658. {
  19659. const ScopedLock sl (lock);
  19660. requiredNumberOfChannels = requiredNumberOfChannels_;
  19661. }
  19662. void ChannelRemappingAudioSource::clearAllMappings()
  19663. {
  19664. const ScopedLock sl (lock);
  19665. remappedInputs.clear();
  19666. remappedOutputs.clear();
  19667. }
  19668. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex)
  19669. {
  19670. const ScopedLock sl (lock);
  19671. while (remappedInputs.size() < destIndex)
  19672. remappedInputs.add (-1);
  19673. remappedInputs.set (destIndex, sourceIndex);
  19674. }
  19675. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex)
  19676. {
  19677. const ScopedLock sl (lock);
  19678. while (remappedOutputs.size() < sourceIndex)
  19679. remappedOutputs.add (-1);
  19680. remappedOutputs.set (sourceIndex, destIndex);
  19681. }
  19682. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const
  19683. {
  19684. const ScopedLock sl (lock);
  19685. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  19686. return remappedInputs.getUnchecked (inputChannelIndex);
  19687. return -1;
  19688. }
  19689. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const
  19690. {
  19691. const ScopedLock sl (lock);
  19692. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  19693. return remappedOutputs .getUnchecked (outputChannelIndex);
  19694. return -1;
  19695. }
  19696. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19697. {
  19698. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19699. }
  19700. void ChannelRemappingAudioSource::releaseResources()
  19701. {
  19702. source->releaseResources();
  19703. }
  19704. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19705. {
  19706. const ScopedLock sl (lock);
  19707. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  19708. const int numChans = bufferToFill.buffer->getNumChannels();
  19709. int i;
  19710. for (i = 0; i < buffer.getNumChannels(); ++i)
  19711. {
  19712. const int remappedChan = getRemappedInputChannel (i);
  19713. if (remappedChan >= 0 && remappedChan < numChans)
  19714. {
  19715. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  19716. remappedChan,
  19717. bufferToFill.startSample,
  19718. bufferToFill.numSamples);
  19719. }
  19720. else
  19721. {
  19722. buffer.clear (i, 0, bufferToFill.numSamples);
  19723. }
  19724. }
  19725. remappedInfo.numSamples = bufferToFill.numSamples;
  19726. source->getNextAudioBlock (remappedInfo);
  19727. bufferToFill.clearActiveBufferRegion();
  19728. for (i = 0; i < requiredNumberOfChannels; ++i)
  19729. {
  19730. const int remappedChan = getRemappedOutputChannel (i);
  19731. if (remappedChan >= 0 && remappedChan < numChans)
  19732. {
  19733. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  19734. buffer, i, 0, bufferToFill.numSamples);
  19735. }
  19736. }
  19737. }
  19738. XmlElement* ChannelRemappingAudioSource::createXml() const
  19739. {
  19740. XmlElement* e = new XmlElement ("MAPPINGS");
  19741. String ins, outs;
  19742. int i;
  19743. const ScopedLock sl (lock);
  19744. for (i = 0; i < remappedInputs.size(); ++i)
  19745. ins << remappedInputs.getUnchecked(i) << ' ';
  19746. for (i = 0; i < remappedOutputs.size(); ++i)
  19747. outs << remappedOutputs.getUnchecked(i) << ' ';
  19748. e->setAttribute ("inputs", ins.trimEnd());
  19749. e->setAttribute ("outputs", outs.trimEnd());
  19750. return e;
  19751. }
  19752. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e)
  19753. {
  19754. if (e.hasTagName ("MAPPINGS"))
  19755. {
  19756. const ScopedLock sl (lock);
  19757. clearAllMappings();
  19758. StringArray ins, outs;
  19759. ins.addTokens (e.getStringAttribute ("inputs"), false);
  19760. outs.addTokens (e.getStringAttribute ("outputs"), false);
  19761. int i;
  19762. for (i = 0; i < ins.size(); ++i)
  19763. remappedInputs.add (ins[i].getIntValue());
  19764. for (i = 0; i < outs.size(); ++i)
  19765. remappedOutputs.add (outs[i].getIntValue());
  19766. }
  19767. }
  19768. END_JUCE_NAMESPACE
  19769. /*** End of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19770. /*** Start of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19771. BEGIN_JUCE_NAMESPACE
  19772. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  19773. const bool deleteInputWhenDeleted_)
  19774. : input (inputSource),
  19775. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  19776. {
  19777. jassert (inputSource != 0);
  19778. for (int i = 2; --i >= 0;)
  19779. iirFilters.add (new IIRFilter());
  19780. }
  19781. IIRFilterAudioSource::~IIRFilterAudioSource()
  19782. {
  19783. if (deleteInputWhenDeleted)
  19784. delete input;
  19785. }
  19786. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  19787. {
  19788. for (int i = iirFilters.size(); --i >= 0;)
  19789. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  19790. }
  19791. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19792. {
  19793. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19794. for (int i = iirFilters.size(); --i >= 0;)
  19795. iirFilters.getUnchecked(i)->reset();
  19796. }
  19797. void IIRFilterAudioSource::releaseResources()
  19798. {
  19799. input->releaseResources();
  19800. }
  19801. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19802. {
  19803. input->getNextAudioBlock (bufferToFill);
  19804. const int numChannels = bufferToFill.buffer->getNumChannels();
  19805. while (numChannels > iirFilters.size())
  19806. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  19807. for (int i = 0; i < numChannels; ++i)
  19808. iirFilters.getUnchecked(i)
  19809. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  19810. bufferToFill.numSamples);
  19811. }
  19812. END_JUCE_NAMESPACE
  19813. /*** End of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19814. /*** Start of inlined file: juce_MixerAudioSource.cpp ***/
  19815. BEGIN_JUCE_NAMESPACE
  19816. MixerAudioSource::MixerAudioSource()
  19817. : tempBuffer (2, 0),
  19818. currentSampleRate (0.0),
  19819. bufferSizeExpected (0)
  19820. {
  19821. }
  19822. MixerAudioSource::~MixerAudioSource()
  19823. {
  19824. removeAllInputs();
  19825. }
  19826. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  19827. {
  19828. if (input != 0 && ! inputs.contains (input))
  19829. {
  19830. double localRate;
  19831. int localBufferSize;
  19832. {
  19833. const ScopedLock sl (lock);
  19834. localRate = currentSampleRate;
  19835. localBufferSize = bufferSizeExpected;
  19836. }
  19837. if (localRate != 0.0)
  19838. input->prepareToPlay (localBufferSize, localRate);
  19839. const ScopedLock sl (lock);
  19840. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  19841. inputs.add (input);
  19842. }
  19843. }
  19844. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  19845. {
  19846. if (input != 0)
  19847. {
  19848. int index;
  19849. {
  19850. const ScopedLock sl (lock);
  19851. index = inputs.indexOf (input);
  19852. if (index >= 0)
  19853. {
  19854. inputsToDelete.shiftBits (index, 1);
  19855. inputs.remove (index);
  19856. }
  19857. }
  19858. if (index >= 0)
  19859. {
  19860. input->releaseResources();
  19861. if (deleteInput)
  19862. delete input;
  19863. }
  19864. }
  19865. }
  19866. void MixerAudioSource::removeAllInputs()
  19867. {
  19868. OwnedArray<AudioSource> toDelete;
  19869. {
  19870. const ScopedLock sl (lock);
  19871. for (int i = inputs.size(); --i >= 0;)
  19872. if (inputsToDelete[i])
  19873. toDelete.add (inputs.getUnchecked(i));
  19874. }
  19875. }
  19876. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19877. {
  19878. tempBuffer.setSize (2, samplesPerBlockExpected);
  19879. const ScopedLock sl (lock);
  19880. currentSampleRate = sampleRate;
  19881. bufferSizeExpected = samplesPerBlockExpected;
  19882. for (int i = inputs.size(); --i >= 0;)
  19883. inputs.getUnchecked(i)->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19884. }
  19885. void MixerAudioSource::releaseResources()
  19886. {
  19887. const ScopedLock sl (lock);
  19888. for (int i = inputs.size(); --i >= 0;)
  19889. inputs.getUnchecked(i)->releaseResources();
  19890. tempBuffer.setSize (2, 0);
  19891. currentSampleRate = 0;
  19892. bufferSizeExpected = 0;
  19893. }
  19894. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19895. {
  19896. const ScopedLock sl (lock);
  19897. if (inputs.size() > 0)
  19898. {
  19899. inputs.getUnchecked(0)->getNextAudioBlock (info);
  19900. if (inputs.size() > 1)
  19901. {
  19902. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  19903. info.buffer->getNumSamples());
  19904. AudioSourceChannelInfo info2;
  19905. info2.buffer = &tempBuffer;
  19906. info2.numSamples = info.numSamples;
  19907. info2.startSample = 0;
  19908. for (int i = 1; i < inputs.size(); ++i)
  19909. {
  19910. inputs.getUnchecked(i)->getNextAudioBlock (info2);
  19911. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  19912. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  19913. }
  19914. }
  19915. }
  19916. else
  19917. {
  19918. info.clearActiveBufferRegion();
  19919. }
  19920. }
  19921. END_JUCE_NAMESPACE
  19922. /*** End of inlined file: juce_MixerAudioSource.cpp ***/
  19923. /*** Start of inlined file: juce_ResamplingAudioSource.cpp ***/
  19924. BEGIN_JUCE_NAMESPACE
  19925. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  19926. const bool deleteInputWhenDeleted_,
  19927. const int numChannels_)
  19928. : input (inputSource),
  19929. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  19930. ratio (1.0),
  19931. lastRatio (1.0),
  19932. buffer (numChannels_, 0),
  19933. sampsInBuffer (0),
  19934. numChannels (numChannels_)
  19935. {
  19936. jassert (input != 0);
  19937. }
  19938. ResamplingAudioSource::~ResamplingAudioSource()
  19939. {
  19940. if (deleteInputWhenDeleted)
  19941. delete input;
  19942. }
  19943. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  19944. {
  19945. jassert (samplesInPerOutputSample > 0);
  19946. const ScopedLock sl (ratioLock);
  19947. ratio = jmax (0.0, samplesInPerOutputSample);
  19948. }
  19949. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  19950. double sampleRate)
  19951. {
  19952. const ScopedLock sl (ratioLock);
  19953. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19954. buffer.setSize (numChannels, roundToInt (samplesPerBlockExpected * ratio) + 32);
  19955. buffer.clear();
  19956. sampsInBuffer = 0;
  19957. bufferPos = 0;
  19958. subSampleOffset = 0.0;
  19959. filterStates.calloc (numChannels);
  19960. srcBuffers.calloc (numChannels);
  19961. destBuffers.calloc (numChannels);
  19962. createLowPass (ratio);
  19963. resetFilters();
  19964. }
  19965. void ResamplingAudioSource::releaseResources()
  19966. {
  19967. input->releaseResources();
  19968. buffer.setSize (numChannels, 0);
  19969. }
  19970. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19971. {
  19972. const ScopedLock sl (ratioLock);
  19973. if (lastRatio != ratio)
  19974. {
  19975. createLowPass (ratio);
  19976. lastRatio = ratio;
  19977. }
  19978. const int sampsNeeded = roundToInt (info.numSamples * ratio) + 2;
  19979. int bufferSize = buffer.getNumSamples();
  19980. if (bufferSize < sampsNeeded + 8)
  19981. {
  19982. bufferPos %= bufferSize;
  19983. bufferSize = sampsNeeded + 32;
  19984. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  19985. }
  19986. bufferPos %= bufferSize;
  19987. int endOfBufferPos = bufferPos + sampsInBuffer;
  19988. const int channelsToProcess = jmin (numChannels, info.buffer->getNumChannels());
  19989. while (sampsNeeded > sampsInBuffer)
  19990. {
  19991. endOfBufferPos %= bufferSize;
  19992. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  19993. bufferSize - endOfBufferPos);
  19994. AudioSourceChannelInfo readInfo;
  19995. readInfo.buffer = &buffer;
  19996. readInfo.numSamples = numToDo;
  19997. readInfo.startSample = endOfBufferPos;
  19998. input->getNextAudioBlock (readInfo);
  19999. if (ratio > 1.0001)
  20000. {
  20001. // for down-sampling, pre-apply the filter..
  20002. for (int i = channelsToProcess; --i >= 0;)
  20003. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  20004. }
  20005. sampsInBuffer += numToDo;
  20006. endOfBufferPos += numToDo;
  20007. }
  20008. for (int channel = 0; channel < channelsToProcess; ++channel)
  20009. {
  20010. destBuffers[channel] = info.buffer->getSampleData (channel, info.startSample);
  20011. srcBuffers[channel] = buffer.getSampleData (channel, 0);
  20012. }
  20013. int nextPos = (bufferPos + 1) % bufferSize;
  20014. for (int m = info.numSamples; --m >= 0;)
  20015. {
  20016. const float alpha = (float) subSampleOffset;
  20017. const float invAlpha = 1.0f - alpha;
  20018. for (int channel = 0; channel < channelsToProcess; ++channel)
  20019. *destBuffers[channel]++ = srcBuffers[channel][bufferPos] * invAlpha + srcBuffers[channel][nextPos] * alpha;
  20020. subSampleOffset += ratio;
  20021. jassert (sampsInBuffer > 0);
  20022. while (subSampleOffset >= 1.0)
  20023. {
  20024. if (++bufferPos >= bufferSize)
  20025. bufferPos = 0;
  20026. --sampsInBuffer;
  20027. nextPos = (bufferPos + 1) % bufferSize;
  20028. subSampleOffset -= 1.0;
  20029. }
  20030. }
  20031. if (ratio < 0.9999)
  20032. {
  20033. // for up-sampling, apply the filter after transposing..
  20034. for (int i = channelsToProcess; --i >= 0;)
  20035. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  20036. }
  20037. else if (ratio <= 1.0001)
  20038. {
  20039. // if the filter's not currently being applied, keep it stoked with the last couple of samples to avoid discontinuities
  20040. for (int i = channelsToProcess; --i >= 0;)
  20041. {
  20042. const float* const endOfBuffer = info.buffer->getSampleData (i, info.startSample + info.numSamples - 1);
  20043. FilterState& fs = filterStates[i];
  20044. if (info.numSamples > 1)
  20045. {
  20046. fs.y2 = fs.x2 = *(endOfBuffer - 1);
  20047. }
  20048. else
  20049. {
  20050. fs.y2 = fs.y1;
  20051. fs.x2 = fs.x1;
  20052. }
  20053. fs.y1 = fs.x1 = *endOfBuffer;
  20054. }
  20055. }
  20056. jassert (sampsInBuffer >= 0);
  20057. }
  20058. void ResamplingAudioSource::createLowPass (const double frequencyRatio)
  20059. {
  20060. const double proportionalRate = (frequencyRatio > 1.0) ? 0.5 / frequencyRatio
  20061. : 0.5 * frequencyRatio;
  20062. const double n = 1.0 / tan (double_Pi * jmax (0.001, proportionalRate));
  20063. const double nSquared = n * n;
  20064. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  20065. setFilterCoefficients (c1,
  20066. c1 * 2.0f,
  20067. c1,
  20068. 1.0,
  20069. c1 * 2.0 * (1.0 - nSquared),
  20070. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  20071. }
  20072. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  20073. {
  20074. const double a = 1.0 / c4;
  20075. c1 *= a;
  20076. c2 *= a;
  20077. c3 *= a;
  20078. c5 *= a;
  20079. c6 *= a;
  20080. coefficients[0] = c1;
  20081. coefficients[1] = c2;
  20082. coefficients[2] = c3;
  20083. coefficients[3] = c4;
  20084. coefficients[4] = c5;
  20085. coefficients[5] = c6;
  20086. }
  20087. void ResamplingAudioSource::resetFilters()
  20088. {
  20089. zeromem (filterStates, sizeof (FilterState) * numChannels);
  20090. }
  20091. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  20092. {
  20093. while (--num >= 0)
  20094. {
  20095. const double in = *samples;
  20096. double out = coefficients[0] * in
  20097. + coefficients[1] * fs.x1
  20098. + coefficients[2] * fs.x2
  20099. - coefficients[4] * fs.y1
  20100. - coefficients[5] * fs.y2;
  20101. #if JUCE_INTEL
  20102. if (! (out < -1.0e-8 || out > 1.0e-8))
  20103. out = 0;
  20104. #endif
  20105. fs.x2 = fs.x1;
  20106. fs.x1 = in;
  20107. fs.y2 = fs.y1;
  20108. fs.y1 = out;
  20109. *samples++ = (float) out;
  20110. }
  20111. }
  20112. END_JUCE_NAMESPACE
  20113. /*** End of inlined file: juce_ResamplingAudioSource.cpp ***/
  20114. /*** Start of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20115. BEGIN_JUCE_NAMESPACE
  20116. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  20117. : frequency (1000.0),
  20118. sampleRate (44100.0),
  20119. currentPhase (0.0),
  20120. phasePerSample (0.0),
  20121. amplitude (0.5f)
  20122. {
  20123. }
  20124. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  20125. {
  20126. }
  20127. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  20128. {
  20129. amplitude = newAmplitude;
  20130. }
  20131. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  20132. {
  20133. frequency = newFrequencyHz;
  20134. phasePerSample = 0.0;
  20135. }
  20136. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  20137. double sampleRate_)
  20138. {
  20139. currentPhase = 0.0;
  20140. phasePerSample = 0.0;
  20141. sampleRate = sampleRate_;
  20142. }
  20143. void ToneGeneratorAudioSource::releaseResources()
  20144. {
  20145. }
  20146. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  20147. {
  20148. if (phasePerSample == 0.0)
  20149. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20150. for (int i = 0; i < info.numSamples; ++i)
  20151. {
  20152. const float sample = amplitude * (float) std::sin (currentPhase);
  20153. currentPhase += phasePerSample;
  20154. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  20155. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  20156. }
  20157. }
  20158. END_JUCE_NAMESPACE
  20159. /*** End of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20160. /*** Start of inlined file: juce_AudioDeviceManager.cpp ***/
  20161. BEGIN_JUCE_NAMESPACE
  20162. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  20163. : sampleRate (0),
  20164. bufferSize (0),
  20165. useDefaultInputChannels (true),
  20166. useDefaultOutputChannels (true)
  20167. {
  20168. }
  20169. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  20170. {
  20171. return outputDeviceName == other.outputDeviceName
  20172. && inputDeviceName == other.inputDeviceName
  20173. && sampleRate == other.sampleRate
  20174. && bufferSize == other.bufferSize
  20175. && inputChannels == other.inputChannels
  20176. && useDefaultInputChannels == other.useDefaultInputChannels
  20177. && outputChannels == other.outputChannels
  20178. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  20179. }
  20180. AudioDeviceManager::AudioDeviceManager()
  20181. : currentAudioDevice (0),
  20182. numInputChansNeeded (0),
  20183. numOutputChansNeeded (2),
  20184. listNeedsScanning (true),
  20185. useInputNames (false),
  20186. inputLevelMeasurementEnabledCount (0),
  20187. inputLevel (0),
  20188. tempBuffer (2, 2),
  20189. defaultMidiOutput (0),
  20190. cpuUsageMs (0),
  20191. timeToCpuScale (0)
  20192. {
  20193. callbackHandler.owner = this;
  20194. }
  20195. AudioDeviceManager::~AudioDeviceManager()
  20196. {
  20197. currentAudioDevice = 0;
  20198. defaultMidiOutput = 0;
  20199. }
  20200. void AudioDeviceManager::createDeviceTypesIfNeeded()
  20201. {
  20202. if (availableDeviceTypes.size() == 0)
  20203. {
  20204. createAudioDeviceTypes (availableDeviceTypes);
  20205. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  20206. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  20207. if (availableDeviceTypes.size() > 0)
  20208. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  20209. }
  20210. }
  20211. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  20212. {
  20213. scanDevicesIfNeeded();
  20214. return availableDeviceTypes;
  20215. }
  20216. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio();
  20217. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio();
  20218. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI();
  20219. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound();
  20220. AudioIODeviceType* juce_createAudioIODeviceType_ASIO();
  20221. AudioIODeviceType* juce_createAudioIODeviceType_ALSA();
  20222. AudioIODeviceType* juce_createAudioIODeviceType_JACK();
  20223. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  20224. {
  20225. (void) list; // (to avoid 'unused param' warnings)
  20226. #if JUCE_WINDOWS
  20227. #if JUCE_WASAPI
  20228. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  20229. list.add (juce_createAudioIODeviceType_WASAPI());
  20230. #endif
  20231. #if JUCE_DIRECTSOUND
  20232. list.add (juce_createAudioIODeviceType_DirectSound());
  20233. #endif
  20234. #if JUCE_ASIO
  20235. list.add (juce_createAudioIODeviceType_ASIO());
  20236. #endif
  20237. #endif
  20238. #if JUCE_MAC
  20239. list.add (juce_createAudioIODeviceType_CoreAudio());
  20240. #endif
  20241. #if JUCE_IOS
  20242. list.add (juce_createAudioIODeviceType_iPhoneAudio());
  20243. #endif
  20244. #if JUCE_LINUX && JUCE_ALSA
  20245. list.add (juce_createAudioIODeviceType_ALSA());
  20246. #endif
  20247. #if JUCE_LINUX && JUCE_JACK
  20248. list.add (juce_createAudioIODeviceType_JACK());
  20249. #endif
  20250. }
  20251. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  20252. const int numOutputChannelsNeeded,
  20253. const XmlElement* const e,
  20254. const bool selectDefaultDeviceOnFailure,
  20255. const String& preferredDefaultDeviceName,
  20256. const AudioDeviceSetup* preferredSetupOptions)
  20257. {
  20258. scanDevicesIfNeeded();
  20259. numInputChansNeeded = numInputChannelsNeeded;
  20260. numOutputChansNeeded = numOutputChannelsNeeded;
  20261. if (e != 0 && e->hasTagName ("DEVICESETUP"))
  20262. {
  20263. lastExplicitSettings = new XmlElement (*e);
  20264. String error;
  20265. AudioDeviceSetup setup;
  20266. if (preferredSetupOptions != 0)
  20267. setup = *preferredSetupOptions;
  20268. if (e->getStringAttribute ("audioDeviceName").isNotEmpty())
  20269. {
  20270. setup.inputDeviceName = setup.outputDeviceName
  20271. = e->getStringAttribute ("audioDeviceName");
  20272. }
  20273. else
  20274. {
  20275. setup.inputDeviceName = e->getStringAttribute ("audioInputDeviceName");
  20276. setup.outputDeviceName = e->getStringAttribute ("audioOutputDeviceName");
  20277. }
  20278. currentDeviceType = e->getStringAttribute ("deviceType");
  20279. if (currentDeviceType.isEmpty())
  20280. {
  20281. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  20282. if (type != 0)
  20283. currentDeviceType = type->getTypeName();
  20284. else if (availableDeviceTypes.size() > 0)
  20285. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  20286. }
  20287. setup.bufferSize = e->getIntAttribute ("audioDeviceBufferSize");
  20288. setup.sampleRate = e->getDoubleAttribute ("audioDeviceRate");
  20289. setup.inputChannels.parseString (e->getStringAttribute ("audioDeviceInChans", "11"), 2);
  20290. setup.outputChannels.parseString (e->getStringAttribute ("audioDeviceOutChans", "11"), 2);
  20291. setup.useDefaultInputChannels = ! e->hasAttribute ("audioDeviceInChans");
  20292. setup.useDefaultOutputChannels = ! e->hasAttribute ("audioDeviceOutChans");
  20293. error = setAudioDeviceSetup (setup, true);
  20294. midiInsFromXml.clear();
  20295. forEachXmlChildElementWithTagName (*e, c, "MIDIINPUT")
  20296. midiInsFromXml.add (c->getStringAttribute ("name"));
  20297. const StringArray allMidiIns (MidiInput::getDevices());
  20298. for (int i = allMidiIns.size(); --i >= 0;)
  20299. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  20300. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  20301. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  20302. false, preferredDefaultDeviceName);
  20303. setDefaultMidiOutput (e->getStringAttribute ("defaultMidiOutput"));
  20304. return error;
  20305. }
  20306. else
  20307. {
  20308. AudioDeviceSetup setup;
  20309. if (preferredSetupOptions != 0)
  20310. {
  20311. setup = *preferredSetupOptions;
  20312. }
  20313. else if (preferredDefaultDeviceName.isNotEmpty())
  20314. {
  20315. for (int j = availableDeviceTypes.size(); --j >= 0;)
  20316. {
  20317. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  20318. StringArray outs (type->getDeviceNames (false));
  20319. int i;
  20320. for (i = 0; i < outs.size(); ++i)
  20321. {
  20322. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  20323. {
  20324. setup.outputDeviceName = outs[i];
  20325. break;
  20326. }
  20327. }
  20328. StringArray ins (type->getDeviceNames (true));
  20329. for (i = 0; i < ins.size(); ++i)
  20330. {
  20331. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  20332. {
  20333. setup.inputDeviceName = ins[i];
  20334. break;
  20335. }
  20336. }
  20337. }
  20338. }
  20339. insertDefaultDeviceNames (setup);
  20340. return setAudioDeviceSetup (setup, false);
  20341. }
  20342. }
  20343. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  20344. {
  20345. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20346. if (type != 0)
  20347. {
  20348. if (setup.outputDeviceName.isEmpty())
  20349. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  20350. if (setup.inputDeviceName.isEmpty())
  20351. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  20352. }
  20353. }
  20354. XmlElement* AudioDeviceManager::createStateXml() const
  20355. {
  20356. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  20357. }
  20358. void AudioDeviceManager::scanDevicesIfNeeded()
  20359. {
  20360. if (listNeedsScanning)
  20361. {
  20362. listNeedsScanning = false;
  20363. createDeviceTypesIfNeeded();
  20364. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20365. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  20366. }
  20367. }
  20368. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  20369. {
  20370. scanDevicesIfNeeded();
  20371. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20372. {
  20373. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  20374. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  20375. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  20376. {
  20377. return type;
  20378. }
  20379. }
  20380. return 0;
  20381. }
  20382. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  20383. {
  20384. setup = currentSetup;
  20385. }
  20386. void AudioDeviceManager::deleteCurrentDevice()
  20387. {
  20388. currentAudioDevice = 0;
  20389. currentSetup.inputDeviceName = String::empty;
  20390. currentSetup.outputDeviceName = String::empty;
  20391. }
  20392. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  20393. const bool treatAsChosenDevice)
  20394. {
  20395. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20396. {
  20397. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  20398. && currentDeviceType != type)
  20399. {
  20400. currentDeviceType = type;
  20401. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  20402. insertDefaultDeviceNames (s);
  20403. setAudioDeviceSetup (s, treatAsChosenDevice);
  20404. sendChangeMessage (this);
  20405. break;
  20406. }
  20407. }
  20408. }
  20409. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  20410. {
  20411. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20412. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  20413. return availableDeviceTypes[i];
  20414. return availableDeviceTypes[0];
  20415. }
  20416. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  20417. const bool treatAsChosenDevice)
  20418. {
  20419. jassert (&newSetup != &currentSetup); // this will have no effect
  20420. if (newSetup == currentSetup && currentAudioDevice != 0)
  20421. return String::empty;
  20422. if (! (newSetup == currentSetup))
  20423. sendChangeMessage (this);
  20424. stopDevice();
  20425. const String newInputDeviceName (numInputChansNeeded == 0 ? String::empty : newSetup.inputDeviceName);
  20426. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String::empty : newSetup.outputDeviceName);
  20427. String error;
  20428. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20429. if (type == 0 || (newInputDeviceName.isEmpty() && newOutputDeviceName.isEmpty()))
  20430. {
  20431. deleteCurrentDevice();
  20432. if (treatAsChosenDevice)
  20433. updateXml();
  20434. return String::empty;
  20435. }
  20436. if (currentSetup.inputDeviceName != newInputDeviceName
  20437. || currentSetup.outputDeviceName != newOutputDeviceName
  20438. || currentAudioDevice == 0)
  20439. {
  20440. deleteCurrentDevice();
  20441. scanDevicesIfNeeded();
  20442. if (newOutputDeviceName.isNotEmpty()
  20443. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  20444. {
  20445. return "No such device: " + newOutputDeviceName;
  20446. }
  20447. if (newInputDeviceName.isNotEmpty()
  20448. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  20449. {
  20450. return "No such device: " + newInputDeviceName;
  20451. }
  20452. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  20453. if (currentAudioDevice == 0)
  20454. 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!";
  20455. else
  20456. error = currentAudioDevice->getLastError();
  20457. if (error.isNotEmpty())
  20458. {
  20459. deleteCurrentDevice();
  20460. return error;
  20461. }
  20462. if (newSetup.useDefaultInputChannels)
  20463. {
  20464. inputChannels.clear();
  20465. inputChannels.setRange (0, numInputChansNeeded, true);
  20466. }
  20467. if (newSetup.useDefaultOutputChannels)
  20468. {
  20469. outputChannels.clear();
  20470. outputChannels.setRange (0, numOutputChansNeeded, true);
  20471. }
  20472. if (newInputDeviceName.isEmpty())
  20473. inputChannels.clear();
  20474. if (newOutputDeviceName.isEmpty())
  20475. outputChannels.clear();
  20476. }
  20477. if (! newSetup.useDefaultInputChannels)
  20478. inputChannels = newSetup.inputChannels;
  20479. if (! newSetup.useDefaultOutputChannels)
  20480. outputChannels = newSetup.outputChannels;
  20481. currentSetup = newSetup;
  20482. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  20483. error = currentAudioDevice->open (inputChannels,
  20484. outputChannels,
  20485. currentSetup.sampleRate,
  20486. currentSetup.bufferSize);
  20487. if (error.isEmpty())
  20488. {
  20489. currentDeviceType = currentAudioDevice->getTypeName();
  20490. currentAudioDevice->start (&callbackHandler);
  20491. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  20492. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  20493. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  20494. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  20495. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20496. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  20497. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  20498. if (treatAsChosenDevice)
  20499. updateXml();
  20500. }
  20501. else
  20502. {
  20503. deleteCurrentDevice();
  20504. }
  20505. return error;
  20506. }
  20507. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  20508. {
  20509. jassert (currentAudioDevice != 0);
  20510. if (rate > 0)
  20511. {
  20512. bool ok = false;
  20513. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20514. {
  20515. const double sr = currentAudioDevice->getSampleRate (i);
  20516. if (sr == rate)
  20517. ok = true;
  20518. }
  20519. if (! ok)
  20520. rate = 0;
  20521. }
  20522. if (rate == 0)
  20523. {
  20524. double lowestAbove44 = 0.0;
  20525. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20526. {
  20527. const double sr = currentAudioDevice->getSampleRate (i);
  20528. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  20529. lowestAbove44 = sr;
  20530. }
  20531. if (lowestAbove44 == 0.0)
  20532. rate = currentAudioDevice->getSampleRate (0);
  20533. else
  20534. rate = lowestAbove44;
  20535. }
  20536. return rate;
  20537. }
  20538. void AudioDeviceManager::stopDevice()
  20539. {
  20540. if (currentAudioDevice != 0)
  20541. currentAudioDevice->stop();
  20542. testSound = 0;
  20543. }
  20544. void AudioDeviceManager::closeAudioDevice()
  20545. {
  20546. stopDevice();
  20547. currentAudioDevice = 0;
  20548. }
  20549. void AudioDeviceManager::restartLastAudioDevice()
  20550. {
  20551. if (currentAudioDevice == 0)
  20552. {
  20553. if (currentSetup.inputDeviceName.isEmpty()
  20554. && currentSetup.outputDeviceName.isEmpty())
  20555. {
  20556. // This method will only reload the last device that was running
  20557. // before closeAudioDevice() was called - you need to actually open
  20558. // one first, with setAudioDevice().
  20559. jassertfalse;
  20560. return;
  20561. }
  20562. AudioDeviceSetup s (currentSetup);
  20563. setAudioDeviceSetup (s, false);
  20564. }
  20565. }
  20566. void AudioDeviceManager::updateXml()
  20567. {
  20568. lastExplicitSettings = new XmlElement ("DEVICESETUP");
  20569. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  20570. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  20571. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  20572. if (currentAudioDevice != 0)
  20573. {
  20574. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  20575. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  20576. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  20577. if (! currentSetup.useDefaultInputChannels)
  20578. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  20579. if (! currentSetup.useDefaultOutputChannels)
  20580. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  20581. }
  20582. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  20583. {
  20584. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20585. m->setAttribute ("name", enabledMidiInputs[i]->getName());
  20586. }
  20587. if (midiInsFromXml.size() > 0)
  20588. {
  20589. // Add any midi devices that have been enabled before, but which aren't currently
  20590. // open because the device has been disconnected.
  20591. const StringArray availableMidiDevices (MidiInput::getDevices());
  20592. for (int i = 0; i < midiInsFromXml.size(); ++i)
  20593. {
  20594. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  20595. {
  20596. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20597. m->setAttribute ("name", midiInsFromXml[i]);
  20598. }
  20599. }
  20600. }
  20601. if (defaultMidiOutputName.isNotEmpty())
  20602. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputName);
  20603. }
  20604. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  20605. {
  20606. {
  20607. const ScopedLock sl (audioCallbackLock);
  20608. if (callbacks.contains (newCallback))
  20609. return;
  20610. }
  20611. if (currentAudioDevice != 0 && newCallback != 0)
  20612. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  20613. const ScopedLock sl (audioCallbackLock);
  20614. callbacks.add (newCallback);
  20615. }
  20616. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callback)
  20617. {
  20618. if (callback != 0)
  20619. {
  20620. bool needsDeinitialising = currentAudioDevice != 0;
  20621. {
  20622. const ScopedLock sl (audioCallbackLock);
  20623. needsDeinitialising = needsDeinitialising && callbacks.contains (callback);
  20624. callbacks.removeValue (callback);
  20625. }
  20626. if (needsDeinitialising)
  20627. callback->audioDeviceStopped();
  20628. }
  20629. }
  20630. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  20631. int numInputChannels,
  20632. float** outputChannelData,
  20633. int numOutputChannels,
  20634. int numSamples)
  20635. {
  20636. const ScopedLock sl (audioCallbackLock);
  20637. if (inputLevelMeasurementEnabledCount > 0)
  20638. {
  20639. for (int j = 0; j < numSamples; ++j)
  20640. {
  20641. float s = 0;
  20642. for (int i = 0; i < numInputChannels; ++i)
  20643. s += std::abs (inputChannelData[i][j]);
  20644. s /= numInputChannels;
  20645. const double decayFactor = 0.99992;
  20646. if (s > inputLevel)
  20647. inputLevel = s;
  20648. else if (inputLevel > 0.001f)
  20649. inputLevel *= decayFactor;
  20650. else
  20651. inputLevel = 0;
  20652. }
  20653. }
  20654. if (callbacks.size() > 0)
  20655. {
  20656. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  20657. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  20658. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20659. outputChannelData, numOutputChannels, numSamples);
  20660. float** const tempChans = tempBuffer.getArrayOfChannels();
  20661. for (int i = callbacks.size(); --i > 0;)
  20662. {
  20663. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20664. tempChans, numOutputChannels, numSamples);
  20665. for (int chan = 0; chan < numOutputChannels; ++chan)
  20666. {
  20667. const float* const src = tempChans [chan];
  20668. float* const dst = outputChannelData [chan];
  20669. if (src != 0 && dst != 0)
  20670. for (int j = 0; j < numSamples; ++j)
  20671. dst[j] += src[j];
  20672. }
  20673. }
  20674. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  20675. const double filterAmount = 0.2;
  20676. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  20677. }
  20678. else
  20679. {
  20680. for (int i = 0; i < numOutputChannels; ++i)
  20681. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  20682. }
  20683. if (testSound != 0)
  20684. {
  20685. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  20686. const float* const src = testSound->getSampleData (0, testSoundPosition);
  20687. for (int i = 0; i < numOutputChannels; ++i)
  20688. for (int j = 0; j < numSamps; ++j)
  20689. outputChannelData [i][j] += src[j];
  20690. testSoundPosition += numSamps;
  20691. if (testSoundPosition >= testSound->getNumSamples())
  20692. testSound = 0;
  20693. }
  20694. }
  20695. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  20696. {
  20697. cpuUsageMs = 0;
  20698. const double sampleRate = device->getCurrentSampleRate();
  20699. const int blockSize = device->getCurrentBufferSizeSamples();
  20700. if (sampleRate > 0.0 && blockSize > 0)
  20701. {
  20702. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  20703. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  20704. }
  20705. {
  20706. const ScopedLock sl (audioCallbackLock);
  20707. for (int i = callbacks.size(); --i >= 0;)
  20708. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  20709. }
  20710. sendChangeMessage (this);
  20711. }
  20712. void AudioDeviceManager::audioDeviceStoppedInt()
  20713. {
  20714. cpuUsageMs = 0;
  20715. timeToCpuScale = 0;
  20716. sendChangeMessage (this);
  20717. const ScopedLock sl (audioCallbackLock);
  20718. for (int i = callbacks.size(); --i >= 0;)
  20719. callbacks.getUnchecked(i)->audioDeviceStopped();
  20720. }
  20721. double AudioDeviceManager::getCpuUsage() const
  20722. {
  20723. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  20724. }
  20725. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  20726. const bool enabled)
  20727. {
  20728. if (enabled != isMidiInputEnabled (name))
  20729. {
  20730. if (enabled)
  20731. {
  20732. const int index = MidiInput::getDevices().indexOf (name);
  20733. if (index >= 0)
  20734. {
  20735. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  20736. if (min != 0)
  20737. {
  20738. enabledMidiInputs.add (min);
  20739. min->start();
  20740. }
  20741. }
  20742. }
  20743. else
  20744. {
  20745. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20746. if (enabledMidiInputs[i]->getName() == name)
  20747. enabledMidiInputs.remove (i);
  20748. }
  20749. updateXml();
  20750. sendChangeMessage (this);
  20751. }
  20752. }
  20753. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  20754. {
  20755. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20756. if (enabledMidiInputs[i]->getName() == name)
  20757. return true;
  20758. return false;
  20759. }
  20760. void AudioDeviceManager::addMidiInputCallback (const String& name,
  20761. MidiInputCallback* callback)
  20762. {
  20763. removeMidiInputCallback (name, callback);
  20764. if (name.isEmpty())
  20765. {
  20766. midiCallbacks.add (callback);
  20767. midiCallbackDevices.add (0);
  20768. }
  20769. else
  20770. {
  20771. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20772. {
  20773. if (enabledMidiInputs[i]->getName() == name)
  20774. {
  20775. const ScopedLock sl (midiCallbackLock);
  20776. midiCallbacks.add (callback);
  20777. midiCallbackDevices.add (enabledMidiInputs[i]);
  20778. break;
  20779. }
  20780. }
  20781. }
  20782. }
  20783. void AudioDeviceManager::removeMidiInputCallback (const String& name,
  20784. MidiInputCallback* /*callback*/)
  20785. {
  20786. const ScopedLock sl (midiCallbackLock);
  20787. for (int i = midiCallbacks.size(); --i >= 0;)
  20788. {
  20789. String devName;
  20790. if (midiCallbackDevices.getUnchecked(i) != 0)
  20791. devName = midiCallbackDevices.getUnchecked(i)->getName();
  20792. if (devName == name)
  20793. {
  20794. midiCallbacks.remove (i);
  20795. midiCallbackDevices.remove (i);
  20796. }
  20797. }
  20798. }
  20799. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  20800. const MidiMessage& message)
  20801. {
  20802. if (! message.isActiveSense())
  20803. {
  20804. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  20805. const ScopedLock sl (midiCallbackLock);
  20806. for (int i = midiCallbackDevices.size(); --i >= 0;)
  20807. {
  20808. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  20809. if (md == source || (md == 0 && isDefaultSource))
  20810. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  20811. }
  20812. }
  20813. }
  20814. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  20815. {
  20816. if (defaultMidiOutputName != deviceName)
  20817. {
  20818. SortedSet <AudioIODeviceCallback*> oldCallbacks;
  20819. {
  20820. const ScopedLock sl (audioCallbackLock);
  20821. oldCallbacks = callbacks;
  20822. callbacks.clear();
  20823. }
  20824. if (currentAudioDevice != 0)
  20825. for (int i = oldCallbacks.size(); --i >= 0;)
  20826. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  20827. defaultMidiOutput = 0;
  20828. defaultMidiOutputName = deviceName;
  20829. if (deviceName.isNotEmpty())
  20830. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  20831. if (currentAudioDevice != 0)
  20832. for (int i = oldCallbacks.size(); --i >= 0;)
  20833. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  20834. {
  20835. const ScopedLock sl (audioCallbackLock);
  20836. callbacks = oldCallbacks;
  20837. }
  20838. updateXml();
  20839. sendChangeMessage (this);
  20840. }
  20841. }
  20842. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  20843. int numInputChannels,
  20844. float** outputChannelData,
  20845. int numOutputChannels,
  20846. int numSamples)
  20847. {
  20848. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  20849. }
  20850. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  20851. {
  20852. owner->audioDeviceAboutToStartInt (device);
  20853. }
  20854. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  20855. {
  20856. owner->audioDeviceStoppedInt();
  20857. }
  20858. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  20859. {
  20860. owner->handleIncomingMidiMessageInt (source, message);
  20861. }
  20862. void AudioDeviceManager::playTestSound()
  20863. {
  20864. { // cunningly nested to swap, unlock and delete in that order.
  20865. ScopedPointer <AudioSampleBuffer> oldSound;
  20866. {
  20867. const ScopedLock sl (audioCallbackLock);
  20868. oldSound = testSound;
  20869. }
  20870. }
  20871. testSoundPosition = 0;
  20872. if (currentAudioDevice != 0)
  20873. {
  20874. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  20875. const int soundLength = (int) sampleRate;
  20876. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  20877. float* samples = newSound->getSampleData (0);
  20878. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  20879. const float amplitude = 0.5f;
  20880. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20881. for (int i = 0; i < soundLength; ++i)
  20882. samples[i] = amplitude * (float) std::sin (i * phasePerSample);
  20883. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  20884. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  20885. const ScopedLock sl (audioCallbackLock);
  20886. testSound = newSound;
  20887. }
  20888. }
  20889. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  20890. {
  20891. const ScopedLock sl (audioCallbackLock);
  20892. if (enableMeasurement)
  20893. ++inputLevelMeasurementEnabledCount;
  20894. else
  20895. --inputLevelMeasurementEnabledCount;
  20896. inputLevel = 0;
  20897. }
  20898. double AudioDeviceManager::getCurrentInputLevel() const
  20899. {
  20900. jassert (inputLevelMeasurementEnabledCount > 0); // you need to call enableInputLevelMeasurement() before using this!
  20901. return inputLevel;
  20902. }
  20903. END_JUCE_NAMESPACE
  20904. /*** End of inlined file: juce_AudioDeviceManager.cpp ***/
  20905. /*** Start of inlined file: juce_AudioIODevice.cpp ***/
  20906. BEGIN_JUCE_NAMESPACE
  20907. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  20908. : name (deviceName),
  20909. typeName (typeName_)
  20910. {
  20911. }
  20912. AudioIODevice::~AudioIODevice()
  20913. {
  20914. }
  20915. bool AudioIODevice::hasControlPanel() const
  20916. {
  20917. return false;
  20918. }
  20919. bool AudioIODevice::showControlPanel()
  20920. {
  20921. jassertfalse; // this should only be called for devices which return true from
  20922. // their hasControlPanel() method.
  20923. return false;
  20924. }
  20925. END_JUCE_NAMESPACE
  20926. /*** End of inlined file: juce_AudioIODevice.cpp ***/
  20927. /*** Start of inlined file: juce_AudioIODeviceType.cpp ***/
  20928. BEGIN_JUCE_NAMESPACE
  20929. AudioIODeviceType::AudioIODeviceType (const String& name)
  20930. : typeName (name)
  20931. {
  20932. }
  20933. AudioIODeviceType::~AudioIODeviceType()
  20934. {
  20935. }
  20936. END_JUCE_NAMESPACE
  20937. /*** End of inlined file: juce_AudioIODeviceType.cpp ***/
  20938. /*** Start of inlined file: juce_MidiOutput.cpp ***/
  20939. BEGIN_JUCE_NAMESPACE
  20940. MidiOutput::MidiOutput()
  20941. : Thread ("midi out"),
  20942. internal (0),
  20943. firstMessage (0)
  20944. {
  20945. }
  20946. MidiOutput::PendingMessage::PendingMessage (const uint8* const data, const int len,
  20947. const double sampleNumber)
  20948. : message (data, len, sampleNumber)
  20949. {
  20950. }
  20951. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  20952. const double millisecondCounterToStartAt,
  20953. double samplesPerSecondForBuffer)
  20954. {
  20955. // You've got to call startBackgroundThread() for this to actually work..
  20956. jassert (isThreadRunning());
  20957. // this needs to be a value in the future - RTFM for this method!
  20958. jassert (millisecondCounterToStartAt > 0);
  20959. const double timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  20960. MidiBuffer::Iterator i (buffer);
  20961. const uint8* data;
  20962. int len, time;
  20963. while (i.getNextEvent (data, len, time))
  20964. {
  20965. const double eventTime = millisecondCounterToStartAt + timeScaleFactor * time;
  20966. PendingMessage* const m
  20967. = new PendingMessage (data, len, eventTime);
  20968. const ScopedLock sl (lock);
  20969. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  20970. {
  20971. m->next = firstMessage;
  20972. firstMessage = m;
  20973. }
  20974. else
  20975. {
  20976. PendingMessage* mm = firstMessage;
  20977. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  20978. mm = mm->next;
  20979. m->next = mm->next;
  20980. mm->next = m;
  20981. }
  20982. }
  20983. notify();
  20984. }
  20985. void MidiOutput::clearAllPendingMessages()
  20986. {
  20987. const ScopedLock sl (lock);
  20988. while (firstMessage != 0)
  20989. {
  20990. PendingMessage* const m = firstMessage;
  20991. firstMessage = firstMessage->next;
  20992. delete m;
  20993. }
  20994. }
  20995. void MidiOutput::startBackgroundThread()
  20996. {
  20997. startThread (9);
  20998. }
  20999. void MidiOutput::stopBackgroundThread()
  21000. {
  21001. stopThread (5000);
  21002. }
  21003. void MidiOutput::run()
  21004. {
  21005. while (! threadShouldExit())
  21006. {
  21007. uint32 now = Time::getMillisecondCounter();
  21008. uint32 eventTime = 0;
  21009. uint32 timeToWait = 500;
  21010. PendingMessage* message;
  21011. {
  21012. const ScopedLock sl (lock);
  21013. message = firstMessage;
  21014. if (message != 0)
  21015. {
  21016. eventTime = roundToInt (message->message.getTimeStamp());
  21017. if (eventTime > now + 20)
  21018. {
  21019. timeToWait = eventTime - (now + 20);
  21020. message = 0;
  21021. }
  21022. else
  21023. {
  21024. firstMessage = message->next;
  21025. }
  21026. }
  21027. }
  21028. if (message != 0)
  21029. {
  21030. if (eventTime > now)
  21031. {
  21032. Time::waitForMillisecondCounter (eventTime);
  21033. if (threadShouldExit())
  21034. break;
  21035. }
  21036. if (eventTime > now - 200)
  21037. sendMessageNow (message->message);
  21038. delete message;
  21039. }
  21040. else
  21041. {
  21042. jassert (timeToWait < 1000 * 30);
  21043. wait (timeToWait);
  21044. }
  21045. }
  21046. clearAllPendingMessages();
  21047. }
  21048. END_JUCE_NAMESPACE
  21049. /*** End of inlined file: juce_MidiOutput.cpp ***/
  21050. /*** Start of inlined file: juce_AudioDataConverters.cpp ***/
  21051. BEGIN_JUCE_NAMESPACE
  21052. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21053. {
  21054. const double maxVal = (double) 0x7fff;
  21055. char* intData = static_cast <char*> (dest);
  21056. if (dest != (void*) source || destBytesPerSample <= 4)
  21057. {
  21058. for (int i = 0; i < numSamples; ++i)
  21059. {
  21060. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21061. intData += destBytesPerSample;
  21062. }
  21063. }
  21064. else
  21065. {
  21066. intData += destBytesPerSample * numSamples;
  21067. for (int i = numSamples; --i >= 0;)
  21068. {
  21069. intData -= destBytesPerSample;
  21070. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21071. }
  21072. }
  21073. }
  21074. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21075. {
  21076. const double maxVal = (double) 0x7fff;
  21077. char* intData = static_cast <char*> (dest);
  21078. if (dest != (void*) source || destBytesPerSample <= 4)
  21079. {
  21080. for (int i = 0; i < numSamples; ++i)
  21081. {
  21082. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21083. intData += destBytesPerSample;
  21084. }
  21085. }
  21086. else
  21087. {
  21088. intData += destBytesPerSample * numSamples;
  21089. for (int i = numSamples; --i >= 0;)
  21090. {
  21091. intData -= destBytesPerSample;
  21092. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21093. }
  21094. }
  21095. }
  21096. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21097. {
  21098. const double maxVal = (double) 0x7fffff;
  21099. char* intData = static_cast <char*> (dest);
  21100. if (dest != (void*) source || destBytesPerSample <= 4)
  21101. {
  21102. for (int i = 0; i < numSamples; ++i)
  21103. {
  21104. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21105. intData += destBytesPerSample;
  21106. }
  21107. }
  21108. else
  21109. {
  21110. intData += destBytesPerSample * numSamples;
  21111. for (int i = numSamples; --i >= 0;)
  21112. {
  21113. intData -= destBytesPerSample;
  21114. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21115. }
  21116. }
  21117. }
  21118. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21119. {
  21120. const double maxVal = (double) 0x7fffff;
  21121. char* intData = static_cast <char*> (dest);
  21122. if (dest != (void*) source || destBytesPerSample <= 4)
  21123. {
  21124. for (int i = 0; i < numSamples; ++i)
  21125. {
  21126. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21127. intData += destBytesPerSample;
  21128. }
  21129. }
  21130. else
  21131. {
  21132. intData += destBytesPerSample * numSamples;
  21133. for (int i = numSamples; --i >= 0;)
  21134. {
  21135. intData -= destBytesPerSample;
  21136. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21137. }
  21138. }
  21139. }
  21140. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21141. {
  21142. const double maxVal = (double) 0x7fffffff;
  21143. char* intData = static_cast <char*> (dest);
  21144. if (dest != (void*) source || destBytesPerSample <= 4)
  21145. {
  21146. for (int i = 0; i < numSamples; ++i)
  21147. {
  21148. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21149. intData += destBytesPerSample;
  21150. }
  21151. }
  21152. else
  21153. {
  21154. intData += destBytesPerSample * numSamples;
  21155. for (int i = numSamples; --i >= 0;)
  21156. {
  21157. intData -= destBytesPerSample;
  21158. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21159. }
  21160. }
  21161. }
  21162. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21163. {
  21164. const double maxVal = (double) 0x7fffffff;
  21165. char* intData = static_cast <char*> (dest);
  21166. if (dest != (void*) source || destBytesPerSample <= 4)
  21167. {
  21168. for (int i = 0; i < numSamples; ++i)
  21169. {
  21170. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21171. intData += destBytesPerSample;
  21172. }
  21173. }
  21174. else
  21175. {
  21176. intData += destBytesPerSample * numSamples;
  21177. for (int i = numSamples; --i >= 0;)
  21178. {
  21179. intData -= destBytesPerSample;
  21180. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21181. }
  21182. }
  21183. }
  21184. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21185. {
  21186. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21187. char* d = static_cast <char*> (dest);
  21188. for (int i = 0; i < numSamples; ++i)
  21189. {
  21190. *(float*) d = source[i];
  21191. #if JUCE_BIG_ENDIAN
  21192. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21193. #endif
  21194. d += destBytesPerSample;
  21195. }
  21196. }
  21197. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21198. {
  21199. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21200. char* d = static_cast <char*> (dest);
  21201. for (int i = 0; i < numSamples; ++i)
  21202. {
  21203. *(float*) d = source[i];
  21204. #if JUCE_LITTLE_ENDIAN
  21205. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21206. #endif
  21207. d += destBytesPerSample;
  21208. }
  21209. }
  21210. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21211. {
  21212. const float scale = 1.0f / 0x7fff;
  21213. const char* intData = static_cast <const char*> (source);
  21214. if (source != (void*) dest || srcBytesPerSample >= 4)
  21215. {
  21216. for (int i = 0; i < numSamples; ++i)
  21217. {
  21218. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21219. intData += srcBytesPerSample;
  21220. }
  21221. }
  21222. else
  21223. {
  21224. intData += srcBytesPerSample * numSamples;
  21225. for (int i = numSamples; --i >= 0;)
  21226. {
  21227. intData -= srcBytesPerSample;
  21228. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21229. }
  21230. }
  21231. }
  21232. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21233. {
  21234. const float scale = 1.0f / 0x7fff;
  21235. const char* intData = static_cast <const char*> (source);
  21236. if (source != (void*) dest || srcBytesPerSample >= 4)
  21237. {
  21238. for (int i = 0; i < numSamples; ++i)
  21239. {
  21240. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21241. intData += srcBytesPerSample;
  21242. }
  21243. }
  21244. else
  21245. {
  21246. intData += srcBytesPerSample * numSamples;
  21247. for (int i = numSamples; --i >= 0;)
  21248. {
  21249. intData -= srcBytesPerSample;
  21250. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21251. }
  21252. }
  21253. }
  21254. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21255. {
  21256. const float scale = 1.0f / 0x7fffff;
  21257. const char* intData = static_cast <const char*> (source);
  21258. if (source != (void*) dest || srcBytesPerSample >= 4)
  21259. {
  21260. for (int i = 0; i < numSamples; ++i)
  21261. {
  21262. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21263. intData += srcBytesPerSample;
  21264. }
  21265. }
  21266. else
  21267. {
  21268. intData += srcBytesPerSample * numSamples;
  21269. for (int i = numSamples; --i >= 0;)
  21270. {
  21271. intData -= srcBytesPerSample;
  21272. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21273. }
  21274. }
  21275. }
  21276. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21277. {
  21278. const float scale = 1.0f / 0x7fffff;
  21279. const char* intData = static_cast <const char*> (source);
  21280. if (source != (void*) dest || srcBytesPerSample >= 4)
  21281. {
  21282. for (int i = 0; i < numSamples; ++i)
  21283. {
  21284. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21285. intData += srcBytesPerSample;
  21286. }
  21287. }
  21288. else
  21289. {
  21290. intData += srcBytesPerSample * numSamples;
  21291. for (int i = numSamples; --i >= 0;)
  21292. {
  21293. intData -= srcBytesPerSample;
  21294. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21295. }
  21296. }
  21297. }
  21298. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21299. {
  21300. const float scale = 1.0f / 0x7fffffff;
  21301. const char* intData = static_cast <const char*> (source);
  21302. if (source != (void*) dest || srcBytesPerSample >= 4)
  21303. {
  21304. for (int i = 0; i < numSamples; ++i)
  21305. {
  21306. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21307. intData += srcBytesPerSample;
  21308. }
  21309. }
  21310. else
  21311. {
  21312. intData += srcBytesPerSample * numSamples;
  21313. for (int i = numSamples; --i >= 0;)
  21314. {
  21315. intData -= srcBytesPerSample;
  21316. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21317. }
  21318. }
  21319. }
  21320. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21321. {
  21322. const float scale = 1.0f / 0x7fffffff;
  21323. const char* intData = static_cast <const char*> (source);
  21324. if (source != (void*) dest || srcBytesPerSample >= 4)
  21325. {
  21326. for (int i = 0; i < numSamples; ++i)
  21327. {
  21328. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21329. intData += srcBytesPerSample;
  21330. }
  21331. }
  21332. else
  21333. {
  21334. intData += srcBytesPerSample * numSamples;
  21335. for (int i = numSamples; --i >= 0;)
  21336. {
  21337. intData -= srcBytesPerSample;
  21338. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21339. }
  21340. }
  21341. }
  21342. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21343. {
  21344. const char* s = static_cast <const char*> (source);
  21345. for (int i = 0; i < numSamples; ++i)
  21346. {
  21347. dest[i] = *(float*)s;
  21348. #if JUCE_BIG_ENDIAN
  21349. uint32* const d = (uint32*) (dest + i);
  21350. *d = ByteOrder::swap (*d);
  21351. #endif
  21352. s += srcBytesPerSample;
  21353. }
  21354. }
  21355. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21356. {
  21357. const char* s = static_cast <const char*> (source);
  21358. for (int i = 0; i < numSamples; ++i)
  21359. {
  21360. dest[i] = *(float*)s;
  21361. #if JUCE_LITTLE_ENDIAN
  21362. uint32* const d = (uint32*) (dest + i);
  21363. *d = ByteOrder::swap (*d);
  21364. #endif
  21365. s += srcBytesPerSample;
  21366. }
  21367. }
  21368. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  21369. const float* const source,
  21370. void* const dest,
  21371. const int numSamples)
  21372. {
  21373. switch (destFormat)
  21374. {
  21375. case int16LE:
  21376. convertFloatToInt16LE (source, dest, numSamples);
  21377. break;
  21378. case int16BE:
  21379. convertFloatToInt16BE (source, dest, numSamples);
  21380. break;
  21381. case int24LE:
  21382. convertFloatToInt24LE (source, dest, numSamples);
  21383. break;
  21384. case int24BE:
  21385. convertFloatToInt24BE (source, dest, numSamples);
  21386. break;
  21387. case int32LE:
  21388. convertFloatToInt32LE (source, dest, numSamples);
  21389. break;
  21390. case int32BE:
  21391. convertFloatToInt32BE (source, dest, numSamples);
  21392. break;
  21393. case float32LE:
  21394. convertFloatToFloat32LE (source, dest, numSamples);
  21395. break;
  21396. case float32BE:
  21397. convertFloatToFloat32BE (source, dest, numSamples);
  21398. break;
  21399. default:
  21400. jassertfalse;
  21401. break;
  21402. }
  21403. }
  21404. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  21405. const void* const source,
  21406. float* const dest,
  21407. const int numSamples)
  21408. {
  21409. switch (sourceFormat)
  21410. {
  21411. case int16LE:
  21412. convertInt16LEToFloat (source, dest, numSamples);
  21413. break;
  21414. case int16BE:
  21415. convertInt16BEToFloat (source, dest, numSamples);
  21416. break;
  21417. case int24LE:
  21418. convertInt24LEToFloat (source, dest, numSamples);
  21419. break;
  21420. case int24BE:
  21421. convertInt24BEToFloat (source, dest, numSamples);
  21422. break;
  21423. case int32LE:
  21424. convertInt32LEToFloat (source, dest, numSamples);
  21425. break;
  21426. case int32BE:
  21427. convertInt32BEToFloat (source, dest, numSamples);
  21428. break;
  21429. case float32LE:
  21430. convertFloat32LEToFloat (source, dest, numSamples);
  21431. break;
  21432. case float32BE:
  21433. convertFloat32BEToFloat (source, dest, numSamples);
  21434. break;
  21435. default:
  21436. jassertfalse;
  21437. break;
  21438. }
  21439. }
  21440. void AudioDataConverters::interleaveSamples (const float** const source,
  21441. float* const dest,
  21442. const int numSamples,
  21443. const int numChannels)
  21444. {
  21445. for (int chan = 0; chan < numChannels; ++chan)
  21446. {
  21447. int i = chan;
  21448. const float* src = source [chan];
  21449. for (int j = 0; j < numSamples; ++j)
  21450. {
  21451. dest [i] = src [j];
  21452. i += numChannels;
  21453. }
  21454. }
  21455. }
  21456. void AudioDataConverters::deinterleaveSamples (const float* const source,
  21457. float** const dest,
  21458. const int numSamples,
  21459. const int numChannels)
  21460. {
  21461. for (int chan = 0; chan < numChannels; ++chan)
  21462. {
  21463. int i = chan;
  21464. float* dst = dest [chan];
  21465. for (int j = 0; j < numSamples; ++j)
  21466. {
  21467. dst [j] = source [i];
  21468. i += numChannels;
  21469. }
  21470. }
  21471. }
  21472. #if JUCE_UNIT_TESTS
  21473. class AudioConversionTests : public UnitTest
  21474. {
  21475. public:
  21476. AudioConversionTests() : UnitTest ("Audio data conversion") {}
  21477. template <class F1, class E1, class F2, class E2>
  21478. struct Test5
  21479. {
  21480. static void test (UnitTest& unitTest)
  21481. {
  21482. test (unitTest, false);
  21483. test (unitTest, true);
  21484. }
  21485. static void test (UnitTest& unitTest, bool inPlace)
  21486. {
  21487. const int numSamples = 2048;
  21488. int32 original [numSamples], converted [numSamples], reversed [numSamples];
  21489. {
  21490. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::NonConst> d (original);
  21491. bool clippingFailed = false;
  21492. for (int i = 0; i < numSamples / 2; ++i)
  21493. {
  21494. d.setAsFloat (Random::getSystemRandom().nextFloat() * 2.2f - 1.1f);
  21495. if (! d.isFloatingPoint())
  21496. clippingFailed = d.getAsFloat() > 1.0f || d.getAsFloat() < -1.0f || clippingFailed;
  21497. ++d;
  21498. d.setAsInt32 (Random::getSystemRandom().nextInt());
  21499. ++d;
  21500. }
  21501. unitTest.expect (! clippingFailed);
  21502. }
  21503. // convert data from the source to dest format..
  21504. ScopedPointer<AudioData::Converter> conv (new AudioData::ConverterInstance <AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const>,
  21505. AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::NonConst> >());
  21506. conv->convertSamples (inPlace ? reversed : converted, original, numSamples);
  21507. // ..and back again..
  21508. conv = new AudioData::ConverterInstance <AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::Const>,
  21509. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::NonConst> >();
  21510. if (! inPlace)
  21511. zerostruct (reversed);
  21512. conv->convertSamples (reversed, inPlace ? reversed : converted, numSamples);
  21513. {
  21514. int biggestDiff = 0;
  21515. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const> d1 (original);
  21516. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const> d2 (reversed);
  21517. const int errorMargin = 2 * AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const>::get32BitResolution()
  21518. + AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::Const>::get32BitResolution();
  21519. for (int i = 0; i < numSamples; ++i)
  21520. {
  21521. biggestDiff = jmax (biggestDiff, std::abs (d1.getAsInt32() - d2.getAsInt32()));
  21522. ++d1;
  21523. ++d2;
  21524. }
  21525. unitTest.expect (biggestDiff <= errorMargin);
  21526. }
  21527. }
  21528. };
  21529. template <class F1, class E1, class FormatType>
  21530. struct Test3
  21531. {
  21532. static void test (UnitTest& unitTest)
  21533. {
  21534. Test5 <F1, E1, FormatType, AudioData::BigEndian>::test (unitTest);
  21535. Test5 <F1, E1, FormatType, AudioData::LittleEndian>::test (unitTest);
  21536. }
  21537. };
  21538. template <class FormatType, class Endianness>
  21539. struct Test2
  21540. {
  21541. static void test (UnitTest& unitTest)
  21542. {
  21543. Test3 <FormatType, Endianness, AudioData::Int8>::test (unitTest);
  21544. Test3 <FormatType, Endianness, AudioData::UInt8>::test (unitTest);
  21545. Test3 <FormatType, Endianness, AudioData::Int16>::test (unitTest);
  21546. Test3 <FormatType, Endianness, AudioData::Int24>::test (unitTest);
  21547. Test3 <FormatType, Endianness, AudioData::Int32>::test (unitTest);
  21548. Test3 <FormatType, Endianness, AudioData::Float32>::test (unitTest);
  21549. }
  21550. };
  21551. template <class FormatType>
  21552. struct Test1
  21553. {
  21554. static void test (UnitTest& unitTest)
  21555. {
  21556. Test2 <FormatType, AudioData::BigEndian>::test (unitTest);
  21557. Test2 <FormatType, AudioData::LittleEndian>::test (unitTest);
  21558. }
  21559. };
  21560. void runTest()
  21561. {
  21562. beginTest ("Round-trip conversion");
  21563. Test1 <AudioData::Int8>::test (*this);
  21564. Test1 <AudioData::Int16>::test (*this);
  21565. Test1 <AudioData::Int24>::test (*this);
  21566. Test1 <AudioData::Int32>::test (*this);
  21567. Test1 <AudioData::Float32>::test (*this);
  21568. }
  21569. };
  21570. static AudioConversionTests audioConversionUnitTests;
  21571. #endif
  21572. END_JUCE_NAMESPACE
  21573. /*** End of inlined file: juce_AudioDataConverters.cpp ***/
  21574. /*** Start of inlined file: juce_AudioSampleBuffer.cpp ***/
  21575. BEGIN_JUCE_NAMESPACE
  21576. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  21577. const int numSamples) throw()
  21578. : numChannels (numChannels_),
  21579. size (numSamples)
  21580. {
  21581. jassert (numSamples >= 0);
  21582. jassert (numChannels_ > 0);
  21583. allocateData();
  21584. }
  21585. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  21586. : numChannels (other.numChannels),
  21587. size (other.size)
  21588. {
  21589. allocateData();
  21590. const size_t numBytes = size * sizeof (float);
  21591. for (int i = 0; i < numChannels; ++i)
  21592. memcpy (channels[i], other.channels[i], numBytes);
  21593. }
  21594. void AudioSampleBuffer::allocateData()
  21595. {
  21596. const size_t channelListSize = (numChannels + 1) * sizeof (float*);
  21597. allocatedBytes = (int) (numChannels * size * sizeof (float) + channelListSize + 32);
  21598. allocatedData.malloc (allocatedBytes);
  21599. channels = reinterpret_cast <float**> (allocatedData.getData());
  21600. float* chan = (float*) (allocatedData + channelListSize);
  21601. for (int i = 0; i < numChannels; ++i)
  21602. {
  21603. channels[i] = chan;
  21604. chan += size;
  21605. }
  21606. channels [numChannels] = 0;
  21607. }
  21608. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  21609. const int numChannels_,
  21610. const int numSamples) throw()
  21611. : numChannels (numChannels_),
  21612. size (numSamples),
  21613. allocatedBytes (0)
  21614. {
  21615. jassert (numChannels_ > 0);
  21616. allocateChannels (dataToReferTo);
  21617. }
  21618. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  21619. const int newNumChannels,
  21620. const int newNumSamples) throw()
  21621. {
  21622. jassert (newNumChannels > 0);
  21623. allocatedBytes = 0;
  21624. allocatedData.free();
  21625. numChannels = newNumChannels;
  21626. size = newNumSamples;
  21627. allocateChannels (dataToReferTo);
  21628. }
  21629. void AudioSampleBuffer::allocateChannels (float** const dataToReferTo)
  21630. {
  21631. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  21632. if (numChannels < numElementsInArray (preallocatedChannelSpace))
  21633. {
  21634. channels = static_cast <float**> (preallocatedChannelSpace);
  21635. }
  21636. else
  21637. {
  21638. allocatedData.malloc (numChannels + 1, sizeof (float*));
  21639. channels = reinterpret_cast <float**> (allocatedData.getData());
  21640. }
  21641. for (int i = 0; i < numChannels; ++i)
  21642. {
  21643. // you have to pass in the same number of valid pointers as numChannels
  21644. jassert (dataToReferTo[i] != 0);
  21645. channels[i] = dataToReferTo[i];
  21646. }
  21647. channels [numChannels] = 0;
  21648. }
  21649. AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  21650. {
  21651. if (this != &other)
  21652. {
  21653. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  21654. const size_t numBytes = size * sizeof (float);
  21655. for (int i = 0; i < numChannels; ++i)
  21656. memcpy (channels[i], other.channels[i], numBytes);
  21657. }
  21658. return *this;
  21659. }
  21660. AudioSampleBuffer::~AudioSampleBuffer() throw()
  21661. {
  21662. }
  21663. void AudioSampleBuffer::setSize (const int newNumChannels,
  21664. const int newNumSamples,
  21665. const bool keepExistingContent,
  21666. const bool clearExtraSpace,
  21667. const bool avoidReallocating) throw()
  21668. {
  21669. jassert (newNumChannels > 0);
  21670. if (newNumSamples != size || newNumChannels != numChannels)
  21671. {
  21672. const size_t channelListSize = (newNumChannels + 1) * sizeof (float*);
  21673. const size_t newTotalBytes = (newNumChannels * newNumSamples * sizeof (float)) + channelListSize + 32;
  21674. if (keepExistingContent)
  21675. {
  21676. HeapBlock <char> newData;
  21677. newData.allocate (newTotalBytes, clearExtraSpace);
  21678. const int numChansToCopy = jmin (numChannels, newNumChannels);
  21679. const size_t numBytesToCopy = sizeof (float) * jmin (newNumSamples, size);
  21680. float** const newChannels = reinterpret_cast <float**> (newData.getData());
  21681. float* newChan = reinterpret_cast <float*> (newData + channelListSize);
  21682. for (int i = 0; i < numChansToCopy; ++i)
  21683. {
  21684. memcpy (newChan, channels[i], numBytesToCopy);
  21685. newChannels[i] = newChan;
  21686. newChan += newNumSamples;
  21687. }
  21688. allocatedData.swapWith (newData);
  21689. allocatedBytes = (int) newTotalBytes;
  21690. channels = newChannels;
  21691. }
  21692. else
  21693. {
  21694. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  21695. {
  21696. if (clearExtraSpace)
  21697. zeromem (allocatedData, newTotalBytes);
  21698. }
  21699. else
  21700. {
  21701. allocatedBytes = newTotalBytes;
  21702. allocatedData.allocate (newTotalBytes, clearExtraSpace);
  21703. channels = reinterpret_cast <float**> (allocatedData.getData());
  21704. }
  21705. float* chan = reinterpret_cast <float*> (allocatedData + channelListSize);
  21706. for (int i = 0; i < newNumChannels; ++i)
  21707. {
  21708. channels[i] = chan;
  21709. chan += newNumSamples;
  21710. }
  21711. }
  21712. channels [newNumChannels] = 0;
  21713. size = newNumSamples;
  21714. numChannels = newNumChannels;
  21715. }
  21716. }
  21717. void AudioSampleBuffer::clear() throw()
  21718. {
  21719. for (int i = 0; i < numChannels; ++i)
  21720. zeromem (channels[i], size * sizeof (float));
  21721. }
  21722. void AudioSampleBuffer::clear (const int startSample,
  21723. const int numSamples) throw()
  21724. {
  21725. jassert (startSample >= 0 && startSample + numSamples <= size);
  21726. for (int i = 0; i < numChannels; ++i)
  21727. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  21728. }
  21729. void AudioSampleBuffer::clear (const int channel,
  21730. const int startSample,
  21731. const int numSamples) throw()
  21732. {
  21733. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21734. jassert (startSample >= 0 && startSample + numSamples <= size);
  21735. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  21736. }
  21737. void AudioSampleBuffer::applyGain (const int channel,
  21738. const int startSample,
  21739. int numSamples,
  21740. const float gain) throw()
  21741. {
  21742. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21743. jassert (startSample >= 0 && startSample + numSamples <= size);
  21744. if (gain != 1.0f)
  21745. {
  21746. float* d = channels [channel] + startSample;
  21747. if (gain == 0.0f)
  21748. {
  21749. zeromem (d, sizeof (float) * numSamples);
  21750. }
  21751. else
  21752. {
  21753. while (--numSamples >= 0)
  21754. *d++ *= gain;
  21755. }
  21756. }
  21757. }
  21758. void AudioSampleBuffer::applyGainRamp (const int channel,
  21759. const int startSample,
  21760. int numSamples,
  21761. float startGain,
  21762. float endGain) throw()
  21763. {
  21764. if (startGain == endGain)
  21765. {
  21766. applyGain (channel, startSample, numSamples, startGain);
  21767. }
  21768. else
  21769. {
  21770. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21771. jassert (startSample >= 0 && startSample + numSamples <= size);
  21772. const float increment = (endGain - startGain) / numSamples;
  21773. float* d = channels [channel] + startSample;
  21774. while (--numSamples >= 0)
  21775. {
  21776. *d++ *= startGain;
  21777. startGain += increment;
  21778. }
  21779. }
  21780. }
  21781. void AudioSampleBuffer::applyGain (const int startSample,
  21782. const int numSamples,
  21783. const float gain) throw()
  21784. {
  21785. for (int i = 0; i < numChannels; ++i)
  21786. applyGain (i, startSample, numSamples, gain);
  21787. }
  21788. void AudioSampleBuffer::addFrom (const int destChannel,
  21789. const int destStartSample,
  21790. const AudioSampleBuffer& source,
  21791. const int sourceChannel,
  21792. const int sourceStartSample,
  21793. int numSamples,
  21794. const float gain) throw()
  21795. {
  21796. jassert (&source != this || sourceChannel != destChannel);
  21797. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21798. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21799. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  21800. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21801. if (gain != 0.0f && numSamples > 0)
  21802. {
  21803. float* d = channels [destChannel] + destStartSample;
  21804. const float* s = source.channels [sourceChannel] + sourceStartSample;
  21805. if (gain != 1.0f)
  21806. {
  21807. while (--numSamples >= 0)
  21808. *d++ += gain * *s++;
  21809. }
  21810. else
  21811. {
  21812. while (--numSamples >= 0)
  21813. *d++ += *s++;
  21814. }
  21815. }
  21816. }
  21817. void AudioSampleBuffer::addFrom (const int destChannel,
  21818. const int destStartSample,
  21819. const float* source,
  21820. int numSamples,
  21821. const float gain) throw()
  21822. {
  21823. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21824. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21825. jassert (source != 0);
  21826. if (gain != 0.0f && numSamples > 0)
  21827. {
  21828. float* d = channels [destChannel] + destStartSample;
  21829. if (gain != 1.0f)
  21830. {
  21831. while (--numSamples >= 0)
  21832. *d++ += gain * *source++;
  21833. }
  21834. else
  21835. {
  21836. while (--numSamples >= 0)
  21837. *d++ += *source++;
  21838. }
  21839. }
  21840. }
  21841. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  21842. const int destStartSample,
  21843. const float* source,
  21844. int numSamples,
  21845. float startGain,
  21846. const float endGain) throw()
  21847. {
  21848. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21849. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21850. jassert (source != 0);
  21851. if (startGain == endGain)
  21852. {
  21853. addFrom (destChannel,
  21854. destStartSample,
  21855. source,
  21856. numSamples,
  21857. startGain);
  21858. }
  21859. else
  21860. {
  21861. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21862. {
  21863. const float increment = (endGain - startGain) / numSamples;
  21864. float* d = channels [destChannel] + destStartSample;
  21865. while (--numSamples >= 0)
  21866. {
  21867. *d++ += startGain * *source++;
  21868. startGain += increment;
  21869. }
  21870. }
  21871. }
  21872. }
  21873. void AudioSampleBuffer::copyFrom (const int destChannel,
  21874. const int destStartSample,
  21875. const AudioSampleBuffer& source,
  21876. const int sourceChannel,
  21877. const int sourceStartSample,
  21878. int numSamples) throw()
  21879. {
  21880. jassert (&source != this || sourceChannel != destChannel);
  21881. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21882. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21883. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  21884. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21885. if (numSamples > 0)
  21886. {
  21887. memcpy (channels [destChannel] + destStartSample,
  21888. source.channels [sourceChannel] + sourceStartSample,
  21889. sizeof (float) * numSamples);
  21890. }
  21891. }
  21892. void AudioSampleBuffer::copyFrom (const int destChannel,
  21893. const int destStartSample,
  21894. const float* source,
  21895. int numSamples) throw()
  21896. {
  21897. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21898. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21899. jassert (source != 0);
  21900. if (numSamples > 0)
  21901. {
  21902. memcpy (channels [destChannel] + destStartSample,
  21903. source,
  21904. sizeof (float) * numSamples);
  21905. }
  21906. }
  21907. void AudioSampleBuffer::copyFrom (const int destChannel,
  21908. const int destStartSample,
  21909. const float* source,
  21910. int numSamples,
  21911. const float gain) throw()
  21912. {
  21913. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21914. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21915. jassert (source != 0);
  21916. if (numSamples > 0)
  21917. {
  21918. float* d = channels [destChannel] + destStartSample;
  21919. if (gain != 1.0f)
  21920. {
  21921. if (gain == 0)
  21922. {
  21923. zeromem (d, sizeof (float) * numSamples);
  21924. }
  21925. else
  21926. {
  21927. while (--numSamples >= 0)
  21928. *d++ = gain * *source++;
  21929. }
  21930. }
  21931. else
  21932. {
  21933. memcpy (d, source, sizeof (float) * numSamples);
  21934. }
  21935. }
  21936. }
  21937. void AudioSampleBuffer::copyFromWithRamp (const int destChannel,
  21938. const int destStartSample,
  21939. const float* source,
  21940. int numSamples,
  21941. float startGain,
  21942. float endGain) throw()
  21943. {
  21944. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21945. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21946. jassert (source != 0);
  21947. if (startGain == endGain)
  21948. {
  21949. copyFrom (destChannel,
  21950. destStartSample,
  21951. source,
  21952. numSamples,
  21953. startGain);
  21954. }
  21955. else
  21956. {
  21957. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21958. {
  21959. const float increment = (endGain - startGain) / numSamples;
  21960. float* d = channels [destChannel] + destStartSample;
  21961. while (--numSamples >= 0)
  21962. {
  21963. *d++ = startGain * *source++;
  21964. startGain += increment;
  21965. }
  21966. }
  21967. }
  21968. }
  21969. void AudioSampleBuffer::findMinMax (const int channel,
  21970. const int startSample,
  21971. int numSamples,
  21972. float& minVal,
  21973. float& maxVal) const throw()
  21974. {
  21975. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21976. jassert (startSample >= 0 && startSample + numSamples <= size);
  21977. if (numSamples <= 0)
  21978. {
  21979. minVal = 0.0f;
  21980. maxVal = 0.0f;
  21981. }
  21982. else
  21983. {
  21984. const float* d = channels [channel] + startSample;
  21985. float mn = *d++;
  21986. float mx = mn;
  21987. while (--numSamples > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  21988. {
  21989. const float samp = *d++;
  21990. if (samp > mx)
  21991. mx = samp;
  21992. if (samp < mn)
  21993. mn = samp;
  21994. }
  21995. maxVal = mx;
  21996. minVal = mn;
  21997. }
  21998. }
  21999. float AudioSampleBuffer::getMagnitude (const int channel,
  22000. const int startSample,
  22001. const int numSamples) const throw()
  22002. {
  22003. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  22004. jassert (startSample >= 0 && startSample + numSamples <= size);
  22005. float mn, mx;
  22006. findMinMax (channel, startSample, numSamples, mn, mx);
  22007. return jmax (mn, -mn, mx, -mx);
  22008. }
  22009. float AudioSampleBuffer::getMagnitude (const int startSample,
  22010. const int numSamples) const throw()
  22011. {
  22012. float mag = 0.0f;
  22013. for (int i = 0; i < numChannels; ++i)
  22014. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  22015. return mag;
  22016. }
  22017. float AudioSampleBuffer::getRMSLevel (const int channel,
  22018. const int startSample,
  22019. const int numSamples) const throw()
  22020. {
  22021. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  22022. jassert (startSample >= 0 && startSample + numSamples <= size);
  22023. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  22024. return 0.0f;
  22025. const float* const data = channels [channel] + startSample;
  22026. double sum = 0.0;
  22027. for (int i = 0; i < numSamples; ++i)
  22028. {
  22029. const float sample = data [i];
  22030. sum += sample * sample;
  22031. }
  22032. return (float) std::sqrt (sum / numSamples);
  22033. }
  22034. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  22035. const int startSample,
  22036. const int numSamples,
  22037. const int readerStartSample,
  22038. const bool useLeftChan,
  22039. const bool useRightChan)
  22040. {
  22041. jassert (reader != 0);
  22042. jassert (startSample >= 0 && startSample + numSamples <= size);
  22043. if (numSamples > 0)
  22044. {
  22045. int* chans[3];
  22046. if (useLeftChan == useRightChan)
  22047. {
  22048. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22049. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? reinterpret_cast<int*> (getSampleData (1, startSample)) : 0;
  22050. }
  22051. else if (useLeftChan || (reader->numChannels == 1))
  22052. {
  22053. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22054. chans[1] = 0;
  22055. }
  22056. else if (useRightChan)
  22057. {
  22058. chans[0] = 0;
  22059. chans[1] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22060. }
  22061. chans[2] = 0;
  22062. reader->read (chans, 2, readerStartSample, numSamples, true);
  22063. if (! reader->usesFloatingPointData)
  22064. {
  22065. for (int j = 0; j < 2; ++j)
  22066. {
  22067. float* const d = reinterpret_cast <float*> (chans[j]);
  22068. if (d != 0)
  22069. {
  22070. const float multiplier = 1.0f / 0x7fffffff;
  22071. for (int i = 0; i < numSamples; ++i)
  22072. d[i] = *reinterpret_cast<int*> (d + i) * multiplier;
  22073. }
  22074. }
  22075. }
  22076. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  22077. {
  22078. // if this is a stereo buffer and the source was mono, dupe the first channel..
  22079. memcpy (getSampleData (1, startSample),
  22080. getSampleData (0, startSample),
  22081. sizeof (float) * numSamples);
  22082. }
  22083. }
  22084. }
  22085. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  22086. const int startSample,
  22087. const int numSamples) const
  22088. {
  22089. jassert (writer != 0);
  22090. writer->writeFromAudioSampleBuffer (*this, startSample, numSamples);
  22091. }
  22092. END_JUCE_NAMESPACE
  22093. /*** End of inlined file: juce_AudioSampleBuffer.cpp ***/
  22094. /*** Start of inlined file: juce_IIRFilter.cpp ***/
  22095. BEGIN_JUCE_NAMESPACE
  22096. IIRFilter::IIRFilter()
  22097. : active (false)
  22098. {
  22099. reset();
  22100. }
  22101. IIRFilter::IIRFilter (const IIRFilter& other)
  22102. : active (other.active)
  22103. {
  22104. const ScopedLock sl (other.processLock);
  22105. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  22106. reset();
  22107. }
  22108. IIRFilter::~IIRFilter()
  22109. {
  22110. }
  22111. void IIRFilter::reset() throw()
  22112. {
  22113. const ScopedLock sl (processLock);
  22114. x1 = 0;
  22115. x2 = 0;
  22116. y1 = 0;
  22117. y2 = 0;
  22118. }
  22119. float IIRFilter::processSingleSampleRaw (const float in) throw()
  22120. {
  22121. float out = coefficients[0] * in
  22122. + coefficients[1] * x1
  22123. + coefficients[2] * x2
  22124. - coefficients[4] * y1
  22125. - coefficients[5] * y2;
  22126. #if JUCE_INTEL
  22127. if (! (out < -1.0e-8 || out > 1.0e-8))
  22128. out = 0;
  22129. #endif
  22130. x2 = x1;
  22131. x1 = in;
  22132. y2 = y1;
  22133. y1 = out;
  22134. return out;
  22135. }
  22136. void IIRFilter::processSamples (float* const samples,
  22137. const int numSamples) throw()
  22138. {
  22139. const ScopedLock sl (processLock);
  22140. if (active)
  22141. {
  22142. for (int i = 0; i < numSamples; ++i)
  22143. {
  22144. const float in = samples[i];
  22145. float out = coefficients[0] * in
  22146. + coefficients[1] * x1
  22147. + coefficients[2] * x2
  22148. - coefficients[4] * y1
  22149. - coefficients[5] * y2;
  22150. #if JUCE_INTEL
  22151. if (! (out < -1.0e-8 || out > 1.0e-8))
  22152. out = 0;
  22153. #endif
  22154. x2 = x1;
  22155. x1 = in;
  22156. y2 = y1;
  22157. y1 = out;
  22158. samples[i] = out;
  22159. }
  22160. }
  22161. }
  22162. void IIRFilter::makeLowPass (const double sampleRate,
  22163. const double frequency) throw()
  22164. {
  22165. jassert (sampleRate > 0);
  22166. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  22167. const double nSquared = n * n;
  22168. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  22169. setCoefficients (c1,
  22170. c1 * 2.0f,
  22171. c1,
  22172. 1.0,
  22173. c1 * 2.0 * (1.0 - nSquared),
  22174. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22175. }
  22176. void IIRFilter::makeHighPass (const double sampleRate,
  22177. const double frequency) throw()
  22178. {
  22179. const double n = tan (double_Pi * frequency / sampleRate);
  22180. const double nSquared = n * n;
  22181. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  22182. setCoefficients (c1,
  22183. c1 * -2.0f,
  22184. c1,
  22185. 1.0,
  22186. c1 * 2.0 * (nSquared - 1.0),
  22187. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22188. }
  22189. void IIRFilter::makeLowShelf (const double sampleRate,
  22190. const double cutOffFrequency,
  22191. const double Q,
  22192. const float gainFactor) throw()
  22193. {
  22194. jassert (sampleRate > 0);
  22195. jassert (Q > 0);
  22196. const double A = jmax (0.0f, gainFactor);
  22197. const double aminus1 = A - 1.0;
  22198. const double aplus1 = A + 1.0;
  22199. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22200. const double coso = std::cos (omega);
  22201. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22202. const double aminus1TimesCoso = aminus1 * coso;
  22203. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  22204. A * 2.0 * (aminus1 - aplus1 * coso),
  22205. A * (aplus1 - aminus1TimesCoso - beta),
  22206. aplus1 + aminus1TimesCoso + beta,
  22207. -2.0 * (aminus1 + aplus1 * coso),
  22208. aplus1 + aminus1TimesCoso - beta);
  22209. }
  22210. void IIRFilter::makeHighShelf (const double sampleRate,
  22211. const double cutOffFrequency,
  22212. const double Q,
  22213. const float gainFactor) throw()
  22214. {
  22215. jassert (sampleRate > 0);
  22216. jassert (Q > 0);
  22217. const double A = jmax (0.0f, gainFactor);
  22218. const double aminus1 = A - 1.0;
  22219. const double aplus1 = A + 1.0;
  22220. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22221. const double coso = std::cos (omega);
  22222. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22223. const double aminus1TimesCoso = aminus1 * coso;
  22224. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  22225. A * -2.0 * (aminus1 + aplus1 * coso),
  22226. A * (aplus1 + aminus1TimesCoso - beta),
  22227. aplus1 - aminus1TimesCoso + beta,
  22228. 2.0 * (aminus1 - aplus1 * coso),
  22229. aplus1 - aminus1TimesCoso - beta);
  22230. }
  22231. void IIRFilter::makeBandPass (const double sampleRate,
  22232. const double centreFrequency,
  22233. const double Q,
  22234. const float gainFactor) throw()
  22235. {
  22236. jassert (sampleRate > 0);
  22237. jassert (Q > 0);
  22238. const double A = jmax (0.0f, gainFactor);
  22239. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  22240. const double alpha = 0.5 * std::sin (omega) / Q;
  22241. const double c2 = -2.0 * std::cos (omega);
  22242. const double alphaTimesA = alpha * A;
  22243. const double alphaOverA = alpha / A;
  22244. setCoefficients (1.0 + alphaTimesA,
  22245. c2,
  22246. 1.0 - alphaTimesA,
  22247. 1.0 + alphaOverA,
  22248. c2,
  22249. 1.0 - alphaOverA);
  22250. }
  22251. void IIRFilter::makeInactive() throw()
  22252. {
  22253. const ScopedLock sl (processLock);
  22254. active = false;
  22255. }
  22256. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  22257. {
  22258. const ScopedLock sl (processLock);
  22259. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  22260. active = other.active;
  22261. }
  22262. void IIRFilter::setCoefficients (double c1,
  22263. double c2,
  22264. double c3,
  22265. double c4,
  22266. double c5,
  22267. double c6) throw()
  22268. {
  22269. const double a = 1.0 / c4;
  22270. c1 *= a;
  22271. c2 *= a;
  22272. c3 *= a;
  22273. c5 *= a;
  22274. c6 *= a;
  22275. const ScopedLock sl (processLock);
  22276. coefficients[0] = (float) c1;
  22277. coefficients[1] = (float) c2;
  22278. coefficients[2] = (float) c3;
  22279. coefficients[3] = (float) c4;
  22280. coefficients[4] = (float) c5;
  22281. coefficients[5] = (float) c6;
  22282. active = true;
  22283. }
  22284. END_JUCE_NAMESPACE
  22285. /*** End of inlined file: juce_IIRFilter.cpp ***/
  22286. /*** Start of inlined file: juce_MidiBuffer.cpp ***/
  22287. BEGIN_JUCE_NAMESPACE
  22288. MidiBuffer::MidiBuffer() throw()
  22289. : bytesUsed (0)
  22290. {
  22291. }
  22292. MidiBuffer::MidiBuffer (const MidiMessage& message) throw()
  22293. : bytesUsed (0)
  22294. {
  22295. addEvent (message, 0);
  22296. }
  22297. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  22298. : data (other.data),
  22299. bytesUsed (other.bytesUsed)
  22300. {
  22301. }
  22302. MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  22303. {
  22304. bytesUsed = other.bytesUsed;
  22305. data = other.data;
  22306. return *this;
  22307. }
  22308. void MidiBuffer::swapWith (MidiBuffer& other) throw()
  22309. {
  22310. data.swapWith (other.data);
  22311. swapVariables <int> (bytesUsed, other.bytesUsed);
  22312. }
  22313. MidiBuffer::~MidiBuffer()
  22314. {
  22315. }
  22316. inline uint8* MidiBuffer::getData() const throw()
  22317. {
  22318. return static_cast <uint8*> (data.getData());
  22319. }
  22320. inline int MidiBuffer::getEventTime (const void* const d) throw()
  22321. {
  22322. return *static_cast <const int*> (d);
  22323. }
  22324. inline uint16 MidiBuffer::getEventDataSize (const void* const d) throw()
  22325. {
  22326. return *reinterpret_cast <const uint16*> (static_cast <const char*> (d) + sizeof (int));
  22327. }
  22328. inline uint16 MidiBuffer::getEventTotalSize (const void* const d) throw()
  22329. {
  22330. return getEventDataSize (d) + sizeof (int) + sizeof (uint16);
  22331. }
  22332. void MidiBuffer::clear() throw()
  22333. {
  22334. bytesUsed = 0;
  22335. }
  22336. void MidiBuffer::clear (const int startSample, const int numSamples)
  22337. {
  22338. uint8* const start = findEventAfter (getData(), startSample - 1);
  22339. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  22340. if (end > start)
  22341. {
  22342. const int bytesToMove = bytesUsed - (int) (end - getData());
  22343. if (bytesToMove > 0)
  22344. memmove (start, end, bytesToMove);
  22345. bytesUsed -= (int) (end - start);
  22346. }
  22347. }
  22348. void MidiBuffer::addEvent (const MidiMessage& m, const int sampleNumber)
  22349. {
  22350. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  22351. }
  22352. static int findActualEventLength (const uint8* const data, const int maxBytes) throw()
  22353. {
  22354. unsigned int byte = (unsigned int) *data;
  22355. int size = 0;
  22356. if (byte == 0xf0 || byte == 0xf7)
  22357. {
  22358. const uint8* d = data + 1;
  22359. while (d < data + maxBytes)
  22360. if (*d++ == 0xf7)
  22361. break;
  22362. size = (int) (d - data);
  22363. }
  22364. else if (byte == 0xff)
  22365. {
  22366. int n;
  22367. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  22368. size = jmin (maxBytes, n + 2 + bytesLeft);
  22369. }
  22370. else if (byte >= 0x80)
  22371. {
  22372. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  22373. }
  22374. return size;
  22375. }
  22376. void MidiBuffer::addEvent (const void* const newData, const int maxBytes, const int sampleNumber)
  22377. {
  22378. const int numBytes = findActualEventLength (static_cast <const uint8*> (newData), maxBytes);
  22379. if (numBytes > 0)
  22380. {
  22381. int spaceNeeded = bytesUsed + numBytes + sizeof (int) + sizeof (uint16);
  22382. data.ensureSize ((spaceNeeded + spaceNeeded / 2 + 8) & ~7);
  22383. uint8* d = findEventAfter (getData(), sampleNumber);
  22384. const int bytesToMove = bytesUsed - (int) (d - getData());
  22385. if (bytesToMove > 0)
  22386. memmove (d + numBytes + sizeof (int) + sizeof (uint16), d, bytesToMove);
  22387. *reinterpret_cast <int*> (d) = sampleNumber;
  22388. d += sizeof (int);
  22389. *reinterpret_cast <uint16*> (d) = (uint16) numBytes;
  22390. d += sizeof (uint16);
  22391. memcpy (d, newData, numBytes);
  22392. bytesUsed += numBytes + sizeof (int) + sizeof (uint16);
  22393. }
  22394. }
  22395. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  22396. const int startSample,
  22397. const int numSamples,
  22398. const int sampleDeltaToAdd)
  22399. {
  22400. Iterator i (otherBuffer);
  22401. i.setNextSamplePosition (startSample);
  22402. const uint8* eventData;
  22403. int eventSize, position;
  22404. while (i.getNextEvent (eventData, eventSize, position)
  22405. && (position < startSample + numSamples || numSamples < 0))
  22406. {
  22407. addEvent (eventData, eventSize, position + sampleDeltaToAdd);
  22408. }
  22409. }
  22410. void MidiBuffer::ensureSize (size_t minimumNumBytes)
  22411. {
  22412. data.ensureSize (minimumNumBytes);
  22413. }
  22414. bool MidiBuffer::isEmpty() const throw()
  22415. {
  22416. return bytesUsed == 0;
  22417. }
  22418. int MidiBuffer::getNumEvents() const throw()
  22419. {
  22420. int n = 0;
  22421. const uint8* d = getData();
  22422. const uint8* const end = d + bytesUsed;
  22423. while (d < end)
  22424. {
  22425. d += getEventTotalSize (d);
  22426. ++n;
  22427. }
  22428. return n;
  22429. }
  22430. int MidiBuffer::getFirstEventTime() const throw()
  22431. {
  22432. return bytesUsed > 0 ? getEventTime (data.getData()) : 0;
  22433. }
  22434. int MidiBuffer::getLastEventTime() const throw()
  22435. {
  22436. if (bytesUsed == 0)
  22437. return 0;
  22438. const uint8* d = getData();
  22439. const uint8* const endData = d + bytesUsed;
  22440. for (;;)
  22441. {
  22442. const uint8* const nextOne = d + getEventTotalSize (d);
  22443. if (nextOne >= endData)
  22444. return getEventTime (d);
  22445. d = nextOne;
  22446. }
  22447. }
  22448. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  22449. {
  22450. const uint8* const endData = getData() + bytesUsed;
  22451. while (d < endData && getEventTime (d) <= samplePosition)
  22452. d += getEventTotalSize (d);
  22453. return d;
  22454. }
  22455. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer_) throw()
  22456. : buffer (buffer_),
  22457. data (buffer_.getData())
  22458. {
  22459. }
  22460. MidiBuffer::Iterator::~Iterator() throw()
  22461. {
  22462. }
  22463. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  22464. {
  22465. data = buffer.getData();
  22466. const uint8* dataEnd = data + buffer.bytesUsed;
  22467. while (data < dataEnd && getEventTime (data) < samplePosition)
  22468. data += getEventTotalSize (data);
  22469. }
  22470. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData, int& numBytes, int& samplePosition) throw()
  22471. {
  22472. if (data >= buffer.getData() + buffer.bytesUsed)
  22473. return false;
  22474. samplePosition = getEventTime (data);
  22475. numBytes = getEventDataSize (data);
  22476. data += sizeof (int) + sizeof (uint16);
  22477. midiData = data;
  22478. data += numBytes;
  22479. return true;
  22480. }
  22481. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result, int& samplePosition) throw()
  22482. {
  22483. if (data >= buffer.getData() + buffer.bytesUsed)
  22484. return false;
  22485. samplePosition = getEventTime (data);
  22486. const int numBytes = getEventDataSize (data);
  22487. data += sizeof (int) + sizeof (uint16);
  22488. result = MidiMessage (data, numBytes, samplePosition);
  22489. data += numBytes;
  22490. return true;
  22491. }
  22492. END_JUCE_NAMESPACE
  22493. /*** End of inlined file: juce_MidiBuffer.cpp ***/
  22494. /*** Start of inlined file: juce_MidiFile.cpp ***/
  22495. BEGIN_JUCE_NAMESPACE
  22496. namespace MidiFileHelpers
  22497. {
  22498. static void writeVariableLengthInt (OutputStream& out, unsigned int v)
  22499. {
  22500. unsigned int buffer = v & 0x7F;
  22501. while ((v >>= 7) != 0)
  22502. {
  22503. buffer <<= 8;
  22504. buffer |= ((v & 0x7F) | 0x80);
  22505. }
  22506. for (;;)
  22507. {
  22508. out.writeByte ((char) buffer);
  22509. if (buffer & 0x80)
  22510. buffer >>= 8;
  22511. else
  22512. break;
  22513. }
  22514. }
  22515. static bool parseMidiHeader (const uint8* &data, short& timeFormat, short& fileType, short& numberOfTracks) throw()
  22516. {
  22517. unsigned int ch = (int) ByteOrder::bigEndianInt (data);
  22518. data += 4;
  22519. if (ch != ByteOrder::bigEndianInt ("MThd"))
  22520. {
  22521. bool ok = false;
  22522. if (ch == ByteOrder::bigEndianInt ("RIFF"))
  22523. {
  22524. for (int i = 0; i < 8; ++i)
  22525. {
  22526. ch = ByteOrder::bigEndianInt (data);
  22527. data += 4;
  22528. if (ch == ByteOrder::bigEndianInt ("MThd"))
  22529. {
  22530. ok = true;
  22531. break;
  22532. }
  22533. }
  22534. }
  22535. if (! ok)
  22536. return false;
  22537. }
  22538. unsigned int bytesRemaining = ByteOrder::bigEndianInt (data);
  22539. data += 4;
  22540. fileType = (short) ByteOrder::bigEndianShort (data);
  22541. data += 2;
  22542. numberOfTracks = (short) ByteOrder::bigEndianShort (data);
  22543. data += 2;
  22544. timeFormat = (short) ByteOrder::bigEndianShort (data);
  22545. data += 2;
  22546. bytesRemaining -= 6;
  22547. data += bytesRemaining;
  22548. return true;
  22549. }
  22550. static double convertTicksToSeconds (const double time,
  22551. const MidiMessageSequence& tempoEvents,
  22552. const int timeFormat)
  22553. {
  22554. if (timeFormat > 0)
  22555. {
  22556. int numer = 4, denom = 4;
  22557. double tempoTime = 0.0, correctedTempoTime = 0.0;
  22558. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  22559. double secsPerTick = 0.5 * tickLen;
  22560. const int numEvents = tempoEvents.getNumEvents();
  22561. for (int i = 0; i < numEvents; ++i)
  22562. {
  22563. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  22564. if (time <= m.getTimeStamp())
  22565. break;
  22566. if (timeFormat > 0)
  22567. {
  22568. correctedTempoTime = correctedTempoTime
  22569. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  22570. }
  22571. else
  22572. {
  22573. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22574. }
  22575. tempoTime = m.getTimeStamp();
  22576. if (m.isTempoMetaEvent())
  22577. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  22578. else if (m.isTimeSignatureMetaEvent())
  22579. m.getTimeSignatureInfo (numer, denom);
  22580. while (i + 1 < numEvents)
  22581. {
  22582. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  22583. if (m2.getTimeStamp() == tempoTime)
  22584. {
  22585. ++i;
  22586. if (m2.isTempoMetaEvent())
  22587. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  22588. else if (m2.isTimeSignatureMetaEvent())
  22589. m2.getTimeSignatureInfo (numer, denom);
  22590. }
  22591. else
  22592. {
  22593. break;
  22594. }
  22595. }
  22596. }
  22597. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  22598. }
  22599. else
  22600. {
  22601. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22602. }
  22603. }
  22604. // a comparator that puts all the note-offs before note-ons that have the same time
  22605. struct Sorter
  22606. {
  22607. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  22608. const MidiMessageSequence::MidiEventHolder* const second) throw()
  22609. {
  22610. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  22611. if (diff == 0)
  22612. {
  22613. if (first->message.isNoteOff() && second->message.isNoteOn())
  22614. return -1;
  22615. else if (first->message.isNoteOn() && second->message.isNoteOff())
  22616. return 1;
  22617. else
  22618. return 0;
  22619. }
  22620. else
  22621. {
  22622. return (diff > 0) ? 1 : -1;
  22623. }
  22624. }
  22625. };
  22626. }
  22627. MidiFile::MidiFile()
  22628. : timeFormat ((short) (unsigned short) 0xe728)
  22629. {
  22630. }
  22631. MidiFile::~MidiFile()
  22632. {
  22633. clear();
  22634. }
  22635. void MidiFile::clear()
  22636. {
  22637. tracks.clear();
  22638. }
  22639. int MidiFile::getNumTracks() const throw()
  22640. {
  22641. return tracks.size();
  22642. }
  22643. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  22644. {
  22645. return tracks [index];
  22646. }
  22647. void MidiFile::addTrack (const MidiMessageSequence& trackSequence)
  22648. {
  22649. tracks.add (new MidiMessageSequence (trackSequence));
  22650. }
  22651. short MidiFile::getTimeFormat() const throw()
  22652. {
  22653. return timeFormat;
  22654. }
  22655. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  22656. {
  22657. timeFormat = (short) ticks;
  22658. }
  22659. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  22660. const int subframeResolution) throw()
  22661. {
  22662. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  22663. }
  22664. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  22665. {
  22666. for (int i = tracks.size(); --i >= 0;)
  22667. {
  22668. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22669. for (int j = 0; j < numEvents; ++j)
  22670. {
  22671. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22672. if (m.isTempoMetaEvent())
  22673. tempoChangeEvents.addEvent (m);
  22674. }
  22675. }
  22676. }
  22677. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  22678. {
  22679. for (int i = tracks.size(); --i >= 0;)
  22680. {
  22681. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22682. for (int j = 0; j < numEvents; ++j)
  22683. {
  22684. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22685. if (m.isTimeSignatureMetaEvent())
  22686. timeSigEvents.addEvent (m);
  22687. }
  22688. }
  22689. }
  22690. double MidiFile::getLastTimestamp() const
  22691. {
  22692. double t = 0.0;
  22693. for (int i = tracks.size(); --i >= 0;)
  22694. t = jmax (t, tracks.getUnchecked(i)->getEndTime());
  22695. return t;
  22696. }
  22697. bool MidiFile::readFrom (InputStream& sourceStream)
  22698. {
  22699. clear();
  22700. MemoryBlock data;
  22701. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  22702. // (put a sanity-check on the file size, as midi files are generally small)
  22703. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  22704. {
  22705. size_t size = data.getSize();
  22706. const uint8* d = static_cast <const uint8*> (data.getData());
  22707. short fileType, expectedTracks;
  22708. if (size > 16 && MidiFileHelpers::parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  22709. {
  22710. size -= (int) (d - static_cast <const uint8*> (data.getData()));
  22711. int track = 0;
  22712. while (size > 0 && track < expectedTracks)
  22713. {
  22714. const int chunkType = (int) ByteOrder::bigEndianInt (d);
  22715. d += 4;
  22716. const int chunkSize = (int) ByteOrder::bigEndianInt (d);
  22717. d += 4;
  22718. if (chunkSize <= 0)
  22719. break;
  22720. if (size < 0)
  22721. return false;
  22722. if (chunkType == (int) ByteOrder::bigEndianInt ("MTrk"))
  22723. {
  22724. readNextTrack (d, chunkSize);
  22725. }
  22726. size -= chunkSize + 8;
  22727. d += chunkSize;
  22728. ++track;
  22729. }
  22730. return true;
  22731. }
  22732. }
  22733. return false;
  22734. }
  22735. void MidiFile::readNextTrack (const uint8* data, int size)
  22736. {
  22737. double time = 0;
  22738. char lastStatusByte = 0;
  22739. MidiMessageSequence result;
  22740. while (size > 0)
  22741. {
  22742. int bytesUsed;
  22743. const int delay = MidiMessage::readVariableLengthVal (data, bytesUsed);
  22744. data += bytesUsed;
  22745. size -= bytesUsed;
  22746. time += delay;
  22747. int messSize = 0;
  22748. const MidiMessage mm (data, size, messSize, lastStatusByte, time);
  22749. if (messSize <= 0)
  22750. break;
  22751. size -= messSize;
  22752. data += messSize;
  22753. result.addEvent (mm);
  22754. const char firstByte = *(mm.getRawData());
  22755. if ((firstByte & 0xf0) != 0xf0)
  22756. lastStatusByte = firstByte;
  22757. }
  22758. // use a sort that puts all the note-offs before note-ons that have the same time
  22759. MidiFileHelpers::Sorter sorter;
  22760. result.list.sort (sorter, true);
  22761. result.updateMatchedPairs();
  22762. addTrack (result);
  22763. }
  22764. void MidiFile::convertTimestampTicksToSeconds()
  22765. {
  22766. MidiMessageSequence tempoEvents;
  22767. findAllTempoEvents (tempoEvents);
  22768. findAllTimeSigEvents (tempoEvents);
  22769. for (int i = 0; i < tracks.size(); ++i)
  22770. {
  22771. MidiMessageSequence& ms = *tracks.getUnchecked(i);
  22772. for (int j = ms.getNumEvents(); --j >= 0;)
  22773. {
  22774. MidiMessage& m = ms.getEventPointer(j)->message;
  22775. m.setTimeStamp (MidiFileHelpers::convertTicksToSeconds (m.getTimeStamp(),
  22776. tempoEvents,
  22777. timeFormat));
  22778. }
  22779. }
  22780. }
  22781. bool MidiFile::writeTo (OutputStream& out)
  22782. {
  22783. out.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MThd"));
  22784. out.writeIntBigEndian (6);
  22785. out.writeShortBigEndian (1); // type
  22786. out.writeShortBigEndian ((short) tracks.size());
  22787. out.writeShortBigEndian (timeFormat);
  22788. for (int i = 0; i < tracks.size(); ++i)
  22789. writeTrack (out, i);
  22790. out.flush();
  22791. return true;
  22792. }
  22793. void MidiFile::writeTrack (OutputStream& mainOut,
  22794. const int trackNum)
  22795. {
  22796. MemoryOutputStream out;
  22797. const MidiMessageSequence& ms = *tracks[trackNum];
  22798. int lastTick = 0;
  22799. char lastStatusByte = 0;
  22800. for (int i = 0; i < ms.getNumEvents(); ++i)
  22801. {
  22802. const MidiMessage& mm = ms.getEventPointer(i)->message;
  22803. const int tick = roundToInt (mm.getTimeStamp());
  22804. const int delta = jmax (0, tick - lastTick);
  22805. MidiFileHelpers::writeVariableLengthInt (out, delta);
  22806. lastTick = tick;
  22807. const char statusByte = *(mm.getRawData());
  22808. if ((statusByte == lastStatusByte)
  22809. && ((statusByte & 0xf0) != 0xf0)
  22810. && i > 0
  22811. && mm.getRawDataSize() > 1)
  22812. {
  22813. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  22814. }
  22815. else
  22816. {
  22817. out.write (mm.getRawData(), mm.getRawDataSize());
  22818. }
  22819. lastStatusByte = statusByte;
  22820. }
  22821. out.writeByte (0);
  22822. const MidiMessage m (MidiMessage::endOfTrack());
  22823. out.write (m.getRawData(),
  22824. m.getRawDataSize());
  22825. mainOut.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MTrk"));
  22826. mainOut.writeIntBigEndian ((int) out.getDataSize());
  22827. mainOut.write (out.getData(), (int) out.getDataSize());
  22828. }
  22829. END_JUCE_NAMESPACE
  22830. /*** End of inlined file: juce_MidiFile.cpp ***/
  22831. /*** Start of inlined file: juce_MidiKeyboardState.cpp ***/
  22832. BEGIN_JUCE_NAMESPACE
  22833. MidiKeyboardState::MidiKeyboardState()
  22834. {
  22835. zerostruct (noteStates);
  22836. }
  22837. MidiKeyboardState::~MidiKeyboardState()
  22838. {
  22839. }
  22840. void MidiKeyboardState::reset()
  22841. {
  22842. const ScopedLock sl (lock);
  22843. zerostruct (noteStates);
  22844. eventsToAdd.clear();
  22845. }
  22846. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  22847. {
  22848. jassert (midiChannel >= 0 && midiChannel <= 16);
  22849. return ((unsigned int) n) < 128
  22850. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  22851. }
  22852. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  22853. {
  22854. return ((unsigned int) n) < 128
  22855. && (noteStates[n] & midiChannelMask) != 0;
  22856. }
  22857. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  22858. {
  22859. jassert (midiChannel >= 0 && midiChannel <= 16);
  22860. jassert (((unsigned int) midiNoteNumber) < 128);
  22861. const ScopedLock sl (lock);
  22862. if (((unsigned int) midiNoteNumber) < 128)
  22863. {
  22864. const int timeNow = (int) Time::getMillisecondCounter();
  22865. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  22866. eventsToAdd.clear (0, timeNow - 500);
  22867. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  22868. }
  22869. }
  22870. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  22871. {
  22872. if (((unsigned int) midiNoteNumber) < 128)
  22873. {
  22874. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  22875. for (int i = listeners.size(); --i >= 0;)
  22876. listeners.getUnchecked(i)->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  22877. }
  22878. }
  22879. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  22880. {
  22881. const ScopedLock sl (lock);
  22882. if (isNoteOn (midiChannel, midiNoteNumber))
  22883. {
  22884. const int timeNow = (int) Time::getMillisecondCounter();
  22885. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  22886. eventsToAdd.clear (0, timeNow - 500);
  22887. noteOffInternal (midiChannel, midiNoteNumber);
  22888. }
  22889. }
  22890. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  22891. {
  22892. if (isNoteOn (midiChannel, midiNoteNumber))
  22893. {
  22894. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  22895. for (int i = listeners.size(); --i >= 0;)
  22896. listeners.getUnchecked(i)->handleNoteOff (this, midiChannel, midiNoteNumber);
  22897. }
  22898. }
  22899. void MidiKeyboardState::allNotesOff (const int midiChannel)
  22900. {
  22901. const ScopedLock sl (lock);
  22902. if (midiChannel <= 0)
  22903. {
  22904. for (int i = 1; i <= 16; ++i)
  22905. allNotesOff (i);
  22906. }
  22907. else
  22908. {
  22909. for (int i = 0; i < 128; ++i)
  22910. noteOff (midiChannel, i);
  22911. }
  22912. }
  22913. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  22914. {
  22915. if (message.isNoteOn())
  22916. {
  22917. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  22918. }
  22919. else if (message.isNoteOff())
  22920. {
  22921. noteOffInternal (message.getChannel(), message.getNoteNumber());
  22922. }
  22923. else if (message.isAllNotesOff())
  22924. {
  22925. for (int i = 0; i < 128; ++i)
  22926. noteOffInternal (message.getChannel(), i);
  22927. }
  22928. }
  22929. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  22930. const int startSample,
  22931. const int numSamples,
  22932. const bool injectIndirectEvents)
  22933. {
  22934. MidiBuffer::Iterator i (buffer);
  22935. MidiMessage message (0xf4, 0.0);
  22936. int time;
  22937. const ScopedLock sl (lock);
  22938. while (i.getNextEvent (message, time))
  22939. processNextMidiEvent (message);
  22940. if (injectIndirectEvents)
  22941. {
  22942. MidiBuffer::Iterator i2 (eventsToAdd);
  22943. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  22944. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  22945. while (i2.getNextEvent (message, time))
  22946. {
  22947. const int pos = jlimit (0, numSamples - 1, roundToInt ((time - firstEventToAdd) * scaleFactor));
  22948. buffer.addEvent (message, startSample + pos);
  22949. }
  22950. }
  22951. eventsToAdd.clear();
  22952. }
  22953. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener)
  22954. {
  22955. const ScopedLock sl (lock);
  22956. listeners.addIfNotAlreadyThere (listener);
  22957. }
  22958. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener)
  22959. {
  22960. const ScopedLock sl (lock);
  22961. listeners.removeValue (listener);
  22962. }
  22963. END_JUCE_NAMESPACE
  22964. /*** End of inlined file: juce_MidiKeyboardState.cpp ***/
  22965. /*** Start of inlined file: juce_MidiMessage.cpp ***/
  22966. BEGIN_JUCE_NAMESPACE
  22967. int MidiMessage::readVariableLengthVal (const uint8* data, int& numBytesUsed) throw()
  22968. {
  22969. numBytesUsed = 0;
  22970. int v = 0;
  22971. int i;
  22972. do
  22973. {
  22974. i = (int) *data++;
  22975. if (++numBytesUsed > 6)
  22976. break;
  22977. v = (v << 7) + (i & 0x7f);
  22978. } while (i & 0x80);
  22979. return v;
  22980. }
  22981. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  22982. {
  22983. // this method only works for valid starting bytes of a short midi message
  22984. jassert (firstByte >= 0x80
  22985. && firstByte != 0xf0
  22986. && firstByte != 0xf7);
  22987. static const char messageLengths[] =
  22988. {
  22989. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22990. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22991. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22992. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22993. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22994. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  22995. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  22996. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  22997. };
  22998. return messageLengths [firstByte & 0x7f];
  22999. }
  23000. MidiMessage::MidiMessage (const void* const d, const int dataSize, const double t)
  23001. : timeStamp (t),
  23002. size (dataSize)
  23003. {
  23004. jassert (dataSize > 0);
  23005. if (dataSize <= 4)
  23006. data = static_cast<uint8*> (preallocatedData.asBytes);
  23007. else
  23008. data = new uint8 [dataSize];
  23009. memcpy (data, d, dataSize);
  23010. // check that the length matches the data..
  23011. jassert (size > 3 || data[0] >= 0xf0 || getMessageLengthFromFirstByte (data[0]) == size);
  23012. }
  23013. MidiMessage::MidiMessage (const int byte1, const double t) throw()
  23014. : timeStamp (t),
  23015. data (static_cast<uint8*> (preallocatedData.asBytes)),
  23016. size (1)
  23017. {
  23018. data[0] = (uint8) byte1;
  23019. // check that the length matches the data..
  23020. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  23021. }
  23022. MidiMessage::MidiMessage (const int byte1, const int byte2, const double t) throw()
  23023. : timeStamp (t),
  23024. data (static_cast<uint8*> (preallocatedData.asBytes)),
  23025. size (2)
  23026. {
  23027. data[0] = (uint8) byte1;
  23028. data[1] = (uint8) byte2;
  23029. // check that the length matches the data..
  23030. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  23031. }
  23032. MidiMessage::MidiMessage (const int byte1, const int byte2, const int byte3, const double t) throw()
  23033. : timeStamp (t),
  23034. data (static_cast<uint8*> (preallocatedData.asBytes)),
  23035. size (3)
  23036. {
  23037. data[0] = (uint8) byte1;
  23038. data[1] = (uint8) byte2;
  23039. data[2] = (uint8) byte3;
  23040. // check that the length matches the data..
  23041. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  23042. }
  23043. MidiMessage::MidiMessage (const MidiMessage& other)
  23044. : timeStamp (other.timeStamp),
  23045. size (other.size)
  23046. {
  23047. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23048. {
  23049. data = new uint8 [size];
  23050. memcpy (data, other.data, size);
  23051. }
  23052. else
  23053. {
  23054. data = static_cast<uint8*> (preallocatedData.asBytes);
  23055. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23056. }
  23057. }
  23058. MidiMessage::MidiMessage (const MidiMessage& other, const double newTimeStamp)
  23059. : timeStamp (newTimeStamp),
  23060. size (other.size)
  23061. {
  23062. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23063. {
  23064. data = new uint8 [size];
  23065. memcpy (data, other.data, size);
  23066. }
  23067. else
  23068. {
  23069. data = static_cast<uint8*> (preallocatedData.asBytes);
  23070. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23071. }
  23072. }
  23073. MidiMessage::MidiMessage (const void* src_, int sz, int& numBytesUsed, const uint8 lastStatusByte, double t)
  23074. : timeStamp (t),
  23075. data (static_cast<uint8*> (preallocatedData.asBytes))
  23076. {
  23077. const uint8* src = static_cast <const uint8*> (src_);
  23078. unsigned int byte = (unsigned int) *src;
  23079. if (byte < 0x80)
  23080. {
  23081. byte = (unsigned int) (uint8) lastStatusByte;
  23082. numBytesUsed = -1;
  23083. }
  23084. else
  23085. {
  23086. numBytesUsed = 0;
  23087. --sz;
  23088. ++src;
  23089. }
  23090. if (byte >= 0x80)
  23091. {
  23092. if (byte == 0xf0)
  23093. {
  23094. const uint8* d = src;
  23095. while (d < src + sz)
  23096. {
  23097. if (*d >= 0x80) // stop if we hit a status byte, and don't include it in this message
  23098. {
  23099. if (*d == 0xf7) // include an 0xf7 if we hit one
  23100. ++d;
  23101. break;
  23102. }
  23103. ++d;
  23104. }
  23105. size = 1 + (int) (d - src);
  23106. data = new uint8 [size];
  23107. *data = (uint8) byte;
  23108. memcpy (data + 1, src, size - 1);
  23109. }
  23110. else if (byte == 0xff)
  23111. {
  23112. int n;
  23113. const int bytesLeft = readVariableLengthVal (src + 1, n);
  23114. size = jmin (sz + 1, n + 2 + bytesLeft);
  23115. data = new uint8 [size];
  23116. *data = (uint8) byte;
  23117. memcpy (data + 1, src, size - 1);
  23118. }
  23119. else
  23120. {
  23121. preallocatedData.asInt32 = 0;
  23122. size = getMessageLengthFromFirstByte ((uint8) byte);
  23123. data[0] = (uint8) byte;
  23124. if (size > 1)
  23125. {
  23126. data[1] = src[0];
  23127. if (size > 2)
  23128. data[2] = src[1];
  23129. }
  23130. }
  23131. numBytesUsed += size;
  23132. }
  23133. else
  23134. {
  23135. preallocatedData.asInt32 = 0;
  23136. size = 0;
  23137. }
  23138. }
  23139. MidiMessage& MidiMessage::operator= (const MidiMessage& other)
  23140. {
  23141. if (this != &other)
  23142. {
  23143. timeStamp = other.timeStamp;
  23144. size = other.size;
  23145. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23146. delete[] data;
  23147. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23148. {
  23149. data = new uint8 [size];
  23150. memcpy (data, other.data, size);
  23151. }
  23152. else
  23153. {
  23154. data = static_cast<uint8*> (preallocatedData.asBytes);
  23155. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23156. }
  23157. }
  23158. return *this;
  23159. }
  23160. MidiMessage::~MidiMessage()
  23161. {
  23162. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23163. delete[] data;
  23164. }
  23165. int MidiMessage::getChannel() const throw()
  23166. {
  23167. if ((data[0] & 0xf0) != 0xf0)
  23168. return (data[0] & 0xf) + 1;
  23169. else
  23170. return 0;
  23171. }
  23172. bool MidiMessage::isForChannel (const int channel) const throw()
  23173. {
  23174. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23175. return ((data[0] & 0xf) == channel - 1)
  23176. && ((data[0] & 0xf0) != 0xf0);
  23177. }
  23178. void MidiMessage::setChannel (const int channel) throw()
  23179. {
  23180. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23181. if ((data[0] & 0xf0) != (uint8) 0xf0)
  23182. data[0] = (uint8) ((data[0] & (uint8)0xf0)
  23183. | (uint8)(channel - 1));
  23184. }
  23185. bool MidiMessage::isNoteOn (const bool returnTrueForVelocity0) const throw()
  23186. {
  23187. return ((data[0] & 0xf0) == 0x90)
  23188. && (returnTrueForVelocity0 || data[2] != 0);
  23189. }
  23190. bool MidiMessage::isNoteOff (const bool returnTrueForNoteOnVelocity0) const throw()
  23191. {
  23192. return ((data[0] & 0xf0) == 0x80)
  23193. || (returnTrueForNoteOnVelocity0 && (data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  23194. }
  23195. bool MidiMessage::isNoteOnOrOff() const throw()
  23196. {
  23197. const int d = data[0] & 0xf0;
  23198. return (d == 0x90) || (d == 0x80);
  23199. }
  23200. int MidiMessage::getNoteNumber() const throw()
  23201. {
  23202. return data[1];
  23203. }
  23204. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  23205. {
  23206. if (isNoteOnOrOff())
  23207. data[1] = (uint8) jlimit (0, 127, newNoteNumber);
  23208. }
  23209. uint8 MidiMessage::getVelocity() const throw()
  23210. {
  23211. if (isNoteOnOrOff())
  23212. return data[2];
  23213. else
  23214. return 0;
  23215. }
  23216. float MidiMessage::getFloatVelocity() const throw()
  23217. {
  23218. return getVelocity() * (1.0f / 127.0f);
  23219. }
  23220. void MidiMessage::setVelocity (const float newVelocity) throw()
  23221. {
  23222. if (isNoteOnOrOff())
  23223. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (newVelocity * 127.0f));
  23224. }
  23225. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  23226. {
  23227. if (isNoteOnOrOff())
  23228. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (scaleFactor * data[2]));
  23229. }
  23230. bool MidiMessage::isAftertouch() const throw()
  23231. {
  23232. return (data[0] & 0xf0) == 0xa0;
  23233. }
  23234. int MidiMessage::getAfterTouchValue() const throw()
  23235. {
  23236. return data[2];
  23237. }
  23238. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  23239. const int noteNum,
  23240. const int aftertouchValue) throw()
  23241. {
  23242. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23243. jassert (((unsigned int) noteNum) <= 127);
  23244. jassert (((unsigned int) aftertouchValue) <= 127);
  23245. return MidiMessage (0xa0 | jlimit (0, 15, channel - 1),
  23246. noteNum & 0x7f,
  23247. aftertouchValue & 0x7f);
  23248. }
  23249. bool MidiMessage::isChannelPressure() const throw()
  23250. {
  23251. return (data[0] & 0xf0) == 0xd0;
  23252. }
  23253. int MidiMessage::getChannelPressureValue() const throw()
  23254. {
  23255. jassert (isChannelPressure());
  23256. return data[1];
  23257. }
  23258. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  23259. const int pressure) throw()
  23260. {
  23261. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23262. jassert (((unsigned int) pressure) <= 127);
  23263. return MidiMessage (0xd0 | jlimit (0, 15, channel - 1),
  23264. pressure & 0x7f);
  23265. }
  23266. bool MidiMessage::isProgramChange() const throw()
  23267. {
  23268. return (data[0] & 0xf0) == 0xc0;
  23269. }
  23270. int MidiMessage::getProgramChangeNumber() const throw()
  23271. {
  23272. return data[1];
  23273. }
  23274. const MidiMessage MidiMessage::programChange (const int channel,
  23275. const int programNumber) throw()
  23276. {
  23277. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23278. return MidiMessage (0xc0 | jlimit (0, 15, channel - 1),
  23279. programNumber & 0x7f);
  23280. }
  23281. bool MidiMessage::isPitchWheel() const throw()
  23282. {
  23283. return (data[0] & 0xf0) == 0xe0;
  23284. }
  23285. int MidiMessage::getPitchWheelValue() const throw()
  23286. {
  23287. return data[1] | (data[2] << 7);
  23288. }
  23289. const MidiMessage MidiMessage::pitchWheel (const int channel,
  23290. const int position) throw()
  23291. {
  23292. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23293. jassert (((unsigned int) position) <= 0x3fff);
  23294. return MidiMessage (0xe0 | jlimit (0, 15, channel - 1),
  23295. position & 127,
  23296. (position >> 7) & 127);
  23297. }
  23298. bool MidiMessage::isController() const throw()
  23299. {
  23300. return (data[0] & 0xf0) == 0xb0;
  23301. }
  23302. int MidiMessage::getControllerNumber() const throw()
  23303. {
  23304. jassert (isController());
  23305. return data[1];
  23306. }
  23307. int MidiMessage::getControllerValue() const throw()
  23308. {
  23309. jassert (isController());
  23310. return data[2];
  23311. }
  23312. const MidiMessage MidiMessage::controllerEvent (const int channel,
  23313. const int controllerType,
  23314. const int value) throw()
  23315. {
  23316. // the channel must be between 1 and 16 inclusive
  23317. jassert (channel > 0 && channel <= 16);
  23318. return MidiMessage (0xb0 | jlimit (0, 15, channel - 1),
  23319. controllerType & 127,
  23320. value & 127);
  23321. }
  23322. const MidiMessage MidiMessage::noteOn (const int channel,
  23323. const int noteNumber,
  23324. const float velocity) throw()
  23325. {
  23326. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  23327. }
  23328. const MidiMessage MidiMessage::noteOn (const int channel,
  23329. const int noteNumber,
  23330. const uint8 velocity) throw()
  23331. {
  23332. jassert (channel > 0 && channel <= 16);
  23333. jassert (((unsigned int) noteNumber) <= 127);
  23334. return MidiMessage (0x90 | jlimit (0, 15, channel - 1),
  23335. noteNumber & 127,
  23336. jlimit (0, 127, roundToInt (velocity)));
  23337. }
  23338. const MidiMessage MidiMessage::noteOff (const int channel,
  23339. const int noteNumber) throw()
  23340. {
  23341. jassert (channel > 0 && channel <= 16);
  23342. jassert (((unsigned int) noteNumber) <= 127);
  23343. return MidiMessage (0x80 | jlimit (0, 15, channel - 1), noteNumber & 127, 0);
  23344. }
  23345. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  23346. {
  23347. return controllerEvent (channel, 123, 0);
  23348. }
  23349. bool MidiMessage::isAllNotesOff() const throw()
  23350. {
  23351. return (data[0] & 0xf0) == 0xb0
  23352. && data[1] == 123;
  23353. }
  23354. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  23355. {
  23356. return controllerEvent (channel, 120, 0);
  23357. }
  23358. bool MidiMessage::isAllSoundOff() const throw()
  23359. {
  23360. return (data[0] & 0xf0) == 0xb0
  23361. && data[1] == 120;
  23362. }
  23363. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  23364. {
  23365. return controllerEvent (channel, 121, 0);
  23366. }
  23367. const MidiMessage MidiMessage::masterVolume (const float volume)
  23368. {
  23369. const int vol = jlimit (0, 0x3fff, roundToInt (volume * 0x4000));
  23370. uint8 buf[8];
  23371. buf[0] = 0xf0;
  23372. buf[1] = 0x7f;
  23373. buf[2] = 0x7f;
  23374. buf[3] = 0x04;
  23375. buf[4] = 0x01;
  23376. buf[5] = (uint8) (vol & 0x7f);
  23377. buf[6] = (uint8) (vol >> 7);
  23378. buf[7] = 0xf7;
  23379. return MidiMessage (buf, 8);
  23380. }
  23381. bool MidiMessage::isSysEx() const throw()
  23382. {
  23383. return *data == 0xf0;
  23384. }
  23385. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData, const int dataSize)
  23386. {
  23387. MemoryBlock mm (dataSize + 2);
  23388. uint8* const m = static_cast <uint8*> (mm.getData());
  23389. m[0] = 0xf0;
  23390. memcpy (m + 1, sysexData, dataSize);
  23391. m[dataSize + 1] = 0xf7;
  23392. return MidiMessage (m, dataSize + 2);
  23393. }
  23394. const uint8* MidiMessage::getSysExData() const throw()
  23395. {
  23396. return (isSysEx()) ? getRawData() + 1 : 0;
  23397. }
  23398. int MidiMessage::getSysExDataSize() const throw()
  23399. {
  23400. return (isSysEx()) ? size - 2 : 0;
  23401. }
  23402. bool MidiMessage::isMetaEvent() const throw()
  23403. {
  23404. return *data == 0xff;
  23405. }
  23406. bool MidiMessage::isActiveSense() const throw()
  23407. {
  23408. return *data == 0xfe;
  23409. }
  23410. int MidiMessage::getMetaEventType() const throw()
  23411. {
  23412. if (*data != 0xff)
  23413. return -1;
  23414. else
  23415. return data[1];
  23416. }
  23417. int MidiMessage::getMetaEventLength() const throw()
  23418. {
  23419. if (*data == 0xff)
  23420. {
  23421. int n;
  23422. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  23423. }
  23424. return 0;
  23425. }
  23426. const uint8* MidiMessage::getMetaEventData() const throw()
  23427. {
  23428. int n;
  23429. const uint8* d = data + 2;
  23430. readVariableLengthVal (d, n);
  23431. return d + n;
  23432. }
  23433. bool MidiMessage::isTrackMetaEvent() const throw()
  23434. {
  23435. return getMetaEventType() == 0;
  23436. }
  23437. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  23438. {
  23439. return getMetaEventType() == 47;
  23440. }
  23441. bool MidiMessage::isTextMetaEvent() const throw()
  23442. {
  23443. const int t = getMetaEventType();
  23444. return t > 0 && t < 16;
  23445. }
  23446. const String MidiMessage::getTextFromTextMetaEvent() const
  23447. {
  23448. return String (reinterpret_cast <const char*> (getMetaEventData()), getMetaEventLength());
  23449. }
  23450. bool MidiMessage::isTrackNameEvent() const throw()
  23451. {
  23452. return (data[1] == 3)
  23453. && (*data == 0xff);
  23454. }
  23455. bool MidiMessage::isTempoMetaEvent() const throw()
  23456. {
  23457. return (data[1] == 81)
  23458. && (*data == 0xff);
  23459. }
  23460. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  23461. {
  23462. return (data[1] == 0x20)
  23463. && (*data == 0xff)
  23464. && (data[2] == 1);
  23465. }
  23466. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  23467. {
  23468. return data[3] + 1;
  23469. }
  23470. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  23471. {
  23472. if (! isTempoMetaEvent())
  23473. return 0.0;
  23474. const uint8* const d = getMetaEventData();
  23475. return (((unsigned int) d[0] << 16)
  23476. | ((unsigned int) d[1] << 8)
  23477. | d[2])
  23478. / 1000000.0;
  23479. }
  23480. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  23481. {
  23482. if (timeFormat > 0)
  23483. {
  23484. if (! isTempoMetaEvent())
  23485. return 0.5 / timeFormat;
  23486. return getTempoSecondsPerQuarterNote() / timeFormat;
  23487. }
  23488. else
  23489. {
  23490. const int frameCode = (-timeFormat) >> 8;
  23491. double framesPerSecond;
  23492. switch (frameCode)
  23493. {
  23494. case 24: framesPerSecond = 24.0; break;
  23495. case 25: framesPerSecond = 25.0; break;
  23496. case 29: framesPerSecond = 29.97; break;
  23497. case 30: framesPerSecond = 30.0; break;
  23498. default: framesPerSecond = 30.0; break;
  23499. }
  23500. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  23501. }
  23502. }
  23503. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  23504. {
  23505. uint8 d[8];
  23506. d[0] = 0xff;
  23507. d[1] = 81;
  23508. d[2] = 3;
  23509. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  23510. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  23511. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  23512. return MidiMessage (d, 6, 0.0);
  23513. }
  23514. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  23515. {
  23516. return (data[1] == 0x58)
  23517. && (*data == (uint8) 0xff);
  23518. }
  23519. void MidiMessage::getTimeSignatureInfo (int& numerator, int& denominator) const throw()
  23520. {
  23521. if (isTimeSignatureMetaEvent())
  23522. {
  23523. const uint8* const d = getMetaEventData();
  23524. numerator = d[0];
  23525. denominator = 1 << d[1];
  23526. }
  23527. else
  23528. {
  23529. numerator = 4;
  23530. denominator = 4;
  23531. }
  23532. }
  23533. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator, const int denominator)
  23534. {
  23535. uint8 d[8];
  23536. d[0] = 0xff;
  23537. d[1] = 0x58;
  23538. d[2] = 0x04;
  23539. d[3] = (uint8) numerator;
  23540. int n = 1;
  23541. int powerOfTwo = 0;
  23542. while (n < denominator)
  23543. {
  23544. n <<= 1;
  23545. ++powerOfTwo;
  23546. }
  23547. d[4] = (uint8) powerOfTwo;
  23548. d[5] = 0x01;
  23549. d[6] = 96;
  23550. return MidiMessage (d, 7, 0.0);
  23551. }
  23552. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  23553. {
  23554. uint8 d[8];
  23555. d[0] = 0xff;
  23556. d[1] = 0x20;
  23557. d[2] = 0x01;
  23558. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  23559. return MidiMessage (d, 4, 0.0);
  23560. }
  23561. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  23562. {
  23563. return getMetaEventType() == 89;
  23564. }
  23565. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  23566. {
  23567. return (int) *getMetaEventData();
  23568. }
  23569. const MidiMessage MidiMessage::endOfTrack() throw()
  23570. {
  23571. return MidiMessage (0xff, 0x2f, 0, 0.0);
  23572. }
  23573. bool MidiMessage::isSongPositionPointer() const throw()
  23574. {
  23575. return *data == 0xf2;
  23576. }
  23577. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  23578. {
  23579. return data[1] | (data[2] << 7);
  23580. }
  23581. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  23582. {
  23583. return MidiMessage (0xf2,
  23584. positionInMidiBeats & 127,
  23585. (positionInMidiBeats >> 7) & 127);
  23586. }
  23587. bool MidiMessage::isMidiStart() const throw()
  23588. {
  23589. return *data == 0xfa;
  23590. }
  23591. const MidiMessage MidiMessage::midiStart() throw()
  23592. {
  23593. return MidiMessage (0xfa);
  23594. }
  23595. bool MidiMessage::isMidiContinue() const throw()
  23596. {
  23597. return *data == 0xfb;
  23598. }
  23599. const MidiMessage MidiMessage::midiContinue() throw()
  23600. {
  23601. return MidiMessage (0xfb);
  23602. }
  23603. bool MidiMessage::isMidiStop() const throw()
  23604. {
  23605. return *data == 0xfc;
  23606. }
  23607. const MidiMessage MidiMessage::midiStop() throw()
  23608. {
  23609. return MidiMessage (0xfc);
  23610. }
  23611. bool MidiMessage::isMidiClock() const throw()
  23612. {
  23613. return *data == 0xf8;
  23614. }
  23615. const MidiMessage MidiMessage::midiClock() throw()
  23616. {
  23617. return MidiMessage (0xf8);
  23618. }
  23619. bool MidiMessage::isQuarterFrame() const throw()
  23620. {
  23621. return *data == 0xf1;
  23622. }
  23623. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  23624. {
  23625. return ((int) data[1]) >> 4;
  23626. }
  23627. int MidiMessage::getQuarterFrameValue() const throw()
  23628. {
  23629. return ((int) data[1]) & 0x0f;
  23630. }
  23631. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  23632. const int value) throw()
  23633. {
  23634. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  23635. }
  23636. bool MidiMessage::isFullFrame() const throw()
  23637. {
  23638. return data[0] == 0xf0
  23639. && data[1] == 0x7f
  23640. && size >= 10
  23641. && data[3] == 0x01
  23642. && data[4] == 0x01;
  23643. }
  23644. void MidiMessage::getFullFrameParameters (int& hours,
  23645. int& minutes,
  23646. int& seconds,
  23647. int& frames,
  23648. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  23649. {
  23650. jassert (isFullFrame());
  23651. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  23652. hours = data[5] & 0x1f;
  23653. minutes = data[6];
  23654. seconds = data[7];
  23655. frames = data[8];
  23656. }
  23657. const MidiMessage MidiMessage::fullFrame (const int hours,
  23658. const int minutes,
  23659. const int seconds,
  23660. const int frames,
  23661. MidiMessage::SmpteTimecodeType timecodeType)
  23662. {
  23663. uint8 d[10];
  23664. d[0] = 0xf0;
  23665. d[1] = 0x7f;
  23666. d[2] = 0x7f;
  23667. d[3] = 0x01;
  23668. d[4] = 0x01;
  23669. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  23670. d[6] = (uint8) minutes;
  23671. d[7] = (uint8) seconds;
  23672. d[8] = (uint8) frames;
  23673. d[9] = 0xf7;
  23674. return MidiMessage (d, 10, 0.0);
  23675. }
  23676. bool MidiMessage::isMidiMachineControlMessage() const throw()
  23677. {
  23678. return data[0] == 0xf0
  23679. && data[1] == 0x7f
  23680. && data[3] == 0x06
  23681. && size > 5;
  23682. }
  23683. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  23684. {
  23685. jassert (isMidiMachineControlMessage());
  23686. return (MidiMachineControlCommand) data[4];
  23687. }
  23688. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  23689. {
  23690. uint8 d[6];
  23691. d[0] = 0xf0;
  23692. d[1] = 0x7f;
  23693. d[2] = 0x00;
  23694. d[3] = 0x06;
  23695. d[4] = (uint8) command;
  23696. d[5] = 0xf7;
  23697. return MidiMessage (d, 6, 0.0);
  23698. }
  23699. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  23700. int& minutes,
  23701. int& seconds,
  23702. int& frames) const throw()
  23703. {
  23704. if (size >= 12
  23705. && data[0] == 0xf0
  23706. && data[1] == 0x7f
  23707. && data[3] == 0x06
  23708. && data[4] == 0x44
  23709. && data[5] == 0x06
  23710. && data[6] == 0x01)
  23711. {
  23712. hours = data[7] % 24; // (that some machines send out hours > 24)
  23713. minutes = data[8];
  23714. seconds = data[9];
  23715. frames = data[10];
  23716. return true;
  23717. }
  23718. return false;
  23719. }
  23720. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  23721. int minutes,
  23722. int seconds,
  23723. int frames)
  23724. {
  23725. uint8 d[12];
  23726. d[0] = 0xf0;
  23727. d[1] = 0x7f;
  23728. d[2] = 0x00;
  23729. d[3] = 0x06;
  23730. d[4] = 0x44;
  23731. d[5] = 0x06;
  23732. d[6] = 0x01;
  23733. d[7] = (uint8) hours;
  23734. d[8] = (uint8) minutes;
  23735. d[9] = (uint8) seconds;
  23736. d[10] = (uint8) frames;
  23737. d[11] = 0xf7;
  23738. return MidiMessage (d, 12, 0.0);
  23739. }
  23740. const String MidiMessage::getMidiNoteName (int note, bool useSharps, bool includeOctaveNumber, int octaveNumForMiddleC)
  23741. {
  23742. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
  23743. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B" };
  23744. if (((unsigned int) note) < 128)
  23745. {
  23746. String s (useSharps ? sharpNoteNames [note % 12]
  23747. : flatNoteNames [note % 12]);
  23748. if (includeOctaveNumber)
  23749. s << (note / 12 + (octaveNumForMiddleC - 5));
  23750. return s;
  23751. }
  23752. return String::empty;
  23753. }
  23754. const double MidiMessage::getMidiNoteInHertz (int noteNumber, const double frequencyOfA) throw()
  23755. {
  23756. noteNumber -= 12 * 6 + 9; // now 0 = A
  23757. return frequencyOfA * pow (2.0, noteNumber / 12.0);
  23758. }
  23759. const String MidiMessage::getGMInstrumentName (const int n)
  23760. {
  23761. const char* names[] =
  23762. {
  23763. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  23764. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  23765. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  23766. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  23767. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  23768. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  23769. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  23770. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  23771. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  23772. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  23773. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  23774. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  23775. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  23776. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  23777. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  23778. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  23779. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  23780. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  23781. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  23782. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  23783. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  23784. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  23785. "Applause", "Gunshot"
  23786. };
  23787. return (((unsigned int) n) < 128) ? names[n] : (const char*) 0;
  23788. }
  23789. const String MidiMessage::getGMInstrumentBankName (const int n)
  23790. {
  23791. const char* names[] =
  23792. {
  23793. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  23794. "Bass", "Strings", "Ensemble", "Brass",
  23795. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  23796. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  23797. };
  23798. return (((unsigned int) n) <= 15) ? names[n] : (const char*) 0;
  23799. }
  23800. const String MidiMessage::getRhythmInstrumentName (const int n)
  23801. {
  23802. const char* names[] =
  23803. {
  23804. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  23805. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  23806. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  23807. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  23808. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  23809. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  23810. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  23811. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  23812. "Mute Triangle", "Open Triangle"
  23813. };
  23814. return (n >= 35 && n <= 81) ? names [n - 35] : (const char*) 0;
  23815. }
  23816. const String MidiMessage::getControllerName (const int n)
  23817. {
  23818. const char* names[] =
  23819. {
  23820. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  23821. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  23822. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  23823. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  23824. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  23825. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  23826. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  23827. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  23828. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  23829. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  23830. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  23831. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  23832. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  23833. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  23834. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  23835. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  23836. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  23837. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  23838. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  23839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  23840. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  23841. "Poly Operation"
  23842. };
  23843. return (((unsigned int) n) < 128) ? names[n] : (const char*) 0;
  23844. }
  23845. END_JUCE_NAMESPACE
  23846. /*** End of inlined file: juce_MidiMessage.cpp ***/
  23847. /*** Start of inlined file: juce_MidiMessageCollector.cpp ***/
  23848. BEGIN_JUCE_NAMESPACE
  23849. MidiMessageCollector::MidiMessageCollector()
  23850. : lastCallbackTime (0),
  23851. sampleRate (44100.0001)
  23852. {
  23853. }
  23854. MidiMessageCollector::~MidiMessageCollector()
  23855. {
  23856. }
  23857. void MidiMessageCollector::reset (const double sampleRate_)
  23858. {
  23859. jassert (sampleRate_ > 0);
  23860. const ScopedLock sl (midiCallbackLock);
  23861. sampleRate = sampleRate_;
  23862. incomingMessages.clear();
  23863. lastCallbackTime = Time::getMillisecondCounterHiRes();
  23864. }
  23865. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  23866. {
  23867. // you need to call reset() to set the correct sample rate before using this object
  23868. jassert (sampleRate != 44100.0001);
  23869. // the messages that come in here need to be time-stamped correctly - see MidiInput
  23870. // for details of what the number should be.
  23871. jassert (message.getTimeStamp() != 0);
  23872. const ScopedLock sl (midiCallbackLock);
  23873. const int sampleNumber
  23874. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  23875. incomingMessages.addEvent (message, sampleNumber);
  23876. // if the messages don't get used for over a second, we'd better
  23877. // get rid of any old ones to avoid the queue getting too big
  23878. if (sampleNumber > sampleRate)
  23879. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  23880. }
  23881. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  23882. const int numSamples)
  23883. {
  23884. // you need to call reset() to set the correct sample rate before using this object
  23885. jassert (sampleRate != 44100.0001);
  23886. const double timeNow = Time::getMillisecondCounterHiRes();
  23887. const double msElapsed = timeNow - lastCallbackTime;
  23888. const ScopedLock sl (midiCallbackLock);
  23889. lastCallbackTime = timeNow;
  23890. if (! incomingMessages.isEmpty())
  23891. {
  23892. int numSourceSamples = jmax (1, roundToInt (msElapsed * 0.001 * sampleRate));
  23893. int startSample = 0;
  23894. int scale = 1 << 16;
  23895. const uint8* midiData;
  23896. int numBytes, samplePosition;
  23897. MidiBuffer::Iterator iter (incomingMessages);
  23898. if (numSourceSamples > numSamples)
  23899. {
  23900. // if our list of events is longer than the buffer we're being
  23901. // asked for, scale them down to squeeze them all in..
  23902. const int maxBlockLengthToUse = numSamples << 5;
  23903. if (numSourceSamples > maxBlockLengthToUse)
  23904. {
  23905. startSample = numSourceSamples - maxBlockLengthToUse;
  23906. numSourceSamples = maxBlockLengthToUse;
  23907. iter.setNextSamplePosition (startSample);
  23908. }
  23909. scale = (numSamples << 10) / numSourceSamples;
  23910. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23911. {
  23912. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  23913. destBuffer.addEvent (midiData, numBytes,
  23914. jlimit (0, numSamples - 1, samplePosition));
  23915. }
  23916. }
  23917. else
  23918. {
  23919. // if our event list is shorter than the number we need, put them
  23920. // towards the end of the buffer
  23921. startSample = numSamples - numSourceSamples;
  23922. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23923. {
  23924. destBuffer.addEvent (midiData, numBytes,
  23925. jlimit (0, numSamples - 1, samplePosition + startSample));
  23926. }
  23927. }
  23928. incomingMessages.clear();
  23929. }
  23930. }
  23931. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  23932. {
  23933. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  23934. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23935. addMessageToQueue (m);
  23936. }
  23937. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  23938. {
  23939. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  23940. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  23941. addMessageToQueue (m);
  23942. }
  23943. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  23944. {
  23945. addMessageToQueue (message);
  23946. }
  23947. END_JUCE_NAMESPACE
  23948. /*** End of inlined file: juce_MidiMessageCollector.cpp ***/
  23949. /*** Start of inlined file: juce_MidiMessageSequence.cpp ***/
  23950. BEGIN_JUCE_NAMESPACE
  23951. MidiMessageSequence::MidiMessageSequence()
  23952. {
  23953. }
  23954. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  23955. {
  23956. list.ensureStorageAllocated (other.list.size());
  23957. for (int i = 0; i < other.list.size(); ++i)
  23958. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  23959. }
  23960. MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  23961. {
  23962. MidiMessageSequence otherCopy (other);
  23963. swapWith (otherCopy);
  23964. return *this;
  23965. }
  23966. void MidiMessageSequence::swapWith (MidiMessageSequence& other) throw()
  23967. {
  23968. list.swapWithArray (other.list);
  23969. }
  23970. MidiMessageSequence::~MidiMessageSequence()
  23971. {
  23972. }
  23973. void MidiMessageSequence::clear()
  23974. {
  23975. list.clear();
  23976. }
  23977. int MidiMessageSequence::getNumEvents() const
  23978. {
  23979. return list.size();
  23980. }
  23981. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  23982. {
  23983. return list [index];
  23984. }
  23985. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  23986. {
  23987. const MidiEventHolder* const meh = list [index];
  23988. if (meh != 0 && meh->noteOffObject != 0)
  23989. return meh->noteOffObject->message.getTimeStamp();
  23990. else
  23991. return 0.0;
  23992. }
  23993. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  23994. {
  23995. const MidiEventHolder* const meh = list [index];
  23996. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  23997. }
  23998. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  23999. {
  24000. return list.indexOf (event);
  24001. }
  24002. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  24003. {
  24004. const int numEvents = list.size();
  24005. int i;
  24006. for (i = 0; i < numEvents; ++i)
  24007. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  24008. break;
  24009. return i;
  24010. }
  24011. double MidiMessageSequence::getStartTime() const
  24012. {
  24013. if (list.size() > 0)
  24014. return list.getUnchecked(0)->message.getTimeStamp();
  24015. else
  24016. return 0;
  24017. }
  24018. double MidiMessageSequence::getEndTime() const
  24019. {
  24020. if (list.size() > 0)
  24021. return list.getLast()->message.getTimeStamp();
  24022. else
  24023. return 0;
  24024. }
  24025. double MidiMessageSequence::getEventTime (const int index) const
  24026. {
  24027. if (((unsigned int) index) < (unsigned int) list.size())
  24028. return list.getUnchecked (index)->message.getTimeStamp();
  24029. return 0.0;
  24030. }
  24031. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  24032. double timeAdjustment)
  24033. {
  24034. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  24035. timeAdjustment += newMessage.getTimeStamp();
  24036. newOne->message.setTimeStamp (timeAdjustment);
  24037. int i;
  24038. for (i = list.size(); --i >= 0;)
  24039. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  24040. break;
  24041. list.insert (i + 1, newOne);
  24042. }
  24043. void MidiMessageSequence::deleteEvent (const int index,
  24044. const bool deleteMatchingNoteUp)
  24045. {
  24046. if (((unsigned int) index) < (unsigned int) list.size())
  24047. {
  24048. if (deleteMatchingNoteUp)
  24049. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  24050. list.remove (index);
  24051. }
  24052. }
  24053. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  24054. double timeAdjustment,
  24055. double firstAllowableTime,
  24056. double endOfAllowableDestTimes)
  24057. {
  24058. firstAllowableTime -= timeAdjustment;
  24059. endOfAllowableDestTimes -= timeAdjustment;
  24060. for (int i = 0; i < other.list.size(); ++i)
  24061. {
  24062. const MidiMessage& m = other.list.getUnchecked(i)->message;
  24063. const double t = m.getTimeStamp();
  24064. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  24065. {
  24066. MidiEventHolder* const newOne = new MidiEventHolder (m);
  24067. newOne->message.setTimeStamp (timeAdjustment + t);
  24068. list.add (newOne);
  24069. }
  24070. }
  24071. sort();
  24072. }
  24073. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  24074. const MidiMessageSequence::MidiEventHolder* const second) throw()
  24075. {
  24076. const double diff = first->message.getTimeStamp()
  24077. - second->message.getTimeStamp();
  24078. return (diff > 0) - (diff < 0);
  24079. }
  24080. void MidiMessageSequence::sort()
  24081. {
  24082. list.sort (*this, true);
  24083. }
  24084. void MidiMessageSequence::updateMatchedPairs()
  24085. {
  24086. for (int i = 0; i < list.size(); ++i)
  24087. {
  24088. const MidiMessage& m1 = list.getUnchecked(i)->message;
  24089. if (m1.isNoteOn())
  24090. {
  24091. list.getUnchecked(i)->noteOffObject = 0;
  24092. const int note = m1.getNoteNumber();
  24093. const int chan = m1.getChannel();
  24094. const int len = list.size();
  24095. for (int j = i + 1; j < len; ++j)
  24096. {
  24097. const MidiMessage& m = list.getUnchecked(j)->message;
  24098. if (m.getNoteNumber() == note && m.getChannel() == chan)
  24099. {
  24100. if (m.isNoteOff())
  24101. {
  24102. list.getUnchecked(i)->noteOffObject = list[j];
  24103. break;
  24104. }
  24105. else if (m.isNoteOn())
  24106. {
  24107. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  24108. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  24109. list.getUnchecked(i)->noteOffObject = list[j];
  24110. break;
  24111. }
  24112. }
  24113. }
  24114. }
  24115. }
  24116. }
  24117. void MidiMessageSequence::addTimeToMessages (const double delta)
  24118. {
  24119. for (int i = list.size(); --i >= 0;)
  24120. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  24121. + delta);
  24122. }
  24123. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  24124. MidiMessageSequence& destSequence,
  24125. const bool alsoIncludeMetaEvents) const
  24126. {
  24127. for (int i = 0; i < list.size(); ++i)
  24128. {
  24129. const MidiMessage& mm = list.getUnchecked(i)->message;
  24130. if (mm.isForChannel (channelNumberToExtract)
  24131. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  24132. {
  24133. destSequence.addEvent (mm);
  24134. }
  24135. }
  24136. }
  24137. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  24138. {
  24139. for (int i = 0; i < list.size(); ++i)
  24140. {
  24141. const MidiMessage& mm = list.getUnchecked(i)->message;
  24142. if (mm.isSysEx())
  24143. destSequence.addEvent (mm);
  24144. }
  24145. }
  24146. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  24147. {
  24148. for (int i = list.size(); --i >= 0;)
  24149. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  24150. list.remove(i);
  24151. }
  24152. void MidiMessageSequence::deleteSysExMessages()
  24153. {
  24154. for (int i = list.size(); --i >= 0;)
  24155. if (list.getUnchecked(i)->message.isSysEx())
  24156. list.remove(i);
  24157. }
  24158. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  24159. const double time,
  24160. OwnedArray<MidiMessage>& dest)
  24161. {
  24162. bool doneProg = false;
  24163. bool donePitchWheel = false;
  24164. Array <int> doneControllers;
  24165. doneControllers.ensureStorageAllocated (32);
  24166. for (int i = list.size(); --i >= 0;)
  24167. {
  24168. const MidiMessage& mm = list.getUnchecked(i)->message;
  24169. if (mm.isForChannel (channelNumber)
  24170. && mm.getTimeStamp() <= time)
  24171. {
  24172. if (mm.isProgramChange())
  24173. {
  24174. if (! doneProg)
  24175. {
  24176. dest.add (new MidiMessage (mm, 0.0));
  24177. doneProg = true;
  24178. }
  24179. }
  24180. else if (mm.isController())
  24181. {
  24182. if (! doneControllers.contains (mm.getControllerNumber()))
  24183. {
  24184. dest.add (new MidiMessage (mm, 0.0));
  24185. doneControllers.add (mm.getControllerNumber());
  24186. }
  24187. }
  24188. else if (mm.isPitchWheel())
  24189. {
  24190. if (! donePitchWheel)
  24191. {
  24192. dest.add (new MidiMessage (mm, 0.0));
  24193. donePitchWheel = true;
  24194. }
  24195. }
  24196. }
  24197. }
  24198. }
  24199. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  24200. : message (message_),
  24201. noteOffObject (0)
  24202. {
  24203. }
  24204. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  24205. {
  24206. }
  24207. END_JUCE_NAMESPACE
  24208. /*** End of inlined file: juce_MidiMessageSequence.cpp ***/
  24209. /*** Start of inlined file: juce_AudioPluginFormat.cpp ***/
  24210. BEGIN_JUCE_NAMESPACE
  24211. AudioPluginFormat::AudioPluginFormat() throw()
  24212. {
  24213. }
  24214. AudioPluginFormat::~AudioPluginFormat()
  24215. {
  24216. }
  24217. END_JUCE_NAMESPACE
  24218. /*** End of inlined file: juce_AudioPluginFormat.cpp ***/
  24219. /*** Start of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24220. BEGIN_JUCE_NAMESPACE
  24221. AudioPluginFormatManager::AudioPluginFormatManager()
  24222. {
  24223. }
  24224. AudioPluginFormatManager::~AudioPluginFormatManager()
  24225. {
  24226. clearSingletonInstance();
  24227. }
  24228. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  24229. void AudioPluginFormatManager::addDefaultFormats()
  24230. {
  24231. #if JUCE_DEBUG
  24232. // you should only call this method once!
  24233. for (int i = formats.size(); --i >= 0;)
  24234. {
  24235. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24236. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  24237. #endif
  24238. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24239. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  24240. #endif
  24241. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24242. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  24243. #endif
  24244. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24245. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  24246. #endif
  24247. }
  24248. #endif
  24249. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24250. formats.add (new AudioUnitPluginFormat());
  24251. #endif
  24252. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24253. formats.add (new VSTPluginFormat());
  24254. #endif
  24255. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24256. formats.add (new DirectXPluginFormat());
  24257. #endif
  24258. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24259. formats.add (new LADSPAPluginFormat());
  24260. #endif
  24261. }
  24262. int AudioPluginFormatManager::getNumFormats()
  24263. {
  24264. return formats.size();
  24265. }
  24266. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index)
  24267. {
  24268. return formats [index];
  24269. }
  24270. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format)
  24271. {
  24272. formats.add (format);
  24273. }
  24274. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  24275. String& errorMessage) const
  24276. {
  24277. AudioPluginInstance* result = 0;
  24278. for (int i = 0; i < formats.size(); ++i)
  24279. {
  24280. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  24281. if (result != 0)
  24282. break;
  24283. }
  24284. if (result == 0)
  24285. {
  24286. if (! doesPluginStillExist (description))
  24287. errorMessage = TRANS ("This plug-in file no longer exists");
  24288. else
  24289. errorMessage = TRANS ("This plug-in failed to load correctly");
  24290. }
  24291. return result;
  24292. }
  24293. bool AudioPluginFormatManager::doesPluginStillExist (const PluginDescription& description) const
  24294. {
  24295. for (int i = 0; i < formats.size(); ++i)
  24296. if (formats.getUnchecked(i)->getName() == description.pluginFormatName)
  24297. return formats.getUnchecked(i)->doesPluginStillExist (description);
  24298. return false;
  24299. }
  24300. END_JUCE_NAMESPACE
  24301. /*** End of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24302. /*** Start of inlined file: juce_AudioPluginInstance.cpp ***/
  24303. #define JUCE_PLUGIN_HOST 1
  24304. BEGIN_JUCE_NAMESPACE
  24305. AudioPluginInstance::AudioPluginInstance()
  24306. {
  24307. }
  24308. AudioPluginInstance::~AudioPluginInstance()
  24309. {
  24310. }
  24311. END_JUCE_NAMESPACE
  24312. /*** End of inlined file: juce_AudioPluginInstance.cpp ***/
  24313. /*** Start of inlined file: juce_KnownPluginList.cpp ***/
  24314. BEGIN_JUCE_NAMESPACE
  24315. KnownPluginList::KnownPluginList()
  24316. {
  24317. }
  24318. KnownPluginList::~KnownPluginList()
  24319. {
  24320. }
  24321. void KnownPluginList::clear()
  24322. {
  24323. if (types.size() > 0)
  24324. {
  24325. types.clear();
  24326. sendChangeMessage (this);
  24327. }
  24328. }
  24329. PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const
  24330. {
  24331. for (int i = 0; i < types.size(); ++i)
  24332. if (types.getUnchecked(i)->fileOrIdentifier == fileOrIdentifier)
  24333. return types.getUnchecked(i);
  24334. return 0;
  24335. }
  24336. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const
  24337. {
  24338. for (int i = 0; i < types.size(); ++i)
  24339. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  24340. return types.getUnchecked(i);
  24341. return 0;
  24342. }
  24343. bool KnownPluginList::addType (const PluginDescription& type)
  24344. {
  24345. for (int i = types.size(); --i >= 0;)
  24346. {
  24347. if (types.getUnchecked(i)->isDuplicateOf (type))
  24348. {
  24349. // strange - found a duplicate plugin with different info..
  24350. jassert (types.getUnchecked(i)->name == type.name);
  24351. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  24352. *types.getUnchecked(i) = type;
  24353. return false;
  24354. }
  24355. }
  24356. types.add (new PluginDescription (type));
  24357. sendChangeMessage (this);
  24358. return true;
  24359. }
  24360. void KnownPluginList::removeType (const int index)
  24361. {
  24362. types.remove (index);
  24363. sendChangeMessage (this);
  24364. }
  24365. static const Time getPluginFileModTime (const String& fileOrIdentifier)
  24366. {
  24367. if (fileOrIdentifier.startsWithChar ('/') || fileOrIdentifier[1] == ':')
  24368. return File (fileOrIdentifier).getLastModificationTime();
  24369. return Time (0);
  24370. }
  24371. static bool timesAreDifferent (const Time& t1, const Time& t2) throw()
  24372. {
  24373. return t1 != t2 || t1 == Time (0);
  24374. }
  24375. bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const
  24376. {
  24377. if (getTypeForFile (fileOrIdentifier) == 0)
  24378. return false;
  24379. for (int i = types.size(); --i >= 0;)
  24380. {
  24381. const PluginDescription* const d = types.getUnchecked(i);
  24382. if (d->fileOrIdentifier == fileOrIdentifier
  24383. && timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24384. {
  24385. return false;
  24386. }
  24387. }
  24388. return true;
  24389. }
  24390. bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
  24391. const bool dontRescanIfAlreadyInList,
  24392. OwnedArray <PluginDescription>& typesFound,
  24393. AudioPluginFormat& format)
  24394. {
  24395. bool addedOne = false;
  24396. if (dontRescanIfAlreadyInList
  24397. && getTypeForFile (fileOrIdentifier) != 0)
  24398. {
  24399. bool needsRescanning = false;
  24400. for (int i = types.size(); --i >= 0;)
  24401. {
  24402. const PluginDescription* const d = types.getUnchecked(i);
  24403. if (d->fileOrIdentifier == fileOrIdentifier)
  24404. {
  24405. if (timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24406. needsRescanning = true;
  24407. else
  24408. typesFound.add (new PluginDescription (*d));
  24409. }
  24410. }
  24411. if (! needsRescanning)
  24412. return false;
  24413. }
  24414. OwnedArray <PluginDescription> found;
  24415. format.findAllTypesForFile (found, fileOrIdentifier);
  24416. for (int i = 0; i < found.size(); ++i)
  24417. {
  24418. PluginDescription* const desc = found.getUnchecked(i);
  24419. jassert (desc != 0);
  24420. if (addType (*desc))
  24421. addedOne = true;
  24422. typesFound.add (new PluginDescription (*desc));
  24423. }
  24424. return addedOne;
  24425. }
  24426. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  24427. OwnedArray <PluginDescription>& typesFound)
  24428. {
  24429. for (int i = 0; i < files.size(); ++i)
  24430. {
  24431. bool loaded = false;
  24432. for (int j = 0; j < AudioPluginFormatManager::getInstance()->getNumFormats(); ++j)
  24433. {
  24434. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (j);
  24435. if (scanAndAddFile (files[i], true, typesFound, *format))
  24436. loaded = true;
  24437. }
  24438. if (! loaded)
  24439. {
  24440. const File f (files[i]);
  24441. if (f.isDirectory())
  24442. {
  24443. StringArray s;
  24444. {
  24445. Array<File> subFiles;
  24446. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  24447. for (int j = 0; j < subFiles.size(); ++j)
  24448. s.add (subFiles.getReference(j).getFullPathName());
  24449. }
  24450. scanAndAddDragAndDroppedFiles (s, typesFound);
  24451. }
  24452. }
  24453. }
  24454. }
  24455. class PluginSorter
  24456. {
  24457. public:
  24458. KnownPluginList::SortMethod method;
  24459. PluginSorter() throw() {}
  24460. int compareElements (const PluginDescription* const first,
  24461. const PluginDescription* const second) const
  24462. {
  24463. int diff = 0;
  24464. if (method == KnownPluginList::sortByCategory)
  24465. diff = first->category.compareLexicographically (second->category);
  24466. else if (method == KnownPluginList::sortByManufacturer)
  24467. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  24468. else if (method == KnownPluginList::sortByFileSystemLocation)
  24469. diff = first->fileOrIdentifier.replaceCharacter ('\\', '/')
  24470. .upToLastOccurrenceOf ("/", false, false)
  24471. .compare (second->fileOrIdentifier.replaceCharacter ('\\', '/')
  24472. .upToLastOccurrenceOf ("/", false, false));
  24473. if (diff == 0)
  24474. diff = first->name.compareLexicographically (second->name);
  24475. return diff;
  24476. }
  24477. };
  24478. void KnownPluginList::sort (const SortMethod method)
  24479. {
  24480. if (method != defaultOrder)
  24481. {
  24482. PluginSorter sorter;
  24483. sorter.method = method;
  24484. types.sort (sorter, true);
  24485. sendChangeMessage (this);
  24486. }
  24487. }
  24488. XmlElement* KnownPluginList::createXml() const
  24489. {
  24490. XmlElement* const e = new XmlElement ("KNOWNPLUGINS");
  24491. for (int i = 0; i < types.size(); ++i)
  24492. e->addChildElement (types.getUnchecked(i)->createXml());
  24493. return e;
  24494. }
  24495. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  24496. {
  24497. clear();
  24498. if (xml.hasTagName ("KNOWNPLUGINS"))
  24499. {
  24500. forEachXmlChildElement (xml, e)
  24501. {
  24502. PluginDescription info;
  24503. if (info.loadFromXml (*e))
  24504. addType (info);
  24505. }
  24506. }
  24507. }
  24508. const int menuIdBase = 0x324503f4;
  24509. // This is used to turn a bunch of paths into a nested menu structure.
  24510. struct PluginFilesystemTree
  24511. {
  24512. private:
  24513. String folder;
  24514. OwnedArray <PluginFilesystemTree> subFolders;
  24515. Array <PluginDescription*> plugins;
  24516. void addPlugin (PluginDescription* const pd, const String& path)
  24517. {
  24518. if (path.isEmpty())
  24519. {
  24520. plugins.add (pd);
  24521. }
  24522. else
  24523. {
  24524. const String firstSubFolder (path.upToFirstOccurrenceOf ("/", false, false));
  24525. const String remainingPath (path.fromFirstOccurrenceOf ("/", false, false));
  24526. for (int i = subFolders.size(); --i >= 0;)
  24527. {
  24528. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  24529. {
  24530. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  24531. return;
  24532. }
  24533. }
  24534. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  24535. newFolder->folder = firstSubFolder;
  24536. subFolders.add (newFolder);
  24537. newFolder->addPlugin (pd, remainingPath);
  24538. }
  24539. }
  24540. // removes any deeply nested folders that don't contain any actual plugins
  24541. void optimise()
  24542. {
  24543. for (int i = subFolders.size(); --i >= 0;)
  24544. {
  24545. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24546. sub->optimise();
  24547. if (sub->plugins.size() == 0)
  24548. {
  24549. for (int j = 0; j < sub->subFolders.size(); ++j)
  24550. subFolders.add (sub->subFolders.getUnchecked(j));
  24551. sub->subFolders.clear (false);
  24552. subFolders.remove (i);
  24553. }
  24554. }
  24555. }
  24556. public:
  24557. void buildTree (const Array <PluginDescription*>& allPlugins)
  24558. {
  24559. for (int i = 0; i < allPlugins.size(); ++i)
  24560. {
  24561. String path (allPlugins.getUnchecked(i)
  24562. ->fileOrIdentifier.replaceCharacter ('\\', '/')
  24563. .upToLastOccurrenceOf ("/", false, false));
  24564. if (path.substring (1, 2) == ":")
  24565. path = path.substring (2);
  24566. addPlugin (allPlugins.getUnchecked(i), path);
  24567. }
  24568. optimise();
  24569. }
  24570. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  24571. {
  24572. int i;
  24573. for (i = 0; i < subFolders.size(); ++i)
  24574. {
  24575. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24576. PopupMenu subMenu;
  24577. sub->addToMenu (subMenu, allPlugins);
  24578. #if JUCE_MAC
  24579. // avoid the special AU formatting nonsense on Mac..
  24580. m.addSubMenu (sub->folder.fromFirstOccurrenceOf (":", false, false), subMenu);
  24581. #else
  24582. m.addSubMenu (sub->folder, subMenu);
  24583. #endif
  24584. }
  24585. for (i = 0; i < plugins.size(); ++i)
  24586. {
  24587. PluginDescription* const plugin = plugins.getUnchecked(i);
  24588. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  24589. plugin->name, true, false);
  24590. }
  24591. }
  24592. };
  24593. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  24594. {
  24595. Array <PluginDescription*> sorted;
  24596. {
  24597. PluginSorter sorter;
  24598. sorter.method = sortMethod;
  24599. for (int i = 0; i < types.size(); ++i)
  24600. sorted.addSorted (sorter, types.getUnchecked(i));
  24601. }
  24602. if (sortMethod == sortByCategory
  24603. || sortMethod == sortByManufacturer)
  24604. {
  24605. String lastSubMenuName;
  24606. PopupMenu sub;
  24607. for (int i = 0; i < sorted.size(); ++i)
  24608. {
  24609. const PluginDescription* const pd = sorted.getUnchecked(i);
  24610. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  24611. : pd->manufacturerName);
  24612. if (! thisSubMenuName.containsNonWhitespaceChars())
  24613. thisSubMenuName = "Other";
  24614. if (thisSubMenuName != lastSubMenuName)
  24615. {
  24616. if (sub.getNumItems() > 0)
  24617. {
  24618. menu.addSubMenu (lastSubMenuName, sub);
  24619. sub.clear();
  24620. }
  24621. lastSubMenuName = thisSubMenuName;
  24622. }
  24623. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24624. }
  24625. if (sub.getNumItems() > 0)
  24626. menu.addSubMenu (lastSubMenuName, sub);
  24627. }
  24628. else if (sortMethod == sortByFileSystemLocation)
  24629. {
  24630. PluginFilesystemTree root;
  24631. root.buildTree (sorted);
  24632. root.addToMenu (menu, types);
  24633. }
  24634. else
  24635. {
  24636. for (int i = 0; i < sorted.size(); ++i)
  24637. {
  24638. const PluginDescription* const pd = sorted.getUnchecked(i);
  24639. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24640. }
  24641. }
  24642. }
  24643. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  24644. {
  24645. const int i = menuResultCode - menuIdBase;
  24646. return (((unsigned int) i) < (unsigned int) types.size()) ? i : -1;
  24647. }
  24648. END_JUCE_NAMESPACE
  24649. /*** End of inlined file: juce_KnownPluginList.cpp ***/
  24650. /*** Start of inlined file: juce_PluginDescription.cpp ***/
  24651. BEGIN_JUCE_NAMESPACE
  24652. PluginDescription::PluginDescription()
  24653. : uid (0),
  24654. isInstrument (false),
  24655. numInputChannels (0),
  24656. numOutputChannels (0)
  24657. {
  24658. }
  24659. PluginDescription::~PluginDescription()
  24660. {
  24661. }
  24662. PluginDescription::PluginDescription (const PluginDescription& other)
  24663. : name (other.name),
  24664. pluginFormatName (other.pluginFormatName),
  24665. category (other.category),
  24666. manufacturerName (other.manufacturerName),
  24667. version (other.version),
  24668. fileOrIdentifier (other.fileOrIdentifier),
  24669. lastFileModTime (other.lastFileModTime),
  24670. uid (other.uid),
  24671. isInstrument (other.isInstrument),
  24672. numInputChannels (other.numInputChannels),
  24673. numOutputChannels (other.numOutputChannels)
  24674. {
  24675. }
  24676. PluginDescription& PluginDescription::operator= (const PluginDescription& other)
  24677. {
  24678. name = other.name;
  24679. pluginFormatName = other.pluginFormatName;
  24680. category = other.category;
  24681. manufacturerName = other.manufacturerName;
  24682. version = other.version;
  24683. fileOrIdentifier = other.fileOrIdentifier;
  24684. uid = other.uid;
  24685. isInstrument = other.isInstrument;
  24686. lastFileModTime = other.lastFileModTime;
  24687. numInputChannels = other.numInputChannels;
  24688. numOutputChannels = other.numOutputChannels;
  24689. return *this;
  24690. }
  24691. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  24692. {
  24693. return fileOrIdentifier == other.fileOrIdentifier
  24694. && uid == other.uid;
  24695. }
  24696. const String PluginDescription::createIdentifierString() const
  24697. {
  24698. return pluginFormatName
  24699. + "-" + name
  24700. + "-" + String::toHexString (fileOrIdentifier.hashCode())
  24701. + "-" + String::toHexString (uid);
  24702. }
  24703. XmlElement* PluginDescription::createXml() const
  24704. {
  24705. XmlElement* const e = new XmlElement ("PLUGIN");
  24706. e->setAttribute ("name", name);
  24707. e->setAttribute ("format", pluginFormatName);
  24708. e->setAttribute ("category", category);
  24709. e->setAttribute ("manufacturer", manufacturerName);
  24710. e->setAttribute ("version", version);
  24711. e->setAttribute ("file", fileOrIdentifier);
  24712. e->setAttribute ("uid", String::toHexString (uid));
  24713. e->setAttribute ("isInstrument", isInstrument);
  24714. e->setAttribute ("fileTime", String::toHexString (lastFileModTime.toMilliseconds()));
  24715. e->setAttribute ("numInputs", numInputChannels);
  24716. e->setAttribute ("numOutputs", numOutputChannels);
  24717. return e;
  24718. }
  24719. bool PluginDescription::loadFromXml (const XmlElement& xml)
  24720. {
  24721. if (xml.hasTagName ("PLUGIN"))
  24722. {
  24723. name = xml.getStringAttribute ("name");
  24724. pluginFormatName = xml.getStringAttribute ("format");
  24725. category = xml.getStringAttribute ("category");
  24726. manufacturerName = xml.getStringAttribute ("manufacturer");
  24727. version = xml.getStringAttribute ("version");
  24728. fileOrIdentifier = xml.getStringAttribute ("file");
  24729. uid = xml.getStringAttribute ("uid").getHexValue32();
  24730. isInstrument = xml.getBoolAttribute ("isInstrument", false);
  24731. lastFileModTime = Time (xml.getStringAttribute ("fileTime").getHexValue64());
  24732. numInputChannels = xml.getIntAttribute ("numInputs");
  24733. numOutputChannels = xml.getIntAttribute ("numOutputs");
  24734. return true;
  24735. }
  24736. return false;
  24737. }
  24738. END_JUCE_NAMESPACE
  24739. /*** End of inlined file: juce_PluginDescription.cpp ***/
  24740. /*** Start of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24741. BEGIN_JUCE_NAMESPACE
  24742. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  24743. AudioPluginFormat& formatToLookFor,
  24744. FileSearchPath directoriesToSearch,
  24745. const bool recursive,
  24746. const File& deadMansPedalFile_)
  24747. : list (listToAddTo),
  24748. format (formatToLookFor),
  24749. deadMansPedalFile (deadMansPedalFile_),
  24750. nextIndex (0),
  24751. progress (0)
  24752. {
  24753. directoriesToSearch.removeRedundantPaths();
  24754. filesOrIdentifiersToScan = format.searchPathsForPlugins (directoriesToSearch, recursive);
  24755. // If any plugins have crashed recently when being loaded, move them to the
  24756. // end of the list to give the others a chance to load correctly..
  24757. const StringArray crashedPlugins (getDeadMansPedalFile());
  24758. for (int i = 0; i < crashedPlugins.size(); ++i)
  24759. {
  24760. const String f = crashedPlugins[i];
  24761. for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
  24762. if (f == filesOrIdentifiersToScan[j])
  24763. filesOrIdentifiersToScan.move (j, -1);
  24764. }
  24765. }
  24766. PluginDirectoryScanner::~PluginDirectoryScanner()
  24767. {
  24768. }
  24769. const String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const
  24770. {
  24771. return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex]);
  24772. }
  24773. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  24774. {
  24775. String file (filesOrIdentifiersToScan [nextIndex]);
  24776. if (file.isNotEmpty())
  24777. {
  24778. if (! list.isListingUpToDate (file))
  24779. {
  24780. OwnedArray <PluginDescription> typesFound;
  24781. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  24782. StringArray crashedPlugins (getDeadMansPedalFile());
  24783. crashedPlugins.removeString (file);
  24784. crashedPlugins.add (file);
  24785. setDeadMansPedalFile (crashedPlugins);
  24786. list.scanAndAddFile (file,
  24787. dontRescanIfAlreadyInList,
  24788. typesFound,
  24789. format);
  24790. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  24791. crashedPlugins.removeString (file);
  24792. setDeadMansPedalFile (crashedPlugins);
  24793. if (typesFound.size() == 0)
  24794. failedFiles.add (file);
  24795. }
  24796. ++nextIndex;
  24797. progress = nextIndex / (float) filesOrIdentifiersToScan.size();
  24798. }
  24799. return nextIndex < filesOrIdentifiersToScan.size();
  24800. }
  24801. const StringArray PluginDirectoryScanner::getDeadMansPedalFile()
  24802. {
  24803. StringArray lines;
  24804. if (deadMansPedalFile != File::nonexistent)
  24805. {
  24806. lines.addLines (deadMansPedalFile.loadFileAsString());
  24807. lines.removeEmptyStrings();
  24808. }
  24809. return lines;
  24810. }
  24811. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents)
  24812. {
  24813. if (deadMansPedalFile != File::nonexistent)
  24814. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  24815. }
  24816. END_JUCE_NAMESPACE
  24817. /*** End of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24818. /*** Start of inlined file: juce_PluginListComponent.cpp ***/
  24819. BEGIN_JUCE_NAMESPACE
  24820. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  24821. const File& deadMansPedalFile_,
  24822. PropertiesFile* const propertiesToUse_)
  24823. : list (listToEdit),
  24824. deadMansPedalFile (deadMansPedalFile_),
  24825. propertiesToUse (propertiesToUse_)
  24826. {
  24827. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  24828. addAndMakeVisible (optionsButton = new TextButton ("Options..."));
  24829. optionsButton->addButtonListener (this);
  24830. optionsButton->setTriggeredOnMouseDown (true);
  24831. setSize (400, 600);
  24832. list.addChangeListener (this);
  24833. changeListenerCallback (0);
  24834. }
  24835. PluginListComponent::~PluginListComponent()
  24836. {
  24837. list.removeChangeListener (this);
  24838. deleteAllChildren();
  24839. }
  24840. void PluginListComponent::resized()
  24841. {
  24842. listBox->setBounds (0, 0, getWidth(), getHeight() - 30);
  24843. optionsButton->changeWidthToFitText (24);
  24844. optionsButton->setTopLeftPosition (8, getHeight() - 28);
  24845. }
  24846. void PluginListComponent::changeListenerCallback (void*)
  24847. {
  24848. listBox->updateContent();
  24849. listBox->repaint();
  24850. }
  24851. int PluginListComponent::getNumRows()
  24852. {
  24853. return list.getNumTypes();
  24854. }
  24855. void PluginListComponent::paintListBoxItem (int row,
  24856. Graphics& g,
  24857. int width, int height,
  24858. bool rowIsSelected)
  24859. {
  24860. if (rowIsSelected)
  24861. g.fillAll (findColour (TextEditor::highlightColourId));
  24862. const PluginDescription* const pd = list.getType (row);
  24863. if (pd != 0)
  24864. {
  24865. GlyphArrangement ga;
  24866. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  24867. g.setColour (Colours::black);
  24868. ga.draw (g);
  24869. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  24870. String desc;
  24871. desc << pd->pluginFormatName
  24872. << (pd->isInstrument ? " instrument" : " effect")
  24873. << " - "
  24874. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  24875. << " / "
  24876. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  24877. if (pd->manufacturerName.isNotEmpty())
  24878. desc << " - " << pd->manufacturerName;
  24879. if (pd->version.isNotEmpty())
  24880. desc << " - " << pd->version;
  24881. if (pd->category.isNotEmpty())
  24882. desc << " - category: '" << pd->category << '\'';
  24883. g.setColour (Colours::grey);
  24884. ga.clear();
  24885. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, bb.getRight() + 10.0f, height * 0.8f, width - bb.getRight() - 12.0f, true);
  24886. ga.draw (g);
  24887. }
  24888. }
  24889. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  24890. {
  24891. list.removeType (lastRowSelected);
  24892. }
  24893. void PluginListComponent::buttonClicked (Button* b)
  24894. {
  24895. if (optionsButton == b)
  24896. {
  24897. PopupMenu menu;
  24898. menu.addItem (1, TRANS("Clear list"));
  24899. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox->getNumSelectedRows() > 0);
  24900. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox->getNumSelectedRows() > 0);
  24901. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  24902. menu.addSeparator();
  24903. menu.addItem (2, TRANS("Sort alphabetically"));
  24904. menu.addItem (3, TRANS("Sort by category"));
  24905. menu.addItem (4, TRANS("Sort by manufacturer"));
  24906. menu.addSeparator();
  24907. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  24908. {
  24909. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  24910. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  24911. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  24912. }
  24913. const int r = menu.showAt (optionsButton);
  24914. if (r == 1)
  24915. {
  24916. list.clear();
  24917. }
  24918. else if (r == 2)
  24919. {
  24920. list.sort (KnownPluginList::sortAlphabetically);
  24921. }
  24922. else if (r == 3)
  24923. {
  24924. list.sort (KnownPluginList::sortByCategory);
  24925. }
  24926. else if (r == 4)
  24927. {
  24928. list.sort (KnownPluginList::sortByManufacturer);
  24929. }
  24930. else if (r == 5)
  24931. {
  24932. const SparseSet <int> selected (listBox->getSelectedRows());
  24933. for (int i = list.getNumTypes(); --i >= 0;)
  24934. if (selected.contains (i))
  24935. list.removeType (i);
  24936. }
  24937. else if (r == 6)
  24938. {
  24939. const PluginDescription* const desc = list.getType (listBox->getSelectedRow());
  24940. if (desc != 0)
  24941. {
  24942. if (File (desc->fileOrIdentifier).existsAsFile())
  24943. File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
  24944. }
  24945. }
  24946. else if (r == 7)
  24947. {
  24948. for (int i = list.getNumTypes(); --i >= 0;)
  24949. {
  24950. if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
  24951. {
  24952. list.removeType (i);
  24953. }
  24954. }
  24955. }
  24956. else if (r != 0)
  24957. {
  24958. typeToScan = r - 10;
  24959. startTimer (1);
  24960. }
  24961. }
  24962. }
  24963. void PluginListComponent::timerCallback()
  24964. {
  24965. stopTimer();
  24966. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  24967. }
  24968. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  24969. {
  24970. return true;
  24971. }
  24972. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  24973. {
  24974. OwnedArray <PluginDescription> typesFound;
  24975. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  24976. }
  24977. void PluginListComponent::scanFor (AudioPluginFormat* format)
  24978. {
  24979. if (format == 0)
  24980. return;
  24981. FileSearchPath path (format->getDefaultLocationsToSearch());
  24982. if (propertiesToUse != 0)
  24983. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24984. {
  24985. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  24986. FileSearchPathListComponent pathList;
  24987. pathList.setSize (500, 300);
  24988. pathList.setPath (path);
  24989. aw.addCustomComponent (&pathList);
  24990. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  24991. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  24992. if (aw.runModalLoop() == 0)
  24993. return;
  24994. path = pathList.getPath();
  24995. }
  24996. if (propertiesToUse != 0)
  24997. {
  24998. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  24999. propertiesToUse->saveIfNeeded();
  25000. }
  25001. double progress = 0.0;
  25002. AlertWindow aw (TRANS("Scanning for plugins..."),
  25003. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  25004. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  25005. aw.addProgressBarComponent (progress);
  25006. aw.enterModalState();
  25007. MessageManager::getInstance()->runDispatchLoopUntil (300);
  25008. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  25009. for (;;)
  25010. {
  25011. aw.setMessage (TRANS("Testing:\n\n")
  25012. + scanner.getNextPluginFileThatWillBeScanned());
  25013. MessageManager::getInstance()->runDispatchLoopUntil (20);
  25014. if (! scanner.scanNextFile (true))
  25015. break;
  25016. if (! aw.isCurrentlyModal())
  25017. break;
  25018. progress = scanner.getProgress();
  25019. }
  25020. if (scanner.getFailedFiles().size() > 0)
  25021. {
  25022. StringArray shortNames;
  25023. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  25024. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  25025. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  25026. TRANS("Scan complete"),
  25027. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  25028. + shortNames.joinIntoString (", "));
  25029. }
  25030. }
  25031. END_JUCE_NAMESPACE
  25032. /*** End of inlined file: juce_PluginListComponent.cpp ***/
  25033. /*** Start of inlined file: juce_AudioUnitPluginFormat.mm ***/
  25034. #if JUCE_PLUGINHOST_AU && ! (JUCE_LINUX || JUCE_WINDOWS)
  25035. #include <AudioUnit/AudioUnit.h>
  25036. #include <AudioUnit/AUCocoaUIView.h>
  25037. #include <CoreAudioKit/AUGenericView.h>
  25038. #if JUCE_SUPPORT_CARBON
  25039. #include <AudioToolbox/AudioUnitUtilities.h>
  25040. #include <AudioUnit/AudioUnitCarbonView.h>
  25041. #endif
  25042. BEGIN_JUCE_NAMESPACE
  25043. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  25044. #endif
  25045. #if JUCE_MAC
  25046. // Change this to disable logging of various activities
  25047. #ifndef AU_LOGGING
  25048. #define AU_LOGGING 1
  25049. #endif
  25050. #if AU_LOGGING
  25051. #define log(a) Logger::writeToLog(a);
  25052. #else
  25053. #define log(a)
  25054. #endif
  25055. namespace AudioUnitFormatHelpers
  25056. {
  25057. static int insideCallback = 0;
  25058. static const String osTypeToString (OSType type)
  25059. {
  25060. char s[4];
  25061. s[0] = (char) (((uint32) type) >> 24);
  25062. s[1] = (char) (((uint32) type) >> 16);
  25063. s[2] = (char) (((uint32) type) >> 8);
  25064. s[3] = (char) ((uint32) type);
  25065. return String (s, 4);
  25066. }
  25067. static OSType stringToOSType (const String& s1)
  25068. {
  25069. const String s (s1 + " ");
  25070. return (((OSType) (unsigned char) s[0]) << 24)
  25071. | (((OSType) (unsigned char) s[1]) << 16)
  25072. | (((OSType) (unsigned char) s[2]) << 8)
  25073. | ((OSType) (unsigned char) s[3]);
  25074. }
  25075. static const char* auIdentifierPrefix = "AudioUnit:";
  25076. static const String createAUPluginIdentifier (const ComponentDescription& desc)
  25077. {
  25078. jassert (osTypeToString ('abcd') == "abcd"); // agh, must have got the endianness wrong..
  25079. jassert (stringToOSType ("abcd") == (OSType) 'abcd'); // ditto
  25080. String s (auIdentifierPrefix);
  25081. if (desc.componentType == kAudioUnitType_MusicDevice)
  25082. s << "Synths/";
  25083. else if (desc.componentType == kAudioUnitType_MusicEffect
  25084. || desc.componentType == kAudioUnitType_Effect)
  25085. s << "Effects/";
  25086. else if (desc.componentType == kAudioUnitType_Generator)
  25087. s << "Generators/";
  25088. else if (desc.componentType == kAudioUnitType_Panner)
  25089. s << "Panners/";
  25090. s << osTypeToString (desc.componentType) << ","
  25091. << osTypeToString (desc.componentSubType) << ","
  25092. << osTypeToString (desc.componentManufacturer);
  25093. return s;
  25094. }
  25095. static void getAUDetails (ComponentRecord* comp, String& name, String& manufacturer)
  25096. {
  25097. Handle componentNameHandle = NewHandle (sizeof (void*));
  25098. Handle componentInfoHandle = NewHandle (sizeof (void*));
  25099. if (componentNameHandle != 0 && componentInfoHandle != 0)
  25100. {
  25101. ComponentDescription desc;
  25102. if (GetComponentInfo (comp, &desc, componentNameHandle, componentInfoHandle, 0) == noErr)
  25103. {
  25104. ConstStr255Param nameString = (ConstStr255Param) (*componentNameHandle);
  25105. ConstStr255Param infoString = (ConstStr255Param) (*componentInfoHandle);
  25106. if (nameString != 0 && nameString[0] != 0)
  25107. {
  25108. const String all ((const char*) nameString + 1, nameString[0]);
  25109. DBG ("name: "+ all);
  25110. manufacturer = all.upToFirstOccurrenceOf (":", false, false).trim();
  25111. name = all.fromFirstOccurrenceOf (":", false, false).trim();
  25112. }
  25113. if (infoString != 0 && infoString[0] != 0)
  25114. {
  25115. DBG ("info: " + String ((const char*) infoString + 1, infoString[0]));
  25116. }
  25117. if (name.isEmpty())
  25118. name = "<Unknown>";
  25119. }
  25120. DisposeHandle (componentNameHandle);
  25121. DisposeHandle (componentInfoHandle);
  25122. }
  25123. }
  25124. static bool getComponentDescFromIdentifier (const String& fileOrIdentifier, ComponentDescription& desc,
  25125. String& name, String& version, String& manufacturer)
  25126. {
  25127. zerostruct (desc);
  25128. if (fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  25129. {
  25130. String s (fileOrIdentifier.substring (jmax (fileOrIdentifier.lastIndexOfChar (':'),
  25131. fileOrIdentifier.lastIndexOfChar ('/')) + 1));
  25132. StringArray tokens;
  25133. tokens.addTokens (s, ",", String::empty);
  25134. tokens.trim();
  25135. tokens.removeEmptyStrings();
  25136. if (tokens.size() == 3)
  25137. {
  25138. desc.componentType = stringToOSType (tokens[0]);
  25139. desc.componentSubType = stringToOSType (tokens[1]);
  25140. desc.componentManufacturer = stringToOSType (tokens[2]);
  25141. ComponentRecord* comp = FindNextComponent (0, &desc);
  25142. if (comp != 0)
  25143. {
  25144. getAUDetails (comp, name, manufacturer);
  25145. return true;
  25146. }
  25147. }
  25148. }
  25149. return false;
  25150. }
  25151. }
  25152. class AudioUnitPluginWindowCarbon;
  25153. class AudioUnitPluginWindowCocoa;
  25154. class AudioUnitPluginInstance : public AudioPluginInstance
  25155. {
  25156. public:
  25157. ~AudioUnitPluginInstance();
  25158. void initialise();
  25159. // AudioPluginInstance methods:
  25160. void fillInPluginDescription (PluginDescription& desc) const
  25161. {
  25162. desc.name = pluginName;
  25163. desc.fileOrIdentifier = AudioUnitFormatHelpers::createAUPluginIdentifier (componentDesc);
  25164. desc.uid = ((int) componentDesc.componentType)
  25165. ^ ((int) componentDesc.componentSubType)
  25166. ^ ((int) componentDesc.componentManufacturer);
  25167. desc.lastFileModTime = 0;
  25168. desc.pluginFormatName = "AudioUnit";
  25169. desc.category = getCategory();
  25170. desc.manufacturerName = manufacturer;
  25171. desc.version = version;
  25172. desc.numInputChannels = getNumInputChannels();
  25173. desc.numOutputChannels = getNumOutputChannels();
  25174. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  25175. }
  25176. const String getName() const { return pluginName; }
  25177. bool acceptsMidi() const { return wantsMidiMessages; }
  25178. bool producesMidi() const { return false; }
  25179. // AudioProcessor methods:
  25180. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  25181. void releaseResources();
  25182. void processBlock (AudioSampleBuffer& buffer,
  25183. MidiBuffer& midiMessages);
  25184. bool hasEditor() const;
  25185. AudioProcessorEditor* createEditor();
  25186. const String getInputChannelName (int index) const;
  25187. bool isInputChannelStereoPair (int index) const;
  25188. const String getOutputChannelName (int index) const;
  25189. bool isOutputChannelStereoPair (int index) const;
  25190. int getNumParameters();
  25191. float getParameter (int index);
  25192. void setParameter (int index, float newValue);
  25193. const String getParameterName (int index);
  25194. const String getParameterText (int index);
  25195. bool isParameterAutomatable (int index) const;
  25196. int getNumPrograms();
  25197. int getCurrentProgram();
  25198. void setCurrentProgram (int index);
  25199. const String getProgramName (int index);
  25200. void changeProgramName (int index, const String& newName);
  25201. void getStateInformation (MemoryBlock& destData);
  25202. void getCurrentProgramStateInformation (MemoryBlock& destData);
  25203. void setStateInformation (const void* data, int sizeInBytes);
  25204. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  25205. juce_UseDebuggingNewOperator
  25206. private:
  25207. friend class AudioUnitPluginWindowCarbon;
  25208. friend class AudioUnitPluginWindowCocoa;
  25209. friend class AudioUnitPluginFormat;
  25210. ComponentDescription componentDesc;
  25211. String pluginName, manufacturer, version;
  25212. String fileOrIdentifier;
  25213. CriticalSection lock;
  25214. bool wantsMidiMessages, wasPlaying, prepared;
  25215. HeapBlock <AudioBufferList> outputBufferList;
  25216. AudioTimeStamp timeStamp;
  25217. AudioSampleBuffer* currentBuffer;
  25218. AudioUnit audioUnit;
  25219. Array <int> parameterIds;
  25220. bool getComponentDescFromFile (const String& fileOrIdentifier);
  25221. void setPluginCallbacks();
  25222. void getParameterListFromPlugin();
  25223. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25224. const AudioTimeStamp* inTimeStamp,
  25225. UInt32 inBusNumber,
  25226. UInt32 inNumberFrames,
  25227. AudioBufferList* ioData) const;
  25228. static OSStatus renderGetInputCallback (void* inRefCon,
  25229. AudioUnitRenderActionFlags* ioActionFlags,
  25230. const AudioTimeStamp* inTimeStamp,
  25231. UInt32 inBusNumber,
  25232. UInt32 inNumberFrames,
  25233. AudioBufferList* ioData)
  25234. {
  25235. return ((AudioUnitPluginInstance*) inRefCon)
  25236. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  25237. }
  25238. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  25239. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  25240. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  25241. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25242. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25243. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  25244. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  25245. {
  25246. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  25247. }
  25248. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  25249. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  25250. Float64* outCurrentMeasureDownBeat)
  25251. {
  25252. return ((AudioUnitPluginInstance*) inHostUserData)
  25253. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  25254. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  25255. }
  25256. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25257. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25258. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  25259. {
  25260. return ((AudioUnitPluginInstance*) inHostUserData)
  25261. ->getTransportState (outIsPlaying, outTransportStateChanged,
  25262. outCurrentSampleInTimeLine, outIsCycling,
  25263. outCycleStartBeat, outCycleEndBeat);
  25264. }
  25265. void getNumChannels (int& numIns, int& numOuts)
  25266. {
  25267. numIns = 0;
  25268. numOuts = 0;
  25269. AUChannelInfo supportedChannels [128];
  25270. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  25271. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  25272. 0, supportedChannels, &supportedChannelsSize) == noErr
  25273. && supportedChannelsSize > 0)
  25274. {
  25275. int explicitNumIns = 0;
  25276. int explicitNumOuts = 0;
  25277. int maximumNumIns = 0;
  25278. int maximumNumOuts = 0;
  25279. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  25280. {
  25281. const int inChannels = (int) supportedChannels[i].inChannels;
  25282. const int outChannels = (int) supportedChannels[i].outChannels;
  25283. if (inChannels < 0)
  25284. maximumNumIns = jmin (maximumNumIns, inChannels);
  25285. else
  25286. explicitNumIns = jmax (explicitNumIns, inChannels);
  25287. if (outChannels < 0)
  25288. maximumNumOuts = jmin (maximumNumOuts, outChannels);
  25289. else
  25290. explicitNumOuts = jmax (explicitNumOuts, outChannels);
  25291. }
  25292. if ((maximumNumIns == -1 && maximumNumOuts == -1) // (special meaning: any number of ins/outs, as long as they match)
  25293. || (maximumNumIns == -2 && maximumNumOuts == -1) // (special meaning: any number of ins/outs, even if they don't match)
  25294. || (maximumNumIns == -1 && maximumNumOuts == -2))
  25295. {
  25296. numIns = numOuts = 2;
  25297. }
  25298. else
  25299. {
  25300. numIns = explicitNumIns;
  25301. numOuts = explicitNumOuts;
  25302. if (maximumNumIns == -1 || (maximumNumIns < 0 && explicitNumIns <= -maximumNumIns))
  25303. numIns = 2;
  25304. if (maximumNumOuts == -1 || (maximumNumOuts < 0 && explicitNumOuts <= -maximumNumOuts))
  25305. numOuts = 2;
  25306. }
  25307. }
  25308. else
  25309. {
  25310. // (this really means the plugin will take any number of ins/outs as long
  25311. // as they are the same)
  25312. numIns = numOuts = 2;
  25313. }
  25314. }
  25315. const String getCategory() const;
  25316. AudioUnitPluginInstance (const String& fileOrIdentifier);
  25317. };
  25318. AudioUnitPluginInstance::AudioUnitPluginInstance (const String& fileOrIdentifier)
  25319. : fileOrIdentifier (fileOrIdentifier),
  25320. wantsMidiMessages (false), wasPlaying (false), prepared (false),
  25321. audioUnit (0),
  25322. currentBuffer (0)
  25323. {
  25324. using namespace AudioUnitFormatHelpers;
  25325. try
  25326. {
  25327. ++insideCallback;
  25328. log ("Opening AU: " + fileOrIdentifier);
  25329. if (getComponentDescFromFile (fileOrIdentifier))
  25330. {
  25331. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  25332. if (comp != 0)
  25333. {
  25334. audioUnit = (AudioUnit) OpenComponent (comp);
  25335. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  25336. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  25337. }
  25338. }
  25339. --insideCallback;
  25340. }
  25341. catch (...)
  25342. {
  25343. --insideCallback;
  25344. }
  25345. }
  25346. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  25347. {
  25348. const ScopedLock sl (lock);
  25349. jassert (AudioUnitFormatHelpers::insideCallback == 0);
  25350. if (audioUnit != 0)
  25351. {
  25352. AudioUnitUninitialize (audioUnit);
  25353. CloseComponent (audioUnit);
  25354. audioUnit = 0;
  25355. }
  25356. }
  25357. bool AudioUnitPluginInstance::getComponentDescFromFile (const String& fileOrIdentifier)
  25358. {
  25359. zerostruct (componentDesc);
  25360. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, componentDesc, pluginName, version, manufacturer))
  25361. return true;
  25362. const File file (fileOrIdentifier);
  25363. if (! file.hasFileExtension (".component"))
  25364. return false;
  25365. const char* const utf8 = fileOrIdentifier.toUTF8();
  25366. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  25367. strlen (utf8), file.isDirectory());
  25368. if (url != 0)
  25369. {
  25370. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  25371. CFRelease (url);
  25372. if (bundleRef != 0)
  25373. {
  25374. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  25375. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  25376. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  25377. if (pluginName.isEmpty())
  25378. pluginName = file.getFileNameWithoutExtension();
  25379. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  25380. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  25381. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  25382. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  25383. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  25384. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  25385. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  25386. UseResFile (resFileId);
  25387. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  25388. {
  25389. Handle h = Get1IndResource ('thng', i);
  25390. if (h != 0)
  25391. {
  25392. HLock (h);
  25393. const uint32* const types = (const uint32*) *h;
  25394. if (types[0] == kAudioUnitType_MusicDevice
  25395. || types[0] == kAudioUnitType_MusicEffect
  25396. || types[0] == kAudioUnitType_Effect
  25397. || types[0] == kAudioUnitType_Generator
  25398. || types[0] == kAudioUnitType_Panner)
  25399. {
  25400. componentDesc.componentType = types[0];
  25401. componentDesc.componentSubType = types[1];
  25402. componentDesc.componentManufacturer = types[2];
  25403. break;
  25404. }
  25405. HUnlock (h);
  25406. ReleaseResource (h);
  25407. }
  25408. }
  25409. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  25410. CFRelease (bundleRef);
  25411. }
  25412. }
  25413. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  25414. }
  25415. void AudioUnitPluginInstance::initialise()
  25416. {
  25417. getParameterListFromPlugin();
  25418. setPluginCallbacks();
  25419. int numIns, numOuts;
  25420. getNumChannels (numIns, numOuts);
  25421. setPlayConfigDetails (numIns, numOuts, 0, 0);
  25422. setLatencySamples (0);
  25423. }
  25424. void AudioUnitPluginInstance::getParameterListFromPlugin()
  25425. {
  25426. parameterIds.clear();
  25427. if (audioUnit != 0)
  25428. {
  25429. UInt32 paramListSize = 0;
  25430. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25431. 0, 0, &paramListSize);
  25432. if (paramListSize > 0)
  25433. {
  25434. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  25435. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25436. 0, &parameterIds.getReference(0), &paramListSize);
  25437. }
  25438. }
  25439. }
  25440. void AudioUnitPluginInstance::setPluginCallbacks()
  25441. {
  25442. if (audioUnit != 0)
  25443. {
  25444. {
  25445. AURenderCallbackStruct info;
  25446. zerostruct (info);
  25447. info.inputProcRefCon = this;
  25448. info.inputProc = renderGetInputCallback;
  25449. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  25450. 0, &info, sizeof (info));
  25451. }
  25452. {
  25453. HostCallbackInfo info;
  25454. zerostruct (info);
  25455. info.hostUserData = this;
  25456. info.beatAndTempoProc = getBeatAndTempoCallback;
  25457. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  25458. info.transportStateProc = getTransportStateCallback;
  25459. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  25460. 0, &info, sizeof (info));
  25461. }
  25462. }
  25463. }
  25464. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  25465. int samplesPerBlockExpected)
  25466. {
  25467. if (audioUnit != 0)
  25468. {
  25469. releaseResources();
  25470. Float64 sampleRateIn = 0, sampleRateOut = 0;
  25471. UInt32 sampleRateSize = sizeof (sampleRateIn);
  25472. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sampleRateIn, &sampleRateSize);
  25473. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sampleRateOut, &sampleRateSize);
  25474. if (sampleRateIn != sampleRate_ || sampleRateOut != sampleRate_)
  25475. {
  25476. Float64 sr = sampleRate_;
  25477. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sr, sizeof (Float64));
  25478. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sr, sizeof (Float64));
  25479. }
  25480. int numIns, numOuts;
  25481. getNumChannels (numIns, numOuts);
  25482. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  25483. Float64 latencySecs = 0.0;
  25484. UInt32 latencySize = sizeof (latencySecs);
  25485. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  25486. 0, &latencySecs, &latencySize);
  25487. setLatencySamples (roundToInt (latencySecs * sampleRate_));
  25488. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25489. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25490. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25491. {
  25492. AudioStreamBasicDescription stream;
  25493. zerostruct (stream);
  25494. stream.mSampleRate = sampleRate_;
  25495. stream.mFormatID = kAudioFormatLinearPCM;
  25496. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  25497. stream.mFramesPerPacket = 1;
  25498. stream.mBytesPerPacket = 4;
  25499. stream.mBytesPerFrame = 4;
  25500. stream.mBitsPerChannel = 32;
  25501. stream.mChannelsPerFrame = numIns;
  25502. OSStatus err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input,
  25503. 0, &stream, sizeof (stream));
  25504. stream.mChannelsPerFrame = numOuts;
  25505. err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output,
  25506. 0, &stream, sizeof (stream));
  25507. }
  25508. outputBufferList.calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1), 1);
  25509. outputBufferList->mNumberBuffers = numOuts;
  25510. for (int i = numOuts; --i >= 0;)
  25511. outputBufferList->mBuffers[i].mNumberChannels = 1;
  25512. zerostruct (timeStamp);
  25513. timeStamp.mSampleTime = 0;
  25514. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25515. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  25516. currentBuffer = 0;
  25517. wasPlaying = false;
  25518. prepared = (AudioUnitInitialize (audioUnit) == noErr);
  25519. }
  25520. }
  25521. void AudioUnitPluginInstance::releaseResources()
  25522. {
  25523. if (prepared)
  25524. {
  25525. AudioUnitUninitialize (audioUnit);
  25526. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25527. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25528. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25529. outputBufferList.free();
  25530. currentBuffer = 0;
  25531. prepared = false;
  25532. }
  25533. }
  25534. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25535. const AudioTimeStamp* inTimeStamp,
  25536. UInt32 inBusNumber,
  25537. UInt32 inNumberFrames,
  25538. AudioBufferList* ioData) const
  25539. {
  25540. if (inBusNumber == 0
  25541. && currentBuffer != 0)
  25542. {
  25543. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  25544. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  25545. {
  25546. if (i < currentBuffer->getNumChannels())
  25547. {
  25548. memcpy (ioData->mBuffers[i].mData,
  25549. currentBuffer->getSampleData (i, 0),
  25550. sizeof (float) * inNumberFrames);
  25551. }
  25552. else
  25553. {
  25554. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  25555. }
  25556. }
  25557. }
  25558. return noErr;
  25559. }
  25560. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  25561. MidiBuffer& midiMessages)
  25562. {
  25563. const int numSamples = buffer.getNumSamples();
  25564. if (prepared)
  25565. {
  25566. AudioUnitRenderActionFlags flags = 0;
  25567. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25568. for (int i = getNumOutputChannels(); --i >= 0;)
  25569. {
  25570. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  25571. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  25572. }
  25573. currentBuffer = &buffer;
  25574. if (wantsMidiMessages)
  25575. {
  25576. const uint8* midiEventData;
  25577. int midiEventSize, midiEventPosition;
  25578. MidiBuffer::Iterator i (midiMessages);
  25579. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  25580. {
  25581. if (midiEventSize <= 3)
  25582. MusicDeviceMIDIEvent (audioUnit,
  25583. midiEventData[0], midiEventData[1], midiEventData[2],
  25584. midiEventPosition);
  25585. else
  25586. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  25587. }
  25588. midiMessages.clear();
  25589. }
  25590. AudioUnitRender (audioUnit, &flags, &timeStamp,
  25591. 0, numSamples, outputBufferList);
  25592. timeStamp.mSampleTime += numSamples;
  25593. }
  25594. else
  25595. {
  25596. // Plugin not working correctly, so just bypass..
  25597. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  25598. buffer.clear (i, 0, buffer.getNumSamples());
  25599. }
  25600. }
  25601. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  25602. {
  25603. AudioPlayHead* const ph = getPlayHead();
  25604. AudioPlayHead::CurrentPositionInfo result;
  25605. if (ph != 0 && ph->getCurrentPosition (result))
  25606. {
  25607. if (outCurrentBeat != 0)
  25608. *outCurrentBeat = result.ppqPosition;
  25609. if (outCurrentTempo != 0)
  25610. *outCurrentTempo = result.bpm;
  25611. }
  25612. else
  25613. {
  25614. if (outCurrentBeat != 0)
  25615. *outCurrentBeat = 0;
  25616. if (outCurrentTempo != 0)
  25617. *outCurrentTempo = 120.0;
  25618. }
  25619. return noErr;
  25620. }
  25621. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  25622. Float32* outTimeSig_Numerator,
  25623. UInt32* outTimeSig_Denominator,
  25624. Float64* outCurrentMeasureDownBeat) const
  25625. {
  25626. AudioPlayHead* const ph = getPlayHead();
  25627. AudioPlayHead::CurrentPositionInfo result;
  25628. if (ph != 0 && ph->getCurrentPosition (result))
  25629. {
  25630. if (outTimeSig_Numerator != 0)
  25631. *outTimeSig_Numerator = result.timeSigNumerator;
  25632. if (outTimeSig_Denominator != 0)
  25633. *outTimeSig_Denominator = result.timeSigDenominator;
  25634. if (outDeltaSampleOffsetToNextBeat != 0)
  25635. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  25636. if (outCurrentMeasureDownBeat != 0)
  25637. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  25638. }
  25639. else
  25640. {
  25641. if (outDeltaSampleOffsetToNextBeat != 0)
  25642. *outDeltaSampleOffsetToNextBeat = 0;
  25643. if (outTimeSig_Numerator != 0)
  25644. *outTimeSig_Numerator = 4;
  25645. if (outTimeSig_Denominator != 0)
  25646. *outTimeSig_Denominator = 4;
  25647. if (outCurrentMeasureDownBeat != 0)
  25648. *outCurrentMeasureDownBeat = 0;
  25649. }
  25650. return noErr;
  25651. }
  25652. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  25653. Boolean* outTransportStateChanged,
  25654. Float64* outCurrentSampleInTimeLine,
  25655. Boolean* outIsCycling,
  25656. Float64* outCycleStartBeat,
  25657. Float64* outCycleEndBeat)
  25658. {
  25659. AudioPlayHead* const ph = getPlayHead();
  25660. AudioPlayHead::CurrentPositionInfo result;
  25661. if (ph != 0 && ph->getCurrentPosition (result))
  25662. {
  25663. if (outIsPlaying != 0)
  25664. *outIsPlaying = result.isPlaying;
  25665. if (outTransportStateChanged != 0)
  25666. {
  25667. *outTransportStateChanged = result.isPlaying != wasPlaying;
  25668. wasPlaying = result.isPlaying;
  25669. }
  25670. if (outCurrentSampleInTimeLine != 0)
  25671. *outCurrentSampleInTimeLine = roundToInt (result.timeInSeconds * getSampleRate());
  25672. if (outIsCycling != 0)
  25673. *outIsCycling = false;
  25674. if (outCycleStartBeat != 0)
  25675. *outCycleStartBeat = 0;
  25676. if (outCycleEndBeat != 0)
  25677. *outCycleEndBeat = 0;
  25678. }
  25679. else
  25680. {
  25681. if (outIsPlaying != 0)
  25682. *outIsPlaying = false;
  25683. if (outTransportStateChanged != 0)
  25684. *outTransportStateChanged = false;
  25685. if (outCurrentSampleInTimeLine != 0)
  25686. *outCurrentSampleInTimeLine = 0;
  25687. if (outIsCycling != 0)
  25688. *outIsCycling = false;
  25689. if (outCycleStartBeat != 0)
  25690. *outCycleStartBeat = 0;
  25691. if (outCycleEndBeat != 0)
  25692. *outCycleEndBeat = 0;
  25693. }
  25694. return noErr;
  25695. }
  25696. class AudioUnitPluginWindowCocoa : public AudioProcessorEditor
  25697. {
  25698. public:
  25699. AudioUnitPluginWindowCocoa (AudioUnitPluginInstance& plugin_, const bool createGenericViewIfNeeded)
  25700. : AudioProcessorEditor (&plugin_),
  25701. plugin (plugin_)
  25702. {
  25703. addAndMakeVisible (&wrapper);
  25704. setOpaque (true);
  25705. setVisible (true);
  25706. setSize (100, 100);
  25707. createView (createGenericViewIfNeeded);
  25708. }
  25709. ~AudioUnitPluginWindowCocoa()
  25710. {
  25711. const bool wasValid = isValid();
  25712. wrapper.setView (0);
  25713. if (wasValid)
  25714. plugin.editorBeingDeleted (this);
  25715. }
  25716. bool isValid() const { return wrapper.getView() != 0; }
  25717. void paint (Graphics& g)
  25718. {
  25719. g.fillAll (Colours::white);
  25720. }
  25721. void resized()
  25722. {
  25723. wrapper.setSize (getWidth(), getHeight());
  25724. }
  25725. private:
  25726. AudioUnitPluginInstance& plugin;
  25727. NSViewComponent wrapper;
  25728. bool createView (const bool createGenericViewIfNeeded)
  25729. {
  25730. NSView* pluginView = 0;
  25731. UInt32 dataSize = 0;
  25732. Boolean isWritable = false;
  25733. AudioUnitInitialize (plugin.audioUnit);
  25734. if (AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25735. 0, &dataSize, &isWritable) == noErr
  25736. && dataSize != 0
  25737. && AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25738. 0, &dataSize, &isWritable) == noErr)
  25739. {
  25740. HeapBlock <AudioUnitCocoaViewInfo> info;
  25741. info.calloc (dataSize, 1);
  25742. if (AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25743. 0, info, &dataSize) == noErr)
  25744. {
  25745. NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
  25746. NSString* path = (NSString*) CFURLCopyPath (info->mCocoaAUViewBundleLocation);
  25747. NSBundle* viewBundle = [NSBundle bundleWithPath: [path autorelease]];
  25748. Class viewClass = [viewBundle classNamed: viewClassName];
  25749. if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
  25750. && [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
  25751. && [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
  25752. {
  25753. id factory = [[[viewClass alloc] init] autorelease];
  25754. pluginView = [factory uiViewForAudioUnit: plugin.audioUnit
  25755. withSize: NSMakeSize (getWidth(), getHeight())];
  25756. }
  25757. for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
  25758. {
  25759. CFRelease (info->mCocoaAUViewClass[i]);
  25760. CFRelease (info->mCocoaAUViewBundleLocation);
  25761. }
  25762. }
  25763. }
  25764. if (createGenericViewIfNeeded && (pluginView == 0))
  25765. pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.audioUnit];
  25766. wrapper.setView (pluginView);
  25767. if (pluginView != 0)
  25768. setSize ([pluginView frame].size.width,
  25769. [pluginView frame].size.height);
  25770. return pluginView != 0;
  25771. }
  25772. };
  25773. #if JUCE_SUPPORT_CARBON
  25774. class AudioUnitPluginWindowCarbon : public AudioProcessorEditor
  25775. {
  25776. public:
  25777. AudioUnitPluginWindowCarbon (AudioUnitPluginInstance& plugin_)
  25778. : AudioProcessorEditor (&plugin_),
  25779. plugin (plugin_),
  25780. viewComponent (0)
  25781. {
  25782. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  25783. setOpaque (true);
  25784. setVisible (true);
  25785. setSize (400, 300);
  25786. ComponentDescription viewList [16];
  25787. UInt32 viewListSize = sizeof (viewList);
  25788. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  25789. 0, &viewList, &viewListSize);
  25790. componentRecord = FindNextComponent (0, &viewList[0]);
  25791. }
  25792. ~AudioUnitPluginWindowCarbon()
  25793. {
  25794. innerWrapper = 0;
  25795. if (isValid())
  25796. plugin.editorBeingDeleted (this);
  25797. }
  25798. bool isValid() const throw() { return componentRecord != 0; }
  25799. void paint (Graphics& g)
  25800. {
  25801. g.fillAll (Colours::black);
  25802. }
  25803. void resized()
  25804. {
  25805. innerWrapper->setSize (getWidth(), getHeight());
  25806. }
  25807. bool keyStateChanged (bool)
  25808. {
  25809. return false;
  25810. }
  25811. bool keyPressed (const KeyPress&)
  25812. {
  25813. return false;
  25814. }
  25815. AudioUnit getAudioUnit() const { return plugin.audioUnit; }
  25816. AudioUnitCarbonView getViewComponent()
  25817. {
  25818. if (viewComponent == 0 && componentRecord != 0)
  25819. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  25820. return viewComponent;
  25821. }
  25822. void closeViewComponent()
  25823. {
  25824. if (viewComponent != 0)
  25825. {
  25826. log ("Closing AU GUI: " + plugin.getName());
  25827. CloseComponent (viewComponent);
  25828. viewComponent = 0;
  25829. }
  25830. }
  25831. juce_UseDebuggingNewOperator
  25832. private:
  25833. AudioUnitPluginInstance& plugin;
  25834. ComponentRecord* componentRecord;
  25835. AudioUnitCarbonView viewComponent;
  25836. class InnerWrapperComponent : public CarbonViewWrapperComponent
  25837. {
  25838. public:
  25839. InnerWrapperComponent (AudioUnitPluginWindowCarbon* const owner_)
  25840. : owner (owner_)
  25841. {
  25842. }
  25843. ~InnerWrapperComponent()
  25844. {
  25845. deleteWindow();
  25846. }
  25847. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  25848. {
  25849. log ("Opening AU GUI: " + owner->plugin.getName());
  25850. AudioUnitCarbonView viewComponent = owner->getViewComponent();
  25851. if (viewComponent == 0)
  25852. return 0;
  25853. Float32Point pos = { 0, 0 };
  25854. Float32Point size = { 250, 200 };
  25855. HIViewRef pluginView = 0;
  25856. AudioUnitCarbonViewCreate (viewComponent,
  25857. owner->getAudioUnit(),
  25858. windowRef,
  25859. rootView,
  25860. &pos,
  25861. &size,
  25862. (ControlRef*) &pluginView);
  25863. return pluginView;
  25864. }
  25865. void removeView (HIViewRef)
  25866. {
  25867. owner->closeViewComponent();
  25868. }
  25869. private:
  25870. AudioUnitPluginWindowCarbon* const owner;
  25871. };
  25872. friend class InnerWrapperComponent;
  25873. ScopedPointer<InnerWrapperComponent> innerWrapper;
  25874. };
  25875. #endif
  25876. bool AudioUnitPluginInstance::hasEditor() const
  25877. {
  25878. return true;
  25879. }
  25880. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  25881. {
  25882. ScopedPointer<AudioProcessorEditor> w (new AudioUnitPluginWindowCocoa (*this, false));
  25883. if (! static_cast <AudioUnitPluginWindowCocoa*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  25884. w = 0;
  25885. #if JUCE_SUPPORT_CARBON
  25886. if (w == 0)
  25887. {
  25888. w = new AudioUnitPluginWindowCarbon (*this);
  25889. if (! static_cast <AudioUnitPluginWindowCarbon*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  25890. w = 0;
  25891. }
  25892. #endif
  25893. if (w == 0)
  25894. w = new AudioUnitPluginWindowCocoa (*this, true); // use AUGenericView as a fallback
  25895. return w.release();
  25896. }
  25897. const String AudioUnitPluginInstance::getCategory() const
  25898. {
  25899. const char* result = 0;
  25900. switch (componentDesc.componentType)
  25901. {
  25902. case kAudioUnitType_Effect:
  25903. case kAudioUnitType_MusicEffect:
  25904. result = "Effect";
  25905. break;
  25906. case kAudioUnitType_MusicDevice:
  25907. result = "Synth";
  25908. break;
  25909. case kAudioUnitType_Generator:
  25910. result = "Generator";
  25911. break;
  25912. case kAudioUnitType_Panner:
  25913. result = "Panner";
  25914. break;
  25915. default:
  25916. break;
  25917. }
  25918. return result;
  25919. }
  25920. int AudioUnitPluginInstance::getNumParameters()
  25921. {
  25922. return parameterIds.size();
  25923. }
  25924. float AudioUnitPluginInstance::getParameter (int index)
  25925. {
  25926. const ScopedLock sl (lock);
  25927. Float32 value = 0.0f;
  25928. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  25929. {
  25930. AudioUnitGetParameter (audioUnit,
  25931. (UInt32) parameterIds.getUnchecked (index),
  25932. kAudioUnitScope_Global, 0,
  25933. &value);
  25934. }
  25935. return value;
  25936. }
  25937. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  25938. {
  25939. const ScopedLock sl (lock);
  25940. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  25941. {
  25942. AudioUnitSetParameter (audioUnit,
  25943. (UInt32) parameterIds.getUnchecked (index),
  25944. kAudioUnitScope_Global, 0,
  25945. newValue, 0);
  25946. }
  25947. }
  25948. const String AudioUnitPluginInstance::getParameterName (int index)
  25949. {
  25950. AudioUnitParameterInfo info;
  25951. zerostruct (info);
  25952. UInt32 sz = sizeof (info);
  25953. String name;
  25954. if (AudioUnitGetProperty (audioUnit,
  25955. kAudioUnitProperty_ParameterInfo,
  25956. kAudioUnitScope_Global,
  25957. parameterIds [index], &info, &sz) == noErr)
  25958. {
  25959. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  25960. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  25961. else
  25962. name = String (info.name, sizeof (info.name));
  25963. }
  25964. return name;
  25965. }
  25966. const String AudioUnitPluginInstance::getParameterText (int index)
  25967. {
  25968. return String (getParameter (index));
  25969. }
  25970. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  25971. {
  25972. AudioUnitParameterInfo info;
  25973. UInt32 sz = sizeof (info);
  25974. if (AudioUnitGetProperty (audioUnit,
  25975. kAudioUnitProperty_ParameterInfo,
  25976. kAudioUnitScope_Global,
  25977. parameterIds [index], &info, &sz) == noErr)
  25978. {
  25979. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  25980. }
  25981. return true;
  25982. }
  25983. int AudioUnitPluginInstance::getNumPrograms()
  25984. {
  25985. CFArrayRef presets;
  25986. UInt32 sz = sizeof (CFArrayRef);
  25987. int num = 0;
  25988. if (AudioUnitGetProperty (audioUnit,
  25989. kAudioUnitProperty_FactoryPresets,
  25990. kAudioUnitScope_Global,
  25991. 0, &presets, &sz) == noErr)
  25992. {
  25993. num = (int) CFArrayGetCount (presets);
  25994. CFRelease (presets);
  25995. }
  25996. return num;
  25997. }
  25998. int AudioUnitPluginInstance::getCurrentProgram()
  25999. {
  26000. AUPreset current;
  26001. current.presetNumber = 0;
  26002. UInt32 sz = sizeof (AUPreset);
  26003. AudioUnitGetProperty (audioUnit,
  26004. kAudioUnitProperty_FactoryPresets,
  26005. kAudioUnitScope_Global,
  26006. 0, &current, &sz);
  26007. return current.presetNumber;
  26008. }
  26009. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  26010. {
  26011. AUPreset current;
  26012. current.presetNumber = newIndex;
  26013. current.presetName = 0;
  26014. AudioUnitSetProperty (audioUnit,
  26015. kAudioUnitProperty_FactoryPresets,
  26016. kAudioUnitScope_Global,
  26017. 0, &current, sizeof (AUPreset));
  26018. }
  26019. const String AudioUnitPluginInstance::getProgramName (int index)
  26020. {
  26021. String s;
  26022. CFArrayRef presets;
  26023. UInt32 sz = sizeof (CFArrayRef);
  26024. if (AudioUnitGetProperty (audioUnit,
  26025. kAudioUnitProperty_FactoryPresets,
  26026. kAudioUnitScope_Global,
  26027. 0, &presets, &sz) == noErr)
  26028. {
  26029. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  26030. {
  26031. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  26032. if (p != 0 && p->presetNumber == index)
  26033. {
  26034. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  26035. break;
  26036. }
  26037. }
  26038. CFRelease (presets);
  26039. }
  26040. return s;
  26041. }
  26042. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  26043. {
  26044. jassertfalse; // xxx not implemented!
  26045. }
  26046. const String AudioUnitPluginInstance::getInputChannelName (int index) const
  26047. {
  26048. if (((unsigned int) index) < (unsigned int) getNumInputChannels())
  26049. return "Input " + String (index + 1);
  26050. return String::empty;
  26051. }
  26052. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  26053. {
  26054. if (((unsigned int) index) >= (unsigned int) getNumInputChannels())
  26055. return false;
  26056. return true;
  26057. }
  26058. const String AudioUnitPluginInstance::getOutputChannelName (int index) const
  26059. {
  26060. if (((unsigned int) index) < (unsigned int) getNumOutputChannels())
  26061. return "Output " + String (index + 1);
  26062. return String::empty;
  26063. }
  26064. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  26065. {
  26066. if (((unsigned int) index) >= (unsigned int) getNumOutputChannels())
  26067. return false;
  26068. return true;
  26069. }
  26070. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  26071. {
  26072. getCurrentProgramStateInformation (destData);
  26073. }
  26074. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  26075. {
  26076. CFPropertyListRef propertyList = 0;
  26077. UInt32 sz = sizeof (CFPropertyListRef);
  26078. if (AudioUnitGetProperty (audioUnit,
  26079. kAudioUnitProperty_ClassInfo,
  26080. kAudioUnitScope_Global,
  26081. 0, &propertyList, &sz) == noErr)
  26082. {
  26083. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  26084. CFWriteStreamOpen (stream);
  26085. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  26086. CFWriteStreamClose (stream);
  26087. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  26088. destData.setSize (bytesWritten);
  26089. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  26090. CFRelease (data);
  26091. CFRelease (stream);
  26092. CFRelease (propertyList);
  26093. }
  26094. }
  26095. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  26096. {
  26097. setCurrentProgramStateInformation (data, sizeInBytes);
  26098. }
  26099. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  26100. {
  26101. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  26102. (const UInt8*) data,
  26103. sizeInBytes,
  26104. kCFAllocatorNull);
  26105. CFReadStreamOpen (stream);
  26106. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  26107. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  26108. stream,
  26109. 0,
  26110. kCFPropertyListImmutable,
  26111. &format,
  26112. 0);
  26113. CFRelease (stream);
  26114. if (propertyList != 0)
  26115. AudioUnitSetProperty (audioUnit,
  26116. kAudioUnitProperty_ClassInfo,
  26117. kAudioUnitScope_Global,
  26118. 0, &propertyList, sizeof (propertyList));
  26119. }
  26120. AudioUnitPluginFormat::AudioUnitPluginFormat()
  26121. {
  26122. }
  26123. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  26124. {
  26125. }
  26126. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  26127. const String& fileOrIdentifier)
  26128. {
  26129. if (! fileMightContainThisPluginType (fileOrIdentifier))
  26130. return;
  26131. PluginDescription desc;
  26132. desc.fileOrIdentifier = fileOrIdentifier;
  26133. desc.uid = 0;
  26134. try
  26135. {
  26136. ScopedPointer <AudioPluginInstance> createdInstance (createInstanceFromDescription (desc));
  26137. AudioUnitPluginInstance* const auInstance = dynamic_cast <AudioUnitPluginInstance*> ((AudioPluginInstance*) createdInstance);
  26138. if (auInstance != 0)
  26139. {
  26140. auInstance->fillInPluginDescription (desc);
  26141. results.add (new PluginDescription (desc));
  26142. }
  26143. }
  26144. catch (...)
  26145. {
  26146. // crashed while loading...
  26147. }
  26148. }
  26149. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  26150. {
  26151. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  26152. {
  26153. ScopedPointer <AudioUnitPluginInstance> result (new AudioUnitPluginInstance (desc.fileOrIdentifier));
  26154. if (result->audioUnit != 0)
  26155. {
  26156. result->initialise();
  26157. return result.release();
  26158. }
  26159. }
  26160. return 0;
  26161. }
  26162. const StringArray AudioUnitPluginFormat::searchPathsForPlugins (const FileSearchPath& /*directoriesToSearch*/,
  26163. const bool /*recursive*/)
  26164. {
  26165. StringArray result;
  26166. ComponentRecord* comp = 0;
  26167. ComponentDescription desc;
  26168. zerostruct (desc);
  26169. for (;;)
  26170. {
  26171. zerostruct (desc);
  26172. comp = FindNextComponent (comp, &desc);
  26173. if (comp == 0)
  26174. break;
  26175. GetComponentInfo (comp, &desc, 0, 0, 0);
  26176. if (desc.componentType == kAudioUnitType_MusicDevice
  26177. || desc.componentType == kAudioUnitType_MusicEffect
  26178. || desc.componentType == kAudioUnitType_Effect
  26179. || desc.componentType == kAudioUnitType_Generator
  26180. || desc.componentType == kAudioUnitType_Panner)
  26181. {
  26182. const String s (AudioUnitFormatHelpers::createAUPluginIdentifier (desc));
  26183. DBG (s);
  26184. result.add (s);
  26185. }
  26186. }
  26187. return result;
  26188. }
  26189. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  26190. {
  26191. ComponentDescription desc;
  26192. String name, version, manufacturer;
  26193. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer))
  26194. return FindNextComponent (0, &desc) != 0;
  26195. const File f (fileOrIdentifier);
  26196. return f.hasFileExtension (".component")
  26197. && f.isDirectory();
  26198. }
  26199. const String AudioUnitPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  26200. {
  26201. ComponentDescription desc;
  26202. String name, version, manufacturer;
  26203. AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer);
  26204. if (name.isEmpty())
  26205. name = fileOrIdentifier;
  26206. return name;
  26207. }
  26208. bool AudioUnitPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  26209. {
  26210. if (desc.fileOrIdentifier.startsWithIgnoreCase (AudioUnitFormatHelpers::auIdentifierPrefix))
  26211. return fileMightContainThisPluginType (desc.fileOrIdentifier);
  26212. else
  26213. return File (desc.fileOrIdentifier).exists();
  26214. }
  26215. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  26216. {
  26217. return FileSearchPath ("/(Default AudioUnit locations)");
  26218. }
  26219. #endif
  26220. END_JUCE_NAMESPACE
  26221. #undef log
  26222. #endif
  26223. /*** End of inlined file: juce_AudioUnitPluginFormat.mm ***/
  26224. /*** Start of inlined file: juce_VSTPluginFormat.mm ***/
  26225. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  26226. #define JUCE_MAC_VST_INCLUDED 1
  26227. /*** Start of inlined file: juce_VSTPluginFormat.cpp ***/
  26228. #if JUCE_PLUGINHOST_VST && (JUCE_MAC_VST_INCLUDED || ! JUCE_MAC)
  26229. #if JUCE_WINDOWS
  26230. #undef _WIN32_WINNT
  26231. #define _WIN32_WINNT 0x500
  26232. #undef STRICT
  26233. #define STRICT
  26234. #include <windows.h>
  26235. #include <float.h>
  26236. #pragma warning (disable : 4312 4355)
  26237. #elif JUCE_LINUX
  26238. #include <float.h>
  26239. #include <sys/time.h>
  26240. #include <X11/Xlib.h>
  26241. #include <X11/Xutil.h>
  26242. #include <X11/Xatom.h>
  26243. #undef Font
  26244. #undef KeyPress
  26245. #undef Drawable
  26246. #undef Time
  26247. #else
  26248. #include <Cocoa/Cocoa.h>
  26249. #include <Carbon/Carbon.h>
  26250. #endif
  26251. #if ! (JUCE_MAC && JUCE_64BIT)
  26252. BEGIN_JUCE_NAMESPACE
  26253. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  26254. #endif
  26255. #undef PRAGMA_ALIGN_SUPPORTED
  26256. #define VST_FORCE_DEPRECATED 0
  26257. #if JUCE_MSVC
  26258. #pragma warning (push)
  26259. #pragma warning (disable: 4996)
  26260. #endif
  26261. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  26262. your include path if you want to add VST support.
  26263. If you're not interested in VSTs, you can disable them by changing the
  26264. JUCE_PLUGINHOST_VST flag in juce_Config.h
  26265. */
  26266. #include "pluginterfaces/vst2.x/aeffectx.h"
  26267. #if JUCE_MSVC
  26268. #pragma warning (pop)
  26269. #endif
  26270. #if JUCE_LINUX
  26271. #define Font JUCE_NAMESPACE::Font
  26272. #define KeyPress JUCE_NAMESPACE::KeyPress
  26273. #define Drawable JUCE_NAMESPACE::Drawable
  26274. #define Time JUCE_NAMESPACE::Time
  26275. #endif
  26276. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  26277. #ifdef __aeffect__
  26278. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26279. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26280. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  26281. events to the list.
  26282. This is used by both the VST hosting code and the plugin wrapper.
  26283. */
  26284. class VSTMidiEventList
  26285. {
  26286. public:
  26287. VSTMidiEventList()
  26288. : numEventsUsed (0), numEventsAllocated (0)
  26289. {
  26290. }
  26291. ~VSTMidiEventList()
  26292. {
  26293. freeEvents();
  26294. }
  26295. void clear()
  26296. {
  26297. numEventsUsed = 0;
  26298. if (events != 0)
  26299. events->numEvents = 0;
  26300. }
  26301. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  26302. {
  26303. ensureSize (numEventsUsed + 1);
  26304. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  26305. events->numEvents = ++numEventsUsed;
  26306. if (numBytes <= 4)
  26307. {
  26308. if (e->type == kVstSysExType)
  26309. {
  26310. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  26311. e->type = kVstMidiType;
  26312. e->byteSize = sizeof (VstMidiEvent);
  26313. e->noteLength = 0;
  26314. e->noteOffset = 0;
  26315. e->detune = 0;
  26316. e->noteOffVelocity = 0;
  26317. }
  26318. e->deltaFrames = frameOffset;
  26319. memcpy (e->midiData, midiData, numBytes);
  26320. }
  26321. else
  26322. {
  26323. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  26324. if (se->type == kVstSysExType)
  26325. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  26326. else
  26327. se->sysexDump = (char*) juce_malloc (numBytes);
  26328. memcpy (se->sysexDump, midiData, numBytes);
  26329. se->type = kVstSysExType;
  26330. se->byteSize = sizeof (VstMidiSysexEvent);
  26331. se->deltaFrames = frameOffset;
  26332. se->flags = 0;
  26333. se->dumpBytes = numBytes;
  26334. se->resvd1 = 0;
  26335. se->resvd2 = 0;
  26336. }
  26337. }
  26338. // Handy method to pull the events out of an event buffer supplied by the host
  26339. // or plugin.
  26340. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  26341. {
  26342. for (int i = 0; i < events->numEvents; ++i)
  26343. {
  26344. const VstEvent* const e = events->events[i];
  26345. if (e != 0)
  26346. {
  26347. if (e->type == kVstMidiType)
  26348. {
  26349. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  26350. 4, e->deltaFrames);
  26351. }
  26352. else if (e->type == kVstSysExType)
  26353. {
  26354. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  26355. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  26356. e->deltaFrames);
  26357. }
  26358. }
  26359. }
  26360. }
  26361. void ensureSize (int numEventsNeeded)
  26362. {
  26363. if (numEventsNeeded > numEventsAllocated)
  26364. {
  26365. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  26366. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  26367. if (events == 0)
  26368. events.calloc (size, 1);
  26369. else
  26370. events.realloc (size, 1);
  26371. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  26372. {
  26373. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  26374. (int) sizeof (VstMidiSysexEvent)));
  26375. e->type = kVstMidiType;
  26376. e->byteSize = sizeof (VstMidiEvent);
  26377. events->events[i] = (VstEvent*) e;
  26378. }
  26379. numEventsAllocated = numEventsNeeded;
  26380. }
  26381. }
  26382. void freeEvents()
  26383. {
  26384. if (events != 0)
  26385. {
  26386. for (int i = numEventsAllocated; --i >= 0;)
  26387. {
  26388. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  26389. if (e->type == kVstSysExType)
  26390. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  26391. juce_free (e);
  26392. }
  26393. events.free();
  26394. numEventsUsed = 0;
  26395. numEventsAllocated = 0;
  26396. }
  26397. }
  26398. HeapBlock <VstEvents> events;
  26399. private:
  26400. int numEventsUsed, numEventsAllocated;
  26401. };
  26402. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26403. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26404. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  26405. #if ! JUCE_WINDOWS
  26406. static void _fpreset() {}
  26407. static void _clearfp() {}
  26408. #endif
  26409. extern void juce_callAnyTimersSynchronously();
  26410. const int fxbVersionNum = 1;
  26411. struct fxProgram
  26412. {
  26413. long chunkMagic; // 'CcnK'
  26414. long byteSize; // of this chunk, excl. magic + byteSize
  26415. long fxMagic; // 'FxCk'
  26416. long version;
  26417. long fxID; // fx unique id
  26418. long fxVersion;
  26419. long numParams;
  26420. char prgName[28];
  26421. float params[1]; // variable no. of parameters
  26422. };
  26423. struct fxSet
  26424. {
  26425. long chunkMagic; // 'CcnK'
  26426. long byteSize; // of this chunk, excl. magic + byteSize
  26427. long fxMagic; // 'FxBk'
  26428. long version;
  26429. long fxID; // fx unique id
  26430. long fxVersion;
  26431. long numPrograms;
  26432. char future[128];
  26433. fxProgram programs[1]; // variable no. of programs
  26434. };
  26435. struct fxChunkSet
  26436. {
  26437. long chunkMagic; // 'CcnK'
  26438. long byteSize; // of this chunk, excl. magic + byteSize
  26439. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26440. long version;
  26441. long fxID; // fx unique id
  26442. long fxVersion;
  26443. long numPrograms;
  26444. char future[128];
  26445. long chunkSize;
  26446. char chunk[8]; // variable
  26447. };
  26448. struct fxProgramSet
  26449. {
  26450. long chunkMagic; // 'CcnK'
  26451. long byteSize; // of this chunk, excl. magic + byteSize
  26452. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26453. long version;
  26454. long fxID; // fx unique id
  26455. long fxVersion;
  26456. long numPrograms;
  26457. char name[28];
  26458. long chunkSize;
  26459. char chunk[8]; // variable
  26460. };
  26461. static long vst_swap (const long x) throw()
  26462. {
  26463. #ifdef JUCE_LITTLE_ENDIAN
  26464. return (long) ByteOrder::swap ((uint32) x);
  26465. #else
  26466. return x;
  26467. #endif
  26468. }
  26469. static float vst_swapFloat (const float x) throw()
  26470. {
  26471. #ifdef JUCE_LITTLE_ENDIAN
  26472. union { uint32 asInt; float asFloat; } n;
  26473. n.asFloat = x;
  26474. n.asInt = ByteOrder::swap (n.asInt);
  26475. return n.asFloat;
  26476. #else
  26477. return x;
  26478. #endif
  26479. }
  26480. static double getVSTHostTimeNanoseconds()
  26481. {
  26482. #if JUCE_WINDOWS
  26483. return timeGetTime() * 1000000.0;
  26484. #elif JUCE_LINUX
  26485. timeval micro;
  26486. gettimeofday (&micro, 0);
  26487. return micro.tv_usec * 1000.0;
  26488. #elif JUCE_MAC
  26489. UnsignedWide micro;
  26490. Microseconds (&micro);
  26491. return micro.lo * 1000.0;
  26492. #endif
  26493. }
  26494. typedef AEffect* (*MainCall) (audioMasterCallback);
  26495. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  26496. static int shellUIDToCreate = 0;
  26497. static int insideVSTCallback = 0;
  26498. class VSTPluginWindow;
  26499. // Change this to disable logging of various VST activities
  26500. #ifndef VST_LOGGING
  26501. #define VST_LOGGING 1
  26502. #endif
  26503. #if VST_LOGGING
  26504. #define log(a) Logger::writeToLog(a);
  26505. #else
  26506. #define log(a)
  26507. #endif
  26508. #if JUCE_MAC && JUCE_PPC
  26509. static void* NewCFMFromMachO (void* const machofp) throw()
  26510. {
  26511. void* result = juce_malloc (8);
  26512. ((void**) result)[0] = machofp;
  26513. ((void**) result)[1] = result;
  26514. return result;
  26515. }
  26516. #endif
  26517. #if JUCE_LINUX
  26518. extern Display* display;
  26519. extern XContext windowHandleXContext;
  26520. typedef void (*EventProcPtr) (XEvent* ev);
  26521. static bool xErrorTriggered;
  26522. static int temporaryErrorHandler (Display*, XErrorEvent*)
  26523. {
  26524. xErrorTriggered = true;
  26525. return 0;
  26526. }
  26527. static int getPropertyFromXWindow (Window handle, Atom atom)
  26528. {
  26529. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  26530. xErrorTriggered = false;
  26531. int userSize;
  26532. unsigned long bytes, userCount;
  26533. unsigned char* data;
  26534. Atom userType;
  26535. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  26536. &userType, &userSize, &userCount, &bytes, &data);
  26537. XSetErrorHandler (oldErrorHandler);
  26538. return (userCount == 1 && ! xErrorTriggered) ? *reinterpret_cast<int*> (data)
  26539. : 0;
  26540. }
  26541. static Window getChildWindow (Window windowToCheck)
  26542. {
  26543. Window rootWindow, parentWindow;
  26544. Window* childWindows;
  26545. unsigned int numChildren;
  26546. XQueryTree (display,
  26547. windowToCheck,
  26548. &rootWindow,
  26549. &parentWindow,
  26550. &childWindows,
  26551. &numChildren);
  26552. if (numChildren > 0)
  26553. return childWindows [0];
  26554. return 0;
  26555. }
  26556. static void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  26557. {
  26558. if (e.mods.isLeftButtonDown())
  26559. {
  26560. ev.xbutton.button = Button1;
  26561. ev.xbutton.state |= Button1Mask;
  26562. }
  26563. else if (e.mods.isRightButtonDown())
  26564. {
  26565. ev.xbutton.button = Button3;
  26566. ev.xbutton.state |= Button3Mask;
  26567. }
  26568. else if (e.mods.isMiddleButtonDown())
  26569. {
  26570. ev.xbutton.button = Button2;
  26571. ev.xbutton.state |= Button2Mask;
  26572. }
  26573. }
  26574. static void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  26575. {
  26576. if (e.mods.isLeftButtonDown()) ev.xmotion.state |= Button1Mask;
  26577. else if (e.mods.isRightButtonDown()) ev.xmotion.state |= Button3Mask;
  26578. else if (e.mods.isMiddleButtonDown()) ev.xmotion.state |= Button2Mask;
  26579. }
  26580. static void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  26581. {
  26582. if (e.mods.isLeftButtonDown()) ev.xcrossing.state |= Button1Mask;
  26583. else if (e.mods.isRightButtonDown()) ev.xcrossing.state |= Button3Mask;
  26584. else if (e.mods.isMiddleButtonDown()) ev.xcrossing.state |= Button2Mask;
  26585. }
  26586. static void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  26587. {
  26588. if (increment < 0)
  26589. {
  26590. ev.xbutton.button = Button5;
  26591. ev.xbutton.state |= Button5Mask;
  26592. }
  26593. else if (increment > 0)
  26594. {
  26595. ev.xbutton.button = Button4;
  26596. ev.xbutton.state |= Button4Mask;
  26597. }
  26598. }
  26599. #endif
  26600. class ModuleHandle : public ReferenceCountedObject
  26601. {
  26602. public:
  26603. File file;
  26604. MainCall moduleMain;
  26605. String pluginName;
  26606. static Array <ModuleHandle*>& getActiveModules()
  26607. {
  26608. static Array <ModuleHandle*> activeModules;
  26609. return activeModules;
  26610. }
  26611. static ModuleHandle* findOrCreateModule (const File& file)
  26612. {
  26613. for (int i = getActiveModules().size(); --i >= 0;)
  26614. {
  26615. ModuleHandle* const module = getActiveModules().getUnchecked(i);
  26616. if (module->file == file)
  26617. return module;
  26618. }
  26619. _fpreset(); // (doesn't do any harm)
  26620. ++insideVSTCallback;
  26621. shellUIDToCreate = 0;
  26622. log ("Attempting to load VST: " + file.getFullPathName());
  26623. ScopedPointer <ModuleHandle> m (new ModuleHandle (file));
  26624. if (! m->open())
  26625. m = 0;
  26626. --insideVSTCallback;
  26627. _fpreset(); // (doesn't do any harm)
  26628. return m.release();
  26629. }
  26630. ModuleHandle (const File& file_)
  26631. : file (file_),
  26632. moduleMain (0),
  26633. #if JUCE_WINDOWS || JUCE_LINUX
  26634. hModule (0)
  26635. #elif JUCE_MAC
  26636. fragId (0),
  26637. resHandle (0),
  26638. bundleRef (0),
  26639. resFileId (0)
  26640. #endif
  26641. {
  26642. getActiveModules().add (this);
  26643. #if JUCE_WINDOWS || JUCE_LINUX
  26644. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  26645. #elif JUCE_MAC
  26646. FSRef ref;
  26647. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  26648. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  26649. #endif
  26650. }
  26651. ~ModuleHandle()
  26652. {
  26653. getActiveModules().removeValue (this);
  26654. close();
  26655. }
  26656. juce_UseDebuggingNewOperator
  26657. #if JUCE_WINDOWS || JUCE_LINUX
  26658. void* hModule;
  26659. String fullParentDirectoryPathName;
  26660. bool open()
  26661. {
  26662. #if JUCE_WINDOWS
  26663. static bool timePeriodSet = false;
  26664. if (! timePeriodSet)
  26665. {
  26666. timePeriodSet = true;
  26667. timeBeginPeriod (2);
  26668. }
  26669. #endif
  26670. pluginName = file.getFileNameWithoutExtension();
  26671. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  26672. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  26673. if (moduleMain == 0)
  26674. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  26675. return moduleMain != 0;
  26676. }
  26677. void close()
  26678. {
  26679. _fpreset(); // (doesn't do any harm)
  26680. PlatformUtilities::freeDynamicLibrary (hModule);
  26681. }
  26682. void closeEffect (AEffect* eff)
  26683. {
  26684. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26685. }
  26686. #else
  26687. CFragConnectionID fragId;
  26688. Handle resHandle;
  26689. CFBundleRef bundleRef;
  26690. FSSpec parentDirFSSpec;
  26691. short resFileId;
  26692. bool open()
  26693. {
  26694. bool ok = false;
  26695. const String filename (file.getFullPathName());
  26696. if (file.hasFileExtension (".vst"))
  26697. {
  26698. const char* const utf8 = filename.toUTF8();
  26699. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  26700. strlen (utf8), file.isDirectory());
  26701. if (url != 0)
  26702. {
  26703. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  26704. CFRelease (url);
  26705. if (bundleRef != 0)
  26706. {
  26707. if (CFBundleLoadExecutable (bundleRef))
  26708. {
  26709. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  26710. if (moduleMain == 0)
  26711. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  26712. if (moduleMain != 0)
  26713. {
  26714. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  26715. if (name != 0)
  26716. {
  26717. if (CFGetTypeID (name) == CFStringGetTypeID())
  26718. {
  26719. char buffer[1024];
  26720. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  26721. pluginName = buffer;
  26722. }
  26723. }
  26724. if (pluginName.isEmpty())
  26725. pluginName = file.getFileNameWithoutExtension();
  26726. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  26727. ok = true;
  26728. }
  26729. }
  26730. if (! ok)
  26731. {
  26732. CFBundleUnloadExecutable (bundleRef);
  26733. CFRelease (bundleRef);
  26734. bundleRef = 0;
  26735. }
  26736. }
  26737. }
  26738. }
  26739. #if JUCE_PPC
  26740. else
  26741. {
  26742. FSRef fn;
  26743. if (FSPathMakeRef ((UInt8*) filename.toUTF8(), &fn, 0) == noErr)
  26744. {
  26745. resFileId = FSOpenResFile (&fn, fsRdPerm);
  26746. if (resFileId != -1)
  26747. {
  26748. const int numEffs = Count1Resources ('aEff');
  26749. for (int i = 0; i < numEffs; ++i)
  26750. {
  26751. resHandle = Get1IndResource ('aEff', i + 1);
  26752. if (resHandle != 0)
  26753. {
  26754. OSType type;
  26755. Str255 name;
  26756. SInt16 id;
  26757. GetResInfo (resHandle, &id, &type, name);
  26758. pluginName = String ((const char*) name + 1, name[0]);
  26759. DetachResource (resHandle);
  26760. HLock (resHandle);
  26761. Ptr ptr;
  26762. Str255 errorText;
  26763. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  26764. name, kPrivateCFragCopy,
  26765. &fragId, &ptr, errorText);
  26766. if (err == noErr)
  26767. {
  26768. moduleMain = (MainCall) newMachOFromCFM (ptr);
  26769. ok = true;
  26770. }
  26771. else
  26772. {
  26773. HUnlock (resHandle);
  26774. }
  26775. break;
  26776. }
  26777. }
  26778. if (! ok)
  26779. CloseResFile (resFileId);
  26780. }
  26781. }
  26782. }
  26783. #endif
  26784. return ok;
  26785. }
  26786. void close()
  26787. {
  26788. #if JUCE_PPC
  26789. if (fragId != 0)
  26790. {
  26791. if (moduleMain != 0)
  26792. disposeMachOFromCFM ((void*) moduleMain);
  26793. CloseConnection (&fragId);
  26794. HUnlock (resHandle);
  26795. if (resFileId != 0)
  26796. CloseResFile (resFileId);
  26797. }
  26798. else
  26799. #endif
  26800. if (bundleRef != 0)
  26801. {
  26802. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  26803. if (CFGetRetainCount (bundleRef) == 1)
  26804. CFBundleUnloadExecutable (bundleRef);
  26805. if (CFGetRetainCount (bundleRef) > 0)
  26806. CFRelease (bundleRef);
  26807. }
  26808. }
  26809. void closeEffect (AEffect* eff)
  26810. {
  26811. #if JUCE_PPC
  26812. if (fragId != 0)
  26813. {
  26814. Array<void*> thingsToDelete;
  26815. thingsToDelete.add ((void*) eff->dispatcher);
  26816. thingsToDelete.add ((void*) eff->process);
  26817. thingsToDelete.add ((void*) eff->setParameter);
  26818. thingsToDelete.add ((void*) eff->getParameter);
  26819. thingsToDelete.add ((void*) eff->processReplacing);
  26820. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26821. for (int i = thingsToDelete.size(); --i >= 0;)
  26822. disposeMachOFromCFM (thingsToDelete[i]);
  26823. }
  26824. else
  26825. #endif
  26826. {
  26827. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26828. }
  26829. }
  26830. #if JUCE_PPC
  26831. static void* newMachOFromCFM (void* cfmfp)
  26832. {
  26833. if (cfmfp == 0)
  26834. return 0;
  26835. UInt32* const mfp = new UInt32[6];
  26836. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  26837. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  26838. mfp[2] = 0x800c0000;
  26839. mfp[3] = 0x804c0004;
  26840. mfp[4] = 0x7c0903a6;
  26841. mfp[5] = 0x4e800420;
  26842. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  26843. return mfp;
  26844. }
  26845. static void disposeMachOFromCFM (void* ptr)
  26846. {
  26847. delete[] static_cast <UInt32*> (ptr);
  26848. }
  26849. void coerceAEffectFunctionCalls (AEffect* eff)
  26850. {
  26851. if (fragId != 0)
  26852. {
  26853. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  26854. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  26855. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  26856. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  26857. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  26858. }
  26859. }
  26860. #endif
  26861. #endif
  26862. };
  26863. /**
  26864. An instance of a plugin, created by a VSTPluginFormat.
  26865. */
  26866. class VSTPluginInstance : public AudioPluginInstance,
  26867. private Timer,
  26868. private AsyncUpdater
  26869. {
  26870. public:
  26871. ~VSTPluginInstance();
  26872. // AudioPluginInstance methods:
  26873. void fillInPluginDescription (PluginDescription& desc) const
  26874. {
  26875. desc.name = name;
  26876. desc.fileOrIdentifier = module->file.getFullPathName();
  26877. desc.uid = getUID();
  26878. desc.lastFileModTime = module->file.getLastModificationTime();
  26879. desc.pluginFormatName = "VST";
  26880. desc.category = getCategory();
  26881. {
  26882. char buffer [kVstMaxVendorStrLen + 8];
  26883. zerostruct (buffer);
  26884. dispatch (effGetVendorString, 0, 0, buffer, 0);
  26885. desc.manufacturerName = buffer;
  26886. }
  26887. desc.version = getVersion();
  26888. desc.numInputChannels = getNumInputChannels();
  26889. desc.numOutputChannels = getNumOutputChannels();
  26890. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  26891. }
  26892. const String getName() const { return name; }
  26893. int getUID() const;
  26894. bool acceptsMidi() const { return wantsMidiMessages; }
  26895. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  26896. // AudioProcessor methods:
  26897. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  26898. void releaseResources();
  26899. void processBlock (AudioSampleBuffer& buffer,
  26900. MidiBuffer& midiMessages);
  26901. bool hasEditor() const { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  26902. AudioProcessorEditor* createEditor();
  26903. const String getInputChannelName (int index) const;
  26904. bool isInputChannelStereoPair (int index) const;
  26905. const String getOutputChannelName (int index) const;
  26906. bool isOutputChannelStereoPair (int index) const;
  26907. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  26908. float getParameter (int index);
  26909. void setParameter (int index, float newValue);
  26910. const String getParameterName (int index);
  26911. const String getParameterText (int index);
  26912. bool isParameterAutomatable (int index) const;
  26913. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  26914. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  26915. void setCurrentProgram (int index);
  26916. const String getProgramName (int index);
  26917. void changeProgramName (int index, const String& newName);
  26918. void getStateInformation (MemoryBlock& destData);
  26919. void getCurrentProgramStateInformation (MemoryBlock& destData);
  26920. void setStateInformation (const void* data, int sizeInBytes);
  26921. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  26922. void timerCallback();
  26923. void handleAsyncUpdate();
  26924. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  26925. juce_UseDebuggingNewOperator
  26926. private:
  26927. friend class VSTPluginWindow;
  26928. friend class VSTPluginFormat;
  26929. AEffect* effect;
  26930. String name;
  26931. CriticalSection lock;
  26932. bool wantsMidiMessages, initialised, isPowerOn;
  26933. mutable StringArray programNames;
  26934. AudioSampleBuffer tempBuffer;
  26935. CriticalSection midiInLock;
  26936. MidiBuffer incomingMidi;
  26937. VSTMidiEventList midiEventsToSend;
  26938. VstTimeInfo vstHostTime;
  26939. ReferenceCountedObjectPtr <ModuleHandle> module;
  26940. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  26941. bool restoreProgramSettings (const fxProgram* const prog);
  26942. const String getCurrentProgramName();
  26943. void setParamsInProgramBlock (fxProgram* const prog);
  26944. void updateStoredProgramNames();
  26945. void initialise();
  26946. void handleMidiFromPlugin (const VstEvents* const events);
  26947. void createTempParameterStore (MemoryBlock& dest);
  26948. void restoreFromTempParameterStore (const MemoryBlock& mb);
  26949. const String getParameterLabel (int index) const;
  26950. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  26951. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  26952. void setChunkData (const char* data, int size, bool isPreset);
  26953. bool loadFromFXBFile (const void* data, int numBytes);
  26954. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  26955. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  26956. const String getVersion() const;
  26957. const String getCategory() const;
  26958. void setPower (const bool on);
  26959. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  26960. };
  26961. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  26962. : effect (0),
  26963. wantsMidiMessages (false),
  26964. initialised (false),
  26965. isPowerOn (false),
  26966. tempBuffer (1, 1),
  26967. module (module_)
  26968. {
  26969. try
  26970. {
  26971. _fpreset();
  26972. ++insideVSTCallback;
  26973. name = module->pluginName;
  26974. log ("Creating VST instance: " + name);
  26975. #if JUCE_MAC
  26976. if (module->resFileId != 0)
  26977. UseResFile (module->resFileId);
  26978. #if JUCE_PPC
  26979. if (module->fragId != 0)
  26980. {
  26981. static void* audioMasterCoerced = 0;
  26982. if (audioMasterCoerced == 0)
  26983. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  26984. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  26985. }
  26986. else
  26987. #endif
  26988. #endif
  26989. {
  26990. effect = module->moduleMain (&audioMaster);
  26991. }
  26992. --insideVSTCallback;
  26993. if (effect != 0 && effect->magic == kEffectMagic)
  26994. {
  26995. #if JUCE_PPC
  26996. module->coerceAEffectFunctionCalls (effect);
  26997. #endif
  26998. jassert (effect->resvd2 == 0);
  26999. jassert (effect->object != 0);
  27000. _fpreset(); // some dodgy plugs fuck around with this
  27001. }
  27002. else
  27003. {
  27004. effect = 0;
  27005. }
  27006. }
  27007. catch (...)
  27008. {
  27009. --insideVSTCallback;
  27010. }
  27011. }
  27012. VSTPluginInstance::~VSTPluginInstance()
  27013. {
  27014. const ScopedLock sl (lock);
  27015. jassert (insideVSTCallback == 0);
  27016. if (effect != 0 && effect->magic == kEffectMagic)
  27017. {
  27018. try
  27019. {
  27020. #if JUCE_MAC
  27021. if (module->resFileId != 0)
  27022. UseResFile (module->resFileId);
  27023. #endif
  27024. // Must delete any editors before deleting the plugin instance!
  27025. jassert (getActiveEditor() == 0);
  27026. _fpreset(); // some dodgy plugs fuck around with this
  27027. module->closeEffect (effect);
  27028. }
  27029. catch (...)
  27030. {}
  27031. }
  27032. module = 0;
  27033. effect = 0;
  27034. }
  27035. void VSTPluginInstance::initialise()
  27036. {
  27037. if (initialised || effect == 0)
  27038. return;
  27039. log ("Initialising VST: " + module->pluginName);
  27040. initialised = true;
  27041. dispatch (effIdentify, 0, 0, 0, 0);
  27042. // this code would ask the plugin for its name, but so few plugins
  27043. // actually bother implementing this correctly, that it's better to
  27044. // just ignore it and use the file name instead.
  27045. /* {
  27046. char buffer [256];
  27047. zerostruct (buffer);
  27048. dispatch (effGetEffectName, 0, 0, buffer, 0);
  27049. name = String (buffer).trim();
  27050. if (name.isEmpty())
  27051. name = module->pluginName;
  27052. }
  27053. */
  27054. if (getSampleRate() > 0)
  27055. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  27056. if (getBlockSize() > 0)
  27057. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  27058. dispatch (effOpen, 0, 0, 0, 0);
  27059. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  27060. getSampleRate(), getBlockSize());
  27061. if (getNumPrograms() > 1)
  27062. setCurrentProgram (0);
  27063. else
  27064. dispatch (effSetProgram, 0, 0, 0, 0);
  27065. int i;
  27066. for (i = effect->numInputs; --i >= 0;)
  27067. dispatch (effConnectInput, i, 1, 0, 0);
  27068. for (i = effect->numOutputs; --i >= 0;)
  27069. dispatch (effConnectOutput, i, 1, 0, 0);
  27070. updateStoredProgramNames();
  27071. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  27072. setLatencySamples (effect->initialDelay);
  27073. }
  27074. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  27075. int samplesPerBlockExpected)
  27076. {
  27077. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  27078. sampleRate_, samplesPerBlockExpected);
  27079. setLatencySamples (effect->initialDelay);
  27080. vstHostTime.tempo = 120.0;
  27081. vstHostTime.timeSigNumerator = 4;
  27082. vstHostTime.timeSigDenominator = 4;
  27083. vstHostTime.sampleRate = sampleRate_;
  27084. vstHostTime.samplePos = 0;
  27085. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  27086. initialise();
  27087. if (initialised)
  27088. {
  27089. wantsMidiMessages = wantsMidiMessages
  27090. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  27091. if (wantsMidiMessages)
  27092. midiEventsToSend.ensureSize (256);
  27093. else
  27094. midiEventsToSend.freeEvents();
  27095. incomingMidi.clear();
  27096. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  27097. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  27098. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  27099. if (! isPowerOn)
  27100. setPower (true);
  27101. // dodgy hack to force some plugins to initialise the sample rate..
  27102. if ((! hasEditor()) && getNumParameters() > 0)
  27103. {
  27104. const float old = getParameter (0);
  27105. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  27106. setParameter (0, old);
  27107. }
  27108. dispatch (effStartProcess, 0, 0, 0, 0);
  27109. }
  27110. }
  27111. void VSTPluginInstance::releaseResources()
  27112. {
  27113. if (initialised)
  27114. {
  27115. dispatch (effStopProcess, 0, 0, 0, 0);
  27116. setPower (false);
  27117. }
  27118. tempBuffer.setSize (1, 1);
  27119. incomingMidi.clear();
  27120. midiEventsToSend.freeEvents();
  27121. }
  27122. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  27123. MidiBuffer& midiMessages)
  27124. {
  27125. const int numSamples = buffer.getNumSamples();
  27126. if (initialised)
  27127. {
  27128. AudioPlayHead* playHead = getPlayHead();
  27129. if (playHead != 0)
  27130. {
  27131. AudioPlayHead::CurrentPositionInfo position;
  27132. playHead->getCurrentPosition (position);
  27133. vstHostTime.tempo = position.bpm;
  27134. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  27135. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  27136. vstHostTime.ppqPos = position.ppqPosition;
  27137. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  27138. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  27139. if (position.isPlaying)
  27140. vstHostTime.flags |= kVstTransportPlaying;
  27141. else
  27142. vstHostTime.flags &= ~kVstTransportPlaying;
  27143. }
  27144. vstHostTime.nanoSeconds = getVSTHostTimeNanoseconds();
  27145. if (wantsMidiMessages)
  27146. {
  27147. midiEventsToSend.clear();
  27148. midiEventsToSend.ensureSize (1);
  27149. MidiBuffer::Iterator iter (midiMessages);
  27150. const uint8* midiData;
  27151. int numBytesOfMidiData, samplePosition;
  27152. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  27153. {
  27154. midiEventsToSend.addEvent (midiData, numBytesOfMidiData,
  27155. jlimit (0, numSamples - 1, samplePosition));
  27156. }
  27157. try
  27158. {
  27159. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend.events, 0);
  27160. }
  27161. catch (...)
  27162. {}
  27163. }
  27164. _clearfp();
  27165. if ((effect->flags & effFlagsCanReplacing) != 0)
  27166. {
  27167. try
  27168. {
  27169. effect->processReplacing (effect, buffer.getArrayOfChannels(), buffer.getArrayOfChannels(), numSamples);
  27170. }
  27171. catch (...)
  27172. {}
  27173. }
  27174. else
  27175. {
  27176. tempBuffer.setSize (effect->numOutputs, numSamples);
  27177. tempBuffer.clear();
  27178. try
  27179. {
  27180. effect->process (effect, buffer.getArrayOfChannels(), tempBuffer.getArrayOfChannels(), numSamples);
  27181. }
  27182. catch (...)
  27183. {}
  27184. for (int i = effect->numOutputs; --i >= 0;)
  27185. buffer.copyFrom (i, 0, tempBuffer.getSampleData (i), numSamples);
  27186. }
  27187. }
  27188. else
  27189. {
  27190. // Not initialised, so just bypass..
  27191. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  27192. buffer.clear (i, 0, buffer.getNumSamples());
  27193. }
  27194. {
  27195. // copy any incoming midi..
  27196. const ScopedLock sl (midiInLock);
  27197. midiMessages.swapWith (incomingMidi);
  27198. incomingMidi.clear();
  27199. }
  27200. }
  27201. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  27202. {
  27203. if (events != 0)
  27204. {
  27205. const ScopedLock sl (midiInLock);
  27206. VSTMidiEventList::addEventsToMidiBuffer (events, incomingMidi);
  27207. }
  27208. }
  27209. static Array <VSTPluginWindow*> activeVSTWindows;
  27210. class VSTPluginWindow : public AudioProcessorEditor,
  27211. #if ! JUCE_MAC
  27212. public ComponentMovementWatcher,
  27213. #endif
  27214. public Timer
  27215. {
  27216. public:
  27217. VSTPluginWindow (VSTPluginInstance& plugin_)
  27218. : AudioProcessorEditor (&plugin_),
  27219. #if ! JUCE_MAC
  27220. ComponentMovementWatcher (this),
  27221. #endif
  27222. plugin (plugin_),
  27223. isOpen (false),
  27224. wasShowing (false),
  27225. pluginRefusesToResize (false),
  27226. pluginWantsKeys (false),
  27227. alreadyInside (false),
  27228. recursiveResize (false)
  27229. {
  27230. #if JUCE_WINDOWS
  27231. sizeCheckCount = 0;
  27232. pluginHWND = 0;
  27233. #elif JUCE_LINUX
  27234. pluginWindow = None;
  27235. pluginProc = None;
  27236. #else
  27237. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  27238. #endif
  27239. activeVSTWindows.add (this);
  27240. setSize (1, 1);
  27241. setOpaque (true);
  27242. setVisible (true);
  27243. }
  27244. ~VSTPluginWindow()
  27245. {
  27246. #if JUCE_MAC
  27247. innerWrapper = 0;
  27248. #else
  27249. closePluginWindow();
  27250. #endif
  27251. activeVSTWindows.removeValue (this);
  27252. plugin.editorBeingDeleted (this);
  27253. }
  27254. #if ! JUCE_MAC
  27255. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  27256. {
  27257. if (recursiveResize)
  27258. return;
  27259. Component* const topComp = getTopLevelComponent();
  27260. if (topComp->getPeer() != 0)
  27261. {
  27262. const Point<int> pos (relativePositionToOtherComponent (topComp, Point<int>()));
  27263. recursiveResize = true;
  27264. #if JUCE_WINDOWS
  27265. if (pluginHWND != 0)
  27266. MoveWindow (pluginHWND, pos.getX(), pos.getY(), getWidth(), getHeight(), TRUE);
  27267. #elif JUCE_LINUX
  27268. if (pluginWindow != 0)
  27269. {
  27270. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  27271. XMoveWindow (display, pluginWindow, pos.getX(), pos.getY());
  27272. XMapRaised (display, pluginWindow);
  27273. }
  27274. #endif
  27275. recursiveResize = false;
  27276. }
  27277. }
  27278. void componentVisibilityChanged (Component&)
  27279. {
  27280. const bool isShowingNow = isShowing();
  27281. if (wasShowing != isShowingNow)
  27282. {
  27283. wasShowing = isShowingNow;
  27284. if (isShowingNow)
  27285. openPluginWindow();
  27286. else
  27287. closePluginWindow();
  27288. }
  27289. componentMovedOrResized (true, true);
  27290. }
  27291. void componentPeerChanged()
  27292. {
  27293. closePluginWindow();
  27294. openPluginWindow();
  27295. }
  27296. #endif
  27297. bool keyStateChanged (bool)
  27298. {
  27299. return pluginWantsKeys;
  27300. }
  27301. bool keyPressed (const KeyPress&)
  27302. {
  27303. return pluginWantsKeys;
  27304. }
  27305. #if JUCE_MAC
  27306. void paint (Graphics& g)
  27307. {
  27308. g.fillAll (Colours::black);
  27309. }
  27310. #else
  27311. void paint (Graphics& g)
  27312. {
  27313. if (isOpen)
  27314. {
  27315. ComponentPeer* const peer = getPeer();
  27316. if (peer != 0)
  27317. {
  27318. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27319. peer->addMaskedRegion (pos.getX(), pos.getY(), getWidth(), getHeight());
  27320. #if JUCE_LINUX
  27321. if (pluginWindow != 0)
  27322. {
  27323. const Rectangle<int> clip (g.getClipBounds());
  27324. XEvent ev;
  27325. zerostruct (ev);
  27326. ev.xexpose.type = Expose;
  27327. ev.xexpose.display = display;
  27328. ev.xexpose.window = pluginWindow;
  27329. ev.xexpose.x = clip.getX();
  27330. ev.xexpose.y = clip.getY();
  27331. ev.xexpose.width = clip.getWidth();
  27332. ev.xexpose.height = clip.getHeight();
  27333. sendEventToChild (&ev);
  27334. }
  27335. #endif
  27336. }
  27337. }
  27338. else
  27339. {
  27340. g.fillAll (Colours::black);
  27341. }
  27342. }
  27343. #endif
  27344. void timerCallback()
  27345. {
  27346. #if JUCE_WINDOWS
  27347. if (--sizeCheckCount <= 0)
  27348. {
  27349. sizeCheckCount = 10;
  27350. checkPluginWindowSize();
  27351. }
  27352. #endif
  27353. try
  27354. {
  27355. static bool reentrant = false;
  27356. if (! reentrant)
  27357. {
  27358. reentrant = true;
  27359. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  27360. reentrant = false;
  27361. }
  27362. }
  27363. catch (...)
  27364. {}
  27365. }
  27366. void mouseDown (const MouseEvent& e)
  27367. {
  27368. #if JUCE_LINUX
  27369. if (pluginWindow == 0)
  27370. return;
  27371. toFront (true);
  27372. XEvent ev;
  27373. zerostruct (ev);
  27374. ev.xbutton.display = display;
  27375. ev.xbutton.type = ButtonPress;
  27376. ev.xbutton.window = pluginWindow;
  27377. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27378. ev.xbutton.time = CurrentTime;
  27379. ev.xbutton.x = e.x;
  27380. ev.xbutton.y = e.y;
  27381. ev.xbutton.x_root = e.getScreenX();
  27382. ev.xbutton.y_root = e.getScreenY();
  27383. translateJuceToXButtonModifiers (e, ev);
  27384. sendEventToChild (&ev);
  27385. #elif JUCE_WINDOWS
  27386. (void) e;
  27387. toFront (true);
  27388. #endif
  27389. }
  27390. void broughtToFront()
  27391. {
  27392. activeVSTWindows.removeValue (this);
  27393. activeVSTWindows.add (this);
  27394. #if JUCE_MAC
  27395. dispatch (effEditTop, 0, 0, 0, 0);
  27396. #endif
  27397. }
  27398. juce_UseDebuggingNewOperator
  27399. private:
  27400. VSTPluginInstance& plugin;
  27401. bool isOpen, wasShowing, recursiveResize;
  27402. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  27403. #if JUCE_WINDOWS
  27404. HWND pluginHWND;
  27405. void* originalWndProc;
  27406. int sizeCheckCount;
  27407. #elif JUCE_LINUX
  27408. Window pluginWindow;
  27409. EventProcPtr pluginProc;
  27410. #endif
  27411. #if JUCE_MAC
  27412. void openPluginWindow (WindowRef parentWindow)
  27413. {
  27414. if (isOpen || parentWindow == 0)
  27415. return;
  27416. isOpen = true;
  27417. ERect* rect = 0;
  27418. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27419. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  27420. // do this before and after like in the steinberg example
  27421. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27422. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27423. // Install keyboard hooks
  27424. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27425. // double-check it's not too tiny
  27426. int w = 250, h = 150;
  27427. if (rect != 0)
  27428. {
  27429. w = rect->right - rect->left;
  27430. h = rect->bottom - rect->top;
  27431. if (w == 0 || h == 0)
  27432. {
  27433. w = 250;
  27434. h = 150;
  27435. }
  27436. }
  27437. w = jmax (w, 32);
  27438. h = jmax (h, 32);
  27439. setSize (w, h);
  27440. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27441. repaint();
  27442. }
  27443. #else
  27444. void openPluginWindow()
  27445. {
  27446. if (isOpen || getWindowHandle() == 0)
  27447. return;
  27448. log ("Opening VST UI: " + plugin.name);
  27449. isOpen = true;
  27450. ERect* rect = 0;
  27451. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27452. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  27453. // do this before and after like in the steinberg example
  27454. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27455. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27456. // Install keyboard hooks
  27457. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27458. #if JUCE_WINDOWS
  27459. originalWndProc = 0;
  27460. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  27461. if (pluginHWND == 0)
  27462. {
  27463. isOpen = false;
  27464. setSize (300, 150);
  27465. return;
  27466. }
  27467. #pragma warning (push)
  27468. #pragma warning (disable: 4244)
  27469. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWLP_WNDPROC);
  27470. if (! pluginWantsKeys)
  27471. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) vstHookWndProc);
  27472. #pragma warning (pop)
  27473. int w, h;
  27474. RECT r;
  27475. GetWindowRect (pluginHWND, &r);
  27476. w = r.right - r.left;
  27477. h = r.bottom - r.top;
  27478. if (rect != 0)
  27479. {
  27480. const int rw = rect->right - rect->left;
  27481. const int rh = rect->bottom - rect->top;
  27482. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  27483. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  27484. {
  27485. // very dodgy logic to decide which size is right.
  27486. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  27487. {
  27488. SetWindowPos (pluginHWND, 0,
  27489. 0, 0, rw, rh,
  27490. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  27491. GetWindowRect (pluginHWND, &r);
  27492. w = r.right - r.left;
  27493. h = r.bottom - r.top;
  27494. pluginRefusesToResize = (w != rw) || (h != rh);
  27495. w = rw;
  27496. h = rh;
  27497. }
  27498. }
  27499. }
  27500. #elif JUCE_LINUX
  27501. pluginWindow = getChildWindow ((Window) getWindowHandle());
  27502. if (pluginWindow != 0)
  27503. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  27504. XInternAtom (display, "_XEventProc", False));
  27505. int w = 250, h = 150;
  27506. if (rect != 0)
  27507. {
  27508. w = rect->right - rect->left;
  27509. h = rect->bottom - rect->top;
  27510. if (w == 0 || h == 0)
  27511. {
  27512. w = 250;
  27513. h = 150;
  27514. }
  27515. }
  27516. if (pluginWindow != 0)
  27517. XMapRaised (display, pluginWindow);
  27518. #endif
  27519. // double-check it's not too tiny
  27520. w = jmax (w, 32);
  27521. h = jmax (h, 32);
  27522. setSize (w, h);
  27523. #if JUCE_WINDOWS
  27524. checkPluginWindowSize();
  27525. #endif
  27526. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27527. repaint();
  27528. }
  27529. #endif
  27530. #if ! JUCE_MAC
  27531. void closePluginWindow()
  27532. {
  27533. if (isOpen)
  27534. {
  27535. log ("Closing VST UI: " + plugin.getName());
  27536. isOpen = false;
  27537. dispatch (effEditClose, 0, 0, 0, 0);
  27538. #if JUCE_WINDOWS
  27539. #pragma warning (push)
  27540. #pragma warning (disable: 4244)
  27541. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27542. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) originalWndProc);
  27543. #pragma warning (pop)
  27544. stopTimer();
  27545. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27546. DestroyWindow (pluginHWND);
  27547. pluginHWND = 0;
  27548. #elif JUCE_LINUX
  27549. stopTimer();
  27550. pluginWindow = 0;
  27551. pluginProc = 0;
  27552. #endif
  27553. }
  27554. }
  27555. #endif
  27556. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  27557. {
  27558. return plugin.dispatch (opcode, index, value, ptr, opt);
  27559. }
  27560. #if JUCE_WINDOWS
  27561. void checkPluginWindowSize()
  27562. {
  27563. RECT r;
  27564. GetWindowRect (pluginHWND, &r);
  27565. const int w = r.right - r.left;
  27566. const int h = r.bottom - r.top;
  27567. if (isShowing() && w > 0 && h > 0
  27568. && (w != getWidth() || h != getHeight())
  27569. && ! pluginRefusesToResize)
  27570. {
  27571. setSize (w, h);
  27572. sizeCheckCount = 0;
  27573. }
  27574. }
  27575. // hooks to get keyboard events from VST windows..
  27576. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  27577. {
  27578. for (int i = activeVSTWindows.size(); --i >= 0;)
  27579. {
  27580. const VSTPluginWindow* const w = activeVSTWindows.getUnchecked (i);
  27581. if (w->pluginHWND == hW)
  27582. {
  27583. if (message == WM_CHAR
  27584. || message == WM_KEYDOWN
  27585. || message == WM_SYSKEYDOWN
  27586. || message == WM_KEYUP
  27587. || message == WM_SYSKEYUP
  27588. || message == WM_APPCOMMAND)
  27589. {
  27590. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  27591. message, wParam, lParam);
  27592. }
  27593. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  27594. (HWND) w->pluginHWND,
  27595. message,
  27596. wParam,
  27597. lParam);
  27598. }
  27599. }
  27600. return DefWindowProc (hW, message, wParam, lParam);
  27601. }
  27602. #endif
  27603. #if JUCE_LINUX
  27604. // overload mouse/keyboard events to forward them to the plugin's inner window..
  27605. void sendEventToChild (XEvent* event)
  27606. {
  27607. if (pluginProc != 0)
  27608. {
  27609. // if the plugin publishes an event procedure, pass the event directly..
  27610. pluginProc (event);
  27611. }
  27612. else if (pluginWindow != 0)
  27613. {
  27614. // if the plugin has a window, then send the event to the window so that
  27615. // its message thread will pick it up..
  27616. XSendEvent (display, pluginWindow, False, 0L, event);
  27617. XFlush (display);
  27618. }
  27619. }
  27620. void mouseEnter (const MouseEvent& e)
  27621. {
  27622. if (pluginWindow != 0)
  27623. {
  27624. XEvent ev;
  27625. zerostruct (ev);
  27626. ev.xcrossing.display = display;
  27627. ev.xcrossing.type = EnterNotify;
  27628. ev.xcrossing.window = pluginWindow;
  27629. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27630. ev.xcrossing.time = CurrentTime;
  27631. ev.xcrossing.x = e.x;
  27632. ev.xcrossing.y = e.y;
  27633. ev.xcrossing.x_root = e.getScreenX();
  27634. ev.xcrossing.y_root = e.getScreenY();
  27635. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27636. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27637. translateJuceToXCrossingModifiers (e, ev);
  27638. sendEventToChild (&ev);
  27639. }
  27640. }
  27641. void mouseExit (const MouseEvent& e)
  27642. {
  27643. if (pluginWindow != 0)
  27644. {
  27645. XEvent ev;
  27646. zerostruct (ev);
  27647. ev.xcrossing.display = display;
  27648. ev.xcrossing.type = LeaveNotify;
  27649. ev.xcrossing.window = pluginWindow;
  27650. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27651. ev.xcrossing.time = CurrentTime;
  27652. ev.xcrossing.x = e.x;
  27653. ev.xcrossing.y = e.y;
  27654. ev.xcrossing.x_root = e.getScreenX();
  27655. ev.xcrossing.y_root = e.getScreenY();
  27656. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27657. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27658. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  27659. translateJuceToXCrossingModifiers (e, ev);
  27660. sendEventToChild (&ev);
  27661. }
  27662. }
  27663. void mouseMove (const MouseEvent& e)
  27664. {
  27665. if (pluginWindow != 0)
  27666. {
  27667. XEvent ev;
  27668. zerostruct (ev);
  27669. ev.xmotion.display = display;
  27670. ev.xmotion.type = MotionNotify;
  27671. ev.xmotion.window = pluginWindow;
  27672. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27673. ev.xmotion.time = CurrentTime;
  27674. ev.xmotion.is_hint = NotifyNormal;
  27675. ev.xmotion.x = e.x;
  27676. ev.xmotion.y = e.y;
  27677. ev.xmotion.x_root = e.getScreenX();
  27678. ev.xmotion.y_root = e.getScreenY();
  27679. sendEventToChild (&ev);
  27680. }
  27681. }
  27682. void mouseDrag (const MouseEvent& e)
  27683. {
  27684. if (pluginWindow != 0)
  27685. {
  27686. XEvent ev;
  27687. zerostruct (ev);
  27688. ev.xmotion.display = display;
  27689. ev.xmotion.type = MotionNotify;
  27690. ev.xmotion.window = pluginWindow;
  27691. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27692. ev.xmotion.time = CurrentTime;
  27693. ev.xmotion.x = e.x ;
  27694. ev.xmotion.y = e.y;
  27695. ev.xmotion.x_root = e.getScreenX();
  27696. ev.xmotion.y_root = e.getScreenY();
  27697. ev.xmotion.is_hint = NotifyNormal;
  27698. translateJuceToXMotionModifiers (e, ev);
  27699. sendEventToChild (&ev);
  27700. }
  27701. }
  27702. void mouseUp (const MouseEvent& e)
  27703. {
  27704. if (pluginWindow != 0)
  27705. {
  27706. XEvent ev;
  27707. zerostruct (ev);
  27708. ev.xbutton.display = display;
  27709. ev.xbutton.type = ButtonRelease;
  27710. ev.xbutton.window = pluginWindow;
  27711. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27712. ev.xbutton.time = CurrentTime;
  27713. ev.xbutton.x = e.x;
  27714. ev.xbutton.y = e.y;
  27715. ev.xbutton.x_root = e.getScreenX();
  27716. ev.xbutton.y_root = e.getScreenY();
  27717. translateJuceToXButtonModifiers (e, ev);
  27718. sendEventToChild (&ev);
  27719. }
  27720. }
  27721. void mouseWheelMove (const MouseEvent& e,
  27722. float incrementX,
  27723. float incrementY)
  27724. {
  27725. if (pluginWindow != 0)
  27726. {
  27727. XEvent ev;
  27728. zerostruct (ev);
  27729. ev.xbutton.display = display;
  27730. ev.xbutton.type = ButtonPress;
  27731. ev.xbutton.window = pluginWindow;
  27732. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27733. ev.xbutton.time = CurrentTime;
  27734. ev.xbutton.x = e.x;
  27735. ev.xbutton.y = e.y;
  27736. ev.xbutton.x_root = e.getScreenX();
  27737. ev.xbutton.y_root = e.getScreenY();
  27738. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  27739. sendEventToChild (&ev);
  27740. // TODO - put a usleep here ?
  27741. ev.xbutton.type = ButtonRelease;
  27742. sendEventToChild (&ev);
  27743. }
  27744. }
  27745. #endif
  27746. #if JUCE_MAC
  27747. #if ! JUCE_SUPPORT_CARBON
  27748. #error "To build VSTs, you need to enable the JUCE_SUPPORT_CARBON flag in your config!"
  27749. #endif
  27750. class InnerWrapperComponent : public CarbonViewWrapperComponent
  27751. {
  27752. public:
  27753. InnerWrapperComponent (VSTPluginWindow* const owner_)
  27754. : owner (owner_),
  27755. alreadyInside (false)
  27756. {
  27757. }
  27758. ~InnerWrapperComponent()
  27759. {
  27760. deleteWindow();
  27761. }
  27762. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  27763. {
  27764. owner->openPluginWindow (windowRef);
  27765. return 0;
  27766. }
  27767. void removeView (HIViewRef)
  27768. {
  27769. owner->dispatch (effEditClose, 0, 0, 0, 0);
  27770. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  27771. }
  27772. bool getEmbeddedViewSize (int& w, int& h)
  27773. {
  27774. ERect* rect = 0;
  27775. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  27776. w = rect->right - rect->left;
  27777. h = rect->bottom - rect->top;
  27778. return true;
  27779. }
  27780. void mouseDown (int x, int y)
  27781. {
  27782. if (! alreadyInside)
  27783. {
  27784. alreadyInside = true;
  27785. getTopLevelComponent()->toFront (true);
  27786. owner->dispatch (effEditMouse, x, y, 0, 0);
  27787. alreadyInside = false;
  27788. }
  27789. else
  27790. {
  27791. PostEvent (::mouseDown, 0);
  27792. }
  27793. }
  27794. void paint()
  27795. {
  27796. ComponentPeer* const peer = getPeer();
  27797. if (peer != 0)
  27798. {
  27799. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27800. ERect r;
  27801. r.left = pos.getX();
  27802. r.right = r.left + getWidth();
  27803. r.top = pos.getY();
  27804. r.bottom = r.top + getHeight();
  27805. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  27806. }
  27807. }
  27808. private:
  27809. VSTPluginWindow* const owner;
  27810. bool alreadyInside;
  27811. };
  27812. friend class InnerWrapperComponent;
  27813. ScopedPointer <InnerWrapperComponent> innerWrapper;
  27814. void resized()
  27815. {
  27816. innerWrapper->setSize (getWidth(), getHeight());
  27817. }
  27818. #endif
  27819. };
  27820. AudioProcessorEditor* VSTPluginInstance::createEditor()
  27821. {
  27822. if (hasEditor())
  27823. return new VSTPluginWindow (*this);
  27824. return 0;
  27825. }
  27826. void VSTPluginInstance::handleAsyncUpdate()
  27827. {
  27828. // indicates that something about the plugin has changed..
  27829. updateHostDisplay();
  27830. }
  27831. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  27832. {
  27833. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  27834. {
  27835. changeProgramName (getCurrentProgram(), prog->prgName);
  27836. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  27837. setParameter (i, vst_swapFloat (prog->params[i]));
  27838. return true;
  27839. }
  27840. return false;
  27841. }
  27842. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  27843. const int dataSize)
  27844. {
  27845. if (dataSize < 28)
  27846. return false;
  27847. const fxSet* const set = (const fxSet*) data;
  27848. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  27849. || vst_swap (set->version) > fxbVersionNum)
  27850. return false;
  27851. if (vst_swap (set->fxMagic) == 'FxBk')
  27852. {
  27853. // bank of programs
  27854. if (vst_swap (set->numPrograms) >= 0)
  27855. {
  27856. const int oldProg = getCurrentProgram();
  27857. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  27858. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27859. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  27860. {
  27861. if (i != oldProg)
  27862. {
  27863. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  27864. if (((const char*) prog) - ((const char*) set) >= dataSize)
  27865. return false;
  27866. if (vst_swap (set->numPrograms) > 0)
  27867. setCurrentProgram (i);
  27868. if (! restoreProgramSettings (prog))
  27869. return false;
  27870. }
  27871. }
  27872. if (vst_swap (set->numPrograms) > 0)
  27873. setCurrentProgram (oldProg);
  27874. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  27875. if (((const char*) prog) - ((const char*) set) >= dataSize)
  27876. return false;
  27877. if (! restoreProgramSettings (prog))
  27878. return false;
  27879. }
  27880. }
  27881. else if (vst_swap (set->fxMagic) == 'FxCk')
  27882. {
  27883. // single program
  27884. const fxProgram* const prog = (const fxProgram*) data;
  27885. if (vst_swap (prog->chunkMagic) != 'CcnK')
  27886. return false;
  27887. changeProgramName (getCurrentProgram(), prog->prgName);
  27888. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  27889. setParameter (i, vst_swapFloat (prog->params[i]));
  27890. }
  27891. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  27892. {
  27893. // non-preset chunk
  27894. const fxChunkSet* const cset = (const fxChunkSet*) data;
  27895. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  27896. return false;
  27897. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  27898. }
  27899. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  27900. {
  27901. // preset chunk
  27902. const fxProgramSet* const cset = (const fxProgramSet*) data;
  27903. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  27904. return false;
  27905. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  27906. changeProgramName (getCurrentProgram(), cset->name);
  27907. }
  27908. else
  27909. {
  27910. return false;
  27911. }
  27912. return true;
  27913. }
  27914. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog)
  27915. {
  27916. const int numParams = getNumParameters();
  27917. prog->chunkMagic = vst_swap ('CcnK');
  27918. prog->byteSize = 0;
  27919. prog->fxMagic = vst_swap ('FxCk');
  27920. prog->version = vst_swap (fxbVersionNum);
  27921. prog->fxID = vst_swap (getUID());
  27922. prog->fxVersion = vst_swap (getVersionNumber());
  27923. prog->numParams = vst_swap (numParams);
  27924. getCurrentProgramName().copyToCString (prog->prgName, sizeof (prog->prgName) - 1);
  27925. for (int i = 0; i < numParams; ++i)
  27926. prog->params[i] = vst_swapFloat (getParameter (i));
  27927. }
  27928. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  27929. {
  27930. const int numPrograms = getNumPrograms();
  27931. const int numParams = getNumParameters();
  27932. if (usesChunks())
  27933. {
  27934. if (isFXB)
  27935. {
  27936. MemoryBlock chunk;
  27937. getChunkData (chunk, false, maxSizeMB);
  27938. const size_t totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  27939. dest.setSize (totalLen, true);
  27940. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  27941. set->chunkMagic = vst_swap ('CcnK');
  27942. set->byteSize = 0;
  27943. set->fxMagic = vst_swap ('FBCh');
  27944. set->version = vst_swap (fxbVersionNum);
  27945. set->fxID = vst_swap (getUID());
  27946. set->fxVersion = vst_swap (getVersionNumber());
  27947. set->numPrograms = vst_swap (numPrograms);
  27948. set->chunkSize = vst_swap ((long) chunk.getSize());
  27949. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27950. }
  27951. else
  27952. {
  27953. MemoryBlock chunk;
  27954. getChunkData (chunk, true, maxSizeMB);
  27955. const size_t totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  27956. dest.setSize (totalLen, true);
  27957. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  27958. set->chunkMagic = vst_swap ('CcnK');
  27959. set->byteSize = 0;
  27960. set->fxMagic = vst_swap ('FPCh');
  27961. set->version = vst_swap (fxbVersionNum);
  27962. set->fxID = vst_swap (getUID());
  27963. set->fxVersion = vst_swap (getVersionNumber());
  27964. set->numPrograms = vst_swap (numPrograms);
  27965. set->chunkSize = vst_swap ((long) chunk.getSize());
  27966. getCurrentProgramName().copyToCString (set->name, sizeof (set->name) - 1);
  27967. chunk.copyTo (set->chunk, 0, chunk.getSize());
  27968. }
  27969. }
  27970. else
  27971. {
  27972. if (isFXB)
  27973. {
  27974. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27975. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  27976. dest.setSize (len, true);
  27977. fxSet* const set = (fxSet*) dest.getData();
  27978. set->chunkMagic = vst_swap ('CcnK');
  27979. set->byteSize = 0;
  27980. set->fxMagic = vst_swap ('FxBk');
  27981. set->version = vst_swap (fxbVersionNum);
  27982. set->fxID = vst_swap (getUID());
  27983. set->fxVersion = vst_swap (getVersionNumber());
  27984. set->numPrograms = vst_swap (numPrograms);
  27985. const int oldProgram = getCurrentProgram();
  27986. MemoryBlock oldSettings;
  27987. createTempParameterStore (oldSettings);
  27988. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  27989. for (int i = 0; i < numPrograms; ++i)
  27990. {
  27991. if (i != oldProgram)
  27992. {
  27993. setCurrentProgram (i);
  27994. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  27995. }
  27996. }
  27997. setCurrentProgram (oldProgram);
  27998. restoreFromTempParameterStore (oldSettings);
  27999. }
  28000. else
  28001. {
  28002. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  28003. dest.setSize (totalLen, true);
  28004. setParamsInProgramBlock ((fxProgram*) dest.getData());
  28005. }
  28006. }
  28007. return true;
  28008. }
  28009. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  28010. {
  28011. if (usesChunks())
  28012. {
  28013. void* data = 0;
  28014. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  28015. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  28016. {
  28017. mb.setSize (bytes);
  28018. mb.copyFrom (data, 0, bytes);
  28019. }
  28020. }
  28021. }
  28022. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  28023. {
  28024. if (size > 0 && usesChunks())
  28025. {
  28026. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  28027. if (! isPreset)
  28028. updateStoredProgramNames();
  28029. }
  28030. }
  28031. void VSTPluginInstance::timerCallback()
  28032. {
  28033. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  28034. stopTimer();
  28035. }
  28036. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  28037. {
  28038. const ScopedLock sl (lock);
  28039. ++insideVSTCallback;
  28040. int result = 0;
  28041. try
  28042. {
  28043. if (effect != 0)
  28044. {
  28045. #if JUCE_MAC
  28046. if (module->resFileId != 0)
  28047. UseResFile (module->resFileId);
  28048. #endif
  28049. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  28050. #if JUCE_MAC
  28051. module->resFileId = CurResFile();
  28052. #endif
  28053. --insideVSTCallback;
  28054. return result;
  28055. }
  28056. }
  28057. catch (...)
  28058. {
  28059. }
  28060. --insideVSTCallback;
  28061. return result;
  28062. }
  28063. // handles non plugin-specific callbacks..
  28064. static const int defaultVSTSampleRateValue = 16384;
  28065. static const int defaultVSTBlockSizeValue = 512;
  28066. static VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  28067. {
  28068. (void) index;
  28069. (void) value;
  28070. (void) opt;
  28071. switch (opcode)
  28072. {
  28073. case audioMasterCanDo:
  28074. {
  28075. static const char* canDos[] = { "supplyIdle",
  28076. "sendVstEvents",
  28077. "sendVstMidiEvent",
  28078. "sendVstTimeInfo",
  28079. "receiveVstEvents",
  28080. "receiveVstMidiEvent",
  28081. "supportShell",
  28082. "shellCategory" };
  28083. for (int i = 0; i < numElementsInArray (canDos); ++i)
  28084. if (strcmp (canDos[i], (const char*) ptr) == 0)
  28085. return 1;
  28086. return 0;
  28087. }
  28088. case audioMasterVersion: return 0x2400;
  28089. case audioMasterCurrentId: return shellUIDToCreate;
  28090. case audioMasterGetNumAutomatableParameters: return 0;
  28091. case audioMasterGetAutomationState: return 1;
  28092. case audioMasterGetVendorVersion: return 0x0101;
  28093. case audioMasterGetVendorString:
  28094. case audioMasterGetProductString:
  28095. {
  28096. String hostName ("Juce VST Host");
  28097. if (JUCEApplication::getInstance() != 0)
  28098. hostName = JUCEApplication::getInstance()->getApplicationName();
  28099. hostName.copyToCString ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  28100. break;
  28101. }
  28102. case audioMasterGetSampleRate: return (VstIntPtr) defaultVSTSampleRateValue;
  28103. case audioMasterGetBlockSize: return (VstIntPtr) defaultVSTBlockSizeValue;
  28104. case audioMasterSetOutputSampleRate: return 0;
  28105. default:
  28106. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  28107. break;
  28108. }
  28109. return 0;
  28110. }
  28111. // handles callbacks for a specific plugin
  28112. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  28113. {
  28114. switch (opcode)
  28115. {
  28116. case audioMasterAutomate:
  28117. sendParamChangeMessageToListeners (index, opt);
  28118. break;
  28119. case audioMasterProcessEvents:
  28120. handleMidiFromPlugin ((const VstEvents*) ptr);
  28121. break;
  28122. case audioMasterGetTime:
  28123. #if JUCE_MSVC
  28124. #pragma warning (push)
  28125. #pragma warning (disable: 4311)
  28126. #endif
  28127. return (VstIntPtr) &vstHostTime;
  28128. #if JUCE_MSVC
  28129. #pragma warning (pop)
  28130. #endif
  28131. break;
  28132. case audioMasterIdle:
  28133. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  28134. {
  28135. ++insideVSTCallback;
  28136. #if JUCE_MAC
  28137. if (getActiveEditor() != 0)
  28138. dispatch (effEditIdle, 0, 0, 0, 0);
  28139. #endif
  28140. juce_callAnyTimersSynchronously();
  28141. handleUpdateNowIfNeeded();
  28142. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  28143. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  28144. --insideVSTCallback;
  28145. }
  28146. break;
  28147. case audioMasterUpdateDisplay:
  28148. triggerAsyncUpdate();
  28149. break;
  28150. case audioMasterTempoAt:
  28151. // returns (10000 * bpm)
  28152. break;
  28153. case audioMasterNeedIdle:
  28154. startTimer (50);
  28155. break;
  28156. case audioMasterSizeWindow:
  28157. if (getActiveEditor() != 0)
  28158. getActiveEditor()->setSize (index, value);
  28159. return 1;
  28160. case audioMasterGetSampleRate:
  28161. return (VstIntPtr) (getSampleRate() > 0 ? getSampleRate() : defaultVSTSampleRateValue);
  28162. case audioMasterGetBlockSize:
  28163. return (VstIntPtr) (getBlockSize() > 0 ? getBlockSize() : defaultVSTBlockSizeValue);
  28164. case audioMasterWantMidi:
  28165. wantsMidiMessages = true;
  28166. break;
  28167. case audioMasterGetDirectory:
  28168. #if JUCE_MAC
  28169. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  28170. #else
  28171. return (VstIntPtr) (pointer_sized_uint) module->fullParentDirectoryPathName.toUTF8();
  28172. #endif
  28173. case audioMasterGetAutomationState:
  28174. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  28175. break;
  28176. // none of these are handled (yet)..
  28177. case audioMasterBeginEdit:
  28178. case audioMasterEndEdit:
  28179. case audioMasterSetTime:
  28180. case audioMasterPinConnected:
  28181. case audioMasterGetParameterQuantization:
  28182. case audioMasterIOChanged:
  28183. case audioMasterGetInputLatency:
  28184. case audioMasterGetOutputLatency:
  28185. case audioMasterGetPreviousPlug:
  28186. case audioMasterGetNextPlug:
  28187. case audioMasterWillReplaceOrAccumulate:
  28188. case audioMasterGetCurrentProcessLevel:
  28189. case audioMasterOfflineStart:
  28190. case audioMasterOfflineRead:
  28191. case audioMasterOfflineWrite:
  28192. case audioMasterOfflineGetCurrentPass:
  28193. case audioMasterOfflineGetCurrentMetaPass:
  28194. case audioMasterVendorSpecific:
  28195. case audioMasterSetIcon:
  28196. case audioMasterGetLanguage:
  28197. case audioMasterOpenWindow:
  28198. case audioMasterCloseWindow:
  28199. break;
  28200. default:
  28201. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28202. }
  28203. return 0;
  28204. }
  28205. // entry point for all callbacks from the plugin
  28206. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  28207. {
  28208. try
  28209. {
  28210. if (effect != 0 && effect->resvd2 != 0)
  28211. {
  28212. return ((VSTPluginInstance*)(effect->resvd2))
  28213. ->handleCallback (opcode, index, value, ptr, opt);
  28214. }
  28215. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28216. }
  28217. catch (...)
  28218. {
  28219. return 0;
  28220. }
  28221. }
  28222. const String VSTPluginInstance::getVersion() const
  28223. {
  28224. unsigned int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  28225. String s;
  28226. if (v == 0 || v == -1)
  28227. v = getVersionNumber();
  28228. if (v != 0)
  28229. {
  28230. int versionBits[4];
  28231. int n = 0;
  28232. while (v != 0)
  28233. {
  28234. versionBits [n++] = (v & 0xff);
  28235. v >>= 8;
  28236. }
  28237. s << 'V';
  28238. while (n > 0)
  28239. {
  28240. s << versionBits [--n];
  28241. if (n > 0)
  28242. s << '.';
  28243. }
  28244. }
  28245. return s;
  28246. }
  28247. int VSTPluginInstance::getUID() const
  28248. {
  28249. int uid = effect != 0 ? effect->uniqueID : 0;
  28250. if (uid == 0)
  28251. uid = module->file.hashCode();
  28252. return uid;
  28253. }
  28254. const String VSTPluginInstance::getCategory() const
  28255. {
  28256. const char* result = 0;
  28257. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  28258. {
  28259. case kPlugCategEffect: result = "Effect"; break;
  28260. case kPlugCategSynth: result = "Synth"; break;
  28261. case kPlugCategAnalysis: result = "Anaylsis"; break;
  28262. case kPlugCategMastering: result = "Mastering"; break;
  28263. case kPlugCategSpacializer: result = "Spacial"; break;
  28264. case kPlugCategRoomFx: result = "Reverb"; break;
  28265. case kPlugSurroundFx: result = "Surround"; break;
  28266. case kPlugCategRestoration: result = "Restoration"; break;
  28267. case kPlugCategGenerator: result = "Tone generation"; break;
  28268. default: break;
  28269. }
  28270. return result;
  28271. }
  28272. float VSTPluginInstance::getParameter (int index)
  28273. {
  28274. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  28275. {
  28276. try
  28277. {
  28278. const ScopedLock sl (lock);
  28279. return effect->getParameter (effect, index);
  28280. }
  28281. catch (...)
  28282. {
  28283. }
  28284. }
  28285. return 0.0f;
  28286. }
  28287. void VSTPluginInstance::setParameter (int index, float newValue)
  28288. {
  28289. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  28290. {
  28291. try
  28292. {
  28293. const ScopedLock sl (lock);
  28294. if (effect->getParameter (effect, index) != newValue)
  28295. effect->setParameter (effect, index, newValue);
  28296. }
  28297. catch (...)
  28298. {
  28299. }
  28300. }
  28301. }
  28302. const String VSTPluginInstance::getParameterName (int index)
  28303. {
  28304. if (effect != 0)
  28305. {
  28306. jassert (index >= 0 && index < effect->numParams);
  28307. char nm [256];
  28308. zerostruct (nm);
  28309. dispatch (effGetParamName, index, 0, nm, 0);
  28310. return String (nm).trim();
  28311. }
  28312. return String::empty;
  28313. }
  28314. const String VSTPluginInstance::getParameterLabel (int index) const
  28315. {
  28316. if (effect != 0)
  28317. {
  28318. jassert (index >= 0 && index < effect->numParams);
  28319. char nm [256];
  28320. zerostruct (nm);
  28321. dispatch (effGetParamLabel, index, 0, nm, 0);
  28322. return String (nm).trim();
  28323. }
  28324. return String::empty;
  28325. }
  28326. const String VSTPluginInstance::getParameterText (int index)
  28327. {
  28328. if (effect != 0)
  28329. {
  28330. jassert (index >= 0 && index < effect->numParams);
  28331. char nm [256];
  28332. zerostruct (nm);
  28333. dispatch (effGetParamDisplay, index, 0, nm, 0);
  28334. return String (nm).trim();
  28335. }
  28336. return String::empty;
  28337. }
  28338. bool VSTPluginInstance::isParameterAutomatable (int index) const
  28339. {
  28340. if (effect != 0)
  28341. {
  28342. jassert (index >= 0 && index < effect->numParams);
  28343. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  28344. }
  28345. return false;
  28346. }
  28347. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  28348. {
  28349. dest.setSize (64 + 4 * getNumParameters());
  28350. dest.fillWith (0);
  28351. getCurrentProgramName().copyToCString ((char*) dest.getData(), 63);
  28352. float* const p = (float*) (((char*) dest.getData()) + 64);
  28353. for (int i = 0; i < getNumParameters(); ++i)
  28354. p[i] = getParameter(i);
  28355. }
  28356. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  28357. {
  28358. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  28359. float* p = (float*) (((char*) m.getData()) + 64);
  28360. for (int i = 0; i < getNumParameters(); ++i)
  28361. setParameter (i, p[i]);
  28362. }
  28363. void VSTPluginInstance::setCurrentProgram (int newIndex)
  28364. {
  28365. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  28366. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  28367. }
  28368. const String VSTPluginInstance::getProgramName (int index)
  28369. {
  28370. if (index == getCurrentProgram())
  28371. {
  28372. return getCurrentProgramName();
  28373. }
  28374. else if (effect != 0)
  28375. {
  28376. char nm [256];
  28377. zerostruct (nm);
  28378. if (dispatch (effGetProgramNameIndexed,
  28379. jlimit (0, getNumPrograms(), index),
  28380. -1, nm, 0) != 0)
  28381. {
  28382. return String (nm).trim();
  28383. }
  28384. }
  28385. return programNames [index];
  28386. }
  28387. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  28388. {
  28389. if (index == getCurrentProgram())
  28390. {
  28391. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  28392. dispatch (effSetProgramName, 0, 0, (void*) newName.substring (0, 24).toCString(), 0.0f);
  28393. }
  28394. else
  28395. {
  28396. jassertfalse; // xxx not implemented!
  28397. }
  28398. }
  28399. void VSTPluginInstance::updateStoredProgramNames()
  28400. {
  28401. if (effect != 0 && getNumPrograms() > 0)
  28402. {
  28403. char nm [256];
  28404. zerostruct (nm);
  28405. // only do this if the plugin can't use indexed names..
  28406. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  28407. {
  28408. const int oldProgram = getCurrentProgram();
  28409. MemoryBlock oldSettings;
  28410. createTempParameterStore (oldSettings);
  28411. for (int i = 0; i < getNumPrograms(); ++i)
  28412. {
  28413. setCurrentProgram (i);
  28414. getCurrentProgramName(); // (this updates the list)
  28415. }
  28416. setCurrentProgram (oldProgram);
  28417. restoreFromTempParameterStore (oldSettings);
  28418. }
  28419. }
  28420. }
  28421. const String VSTPluginInstance::getCurrentProgramName()
  28422. {
  28423. if (effect != 0)
  28424. {
  28425. char nm [256];
  28426. zerostruct (nm);
  28427. dispatch (effGetProgramName, 0, 0, nm, 0);
  28428. const int index = getCurrentProgram();
  28429. if (programNames[index].isEmpty())
  28430. {
  28431. while (programNames.size() < index)
  28432. programNames.add (String::empty);
  28433. programNames.set (index, String (nm).trim());
  28434. }
  28435. return String (nm).trim();
  28436. }
  28437. return String::empty;
  28438. }
  28439. const String VSTPluginInstance::getInputChannelName (int index) const
  28440. {
  28441. if (index >= 0 && index < getNumInputChannels())
  28442. {
  28443. VstPinProperties pinProps;
  28444. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28445. return String (pinProps.label, sizeof (pinProps.label));
  28446. }
  28447. return String::empty;
  28448. }
  28449. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  28450. {
  28451. if (index < 0 || index >= getNumInputChannels())
  28452. return false;
  28453. VstPinProperties pinProps;
  28454. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28455. return (pinProps.flags & kVstPinIsStereo) != 0;
  28456. return true;
  28457. }
  28458. const String VSTPluginInstance::getOutputChannelName (int index) const
  28459. {
  28460. if (index >= 0 && index < getNumOutputChannels())
  28461. {
  28462. VstPinProperties pinProps;
  28463. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28464. return String (pinProps.label, sizeof (pinProps.label));
  28465. }
  28466. return String::empty;
  28467. }
  28468. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  28469. {
  28470. if (index < 0 || index >= getNumOutputChannels())
  28471. return false;
  28472. VstPinProperties pinProps;
  28473. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28474. return (pinProps.flags & kVstPinIsStereo) != 0;
  28475. return true;
  28476. }
  28477. void VSTPluginInstance::setPower (const bool on)
  28478. {
  28479. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  28480. isPowerOn = on;
  28481. }
  28482. const int defaultMaxSizeMB = 64;
  28483. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  28484. {
  28485. saveToFXBFile (destData, true, defaultMaxSizeMB);
  28486. }
  28487. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  28488. {
  28489. saveToFXBFile (destData, false, defaultMaxSizeMB);
  28490. }
  28491. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  28492. {
  28493. loadFromFXBFile (data, sizeInBytes);
  28494. }
  28495. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28496. {
  28497. loadFromFXBFile (data, sizeInBytes);
  28498. }
  28499. VSTPluginFormat::VSTPluginFormat()
  28500. {
  28501. }
  28502. VSTPluginFormat::~VSTPluginFormat()
  28503. {
  28504. }
  28505. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  28506. const String& fileOrIdentifier)
  28507. {
  28508. if (! fileMightContainThisPluginType (fileOrIdentifier))
  28509. return;
  28510. PluginDescription desc;
  28511. desc.fileOrIdentifier = fileOrIdentifier;
  28512. desc.uid = 0;
  28513. ScopedPointer <VSTPluginInstance> instance (dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc)));
  28514. if (instance == 0)
  28515. return;
  28516. try
  28517. {
  28518. #if JUCE_MAC
  28519. if (instance->module->resFileId != 0)
  28520. UseResFile (instance->module->resFileId);
  28521. #endif
  28522. instance->fillInPluginDescription (desc);
  28523. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  28524. if (category != kPlugCategShell)
  28525. {
  28526. // Normal plugin...
  28527. results.add (new PluginDescription (desc));
  28528. ++insideVSTCallback;
  28529. instance->dispatch (effOpen, 0, 0, 0, 0);
  28530. --insideVSTCallback;
  28531. }
  28532. else
  28533. {
  28534. // It's a shell plugin, so iterate all the subtypes...
  28535. char shellEffectName [64];
  28536. for (;;)
  28537. {
  28538. zerostruct (shellEffectName);
  28539. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  28540. if (uid == 0)
  28541. {
  28542. break;
  28543. }
  28544. else
  28545. {
  28546. desc.uid = uid;
  28547. desc.name = shellEffectName;
  28548. bool alreadyThere = false;
  28549. for (int i = results.size(); --i >= 0;)
  28550. {
  28551. PluginDescription* const d = results.getUnchecked(i);
  28552. if (d->isDuplicateOf (desc))
  28553. {
  28554. alreadyThere = true;
  28555. break;
  28556. }
  28557. }
  28558. if (! alreadyThere)
  28559. results.add (new PluginDescription (desc));
  28560. }
  28561. }
  28562. }
  28563. }
  28564. catch (...)
  28565. {
  28566. // crashed while loading...
  28567. }
  28568. }
  28569. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  28570. {
  28571. ScopedPointer <VSTPluginInstance> result;
  28572. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  28573. {
  28574. File file (desc.fileOrIdentifier);
  28575. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  28576. file.getParentDirectory().setAsCurrentWorkingDirectory();
  28577. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (file));
  28578. if (module != 0)
  28579. {
  28580. shellUIDToCreate = desc.uid;
  28581. result = new VSTPluginInstance (module);
  28582. if (result->effect != 0)
  28583. {
  28584. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) (VSTPluginInstance*) result;
  28585. result->initialise();
  28586. }
  28587. else
  28588. {
  28589. result = 0;
  28590. }
  28591. }
  28592. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  28593. }
  28594. return result.release();
  28595. }
  28596. bool VSTPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  28597. {
  28598. const File f (fileOrIdentifier);
  28599. #if JUCE_MAC
  28600. if (f.isDirectory() && f.hasFileExtension (".vst"))
  28601. return true;
  28602. #if JUCE_PPC
  28603. FSRef fileRef;
  28604. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  28605. {
  28606. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  28607. if (resFileId != -1)
  28608. {
  28609. const int numEffects = Count1Resources ('aEff');
  28610. CloseResFile (resFileId);
  28611. if (numEffects > 0)
  28612. return true;
  28613. }
  28614. }
  28615. #endif
  28616. return false;
  28617. #elif JUCE_WINDOWS
  28618. return f.existsAsFile() && f.hasFileExtension (".dll");
  28619. #elif JUCE_LINUX
  28620. return f.existsAsFile() && f.hasFileExtension (".so");
  28621. #endif
  28622. }
  28623. const String VSTPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  28624. {
  28625. return fileOrIdentifier;
  28626. }
  28627. bool VSTPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  28628. {
  28629. return File (desc.fileOrIdentifier).exists();
  28630. }
  28631. const StringArray VSTPluginFormat::searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive)
  28632. {
  28633. StringArray results;
  28634. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  28635. recursiveFileSearch (results, directoriesToSearch [j], recursive);
  28636. return results;
  28637. }
  28638. void VSTPluginFormat::recursiveFileSearch (StringArray& results, const File& dir, const bool recursive)
  28639. {
  28640. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  28641. // .component or .vst directories.
  28642. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  28643. while (iter.next())
  28644. {
  28645. const File f (iter.getFile());
  28646. bool isPlugin = false;
  28647. if (fileMightContainThisPluginType (f.getFullPathName()))
  28648. {
  28649. isPlugin = true;
  28650. results.add (f.getFullPathName());
  28651. }
  28652. if (recursive && (! isPlugin) && f.isDirectory())
  28653. recursiveFileSearch (results, f, true);
  28654. }
  28655. }
  28656. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  28657. {
  28658. #if JUCE_MAC
  28659. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  28660. #elif JUCE_WINDOWS
  28661. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  28662. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  28663. #elif JUCE_LINUX
  28664. return FileSearchPath ("/usr/lib/vst");
  28665. #endif
  28666. }
  28667. END_JUCE_NAMESPACE
  28668. #endif
  28669. #undef log
  28670. #endif
  28671. /*** End of inlined file: juce_VSTPluginFormat.cpp ***/
  28672. /*** End of inlined file: juce_VSTPluginFormat.mm ***/
  28673. /*** Start of inlined file: juce_AudioProcessor.cpp ***/
  28674. BEGIN_JUCE_NAMESPACE
  28675. AudioProcessor::AudioProcessor()
  28676. : playHead (0),
  28677. activeEditor (0),
  28678. sampleRate (0),
  28679. blockSize (0),
  28680. numInputChannels (0),
  28681. numOutputChannels (0),
  28682. latencySamples (0),
  28683. suspended (false),
  28684. nonRealtime (false)
  28685. {
  28686. }
  28687. AudioProcessor::~AudioProcessor()
  28688. {
  28689. // ooh, nasty - the editor should have been deleted before the filter
  28690. // that it refers to is deleted..
  28691. jassert (activeEditor == 0);
  28692. #if JUCE_DEBUG
  28693. // This will fail if you've called beginParameterChangeGesture() for one
  28694. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  28695. jassert (changingParams.countNumberOfSetBits() == 0);
  28696. #endif
  28697. }
  28698. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  28699. {
  28700. playHead = newPlayHead;
  28701. }
  28702. void AudioProcessor::addListener (AudioProcessorListener* const newListener)
  28703. {
  28704. const ScopedLock sl (listenerLock);
  28705. listeners.addIfNotAlreadyThere (newListener);
  28706. }
  28707. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove)
  28708. {
  28709. const ScopedLock sl (listenerLock);
  28710. listeners.removeValue (listenerToRemove);
  28711. }
  28712. void AudioProcessor::setPlayConfigDetails (const int numIns,
  28713. const int numOuts,
  28714. const double sampleRate_,
  28715. const int blockSize_) throw()
  28716. {
  28717. numInputChannels = numIns;
  28718. numOutputChannels = numOuts;
  28719. sampleRate = sampleRate_;
  28720. blockSize = blockSize_;
  28721. }
  28722. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  28723. {
  28724. nonRealtime = nonRealtime_;
  28725. }
  28726. void AudioProcessor::setLatencySamples (const int newLatency)
  28727. {
  28728. if (latencySamples != newLatency)
  28729. {
  28730. latencySamples = newLatency;
  28731. updateHostDisplay();
  28732. }
  28733. }
  28734. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  28735. const float newValue)
  28736. {
  28737. setParameter (parameterIndex, newValue);
  28738. sendParamChangeMessageToListeners (parameterIndex, newValue);
  28739. }
  28740. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  28741. {
  28742. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  28743. for (int i = listeners.size(); --i >= 0;)
  28744. {
  28745. AudioProcessorListener* l;
  28746. {
  28747. const ScopedLock sl (listenerLock);
  28748. l = listeners [i];
  28749. }
  28750. if (l != 0)
  28751. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  28752. }
  28753. }
  28754. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  28755. {
  28756. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  28757. #if JUCE_DEBUG
  28758. // This means you've called beginParameterChangeGesture twice in succession without a matching
  28759. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  28760. jassert (! changingParams [parameterIndex]);
  28761. changingParams.setBit (parameterIndex);
  28762. #endif
  28763. for (int i = listeners.size(); --i >= 0;)
  28764. {
  28765. AudioProcessorListener* l;
  28766. {
  28767. const ScopedLock sl (listenerLock);
  28768. l = listeners [i];
  28769. }
  28770. if (l != 0)
  28771. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  28772. }
  28773. }
  28774. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  28775. {
  28776. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  28777. #if JUCE_DEBUG
  28778. // This means you've called endParameterChangeGesture without having previously called
  28779. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  28780. // calls matched correctly.
  28781. jassert (changingParams [parameterIndex]);
  28782. changingParams.clearBit (parameterIndex);
  28783. #endif
  28784. for (int i = listeners.size(); --i >= 0;)
  28785. {
  28786. AudioProcessorListener* l;
  28787. {
  28788. const ScopedLock sl (listenerLock);
  28789. l = listeners [i];
  28790. }
  28791. if (l != 0)
  28792. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  28793. }
  28794. }
  28795. void AudioProcessor::updateHostDisplay()
  28796. {
  28797. for (int i = listeners.size(); --i >= 0;)
  28798. {
  28799. AudioProcessorListener* l;
  28800. {
  28801. const ScopedLock sl (listenerLock);
  28802. l = listeners [i];
  28803. }
  28804. if (l != 0)
  28805. l->audioProcessorChanged (this);
  28806. }
  28807. }
  28808. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  28809. {
  28810. return true;
  28811. }
  28812. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  28813. {
  28814. return false;
  28815. }
  28816. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  28817. {
  28818. const ScopedLock sl (callbackLock);
  28819. suspended = shouldBeSuspended;
  28820. }
  28821. void AudioProcessor::reset()
  28822. {
  28823. }
  28824. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  28825. {
  28826. const ScopedLock sl (callbackLock);
  28827. jassert (activeEditor == editor);
  28828. if (activeEditor == editor)
  28829. activeEditor = 0;
  28830. }
  28831. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  28832. {
  28833. if (activeEditor != 0)
  28834. return activeEditor;
  28835. AudioProcessorEditor* const ed = createEditor();
  28836. // You must make your hasEditor() method return a consistent result!
  28837. jassert (hasEditor() == (ed != 0));
  28838. if (ed != 0)
  28839. {
  28840. // you must give your editor comp a size before returning it..
  28841. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  28842. const ScopedLock sl (callbackLock);
  28843. activeEditor = ed;
  28844. }
  28845. return ed;
  28846. }
  28847. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  28848. {
  28849. getStateInformation (destData);
  28850. }
  28851. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28852. {
  28853. setStateInformation (data, sizeInBytes);
  28854. }
  28855. // magic number to identify memory blocks that we've stored as XML
  28856. const uint32 magicXmlNumber = 0x21324356;
  28857. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  28858. JUCE_NAMESPACE::MemoryBlock& destData)
  28859. {
  28860. const String xmlString (xml.createDocument (String::empty, true, false));
  28861. const int stringLength = xmlString.getNumBytesAsUTF8();
  28862. destData.setSize (stringLength + 10);
  28863. char* const d = static_cast<char*> (destData.getData());
  28864. *(uint32*) d = ByteOrder::swapIfBigEndian ((const uint32) magicXmlNumber);
  28865. *(uint32*) (d + 4) = ByteOrder::swapIfBigEndian ((const uint32) stringLength);
  28866. xmlString.copyToUTF8 (d + 8, stringLength + 1);
  28867. }
  28868. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  28869. const int sizeInBytes)
  28870. {
  28871. if (sizeInBytes > 8
  28872. && ByteOrder::littleEndianInt (data) == magicXmlNumber)
  28873. {
  28874. const int stringLength = (int) ByteOrder::littleEndianInt (addBytesToPointer (data, 4));
  28875. if (stringLength > 0)
  28876. {
  28877. XmlDocument doc (String::fromUTF8 (static_cast<const char*> (data) + 8,
  28878. jmin ((sizeInBytes - 8), stringLength)));
  28879. return doc.getDocumentElement();
  28880. }
  28881. }
  28882. return 0;
  28883. }
  28884. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int) {}
  28885. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int) {}
  28886. bool AudioPlayHead::CurrentPositionInfo::operator== (const CurrentPositionInfo& other) const throw()
  28887. {
  28888. return timeInSeconds == other.timeInSeconds
  28889. && ppqPosition == other.ppqPosition
  28890. && editOriginTime == other.editOriginTime
  28891. && ppqPositionOfLastBarStart == other.ppqPositionOfLastBarStart
  28892. && frameRate == other.frameRate
  28893. && isPlaying == other.isPlaying
  28894. && isRecording == other.isRecording
  28895. && bpm == other.bpm
  28896. && timeSigNumerator == other.timeSigNumerator
  28897. && timeSigDenominator == other.timeSigDenominator;
  28898. }
  28899. bool AudioPlayHead::CurrentPositionInfo::operator!= (const CurrentPositionInfo& other) const throw()
  28900. {
  28901. return ! operator== (other);
  28902. }
  28903. void AudioPlayHead::CurrentPositionInfo::resetToDefault()
  28904. {
  28905. zerostruct (*this);
  28906. timeSigNumerator = 4;
  28907. timeSigDenominator = 4;
  28908. bpm = 120;
  28909. }
  28910. END_JUCE_NAMESPACE
  28911. /*** End of inlined file: juce_AudioProcessor.cpp ***/
  28912. /*** Start of inlined file: juce_AudioProcessorEditor.cpp ***/
  28913. BEGIN_JUCE_NAMESPACE
  28914. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  28915. : owner (owner_)
  28916. {
  28917. // the filter must be valid..
  28918. jassert (owner != 0);
  28919. }
  28920. AudioProcessorEditor::~AudioProcessorEditor()
  28921. {
  28922. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  28923. // filter for some reason..
  28924. jassert (owner->getActiveEditor() != this);
  28925. }
  28926. END_JUCE_NAMESPACE
  28927. /*** End of inlined file: juce_AudioProcessorEditor.cpp ***/
  28928. /*** Start of inlined file: juce_AudioProcessorGraph.cpp ***/
  28929. BEGIN_JUCE_NAMESPACE
  28930. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  28931. AudioProcessorGraph::Node::Node (const uint32 id_, AudioProcessor* const processor_)
  28932. : id (id_),
  28933. processor (processor_),
  28934. isPrepared (false)
  28935. {
  28936. jassert (processor_ != 0);
  28937. }
  28938. AudioProcessorGraph::Node::~Node()
  28939. {
  28940. }
  28941. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  28942. AudioProcessorGraph* const graph)
  28943. {
  28944. if (! isPrepared)
  28945. {
  28946. isPrepared = true;
  28947. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  28948. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (processor));
  28949. if (ioProc != 0)
  28950. ioProc->setParentGraph (graph);
  28951. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  28952. processor->getNumOutputChannels(),
  28953. sampleRate, blockSize);
  28954. processor->prepareToPlay (sampleRate, blockSize);
  28955. }
  28956. }
  28957. void AudioProcessorGraph::Node::unprepare()
  28958. {
  28959. if (isPrepared)
  28960. {
  28961. isPrepared = false;
  28962. processor->releaseResources();
  28963. }
  28964. }
  28965. AudioProcessorGraph::AudioProcessorGraph()
  28966. : lastNodeId (0),
  28967. renderingBuffers (1, 1),
  28968. currentAudioOutputBuffer (1, 1)
  28969. {
  28970. }
  28971. AudioProcessorGraph::~AudioProcessorGraph()
  28972. {
  28973. clearRenderingSequence();
  28974. clear();
  28975. }
  28976. const String AudioProcessorGraph::getName() const
  28977. {
  28978. return "Audio Graph";
  28979. }
  28980. void AudioProcessorGraph::clear()
  28981. {
  28982. nodes.clear();
  28983. connections.clear();
  28984. triggerAsyncUpdate();
  28985. }
  28986. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const
  28987. {
  28988. for (int i = nodes.size(); --i >= 0;)
  28989. if (nodes.getUnchecked(i)->id == nodeId)
  28990. return nodes.getUnchecked(i);
  28991. return 0;
  28992. }
  28993. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  28994. uint32 nodeId)
  28995. {
  28996. if (newProcessor == 0)
  28997. {
  28998. jassertfalse;
  28999. return 0;
  29000. }
  29001. if (nodeId == 0)
  29002. {
  29003. nodeId = ++lastNodeId;
  29004. }
  29005. else
  29006. {
  29007. // you can't add a node with an id that already exists in the graph..
  29008. jassert (getNodeForId (nodeId) == 0);
  29009. removeNode (nodeId);
  29010. }
  29011. lastNodeId = nodeId;
  29012. Node* const n = new Node (nodeId, newProcessor);
  29013. nodes.add (n);
  29014. triggerAsyncUpdate();
  29015. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  29016. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (n->processor));
  29017. if (ioProc != 0)
  29018. ioProc->setParentGraph (this);
  29019. return n;
  29020. }
  29021. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  29022. {
  29023. disconnectNode (nodeId);
  29024. for (int i = nodes.size(); --i >= 0;)
  29025. {
  29026. if (nodes.getUnchecked(i)->id == nodeId)
  29027. {
  29028. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  29029. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (nodes.getUnchecked(i)->processor));
  29030. if (ioProc != 0)
  29031. ioProc->setParentGraph (0);
  29032. nodes.remove (i);
  29033. triggerAsyncUpdate();
  29034. return true;
  29035. }
  29036. }
  29037. return false;
  29038. }
  29039. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  29040. const int sourceChannelIndex,
  29041. const uint32 destNodeId,
  29042. const int destChannelIndex) const
  29043. {
  29044. for (int i = connections.size(); --i >= 0;)
  29045. {
  29046. const Connection* const c = connections.getUnchecked(i);
  29047. if (c->sourceNodeId == sourceNodeId
  29048. && c->destNodeId == destNodeId
  29049. && c->sourceChannelIndex == sourceChannelIndex
  29050. && c->destChannelIndex == destChannelIndex)
  29051. {
  29052. return c;
  29053. }
  29054. }
  29055. return 0;
  29056. }
  29057. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  29058. const uint32 possibleDestNodeId) const
  29059. {
  29060. for (int i = connections.size(); --i >= 0;)
  29061. {
  29062. const Connection* const c = connections.getUnchecked(i);
  29063. if (c->sourceNodeId == possibleSourceNodeId
  29064. && c->destNodeId == possibleDestNodeId)
  29065. {
  29066. return true;
  29067. }
  29068. }
  29069. return false;
  29070. }
  29071. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  29072. const int sourceChannelIndex,
  29073. const uint32 destNodeId,
  29074. const int destChannelIndex) const
  29075. {
  29076. if (sourceChannelIndex < 0
  29077. || destChannelIndex < 0
  29078. || sourceNodeId == destNodeId
  29079. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  29080. return false;
  29081. const Node* const source = getNodeForId (sourceNodeId);
  29082. if (source == 0
  29083. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  29084. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  29085. return false;
  29086. const Node* const dest = getNodeForId (destNodeId);
  29087. if (dest == 0
  29088. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  29089. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  29090. return false;
  29091. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  29092. destNodeId, destChannelIndex) == 0;
  29093. }
  29094. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  29095. const int sourceChannelIndex,
  29096. const uint32 destNodeId,
  29097. const int destChannelIndex)
  29098. {
  29099. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  29100. return false;
  29101. Connection* const c = new Connection();
  29102. c->sourceNodeId = sourceNodeId;
  29103. c->sourceChannelIndex = sourceChannelIndex;
  29104. c->destNodeId = destNodeId;
  29105. c->destChannelIndex = destChannelIndex;
  29106. connections.add (c);
  29107. triggerAsyncUpdate();
  29108. return true;
  29109. }
  29110. void AudioProcessorGraph::removeConnection (const int index)
  29111. {
  29112. connections.remove (index);
  29113. triggerAsyncUpdate();
  29114. }
  29115. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  29116. const uint32 destNodeId, const int destChannelIndex)
  29117. {
  29118. bool doneAnything = false;
  29119. for (int i = connections.size(); --i >= 0;)
  29120. {
  29121. const Connection* const c = connections.getUnchecked(i);
  29122. if (c->sourceNodeId == sourceNodeId
  29123. && c->destNodeId == destNodeId
  29124. && c->sourceChannelIndex == sourceChannelIndex
  29125. && c->destChannelIndex == destChannelIndex)
  29126. {
  29127. removeConnection (i);
  29128. doneAnything = true;
  29129. triggerAsyncUpdate();
  29130. }
  29131. }
  29132. return doneAnything;
  29133. }
  29134. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  29135. {
  29136. bool doneAnything = false;
  29137. for (int i = connections.size(); --i >= 0;)
  29138. {
  29139. const Connection* const c = connections.getUnchecked(i);
  29140. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  29141. {
  29142. removeConnection (i);
  29143. doneAnything = true;
  29144. triggerAsyncUpdate();
  29145. }
  29146. }
  29147. return doneAnything;
  29148. }
  29149. bool AudioProcessorGraph::removeIllegalConnections()
  29150. {
  29151. bool doneAnything = false;
  29152. for (int i = connections.size(); --i >= 0;)
  29153. {
  29154. const Connection* const c = connections.getUnchecked(i);
  29155. const Node* const source = getNodeForId (c->sourceNodeId);
  29156. const Node* const dest = getNodeForId (c->destNodeId);
  29157. if (source == 0 || dest == 0
  29158. || (c->sourceChannelIndex != midiChannelIndex
  29159. && (((unsigned int) c->sourceChannelIndex) >= (unsigned int) source->processor->getNumOutputChannels()))
  29160. || (c->sourceChannelIndex == midiChannelIndex
  29161. && ! source->processor->producesMidi())
  29162. || (c->destChannelIndex != midiChannelIndex
  29163. && (((unsigned int) c->destChannelIndex) >= (unsigned int) dest->processor->getNumInputChannels()))
  29164. || (c->destChannelIndex == midiChannelIndex
  29165. && ! dest->processor->acceptsMidi()))
  29166. {
  29167. removeConnection (i);
  29168. doneAnything = true;
  29169. triggerAsyncUpdate();
  29170. }
  29171. }
  29172. return doneAnything;
  29173. }
  29174. namespace GraphRenderingOps
  29175. {
  29176. class AudioGraphRenderingOp
  29177. {
  29178. public:
  29179. AudioGraphRenderingOp() {}
  29180. virtual ~AudioGraphRenderingOp() {}
  29181. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  29182. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  29183. const int numSamples) = 0;
  29184. juce_UseDebuggingNewOperator
  29185. };
  29186. class ClearChannelOp : public AudioGraphRenderingOp
  29187. {
  29188. public:
  29189. ClearChannelOp (const int channelNum_)
  29190. : channelNum (channelNum_)
  29191. {}
  29192. ~ClearChannelOp() {}
  29193. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29194. {
  29195. sharedBufferChans.clear (channelNum, 0, numSamples);
  29196. }
  29197. private:
  29198. const int channelNum;
  29199. ClearChannelOp (const ClearChannelOp&);
  29200. ClearChannelOp& operator= (const ClearChannelOp&);
  29201. };
  29202. class CopyChannelOp : public AudioGraphRenderingOp
  29203. {
  29204. public:
  29205. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29206. : srcChannelNum (srcChannelNum_),
  29207. dstChannelNum (dstChannelNum_)
  29208. {}
  29209. ~CopyChannelOp() {}
  29210. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29211. {
  29212. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29213. }
  29214. private:
  29215. const int srcChannelNum, dstChannelNum;
  29216. CopyChannelOp (const CopyChannelOp&);
  29217. CopyChannelOp& operator= (const CopyChannelOp&);
  29218. };
  29219. class AddChannelOp : public AudioGraphRenderingOp
  29220. {
  29221. public:
  29222. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29223. : srcChannelNum (srcChannelNum_),
  29224. dstChannelNum (dstChannelNum_)
  29225. {}
  29226. ~AddChannelOp() {}
  29227. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29228. {
  29229. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29230. }
  29231. private:
  29232. const int srcChannelNum, dstChannelNum;
  29233. AddChannelOp (const AddChannelOp&);
  29234. AddChannelOp& operator= (const AddChannelOp&);
  29235. };
  29236. class ClearMidiBufferOp : public AudioGraphRenderingOp
  29237. {
  29238. public:
  29239. ClearMidiBufferOp (const int bufferNum_)
  29240. : bufferNum (bufferNum_)
  29241. {}
  29242. ~ClearMidiBufferOp() {}
  29243. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29244. {
  29245. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  29246. }
  29247. private:
  29248. const int bufferNum;
  29249. ClearMidiBufferOp (const ClearMidiBufferOp&);
  29250. ClearMidiBufferOp& operator= (const ClearMidiBufferOp&);
  29251. };
  29252. class CopyMidiBufferOp : public AudioGraphRenderingOp
  29253. {
  29254. public:
  29255. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29256. : srcBufferNum (srcBufferNum_),
  29257. dstBufferNum (dstBufferNum_)
  29258. {}
  29259. ~CopyMidiBufferOp() {}
  29260. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29261. {
  29262. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  29263. }
  29264. private:
  29265. const int srcBufferNum, dstBufferNum;
  29266. CopyMidiBufferOp (const CopyMidiBufferOp&);
  29267. CopyMidiBufferOp& operator= (const CopyMidiBufferOp&);
  29268. };
  29269. class AddMidiBufferOp : public AudioGraphRenderingOp
  29270. {
  29271. public:
  29272. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29273. : srcBufferNum (srcBufferNum_),
  29274. dstBufferNum (dstBufferNum_)
  29275. {}
  29276. ~AddMidiBufferOp() {}
  29277. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29278. {
  29279. sharedMidiBuffers.getUnchecked (dstBufferNum)
  29280. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  29281. }
  29282. private:
  29283. const int srcBufferNum, dstBufferNum;
  29284. AddMidiBufferOp (const AddMidiBufferOp&);
  29285. AddMidiBufferOp& operator= (const AddMidiBufferOp&);
  29286. };
  29287. class ProcessBufferOp : public AudioGraphRenderingOp
  29288. {
  29289. public:
  29290. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  29291. const Array <int>& audioChannelsToUse_,
  29292. const int totalChans_,
  29293. const int midiBufferToUse_)
  29294. : node (node_),
  29295. processor (node_->getProcessor()),
  29296. audioChannelsToUse (audioChannelsToUse_),
  29297. totalChans (jmax (1, totalChans_)),
  29298. midiBufferToUse (midiBufferToUse_)
  29299. {
  29300. channels.calloc (totalChans);
  29301. while (audioChannelsToUse.size() < totalChans)
  29302. audioChannelsToUse.add (0);
  29303. }
  29304. ~ProcessBufferOp()
  29305. {
  29306. }
  29307. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29308. {
  29309. for (int i = totalChans; --i >= 0;)
  29310. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  29311. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  29312. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  29313. }
  29314. const AudioProcessorGraph::Node::Ptr node;
  29315. AudioProcessor* const processor;
  29316. private:
  29317. Array <int> audioChannelsToUse;
  29318. HeapBlock <float*> channels;
  29319. int totalChans;
  29320. int midiBufferToUse;
  29321. ProcessBufferOp (const ProcessBufferOp&);
  29322. ProcessBufferOp& operator= (const ProcessBufferOp&);
  29323. };
  29324. /** Used to calculate the correct sequence of rendering ops needed, based on
  29325. the best re-use of shared buffers at each stage.
  29326. */
  29327. class RenderingOpSequenceCalculator
  29328. {
  29329. public:
  29330. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  29331. const Array<void*>& orderedNodes_,
  29332. Array<void*>& renderingOps)
  29333. : graph (graph_),
  29334. orderedNodes (orderedNodes_)
  29335. {
  29336. nodeIds.add (-2); // first buffer is read-only zeros
  29337. channels.add (0);
  29338. midiNodeIds.add (-2);
  29339. for (int i = 0; i < orderedNodes.size(); ++i)
  29340. {
  29341. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  29342. renderingOps, i);
  29343. markAnyUnusedBuffersAsFree (i);
  29344. }
  29345. }
  29346. int getNumBuffersNeeded() const { return nodeIds.size(); }
  29347. int getNumMidiBuffersNeeded() const { return midiNodeIds.size(); }
  29348. juce_UseDebuggingNewOperator
  29349. private:
  29350. AudioProcessorGraph& graph;
  29351. const Array<void*>& orderedNodes;
  29352. Array <int> nodeIds, channels, midiNodeIds;
  29353. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  29354. Array<void*>& renderingOps,
  29355. const int ourRenderingIndex)
  29356. {
  29357. const int numIns = node->getProcessor()->getNumInputChannels();
  29358. const int numOuts = node->getProcessor()->getNumOutputChannels();
  29359. const int totalChans = jmax (numIns, numOuts);
  29360. Array <int> audioChannelsToUse;
  29361. int midiBufferToUse = -1;
  29362. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  29363. {
  29364. // get a list of all the inputs to this node
  29365. Array <int> sourceNodes, sourceOutputChans;
  29366. for (int i = graph.getNumConnections(); --i >= 0;)
  29367. {
  29368. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29369. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  29370. {
  29371. sourceNodes.add (c->sourceNodeId);
  29372. sourceOutputChans.add (c->sourceChannelIndex);
  29373. }
  29374. }
  29375. int bufIndex = -1;
  29376. if (sourceNodes.size() == 0)
  29377. {
  29378. // unconnected input channel
  29379. if (inputChan >= numOuts)
  29380. {
  29381. bufIndex = getReadOnlyEmptyBuffer();
  29382. jassert (bufIndex >= 0);
  29383. }
  29384. else
  29385. {
  29386. bufIndex = getFreeBuffer (false);
  29387. renderingOps.add (new ClearChannelOp (bufIndex));
  29388. }
  29389. }
  29390. else if (sourceNodes.size() == 1)
  29391. {
  29392. // channel with a straightforward single input..
  29393. const int srcNode = sourceNodes.getUnchecked(0);
  29394. const int srcChan = sourceOutputChans.getUnchecked(0);
  29395. bufIndex = getBufferContaining (srcNode, srcChan);
  29396. if (bufIndex < 0)
  29397. {
  29398. // if not found, this is probably a feedback loop
  29399. bufIndex = getReadOnlyEmptyBuffer();
  29400. jassert (bufIndex >= 0);
  29401. }
  29402. if (inputChan < numOuts
  29403. && isBufferNeededLater (ourRenderingIndex,
  29404. inputChan,
  29405. srcNode, srcChan))
  29406. {
  29407. // can't mess up this channel because it's needed later by another node, so we
  29408. // need to use a copy of it..
  29409. const int newFreeBuffer = getFreeBuffer (false);
  29410. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  29411. bufIndex = newFreeBuffer;
  29412. }
  29413. }
  29414. else
  29415. {
  29416. // channel with a mix of several inputs..
  29417. // try to find a re-usable channel from our inputs..
  29418. int reusableInputIndex = -1;
  29419. for (int i = 0; i < sourceNodes.size(); ++i)
  29420. {
  29421. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  29422. sourceOutputChans.getUnchecked(i));
  29423. if (sourceBufIndex >= 0
  29424. && ! isBufferNeededLater (ourRenderingIndex,
  29425. inputChan,
  29426. sourceNodes.getUnchecked(i),
  29427. sourceOutputChans.getUnchecked(i)))
  29428. {
  29429. // we've found one of our input chans that can be re-used..
  29430. reusableInputIndex = i;
  29431. bufIndex = sourceBufIndex;
  29432. break;
  29433. }
  29434. }
  29435. if (reusableInputIndex < 0)
  29436. {
  29437. // can't re-use any of our input chans, so get a new one and copy everything into it..
  29438. bufIndex = getFreeBuffer (false);
  29439. jassert (bufIndex != 0);
  29440. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  29441. sourceOutputChans.getUnchecked (0));
  29442. if (srcIndex < 0)
  29443. {
  29444. // if not found, this is probably a feedback loop
  29445. renderingOps.add (new ClearChannelOp (bufIndex));
  29446. }
  29447. else
  29448. {
  29449. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  29450. }
  29451. reusableInputIndex = 0;
  29452. }
  29453. for (int j = 0; j < sourceNodes.size(); ++j)
  29454. {
  29455. if (j != reusableInputIndex)
  29456. {
  29457. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  29458. sourceOutputChans.getUnchecked(j));
  29459. if (srcIndex >= 0)
  29460. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  29461. }
  29462. }
  29463. }
  29464. jassert (bufIndex >= 0);
  29465. audioChannelsToUse.add (bufIndex);
  29466. if (inputChan < numOuts)
  29467. markBufferAsContaining (bufIndex, node->id, inputChan);
  29468. }
  29469. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  29470. {
  29471. const int bufIndex = getFreeBuffer (false);
  29472. jassert (bufIndex != 0);
  29473. audioChannelsToUse.add (bufIndex);
  29474. markBufferAsContaining (bufIndex, node->id, outputChan);
  29475. }
  29476. // Now the same thing for midi..
  29477. Array <int> midiSourceNodes;
  29478. for (int i = graph.getNumConnections(); --i >= 0;)
  29479. {
  29480. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29481. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  29482. midiSourceNodes.add (c->sourceNodeId);
  29483. }
  29484. if (midiSourceNodes.size() == 0)
  29485. {
  29486. // No midi inputs..
  29487. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29488. if (node->getProcessor()->acceptsMidi() || node->getProcessor()->producesMidi())
  29489. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29490. }
  29491. else if (midiSourceNodes.size() == 1)
  29492. {
  29493. // One midi input..
  29494. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29495. AudioProcessorGraph::midiChannelIndex);
  29496. if (midiBufferToUse >= 0)
  29497. {
  29498. if (isBufferNeededLater (ourRenderingIndex,
  29499. AudioProcessorGraph::midiChannelIndex,
  29500. midiSourceNodes.getUnchecked(0),
  29501. AudioProcessorGraph::midiChannelIndex))
  29502. {
  29503. // can't mess up this channel because it's needed later by another node, so we
  29504. // need to use a copy of it..
  29505. const int newFreeBuffer = getFreeBuffer (true);
  29506. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  29507. midiBufferToUse = newFreeBuffer;
  29508. }
  29509. }
  29510. else
  29511. {
  29512. // probably a feedback loop, so just use an empty one..
  29513. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29514. }
  29515. }
  29516. else
  29517. {
  29518. // More than one midi input being mixed..
  29519. int reusableInputIndex = -1;
  29520. for (int i = 0; i < midiSourceNodes.size(); ++i)
  29521. {
  29522. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  29523. AudioProcessorGraph::midiChannelIndex);
  29524. if (sourceBufIndex >= 0
  29525. && ! isBufferNeededLater (ourRenderingIndex,
  29526. AudioProcessorGraph::midiChannelIndex,
  29527. midiSourceNodes.getUnchecked(i),
  29528. AudioProcessorGraph::midiChannelIndex))
  29529. {
  29530. // we've found one of our input buffers that can be re-used..
  29531. reusableInputIndex = i;
  29532. midiBufferToUse = sourceBufIndex;
  29533. break;
  29534. }
  29535. }
  29536. if (reusableInputIndex < 0)
  29537. {
  29538. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  29539. midiBufferToUse = getFreeBuffer (true);
  29540. jassert (midiBufferToUse >= 0);
  29541. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29542. AudioProcessorGraph::midiChannelIndex);
  29543. if (srcIndex >= 0)
  29544. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  29545. else
  29546. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29547. reusableInputIndex = 0;
  29548. }
  29549. for (int j = 0; j < midiSourceNodes.size(); ++j)
  29550. {
  29551. if (j != reusableInputIndex)
  29552. {
  29553. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  29554. AudioProcessorGraph::midiChannelIndex);
  29555. if (srcIndex >= 0)
  29556. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  29557. }
  29558. }
  29559. }
  29560. if (node->getProcessor()->producesMidi())
  29561. markBufferAsContaining (midiBufferToUse, node->id,
  29562. AudioProcessorGraph::midiChannelIndex);
  29563. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  29564. totalChans, midiBufferToUse));
  29565. }
  29566. int getFreeBuffer (const bool forMidi)
  29567. {
  29568. if (forMidi)
  29569. {
  29570. for (int i = 1; i < midiNodeIds.size(); ++i)
  29571. if (midiNodeIds.getUnchecked(i) < 0)
  29572. return i;
  29573. midiNodeIds.add (-1);
  29574. return midiNodeIds.size() - 1;
  29575. }
  29576. else
  29577. {
  29578. for (int i = 1; i < nodeIds.size(); ++i)
  29579. if (nodeIds.getUnchecked(i) < 0)
  29580. return i;
  29581. nodeIds.add (-1);
  29582. channels.add (0);
  29583. return nodeIds.size() - 1;
  29584. }
  29585. }
  29586. int getReadOnlyEmptyBuffer() const
  29587. {
  29588. return 0;
  29589. }
  29590. int getBufferContaining (const int nodeId, const int outputChannel) const
  29591. {
  29592. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  29593. {
  29594. for (int i = midiNodeIds.size(); --i >= 0;)
  29595. if (midiNodeIds.getUnchecked(i) == nodeId)
  29596. return i;
  29597. }
  29598. else
  29599. {
  29600. for (int i = nodeIds.size(); --i >= 0;)
  29601. if (nodeIds.getUnchecked(i) == nodeId
  29602. && channels.getUnchecked(i) == outputChannel)
  29603. return i;
  29604. }
  29605. return -1;
  29606. }
  29607. void markAnyUnusedBuffersAsFree (const int stepIndex)
  29608. {
  29609. int i;
  29610. for (i = 0; i < nodeIds.size(); ++i)
  29611. {
  29612. if (nodeIds.getUnchecked(i) >= 0
  29613. && ! isBufferNeededLater (stepIndex, -1,
  29614. nodeIds.getUnchecked(i),
  29615. channels.getUnchecked(i)))
  29616. {
  29617. nodeIds.set (i, -1);
  29618. }
  29619. }
  29620. for (i = 0; i < midiNodeIds.size(); ++i)
  29621. {
  29622. if (midiNodeIds.getUnchecked(i) >= 0
  29623. && ! isBufferNeededLater (stepIndex, -1,
  29624. midiNodeIds.getUnchecked(i),
  29625. AudioProcessorGraph::midiChannelIndex))
  29626. {
  29627. midiNodeIds.set (i, -1);
  29628. }
  29629. }
  29630. }
  29631. bool isBufferNeededLater (int stepIndexToSearchFrom,
  29632. int inputChannelOfIndexToIgnore,
  29633. const int nodeId,
  29634. const int outputChanIndex) const
  29635. {
  29636. while (stepIndexToSearchFrom < orderedNodes.size())
  29637. {
  29638. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  29639. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  29640. {
  29641. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  29642. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  29643. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  29644. return true;
  29645. }
  29646. else
  29647. {
  29648. for (int i = 0; i < node->getProcessor()->getNumInputChannels(); ++i)
  29649. if (i != inputChannelOfIndexToIgnore
  29650. && graph.getConnectionBetween (nodeId, outputChanIndex,
  29651. node->id, i) != 0)
  29652. return true;
  29653. }
  29654. inputChannelOfIndexToIgnore = -1;
  29655. ++stepIndexToSearchFrom;
  29656. }
  29657. return false;
  29658. }
  29659. void markBufferAsContaining (int bufferNum, int nodeId, int outputIndex)
  29660. {
  29661. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  29662. {
  29663. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  29664. midiNodeIds.set (bufferNum, nodeId);
  29665. }
  29666. else
  29667. {
  29668. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  29669. nodeIds.set (bufferNum, nodeId);
  29670. channels.set (bufferNum, outputIndex);
  29671. }
  29672. }
  29673. RenderingOpSequenceCalculator (const RenderingOpSequenceCalculator&);
  29674. RenderingOpSequenceCalculator& operator= (const RenderingOpSequenceCalculator&);
  29675. };
  29676. }
  29677. void AudioProcessorGraph::clearRenderingSequence()
  29678. {
  29679. const ScopedLock sl (renderLock);
  29680. for (int i = renderingOps.size(); --i >= 0;)
  29681. {
  29682. GraphRenderingOps::AudioGraphRenderingOp* const r
  29683. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29684. renderingOps.remove (i);
  29685. delete r;
  29686. }
  29687. }
  29688. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  29689. const uint32 possibleDestinationId,
  29690. const int recursionCheck) const
  29691. {
  29692. if (recursionCheck > 0)
  29693. {
  29694. for (int i = connections.size(); --i >= 0;)
  29695. {
  29696. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  29697. if (c->destNodeId == possibleDestinationId
  29698. && (c->sourceNodeId == possibleInputId
  29699. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  29700. return true;
  29701. }
  29702. }
  29703. return false;
  29704. }
  29705. void AudioProcessorGraph::buildRenderingSequence()
  29706. {
  29707. Array<void*> newRenderingOps;
  29708. int numRenderingBuffersNeeded = 2;
  29709. int numMidiBuffersNeeded = 1;
  29710. {
  29711. MessageManagerLock mml;
  29712. Array<void*> orderedNodes;
  29713. int i;
  29714. for (i = 0; i < nodes.size(); ++i)
  29715. {
  29716. Node* const node = nodes.getUnchecked(i);
  29717. node->prepare (getSampleRate(), getBlockSize(), this);
  29718. int j = 0;
  29719. for (; j < orderedNodes.size(); ++j)
  29720. if (isAnInputTo (node->id,
  29721. ((Node*) orderedNodes.getUnchecked (j))->id,
  29722. nodes.size() + 1))
  29723. break;
  29724. orderedNodes.insert (j, node);
  29725. }
  29726. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  29727. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  29728. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  29729. }
  29730. Array<void*> oldRenderingOps (renderingOps);
  29731. {
  29732. // swap over to the new rendering sequence..
  29733. const ScopedLock sl (renderLock);
  29734. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  29735. renderingBuffers.clear();
  29736. for (int i = midiBuffers.size(); --i >= 0;)
  29737. midiBuffers.getUnchecked(i)->clear();
  29738. while (midiBuffers.size() < numMidiBuffersNeeded)
  29739. midiBuffers.add (new MidiBuffer());
  29740. renderingOps = newRenderingOps;
  29741. }
  29742. for (int i = oldRenderingOps.size(); --i >= 0;)
  29743. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  29744. }
  29745. void AudioProcessorGraph::handleAsyncUpdate()
  29746. {
  29747. buildRenderingSequence();
  29748. }
  29749. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  29750. {
  29751. currentAudioInputBuffer = 0;
  29752. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  29753. currentMidiInputBuffer = 0;
  29754. currentMidiOutputBuffer.clear();
  29755. clearRenderingSequence();
  29756. buildRenderingSequence();
  29757. }
  29758. void AudioProcessorGraph::releaseResources()
  29759. {
  29760. for (int i = 0; i < nodes.size(); ++i)
  29761. nodes.getUnchecked(i)->unprepare();
  29762. renderingBuffers.setSize (1, 1);
  29763. midiBuffers.clear();
  29764. currentAudioInputBuffer = 0;
  29765. currentAudioOutputBuffer.setSize (1, 1);
  29766. currentMidiInputBuffer = 0;
  29767. currentMidiOutputBuffer.clear();
  29768. }
  29769. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  29770. {
  29771. const int numSamples = buffer.getNumSamples();
  29772. const ScopedLock sl (renderLock);
  29773. currentAudioInputBuffer = &buffer;
  29774. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  29775. currentAudioOutputBuffer.clear();
  29776. currentMidiInputBuffer = &midiMessages;
  29777. currentMidiOutputBuffer.clear();
  29778. int i;
  29779. for (i = 0; i < renderingOps.size(); ++i)
  29780. {
  29781. GraphRenderingOps::AudioGraphRenderingOp* const op
  29782. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29783. op->perform (renderingBuffers, midiBuffers, numSamples);
  29784. }
  29785. for (i = 0; i < buffer.getNumChannels(); ++i)
  29786. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  29787. midiMessages.clear();
  29788. midiMessages.addEvents (currentMidiOutputBuffer, 0, buffer.getNumSamples(), 0);
  29789. }
  29790. const String AudioProcessorGraph::getInputChannelName (int channelIndex) const
  29791. {
  29792. return "Input " + String (channelIndex + 1);
  29793. }
  29794. const String AudioProcessorGraph::getOutputChannelName (int channelIndex) const
  29795. {
  29796. return "Output " + String (channelIndex + 1);
  29797. }
  29798. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const { return true; }
  29799. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const { return true; }
  29800. bool AudioProcessorGraph::acceptsMidi() const { return true; }
  29801. bool AudioProcessorGraph::producesMidi() const { return true; }
  29802. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/) {}
  29803. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/) {}
  29804. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  29805. : type (type_),
  29806. graph (0)
  29807. {
  29808. }
  29809. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  29810. {
  29811. }
  29812. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  29813. {
  29814. switch (type)
  29815. {
  29816. case audioOutputNode: return "Audio Output";
  29817. case audioInputNode: return "Audio Input";
  29818. case midiOutputNode: return "Midi Output";
  29819. case midiInputNode: return "Midi Input";
  29820. default: break;
  29821. }
  29822. return String::empty;
  29823. }
  29824. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  29825. {
  29826. d.name = getName();
  29827. d.uid = d.name.hashCode();
  29828. d.category = "I/O devices";
  29829. d.pluginFormatName = "Internal";
  29830. d.manufacturerName = "Raw Material Software";
  29831. d.version = "1.0";
  29832. d.isInstrument = false;
  29833. d.numInputChannels = getNumInputChannels();
  29834. if (type == audioOutputNode && graph != 0)
  29835. d.numInputChannels = graph->getNumInputChannels();
  29836. d.numOutputChannels = getNumOutputChannels();
  29837. if (type == audioInputNode && graph != 0)
  29838. d.numOutputChannels = graph->getNumOutputChannels();
  29839. }
  29840. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  29841. {
  29842. jassert (graph != 0);
  29843. }
  29844. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  29845. {
  29846. }
  29847. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  29848. MidiBuffer& midiMessages)
  29849. {
  29850. jassert (graph != 0);
  29851. switch (type)
  29852. {
  29853. case audioOutputNode:
  29854. {
  29855. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  29856. buffer.getNumChannels()); --i >= 0;)
  29857. {
  29858. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  29859. }
  29860. break;
  29861. }
  29862. case audioInputNode:
  29863. {
  29864. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  29865. buffer.getNumChannels()); --i >= 0;)
  29866. {
  29867. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  29868. }
  29869. break;
  29870. }
  29871. case midiOutputNode:
  29872. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  29873. break;
  29874. case midiInputNode:
  29875. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  29876. break;
  29877. default:
  29878. break;
  29879. }
  29880. }
  29881. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  29882. {
  29883. return type == midiOutputNode;
  29884. }
  29885. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  29886. {
  29887. return type == midiInputNode;
  29888. }
  29889. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (int channelIndex) const
  29890. {
  29891. switch (type)
  29892. {
  29893. case audioOutputNode: return "Output " + String (channelIndex + 1);
  29894. case midiOutputNode: return "Midi Output";
  29895. default: break;
  29896. }
  29897. return String::empty;
  29898. }
  29899. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (int channelIndex) const
  29900. {
  29901. switch (type)
  29902. {
  29903. case audioInputNode: return "Input " + String (channelIndex + 1);
  29904. case midiInputNode: return "Midi Input";
  29905. default: break;
  29906. }
  29907. return String::empty;
  29908. }
  29909. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  29910. {
  29911. return type == audioInputNode || type == audioOutputNode;
  29912. }
  29913. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  29914. {
  29915. return isInputChannelStereoPair (index);
  29916. }
  29917. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const
  29918. {
  29919. return type == audioInputNode || type == midiInputNode;
  29920. }
  29921. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const
  29922. {
  29923. return type == audioOutputNode || type == midiOutputNode;
  29924. }
  29925. bool AudioProcessorGraph::AudioGraphIOProcessor::hasEditor() const { return false; }
  29926. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor() { return 0; }
  29927. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  29928. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  29929. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  29930. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  29931. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  29932. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  29933. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  29934. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  29935. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  29936. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  29937. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  29938. {
  29939. }
  29940. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  29941. {
  29942. }
  29943. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph)
  29944. {
  29945. graph = newGraph;
  29946. if (graph != 0)
  29947. {
  29948. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  29949. type == audioInputNode ? graph->getNumInputChannels() : 0,
  29950. getSampleRate(),
  29951. getBlockSize());
  29952. updateHostDisplay();
  29953. }
  29954. }
  29955. END_JUCE_NAMESPACE
  29956. /*** End of inlined file: juce_AudioProcessorGraph.cpp ***/
  29957. /*** Start of inlined file: juce_AudioProcessorPlayer.cpp ***/
  29958. BEGIN_JUCE_NAMESPACE
  29959. AudioProcessorPlayer::AudioProcessorPlayer()
  29960. : processor (0),
  29961. sampleRate (0),
  29962. blockSize (0),
  29963. isPrepared (false),
  29964. numInputChans (0),
  29965. numOutputChans (0),
  29966. tempBuffer (1, 1)
  29967. {
  29968. }
  29969. AudioProcessorPlayer::~AudioProcessorPlayer()
  29970. {
  29971. setProcessor (0);
  29972. }
  29973. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  29974. {
  29975. if (processor != processorToPlay)
  29976. {
  29977. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  29978. {
  29979. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  29980. sampleRate, blockSize);
  29981. processorToPlay->prepareToPlay (sampleRate, blockSize);
  29982. }
  29983. AudioProcessor* oldOne;
  29984. {
  29985. const ScopedLock sl (lock);
  29986. oldOne = isPrepared ? processor : 0;
  29987. processor = processorToPlay;
  29988. isPrepared = true;
  29989. }
  29990. if (oldOne != 0)
  29991. oldOne->releaseResources();
  29992. }
  29993. }
  29994. void AudioProcessorPlayer::audioDeviceIOCallback (const float** const inputChannelData,
  29995. const int numInputChannels,
  29996. float** const outputChannelData,
  29997. const int numOutputChannels,
  29998. const int numSamples)
  29999. {
  30000. // these should have been prepared by audioDeviceAboutToStart()...
  30001. jassert (sampleRate > 0 && blockSize > 0);
  30002. incomingMidi.clear();
  30003. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  30004. int i, totalNumChans = 0;
  30005. if (numInputChannels > numOutputChannels)
  30006. {
  30007. // if there aren't enough output channels for the number of
  30008. // inputs, we need to create some temporary extra ones (can't
  30009. // use the input data in case it gets written to)
  30010. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  30011. false, false, true);
  30012. for (i = 0; i < numOutputChannels; ++i)
  30013. {
  30014. channels[totalNumChans] = outputChannelData[i];
  30015. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30016. ++totalNumChans;
  30017. }
  30018. for (i = numOutputChannels; i < numInputChannels; ++i)
  30019. {
  30020. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  30021. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30022. ++totalNumChans;
  30023. }
  30024. }
  30025. else
  30026. {
  30027. for (i = 0; i < numInputChannels; ++i)
  30028. {
  30029. channels[totalNumChans] = outputChannelData[i];
  30030. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30031. ++totalNumChans;
  30032. }
  30033. for (i = numInputChannels; i < numOutputChannels; ++i)
  30034. {
  30035. channels[totalNumChans] = outputChannelData[i];
  30036. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  30037. ++totalNumChans;
  30038. }
  30039. }
  30040. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  30041. const ScopedLock sl (lock);
  30042. if (processor != 0)
  30043. {
  30044. const ScopedLock sl (processor->getCallbackLock());
  30045. if (processor->isSuspended())
  30046. {
  30047. for (i = 0; i < numOutputChannels; ++i)
  30048. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  30049. }
  30050. else
  30051. {
  30052. processor->processBlock (buffer, incomingMidi);
  30053. }
  30054. }
  30055. }
  30056. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  30057. {
  30058. const ScopedLock sl (lock);
  30059. sampleRate = device->getCurrentSampleRate();
  30060. blockSize = device->getCurrentBufferSizeSamples();
  30061. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  30062. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  30063. messageCollector.reset (sampleRate);
  30064. zeromem (channels, sizeof (channels));
  30065. if (processor != 0)
  30066. {
  30067. if (isPrepared)
  30068. processor->releaseResources();
  30069. AudioProcessor* const oldProcessor = processor;
  30070. setProcessor (0);
  30071. setProcessor (oldProcessor);
  30072. }
  30073. }
  30074. void AudioProcessorPlayer::audioDeviceStopped()
  30075. {
  30076. const ScopedLock sl (lock);
  30077. if (processor != 0 && isPrepared)
  30078. processor->releaseResources();
  30079. sampleRate = 0.0;
  30080. blockSize = 0;
  30081. isPrepared = false;
  30082. tempBuffer.setSize (1, 1);
  30083. }
  30084. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  30085. {
  30086. messageCollector.addMessageToQueue (message);
  30087. }
  30088. END_JUCE_NAMESPACE
  30089. /*** End of inlined file: juce_AudioProcessorPlayer.cpp ***/
  30090. /*** Start of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  30091. BEGIN_JUCE_NAMESPACE
  30092. class ProcessorParameterPropertyComp : public PropertyComponent,
  30093. public AudioProcessorListener,
  30094. public AsyncUpdater
  30095. {
  30096. public:
  30097. ProcessorParameterPropertyComp (const String& name, AudioProcessor& owner_, int index_)
  30098. : PropertyComponent (name),
  30099. owner (owner_),
  30100. index (index_),
  30101. slider (owner_, index_)
  30102. {
  30103. addAndMakeVisible (&slider);
  30104. owner_.addListener (this);
  30105. }
  30106. ~ProcessorParameterPropertyComp()
  30107. {
  30108. owner.removeListener (this);
  30109. }
  30110. void refresh()
  30111. {
  30112. slider.setValue (owner.getParameter (index), false);
  30113. }
  30114. void audioProcessorChanged (AudioProcessor*) {}
  30115. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  30116. {
  30117. if (parameterIndex == index)
  30118. triggerAsyncUpdate();
  30119. }
  30120. void handleAsyncUpdate()
  30121. {
  30122. refresh();
  30123. }
  30124. juce_UseDebuggingNewOperator
  30125. private:
  30126. class ParamSlider : public Slider
  30127. {
  30128. public:
  30129. ParamSlider (AudioProcessor& owner_, const int index_)
  30130. : Slider (String::empty),
  30131. owner (owner_),
  30132. index (index_)
  30133. {
  30134. setRange (0.0, 1.0, 0.0);
  30135. setSliderStyle (Slider::LinearBar);
  30136. setTextBoxIsEditable (false);
  30137. setScrollWheelEnabled (false);
  30138. }
  30139. ~ParamSlider()
  30140. {
  30141. }
  30142. void valueChanged()
  30143. {
  30144. const float newVal = (float) getValue();
  30145. if (owner.getParameter (index) != newVal)
  30146. owner.setParameter (index, newVal);
  30147. }
  30148. const String getTextFromValue (double /*value*/)
  30149. {
  30150. return owner.getParameterText (index);
  30151. }
  30152. juce_UseDebuggingNewOperator
  30153. private:
  30154. AudioProcessor& owner;
  30155. const int index;
  30156. ParamSlider (const ParamSlider&);
  30157. ParamSlider& operator= (const ParamSlider&);
  30158. };
  30159. AudioProcessor& owner;
  30160. const int index;
  30161. ParamSlider slider;
  30162. ProcessorParameterPropertyComp (const ProcessorParameterPropertyComp&);
  30163. ProcessorParameterPropertyComp& operator= (const ProcessorParameterPropertyComp&);
  30164. };
  30165. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner_)
  30166. : AudioProcessorEditor (owner_)
  30167. {
  30168. jassert (owner_ != 0);
  30169. setOpaque (true);
  30170. addAndMakeVisible (panel = new PropertyPanel());
  30171. Array <PropertyComponent*> params;
  30172. const int numParams = owner_->getNumParameters();
  30173. int totalHeight = 0;
  30174. for (int i = 0; i < numParams; ++i)
  30175. {
  30176. String name (owner_->getParameterName (i));
  30177. if (name.trim().isEmpty())
  30178. name = "Unnamed";
  30179. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, *owner_, i);
  30180. params.add (pc);
  30181. totalHeight += pc->getPreferredHeight();
  30182. }
  30183. panel->addProperties (params);
  30184. setSize (400, jlimit (25, 400, totalHeight));
  30185. }
  30186. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  30187. {
  30188. deleteAllChildren();
  30189. }
  30190. void GenericAudioProcessorEditor::paint (Graphics& g)
  30191. {
  30192. g.fillAll (Colours::white);
  30193. }
  30194. void GenericAudioProcessorEditor::resized()
  30195. {
  30196. panel->setSize (getWidth(), getHeight());
  30197. }
  30198. END_JUCE_NAMESPACE
  30199. /*** End of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  30200. /*** Start of inlined file: juce_Sampler.cpp ***/
  30201. BEGIN_JUCE_NAMESPACE
  30202. SamplerSound::SamplerSound (const String& name_,
  30203. AudioFormatReader& source,
  30204. const BigInteger& midiNotes_,
  30205. const int midiNoteForNormalPitch,
  30206. const double attackTimeSecs,
  30207. const double releaseTimeSecs,
  30208. const double maxSampleLengthSeconds)
  30209. : name (name_),
  30210. midiNotes (midiNotes_),
  30211. midiRootNote (midiNoteForNormalPitch)
  30212. {
  30213. sourceSampleRate = source.sampleRate;
  30214. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  30215. {
  30216. length = 0;
  30217. attackSamples = 0;
  30218. releaseSamples = 0;
  30219. }
  30220. else
  30221. {
  30222. length = jmin ((int) source.lengthInSamples,
  30223. (int) (maxSampleLengthSeconds * sourceSampleRate));
  30224. data = new AudioSampleBuffer (jmin (2, (int) source.numChannels), length + 4);
  30225. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  30226. attackSamples = roundToInt (attackTimeSecs * sourceSampleRate);
  30227. releaseSamples = roundToInt (releaseTimeSecs * sourceSampleRate);
  30228. }
  30229. }
  30230. SamplerSound::~SamplerSound()
  30231. {
  30232. }
  30233. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  30234. {
  30235. return midiNotes [midiNoteNumber];
  30236. }
  30237. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  30238. {
  30239. return true;
  30240. }
  30241. SamplerVoice::SamplerVoice()
  30242. : pitchRatio (0.0),
  30243. sourceSamplePosition (0.0),
  30244. lgain (0.0f),
  30245. rgain (0.0f),
  30246. isInAttack (false),
  30247. isInRelease (false)
  30248. {
  30249. }
  30250. SamplerVoice::~SamplerVoice()
  30251. {
  30252. }
  30253. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  30254. {
  30255. return dynamic_cast <const SamplerSound*> (sound) != 0;
  30256. }
  30257. void SamplerVoice::startNote (const int midiNoteNumber,
  30258. const float velocity,
  30259. SynthesiserSound* s,
  30260. const int /*currentPitchWheelPosition*/)
  30261. {
  30262. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  30263. jassert (sound != 0); // this object can only play SamplerSounds!
  30264. if (sound != 0)
  30265. {
  30266. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  30267. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  30268. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  30269. sourceSamplePosition = 0.0;
  30270. lgain = velocity;
  30271. rgain = velocity;
  30272. isInAttack = (sound->attackSamples > 0);
  30273. isInRelease = false;
  30274. if (isInAttack)
  30275. {
  30276. attackReleaseLevel = 0.0f;
  30277. attackDelta = (float) (pitchRatio / sound->attackSamples);
  30278. }
  30279. else
  30280. {
  30281. attackReleaseLevel = 1.0f;
  30282. attackDelta = 0.0f;
  30283. }
  30284. if (sound->releaseSamples > 0)
  30285. {
  30286. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  30287. }
  30288. else
  30289. {
  30290. releaseDelta = 0.0f;
  30291. }
  30292. }
  30293. }
  30294. void SamplerVoice::stopNote (const bool allowTailOff)
  30295. {
  30296. if (allowTailOff)
  30297. {
  30298. isInAttack = false;
  30299. isInRelease = true;
  30300. }
  30301. else
  30302. {
  30303. clearCurrentNote();
  30304. }
  30305. }
  30306. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  30307. {
  30308. }
  30309. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  30310. const int /*newValue*/)
  30311. {
  30312. }
  30313. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  30314. {
  30315. const SamplerSound* const playingSound = static_cast <SamplerSound*> (getCurrentlyPlayingSound().getObject());
  30316. if (playingSound != 0)
  30317. {
  30318. const float* const inL = playingSound->data->getSampleData (0, 0);
  30319. const float* const inR = playingSound->data->getNumChannels() > 1
  30320. ? playingSound->data->getSampleData (1, 0) : 0;
  30321. float* outL = outputBuffer.getSampleData (0, startSample);
  30322. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  30323. while (--numSamples >= 0)
  30324. {
  30325. const int pos = (int) sourceSamplePosition;
  30326. const float alpha = (float) (sourceSamplePosition - pos);
  30327. const float invAlpha = 1.0f - alpha;
  30328. // just using a very simple linear interpolation here..
  30329. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  30330. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  30331. : l;
  30332. l *= lgain;
  30333. r *= rgain;
  30334. if (isInAttack)
  30335. {
  30336. l *= attackReleaseLevel;
  30337. r *= attackReleaseLevel;
  30338. attackReleaseLevel += attackDelta;
  30339. if (attackReleaseLevel >= 1.0f)
  30340. {
  30341. attackReleaseLevel = 1.0f;
  30342. isInAttack = false;
  30343. }
  30344. }
  30345. else if (isInRelease)
  30346. {
  30347. l *= attackReleaseLevel;
  30348. r *= attackReleaseLevel;
  30349. attackReleaseLevel += releaseDelta;
  30350. if (attackReleaseLevel <= 0.0f)
  30351. {
  30352. stopNote (false);
  30353. break;
  30354. }
  30355. }
  30356. if (outR != 0)
  30357. {
  30358. *outL++ += l;
  30359. *outR++ += r;
  30360. }
  30361. else
  30362. {
  30363. *outL++ += (l + r) * 0.5f;
  30364. }
  30365. sourceSamplePosition += pitchRatio;
  30366. if (sourceSamplePosition > playingSound->length)
  30367. {
  30368. stopNote (false);
  30369. break;
  30370. }
  30371. }
  30372. }
  30373. }
  30374. END_JUCE_NAMESPACE
  30375. /*** End of inlined file: juce_Sampler.cpp ***/
  30376. /*** Start of inlined file: juce_Synthesiser.cpp ***/
  30377. BEGIN_JUCE_NAMESPACE
  30378. SynthesiserSound::SynthesiserSound()
  30379. {
  30380. }
  30381. SynthesiserSound::~SynthesiserSound()
  30382. {
  30383. }
  30384. SynthesiserVoice::SynthesiserVoice()
  30385. : currentSampleRate (44100.0),
  30386. currentlyPlayingNote (-1),
  30387. noteOnTime (0),
  30388. currentlyPlayingSound (0)
  30389. {
  30390. }
  30391. SynthesiserVoice::~SynthesiserVoice()
  30392. {
  30393. }
  30394. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  30395. {
  30396. return currentlyPlayingSound != 0
  30397. && currentlyPlayingSound->appliesToChannel (midiChannel);
  30398. }
  30399. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  30400. {
  30401. currentSampleRate = newRate;
  30402. }
  30403. void SynthesiserVoice::clearCurrentNote()
  30404. {
  30405. currentlyPlayingNote = -1;
  30406. currentlyPlayingSound = 0;
  30407. }
  30408. Synthesiser::Synthesiser()
  30409. : sampleRate (0),
  30410. lastNoteOnCounter (0),
  30411. shouldStealNotes (true)
  30412. {
  30413. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  30414. lastPitchWheelValues[i] = 0x2000;
  30415. }
  30416. Synthesiser::~Synthesiser()
  30417. {
  30418. }
  30419. SynthesiserVoice* Synthesiser::getVoice (const int index) const
  30420. {
  30421. const ScopedLock sl (lock);
  30422. return voices [index];
  30423. }
  30424. void Synthesiser::clearVoices()
  30425. {
  30426. const ScopedLock sl (lock);
  30427. voices.clear();
  30428. }
  30429. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  30430. {
  30431. const ScopedLock sl (lock);
  30432. voices.add (newVoice);
  30433. }
  30434. void Synthesiser::removeVoice (const int index)
  30435. {
  30436. const ScopedLock sl (lock);
  30437. voices.remove (index);
  30438. }
  30439. void Synthesiser::clearSounds()
  30440. {
  30441. const ScopedLock sl (lock);
  30442. sounds.clear();
  30443. }
  30444. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  30445. {
  30446. const ScopedLock sl (lock);
  30447. sounds.add (newSound);
  30448. }
  30449. void Synthesiser::removeSound (const int index)
  30450. {
  30451. const ScopedLock sl (lock);
  30452. sounds.remove (index);
  30453. }
  30454. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  30455. {
  30456. shouldStealNotes = shouldStealNotes_;
  30457. }
  30458. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  30459. {
  30460. if (sampleRate != newRate)
  30461. {
  30462. const ScopedLock sl (lock);
  30463. allNotesOff (0, false);
  30464. sampleRate = newRate;
  30465. for (int i = voices.size(); --i >= 0;)
  30466. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  30467. }
  30468. }
  30469. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  30470. const MidiBuffer& midiData,
  30471. int startSample,
  30472. int numSamples)
  30473. {
  30474. // must set the sample rate before using this!
  30475. jassert (sampleRate != 0);
  30476. const ScopedLock sl (lock);
  30477. MidiBuffer::Iterator midiIterator (midiData);
  30478. midiIterator.setNextSamplePosition (startSample);
  30479. MidiMessage m (0xf4, 0.0);
  30480. while (numSamples > 0)
  30481. {
  30482. int midiEventPos;
  30483. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  30484. && midiEventPos < startSample + numSamples;
  30485. const int numThisTime = useEvent ? midiEventPos - startSample
  30486. : numSamples;
  30487. if (numThisTime > 0)
  30488. {
  30489. for (int i = voices.size(); --i >= 0;)
  30490. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  30491. }
  30492. if (useEvent)
  30493. {
  30494. if (m.isNoteOn())
  30495. {
  30496. const int channel = m.getChannel();
  30497. noteOn (channel,
  30498. m.getNoteNumber(),
  30499. m.getFloatVelocity());
  30500. }
  30501. else if (m.isNoteOff())
  30502. {
  30503. noteOff (m.getChannel(),
  30504. m.getNoteNumber(),
  30505. true);
  30506. }
  30507. else if (m.isAllNotesOff() || m.isAllSoundOff())
  30508. {
  30509. allNotesOff (m.getChannel(), true);
  30510. }
  30511. else if (m.isPitchWheel())
  30512. {
  30513. const int channel = m.getChannel();
  30514. const int wheelPos = m.getPitchWheelValue();
  30515. lastPitchWheelValues [channel - 1] = wheelPos;
  30516. handlePitchWheel (channel, wheelPos);
  30517. }
  30518. else if (m.isController())
  30519. {
  30520. handleController (m.getChannel(),
  30521. m.getControllerNumber(),
  30522. m.getControllerValue());
  30523. }
  30524. }
  30525. startSample += numThisTime;
  30526. numSamples -= numThisTime;
  30527. }
  30528. }
  30529. void Synthesiser::noteOn (const int midiChannel,
  30530. const int midiNoteNumber,
  30531. const float velocity)
  30532. {
  30533. const ScopedLock sl (lock);
  30534. for (int i = sounds.size(); --i >= 0;)
  30535. {
  30536. SynthesiserSound* const sound = sounds.getUnchecked(i);
  30537. if (sound->appliesToNote (midiNoteNumber)
  30538. && sound->appliesToChannel (midiChannel))
  30539. {
  30540. startVoice (findFreeVoice (sound, shouldStealNotes),
  30541. sound, midiChannel, midiNoteNumber, velocity);
  30542. }
  30543. }
  30544. }
  30545. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  30546. SynthesiserSound* const sound,
  30547. const int midiChannel,
  30548. const int midiNoteNumber,
  30549. const float velocity)
  30550. {
  30551. if (voice != 0 && sound != 0)
  30552. {
  30553. if (voice->currentlyPlayingSound != 0)
  30554. voice->stopNote (false);
  30555. voice->startNote (midiNoteNumber,
  30556. velocity,
  30557. sound,
  30558. lastPitchWheelValues [midiChannel - 1]);
  30559. voice->currentlyPlayingNote = midiNoteNumber;
  30560. voice->noteOnTime = ++lastNoteOnCounter;
  30561. voice->currentlyPlayingSound = sound;
  30562. }
  30563. }
  30564. void Synthesiser::noteOff (const int midiChannel,
  30565. const int midiNoteNumber,
  30566. const bool allowTailOff)
  30567. {
  30568. const ScopedLock sl (lock);
  30569. for (int i = voices.size(); --i >= 0;)
  30570. {
  30571. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30572. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  30573. {
  30574. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  30575. if (sound != 0
  30576. && sound->appliesToNote (midiNoteNumber)
  30577. && sound->appliesToChannel (midiChannel))
  30578. {
  30579. voice->stopNote (allowTailOff);
  30580. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  30581. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  30582. }
  30583. }
  30584. }
  30585. }
  30586. void Synthesiser::allNotesOff (const int midiChannel,
  30587. const bool allowTailOff)
  30588. {
  30589. const ScopedLock sl (lock);
  30590. for (int i = voices.size(); --i >= 0;)
  30591. {
  30592. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30593. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30594. voice->stopNote (allowTailOff);
  30595. }
  30596. }
  30597. void Synthesiser::handlePitchWheel (const int midiChannel,
  30598. const int wheelValue)
  30599. {
  30600. const ScopedLock sl (lock);
  30601. for (int i = voices.size(); --i >= 0;)
  30602. {
  30603. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30604. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30605. {
  30606. voice->pitchWheelMoved (wheelValue);
  30607. }
  30608. }
  30609. }
  30610. void Synthesiser::handleController (const int midiChannel,
  30611. const int controllerNumber,
  30612. const int controllerValue)
  30613. {
  30614. const ScopedLock sl (lock);
  30615. for (int i = voices.size(); --i >= 0;)
  30616. {
  30617. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30618. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30619. voice->controllerMoved (controllerNumber, controllerValue);
  30620. }
  30621. }
  30622. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  30623. const bool stealIfNoneAvailable) const
  30624. {
  30625. const ScopedLock sl (lock);
  30626. for (int i = voices.size(); --i >= 0;)
  30627. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  30628. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  30629. return voices.getUnchecked (i);
  30630. if (stealIfNoneAvailable)
  30631. {
  30632. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  30633. SynthesiserVoice* oldest = 0;
  30634. for (int i = voices.size(); --i >= 0;)
  30635. {
  30636. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30637. if (voice->canPlaySound (soundToPlay)
  30638. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  30639. oldest = voice;
  30640. }
  30641. jassert (oldest != 0);
  30642. return oldest;
  30643. }
  30644. return 0;
  30645. }
  30646. END_JUCE_NAMESPACE
  30647. /*** End of inlined file: juce_Synthesiser.cpp ***/
  30648. /*** Start of inlined file: juce_ActionBroadcaster.cpp ***/
  30649. BEGIN_JUCE_NAMESPACE
  30650. ActionBroadcaster::ActionBroadcaster() throw()
  30651. {
  30652. // are you trying to create this object before or after juce has been intialised??
  30653. jassert (MessageManager::instance != 0);
  30654. }
  30655. ActionBroadcaster::~ActionBroadcaster()
  30656. {
  30657. // all event-based objects must be deleted BEFORE juce is shut down!
  30658. jassert (MessageManager::instance != 0);
  30659. }
  30660. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  30661. {
  30662. actionListenerList.addActionListener (listener);
  30663. }
  30664. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  30665. {
  30666. jassert (actionListenerList.isValidMessageListener());
  30667. if (actionListenerList.isValidMessageListener())
  30668. actionListenerList.removeActionListener (listener);
  30669. }
  30670. void ActionBroadcaster::removeAllActionListeners()
  30671. {
  30672. actionListenerList.removeAllActionListeners();
  30673. }
  30674. void ActionBroadcaster::sendActionMessage (const String& message) const
  30675. {
  30676. actionListenerList.sendActionMessage (message);
  30677. }
  30678. END_JUCE_NAMESPACE
  30679. /*** End of inlined file: juce_ActionBroadcaster.cpp ***/
  30680. /*** Start of inlined file: juce_ActionListenerList.cpp ***/
  30681. BEGIN_JUCE_NAMESPACE
  30682. // special message of our own with a string in it
  30683. class ActionMessage : public Message
  30684. {
  30685. public:
  30686. const String message;
  30687. ActionMessage (const String& messageText, void* const listener_) throw()
  30688. : message (messageText)
  30689. {
  30690. pointerParameter = listener_;
  30691. }
  30692. ~ActionMessage() throw()
  30693. {
  30694. }
  30695. private:
  30696. ActionMessage (const ActionMessage&);
  30697. ActionMessage& operator= (const ActionMessage&);
  30698. };
  30699. ActionListenerList::ActionListenerList()
  30700. {
  30701. }
  30702. ActionListenerList::~ActionListenerList()
  30703. {
  30704. }
  30705. void ActionListenerList::addActionListener (ActionListener* const listener)
  30706. {
  30707. const ScopedLock sl (actionListenerLock_);
  30708. jassert (listener != 0);
  30709. jassert (! actionListeners_.contains (listener)); // trying to add a listener to the list twice!
  30710. if (listener != 0)
  30711. actionListeners_.add (listener);
  30712. }
  30713. void ActionListenerList::removeActionListener (ActionListener* const listener)
  30714. {
  30715. const ScopedLock sl (actionListenerLock_);
  30716. jassert (actionListeners_.contains (listener)); // trying to remove a listener that isn't on the list!
  30717. actionListeners_.removeValue (listener);
  30718. }
  30719. void ActionListenerList::removeAllActionListeners()
  30720. {
  30721. const ScopedLock sl (actionListenerLock_);
  30722. actionListeners_.clear();
  30723. }
  30724. void ActionListenerList::sendActionMessage (const String& message) const
  30725. {
  30726. const ScopedLock sl (actionListenerLock_);
  30727. for (int i = actionListeners_.size(); --i >= 0;)
  30728. postMessage (new ActionMessage (message, static_cast <ActionListener*> (actionListeners_.getUnchecked(i))));
  30729. }
  30730. void ActionListenerList::handleMessage (const Message& message)
  30731. {
  30732. const ActionMessage& am = (const ActionMessage&) message;
  30733. if (actionListeners_.contains (am.pointerParameter))
  30734. static_cast <ActionListener*> (am.pointerParameter)->actionListenerCallback (am.message);
  30735. }
  30736. END_JUCE_NAMESPACE
  30737. /*** End of inlined file: juce_ActionListenerList.cpp ***/
  30738. /*** Start of inlined file: juce_AsyncUpdater.cpp ***/
  30739. BEGIN_JUCE_NAMESPACE
  30740. AsyncUpdater::AsyncUpdater() throw()
  30741. : asyncMessagePending (false)
  30742. {
  30743. internalAsyncHandler.owner = this;
  30744. }
  30745. AsyncUpdater::~AsyncUpdater()
  30746. {
  30747. }
  30748. void AsyncUpdater::triggerAsyncUpdate()
  30749. {
  30750. if (! asyncMessagePending)
  30751. {
  30752. asyncMessagePending = true;
  30753. internalAsyncHandler.postMessage (new Message());
  30754. }
  30755. }
  30756. void AsyncUpdater::cancelPendingUpdate() throw()
  30757. {
  30758. asyncMessagePending = false;
  30759. }
  30760. void AsyncUpdater::handleUpdateNowIfNeeded()
  30761. {
  30762. if (asyncMessagePending)
  30763. {
  30764. asyncMessagePending = false;
  30765. handleAsyncUpdate();
  30766. }
  30767. }
  30768. void AsyncUpdater::AsyncUpdaterInternal::handleMessage (const Message&)
  30769. {
  30770. owner->handleUpdateNowIfNeeded();
  30771. }
  30772. END_JUCE_NAMESPACE
  30773. /*** End of inlined file: juce_AsyncUpdater.cpp ***/
  30774. /*** Start of inlined file: juce_ChangeBroadcaster.cpp ***/
  30775. BEGIN_JUCE_NAMESPACE
  30776. ChangeBroadcaster::ChangeBroadcaster() throw()
  30777. {
  30778. // are you trying to create this object before or after juce has been intialised??
  30779. jassert (MessageManager::instance != 0);
  30780. }
  30781. ChangeBroadcaster::~ChangeBroadcaster()
  30782. {
  30783. // all event-based objects must be deleted BEFORE juce is shut down!
  30784. jassert (MessageManager::instance != 0);
  30785. }
  30786. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener)
  30787. {
  30788. changeListenerList.addChangeListener (listener);
  30789. }
  30790. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener)
  30791. {
  30792. jassert (changeListenerList.isValidMessageListener());
  30793. if (changeListenerList.isValidMessageListener())
  30794. changeListenerList.removeChangeListener (listener);
  30795. }
  30796. void ChangeBroadcaster::removeAllChangeListeners()
  30797. {
  30798. changeListenerList.removeAllChangeListeners();
  30799. }
  30800. void ChangeBroadcaster::sendChangeMessage (void* objectThatHasChanged)
  30801. {
  30802. changeListenerList.sendChangeMessage (objectThatHasChanged);
  30803. }
  30804. void ChangeBroadcaster::sendSynchronousChangeMessage (void* objectThatHasChanged)
  30805. {
  30806. changeListenerList.sendSynchronousChangeMessage (objectThatHasChanged);
  30807. }
  30808. void ChangeBroadcaster::dispatchPendingMessages()
  30809. {
  30810. changeListenerList.dispatchPendingMessages();
  30811. }
  30812. END_JUCE_NAMESPACE
  30813. /*** End of inlined file: juce_ChangeBroadcaster.cpp ***/
  30814. /*** Start of inlined file: juce_ChangeListenerList.cpp ***/
  30815. BEGIN_JUCE_NAMESPACE
  30816. ChangeListenerList::ChangeListenerList()
  30817. : lastChangedObject (0),
  30818. messagePending (false)
  30819. {
  30820. }
  30821. ChangeListenerList::~ChangeListenerList()
  30822. {
  30823. }
  30824. void ChangeListenerList::addChangeListener (ChangeListener* const listener)
  30825. {
  30826. const ScopedLock sl (lock);
  30827. jassert (listener != 0);
  30828. if (listener != 0)
  30829. listeners.add (listener);
  30830. }
  30831. void ChangeListenerList::removeChangeListener (ChangeListener* const listener)
  30832. {
  30833. const ScopedLock sl (lock);
  30834. listeners.removeValue (listener);
  30835. }
  30836. void ChangeListenerList::removeAllChangeListeners()
  30837. {
  30838. const ScopedLock sl (lock);
  30839. listeners.clear();
  30840. }
  30841. void ChangeListenerList::sendChangeMessage (void* const objectThatHasChanged)
  30842. {
  30843. const ScopedLock sl (lock);
  30844. if ((! messagePending) && (listeners.size() > 0))
  30845. {
  30846. lastChangedObject = objectThatHasChanged;
  30847. postMessage (new Message (0, 0, 0, objectThatHasChanged));
  30848. messagePending = true;
  30849. }
  30850. }
  30851. void ChangeListenerList::handleMessage (const Message& message)
  30852. {
  30853. sendSynchronousChangeMessage (message.pointerParameter);
  30854. }
  30855. void ChangeListenerList::sendSynchronousChangeMessage (void* const objectThatHasChanged)
  30856. {
  30857. const ScopedLock sl (lock);
  30858. messagePending = false;
  30859. for (int i = listeners.size(); --i >= 0;)
  30860. {
  30861. ChangeListener* const l = static_cast <ChangeListener*> (listeners.getUnchecked (i));
  30862. {
  30863. const ScopedUnlock tempUnlocker (lock);
  30864. l->changeListenerCallback (objectThatHasChanged);
  30865. }
  30866. i = jmin (i, listeners.size());
  30867. }
  30868. }
  30869. void ChangeListenerList::dispatchPendingMessages()
  30870. {
  30871. if (messagePending)
  30872. sendSynchronousChangeMessage (lastChangedObject);
  30873. }
  30874. END_JUCE_NAMESPACE
  30875. /*** End of inlined file: juce_ChangeListenerList.cpp ***/
  30876. /*** Start of inlined file: juce_InterprocessConnection.cpp ***/
  30877. BEGIN_JUCE_NAMESPACE
  30878. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  30879. const uint32 magicMessageHeaderNumber)
  30880. : Thread ("Juce IPC connection"),
  30881. callbackConnectionState (false),
  30882. useMessageThread (callbacksOnMessageThread),
  30883. magicMessageHeader (magicMessageHeaderNumber),
  30884. pipeReceiveMessageTimeout (-1)
  30885. {
  30886. }
  30887. InterprocessConnection::~InterprocessConnection()
  30888. {
  30889. callbackConnectionState = false;
  30890. disconnect();
  30891. }
  30892. bool InterprocessConnection::connectToSocket (const String& hostName,
  30893. const int portNumber,
  30894. const int timeOutMillisecs)
  30895. {
  30896. disconnect();
  30897. const ScopedLock sl (pipeAndSocketLock);
  30898. socket = new StreamingSocket();
  30899. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  30900. {
  30901. connectionMadeInt();
  30902. startThread();
  30903. return true;
  30904. }
  30905. else
  30906. {
  30907. socket = 0;
  30908. return false;
  30909. }
  30910. }
  30911. bool InterprocessConnection::connectToPipe (const String& pipeName,
  30912. const int pipeReceiveMessageTimeoutMs)
  30913. {
  30914. disconnect();
  30915. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30916. if (newPipe->openExisting (pipeName))
  30917. {
  30918. const ScopedLock sl (pipeAndSocketLock);
  30919. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30920. initialiseWithPipe (newPipe.release());
  30921. return true;
  30922. }
  30923. return false;
  30924. }
  30925. bool InterprocessConnection::createPipe (const String& pipeName,
  30926. const int pipeReceiveMessageTimeoutMs)
  30927. {
  30928. disconnect();
  30929. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  30930. if (newPipe->createNewPipe (pipeName))
  30931. {
  30932. const ScopedLock sl (pipeAndSocketLock);
  30933. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  30934. initialiseWithPipe (newPipe.release());
  30935. return true;
  30936. }
  30937. return false;
  30938. }
  30939. void InterprocessConnection::disconnect()
  30940. {
  30941. if (socket != 0)
  30942. socket->close();
  30943. if (pipe != 0)
  30944. {
  30945. pipe->cancelPendingReads();
  30946. pipe->close();
  30947. }
  30948. stopThread (4000);
  30949. {
  30950. const ScopedLock sl (pipeAndSocketLock);
  30951. socket = 0;
  30952. pipe = 0;
  30953. }
  30954. connectionLostInt();
  30955. }
  30956. bool InterprocessConnection::isConnected() const
  30957. {
  30958. const ScopedLock sl (pipeAndSocketLock);
  30959. return ((socket != 0 && socket->isConnected())
  30960. || (pipe != 0 && pipe->isOpen()))
  30961. && isThreadRunning();
  30962. }
  30963. const String InterprocessConnection::getConnectedHostName() const
  30964. {
  30965. if (pipe != 0)
  30966. {
  30967. return "localhost";
  30968. }
  30969. else if (socket != 0)
  30970. {
  30971. if (! socket->isLocal())
  30972. return socket->getHostName();
  30973. return "localhost";
  30974. }
  30975. return String::empty;
  30976. }
  30977. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  30978. {
  30979. uint32 messageHeader[2];
  30980. messageHeader [0] = ByteOrder::swapIfBigEndian (magicMessageHeader);
  30981. messageHeader [1] = ByteOrder::swapIfBigEndian ((uint32) message.getSize());
  30982. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  30983. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  30984. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  30985. size_t bytesWritten = 0;
  30986. const ScopedLock sl (pipeAndSocketLock);
  30987. if (socket != 0)
  30988. {
  30989. bytesWritten = socket->write (messageData.getData(), (int) messageData.getSize());
  30990. }
  30991. else if (pipe != 0)
  30992. {
  30993. bytesWritten = pipe->write (messageData.getData(), (int) messageData.getSize());
  30994. }
  30995. if (bytesWritten < 0)
  30996. {
  30997. // error..
  30998. return false;
  30999. }
  31000. return (bytesWritten == messageData.getSize());
  31001. }
  31002. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  31003. {
  31004. jassert (socket == 0);
  31005. socket = socket_;
  31006. connectionMadeInt();
  31007. startThread();
  31008. }
  31009. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  31010. {
  31011. jassert (pipe == 0);
  31012. pipe = pipe_;
  31013. connectionMadeInt();
  31014. startThread();
  31015. }
  31016. const int messageMagicNumber = 0xb734128b;
  31017. void InterprocessConnection::handleMessage (const Message& message)
  31018. {
  31019. if (message.intParameter1 == messageMagicNumber)
  31020. {
  31021. switch (message.intParameter2)
  31022. {
  31023. case 0:
  31024. {
  31025. ScopedPointer <MemoryBlock> data (static_cast <MemoryBlock*> (message.pointerParameter));
  31026. messageReceived (*data);
  31027. break;
  31028. }
  31029. case 1:
  31030. connectionMade();
  31031. break;
  31032. case 2:
  31033. connectionLost();
  31034. break;
  31035. }
  31036. }
  31037. }
  31038. void InterprocessConnection::connectionMadeInt()
  31039. {
  31040. if (! callbackConnectionState)
  31041. {
  31042. callbackConnectionState = true;
  31043. if (useMessageThread)
  31044. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  31045. else
  31046. connectionMade();
  31047. }
  31048. }
  31049. void InterprocessConnection::connectionLostInt()
  31050. {
  31051. if (callbackConnectionState)
  31052. {
  31053. callbackConnectionState = false;
  31054. if (useMessageThread)
  31055. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  31056. else
  31057. connectionLost();
  31058. }
  31059. }
  31060. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  31061. {
  31062. jassert (callbackConnectionState);
  31063. if (useMessageThread)
  31064. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  31065. else
  31066. messageReceived (data);
  31067. }
  31068. bool InterprocessConnection::readNextMessageInt()
  31069. {
  31070. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  31071. uint32 messageHeader[2];
  31072. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader), true)
  31073. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  31074. if (bytes == sizeof (messageHeader)
  31075. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  31076. {
  31077. int bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  31078. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  31079. {
  31080. MemoryBlock messageData (bytesInMessage, true);
  31081. int bytesRead = 0;
  31082. while (bytesInMessage > 0)
  31083. {
  31084. if (threadShouldExit())
  31085. return false;
  31086. const int numThisTime = jmin (bytesInMessage, 65536);
  31087. const int bytesIn = (socket != 0) ? socket->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, true)
  31088. : pipe->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, pipeReceiveMessageTimeout);
  31089. if (bytesIn <= 0)
  31090. break;
  31091. bytesRead += bytesIn;
  31092. bytesInMessage -= bytesIn;
  31093. }
  31094. if (bytesRead >= 0)
  31095. deliverDataInt (messageData);
  31096. }
  31097. }
  31098. else if (bytes < 0)
  31099. {
  31100. {
  31101. const ScopedLock sl (pipeAndSocketLock);
  31102. socket = 0;
  31103. }
  31104. connectionLostInt();
  31105. return false;
  31106. }
  31107. return true;
  31108. }
  31109. void InterprocessConnection::run()
  31110. {
  31111. while (! threadShouldExit())
  31112. {
  31113. if (socket != 0)
  31114. {
  31115. const int ready = socket->waitUntilReady (true, 0);
  31116. if (ready < 0)
  31117. {
  31118. {
  31119. const ScopedLock sl (pipeAndSocketLock);
  31120. socket = 0;
  31121. }
  31122. connectionLostInt();
  31123. break;
  31124. }
  31125. else if (ready > 0)
  31126. {
  31127. if (! readNextMessageInt())
  31128. break;
  31129. }
  31130. else
  31131. {
  31132. Thread::sleep (2);
  31133. }
  31134. }
  31135. else if (pipe != 0)
  31136. {
  31137. if (! pipe->isOpen())
  31138. {
  31139. {
  31140. const ScopedLock sl (pipeAndSocketLock);
  31141. pipe = 0;
  31142. }
  31143. connectionLostInt();
  31144. break;
  31145. }
  31146. else
  31147. {
  31148. if (! readNextMessageInt())
  31149. break;
  31150. }
  31151. }
  31152. else
  31153. {
  31154. break;
  31155. }
  31156. }
  31157. }
  31158. END_JUCE_NAMESPACE
  31159. /*** End of inlined file: juce_InterprocessConnection.cpp ***/
  31160. /*** Start of inlined file: juce_InterprocessConnectionServer.cpp ***/
  31161. BEGIN_JUCE_NAMESPACE
  31162. InterprocessConnectionServer::InterprocessConnectionServer()
  31163. : Thread ("Juce IPC server")
  31164. {
  31165. }
  31166. InterprocessConnectionServer::~InterprocessConnectionServer()
  31167. {
  31168. stop();
  31169. }
  31170. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  31171. {
  31172. stop();
  31173. socket = new StreamingSocket();
  31174. if (socket->createListener (portNumber))
  31175. {
  31176. startThread();
  31177. return true;
  31178. }
  31179. socket = 0;
  31180. return false;
  31181. }
  31182. void InterprocessConnectionServer::stop()
  31183. {
  31184. signalThreadShouldExit();
  31185. if (socket != 0)
  31186. socket->close();
  31187. stopThread (4000);
  31188. socket = 0;
  31189. }
  31190. void InterprocessConnectionServer::run()
  31191. {
  31192. while ((! threadShouldExit()) && socket != 0)
  31193. {
  31194. ScopedPointer <StreamingSocket> clientSocket (socket->waitForNextConnection());
  31195. if (clientSocket != 0)
  31196. {
  31197. InterprocessConnection* newConnection = createConnectionObject();
  31198. if (newConnection != 0)
  31199. newConnection->initialiseWithSocket (clientSocket.release());
  31200. }
  31201. }
  31202. }
  31203. END_JUCE_NAMESPACE
  31204. /*** End of inlined file: juce_InterprocessConnectionServer.cpp ***/
  31205. /*** Start of inlined file: juce_Message.cpp ***/
  31206. BEGIN_JUCE_NAMESPACE
  31207. Message::Message() throw()
  31208. : intParameter1 (0),
  31209. intParameter2 (0),
  31210. intParameter3 (0),
  31211. pointerParameter (0)
  31212. {
  31213. }
  31214. Message::Message (const int intParameter1_,
  31215. const int intParameter2_,
  31216. const int intParameter3_,
  31217. void* const pointerParameter_) throw()
  31218. : intParameter1 (intParameter1_),
  31219. intParameter2 (intParameter2_),
  31220. intParameter3 (intParameter3_),
  31221. pointerParameter (pointerParameter_)
  31222. {
  31223. }
  31224. Message::~Message() throw()
  31225. {
  31226. }
  31227. END_JUCE_NAMESPACE
  31228. /*** End of inlined file: juce_Message.cpp ***/
  31229. /*** Start of inlined file: juce_MessageListener.cpp ***/
  31230. BEGIN_JUCE_NAMESPACE
  31231. MessageListener::MessageListener() throw()
  31232. {
  31233. // are you trying to create a messagelistener before or after juce has been intialised??
  31234. jassert (MessageManager::instance != 0);
  31235. if (MessageManager::instance != 0)
  31236. MessageManager::instance->messageListeners.add (this);
  31237. }
  31238. MessageListener::~MessageListener()
  31239. {
  31240. if (MessageManager::instance != 0)
  31241. MessageManager::instance->messageListeners.removeValue (this);
  31242. }
  31243. void MessageListener::postMessage (Message* const message) const throw()
  31244. {
  31245. message->messageRecipient = const_cast <MessageListener*> (this);
  31246. if (MessageManager::instance == 0)
  31247. MessageManager::getInstance();
  31248. MessageManager::instance->postMessageToQueue (message);
  31249. }
  31250. bool MessageListener::isValidMessageListener() const throw()
  31251. {
  31252. return (MessageManager::instance != 0)
  31253. && MessageManager::instance->messageListeners.contains (this);
  31254. }
  31255. END_JUCE_NAMESPACE
  31256. /*** End of inlined file: juce_MessageListener.cpp ***/
  31257. /*** Start of inlined file: juce_MessageManager.cpp ***/
  31258. BEGIN_JUCE_NAMESPACE
  31259. // platform-specific functions..
  31260. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  31261. bool juce_postMessageToSystemQueue (Message* message);
  31262. MessageManager* MessageManager::instance = 0;
  31263. static const int quitMessageId = 0xfffff321;
  31264. MessageManager::MessageManager() throw()
  31265. : quitMessagePosted (false),
  31266. quitMessageReceived (false),
  31267. threadWithLock (0)
  31268. {
  31269. messageThreadId = Thread::getCurrentThreadId();
  31270. }
  31271. MessageManager::~MessageManager() throw()
  31272. {
  31273. broadcastListeners = 0;
  31274. doPlatformSpecificShutdown();
  31275. // If you hit this assertion, then you've probably leaked a Component or some other
  31276. // kind of MessageListener object...
  31277. jassert (messageListeners.size() == 0);
  31278. jassert (instance == this);
  31279. instance = 0; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  31280. }
  31281. MessageManager* MessageManager::getInstance() throw()
  31282. {
  31283. if (instance == 0)
  31284. {
  31285. instance = new MessageManager();
  31286. doPlatformSpecificInitialisation();
  31287. }
  31288. return instance;
  31289. }
  31290. void MessageManager::postMessageToQueue (Message* const message)
  31291. {
  31292. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  31293. delete message;
  31294. }
  31295. CallbackMessage::CallbackMessage() throw() {}
  31296. CallbackMessage::~CallbackMessage() throw() {}
  31297. void CallbackMessage::post()
  31298. {
  31299. if (MessageManager::instance != 0)
  31300. MessageManager::instance->postCallbackMessage (this);
  31301. }
  31302. void MessageManager::postCallbackMessage (Message* const message)
  31303. {
  31304. message->messageRecipient = 0;
  31305. postMessageToQueue (message);
  31306. }
  31307. // not for public use..
  31308. void MessageManager::deliverMessage (Message* const message)
  31309. {
  31310. const ScopedPointer <Message> messageDeleter (message);
  31311. MessageListener* const recipient = message->messageRecipient;
  31312. JUCE_TRY
  31313. {
  31314. if (messageListeners.contains (recipient))
  31315. {
  31316. recipient->handleMessage (*message);
  31317. }
  31318. else if (recipient == 0)
  31319. {
  31320. if (message->intParameter1 == quitMessageId)
  31321. {
  31322. quitMessageReceived = true;
  31323. }
  31324. else
  31325. {
  31326. CallbackMessage* const cm = dynamic_cast <CallbackMessage*> (message);
  31327. if (cm != 0)
  31328. cm->messageCallback();
  31329. }
  31330. }
  31331. }
  31332. JUCE_CATCH_EXCEPTION
  31333. }
  31334. #if ! (JUCE_MAC || JUCE_IOS)
  31335. void MessageManager::runDispatchLoop()
  31336. {
  31337. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31338. runDispatchLoopUntil (-1);
  31339. }
  31340. void MessageManager::stopDispatchLoop()
  31341. {
  31342. Message* const m = new Message (quitMessageId, 0, 0, 0);
  31343. m->messageRecipient = 0;
  31344. postMessageToQueue (m);
  31345. quitMessagePosted = true;
  31346. }
  31347. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  31348. {
  31349. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31350. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  31351. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  31352. && ! quitMessageReceived)
  31353. {
  31354. JUCE_TRY
  31355. {
  31356. if (! juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  31357. {
  31358. const int msToWait = (int) (endTime - Time::currentTimeMillis());
  31359. if (msToWait > 0)
  31360. Thread::sleep (jmin (5, msToWait));
  31361. }
  31362. }
  31363. JUCE_CATCH_EXCEPTION
  31364. }
  31365. return ! quitMessageReceived;
  31366. }
  31367. #endif
  31368. void MessageManager::deliverBroadcastMessage (const String& value)
  31369. {
  31370. if (broadcastListeners != 0)
  31371. broadcastListeners->sendActionMessage (value);
  31372. }
  31373. void MessageManager::registerBroadcastListener (ActionListener* const listener)
  31374. {
  31375. if (broadcastListeners == 0)
  31376. broadcastListeners = new ActionListenerList();
  31377. broadcastListeners->addActionListener (listener);
  31378. }
  31379. void MessageManager::deregisterBroadcastListener (ActionListener* const listener)
  31380. {
  31381. if (broadcastListeners != 0)
  31382. broadcastListeners->removeActionListener (listener);
  31383. }
  31384. bool MessageManager::isThisTheMessageThread() const throw()
  31385. {
  31386. return Thread::getCurrentThreadId() == messageThreadId;
  31387. }
  31388. void MessageManager::setCurrentThreadAsMessageThread()
  31389. {
  31390. if (messageThreadId != Thread::getCurrentThreadId())
  31391. {
  31392. messageThreadId = Thread::getCurrentThreadId();
  31393. // This is needed on windows to make sure the message window is created by this thread
  31394. doPlatformSpecificShutdown();
  31395. doPlatformSpecificInitialisation();
  31396. }
  31397. }
  31398. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  31399. {
  31400. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  31401. return thisThread == messageThreadId || thisThread == threadWithLock;
  31402. }
  31403. /* The only safe way to lock the message thread while another thread does
  31404. some work is by posting a special message, whose purpose is to tie up the event
  31405. loop until the other thread has finished its business.
  31406. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  31407. get locked before making an event callback, because if the same OS lock gets indirectly
  31408. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  31409. in Cocoa).
  31410. */
  31411. class MessageManagerLock::SharedEvents : public ReferenceCountedObject
  31412. {
  31413. public:
  31414. SharedEvents() {}
  31415. ~SharedEvents() {}
  31416. /* This class just holds a couple of events to communicate between the BlockingMessage
  31417. and the MessageManagerLock. Because both of these objects may be deleted at any time,
  31418. this shared data must be kept in a separate, ref-counted container. */
  31419. WaitableEvent lockedEvent, releaseEvent;
  31420. private:
  31421. SharedEvents (const SharedEvents&);
  31422. SharedEvents& operator= (const SharedEvents&);
  31423. };
  31424. class MessageManagerLock::BlockingMessage : public CallbackMessage
  31425. {
  31426. public:
  31427. BlockingMessage (MessageManagerLock::SharedEvents* const events_) : events (events_) {}
  31428. ~BlockingMessage() throw() {}
  31429. void messageCallback()
  31430. {
  31431. events->lockedEvent.signal();
  31432. events->releaseEvent.wait();
  31433. }
  31434. juce_UseDebuggingNewOperator
  31435. private:
  31436. ReferenceCountedObjectPtr <MessageManagerLock::SharedEvents> events;
  31437. BlockingMessage (const BlockingMessage&);
  31438. BlockingMessage& operator= (const BlockingMessage&);
  31439. };
  31440. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck)
  31441. : sharedEvents (0),
  31442. locked (false)
  31443. {
  31444. init (threadToCheck, 0);
  31445. }
  31446. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal)
  31447. : sharedEvents (0),
  31448. locked (false)
  31449. {
  31450. init (0, jobToCheckForExitSignal);
  31451. }
  31452. void MessageManagerLock::init (Thread* const threadToCheck, ThreadPoolJob* const job)
  31453. {
  31454. if (MessageManager::instance != 0)
  31455. {
  31456. if (MessageManager::instance->currentThreadHasLockedMessageManager())
  31457. {
  31458. locked = true; // either we're on the message thread, or this is a re-entrant call.
  31459. }
  31460. else
  31461. {
  31462. if (threadToCheck == 0 && job == 0)
  31463. {
  31464. MessageManager::instance->lockingLock.enter();
  31465. }
  31466. else
  31467. {
  31468. while (! MessageManager::instance->lockingLock.tryEnter())
  31469. {
  31470. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31471. || (job != 0 && job->shouldExit()))
  31472. return;
  31473. Thread::sleep (1);
  31474. }
  31475. }
  31476. sharedEvents = new SharedEvents();
  31477. sharedEvents->incReferenceCount();
  31478. (new BlockingMessage (sharedEvents))->post();
  31479. while (! sharedEvents->lockedEvent.wait (50))
  31480. {
  31481. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31482. || (job != 0 && job->shouldExit()))
  31483. {
  31484. sharedEvents->releaseEvent.signal();
  31485. sharedEvents->decReferenceCount();
  31486. sharedEvents = 0;
  31487. MessageManager::instance->lockingLock.exit();
  31488. return;
  31489. }
  31490. }
  31491. jassert (MessageManager::instance->threadWithLock == 0);
  31492. MessageManager::instance->threadWithLock = Thread::getCurrentThreadId();
  31493. locked = true;
  31494. }
  31495. }
  31496. }
  31497. MessageManagerLock::~MessageManagerLock() throw()
  31498. {
  31499. if (sharedEvents != 0)
  31500. {
  31501. jassert (MessageManager::instance == 0 || MessageManager::instance->currentThreadHasLockedMessageManager());
  31502. sharedEvents->releaseEvent.signal();
  31503. sharedEvents->decReferenceCount();
  31504. if (MessageManager::instance != 0)
  31505. {
  31506. MessageManager::instance->threadWithLock = 0;
  31507. MessageManager::instance->lockingLock.exit();
  31508. }
  31509. }
  31510. }
  31511. END_JUCE_NAMESPACE
  31512. /*** End of inlined file: juce_MessageManager.cpp ***/
  31513. /*** Start of inlined file: juce_MultiTimer.cpp ***/
  31514. BEGIN_JUCE_NAMESPACE
  31515. class MultiTimer::MultiTimerCallback : public Timer
  31516. {
  31517. public:
  31518. MultiTimerCallback (const int timerId_, MultiTimer& owner_)
  31519. : timerId (timerId_),
  31520. owner (owner_)
  31521. {
  31522. }
  31523. ~MultiTimerCallback()
  31524. {
  31525. }
  31526. void timerCallback()
  31527. {
  31528. owner.timerCallback (timerId);
  31529. }
  31530. const int timerId;
  31531. private:
  31532. MultiTimer& owner;
  31533. };
  31534. MultiTimer::MultiTimer() throw()
  31535. {
  31536. }
  31537. MultiTimer::MultiTimer (const MultiTimer&) throw()
  31538. {
  31539. }
  31540. MultiTimer::~MultiTimer()
  31541. {
  31542. const ScopedLock sl (timerListLock);
  31543. timers.clear();
  31544. }
  31545. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  31546. {
  31547. const ScopedLock sl (timerListLock);
  31548. for (int i = timers.size(); --i >= 0;)
  31549. {
  31550. MultiTimerCallback* const t = timers.getUnchecked(i);
  31551. if (t->timerId == timerId)
  31552. {
  31553. t->startTimer (intervalInMilliseconds);
  31554. return;
  31555. }
  31556. }
  31557. MultiTimerCallback* const newTimer = new MultiTimerCallback (timerId, *this);
  31558. timers.add (newTimer);
  31559. newTimer->startTimer (intervalInMilliseconds);
  31560. }
  31561. void MultiTimer::stopTimer (const int timerId) throw()
  31562. {
  31563. const ScopedLock sl (timerListLock);
  31564. for (int i = timers.size(); --i >= 0;)
  31565. {
  31566. MultiTimerCallback* const t = timers.getUnchecked(i);
  31567. if (t->timerId == timerId)
  31568. t->stopTimer();
  31569. }
  31570. }
  31571. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  31572. {
  31573. const ScopedLock sl (timerListLock);
  31574. for (int i = timers.size(); --i >= 0;)
  31575. {
  31576. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31577. if (t->timerId == timerId)
  31578. return t->isTimerRunning();
  31579. }
  31580. return false;
  31581. }
  31582. int MultiTimer::getTimerInterval (const int timerId) const throw()
  31583. {
  31584. const ScopedLock sl (timerListLock);
  31585. for (int i = timers.size(); --i >= 0;)
  31586. {
  31587. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31588. if (t->timerId == timerId)
  31589. return t->getTimerInterval();
  31590. }
  31591. return 0;
  31592. }
  31593. END_JUCE_NAMESPACE
  31594. /*** End of inlined file: juce_MultiTimer.cpp ***/
  31595. /*** Start of inlined file: juce_Timer.cpp ***/
  31596. BEGIN_JUCE_NAMESPACE
  31597. class InternalTimerThread : private Thread,
  31598. private MessageListener,
  31599. private DeletedAtShutdown,
  31600. private AsyncUpdater
  31601. {
  31602. public:
  31603. InternalTimerThread()
  31604. : Thread ("Juce Timer"),
  31605. firstTimer (0),
  31606. callbackNeeded (0)
  31607. {
  31608. triggerAsyncUpdate();
  31609. }
  31610. ~InternalTimerThread() throw()
  31611. {
  31612. stopThread (4000);
  31613. jassert (instance == this || instance == 0);
  31614. if (instance == this)
  31615. instance = 0;
  31616. }
  31617. void run()
  31618. {
  31619. uint32 lastTime = Time::getMillisecondCounter();
  31620. while (! threadShouldExit())
  31621. {
  31622. const uint32 now = Time::getMillisecondCounter();
  31623. if (now <= lastTime)
  31624. {
  31625. wait (2);
  31626. continue;
  31627. }
  31628. const int elapsed = now - lastTime;
  31629. lastTime = now;
  31630. int timeUntilFirstTimer = 1000;
  31631. {
  31632. const ScopedLock sl (lock);
  31633. decrementAllCounters (elapsed);
  31634. if (firstTimer != 0)
  31635. timeUntilFirstTimer = firstTimer->countdownMs;
  31636. }
  31637. if (timeUntilFirstTimer <= 0)
  31638. {
  31639. /* If we managed to set the atomic boolean to true then send a message, this is needed
  31640. as a memory barrier so the message won't be sent before callbackNeeded is set to true,
  31641. but if it fails it means the message-thread changed the value from under us so at least
  31642. some processing is happenening and we can just loop around and try again
  31643. */
  31644. if (callbackNeeded.compareAndSetBool (1, 0))
  31645. {
  31646. postMessage (new Message());
  31647. /* Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
  31648. when the app has a modal loop), so this is how long to wait before assuming the
  31649. message has been lost and trying again.
  31650. */
  31651. const uint32 messageDeliveryTimeout = now + 2000;
  31652. while (callbackNeeded.get() != 0)
  31653. {
  31654. wait (4);
  31655. if (threadShouldExit())
  31656. return;
  31657. if (Time::getMillisecondCounter() > messageDeliveryTimeout)
  31658. break;
  31659. }
  31660. }
  31661. }
  31662. else
  31663. {
  31664. // don't wait for too long because running this loop also helps keep the
  31665. // Time::getApproximateMillisecondTimer value stay up-to-date
  31666. wait (jlimit (1, 50, timeUntilFirstTimer));
  31667. }
  31668. }
  31669. }
  31670. void callTimers()
  31671. {
  31672. const ScopedLock sl (lock);
  31673. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  31674. {
  31675. Timer* const t = firstTimer;
  31676. t->countdownMs = t->periodMs;
  31677. removeTimer (t);
  31678. addTimer (t);
  31679. const ScopedUnlock ul (lock);
  31680. JUCE_TRY
  31681. {
  31682. t->timerCallback();
  31683. }
  31684. JUCE_CATCH_EXCEPTION
  31685. }
  31686. /* This is needed as a memory barrier to make sure all processing of current timers is done
  31687. before the boolean is set. This set should never fail since if it was false in the first place,
  31688. we wouldn't get a message (so it can't be changed from false to true from under us), and if we
  31689. get a message then the value is true and the other thread can only set it to true again and
  31690. we will get another callback to set it to false.
  31691. */
  31692. callbackNeeded.set (0);
  31693. }
  31694. void handleMessage (const Message&)
  31695. {
  31696. callTimers();
  31697. }
  31698. void callTimersSynchronously()
  31699. {
  31700. if (! isThreadRunning())
  31701. {
  31702. // (This is relied on by some plugins in cases where the MM has
  31703. // had to restart and the async callback never started)
  31704. cancelPendingUpdate();
  31705. triggerAsyncUpdate();
  31706. }
  31707. callTimers();
  31708. }
  31709. static void callAnyTimersSynchronously()
  31710. {
  31711. if (InternalTimerThread::instance != 0)
  31712. InternalTimerThread::instance->callTimersSynchronously();
  31713. }
  31714. static inline void add (Timer* const tim) throw()
  31715. {
  31716. if (instance == 0)
  31717. instance = new InternalTimerThread();
  31718. const ScopedLock sl (instance->lock);
  31719. instance->addTimer (tim);
  31720. }
  31721. static inline void remove (Timer* const tim) throw()
  31722. {
  31723. if (instance != 0)
  31724. {
  31725. const ScopedLock sl (instance->lock);
  31726. instance->removeTimer (tim);
  31727. }
  31728. }
  31729. static inline void resetCounter (Timer* const tim,
  31730. const int newCounter) throw()
  31731. {
  31732. if (instance != 0)
  31733. {
  31734. tim->countdownMs = newCounter;
  31735. tim->periodMs = newCounter;
  31736. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  31737. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  31738. {
  31739. const ScopedLock sl (instance->lock);
  31740. instance->removeTimer (tim);
  31741. instance->addTimer (tim);
  31742. }
  31743. }
  31744. }
  31745. private:
  31746. friend class Timer;
  31747. static InternalTimerThread* instance;
  31748. static CriticalSection lock;
  31749. Timer* volatile firstTimer;
  31750. Atomic <int> callbackNeeded;
  31751. void addTimer (Timer* const t) throw()
  31752. {
  31753. #if JUCE_DEBUG
  31754. Timer* tt = firstTimer;
  31755. while (tt != 0)
  31756. {
  31757. // trying to add a timer that's already here - shouldn't get to this point,
  31758. // so if you get this assertion, let me know!
  31759. jassert (tt != t);
  31760. tt = tt->next;
  31761. }
  31762. jassert (t->previous == 0 && t->next == 0);
  31763. #endif
  31764. Timer* i = firstTimer;
  31765. if (i == 0 || i->countdownMs > t->countdownMs)
  31766. {
  31767. t->next = firstTimer;
  31768. firstTimer = t;
  31769. }
  31770. else
  31771. {
  31772. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  31773. i = i->next;
  31774. jassert (i != 0);
  31775. t->next = i->next;
  31776. t->previous = i;
  31777. i->next = t;
  31778. }
  31779. if (t->next != 0)
  31780. t->next->previous = t;
  31781. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  31782. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  31783. notify();
  31784. }
  31785. void removeTimer (Timer* const t) throw()
  31786. {
  31787. #if JUCE_DEBUG
  31788. Timer* tt = firstTimer;
  31789. bool found = false;
  31790. while (tt != 0)
  31791. {
  31792. if (tt == t)
  31793. {
  31794. found = true;
  31795. break;
  31796. }
  31797. tt = tt->next;
  31798. }
  31799. // trying to remove a timer that's not here - shouldn't get to this point,
  31800. // so if you get this assertion, let me know!
  31801. jassert (found);
  31802. #endif
  31803. if (t->previous != 0)
  31804. {
  31805. jassert (firstTimer != t);
  31806. t->previous->next = t->next;
  31807. }
  31808. else
  31809. {
  31810. jassert (firstTimer == t);
  31811. firstTimer = t->next;
  31812. }
  31813. if (t->next != 0)
  31814. t->next->previous = t->previous;
  31815. t->next = 0;
  31816. t->previous = 0;
  31817. }
  31818. void decrementAllCounters (const int numMillisecs) const
  31819. {
  31820. Timer* t = firstTimer;
  31821. while (t != 0)
  31822. {
  31823. t->countdownMs -= numMillisecs;
  31824. t = t->next;
  31825. }
  31826. }
  31827. void handleAsyncUpdate()
  31828. {
  31829. startThread (7);
  31830. }
  31831. InternalTimerThread (const InternalTimerThread&);
  31832. InternalTimerThread& operator= (const InternalTimerThread&);
  31833. };
  31834. InternalTimerThread* InternalTimerThread::instance = 0;
  31835. CriticalSection InternalTimerThread::lock;
  31836. void juce_callAnyTimersSynchronously()
  31837. {
  31838. InternalTimerThread::callAnyTimersSynchronously();
  31839. }
  31840. #if JUCE_DEBUG
  31841. static SortedSet <Timer*> activeTimers;
  31842. #endif
  31843. Timer::Timer() throw()
  31844. : countdownMs (0),
  31845. periodMs (0),
  31846. previous (0),
  31847. next (0)
  31848. {
  31849. #if JUCE_DEBUG
  31850. activeTimers.add (this);
  31851. #endif
  31852. }
  31853. Timer::Timer (const Timer&) throw()
  31854. : countdownMs (0),
  31855. periodMs (0),
  31856. previous (0),
  31857. next (0)
  31858. {
  31859. #if JUCE_DEBUG
  31860. activeTimers.add (this);
  31861. #endif
  31862. }
  31863. Timer::~Timer()
  31864. {
  31865. stopTimer();
  31866. #if JUCE_DEBUG
  31867. activeTimers.removeValue (this);
  31868. #endif
  31869. }
  31870. void Timer::startTimer (const int interval) throw()
  31871. {
  31872. const ScopedLock sl (InternalTimerThread::lock);
  31873. #if JUCE_DEBUG
  31874. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31875. jassert (activeTimers.contains (this));
  31876. #endif
  31877. if (periodMs == 0)
  31878. {
  31879. countdownMs = interval;
  31880. periodMs = jmax (1, interval);
  31881. InternalTimerThread::add (this);
  31882. }
  31883. else
  31884. {
  31885. InternalTimerThread::resetCounter (this, interval);
  31886. }
  31887. }
  31888. void Timer::stopTimer() throw()
  31889. {
  31890. const ScopedLock sl (InternalTimerThread::lock);
  31891. #if JUCE_DEBUG
  31892. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31893. jassert (activeTimers.contains (this));
  31894. #endif
  31895. if (periodMs > 0)
  31896. {
  31897. InternalTimerThread::remove (this);
  31898. periodMs = 0;
  31899. }
  31900. }
  31901. END_JUCE_NAMESPACE
  31902. /*** End of inlined file: juce_Timer.cpp ***/
  31903. #endif
  31904. #if JUCE_BUILD_GUI
  31905. /*** Start of inlined file: juce_Component.cpp ***/
  31906. BEGIN_JUCE_NAMESPACE
  31907. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  31908. enum ComponentMessageNumbers
  31909. {
  31910. customCommandMessage = 0x7fff0001,
  31911. exitModalStateMessage = 0x7fff0002
  31912. };
  31913. static uint32 nextComponentUID = 0;
  31914. Component* Component::currentlyFocusedComponent = 0;
  31915. Component::Component()
  31916. : parentComponent_ (0),
  31917. componentUID (++nextComponentUID),
  31918. numDeepMouseListeners (0),
  31919. lookAndFeel_ (0),
  31920. effect_ (0),
  31921. bufferedImage_ (0),
  31922. mouseListeners_ (0),
  31923. keyListeners_ (0),
  31924. componentFlags_ (0)
  31925. {
  31926. }
  31927. Component::Component (const String& name)
  31928. : componentName_ (name),
  31929. parentComponent_ (0),
  31930. componentUID (++nextComponentUID),
  31931. numDeepMouseListeners (0),
  31932. lookAndFeel_ (0),
  31933. effect_ (0),
  31934. bufferedImage_ (0),
  31935. mouseListeners_ (0),
  31936. keyListeners_ (0),
  31937. componentFlags_ (0)
  31938. {
  31939. }
  31940. Component::~Component()
  31941. {
  31942. componentListeners.call (&ComponentListener::componentBeingDeleted, *this);
  31943. if (parentComponent_ != 0)
  31944. {
  31945. parentComponent_->removeChildComponent (this);
  31946. }
  31947. else if ((currentlyFocusedComponent == this)
  31948. || isParentOf (currentlyFocusedComponent))
  31949. {
  31950. giveAwayFocus();
  31951. }
  31952. if (flags.hasHeavyweightPeerFlag)
  31953. removeFromDesktop();
  31954. for (int i = childComponentList_.size(); --i >= 0;)
  31955. childComponentList_.getUnchecked(i)->parentComponent_ = 0;
  31956. delete mouseListeners_;
  31957. delete keyListeners_;
  31958. }
  31959. void Component::setName (const String& name)
  31960. {
  31961. // if component methods are being called from threads other than the message
  31962. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31963. checkMessageManagerIsLocked
  31964. if (componentName_ != name)
  31965. {
  31966. componentName_ = name;
  31967. if (flags.hasHeavyweightPeerFlag)
  31968. {
  31969. ComponentPeer* const peer = getPeer();
  31970. jassert (peer != 0);
  31971. if (peer != 0)
  31972. peer->setTitle (name);
  31973. }
  31974. BailOutChecker checker (this);
  31975. componentListeners.callChecked (checker, &ComponentListener::componentNameChanged, *this);
  31976. }
  31977. }
  31978. void Component::setVisible (bool shouldBeVisible)
  31979. {
  31980. if (flags.visibleFlag != shouldBeVisible)
  31981. {
  31982. // if component methods are being called from threads other than the message
  31983. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31984. checkMessageManagerIsLocked
  31985. SafePointer<Component> safePointer (this);
  31986. flags.visibleFlag = shouldBeVisible;
  31987. internalRepaint (0, 0, getWidth(), getHeight());
  31988. sendFakeMouseMove();
  31989. if (! shouldBeVisible)
  31990. {
  31991. if (currentlyFocusedComponent == this
  31992. || isParentOf (currentlyFocusedComponent))
  31993. {
  31994. if (parentComponent_ != 0)
  31995. parentComponent_->grabKeyboardFocus();
  31996. else
  31997. giveAwayFocus();
  31998. }
  31999. }
  32000. if (safePointer != 0)
  32001. {
  32002. sendVisibilityChangeMessage();
  32003. if (safePointer != 0 && flags.hasHeavyweightPeerFlag)
  32004. {
  32005. ComponentPeer* const peer = getPeer();
  32006. jassert (peer != 0);
  32007. if (peer != 0)
  32008. {
  32009. peer->setVisible (shouldBeVisible);
  32010. internalHierarchyChanged();
  32011. }
  32012. }
  32013. }
  32014. }
  32015. }
  32016. void Component::visibilityChanged()
  32017. {
  32018. }
  32019. void Component::sendVisibilityChangeMessage()
  32020. {
  32021. BailOutChecker checker (this);
  32022. visibilityChanged();
  32023. if (! checker.shouldBailOut())
  32024. componentListeners.callChecked (checker, &ComponentListener::componentVisibilityChanged, *this);
  32025. }
  32026. bool Component::isShowing() const
  32027. {
  32028. if (flags.visibleFlag)
  32029. {
  32030. if (parentComponent_ != 0)
  32031. {
  32032. return parentComponent_->isShowing();
  32033. }
  32034. else
  32035. {
  32036. const ComponentPeer* const peer = getPeer();
  32037. return peer != 0 && ! peer->isMinimised();
  32038. }
  32039. }
  32040. return false;
  32041. }
  32042. class FadeOutProxyComponent : public Component,
  32043. public Timer
  32044. {
  32045. public:
  32046. FadeOutProxyComponent (Component* comp,
  32047. const int fadeLengthMs,
  32048. const int deltaXToMove,
  32049. const int deltaYToMove,
  32050. const float scaleFactorAtEnd)
  32051. : lastTime (0),
  32052. alpha (1.0f),
  32053. scale (1.0f)
  32054. {
  32055. image = comp->createComponentSnapshot (comp->getLocalBounds());
  32056. setBounds (comp->getBounds());
  32057. comp->getParentComponent()->addAndMakeVisible (this);
  32058. toBehind (comp);
  32059. alphaChangePerMs = -1.0f / (float)fadeLengthMs;
  32060. centreX = comp->getX() + comp->getWidth() * 0.5f;
  32061. xChangePerMs = deltaXToMove / (float)fadeLengthMs;
  32062. centreY = comp->getY() + comp->getHeight() * 0.5f;
  32063. yChangePerMs = deltaYToMove / (float)fadeLengthMs;
  32064. scaleChangePerMs = (scaleFactorAtEnd - 1.0f) / (float)fadeLengthMs;
  32065. setInterceptsMouseClicks (false, false);
  32066. // 30 fps is enough for a fade, but we need a higher rate if it's moving as well..
  32067. startTimer (1000 / ((deltaXToMove == 0 && deltaYToMove == 0) ? 30 : 50));
  32068. }
  32069. ~FadeOutProxyComponent()
  32070. {
  32071. }
  32072. void paint (Graphics& g)
  32073. {
  32074. g.setOpacity (alpha);
  32075. g.drawImage (image,
  32076. 0, 0, getWidth(), getHeight(),
  32077. 0, 0, image.getWidth(), image.getHeight());
  32078. }
  32079. void timerCallback()
  32080. {
  32081. const uint32 now = Time::getMillisecondCounter();
  32082. if (lastTime == 0)
  32083. lastTime = now;
  32084. const int msPassed = (now > lastTime) ? now - lastTime : 0;
  32085. lastTime = now;
  32086. alpha += alphaChangePerMs * msPassed;
  32087. if (alpha > 0)
  32088. {
  32089. if (xChangePerMs != 0.0f || yChangePerMs != 0.0f || scaleChangePerMs != 0.0f)
  32090. {
  32091. centreX += xChangePerMs * msPassed;
  32092. centreY += yChangePerMs * msPassed;
  32093. scale += scaleChangePerMs * msPassed;
  32094. const int w = roundToInt (image.getWidth() * scale);
  32095. const int h = roundToInt (image.getHeight() * scale);
  32096. setBounds (roundToInt (centreX) - w / 2,
  32097. roundToInt (centreY) - h / 2,
  32098. w, h);
  32099. }
  32100. repaint();
  32101. }
  32102. else
  32103. {
  32104. delete this;
  32105. }
  32106. }
  32107. juce_UseDebuggingNewOperator
  32108. private:
  32109. Image image;
  32110. uint32 lastTime;
  32111. float alpha, alphaChangePerMs;
  32112. float centreX, xChangePerMs;
  32113. float centreY, yChangePerMs;
  32114. float scale, scaleChangePerMs;
  32115. FadeOutProxyComponent (const FadeOutProxyComponent&);
  32116. FadeOutProxyComponent& operator= (const FadeOutProxyComponent&);
  32117. };
  32118. void Component::fadeOutComponent (const int millisecondsToFade,
  32119. const int deltaXToMove,
  32120. const int deltaYToMove,
  32121. const float scaleFactorAtEnd)
  32122. {
  32123. //xxx won't work for comps without parents
  32124. if (isShowing() && millisecondsToFade > 0)
  32125. new FadeOutProxyComponent (this, millisecondsToFade,
  32126. deltaXToMove, deltaYToMove, scaleFactorAtEnd);
  32127. setVisible (false);
  32128. }
  32129. bool Component::isValidComponent() const
  32130. {
  32131. return (this != 0) && isValidMessageListener();
  32132. }
  32133. void* Component::getWindowHandle() const
  32134. {
  32135. const ComponentPeer* const peer = getPeer();
  32136. if (peer != 0)
  32137. return peer->getNativeHandle();
  32138. return 0;
  32139. }
  32140. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  32141. {
  32142. // if component methods are being called from threads other than the message
  32143. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32144. checkMessageManagerIsLocked
  32145. if (isOpaque())
  32146. styleWanted &= ~ComponentPeer::windowIsSemiTransparent;
  32147. else
  32148. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  32149. int currentStyleFlags = 0;
  32150. // don't use getPeer(), so that we only get the peer that's specifically
  32151. // for this comp, and not for one of its parents.
  32152. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  32153. if (peer != 0)
  32154. currentStyleFlags = peer->getStyleFlags();
  32155. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  32156. {
  32157. SafePointer<Component> safePointer (this);
  32158. #if JUCE_LINUX
  32159. // it's wise to give the component a non-zero size before
  32160. // putting it on the desktop, as X windows get confused by this, and
  32161. // a (1, 1) minimum size is enforced here.
  32162. setSize (jmax (1, getWidth()),
  32163. jmax (1, getHeight()));
  32164. #endif
  32165. const Point<int> topLeft (relativePositionToGlobal (Point<int> (0, 0)));
  32166. bool wasFullscreen = false;
  32167. bool wasMinimised = false;
  32168. ComponentBoundsConstrainer* currentConstainer = 0;
  32169. Rectangle<int> oldNonFullScreenBounds;
  32170. if (peer != 0)
  32171. {
  32172. wasFullscreen = peer->isFullScreen();
  32173. wasMinimised = peer->isMinimised();
  32174. currentConstainer = peer->getConstrainer();
  32175. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  32176. removeFromDesktop();
  32177. setTopLeftPosition (topLeft.getX(), topLeft.getY());
  32178. }
  32179. if (parentComponent_ != 0)
  32180. parentComponent_->removeChildComponent (this);
  32181. if (safePointer != 0)
  32182. {
  32183. flags.hasHeavyweightPeerFlag = true;
  32184. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  32185. Desktop::getInstance().addDesktopComponent (this);
  32186. bounds_.setPosition (topLeft);
  32187. peer->setBounds (topLeft.getX(), topLeft.getY(), getWidth(), getHeight(), false);
  32188. peer->setVisible (isVisible());
  32189. if (wasFullscreen)
  32190. {
  32191. peer->setFullScreen (true);
  32192. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  32193. }
  32194. if (wasMinimised)
  32195. peer->setMinimised (true);
  32196. if (isAlwaysOnTop())
  32197. peer->setAlwaysOnTop (true);
  32198. peer->setConstrainer (currentConstainer);
  32199. repaint();
  32200. }
  32201. internalHierarchyChanged();
  32202. }
  32203. }
  32204. void Component::removeFromDesktop()
  32205. {
  32206. // if component methods are being called from threads other than the message
  32207. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32208. checkMessageManagerIsLocked
  32209. if (flags.hasHeavyweightPeerFlag)
  32210. {
  32211. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32212. flags.hasHeavyweightPeerFlag = false;
  32213. jassert (peer != 0);
  32214. delete peer;
  32215. Desktop::getInstance().removeDesktopComponent (this);
  32216. }
  32217. }
  32218. bool Component::isOnDesktop() const throw()
  32219. {
  32220. return flags.hasHeavyweightPeerFlag;
  32221. }
  32222. void Component::userTriedToCloseWindow()
  32223. {
  32224. /* This means that the user's trying to get rid of your window with the 'close window' system
  32225. menu option (on windows) or possibly the task manager - you should really handle this
  32226. and delete or hide your component in an appropriate way.
  32227. If you want to ignore the event and don't want to trigger this assertion, just override
  32228. this method and do nothing.
  32229. */
  32230. jassertfalse;
  32231. }
  32232. void Component::minimisationStateChanged (bool)
  32233. {
  32234. }
  32235. void Component::setOpaque (const bool shouldBeOpaque)
  32236. {
  32237. if (shouldBeOpaque != flags.opaqueFlag)
  32238. {
  32239. flags.opaqueFlag = shouldBeOpaque;
  32240. if (flags.hasHeavyweightPeerFlag)
  32241. {
  32242. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32243. if (peer != 0)
  32244. {
  32245. // to make it recreate the heavyweight window
  32246. addToDesktop (peer->getStyleFlags());
  32247. }
  32248. }
  32249. repaint();
  32250. }
  32251. }
  32252. bool Component::isOpaque() const throw()
  32253. {
  32254. return flags.opaqueFlag;
  32255. }
  32256. void Component::setBufferedToImage (const bool shouldBeBuffered)
  32257. {
  32258. if (shouldBeBuffered != flags.bufferToImageFlag)
  32259. {
  32260. bufferedImage_ = Image::null;
  32261. flags.bufferToImageFlag = shouldBeBuffered;
  32262. }
  32263. }
  32264. void Component::toFront (const bool setAsForeground)
  32265. {
  32266. // if component methods are being called from threads other than the message
  32267. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32268. checkMessageManagerIsLocked
  32269. if (flags.hasHeavyweightPeerFlag)
  32270. {
  32271. ComponentPeer* const peer = getPeer();
  32272. if (peer != 0)
  32273. {
  32274. peer->toFront (setAsForeground);
  32275. if (setAsForeground && ! hasKeyboardFocus (true))
  32276. grabKeyboardFocus();
  32277. }
  32278. }
  32279. else if (parentComponent_ != 0)
  32280. {
  32281. Array<Component*>& childList = parentComponent_->childComponentList_;
  32282. if (childList.getLast() != this)
  32283. {
  32284. const int index = childList.indexOf (this);
  32285. if (index >= 0)
  32286. {
  32287. int insertIndex = -1;
  32288. if (! flags.alwaysOnTopFlag)
  32289. {
  32290. insertIndex = childList.size() - 1;
  32291. while (insertIndex > 0 && childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32292. --insertIndex;
  32293. }
  32294. if (index != insertIndex)
  32295. {
  32296. childList.move (index, insertIndex);
  32297. sendFakeMouseMove();
  32298. repaintParent();
  32299. }
  32300. }
  32301. }
  32302. if (setAsForeground)
  32303. {
  32304. internalBroughtToFront();
  32305. grabKeyboardFocus();
  32306. }
  32307. }
  32308. }
  32309. void Component::toBehind (Component* const other)
  32310. {
  32311. if (other != 0 && other != this)
  32312. {
  32313. // the two components must belong to the same parent..
  32314. jassert (parentComponent_ == other->parentComponent_);
  32315. if (parentComponent_ != 0)
  32316. {
  32317. Array<Component*>& childList = parentComponent_->childComponentList_;
  32318. const int index = childList.indexOf (this);
  32319. if (index >= 0 && childList [index + 1] != other)
  32320. {
  32321. int otherIndex = childList.indexOf (other);
  32322. if (otherIndex >= 0)
  32323. {
  32324. if (index < otherIndex)
  32325. --otherIndex;
  32326. childList.move (index, otherIndex);
  32327. sendFakeMouseMove();
  32328. repaintParent();
  32329. }
  32330. }
  32331. }
  32332. else if (isOnDesktop())
  32333. {
  32334. jassert (other->isOnDesktop());
  32335. if (other->isOnDesktop())
  32336. {
  32337. ComponentPeer* const us = getPeer();
  32338. ComponentPeer* const them = other->getPeer();
  32339. jassert (us != 0 && them != 0);
  32340. if (us != 0 && them != 0)
  32341. us->toBehind (them);
  32342. }
  32343. }
  32344. }
  32345. }
  32346. void Component::toBack()
  32347. {
  32348. Array<Component*>& childList = parentComponent_->childComponentList_;
  32349. if (isOnDesktop())
  32350. {
  32351. jassertfalse; //xxx need to add this to native window
  32352. }
  32353. else if (parentComponent_ != 0 && childList.getFirst() != this)
  32354. {
  32355. const int index = childList.indexOf (this);
  32356. if (index > 0)
  32357. {
  32358. int insertIndex = 0;
  32359. if (flags.alwaysOnTopFlag)
  32360. {
  32361. while (insertIndex < childList.size()
  32362. && ! childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32363. {
  32364. ++insertIndex;
  32365. }
  32366. }
  32367. if (index != insertIndex)
  32368. {
  32369. childList.move (index, insertIndex);
  32370. sendFakeMouseMove();
  32371. repaintParent();
  32372. }
  32373. }
  32374. }
  32375. }
  32376. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  32377. {
  32378. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  32379. {
  32380. flags.alwaysOnTopFlag = shouldStayOnTop;
  32381. if (isOnDesktop())
  32382. {
  32383. ComponentPeer* const peer = getPeer();
  32384. jassert (peer != 0);
  32385. if (peer != 0)
  32386. {
  32387. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  32388. {
  32389. // some kinds of peer can't change their always-on-top status, so
  32390. // for these, we'll need to create a new window
  32391. const int oldFlags = peer->getStyleFlags();
  32392. removeFromDesktop();
  32393. addToDesktop (oldFlags);
  32394. }
  32395. }
  32396. }
  32397. if (shouldStayOnTop)
  32398. toFront (false);
  32399. internalHierarchyChanged();
  32400. }
  32401. }
  32402. bool Component::isAlwaysOnTop() const throw()
  32403. {
  32404. return flags.alwaysOnTopFlag;
  32405. }
  32406. int Component::proportionOfWidth (const float proportion) const throw()
  32407. {
  32408. return roundToInt (proportion * bounds_.getWidth());
  32409. }
  32410. int Component::proportionOfHeight (const float proportion) const throw()
  32411. {
  32412. return roundToInt (proportion * bounds_.getHeight());
  32413. }
  32414. int Component::getParentWidth() const throw()
  32415. {
  32416. return (parentComponent_ != 0) ? parentComponent_->getWidth()
  32417. : getParentMonitorArea().getWidth();
  32418. }
  32419. int Component::getParentHeight() const throw()
  32420. {
  32421. return (parentComponent_ != 0) ? parentComponent_->getHeight()
  32422. : getParentMonitorArea().getHeight();
  32423. }
  32424. int Component::getScreenX() const
  32425. {
  32426. return getScreenPosition().getX();
  32427. }
  32428. int Component::getScreenY() const
  32429. {
  32430. return getScreenPosition().getY();
  32431. }
  32432. const Point<int> Component::getScreenPosition() const
  32433. {
  32434. return (parentComponent_ != 0) ? parentComponent_->getScreenPosition() + getPosition()
  32435. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenPosition()
  32436. : getPosition());
  32437. }
  32438. const Rectangle<int> Component::getScreenBounds() const
  32439. {
  32440. return bounds_.withPosition (getScreenPosition());
  32441. }
  32442. const Point<int> Component::relativePositionToGlobal (const Point<int>& relativePosition) const
  32443. {
  32444. const Component* c = this;
  32445. Point<int> p (relativePosition);
  32446. do
  32447. {
  32448. if (c->flags.hasHeavyweightPeerFlag)
  32449. return c->getPeer()->relativePositionToGlobal (p);
  32450. p += c->getPosition();
  32451. c = c->parentComponent_;
  32452. }
  32453. while (c != 0);
  32454. return p;
  32455. }
  32456. const Point<int> Component::globalPositionToRelative (const Point<int>& screenPosition) const
  32457. {
  32458. if (flags.hasHeavyweightPeerFlag)
  32459. {
  32460. return getPeer()->globalPositionToRelative (screenPosition);
  32461. }
  32462. else
  32463. {
  32464. if (parentComponent_ != 0)
  32465. return parentComponent_->globalPositionToRelative (screenPosition) - getPosition();
  32466. return screenPosition - getPosition();
  32467. }
  32468. }
  32469. const Point<int> Component::relativePositionToOtherComponent (const Component* const targetComponent, const Point<int>& positionRelativeToThis) const
  32470. {
  32471. Point<int> p (positionRelativeToThis);
  32472. if (targetComponent != 0)
  32473. {
  32474. const Component* c = this;
  32475. do
  32476. {
  32477. if (c == targetComponent)
  32478. return p;
  32479. if (c->flags.hasHeavyweightPeerFlag)
  32480. {
  32481. p = c->getPeer()->relativePositionToGlobal (p);
  32482. break;
  32483. }
  32484. p += c->getPosition();
  32485. c = c->parentComponent_;
  32486. }
  32487. while (c != 0);
  32488. p = targetComponent->globalPositionToRelative (p);
  32489. }
  32490. return p;
  32491. }
  32492. void Component::setBounds (const int x, const int y, int w, int h)
  32493. {
  32494. // if component methods are being called from threads other than the message
  32495. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32496. checkMessageManagerIsLocked
  32497. if (w < 0) w = 0;
  32498. if (h < 0) h = 0;
  32499. const bool wasResized = (getWidth() != w || getHeight() != h);
  32500. const bool wasMoved = (getX() != x || getY() != y);
  32501. #if JUCE_DEBUG
  32502. // It's a very bad idea to try to resize a window during its paint() method!
  32503. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  32504. #endif
  32505. if (wasMoved || wasResized)
  32506. {
  32507. if (flags.visibleFlag)
  32508. {
  32509. // send a fake mouse move to trigger enter/exit messages if needed..
  32510. sendFakeMouseMove();
  32511. if (! flags.hasHeavyweightPeerFlag)
  32512. repaintParent();
  32513. }
  32514. bounds_.setBounds (x, y, w, h);
  32515. if (wasResized)
  32516. repaint();
  32517. else if (! flags.hasHeavyweightPeerFlag)
  32518. repaintParent();
  32519. if (flags.hasHeavyweightPeerFlag)
  32520. {
  32521. ComponentPeer* const peer = getPeer();
  32522. if (peer != 0)
  32523. {
  32524. if (wasMoved && wasResized)
  32525. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  32526. else if (wasMoved)
  32527. peer->setPosition (getX(), getY());
  32528. else if (wasResized)
  32529. peer->setSize (getWidth(), getHeight());
  32530. }
  32531. }
  32532. sendMovedResizedMessages (wasMoved, wasResized);
  32533. }
  32534. }
  32535. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  32536. {
  32537. JUCE_TRY
  32538. {
  32539. if (wasMoved)
  32540. moved();
  32541. if (wasResized)
  32542. {
  32543. resized();
  32544. for (int i = childComponentList_.size(); --i >= 0;)
  32545. {
  32546. childComponentList_.getUnchecked(i)->parentSizeChanged();
  32547. i = jmin (i, childComponentList_.size());
  32548. }
  32549. }
  32550. BailOutChecker checker (this);
  32551. if (parentComponent_ != 0)
  32552. parentComponent_->childBoundsChanged (this);
  32553. if (! checker.shouldBailOut())
  32554. componentListeners.callChecked (checker, &ComponentListener::componentMovedOrResized,
  32555. *this, wasMoved, wasResized);
  32556. }
  32557. JUCE_CATCH_EXCEPTION
  32558. }
  32559. void Component::setSize (const int w, const int h)
  32560. {
  32561. setBounds (getX(), getY(), w, h);
  32562. }
  32563. void Component::setTopLeftPosition (const int x, const int y)
  32564. {
  32565. setBounds (x, y, getWidth(), getHeight());
  32566. }
  32567. void Component::setTopRightPosition (const int x, const int y)
  32568. {
  32569. setTopLeftPosition (x - getWidth(), y);
  32570. }
  32571. void Component::setBounds (const Rectangle<int>& r)
  32572. {
  32573. setBounds (r.getX(),
  32574. r.getY(),
  32575. r.getWidth(),
  32576. r.getHeight());
  32577. }
  32578. void Component::setBoundsRelative (const float x, const float y,
  32579. const float w, const float h)
  32580. {
  32581. const int pw = getParentWidth();
  32582. const int ph = getParentHeight();
  32583. setBounds (roundToInt (x * pw),
  32584. roundToInt (y * ph),
  32585. roundToInt (w * pw),
  32586. roundToInt (h * ph));
  32587. }
  32588. void Component::setCentrePosition (const int x, const int y)
  32589. {
  32590. setTopLeftPosition (x - getWidth() / 2,
  32591. y - getHeight() / 2);
  32592. }
  32593. void Component::setCentreRelative (const float x, const float y)
  32594. {
  32595. setCentrePosition (roundToInt (getParentWidth() * x),
  32596. roundToInt (getParentHeight() * y));
  32597. }
  32598. void Component::centreWithSize (const int width, const int height)
  32599. {
  32600. const Rectangle<int> parentArea (getParentOrMainMonitorBounds());
  32601. setBounds (parentArea.getCentreX() - width / 2,
  32602. parentArea.getCentreY() - height / 2,
  32603. width, height);
  32604. }
  32605. void Component::setBoundsInset (const BorderSize& borders)
  32606. {
  32607. setBounds (borders.subtractedFrom (getParentOrMainMonitorBounds()));
  32608. }
  32609. void Component::setBoundsToFit (int x, int y, int width, int height,
  32610. const Justification& justification,
  32611. const bool onlyReduceInSize)
  32612. {
  32613. // it's no good calling this method unless both the component and
  32614. // target rectangle have a finite size.
  32615. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  32616. if (getWidth() > 0 && getHeight() > 0
  32617. && width > 0 && height > 0)
  32618. {
  32619. int newW, newH;
  32620. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  32621. {
  32622. newW = getWidth();
  32623. newH = getHeight();
  32624. }
  32625. else
  32626. {
  32627. const double imageRatio = getHeight() / (double) getWidth();
  32628. const double targetRatio = height / (double) width;
  32629. if (imageRatio <= targetRatio)
  32630. {
  32631. newW = width;
  32632. newH = jmin (height, roundToInt (newW * imageRatio));
  32633. }
  32634. else
  32635. {
  32636. newH = height;
  32637. newW = jmin (width, roundToInt (newH / imageRatio));
  32638. }
  32639. }
  32640. if (newW > 0 && newH > 0)
  32641. {
  32642. int newX, newY;
  32643. justification.applyToRectangle (newX, newY, newW, newH,
  32644. x, y, width, height);
  32645. setBounds (newX, newY, newW, newH);
  32646. }
  32647. }
  32648. }
  32649. bool Component::hitTest (int x, int y)
  32650. {
  32651. if (! flags.ignoresMouseClicksFlag)
  32652. return true;
  32653. if (flags.allowChildMouseClicksFlag)
  32654. {
  32655. for (int i = getNumChildComponents(); --i >= 0;)
  32656. {
  32657. Component* const c = getChildComponent (i);
  32658. if (c->isVisible()
  32659. && c->bounds_.contains (x, y)
  32660. && c->hitTest (x - c->getX(),
  32661. y - c->getY()))
  32662. {
  32663. return true;
  32664. }
  32665. }
  32666. }
  32667. return false;
  32668. }
  32669. void Component::setInterceptsMouseClicks (const bool allowClicks,
  32670. const bool allowClicksOnChildComponents) throw()
  32671. {
  32672. flags.ignoresMouseClicksFlag = ! allowClicks;
  32673. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  32674. }
  32675. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  32676. bool& allowsClicksOnChildComponents) const throw()
  32677. {
  32678. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  32679. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  32680. }
  32681. bool Component::contains (const int x, const int y)
  32682. {
  32683. if (((unsigned int) x) < (unsigned int) getWidth()
  32684. && ((unsigned int) y) < (unsigned int) getHeight()
  32685. && hitTest (x, y))
  32686. {
  32687. if (parentComponent_ != 0)
  32688. {
  32689. return parentComponent_->contains (x + getX(),
  32690. y + getY());
  32691. }
  32692. else if (flags.hasHeavyweightPeerFlag)
  32693. {
  32694. const ComponentPeer* const peer = getPeer();
  32695. if (peer != 0)
  32696. return peer->contains (Point<int> (x, y), true);
  32697. }
  32698. }
  32699. return false;
  32700. }
  32701. bool Component::reallyContains (int x, int y, const bool returnTrueIfWithinAChild)
  32702. {
  32703. if (! contains (x, y))
  32704. return false;
  32705. Component* p = this;
  32706. while (p->parentComponent_ != 0)
  32707. {
  32708. x += p->getX();
  32709. y += p->getY();
  32710. p = p->parentComponent_;
  32711. }
  32712. const Component* const c = p->getComponentAt (x, y);
  32713. return (c == this) || (returnTrueIfWithinAChild && isParentOf (c));
  32714. }
  32715. Component* Component::getComponentAt (const Point<int>& position)
  32716. {
  32717. return getComponentAt (position.getX(), position.getY());
  32718. }
  32719. Component* Component::getComponentAt (const int x, const int y)
  32720. {
  32721. if (flags.visibleFlag
  32722. && ((unsigned int) x) < (unsigned int) getWidth()
  32723. && ((unsigned int) y) < (unsigned int) getHeight()
  32724. && hitTest (x, y))
  32725. {
  32726. for (int i = childComponentList_.size(); --i >= 0;)
  32727. {
  32728. Component* const child = childComponentList_.getUnchecked(i);
  32729. Component* const c = child->getComponentAt (x - child->getX(),
  32730. y - child->getY());
  32731. if (c != 0)
  32732. return c;
  32733. }
  32734. return this;
  32735. }
  32736. return 0;
  32737. }
  32738. void Component::addChildComponent (Component* const child, int zOrder)
  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 (child != 0 && child->parentComponent_ != this)
  32744. {
  32745. if (child->parentComponent_ != 0)
  32746. child->parentComponent_->removeChildComponent (child);
  32747. else
  32748. child->removeFromDesktop();
  32749. child->parentComponent_ = this;
  32750. if (child->isVisible())
  32751. child->repaintParent();
  32752. if (! child->isAlwaysOnTop())
  32753. {
  32754. if (zOrder < 0 || zOrder > childComponentList_.size())
  32755. zOrder = childComponentList_.size();
  32756. while (zOrder > 0)
  32757. {
  32758. if (! childComponentList_.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  32759. break;
  32760. --zOrder;
  32761. }
  32762. }
  32763. childComponentList_.insert (zOrder, child);
  32764. child->internalHierarchyChanged();
  32765. internalChildrenChanged();
  32766. }
  32767. }
  32768. void Component::addAndMakeVisible (Component* const child, int zOrder)
  32769. {
  32770. if (child != 0)
  32771. {
  32772. child->setVisible (true);
  32773. addChildComponent (child, zOrder);
  32774. }
  32775. }
  32776. void Component::removeChildComponent (Component* const child)
  32777. {
  32778. removeChildComponent (childComponentList_.indexOf (child));
  32779. }
  32780. Component* Component::removeChildComponent (const int index)
  32781. {
  32782. // if component methods are being called from threads other than the message
  32783. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32784. checkMessageManagerIsLocked
  32785. Component* const child = childComponentList_ [index];
  32786. if (child != 0)
  32787. {
  32788. sendFakeMouseMove();
  32789. child->repaintParent();
  32790. childComponentList_.remove (index);
  32791. child->parentComponent_ = 0;
  32792. JUCE_TRY
  32793. {
  32794. if ((currentlyFocusedComponent == child)
  32795. || child->isParentOf (currentlyFocusedComponent))
  32796. {
  32797. // get rid first to force the grabKeyboardFocus to change to us.
  32798. giveAwayFocus();
  32799. grabKeyboardFocus();
  32800. }
  32801. }
  32802. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  32803. catch (const std::exception& e)
  32804. {
  32805. currentlyFocusedComponent = 0;
  32806. Desktop::getInstance().triggerFocusCallback();
  32807. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  32808. }
  32809. catch (...)
  32810. {
  32811. currentlyFocusedComponent = 0;
  32812. Desktop::getInstance().triggerFocusCallback();
  32813. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  32814. }
  32815. #endif
  32816. child->internalHierarchyChanged();
  32817. internalChildrenChanged();
  32818. }
  32819. return child;
  32820. }
  32821. void Component::removeAllChildren()
  32822. {
  32823. while (childComponentList_.size() > 0)
  32824. removeChildComponent (childComponentList_.size() - 1);
  32825. }
  32826. void Component::deleteAllChildren()
  32827. {
  32828. while (childComponentList_.size() > 0)
  32829. delete (removeChildComponent (childComponentList_.size() - 1));
  32830. }
  32831. int Component::getNumChildComponents() const throw()
  32832. {
  32833. return childComponentList_.size();
  32834. }
  32835. Component* Component::getChildComponent (const int index) const throw()
  32836. {
  32837. return childComponentList_ [index];
  32838. }
  32839. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  32840. {
  32841. return childComponentList_.indexOf (const_cast <Component*> (child));
  32842. }
  32843. Component* Component::getTopLevelComponent() const throw()
  32844. {
  32845. const Component* comp = this;
  32846. while (comp->parentComponent_ != 0)
  32847. comp = comp->parentComponent_;
  32848. return const_cast <Component*> (comp);
  32849. }
  32850. bool Component::isParentOf (const Component* possibleChild) const throw()
  32851. {
  32852. if (! possibleChild->isValidComponent())
  32853. {
  32854. jassert (possibleChild == 0);
  32855. return false;
  32856. }
  32857. while (possibleChild != 0)
  32858. {
  32859. possibleChild = possibleChild->parentComponent_;
  32860. if (possibleChild == this)
  32861. return true;
  32862. }
  32863. return false;
  32864. }
  32865. void Component::parentHierarchyChanged()
  32866. {
  32867. }
  32868. void Component::childrenChanged()
  32869. {
  32870. }
  32871. void Component::internalChildrenChanged()
  32872. {
  32873. if (componentListeners.isEmpty())
  32874. {
  32875. childrenChanged();
  32876. }
  32877. else
  32878. {
  32879. BailOutChecker checker (this);
  32880. childrenChanged();
  32881. if (! checker.shouldBailOut())
  32882. componentListeners.callChecked (checker, &ComponentListener::componentChildrenChanged, *this);
  32883. }
  32884. }
  32885. void Component::internalHierarchyChanged()
  32886. {
  32887. BailOutChecker checker (this);
  32888. parentHierarchyChanged();
  32889. if (checker.shouldBailOut())
  32890. return;
  32891. componentListeners.callChecked (checker, &ComponentListener::componentParentHierarchyChanged, *this);
  32892. if (checker.shouldBailOut())
  32893. return;
  32894. for (int i = childComponentList_.size(); --i >= 0;)
  32895. {
  32896. childComponentList_.getUnchecked (i)->internalHierarchyChanged();
  32897. if (checker.shouldBailOut())
  32898. {
  32899. // you really shouldn't delete the parent component during a callback telling you
  32900. // that it's changed..
  32901. jassertfalse;
  32902. return;
  32903. }
  32904. i = jmin (i, childComponentList_.size());
  32905. }
  32906. }
  32907. void* Component::runModalLoopCallback (void* userData)
  32908. {
  32909. return (void*) (pointer_sized_int) static_cast <Component*> (userData)->runModalLoop();
  32910. }
  32911. int Component::runModalLoop()
  32912. {
  32913. if (! MessageManager::getInstance()->isThisTheMessageThread())
  32914. {
  32915. // use a callback so this can be called from non-gui threads
  32916. return (int) (pointer_sized_int) MessageManager::getInstance()
  32917. ->callFunctionOnMessageThread (&runModalLoopCallback, this);
  32918. }
  32919. if (! isCurrentlyModal())
  32920. enterModalState (true);
  32921. return ModalComponentManager::getInstance()->runEventLoopForCurrentComponent();
  32922. }
  32923. void Component::enterModalState (const bool takeKeyboardFocus_, ModalComponentManager::Callback* const callback)
  32924. {
  32925. // if component methods are being called from threads other than the message
  32926. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32927. checkMessageManagerIsLocked
  32928. // Check for an attempt to make a component modal when it already is!
  32929. // This can cause nasty problems..
  32930. jassert (! flags.currentlyModalFlag);
  32931. if (! isCurrentlyModal())
  32932. {
  32933. ModalComponentManager::getInstance()->startModal (this, callback);
  32934. flags.currentlyModalFlag = true;
  32935. setVisible (true);
  32936. if (takeKeyboardFocus_)
  32937. grabKeyboardFocus();
  32938. }
  32939. }
  32940. void Component::exitModalState (const int returnValue)
  32941. {
  32942. if (isCurrentlyModal())
  32943. {
  32944. if (MessageManager::getInstance()->isThisTheMessageThread())
  32945. {
  32946. ModalComponentManager::getInstance()->endModal (this, returnValue);
  32947. flags.currentlyModalFlag = false;
  32948. bringModalComponentToFront();
  32949. }
  32950. else
  32951. {
  32952. postMessage (new Message (exitModalStateMessage, returnValue, 0, 0));
  32953. }
  32954. }
  32955. }
  32956. bool Component::isCurrentlyModal() const throw()
  32957. {
  32958. return flags.currentlyModalFlag
  32959. && getCurrentlyModalComponent() == this;
  32960. }
  32961. bool Component::isCurrentlyBlockedByAnotherModalComponent() const
  32962. {
  32963. Component* const mc = getCurrentlyModalComponent();
  32964. return mc != 0
  32965. && mc != this
  32966. && (! mc->isParentOf (this))
  32967. && ! mc->canModalEventBeSentToComponent (this);
  32968. }
  32969. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() throw()
  32970. {
  32971. return ModalComponentManager::getInstance()->getNumModalComponents();
  32972. }
  32973. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) throw()
  32974. {
  32975. return ModalComponentManager::getInstance()->getModalComponent (index);
  32976. }
  32977. void Component::bringModalComponentToFront()
  32978. {
  32979. ComponentPeer* lastOne = 0;
  32980. for (int i = 0; i < getNumCurrentlyModalComponents(); ++i)
  32981. {
  32982. Component* const c = getCurrentlyModalComponent (i);
  32983. if (c == 0)
  32984. break;
  32985. ComponentPeer* peer = c->getPeer();
  32986. if (peer != 0 && peer != lastOne)
  32987. {
  32988. if (lastOne == 0)
  32989. {
  32990. peer->toFront (true);
  32991. peer->grabFocus();
  32992. }
  32993. else
  32994. peer->toBehind (lastOne);
  32995. lastOne = peer;
  32996. }
  32997. }
  32998. }
  32999. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  33000. {
  33001. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  33002. }
  33003. bool Component::isBroughtToFrontOnMouseClick() const throw()
  33004. {
  33005. return flags.bringToFrontOnClickFlag;
  33006. }
  33007. void Component::setMouseCursor (const MouseCursor& cursor)
  33008. {
  33009. if (cursor_ != cursor)
  33010. {
  33011. cursor_ = cursor;
  33012. if (flags.visibleFlag)
  33013. updateMouseCursor();
  33014. }
  33015. }
  33016. const MouseCursor Component::getMouseCursor()
  33017. {
  33018. return cursor_;
  33019. }
  33020. void Component::updateMouseCursor() const
  33021. {
  33022. sendFakeMouseMove();
  33023. }
  33024. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  33025. {
  33026. flags.repaintOnMouseActivityFlag = shouldRepaint;
  33027. }
  33028. void Component::repaintParent()
  33029. {
  33030. if (flags.visibleFlag)
  33031. internalRepaint (0, 0, getWidth(), getHeight());
  33032. }
  33033. void Component::repaint()
  33034. {
  33035. repaint (0, 0, getWidth(), getHeight());
  33036. }
  33037. void Component::repaint (const int x, const int y,
  33038. const int w, const int h)
  33039. {
  33040. bufferedImage_ = Image::null;
  33041. if (flags.visibleFlag)
  33042. internalRepaint (x, y, w, h);
  33043. }
  33044. void Component::repaint (const Rectangle<int>& area)
  33045. {
  33046. repaint (area.getX(), area.getY(), area.getWidth(), area.getHeight());
  33047. }
  33048. void Component::internalRepaint (int x, int y, int w, int h)
  33049. {
  33050. // if component methods are being called from threads other than the message
  33051. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33052. checkMessageManagerIsLocked
  33053. if (x < 0)
  33054. {
  33055. w += x;
  33056. x = 0;
  33057. }
  33058. if (x + w > getWidth())
  33059. w = getWidth() - x;
  33060. if (w > 0)
  33061. {
  33062. if (y < 0)
  33063. {
  33064. h += y;
  33065. y = 0;
  33066. }
  33067. if (y + h > getHeight())
  33068. h = getHeight() - y;
  33069. if (h > 0)
  33070. {
  33071. if (parentComponent_ != 0)
  33072. {
  33073. x += getX();
  33074. y += getY();
  33075. if (parentComponent_->flags.visibleFlag)
  33076. parentComponent_->internalRepaint (x, y, w, h);
  33077. }
  33078. else if (flags.hasHeavyweightPeerFlag)
  33079. {
  33080. ComponentPeer* const peer = getPeer();
  33081. if (peer != 0)
  33082. peer->repaint (Rectangle<int> (x, y, w, h));
  33083. }
  33084. }
  33085. }
  33086. }
  33087. void Component::renderComponent (Graphics& g)
  33088. {
  33089. const Rectangle<int> clipBounds (g.getClipBounds());
  33090. g.saveState();
  33091. clipObscuredRegions (g, clipBounds, 0, 0);
  33092. if (! g.isClipEmpty())
  33093. {
  33094. if (flags.bufferToImageFlag)
  33095. {
  33096. if (bufferedImage_.isNull())
  33097. {
  33098. bufferedImage_ = Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33099. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  33100. Graphics imG (bufferedImage_);
  33101. paint (imG);
  33102. }
  33103. g.setColour (Colours::black);
  33104. g.drawImageAt (bufferedImage_, 0, 0);
  33105. }
  33106. else
  33107. {
  33108. paint (g);
  33109. }
  33110. }
  33111. g.restoreState();
  33112. for (int i = 0; i < childComponentList_.size(); ++i)
  33113. {
  33114. Component* const child = childComponentList_.getUnchecked (i);
  33115. if (child->isVisible() && clipBounds.intersects (child->getBounds()))
  33116. {
  33117. g.saveState();
  33118. if (g.reduceClipRegion (child->getX(), child->getY(),
  33119. child->getWidth(), child->getHeight()))
  33120. {
  33121. for (int j = i + 1; j < childComponentList_.size(); ++j)
  33122. {
  33123. const Component* const sibling = childComponentList_.getUnchecked (j);
  33124. if (sibling->flags.opaqueFlag && sibling->isVisible())
  33125. g.excludeClipRegion (sibling->getBounds());
  33126. }
  33127. if (! g.isClipEmpty())
  33128. {
  33129. g.setOrigin (child->getX(), child->getY());
  33130. child->paintEntireComponent (g);
  33131. }
  33132. }
  33133. g.restoreState();
  33134. }
  33135. }
  33136. g.saveState();
  33137. paintOverChildren (g);
  33138. g.restoreState();
  33139. }
  33140. void Component::paintEntireComponent (Graphics& g)
  33141. {
  33142. jassert (! g.isClipEmpty());
  33143. #if JUCE_DEBUG
  33144. flags.isInsidePaintCall = true;
  33145. #endif
  33146. if (effect_ != 0)
  33147. {
  33148. Image effectImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33149. getWidth(), getHeight(),
  33150. ! flags.opaqueFlag, Image::NativeImage);
  33151. {
  33152. Graphics g2 (effectImage);
  33153. renderComponent (g2);
  33154. }
  33155. effect_->applyEffect (effectImage, g);
  33156. }
  33157. else
  33158. {
  33159. renderComponent (g);
  33160. }
  33161. #if JUCE_DEBUG
  33162. flags.isInsidePaintCall = false;
  33163. #endif
  33164. }
  33165. const Image Component::createComponentSnapshot (const Rectangle<int>& areaToGrab,
  33166. const bool clipImageToComponentBounds)
  33167. {
  33168. Rectangle<int> r (areaToGrab);
  33169. if (clipImageToComponentBounds)
  33170. r = r.getIntersection (getLocalBounds());
  33171. Image componentImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33172. jmax (1, r.getWidth()),
  33173. jmax (1, r.getHeight()),
  33174. true);
  33175. Graphics imageContext (componentImage);
  33176. imageContext.setOrigin (-r.getX(), -r.getY());
  33177. paintEntireComponent (imageContext);
  33178. return componentImage;
  33179. }
  33180. void Component::setComponentEffect (ImageEffectFilter* const effect)
  33181. {
  33182. if (effect_ != effect)
  33183. {
  33184. effect_ = effect;
  33185. repaint();
  33186. }
  33187. }
  33188. LookAndFeel& Component::getLookAndFeel() const throw()
  33189. {
  33190. const Component* c = this;
  33191. do
  33192. {
  33193. if (c->lookAndFeel_ != 0)
  33194. return *(c->lookAndFeel_);
  33195. c = c->parentComponent_;
  33196. }
  33197. while (c != 0);
  33198. return LookAndFeel::getDefaultLookAndFeel();
  33199. }
  33200. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  33201. {
  33202. if (lookAndFeel_ != newLookAndFeel)
  33203. {
  33204. lookAndFeel_ = newLookAndFeel;
  33205. sendLookAndFeelChange();
  33206. }
  33207. }
  33208. void Component::lookAndFeelChanged()
  33209. {
  33210. }
  33211. void Component::sendLookAndFeelChange()
  33212. {
  33213. repaint();
  33214. lookAndFeelChanged();
  33215. // (it's not a great idea to do anything that would delete this component
  33216. // during the lookAndFeelChanged() callback)
  33217. jassert (isValidComponent());
  33218. SafePointer<Component> safePointer (this);
  33219. for (int i = childComponentList_.size(); --i >= 0;)
  33220. {
  33221. childComponentList_.getUnchecked (i)->sendLookAndFeelChange();
  33222. if (safePointer == 0)
  33223. return;
  33224. i = jmin (i, childComponentList_.size());
  33225. }
  33226. }
  33227. static const Identifier getColourPropertyId (const int colourId)
  33228. {
  33229. String s;
  33230. s.preallocateStorage (18);
  33231. s << "jcclr_" << String::toHexString (colourId);
  33232. return s;
  33233. }
  33234. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const
  33235. {
  33236. var* v = properties.getItem (getColourPropertyId (colourId));
  33237. if (v != 0)
  33238. return Colour ((int) *v);
  33239. if (inheritFromParent && parentComponent_ != 0)
  33240. return parentComponent_->findColour (colourId, true);
  33241. return getLookAndFeel().findColour (colourId);
  33242. }
  33243. bool Component::isColourSpecified (const int colourId) const
  33244. {
  33245. return properties.contains (getColourPropertyId (colourId));
  33246. }
  33247. void Component::removeColour (const int colourId)
  33248. {
  33249. if (properties.remove (getColourPropertyId (colourId)))
  33250. colourChanged();
  33251. }
  33252. void Component::setColour (const int colourId, const Colour& colour)
  33253. {
  33254. if (properties.set (getColourPropertyId (colourId), (int) colour.getARGB()))
  33255. colourChanged();
  33256. }
  33257. void Component::copyAllExplicitColoursTo (Component& target) const
  33258. {
  33259. bool changed = false;
  33260. for (int i = properties.size(); --i >= 0;)
  33261. {
  33262. const Identifier name (properties.getName(i));
  33263. if (name.toString().startsWith ("jcclr_"))
  33264. if (target.properties.set (name, properties [name]))
  33265. changed = true;
  33266. }
  33267. if (changed)
  33268. target.colourChanged();
  33269. }
  33270. void Component::colourChanged()
  33271. {
  33272. }
  33273. const Rectangle<int> Component::getLocalBounds() const throw()
  33274. {
  33275. return Rectangle<int> (getWidth(), getHeight());
  33276. }
  33277. const Rectangle<int> Component::getParentOrMainMonitorBounds() const
  33278. {
  33279. return parentComponent_ != 0 ? parentComponent_->getLocalBounds()
  33280. : Desktop::getInstance().getMainMonitorArea();
  33281. }
  33282. const Rectangle<int> Component::getUnclippedArea() const
  33283. {
  33284. int x = 0, y = 0, w = getWidth(), h = getHeight();
  33285. Component* p = parentComponent_;
  33286. int px = getX();
  33287. int py = getY();
  33288. while (p != 0)
  33289. {
  33290. if (! Rectangle<int>::intersectRectangles (x, y, w, h, -px, -py, p->getWidth(), p->getHeight()))
  33291. return Rectangle<int>();
  33292. px += p->getX();
  33293. py += p->getY();
  33294. p = p->parentComponent_;
  33295. }
  33296. return Rectangle<int> (x, y, w, h);
  33297. }
  33298. void Component::clipObscuredRegions (Graphics& g, const Rectangle<int>& clipRect,
  33299. const int deltaX, const int deltaY) const
  33300. {
  33301. for (int i = childComponentList_.size(); --i >= 0;)
  33302. {
  33303. const Component* const c = childComponentList_.getUnchecked(i);
  33304. if (c->isVisible())
  33305. {
  33306. const Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  33307. if (! newClip.isEmpty())
  33308. {
  33309. if (c->isOpaque())
  33310. {
  33311. g.excludeClipRegion (newClip.translated (deltaX, deltaY));
  33312. }
  33313. else
  33314. {
  33315. c->clipObscuredRegions (g, newClip.translated (-c->getX(), -c->getY()),
  33316. c->getX() + deltaX,
  33317. c->getY() + deltaY);
  33318. }
  33319. }
  33320. }
  33321. }
  33322. }
  33323. void Component::getVisibleArea (RectangleList& result, const bool includeSiblings) const
  33324. {
  33325. result.clear();
  33326. const Rectangle<int> unclipped (getUnclippedArea());
  33327. if (! unclipped.isEmpty())
  33328. {
  33329. result.add (unclipped);
  33330. if (includeSiblings)
  33331. {
  33332. const Component* const c = getTopLevelComponent();
  33333. c->subtractObscuredRegions (result, c->relativePositionToOtherComponent (this, Point<int>()),
  33334. c->getLocalBounds(), this);
  33335. }
  33336. subtractObscuredRegions (result, Point<int>(), unclipped, 0);
  33337. result.consolidate();
  33338. }
  33339. }
  33340. void Component::subtractObscuredRegions (RectangleList& result,
  33341. const Point<int>& delta,
  33342. const Rectangle<int>& clipRect,
  33343. const Component* const compToAvoid) const
  33344. {
  33345. for (int i = childComponentList_.size(); --i >= 0;)
  33346. {
  33347. const Component* const c = childComponentList_.getUnchecked(i);
  33348. if (c != compToAvoid && c->isVisible())
  33349. {
  33350. if (c->isOpaque())
  33351. {
  33352. Rectangle<int> childBounds (c->bounds_.getIntersection (clipRect));
  33353. childBounds.translate (delta.getX(), delta.getY());
  33354. result.subtract (childBounds);
  33355. }
  33356. else
  33357. {
  33358. Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  33359. newClip.translate (-c->getX(), -c->getY());
  33360. c->subtractObscuredRegions (result, c->getPosition() + delta,
  33361. newClip, compToAvoid);
  33362. }
  33363. }
  33364. }
  33365. }
  33366. void Component::mouseEnter (const MouseEvent&)
  33367. {
  33368. // base class does nothing
  33369. }
  33370. void Component::mouseExit (const MouseEvent&)
  33371. {
  33372. // base class does nothing
  33373. }
  33374. void Component::mouseDown (const MouseEvent&)
  33375. {
  33376. // base class does nothing
  33377. }
  33378. void Component::mouseUp (const MouseEvent&)
  33379. {
  33380. // base class does nothing
  33381. }
  33382. void Component::mouseDrag (const MouseEvent&)
  33383. {
  33384. // base class does nothing
  33385. }
  33386. void Component::mouseMove (const MouseEvent&)
  33387. {
  33388. // base class does nothing
  33389. }
  33390. void Component::mouseDoubleClick (const MouseEvent&)
  33391. {
  33392. // base class does nothing
  33393. }
  33394. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  33395. {
  33396. // the base class just passes this event up to its parent..
  33397. if (parentComponent_ != 0)
  33398. parentComponent_->mouseWheelMove (e.getEventRelativeTo (parentComponent_),
  33399. wheelIncrementX, wheelIncrementY);
  33400. }
  33401. void Component::resized()
  33402. {
  33403. // base class does nothing
  33404. }
  33405. void Component::moved()
  33406. {
  33407. // base class does nothing
  33408. }
  33409. void Component::childBoundsChanged (Component*)
  33410. {
  33411. // base class does nothing
  33412. }
  33413. void Component::parentSizeChanged()
  33414. {
  33415. // base class does nothing
  33416. }
  33417. void Component::addComponentListener (ComponentListener* const newListener)
  33418. {
  33419. jassert (isValidComponent());
  33420. componentListeners.add (newListener);
  33421. }
  33422. void Component::removeComponentListener (ComponentListener* const listenerToRemove)
  33423. {
  33424. jassert (isValidComponent());
  33425. componentListeners.remove (listenerToRemove);
  33426. }
  33427. void Component::inputAttemptWhenModal()
  33428. {
  33429. bringModalComponentToFront();
  33430. getLookAndFeel().playAlertSound();
  33431. }
  33432. bool Component::canModalEventBeSentToComponent (const Component*)
  33433. {
  33434. return false;
  33435. }
  33436. void Component::internalModalInputAttempt()
  33437. {
  33438. Component* const current = getCurrentlyModalComponent();
  33439. if (current != 0)
  33440. current->inputAttemptWhenModal();
  33441. }
  33442. void Component::paint (Graphics&)
  33443. {
  33444. // all painting is done in the subclasses
  33445. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  33446. }
  33447. void Component::paintOverChildren (Graphics&)
  33448. {
  33449. // all painting is done in the subclasses
  33450. }
  33451. void Component::handleMessage (const Message& message)
  33452. {
  33453. if (message.intParameter1 == exitModalStateMessage)
  33454. {
  33455. exitModalState (message.intParameter2);
  33456. }
  33457. else if (message.intParameter1 == customCommandMessage)
  33458. {
  33459. handleCommandMessage (message.intParameter2);
  33460. }
  33461. }
  33462. void Component::postCommandMessage (const int commandId)
  33463. {
  33464. postMessage (new Message (customCommandMessage, commandId, 0, 0));
  33465. }
  33466. void Component::handleCommandMessage (int)
  33467. {
  33468. // used by subclasses
  33469. }
  33470. void Component::addMouseListener (MouseListener* const newListener,
  33471. const bool wantsEventsForAllNestedChildComponents)
  33472. {
  33473. // if component methods are being called from threads other than the message
  33474. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33475. checkMessageManagerIsLocked
  33476. // If you register a component as a mouselistener for itself, it'll receive all the events
  33477. // twice - once via the direct callback that all components get anyway, and then again as a listener!
  33478. jassert ((newListener != this) || wantsEventsForAllNestedChildComponents);
  33479. if (mouseListeners_ == 0)
  33480. mouseListeners_ = new Array<MouseListener*>();
  33481. if (! mouseListeners_->contains (newListener))
  33482. {
  33483. if (wantsEventsForAllNestedChildComponents)
  33484. {
  33485. mouseListeners_->insert (0, newListener);
  33486. ++numDeepMouseListeners;
  33487. }
  33488. else
  33489. {
  33490. mouseListeners_->add (newListener);
  33491. }
  33492. }
  33493. }
  33494. void Component::removeMouseListener (MouseListener* const listenerToRemove)
  33495. {
  33496. // if component methods are being called from threads other than the message
  33497. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33498. checkMessageManagerIsLocked
  33499. if (mouseListeners_ != 0)
  33500. {
  33501. const int index = mouseListeners_->indexOf (listenerToRemove);
  33502. if (index >= 0)
  33503. {
  33504. if (index < numDeepMouseListeners)
  33505. --numDeepMouseListeners;
  33506. mouseListeners_->remove (index);
  33507. }
  33508. }
  33509. }
  33510. void Component::internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33511. {
  33512. if (isCurrentlyBlockedByAnotherModalComponent())
  33513. {
  33514. // if something else is modal, always just show a normal mouse cursor
  33515. source.showMouseCursor (MouseCursor::NormalCursor);
  33516. return;
  33517. }
  33518. if (! flags.mouseInsideFlag)
  33519. {
  33520. flags.mouseInsideFlag = true;
  33521. flags.mouseOverFlag = true;
  33522. flags.draggingFlag = false;
  33523. BailOutChecker checker (this);
  33524. if (flags.repaintOnMouseActivityFlag)
  33525. repaint();
  33526. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33527. this, this, time, relativePos,
  33528. time, 0, false);
  33529. mouseEnter (me);
  33530. if (checker.shouldBailOut())
  33531. return;
  33532. Desktop::getInstance().resetTimer();
  33533. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseEnter, me);
  33534. if (checker.shouldBailOut())
  33535. return;
  33536. if (mouseListeners_ != 0)
  33537. {
  33538. for (int i = mouseListeners_->size(); --i >= 0;)
  33539. {
  33540. mouseListeners_->getUnchecked(i)->mouseEnter (me);
  33541. if (checker.shouldBailOut())
  33542. return;
  33543. i = jmin (i, mouseListeners_->size());
  33544. }
  33545. }
  33546. Component* p = parentComponent_;
  33547. while (p != 0)
  33548. {
  33549. if (p->numDeepMouseListeners > 0)
  33550. {
  33551. BailOutChecker checker2 (this, p);
  33552. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33553. {
  33554. p->mouseListeners_->getUnchecked(i)->mouseEnter (me);
  33555. if (checker2.shouldBailOut())
  33556. return;
  33557. i = jmin (i, p->numDeepMouseListeners);
  33558. }
  33559. }
  33560. p = p->parentComponent_;
  33561. }
  33562. }
  33563. }
  33564. void Component::internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33565. {
  33566. BailOutChecker checker (this);
  33567. if (flags.draggingFlag)
  33568. {
  33569. internalMouseUp (source, relativePos, time, source.getCurrentModifiers().getRawFlags());
  33570. if (checker.shouldBailOut())
  33571. return;
  33572. }
  33573. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  33574. {
  33575. flags.mouseInsideFlag = false;
  33576. flags.mouseOverFlag = false;
  33577. flags.draggingFlag = false;
  33578. if (flags.repaintOnMouseActivityFlag)
  33579. repaint();
  33580. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33581. this, this, time, relativePos,
  33582. time, 0, false);
  33583. mouseExit (me);
  33584. if (checker.shouldBailOut())
  33585. return;
  33586. Desktop::getInstance().resetTimer();
  33587. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseExit, me);
  33588. if (checker.shouldBailOut())
  33589. return;
  33590. if (mouseListeners_ != 0)
  33591. {
  33592. for (int i = mouseListeners_->size(); --i >= 0;)
  33593. {
  33594. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseExit (me);
  33595. if (checker.shouldBailOut())
  33596. return;
  33597. i = jmin (i, mouseListeners_->size());
  33598. }
  33599. }
  33600. Component* p = parentComponent_;
  33601. while (p != 0)
  33602. {
  33603. if (p->numDeepMouseListeners > 0)
  33604. {
  33605. BailOutChecker checker2 (this, p);
  33606. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33607. {
  33608. p->mouseListeners_->getUnchecked (i)->mouseExit (me);
  33609. if (checker2.shouldBailOut())
  33610. return;
  33611. i = jmin (i, p->numDeepMouseListeners);
  33612. }
  33613. }
  33614. p = p->parentComponent_;
  33615. }
  33616. }
  33617. }
  33618. class InternalDragRepeater : public Timer
  33619. {
  33620. public:
  33621. InternalDragRepeater()
  33622. {}
  33623. ~InternalDragRepeater()
  33624. {
  33625. clearSingletonInstance();
  33626. }
  33627. juce_DeclareSingleton_SingleThreaded_Minimal (InternalDragRepeater)
  33628. void timerCallback()
  33629. {
  33630. Desktop& desktop = Desktop::getInstance();
  33631. int numMiceDown = 0;
  33632. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  33633. {
  33634. MouseInputSource* const source = desktop.getMouseSource(i);
  33635. if (source->isDragging())
  33636. {
  33637. source->triggerFakeMove();
  33638. ++numMiceDown;
  33639. }
  33640. }
  33641. if (numMiceDown == 0)
  33642. deleteInstance();
  33643. }
  33644. juce_UseDebuggingNewOperator
  33645. private:
  33646. InternalDragRepeater (const InternalDragRepeater&);
  33647. InternalDragRepeater& operator= (const InternalDragRepeater&);
  33648. };
  33649. juce_ImplementSingleton_SingleThreaded (InternalDragRepeater)
  33650. void Component::beginDragAutoRepeat (const int interval)
  33651. {
  33652. if (interval > 0)
  33653. {
  33654. if (InternalDragRepeater::getInstance()->getTimerInterval() != interval)
  33655. InternalDragRepeater::getInstance()->startTimer (interval);
  33656. }
  33657. else
  33658. {
  33659. InternalDragRepeater::deleteInstance();
  33660. }
  33661. }
  33662. void Component::internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33663. {
  33664. Desktop& desktop = Desktop::getInstance();
  33665. BailOutChecker checker (this);
  33666. if (isCurrentlyBlockedByAnotherModalComponent())
  33667. {
  33668. internalModalInputAttempt();
  33669. if (checker.shouldBailOut())
  33670. return;
  33671. // If processing the input attempt has exited the modal loop, we'll allow the event
  33672. // to be delivered..
  33673. if (isCurrentlyBlockedByAnotherModalComponent())
  33674. {
  33675. // allow blocked mouse-events to go to global listeners..
  33676. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33677. this, this, time, relativePos, time,
  33678. source.getNumberOfMultipleClicks(), false);
  33679. desktop.resetTimer();
  33680. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33681. return;
  33682. }
  33683. }
  33684. {
  33685. Component* c = this;
  33686. while (c != 0)
  33687. {
  33688. if (c->isBroughtToFrontOnMouseClick())
  33689. {
  33690. c->toFront (true);
  33691. if (checker.shouldBailOut())
  33692. return;
  33693. }
  33694. c = c->parentComponent_;
  33695. }
  33696. }
  33697. if (! flags.dontFocusOnMouseClickFlag)
  33698. {
  33699. grabFocusInternal (focusChangedByMouseClick);
  33700. if (checker.shouldBailOut())
  33701. return;
  33702. }
  33703. flags.draggingFlag = true;
  33704. flags.mouseOverFlag = true;
  33705. if (flags.repaintOnMouseActivityFlag)
  33706. repaint();
  33707. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33708. this, this, time, relativePos, time,
  33709. source.getNumberOfMultipleClicks(), false);
  33710. mouseDown (me);
  33711. if (checker.shouldBailOut())
  33712. return;
  33713. desktop.resetTimer();
  33714. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33715. if (checker.shouldBailOut())
  33716. return;
  33717. if (mouseListeners_ != 0)
  33718. {
  33719. for (int i = mouseListeners_->size(); --i >= 0;)
  33720. {
  33721. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDown (me);
  33722. if (checker.shouldBailOut())
  33723. return;
  33724. i = jmin (i, mouseListeners_->size());
  33725. }
  33726. }
  33727. Component* p = parentComponent_;
  33728. while (p != 0)
  33729. {
  33730. if (p->numDeepMouseListeners > 0)
  33731. {
  33732. BailOutChecker checker2 (this, p);
  33733. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33734. {
  33735. p->mouseListeners_->getUnchecked (i)->mouseDown (me);
  33736. if (checker2.shouldBailOut())
  33737. return;
  33738. i = jmin (i, p->numDeepMouseListeners);
  33739. }
  33740. }
  33741. p = p->parentComponent_;
  33742. }
  33743. }
  33744. void Component::internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers)
  33745. {
  33746. if (flags.draggingFlag)
  33747. {
  33748. Desktop& desktop = Desktop::getInstance();
  33749. flags.draggingFlag = false;
  33750. BailOutChecker checker (this);
  33751. if (flags.repaintOnMouseActivityFlag)
  33752. repaint();
  33753. const MouseEvent me (source, relativePos,
  33754. oldModifiers, this, this, time,
  33755. globalPositionToRelative (source.getLastMouseDownPosition()),
  33756. source.getLastMouseDownTime(),
  33757. source.getNumberOfMultipleClicks(),
  33758. source.hasMouseMovedSignificantlySincePressed());
  33759. mouseUp (me);
  33760. if (checker.shouldBailOut())
  33761. return;
  33762. desktop.resetTimer();
  33763. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseUp, me);
  33764. if (checker.shouldBailOut())
  33765. return;
  33766. if (mouseListeners_ != 0)
  33767. {
  33768. for (int i = mouseListeners_->size(); --i >= 0;)
  33769. {
  33770. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseUp (me);
  33771. if (checker.shouldBailOut())
  33772. return;
  33773. i = jmin (i, mouseListeners_->size());
  33774. }
  33775. }
  33776. {
  33777. Component* p = parentComponent_;
  33778. while (p != 0)
  33779. {
  33780. if (p->numDeepMouseListeners > 0)
  33781. {
  33782. BailOutChecker checker2 (this, p);
  33783. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33784. {
  33785. p->mouseListeners_->getUnchecked (i)->mouseUp (me);
  33786. if (checker2.shouldBailOut())
  33787. return;
  33788. i = jmin (i, p->numDeepMouseListeners);
  33789. }
  33790. }
  33791. p = p->parentComponent_;
  33792. }
  33793. }
  33794. // check for double-click
  33795. if (me.getNumberOfClicks() >= 2)
  33796. {
  33797. const int numListeners = (mouseListeners_ != 0) ? mouseListeners_->size() : 0;
  33798. mouseDoubleClick (me);
  33799. if (checker.shouldBailOut())
  33800. return;
  33801. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDoubleClick, me);
  33802. if (checker.shouldBailOut())
  33803. return;
  33804. for (int i = numListeners; --i >= 0;)
  33805. {
  33806. if (checker.shouldBailOut())
  33807. return;
  33808. MouseListener* const ml = (MouseListener*)((*mouseListeners_)[i]);
  33809. if (ml != 0)
  33810. ml->mouseDoubleClick (me);
  33811. }
  33812. if (checker.shouldBailOut())
  33813. return;
  33814. Component* p = parentComponent_;
  33815. while (p != 0)
  33816. {
  33817. if (p->numDeepMouseListeners > 0)
  33818. {
  33819. BailOutChecker checker2 (this, p);
  33820. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33821. {
  33822. p->mouseListeners_->getUnchecked (i)->mouseDoubleClick (me);
  33823. if (checker2.shouldBailOut())
  33824. return;
  33825. i = jmin (i, p->numDeepMouseListeners);
  33826. }
  33827. }
  33828. p = p->parentComponent_;
  33829. }
  33830. }
  33831. }
  33832. }
  33833. void Component::internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33834. {
  33835. if (flags.draggingFlag)
  33836. {
  33837. Desktop& desktop = Desktop::getInstance();
  33838. flags.mouseOverFlag = reallyContains (relativePos.getX(), relativePos.getY(), false);
  33839. BailOutChecker checker (this);
  33840. const MouseEvent me (source, relativePos,
  33841. source.getCurrentModifiers(), this, this, time,
  33842. globalPositionToRelative (source.getLastMouseDownPosition()),
  33843. source.getLastMouseDownTime(),
  33844. source.getNumberOfMultipleClicks(),
  33845. source.hasMouseMovedSignificantlySincePressed());
  33846. mouseDrag (me);
  33847. if (checker.shouldBailOut())
  33848. return;
  33849. desktop.resetTimer();
  33850. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33851. if (checker.shouldBailOut())
  33852. return;
  33853. if (mouseListeners_ != 0)
  33854. {
  33855. for (int i = mouseListeners_->size(); --i >= 0;)
  33856. {
  33857. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDrag (me);
  33858. if (checker.shouldBailOut())
  33859. return;
  33860. i = jmin (i, mouseListeners_->size());
  33861. }
  33862. }
  33863. Component* p = parentComponent_;
  33864. while (p != 0)
  33865. {
  33866. if (p->numDeepMouseListeners > 0)
  33867. {
  33868. BailOutChecker checker2 (this, p);
  33869. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33870. {
  33871. p->mouseListeners_->getUnchecked (i)->mouseDrag (me);
  33872. if (checker2.shouldBailOut())
  33873. return;
  33874. i = jmin (i, p->numDeepMouseListeners);
  33875. }
  33876. }
  33877. p = p->parentComponent_;
  33878. }
  33879. }
  33880. }
  33881. void Component::internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33882. {
  33883. Desktop& desktop = Desktop::getInstance();
  33884. BailOutChecker checker (this);
  33885. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33886. this, this, time, relativePos,
  33887. time, 0, false);
  33888. if (isCurrentlyBlockedByAnotherModalComponent())
  33889. {
  33890. // allow blocked mouse-events to go to global listeners..
  33891. desktop.sendMouseMove();
  33892. }
  33893. else
  33894. {
  33895. flags.mouseOverFlag = true;
  33896. mouseMove (me);
  33897. if (checker.shouldBailOut())
  33898. return;
  33899. desktop.resetTimer();
  33900. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33901. if (checker.shouldBailOut())
  33902. return;
  33903. if (mouseListeners_ != 0)
  33904. {
  33905. for (int i = mouseListeners_->size(); --i >= 0;)
  33906. {
  33907. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseMove (me);
  33908. if (checker.shouldBailOut())
  33909. return;
  33910. i = jmin (i, mouseListeners_->size());
  33911. }
  33912. }
  33913. Component* p = parentComponent_;
  33914. while (p != 0)
  33915. {
  33916. if (p->numDeepMouseListeners > 0)
  33917. {
  33918. BailOutChecker checker2 (this, p);
  33919. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33920. {
  33921. p->mouseListeners_->getUnchecked (i)->mouseMove (me);
  33922. if (checker2.shouldBailOut())
  33923. return;
  33924. i = jmin (i, p->numDeepMouseListeners);
  33925. }
  33926. }
  33927. p = p->parentComponent_;
  33928. }
  33929. }
  33930. }
  33931. void Component::internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos,
  33932. const Time& time, const float amountX, const float amountY)
  33933. {
  33934. Desktop& desktop = Desktop::getInstance();
  33935. BailOutChecker checker (this);
  33936. const float wheelIncrementX = amountX / 256.0f;
  33937. const float wheelIncrementY = amountY / 256.0f;
  33938. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33939. this, this, time, relativePos, time, 0, false);
  33940. if (isCurrentlyBlockedByAnotherModalComponent())
  33941. {
  33942. // allow blocked mouse-events to go to global listeners..
  33943. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33944. }
  33945. else
  33946. {
  33947. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33948. if (checker.shouldBailOut())
  33949. return;
  33950. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  33951. if (checker.shouldBailOut())
  33952. return;
  33953. if (mouseListeners_ != 0)
  33954. {
  33955. for (int i = mouseListeners_->size(); --i >= 0;)
  33956. {
  33957. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33958. if (checker.shouldBailOut())
  33959. return;
  33960. i = jmin (i, mouseListeners_->size());
  33961. }
  33962. }
  33963. Component* p = parentComponent_;
  33964. while (p != 0)
  33965. {
  33966. if (p->numDeepMouseListeners > 0)
  33967. {
  33968. BailOutChecker checker2 (this, p);
  33969. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33970. {
  33971. p->mouseListeners_->getUnchecked (i)->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  33972. if (checker2.shouldBailOut())
  33973. return;
  33974. i = jmin (i, p->numDeepMouseListeners);
  33975. }
  33976. }
  33977. p = p->parentComponent_;
  33978. }
  33979. }
  33980. }
  33981. void Component::sendFakeMouseMove() const
  33982. {
  33983. Desktop::getInstance().getMainMouseSource().triggerFakeMove();
  33984. }
  33985. void Component::broughtToFront()
  33986. {
  33987. }
  33988. void Component::internalBroughtToFront()
  33989. {
  33990. if (! isValidComponent())
  33991. return;
  33992. if (flags.hasHeavyweightPeerFlag)
  33993. Desktop::getInstance().componentBroughtToFront (this);
  33994. BailOutChecker checker (this);
  33995. broughtToFront();
  33996. if (checker.shouldBailOut())
  33997. return;
  33998. componentListeners.callChecked (checker, &ComponentListener::componentBroughtToFront, *this);
  33999. if (checker.shouldBailOut())
  34000. return;
  34001. // When brought to the front and there's a modal component blocking this one,
  34002. // we need to bring the modal one to the front instead..
  34003. Component* const cm = getCurrentlyModalComponent();
  34004. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  34005. bringModalComponentToFront();
  34006. }
  34007. void Component::focusGained (FocusChangeType)
  34008. {
  34009. // base class does nothing
  34010. }
  34011. void Component::internalFocusGain (const FocusChangeType cause)
  34012. {
  34013. SafePointer<Component> safePointer (this);
  34014. focusGained (cause);
  34015. if (safePointer != 0)
  34016. internalChildFocusChange (cause);
  34017. }
  34018. void Component::focusLost (FocusChangeType)
  34019. {
  34020. // base class does nothing
  34021. }
  34022. void Component::internalFocusLoss (const FocusChangeType cause)
  34023. {
  34024. SafePointer<Component> safePointer (this);
  34025. focusLost (focusChangedDirectly);
  34026. if (safePointer != 0)
  34027. internalChildFocusChange (cause);
  34028. }
  34029. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  34030. {
  34031. // base class does nothing
  34032. }
  34033. void Component::internalChildFocusChange (FocusChangeType cause)
  34034. {
  34035. const bool childIsNowFocused = hasKeyboardFocus (true);
  34036. if (flags.childCompFocusedFlag != childIsNowFocused)
  34037. {
  34038. flags.childCompFocusedFlag = childIsNowFocused;
  34039. SafePointer<Component> safePointer (this);
  34040. focusOfChildComponentChanged (cause);
  34041. if (safePointer == 0)
  34042. return;
  34043. }
  34044. if (parentComponent_ != 0)
  34045. parentComponent_->internalChildFocusChange (cause);
  34046. }
  34047. bool Component::isEnabled() const throw()
  34048. {
  34049. return (! flags.isDisabledFlag)
  34050. && (parentComponent_ == 0 || parentComponent_->isEnabled());
  34051. }
  34052. void Component::setEnabled (const bool shouldBeEnabled)
  34053. {
  34054. if (flags.isDisabledFlag == shouldBeEnabled)
  34055. {
  34056. flags.isDisabledFlag = ! shouldBeEnabled;
  34057. // if any parent components are disabled, setting our flag won't make a difference,
  34058. // so no need to send a change message
  34059. if (parentComponent_ == 0 || parentComponent_->isEnabled())
  34060. sendEnablementChangeMessage();
  34061. }
  34062. }
  34063. void Component::sendEnablementChangeMessage()
  34064. {
  34065. SafePointer<Component> safePointer (this);
  34066. enablementChanged();
  34067. if (safePointer == 0)
  34068. return;
  34069. for (int i = getNumChildComponents(); --i >= 0;)
  34070. {
  34071. Component* const c = getChildComponent (i);
  34072. if (c != 0)
  34073. {
  34074. c->sendEnablementChangeMessage();
  34075. if (safePointer == 0)
  34076. return;
  34077. }
  34078. }
  34079. }
  34080. void Component::enablementChanged()
  34081. {
  34082. }
  34083. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  34084. {
  34085. flags.wantsFocusFlag = wantsFocus;
  34086. }
  34087. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  34088. {
  34089. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  34090. }
  34091. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  34092. {
  34093. return ! flags.dontFocusOnMouseClickFlag;
  34094. }
  34095. bool Component::getWantsKeyboardFocus() const throw()
  34096. {
  34097. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  34098. }
  34099. void Component::setFocusContainer (const bool shouldBeFocusContainer) throw()
  34100. {
  34101. flags.isFocusContainerFlag = shouldBeFocusContainer;
  34102. }
  34103. bool Component::isFocusContainer() const throw()
  34104. {
  34105. return flags.isFocusContainerFlag;
  34106. }
  34107. static const Identifier juce_explicitFocusOrderId ("_jexfo");
  34108. int Component::getExplicitFocusOrder() const
  34109. {
  34110. return properties [juce_explicitFocusOrderId];
  34111. }
  34112. void Component::setExplicitFocusOrder (const int newFocusOrderIndex)
  34113. {
  34114. properties.set (juce_explicitFocusOrderId, newFocusOrderIndex);
  34115. }
  34116. KeyboardFocusTraverser* Component::createFocusTraverser()
  34117. {
  34118. if (flags.isFocusContainerFlag || parentComponent_ == 0)
  34119. return new KeyboardFocusTraverser();
  34120. return parentComponent_->createFocusTraverser();
  34121. }
  34122. void Component::takeKeyboardFocus (const FocusChangeType cause)
  34123. {
  34124. // give the focus to this component
  34125. if (currentlyFocusedComponent != this)
  34126. {
  34127. JUCE_TRY
  34128. {
  34129. // get the focus onto our desktop window
  34130. ComponentPeer* const peer = getPeer();
  34131. if (peer != 0)
  34132. {
  34133. SafePointer<Component> safePointer (this);
  34134. peer->grabFocus();
  34135. if (peer->isFocused() && currentlyFocusedComponent != this)
  34136. {
  34137. SafePointer<Component> componentLosingFocus (currentlyFocusedComponent);
  34138. currentlyFocusedComponent = this;
  34139. Desktop::getInstance().triggerFocusCallback();
  34140. // call this after setting currentlyFocusedComponent so that the one that's
  34141. // losing it has a chance to see where focus is going
  34142. if (componentLosingFocus != 0)
  34143. componentLosingFocus->internalFocusLoss (cause);
  34144. if (currentlyFocusedComponent == this)
  34145. {
  34146. focusGained (cause);
  34147. if (safePointer != 0)
  34148. internalChildFocusChange (cause);
  34149. }
  34150. }
  34151. }
  34152. }
  34153. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  34154. catch (const std::exception& e)
  34155. {
  34156. currentlyFocusedComponent = 0;
  34157. Desktop::getInstance().triggerFocusCallback();
  34158. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  34159. }
  34160. catch (...)
  34161. {
  34162. currentlyFocusedComponent = 0;
  34163. Desktop::getInstance().triggerFocusCallback();
  34164. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  34165. }
  34166. #endif
  34167. }
  34168. }
  34169. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  34170. {
  34171. if (isShowing())
  34172. {
  34173. if (flags.wantsFocusFlag && (isEnabled() || parentComponent_ == 0))
  34174. {
  34175. takeKeyboardFocus (cause);
  34176. }
  34177. else
  34178. {
  34179. if (isParentOf (currentlyFocusedComponent)
  34180. && currentlyFocusedComponent->isShowing())
  34181. {
  34182. // do nothing if the focused component is actually a child of ours..
  34183. }
  34184. else
  34185. {
  34186. // find the default child component..
  34187. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  34188. if (traverser != 0)
  34189. {
  34190. Component* const defaultComp = traverser->getDefaultComponent (this);
  34191. traverser = 0;
  34192. if (defaultComp != 0)
  34193. {
  34194. defaultComp->grabFocusInternal (cause, false);
  34195. return;
  34196. }
  34197. }
  34198. if (canTryParent && parentComponent_ != 0)
  34199. {
  34200. // if no children want it and we're allowed to try our parent comp,
  34201. // then pass up to parent, which will try our siblings.
  34202. parentComponent_->grabFocusInternal (cause, true);
  34203. }
  34204. }
  34205. }
  34206. }
  34207. }
  34208. void Component::grabKeyboardFocus()
  34209. {
  34210. // if component methods are being called from threads other than the message
  34211. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  34212. checkMessageManagerIsLocked
  34213. grabFocusInternal (focusChangedDirectly);
  34214. }
  34215. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  34216. {
  34217. // if component methods are being called from threads other than the message
  34218. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  34219. checkMessageManagerIsLocked
  34220. if (parentComponent_ != 0)
  34221. {
  34222. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  34223. if (traverser != 0)
  34224. {
  34225. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  34226. : traverser->getPreviousComponent (this);
  34227. traverser = 0;
  34228. if (nextComp != 0)
  34229. {
  34230. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  34231. {
  34232. SafePointer<Component> nextCompPointer (nextComp);
  34233. internalModalInputAttempt();
  34234. if (nextCompPointer == 0 || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  34235. return;
  34236. }
  34237. nextComp->grabFocusInternal (focusChangedByTabKey);
  34238. return;
  34239. }
  34240. }
  34241. parentComponent_->moveKeyboardFocusToSibling (moveToNext);
  34242. }
  34243. }
  34244. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const
  34245. {
  34246. return (currentlyFocusedComponent == this)
  34247. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  34248. }
  34249. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  34250. {
  34251. return currentlyFocusedComponent;
  34252. }
  34253. void Component::giveAwayFocus()
  34254. {
  34255. // use a copy so we can clear the value before the call
  34256. SafePointer<Component> componentLosingFocus (currentlyFocusedComponent);
  34257. currentlyFocusedComponent = 0;
  34258. Desktop::getInstance().triggerFocusCallback();
  34259. if (componentLosingFocus != 0)
  34260. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  34261. }
  34262. bool Component::isMouseOver() const throw()
  34263. {
  34264. return flags.mouseOverFlag;
  34265. }
  34266. bool Component::isMouseButtonDown() const throw()
  34267. {
  34268. return flags.draggingFlag;
  34269. }
  34270. bool Component::isMouseOverOrDragging() const throw()
  34271. {
  34272. return flags.mouseOverFlag || flags.draggingFlag;
  34273. }
  34274. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  34275. {
  34276. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  34277. }
  34278. const Point<int> Component::getMouseXYRelative() const
  34279. {
  34280. return globalPositionToRelative (Desktop::getMousePosition());
  34281. }
  34282. const Rectangle<int> Component::getParentMonitorArea() const
  34283. {
  34284. return Desktop::getInstance()
  34285. .getMonitorAreaContaining (relativePositionToGlobal (getLocalBounds().getCentre()));
  34286. }
  34287. void Component::addKeyListener (KeyListener* const newListener)
  34288. {
  34289. if (keyListeners_ == 0)
  34290. keyListeners_ = new Array <KeyListener*>();
  34291. keyListeners_->addIfNotAlreadyThere (newListener);
  34292. }
  34293. void Component::removeKeyListener (KeyListener* const listenerToRemove)
  34294. {
  34295. if (keyListeners_ != 0)
  34296. keyListeners_->removeValue (listenerToRemove);
  34297. }
  34298. bool Component::keyPressed (const KeyPress&)
  34299. {
  34300. return false;
  34301. }
  34302. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  34303. {
  34304. return false;
  34305. }
  34306. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  34307. {
  34308. if (parentComponent_ != 0)
  34309. parentComponent_->modifierKeysChanged (modifiers);
  34310. }
  34311. void Component::internalModifierKeysChanged()
  34312. {
  34313. sendFakeMouseMove();
  34314. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  34315. }
  34316. ComponentPeer* Component::getPeer() const
  34317. {
  34318. if (flags.hasHeavyweightPeerFlag)
  34319. return ComponentPeer::getPeerFor (this);
  34320. else if (parentComponent_ != 0)
  34321. return parentComponent_->getPeer();
  34322. else
  34323. return 0;
  34324. }
  34325. Component::BailOutChecker::BailOutChecker (Component* const component1, Component* const component2_)
  34326. : safePointer1 (component1), safePointer2 (component2_), component2 (component2_)
  34327. {
  34328. jassert (component1 != 0);
  34329. }
  34330. bool Component::BailOutChecker::shouldBailOut() const throw()
  34331. {
  34332. return safePointer1 == 0 || safePointer2.getComponent() != component2;
  34333. }
  34334. END_JUCE_NAMESPACE
  34335. /*** End of inlined file: juce_Component.cpp ***/
  34336. /*** Start of inlined file: juce_ComponentListener.cpp ***/
  34337. BEGIN_JUCE_NAMESPACE
  34338. void ComponentListener::componentMovedOrResized (Component&, bool, bool) {}
  34339. void ComponentListener::componentBroughtToFront (Component&) {}
  34340. void ComponentListener::componentVisibilityChanged (Component&) {}
  34341. void ComponentListener::componentChildrenChanged (Component&) {}
  34342. void ComponentListener::componentParentHierarchyChanged (Component&) {}
  34343. void ComponentListener::componentNameChanged (Component&) {}
  34344. void ComponentListener::componentBeingDeleted (Component&) {}
  34345. END_JUCE_NAMESPACE
  34346. /*** End of inlined file: juce_ComponentListener.cpp ***/
  34347. /*** Start of inlined file: juce_Desktop.cpp ***/
  34348. BEGIN_JUCE_NAMESPACE
  34349. Desktop::Desktop()
  34350. : mouseClickCounter (0),
  34351. kioskModeComponent (0)
  34352. {
  34353. createMouseInputSources();
  34354. refreshMonitorSizes();
  34355. }
  34356. Desktop::~Desktop()
  34357. {
  34358. jassert (instance == this);
  34359. instance = 0;
  34360. // doh! If you don't delete all your windows before exiting, you're going to
  34361. // be leaking memory!
  34362. jassert (desktopComponents.size() == 0);
  34363. }
  34364. Desktop& JUCE_CALLTYPE Desktop::getInstance()
  34365. {
  34366. if (instance == 0)
  34367. instance = new Desktop();
  34368. return *instance;
  34369. }
  34370. Desktop* Desktop::instance = 0;
  34371. extern void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords,
  34372. const bool clipToWorkArea);
  34373. void Desktop::refreshMonitorSizes()
  34374. {
  34375. const Array <Rectangle<int> > oldClipped (monitorCoordsClipped);
  34376. const Array <Rectangle<int> > oldUnclipped (monitorCoordsUnclipped);
  34377. monitorCoordsClipped.clear();
  34378. monitorCoordsUnclipped.clear();
  34379. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  34380. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  34381. jassert (monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  34382. if (oldClipped != monitorCoordsClipped
  34383. || oldUnclipped != monitorCoordsUnclipped)
  34384. {
  34385. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  34386. {
  34387. ComponentPeer* const p = ComponentPeer::getPeer (i);
  34388. if (p != 0)
  34389. p->handleScreenSizeChange();
  34390. }
  34391. }
  34392. }
  34393. int Desktop::getNumDisplayMonitors() const throw()
  34394. {
  34395. return monitorCoordsClipped.size();
  34396. }
  34397. const Rectangle<int> Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  34398. {
  34399. return clippedToWorkArea ? monitorCoordsClipped [index]
  34400. : monitorCoordsUnclipped [index];
  34401. }
  34402. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  34403. {
  34404. RectangleList rl;
  34405. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  34406. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34407. return rl;
  34408. }
  34409. const Rectangle<int> Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  34410. {
  34411. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  34412. }
  34413. const Rectangle<int> Desktop::getMonitorAreaContaining (const Point<int>& position, const bool clippedToWorkArea) const
  34414. {
  34415. Rectangle<int> best (getMainMonitorArea (clippedToWorkArea));
  34416. double bestDistance = 1.0e10;
  34417. for (int i = getNumDisplayMonitors(); --i >= 0;)
  34418. {
  34419. const Rectangle<int> rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34420. if (rect.contains (position))
  34421. return rect;
  34422. const double distance = rect.getCentre().getDistanceFrom (position);
  34423. if (distance < bestDistance)
  34424. {
  34425. bestDistance = distance;
  34426. best = rect;
  34427. }
  34428. }
  34429. return best;
  34430. }
  34431. int Desktop::getNumComponents() const throw()
  34432. {
  34433. return desktopComponents.size();
  34434. }
  34435. Component* Desktop::getComponent (const int index) const throw()
  34436. {
  34437. return desktopComponents [index];
  34438. }
  34439. Component* Desktop::findComponentAt (const Point<int>& screenPosition) const
  34440. {
  34441. for (int i = desktopComponents.size(); --i >= 0;)
  34442. {
  34443. Component* const c = desktopComponents.getUnchecked(i);
  34444. const Point<int> relative (c->globalPositionToRelative (screenPosition));
  34445. if (c->contains (relative.getX(), relative.getY()))
  34446. return c->getComponentAt (relative.getX(), relative.getY());
  34447. }
  34448. return 0;
  34449. }
  34450. void Desktop::addDesktopComponent (Component* const c)
  34451. {
  34452. jassert (c != 0);
  34453. jassert (! desktopComponents.contains (c));
  34454. desktopComponents.addIfNotAlreadyThere (c);
  34455. }
  34456. void Desktop::removeDesktopComponent (Component* const c)
  34457. {
  34458. desktopComponents.removeValue (c);
  34459. }
  34460. void Desktop::componentBroughtToFront (Component* const c)
  34461. {
  34462. const int index = desktopComponents.indexOf (c);
  34463. jassert (index >= 0);
  34464. if (index >= 0)
  34465. {
  34466. int newIndex = -1;
  34467. if (! c->isAlwaysOnTop())
  34468. {
  34469. newIndex = desktopComponents.size();
  34470. while (newIndex > 0 && desktopComponents.getUnchecked (newIndex - 1)->isAlwaysOnTop())
  34471. --newIndex;
  34472. --newIndex;
  34473. }
  34474. desktopComponents.move (index, newIndex);
  34475. }
  34476. }
  34477. const Point<int> Desktop::getLastMouseDownPosition() throw()
  34478. {
  34479. return getInstance().getMainMouseSource().getLastMouseDownPosition();
  34480. }
  34481. int Desktop::getMouseButtonClickCounter() throw()
  34482. {
  34483. return getInstance().mouseClickCounter;
  34484. }
  34485. void Desktop::incrementMouseClickCounter() throw()
  34486. {
  34487. ++mouseClickCounter;
  34488. }
  34489. int Desktop::getNumDraggingMouseSources() const throw()
  34490. {
  34491. int num = 0;
  34492. for (int i = mouseSources.size(); --i >= 0;)
  34493. if (mouseSources.getUnchecked(i)->isDragging())
  34494. ++num;
  34495. return num;
  34496. }
  34497. MouseInputSource* Desktop::getDraggingMouseSource (int index) const throw()
  34498. {
  34499. int num = 0;
  34500. for (int i = mouseSources.size(); --i >= 0;)
  34501. {
  34502. MouseInputSource* const mi = mouseSources.getUnchecked(i);
  34503. if (mi->isDragging())
  34504. {
  34505. if (index == num)
  34506. return mi;
  34507. ++num;
  34508. }
  34509. }
  34510. return 0;
  34511. }
  34512. void Desktop::addFocusChangeListener (FocusChangeListener* const listener)
  34513. {
  34514. focusListeners.add (listener);
  34515. }
  34516. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener)
  34517. {
  34518. focusListeners.remove (listener);
  34519. }
  34520. void Desktop::triggerFocusCallback()
  34521. {
  34522. triggerAsyncUpdate();
  34523. }
  34524. void Desktop::handleAsyncUpdate()
  34525. {
  34526. Component* currentFocus = Component::getCurrentlyFocusedComponent();
  34527. focusListeners.call (&FocusChangeListener::globalFocusChanged, currentFocus);
  34528. }
  34529. void Desktop::addGlobalMouseListener (MouseListener* const listener)
  34530. {
  34531. mouseListeners.add (listener);
  34532. resetTimer();
  34533. }
  34534. void Desktop::removeGlobalMouseListener (MouseListener* const listener)
  34535. {
  34536. mouseListeners.remove (listener);
  34537. resetTimer();
  34538. }
  34539. void Desktop::timerCallback()
  34540. {
  34541. if (lastFakeMouseMove != getMousePosition())
  34542. sendMouseMove();
  34543. }
  34544. void Desktop::sendMouseMove()
  34545. {
  34546. if (! mouseListeners.isEmpty())
  34547. {
  34548. startTimer (20);
  34549. lastFakeMouseMove = getMousePosition();
  34550. Component* const target = findComponentAt (lastFakeMouseMove);
  34551. if (target != 0)
  34552. {
  34553. Component::BailOutChecker checker (target);
  34554. const Point<int> pos (target->globalPositionToRelative (lastFakeMouseMove));
  34555. const Time now (Time::getCurrentTime());
  34556. const MouseEvent me (getMainMouseSource(), pos, ModifierKeys::getCurrentModifiers(),
  34557. target, target, now, pos, now, 0, false);
  34558. if (me.mods.isAnyMouseButtonDown())
  34559. mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  34560. else
  34561. mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  34562. }
  34563. }
  34564. }
  34565. void Desktop::resetTimer()
  34566. {
  34567. if (mouseListeners.size() == 0)
  34568. stopTimer();
  34569. else
  34570. startTimer (100);
  34571. lastFakeMouseMove = getMousePosition();
  34572. }
  34573. extern void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  34574. void Desktop::setKioskModeComponent (Component* componentToUse, const bool allowMenusAndBars)
  34575. {
  34576. if (kioskModeComponent != componentToUse)
  34577. {
  34578. // agh! Don't delete a component without first stopping it being the kiosk comp
  34579. jassert (kioskModeComponent == 0 || kioskModeComponent->isValidComponent());
  34580. // agh! Don't remove a component from the desktop if it's the kiosk comp!
  34581. jassert (kioskModeComponent == 0 || kioskModeComponent->isOnDesktop());
  34582. if (kioskModeComponent->isValidComponent())
  34583. {
  34584. juce_setKioskComponent (kioskModeComponent, false, allowMenusAndBars);
  34585. kioskModeComponent->setBounds (kioskComponentOriginalBounds);
  34586. }
  34587. kioskModeComponent = componentToUse;
  34588. if (kioskModeComponent != 0)
  34589. {
  34590. jassert (kioskModeComponent->isValidComponent());
  34591. // Only components that are already on the desktop can be put into kiosk mode!
  34592. jassert (kioskModeComponent->isOnDesktop());
  34593. kioskComponentOriginalBounds = kioskModeComponent->getBounds();
  34594. juce_setKioskComponent (kioskModeComponent, true, allowMenusAndBars);
  34595. }
  34596. }
  34597. }
  34598. END_JUCE_NAMESPACE
  34599. /*** End of inlined file: juce_Desktop.cpp ***/
  34600. /*** Start of inlined file: juce_ModalComponentManager.cpp ***/
  34601. BEGIN_JUCE_NAMESPACE
  34602. class ModalComponentManager::ModalItem : public ComponentListener
  34603. {
  34604. public:
  34605. ModalItem (Component* const comp, Callback* const callback)
  34606. : component (comp), returnValue (0), isActive (true), isDeleted (false)
  34607. {
  34608. if (callback != 0)
  34609. callbacks.add (callback);
  34610. jassert (comp != 0);
  34611. component->addComponentListener (this);
  34612. }
  34613. ~ModalItem()
  34614. {
  34615. if (! isDeleted)
  34616. component->removeComponentListener (this);
  34617. }
  34618. void componentBeingDeleted (Component&)
  34619. {
  34620. isDeleted = true;
  34621. cancel();
  34622. }
  34623. void componentVisibilityChanged (Component&)
  34624. {
  34625. if (! component->isShowing())
  34626. cancel();
  34627. }
  34628. void componentParentHierarchyChanged (Component&)
  34629. {
  34630. if (! component->isShowing())
  34631. cancel();
  34632. }
  34633. void cancel()
  34634. {
  34635. if (isActive)
  34636. {
  34637. isActive = false;
  34638. ModalComponentManager::getInstance()->triggerAsyncUpdate();
  34639. }
  34640. }
  34641. Component* component;
  34642. OwnedArray<Callback> callbacks;
  34643. int returnValue;
  34644. bool isActive, isDeleted;
  34645. private:
  34646. ModalItem (const ModalItem&);
  34647. ModalItem& operator= (const ModalItem&);
  34648. };
  34649. ModalComponentManager::ModalComponentManager()
  34650. {
  34651. }
  34652. ModalComponentManager::~ModalComponentManager()
  34653. {
  34654. clearSingletonInstance();
  34655. }
  34656. juce_ImplementSingleton_SingleThreaded (ModalComponentManager);
  34657. void ModalComponentManager::startModal (Component* component, Callback* callback)
  34658. {
  34659. if (component != 0)
  34660. stack.add (new ModalItem (component, callback));
  34661. }
  34662. void ModalComponentManager::attachCallback (Component* component, Callback* callback)
  34663. {
  34664. if (callback != 0)
  34665. {
  34666. ScopedPointer<Callback> callbackDeleter (callback);
  34667. for (int i = stack.size(); --i >= 0;)
  34668. {
  34669. ModalItem* const item = stack.getUnchecked(i);
  34670. if (item->component == component)
  34671. {
  34672. item->callbacks.add (callback);
  34673. callbackDeleter.release();
  34674. break;
  34675. }
  34676. }
  34677. }
  34678. }
  34679. void ModalComponentManager::endModal (Component* component)
  34680. {
  34681. for (int i = stack.size(); --i >= 0;)
  34682. {
  34683. ModalItem* const item = stack.getUnchecked(i);
  34684. if (item->component == component)
  34685. item->cancel();
  34686. }
  34687. }
  34688. void ModalComponentManager::endModal (Component* component, int returnValue)
  34689. {
  34690. for (int i = stack.size(); --i >= 0;)
  34691. {
  34692. ModalItem* const item = stack.getUnchecked(i);
  34693. if (item->component == component)
  34694. {
  34695. item->returnValue = returnValue;
  34696. item->cancel();
  34697. }
  34698. }
  34699. }
  34700. int ModalComponentManager::getNumModalComponents() const
  34701. {
  34702. int n = 0;
  34703. for (int i = 0; i < stack.size(); ++i)
  34704. if (stack.getUnchecked(i)->isActive)
  34705. ++n;
  34706. return n;
  34707. }
  34708. Component* ModalComponentManager::getModalComponent (const int index) const
  34709. {
  34710. int n = 0;
  34711. for (int i = stack.size(); --i >= 0;)
  34712. {
  34713. const ModalItem* const item = stack.getUnchecked(i);
  34714. if (item->isActive)
  34715. if (n++ == index)
  34716. return item->component;
  34717. }
  34718. return 0;
  34719. }
  34720. bool ModalComponentManager::isModal (Component* const comp) const
  34721. {
  34722. for (int i = stack.size(); --i >= 0;)
  34723. {
  34724. const ModalItem* const item = stack.getUnchecked(i);
  34725. if (item->isActive && item->component == comp)
  34726. return true;
  34727. }
  34728. return false;
  34729. }
  34730. bool ModalComponentManager::isFrontModalComponent (Component* const comp) const
  34731. {
  34732. return comp == getModalComponent (0);
  34733. }
  34734. void ModalComponentManager::handleAsyncUpdate()
  34735. {
  34736. for (int i = stack.size(); --i >= 0;)
  34737. {
  34738. const ModalItem* const item = stack.getUnchecked(i);
  34739. if (! item->isActive)
  34740. {
  34741. for (int j = item->callbacks.size(); --j >= 0;)
  34742. item->callbacks.getUnchecked(j)->modalStateFinished (item->returnValue);
  34743. stack.remove (i);
  34744. }
  34745. }
  34746. }
  34747. class ModalComponentManager::ReturnValueRetriever : public ModalComponentManager::Callback
  34748. {
  34749. public:
  34750. ReturnValueRetriever (int& value_, bool& finished_) : value (value_), finished (finished_) {}
  34751. ~ReturnValueRetriever() {}
  34752. void modalStateFinished (int returnValue)
  34753. {
  34754. finished = true;
  34755. value = returnValue;
  34756. }
  34757. private:
  34758. int& value;
  34759. bool& finished;
  34760. ReturnValueRetriever (const ReturnValueRetriever&);
  34761. ReturnValueRetriever& operator= (const ReturnValueRetriever&);
  34762. };
  34763. int ModalComponentManager::runEventLoopForCurrentComponent()
  34764. {
  34765. // This can only be run from the message thread!
  34766. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  34767. Component* currentlyModal = getModalComponent (0);
  34768. if (currentlyModal == 0)
  34769. return 0;
  34770. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  34771. int returnValue = 0;
  34772. bool finished = false;
  34773. attachCallback (currentlyModal, new ReturnValueRetriever (returnValue, finished));
  34774. JUCE_TRY
  34775. {
  34776. while (! finished)
  34777. {
  34778. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  34779. break;
  34780. }
  34781. }
  34782. JUCE_CATCH_EXCEPTION
  34783. if (prevFocused != 0)
  34784. prevFocused->grabKeyboardFocus();
  34785. return returnValue;
  34786. }
  34787. END_JUCE_NAMESPACE
  34788. /*** End of inlined file: juce_ModalComponentManager.cpp ***/
  34789. /*** Start of inlined file: juce_ArrowButton.cpp ***/
  34790. BEGIN_JUCE_NAMESPACE
  34791. ArrowButton::ArrowButton (const String& name,
  34792. float arrowDirectionInRadians,
  34793. const Colour& arrowColour)
  34794. : Button (name),
  34795. colour (arrowColour)
  34796. {
  34797. path.lineTo (0.0f, 1.0f);
  34798. path.lineTo (1.0f, 0.5f);
  34799. path.closeSubPath();
  34800. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  34801. 0.5f, 0.5f));
  34802. setComponentEffect (&shadow);
  34803. buttonStateChanged();
  34804. }
  34805. ArrowButton::~ArrowButton()
  34806. {
  34807. }
  34808. void ArrowButton::paintButton (Graphics& g,
  34809. bool /*isMouseOverButton*/,
  34810. bool /*isButtonDown*/)
  34811. {
  34812. g.setColour (colour);
  34813. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  34814. (float) offset,
  34815. (float) (getWidth() - 3),
  34816. (float) (getHeight() - 3),
  34817. false));
  34818. }
  34819. void ArrowButton::buttonStateChanged()
  34820. {
  34821. offset = (isDown()) ? 1 : 0;
  34822. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  34823. 0.3f, -1, 0);
  34824. }
  34825. END_JUCE_NAMESPACE
  34826. /*** End of inlined file: juce_ArrowButton.cpp ***/
  34827. /*** Start of inlined file: juce_Button.cpp ***/
  34828. BEGIN_JUCE_NAMESPACE
  34829. class Button::RepeatTimer : public Timer
  34830. {
  34831. public:
  34832. RepeatTimer (Button& owner_) : owner (owner_) {}
  34833. void timerCallback() { owner.repeatTimerCallback(); }
  34834. juce_UseDebuggingNewOperator
  34835. private:
  34836. Button& owner;
  34837. RepeatTimer (const RepeatTimer&);
  34838. RepeatTimer& operator= (const RepeatTimer&);
  34839. };
  34840. Button::Button (const String& name)
  34841. : Component (name),
  34842. text (name),
  34843. buttonPressTime (0),
  34844. lastTimeCallbackTime (0),
  34845. commandManagerToUse (0),
  34846. autoRepeatDelay (-1),
  34847. autoRepeatSpeed (0),
  34848. autoRepeatMinimumDelay (-1),
  34849. radioGroupId (0),
  34850. commandID (0),
  34851. connectedEdgeFlags (0),
  34852. buttonState (buttonNormal),
  34853. lastToggleState (false),
  34854. clickTogglesState (false),
  34855. needsToRelease (false),
  34856. needsRepainting (false),
  34857. isKeyDown (false),
  34858. triggerOnMouseDown (false),
  34859. generateTooltip (false)
  34860. {
  34861. setWantsKeyboardFocus (true);
  34862. isOn.addListener (this);
  34863. }
  34864. Button::~Button()
  34865. {
  34866. isOn.removeListener (this);
  34867. if (commandManagerToUse != 0)
  34868. commandManagerToUse->removeListener (this);
  34869. repeatTimer = 0;
  34870. clearShortcuts();
  34871. }
  34872. void Button::setButtonText (const String& newText)
  34873. {
  34874. if (text != newText)
  34875. {
  34876. text = newText;
  34877. repaint();
  34878. }
  34879. }
  34880. void Button::setTooltip (const String& newTooltip)
  34881. {
  34882. SettableTooltipClient::setTooltip (newTooltip);
  34883. generateTooltip = false;
  34884. }
  34885. const String Button::getTooltip()
  34886. {
  34887. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  34888. {
  34889. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  34890. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  34891. for (int i = 0; i < keyPresses.size(); ++i)
  34892. {
  34893. const String key (keyPresses.getReference(i).getTextDescription());
  34894. tt << " [";
  34895. if (key.length() == 1)
  34896. tt << TRANS("shortcut") << ": '" << key << "']";
  34897. else
  34898. tt << key << ']';
  34899. }
  34900. return tt;
  34901. }
  34902. return SettableTooltipClient::getTooltip();
  34903. }
  34904. void Button::setConnectedEdges (const int connectedEdgeFlags_)
  34905. {
  34906. if (connectedEdgeFlags != connectedEdgeFlags_)
  34907. {
  34908. connectedEdgeFlags = connectedEdgeFlags_;
  34909. repaint();
  34910. }
  34911. }
  34912. void Button::setToggleState (const bool shouldBeOn,
  34913. const bool sendChangeNotification)
  34914. {
  34915. if (shouldBeOn != lastToggleState)
  34916. {
  34917. if (isOn != shouldBeOn) // this test means that if the value is void rather than explicitly set to
  34918. isOn = shouldBeOn; // false, it won't be changed unless the required value is true.
  34919. lastToggleState = shouldBeOn;
  34920. repaint();
  34921. if (sendChangeNotification)
  34922. {
  34923. Component::SafePointer<Component> deletionWatcher (this);
  34924. sendClickMessage (ModifierKeys());
  34925. if (deletionWatcher == 0)
  34926. return;
  34927. }
  34928. if (lastToggleState)
  34929. turnOffOtherButtonsInGroup (sendChangeNotification);
  34930. }
  34931. }
  34932. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  34933. {
  34934. clickTogglesState = shouldToggle;
  34935. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  34936. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  34937. // it is that this button represents, and the button will update its state to reflect this
  34938. // in the applicationCommandListChanged() method.
  34939. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  34940. }
  34941. bool Button::getClickingTogglesState() const throw()
  34942. {
  34943. return clickTogglesState;
  34944. }
  34945. void Button::valueChanged (Value& value)
  34946. {
  34947. if (value.refersToSameSourceAs (isOn))
  34948. setToggleState (isOn.getValue(), true);
  34949. }
  34950. void Button::setRadioGroupId (const int newGroupId)
  34951. {
  34952. if (radioGroupId != newGroupId)
  34953. {
  34954. radioGroupId = newGroupId;
  34955. if (lastToggleState)
  34956. turnOffOtherButtonsInGroup (true);
  34957. }
  34958. }
  34959. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  34960. {
  34961. Component* const p = getParentComponent();
  34962. if (p != 0 && radioGroupId != 0)
  34963. {
  34964. Component::SafePointer<Component> deletionWatcher (this);
  34965. for (int i = p->getNumChildComponents(); --i >= 0;)
  34966. {
  34967. Component* const c = p->getChildComponent (i);
  34968. if (c != this)
  34969. {
  34970. Button* const b = dynamic_cast <Button*> (c);
  34971. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  34972. {
  34973. b->setToggleState (false, sendChangeNotification);
  34974. if (deletionWatcher == 0)
  34975. return;
  34976. }
  34977. }
  34978. }
  34979. }
  34980. }
  34981. void Button::enablementChanged()
  34982. {
  34983. updateState (0);
  34984. repaint();
  34985. }
  34986. Button::ButtonState Button::updateState (const MouseEvent* const e)
  34987. {
  34988. ButtonState state = buttonNormal;
  34989. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  34990. {
  34991. Point<int> mousePos;
  34992. if (e == 0)
  34993. mousePos = getMouseXYRelative();
  34994. else
  34995. mousePos = e->getEventRelativeTo (this).getPosition();
  34996. const bool over = reallyContains (mousePos.getX(), mousePos.getY(), true);
  34997. const bool down = isMouseButtonDown();
  34998. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  34999. state = buttonDown;
  35000. else if (over)
  35001. state = buttonOver;
  35002. }
  35003. setState (state);
  35004. return state;
  35005. }
  35006. void Button::setState (const ButtonState newState)
  35007. {
  35008. if (buttonState != newState)
  35009. {
  35010. buttonState = newState;
  35011. repaint();
  35012. if (buttonState == buttonDown)
  35013. {
  35014. buttonPressTime = Time::getApproximateMillisecondCounter();
  35015. lastTimeCallbackTime = buttonPressTime;
  35016. }
  35017. sendStateMessage();
  35018. }
  35019. }
  35020. bool Button::isDown() const throw()
  35021. {
  35022. return buttonState == buttonDown;
  35023. }
  35024. bool Button::isOver() const throw()
  35025. {
  35026. return buttonState != buttonNormal;
  35027. }
  35028. void Button::buttonStateChanged()
  35029. {
  35030. }
  35031. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  35032. {
  35033. const uint32 now = Time::getApproximateMillisecondCounter();
  35034. return now > buttonPressTime ? now - buttonPressTime : 0;
  35035. }
  35036. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  35037. {
  35038. triggerOnMouseDown = isTriggeredOnMouseDown;
  35039. }
  35040. void Button::clicked()
  35041. {
  35042. }
  35043. void Button::clicked (const ModifierKeys& /*modifiers*/)
  35044. {
  35045. clicked();
  35046. }
  35047. static const int clickMessageId = 0x2f3f4f99;
  35048. void Button::triggerClick()
  35049. {
  35050. postCommandMessage (clickMessageId);
  35051. }
  35052. void Button::internalClickCallback (const ModifierKeys& modifiers)
  35053. {
  35054. if (clickTogglesState)
  35055. setToggleState ((radioGroupId != 0) || ! lastToggleState, false);
  35056. sendClickMessage (modifiers);
  35057. }
  35058. void Button::flashButtonState()
  35059. {
  35060. if (isEnabled())
  35061. {
  35062. needsToRelease = true;
  35063. setState (buttonDown);
  35064. getRepeatTimer().startTimer (100);
  35065. }
  35066. }
  35067. void Button::handleCommandMessage (int commandId)
  35068. {
  35069. if (commandId == clickMessageId)
  35070. {
  35071. if (isEnabled())
  35072. {
  35073. flashButtonState();
  35074. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35075. }
  35076. }
  35077. else
  35078. {
  35079. Component::handleCommandMessage (commandId);
  35080. }
  35081. }
  35082. void Button::addButtonListener (Listener* const newListener)
  35083. {
  35084. buttonListeners.add (newListener);
  35085. }
  35086. void Button::removeButtonListener (Listener* const listener)
  35087. {
  35088. buttonListeners.remove (listener);
  35089. }
  35090. void Button::sendClickMessage (const ModifierKeys& modifiers)
  35091. {
  35092. Component::BailOutChecker checker (this);
  35093. if (commandManagerToUse != 0 && commandID != 0)
  35094. {
  35095. ApplicationCommandTarget::InvocationInfo info (commandID);
  35096. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  35097. info.originatingComponent = this;
  35098. commandManagerToUse->invoke (info, true);
  35099. }
  35100. clicked (modifiers);
  35101. if (! checker.shouldBailOut())
  35102. buttonListeners.callChecked (checker, &ButtonListener::buttonClicked, this); // (can't use Button::Listener due to idiotic VC2005 bug)
  35103. }
  35104. void Button::sendStateMessage()
  35105. {
  35106. Component::BailOutChecker checker (this);
  35107. buttonStateChanged();
  35108. if (! checker.shouldBailOut())
  35109. buttonListeners.callChecked (checker, &ButtonListener::buttonStateChanged, this);
  35110. }
  35111. void Button::paint (Graphics& g)
  35112. {
  35113. if (needsToRelease && isEnabled())
  35114. {
  35115. needsToRelease = false;
  35116. needsRepainting = true;
  35117. }
  35118. paintButton (g, isOver(), isDown());
  35119. }
  35120. void Button::mouseEnter (const MouseEvent& e)
  35121. {
  35122. updateState (&e);
  35123. }
  35124. void Button::mouseExit (const MouseEvent& e)
  35125. {
  35126. updateState (&e);
  35127. }
  35128. void Button::mouseDown (const MouseEvent& e)
  35129. {
  35130. updateState (&e);
  35131. if (isDown())
  35132. {
  35133. if (autoRepeatDelay >= 0)
  35134. getRepeatTimer().startTimer (autoRepeatDelay);
  35135. if (triggerOnMouseDown)
  35136. internalClickCallback (e.mods);
  35137. }
  35138. }
  35139. void Button::mouseUp (const MouseEvent& e)
  35140. {
  35141. const bool wasDown = isDown();
  35142. updateState (&e);
  35143. if (wasDown && isOver() && ! triggerOnMouseDown)
  35144. internalClickCallback (e.mods);
  35145. }
  35146. void Button::mouseDrag (const MouseEvent& e)
  35147. {
  35148. const ButtonState oldState = buttonState;
  35149. updateState (&e);
  35150. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  35151. getRepeatTimer().startTimer (autoRepeatSpeed);
  35152. }
  35153. void Button::focusGained (FocusChangeType)
  35154. {
  35155. updateState (0);
  35156. repaint();
  35157. }
  35158. void Button::focusLost (FocusChangeType)
  35159. {
  35160. updateState (0);
  35161. repaint();
  35162. }
  35163. void Button::setVisible (bool shouldBeVisible)
  35164. {
  35165. if (shouldBeVisible != isVisible())
  35166. {
  35167. Component::setVisible (shouldBeVisible);
  35168. if (! shouldBeVisible)
  35169. needsToRelease = false;
  35170. updateState (0);
  35171. }
  35172. else
  35173. {
  35174. Component::setVisible (shouldBeVisible);
  35175. }
  35176. }
  35177. void Button::parentHierarchyChanged()
  35178. {
  35179. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  35180. if (newKeySource != keySource.getComponent())
  35181. {
  35182. if (keySource != 0)
  35183. keySource->removeKeyListener (this);
  35184. keySource = newKeySource;
  35185. if (keySource != 0)
  35186. keySource->addKeyListener (this);
  35187. }
  35188. }
  35189. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  35190. const int commandID_,
  35191. const bool generateTooltip_)
  35192. {
  35193. commandID = commandID_;
  35194. generateTooltip = generateTooltip_;
  35195. if (commandManagerToUse != commandManagerToUse_)
  35196. {
  35197. if (commandManagerToUse != 0)
  35198. commandManagerToUse->removeListener (this);
  35199. commandManagerToUse = commandManagerToUse_;
  35200. if (commandManagerToUse != 0)
  35201. commandManagerToUse->addListener (this);
  35202. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  35203. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  35204. // it is that this button represents, and the button will update its state to reflect this
  35205. // in the applicationCommandListChanged() method.
  35206. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  35207. }
  35208. if (commandManagerToUse != 0)
  35209. applicationCommandListChanged();
  35210. else
  35211. setEnabled (true);
  35212. }
  35213. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  35214. {
  35215. if (info.commandID == commandID
  35216. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  35217. {
  35218. flashButtonState();
  35219. }
  35220. }
  35221. void Button::applicationCommandListChanged()
  35222. {
  35223. if (commandManagerToUse != 0)
  35224. {
  35225. ApplicationCommandInfo info (0);
  35226. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  35227. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  35228. if (target != 0)
  35229. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  35230. }
  35231. }
  35232. void Button::addShortcut (const KeyPress& key)
  35233. {
  35234. if (key.isValid())
  35235. {
  35236. jassert (! isRegisteredForShortcut (key)); // already registered!
  35237. shortcuts.add (key);
  35238. parentHierarchyChanged();
  35239. }
  35240. }
  35241. void Button::clearShortcuts()
  35242. {
  35243. shortcuts.clear();
  35244. parentHierarchyChanged();
  35245. }
  35246. bool Button::isShortcutPressed() const
  35247. {
  35248. if (! isCurrentlyBlockedByAnotherModalComponent())
  35249. {
  35250. for (int i = shortcuts.size(); --i >= 0;)
  35251. if (shortcuts.getReference(i).isCurrentlyDown())
  35252. return true;
  35253. }
  35254. return false;
  35255. }
  35256. bool Button::isRegisteredForShortcut (const KeyPress& key) const
  35257. {
  35258. for (int i = shortcuts.size(); --i >= 0;)
  35259. if (key == shortcuts.getReference(i))
  35260. return true;
  35261. return false;
  35262. }
  35263. bool Button::keyStateChanged (const bool, Component*)
  35264. {
  35265. if (! isEnabled())
  35266. return false;
  35267. const bool wasDown = isKeyDown;
  35268. isKeyDown = isShortcutPressed();
  35269. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  35270. getRepeatTimer().startTimer (autoRepeatDelay);
  35271. updateState (0);
  35272. if (isEnabled() && wasDown && ! isKeyDown)
  35273. {
  35274. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35275. // (return immediately - this button may now have been deleted)
  35276. return true;
  35277. }
  35278. return wasDown || isKeyDown;
  35279. }
  35280. bool Button::keyPressed (const KeyPress&, Component*)
  35281. {
  35282. // returning true will avoid forwarding events for keys that we're using as shortcuts
  35283. return isShortcutPressed();
  35284. }
  35285. bool Button::keyPressed (const KeyPress& key)
  35286. {
  35287. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  35288. {
  35289. triggerClick();
  35290. return true;
  35291. }
  35292. return false;
  35293. }
  35294. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  35295. const int repeatMillisecs,
  35296. const int minimumDelayInMillisecs) throw()
  35297. {
  35298. autoRepeatDelay = initialDelayMillisecs;
  35299. autoRepeatSpeed = repeatMillisecs;
  35300. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  35301. }
  35302. void Button::repeatTimerCallback()
  35303. {
  35304. if (needsRepainting)
  35305. {
  35306. getRepeatTimer().stopTimer();
  35307. updateState (0);
  35308. needsRepainting = false;
  35309. }
  35310. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState (0) == buttonDown)))
  35311. {
  35312. int repeatSpeed = autoRepeatSpeed;
  35313. if (autoRepeatMinimumDelay >= 0)
  35314. {
  35315. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  35316. timeHeldDown *= timeHeldDown;
  35317. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  35318. }
  35319. repeatSpeed = jmax (1, repeatSpeed);
  35320. getRepeatTimer().startTimer (repeatSpeed);
  35321. const uint32 now = Time::getApproximateMillisecondCounter();
  35322. const int numTimesToCallback = (now > lastTimeCallbackTime) ? jmax (1, (int) (now - lastTimeCallbackTime) / repeatSpeed) : 1;
  35323. lastTimeCallbackTime = now;
  35324. Component::SafePointer<Component> deletionWatcher (this);
  35325. for (int i = numTimesToCallback; --i >= 0;)
  35326. {
  35327. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35328. if (deletionWatcher == 0 || ! isDown())
  35329. return;
  35330. }
  35331. }
  35332. else if (! needsToRelease)
  35333. {
  35334. getRepeatTimer().stopTimer();
  35335. }
  35336. }
  35337. Button::RepeatTimer& Button::getRepeatTimer()
  35338. {
  35339. if (repeatTimer == 0)
  35340. repeatTimer = new RepeatTimer (*this);
  35341. return *repeatTimer;
  35342. }
  35343. END_JUCE_NAMESPACE
  35344. /*** End of inlined file: juce_Button.cpp ***/
  35345. /*** Start of inlined file: juce_DrawableButton.cpp ***/
  35346. BEGIN_JUCE_NAMESPACE
  35347. DrawableButton::DrawableButton (const String& name,
  35348. const DrawableButton::ButtonStyle buttonStyle)
  35349. : Button (name),
  35350. style (buttonStyle),
  35351. edgeIndent (3)
  35352. {
  35353. if (buttonStyle == ImageOnButtonBackground)
  35354. {
  35355. backgroundOff = Colour (0xffbbbbff);
  35356. backgroundOn = Colour (0xff3333ff);
  35357. }
  35358. else
  35359. {
  35360. backgroundOff = Colours::transparentBlack;
  35361. backgroundOn = Colour (0xaabbbbff);
  35362. }
  35363. }
  35364. DrawableButton::~DrawableButton()
  35365. {
  35366. deleteImages();
  35367. }
  35368. void DrawableButton::deleteImages()
  35369. {
  35370. }
  35371. void DrawableButton::setImages (const Drawable* normal,
  35372. const Drawable* over,
  35373. const Drawable* down,
  35374. const Drawable* disabled,
  35375. const Drawable* normalOn,
  35376. const Drawable* overOn,
  35377. const Drawable* downOn,
  35378. const Drawable* disabledOn)
  35379. {
  35380. deleteImages();
  35381. jassert (normal != 0); // you really need to give it at least a normal image..
  35382. if (normal != 0)
  35383. normalImage = normal->createCopy();
  35384. if (over != 0)
  35385. overImage = over->createCopy();
  35386. if (down != 0)
  35387. downImage = down->createCopy();
  35388. if (disabled != 0)
  35389. disabledImage = disabled->createCopy();
  35390. if (normalOn != 0)
  35391. normalImageOn = normalOn->createCopy();
  35392. if (overOn != 0)
  35393. overImageOn = overOn->createCopy();
  35394. if (downOn != 0)
  35395. downImageOn = downOn->createCopy();
  35396. if (disabledOn != 0)
  35397. disabledImageOn = disabledOn->createCopy();
  35398. repaint();
  35399. }
  35400. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  35401. {
  35402. if (style != newStyle)
  35403. {
  35404. style = newStyle;
  35405. repaint();
  35406. }
  35407. }
  35408. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  35409. const Colour& toggledOnColour)
  35410. {
  35411. if (backgroundOff != toggledOffColour
  35412. || backgroundOn != toggledOnColour)
  35413. {
  35414. backgroundOff = toggledOffColour;
  35415. backgroundOn = toggledOnColour;
  35416. repaint();
  35417. }
  35418. }
  35419. const Colour& DrawableButton::getBackgroundColour() const throw()
  35420. {
  35421. return getToggleState() ? backgroundOn
  35422. : backgroundOff;
  35423. }
  35424. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  35425. {
  35426. edgeIndent = numPixelsIndent;
  35427. repaint();
  35428. }
  35429. void DrawableButton::paintButton (Graphics& g,
  35430. bool isMouseOverButton,
  35431. bool isButtonDown)
  35432. {
  35433. Rectangle<int> imageSpace;
  35434. if (style == ImageOnButtonBackground)
  35435. {
  35436. const int insetX = getWidth() / 4;
  35437. const int insetY = getHeight() / 4;
  35438. imageSpace.setBounds (insetX, insetY, getWidth() - insetX * 2, getHeight() - insetY * 2);
  35439. getLookAndFeel().drawButtonBackground (g, *this,
  35440. getBackgroundColour(),
  35441. isMouseOverButton,
  35442. isButtonDown);
  35443. }
  35444. else
  35445. {
  35446. g.fillAll (getBackgroundColour());
  35447. const int textH = (style == ImageAboveTextLabel)
  35448. ? jmin (16, proportionOfHeight (0.25f))
  35449. : 0;
  35450. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  35451. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  35452. imageSpace.setBounds (indentX, indentY,
  35453. getWidth() - indentX * 2,
  35454. getHeight() - indentY * 2 - textH);
  35455. if (textH > 0)
  35456. {
  35457. g.setFont ((float) textH);
  35458. g.setColour (findColour (DrawableButton::textColourId)
  35459. .withMultipliedAlpha (isEnabled() ? 1.0f : 0.4f));
  35460. g.drawFittedText (getButtonText(),
  35461. 2, getHeight() - textH - 1,
  35462. getWidth() - 4, textH,
  35463. Justification::centred, 1);
  35464. }
  35465. }
  35466. g.setImageResamplingQuality (Graphics::mediumResamplingQuality);
  35467. g.setOpacity (1.0f);
  35468. const Drawable* imageToDraw = 0;
  35469. if (isEnabled())
  35470. {
  35471. imageToDraw = getCurrentImage();
  35472. }
  35473. else
  35474. {
  35475. imageToDraw = getToggleState() ? disabledImageOn
  35476. : disabledImage;
  35477. if (imageToDraw == 0)
  35478. {
  35479. g.setOpacity (0.4f);
  35480. imageToDraw = getNormalImage();
  35481. }
  35482. }
  35483. if (imageToDraw != 0)
  35484. {
  35485. if (style == ImageRaw)
  35486. {
  35487. imageToDraw->draw (g, 1.0f);
  35488. }
  35489. else
  35490. {
  35491. imageToDraw->drawWithin (g,
  35492. imageSpace.getX(),
  35493. imageSpace.getY(),
  35494. imageSpace.getWidth(),
  35495. imageSpace.getHeight(),
  35496. RectanglePlacement::centred,
  35497. 1.0f);
  35498. }
  35499. }
  35500. }
  35501. const Drawable* DrawableButton::getCurrentImage() const throw()
  35502. {
  35503. if (isDown())
  35504. return getDownImage();
  35505. if (isOver())
  35506. return getOverImage();
  35507. return getNormalImage();
  35508. }
  35509. const Drawable* DrawableButton::getNormalImage() const throw()
  35510. {
  35511. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  35512. : normalImage;
  35513. }
  35514. const Drawable* DrawableButton::getOverImage() const throw()
  35515. {
  35516. const Drawable* d = normalImage;
  35517. if (getToggleState())
  35518. {
  35519. if (overImageOn != 0)
  35520. d = overImageOn;
  35521. else if (normalImageOn != 0)
  35522. d = normalImageOn;
  35523. else if (overImage != 0)
  35524. d = overImage;
  35525. }
  35526. else
  35527. {
  35528. if (overImage != 0)
  35529. d = overImage;
  35530. }
  35531. return d;
  35532. }
  35533. const Drawable* DrawableButton::getDownImage() const throw()
  35534. {
  35535. const Drawable* d = normalImage;
  35536. if (getToggleState())
  35537. {
  35538. if (downImageOn != 0)
  35539. d = downImageOn;
  35540. else if (overImageOn != 0)
  35541. d = overImageOn;
  35542. else if (normalImageOn != 0)
  35543. d = normalImageOn;
  35544. else if (downImage != 0)
  35545. d = downImage;
  35546. else
  35547. d = getOverImage();
  35548. }
  35549. else
  35550. {
  35551. if (downImage != 0)
  35552. d = downImage;
  35553. else
  35554. d = getOverImage();
  35555. }
  35556. return d;
  35557. }
  35558. END_JUCE_NAMESPACE
  35559. /*** End of inlined file: juce_DrawableButton.cpp ***/
  35560. /*** Start of inlined file: juce_HyperlinkButton.cpp ***/
  35561. BEGIN_JUCE_NAMESPACE
  35562. HyperlinkButton::HyperlinkButton (const String& linkText,
  35563. const URL& linkURL)
  35564. : Button (linkText),
  35565. url (linkURL),
  35566. font (14.0f, Font::underlined),
  35567. resizeFont (true),
  35568. justification (Justification::centred)
  35569. {
  35570. setMouseCursor (MouseCursor::PointingHandCursor);
  35571. setTooltip (linkURL.toString (false));
  35572. }
  35573. HyperlinkButton::~HyperlinkButton()
  35574. {
  35575. }
  35576. void HyperlinkButton::setFont (const Font& newFont,
  35577. const bool resizeToMatchComponentHeight,
  35578. const Justification& justificationType)
  35579. {
  35580. font = newFont;
  35581. resizeFont = resizeToMatchComponentHeight;
  35582. justification = justificationType;
  35583. repaint();
  35584. }
  35585. void HyperlinkButton::setURL (const URL& newURL) throw()
  35586. {
  35587. url = newURL;
  35588. setTooltip (newURL.toString (false));
  35589. }
  35590. const Font HyperlinkButton::getFontToUse() const
  35591. {
  35592. Font f (font);
  35593. if (resizeFont)
  35594. f.setHeight (getHeight() * 0.7f);
  35595. return f;
  35596. }
  35597. void HyperlinkButton::changeWidthToFitText()
  35598. {
  35599. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  35600. }
  35601. void HyperlinkButton::colourChanged()
  35602. {
  35603. repaint();
  35604. }
  35605. void HyperlinkButton::clicked()
  35606. {
  35607. if (url.isWellFormed())
  35608. url.launchInDefaultBrowser();
  35609. }
  35610. void HyperlinkButton::paintButton (Graphics& g,
  35611. bool isMouseOverButton,
  35612. bool isButtonDown)
  35613. {
  35614. const Colour textColour (findColour (textColourId));
  35615. if (isEnabled())
  35616. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  35617. : textColour);
  35618. else
  35619. g.setColour (textColour.withMultipliedAlpha (0.4f));
  35620. g.setFont (getFontToUse());
  35621. g.drawText (getButtonText(),
  35622. 2, 0, getWidth() - 2, getHeight(),
  35623. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  35624. true);
  35625. }
  35626. END_JUCE_NAMESPACE
  35627. /*** End of inlined file: juce_HyperlinkButton.cpp ***/
  35628. /*** Start of inlined file: juce_ImageButton.cpp ***/
  35629. BEGIN_JUCE_NAMESPACE
  35630. ImageButton::ImageButton (const String& text_)
  35631. : Button (text_),
  35632. scaleImageToFit (true),
  35633. preserveProportions (true),
  35634. alphaThreshold (0),
  35635. imageX (0),
  35636. imageY (0),
  35637. imageW (0),
  35638. imageH (0),
  35639. normalImage (0),
  35640. overImage (0),
  35641. downImage (0)
  35642. {
  35643. }
  35644. ImageButton::~ImageButton()
  35645. {
  35646. }
  35647. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  35648. const bool rescaleImagesWhenButtonSizeChanges,
  35649. const bool preserveImageProportions,
  35650. const Image& normalImage_,
  35651. const float imageOpacityWhenNormal,
  35652. const Colour& overlayColourWhenNormal,
  35653. const Image& overImage_,
  35654. const float imageOpacityWhenOver,
  35655. const Colour& overlayColourWhenOver,
  35656. const Image& downImage_,
  35657. const float imageOpacityWhenDown,
  35658. const Colour& overlayColourWhenDown,
  35659. const float hitTestAlphaThreshold)
  35660. {
  35661. normalImage = normalImage_;
  35662. overImage = overImage_;
  35663. downImage = downImage_;
  35664. if (resizeButtonNowToFitThisImage && normalImage.isValid())
  35665. {
  35666. imageW = normalImage.getWidth();
  35667. imageH = normalImage.getHeight();
  35668. setSize (imageW, imageH);
  35669. }
  35670. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  35671. preserveProportions = preserveImageProportions;
  35672. normalOpacity = imageOpacityWhenNormal;
  35673. normalOverlay = overlayColourWhenNormal;
  35674. overOpacity = imageOpacityWhenOver;
  35675. overOverlay = overlayColourWhenOver;
  35676. downOpacity = imageOpacityWhenDown;
  35677. downOverlay = overlayColourWhenDown;
  35678. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundToInt (255.0f * hitTestAlphaThreshold));
  35679. repaint();
  35680. }
  35681. const Image ImageButton::getCurrentImage() const
  35682. {
  35683. if (isDown() || getToggleState())
  35684. return getDownImage();
  35685. if (isOver())
  35686. return getOverImage();
  35687. return getNormalImage();
  35688. }
  35689. const Image ImageButton::getNormalImage() const
  35690. {
  35691. return normalImage;
  35692. }
  35693. const Image ImageButton::getOverImage() const
  35694. {
  35695. return overImage.isValid() ? overImage
  35696. : normalImage;
  35697. }
  35698. const Image ImageButton::getDownImage() const
  35699. {
  35700. return downImage.isValid() ? downImage
  35701. : getOverImage();
  35702. }
  35703. void ImageButton::paintButton (Graphics& g,
  35704. bool isMouseOverButton,
  35705. bool isButtonDown)
  35706. {
  35707. if (! isEnabled())
  35708. {
  35709. isMouseOverButton = false;
  35710. isButtonDown = false;
  35711. }
  35712. Image im (getCurrentImage());
  35713. if (im.isValid())
  35714. {
  35715. const int iw = im.getWidth();
  35716. const int ih = im.getHeight();
  35717. imageW = getWidth();
  35718. imageH = getHeight();
  35719. imageX = (imageW - iw) >> 1;
  35720. imageY = (imageH - ih) >> 1;
  35721. if (scaleImageToFit)
  35722. {
  35723. if (preserveProportions)
  35724. {
  35725. int newW, newH;
  35726. const float imRatio = ih / (float)iw;
  35727. const float destRatio = imageH / (float)imageW;
  35728. if (imRatio > destRatio)
  35729. {
  35730. newW = roundToInt (imageH / imRatio);
  35731. newH = imageH;
  35732. }
  35733. else
  35734. {
  35735. newW = imageW;
  35736. newH = roundToInt (imageW * imRatio);
  35737. }
  35738. imageX = (imageW - newW) / 2;
  35739. imageY = (imageH - newH) / 2;
  35740. imageW = newW;
  35741. imageH = newH;
  35742. }
  35743. else
  35744. {
  35745. imageX = 0;
  35746. imageY = 0;
  35747. }
  35748. }
  35749. if (! scaleImageToFit)
  35750. {
  35751. imageW = iw;
  35752. imageH = ih;
  35753. }
  35754. getLookAndFeel().drawImageButton (g, &im, imageX, imageY, imageW, imageH,
  35755. isButtonDown ? downOverlay
  35756. : (isMouseOverButton ? overOverlay
  35757. : normalOverlay),
  35758. isButtonDown ? downOpacity
  35759. : (isMouseOverButton ? overOpacity
  35760. : normalOpacity),
  35761. *this);
  35762. }
  35763. }
  35764. bool ImageButton::hitTest (int x, int y)
  35765. {
  35766. if (alphaThreshold == 0)
  35767. return true;
  35768. Image im (getCurrentImage());
  35769. return im.isNull() || (imageW > 0 && imageH > 0
  35770. && alphaThreshold < im.getPixelAt (((x - imageX) * im.getWidth()) / imageW,
  35771. ((y - imageY) * im.getHeight()) / imageH).getAlpha());
  35772. }
  35773. END_JUCE_NAMESPACE
  35774. /*** End of inlined file: juce_ImageButton.cpp ***/
  35775. /*** Start of inlined file: juce_ShapeButton.cpp ***/
  35776. BEGIN_JUCE_NAMESPACE
  35777. ShapeButton::ShapeButton (const String& text_,
  35778. const Colour& normalColour_,
  35779. const Colour& overColour_,
  35780. const Colour& downColour_)
  35781. : Button (text_),
  35782. normalColour (normalColour_),
  35783. overColour (overColour_),
  35784. downColour (downColour_),
  35785. maintainShapeProportions (false),
  35786. outlineWidth (0.0f)
  35787. {
  35788. }
  35789. ShapeButton::~ShapeButton()
  35790. {
  35791. }
  35792. void ShapeButton::setColours (const Colour& newNormalColour,
  35793. const Colour& newOverColour,
  35794. const Colour& newDownColour)
  35795. {
  35796. normalColour = newNormalColour;
  35797. overColour = newOverColour;
  35798. downColour = newDownColour;
  35799. }
  35800. void ShapeButton::setOutline (const Colour& newOutlineColour,
  35801. const float newOutlineWidth)
  35802. {
  35803. outlineColour = newOutlineColour;
  35804. outlineWidth = newOutlineWidth;
  35805. }
  35806. void ShapeButton::setShape (const Path& newShape,
  35807. const bool resizeNowToFitThisShape,
  35808. const bool maintainShapeProportions_,
  35809. const bool hasShadow)
  35810. {
  35811. shape = newShape;
  35812. maintainShapeProportions = maintainShapeProportions_;
  35813. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  35814. setComponentEffect ((hasShadow) ? &shadow : 0);
  35815. if (resizeNowToFitThisShape)
  35816. {
  35817. Rectangle<float> bounds (shape.getBounds());
  35818. if (hasShadow)
  35819. bounds.expand (4.0f, 4.0f);
  35820. shape.applyTransform (AffineTransform::translation (-bounds.getX(), -bounds.getY()));
  35821. setSize (1 + (int) (bounds.getWidth() + outlineWidth),
  35822. 1 + (int) (bounds.getHeight() + outlineWidth));
  35823. }
  35824. }
  35825. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  35826. {
  35827. if (! isEnabled())
  35828. {
  35829. isMouseOverButton = false;
  35830. isButtonDown = false;
  35831. }
  35832. g.setColour ((isButtonDown) ? downColour
  35833. : (isMouseOverButton) ? overColour
  35834. : normalColour);
  35835. int w = getWidth();
  35836. int h = getHeight();
  35837. if (getComponentEffect() != 0)
  35838. {
  35839. w -= 4;
  35840. h -= 4;
  35841. }
  35842. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  35843. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  35844. w - offset - outlineWidth,
  35845. h - offset - outlineWidth,
  35846. maintainShapeProportions));
  35847. g.fillPath (shape, trans);
  35848. if (outlineWidth > 0.0f)
  35849. {
  35850. g.setColour (outlineColour);
  35851. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  35852. }
  35853. }
  35854. END_JUCE_NAMESPACE
  35855. /*** End of inlined file: juce_ShapeButton.cpp ***/
  35856. /*** Start of inlined file: juce_TextButton.cpp ***/
  35857. BEGIN_JUCE_NAMESPACE
  35858. TextButton::TextButton (const String& name,
  35859. const String& toolTip)
  35860. : Button (name)
  35861. {
  35862. setTooltip (toolTip);
  35863. }
  35864. TextButton::~TextButton()
  35865. {
  35866. }
  35867. void TextButton::paintButton (Graphics& g,
  35868. bool isMouseOverButton,
  35869. bool isButtonDown)
  35870. {
  35871. getLookAndFeel().drawButtonBackground (g, *this,
  35872. findColour (getToggleState() ? buttonOnColourId
  35873. : buttonColourId),
  35874. isMouseOverButton,
  35875. isButtonDown);
  35876. getLookAndFeel().drawButtonText (g, *this,
  35877. isMouseOverButton,
  35878. isButtonDown);
  35879. }
  35880. void TextButton::colourChanged()
  35881. {
  35882. repaint();
  35883. }
  35884. const Font TextButton::getFont()
  35885. {
  35886. return Font (jmin (15.0f, getHeight() * 0.6f));
  35887. }
  35888. void TextButton::changeWidthToFitText (const int newHeight)
  35889. {
  35890. if (newHeight >= 0)
  35891. setSize (jmax (1, getWidth()), newHeight);
  35892. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  35893. getHeight());
  35894. }
  35895. END_JUCE_NAMESPACE
  35896. /*** End of inlined file: juce_TextButton.cpp ***/
  35897. /*** Start of inlined file: juce_ToggleButton.cpp ***/
  35898. BEGIN_JUCE_NAMESPACE
  35899. ToggleButton::ToggleButton (const String& buttonText)
  35900. : Button (buttonText)
  35901. {
  35902. setClickingTogglesState (true);
  35903. }
  35904. ToggleButton::~ToggleButton()
  35905. {
  35906. }
  35907. void ToggleButton::paintButton (Graphics& g,
  35908. bool isMouseOverButton,
  35909. bool isButtonDown)
  35910. {
  35911. getLookAndFeel().drawToggleButton (g, *this,
  35912. isMouseOverButton,
  35913. isButtonDown);
  35914. }
  35915. void ToggleButton::changeWidthToFitText()
  35916. {
  35917. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  35918. }
  35919. void ToggleButton::colourChanged()
  35920. {
  35921. repaint();
  35922. }
  35923. END_JUCE_NAMESPACE
  35924. /*** End of inlined file: juce_ToggleButton.cpp ***/
  35925. /*** Start of inlined file: juce_ToolbarButton.cpp ***/
  35926. BEGIN_JUCE_NAMESPACE
  35927. ToolbarButton::ToolbarButton (const int itemId_,
  35928. const String& buttonText,
  35929. Drawable* const normalImage_,
  35930. Drawable* const toggledOnImage_)
  35931. : ToolbarItemComponent (itemId_, buttonText, true),
  35932. normalImage (normalImage_),
  35933. toggledOnImage (toggledOnImage_)
  35934. {
  35935. jassert (normalImage_ != 0);
  35936. }
  35937. ToolbarButton::~ToolbarButton()
  35938. {
  35939. }
  35940. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth,
  35941. bool /*isToolbarVertical*/,
  35942. int& preferredSize,
  35943. int& minSize, int& maxSize)
  35944. {
  35945. preferredSize = minSize = maxSize = toolbarDepth;
  35946. return true;
  35947. }
  35948. void ToolbarButton::paintButtonArea (Graphics& g,
  35949. int width, int height,
  35950. bool /*isMouseOver*/,
  35951. bool /*isMouseDown*/)
  35952. {
  35953. Drawable* d = normalImage;
  35954. if (getToggleState() && toggledOnImage != 0)
  35955. d = toggledOnImage;
  35956. if (! isEnabled())
  35957. {
  35958. Image im (Image::ARGB, width, height, true);
  35959. {
  35960. Graphics g2 (im);
  35961. d->drawWithin (g2, 0, 0, width, height, RectanglePlacement::centred, 1.0f);
  35962. }
  35963. im.desaturate();
  35964. g.drawImageAt (im, 0, 0);
  35965. }
  35966. else
  35967. {
  35968. d->drawWithin (g, 0, 0, width, height, RectanglePlacement::centred, 1.0f);
  35969. }
  35970. }
  35971. void ToolbarButton::contentAreaChanged (const Rectangle<int>&)
  35972. {
  35973. }
  35974. END_JUCE_NAMESPACE
  35975. /*** End of inlined file: juce_ToolbarButton.cpp ***/
  35976. /*** Start of inlined file: juce_CodeDocument.cpp ***/
  35977. BEGIN_JUCE_NAMESPACE
  35978. class CodeDocumentLine
  35979. {
  35980. public:
  35981. CodeDocumentLine (const juce_wchar* const line_,
  35982. const int lineLength_,
  35983. const int numNewLineChars,
  35984. const int lineStartInFile_)
  35985. : line (line_, lineLength_),
  35986. lineStartInFile (lineStartInFile_),
  35987. lineLength (lineLength_),
  35988. lineLengthWithoutNewLines (lineLength_ - numNewLineChars)
  35989. {
  35990. }
  35991. ~CodeDocumentLine()
  35992. {
  35993. }
  35994. static void createLines (Array <CodeDocumentLine*>& newLines, const String& text)
  35995. {
  35996. const juce_wchar* const t = text;
  35997. int pos = 0;
  35998. while (t [pos] != 0)
  35999. {
  36000. const int startOfLine = pos;
  36001. int numNewLineChars = 0;
  36002. while (t[pos] != 0)
  36003. {
  36004. if (t[pos] == '\r')
  36005. {
  36006. ++numNewLineChars;
  36007. ++pos;
  36008. if (t[pos] == '\n')
  36009. {
  36010. ++numNewLineChars;
  36011. ++pos;
  36012. }
  36013. break;
  36014. }
  36015. if (t[pos] == '\n')
  36016. {
  36017. ++numNewLineChars;
  36018. ++pos;
  36019. break;
  36020. }
  36021. ++pos;
  36022. }
  36023. newLines.add (new CodeDocumentLine (t + startOfLine, pos - startOfLine,
  36024. numNewLineChars, startOfLine));
  36025. }
  36026. jassert (pos == text.length());
  36027. }
  36028. bool endsWithLineBreak() const throw()
  36029. {
  36030. return lineLengthWithoutNewLines != lineLength;
  36031. }
  36032. void updateLength() throw()
  36033. {
  36034. lineLengthWithoutNewLines = lineLength = line.length();
  36035. while (lineLengthWithoutNewLines > 0
  36036. && (line [lineLengthWithoutNewLines - 1] == '\n'
  36037. || line [lineLengthWithoutNewLines - 1] == '\r'))
  36038. {
  36039. --lineLengthWithoutNewLines;
  36040. }
  36041. }
  36042. String line;
  36043. int lineStartInFile, lineLength, lineLengthWithoutNewLines;
  36044. };
  36045. CodeDocument::Iterator::Iterator (CodeDocument* const document_)
  36046. : document (document_),
  36047. currentLine (document_->lines[0]),
  36048. line (0),
  36049. position (0)
  36050. {
  36051. }
  36052. CodeDocument::Iterator::Iterator (const CodeDocument::Iterator& other)
  36053. : document (other.document),
  36054. currentLine (other.currentLine),
  36055. line (other.line),
  36056. position (other.position)
  36057. {
  36058. }
  36059. CodeDocument::Iterator& CodeDocument::Iterator::operator= (const CodeDocument::Iterator& other) throw()
  36060. {
  36061. document = other.document;
  36062. currentLine = other.currentLine;
  36063. line = other.line;
  36064. position = other.position;
  36065. return *this;
  36066. }
  36067. CodeDocument::Iterator::~Iterator() throw()
  36068. {
  36069. }
  36070. juce_wchar CodeDocument::Iterator::nextChar()
  36071. {
  36072. if (currentLine == 0)
  36073. return 0;
  36074. jassert (currentLine == document->lines.getUnchecked (line));
  36075. const juce_wchar result = currentLine->line [position - currentLine->lineStartInFile];
  36076. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  36077. {
  36078. ++line;
  36079. currentLine = document->lines [line];
  36080. }
  36081. return result;
  36082. }
  36083. void CodeDocument::Iterator::skip()
  36084. {
  36085. if (currentLine != 0)
  36086. {
  36087. jassert (currentLine == document->lines.getUnchecked (line));
  36088. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  36089. {
  36090. ++line;
  36091. currentLine = document->lines [line];
  36092. }
  36093. }
  36094. }
  36095. void CodeDocument::Iterator::skipToEndOfLine()
  36096. {
  36097. if (currentLine != 0)
  36098. {
  36099. jassert (currentLine == document->lines.getUnchecked (line));
  36100. ++line;
  36101. currentLine = document->lines [line];
  36102. if (currentLine != 0)
  36103. position = currentLine->lineStartInFile;
  36104. else
  36105. position = document->getNumCharacters();
  36106. }
  36107. }
  36108. juce_wchar CodeDocument::Iterator::peekNextChar() const
  36109. {
  36110. if (currentLine == 0)
  36111. return 0;
  36112. jassert (currentLine == document->lines.getUnchecked (line));
  36113. return const_cast <const String&> (currentLine->line) [position - currentLine->lineStartInFile];
  36114. }
  36115. void CodeDocument::Iterator::skipWhitespace()
  36116. {
  36117. while (CharacterFunctions::isWhitespace (peekNextChar()))
  36118. skip();
  36119. }
  36120. bool CodeDocument::Iterator::isEOF() const throw()
  36121. {
  36122. return currentLine == 0;
  36123. }
  36124. CodeDocument::Position::Position() throw()
  36125. : owner (0), characterPos (0), line (0),
  36126. indexInLine (0), positionMaintained (false)
  36127. {
  36128. }
  36129. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  36130. const int line_, const int indexInLine_) throw()
  36131. : owner (const_cast <CodeDocument*> (ownerDocument)),
  36132. characterPos (0), line (line_),
  36133. indexInLine (indexInLine_), positionMaintained (false)
  36134. {
  36135. setLineAndIndex (line_, indexInLine_);
  36136. }
  36137. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  36138. const int characterPos_) throw()
  36139. : owner (const_cast <CodeDocument*> (ownerDocument)),
  36140. positionMaintained (false)
  36141. {
  36142. setPosition (characterPos_);
  36143. }
  36144. CodeDocument::Position::Position (const Position& other) throw()
  36145. : owner (other.owner), characterPos (other.characterPos), line (other.line),
  36146. indexInLine (other.indexInLine), positionMaintained (false)
  36147. {
  36148. jassert (*this == other);
  36149. }
  36150. CodeDocument::Position::~Position()
  36151. {
  36152. setPositionMaintained (false);
  36153. }
  36154. CodeDocument::Position& CodeDocument::Position::operator= (const Position& other)
  36155. {
  36156. if (this != &other)
  36157. {
  36158. const bool wasPositionMaintained = positionMaintained;
  36159. if (owner != other.owner)
  36160. setPositionMaintained (false);
  36161. owner = other.owner;
  36162. line = other.line;
  36163. indexInLine = other.indexInLine;
  36164. characterPos = other.characterPos;
  36165. setPositionMaintained (wasPositionMaintained);
  36166. jassert (*this == other);
  36167. }
  36168. return *this;
  36169. }
  36170. bool CodeDocument::Position::operator== (const Position& other) const throw()
  36171. {
  36172. jassert ((characterPos == other.characterPos)
  36173. == (line == other.line && indexInLine == other.indexInLine));
  36174. return characterPos == other.characterPos
  36175. && line == other.line
  36176. && indexInLine == other.indexInLine
  36177. && owner == other.owner;
  36178. }
  36179. bool CodeDocument::Position::operator!= (const Position& other) const throw()
  36180. {
  36181. return ! operator== (other);
  36182. }
  36183. void CodeDocument::Position::setLineAndIndex (const int newLine, const int newIndexInLine)
  36184. {
  36185. jassert (owner != 0);
  36186. if (owner->lines.size() == 0)
  36187. {
  36188. line = 0;
  36189. indexInLine = 0;
  36190. characterPos = 0;
  36191. }
  36192. else
  36193. {
  36194. if (newLine >= owner->lines.size())
  36195. {
  36196. line = owner->lines.size() - 1;
  36197. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36198. jassert (l != 0);
  36199. indexInLine = l->lineLengthWithoutNewLines;
  36200. characterPos = l->lineStartInFile + indexInLine;
  36201. }
  36202. else
  36203. {
  36204. line = jmax (0, newLine);
  36205. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36206. jassert (l != 0);
  36207. if (l->lineLengthWithoutNewLines > 0)
  36208. indexInLine = jlimit (0, l->lineLengthWithoutNewLines, newIndexInLine);
  36209. else
  36210. indexInLine = 0;
  36211. characterPos = l->lineStartInFile + indexInLine;
  36212. }
  36213. }
  36214. }
  36215. void CodeDocument::Position::setPosition (const int newPosition)
  36216. {
  36217. jassert (owner != 0);
  36218. line = 0;
  36219. indexInLine = 0;
  36220. characterPos = 0;
  36221. if (newPosition > 0)
  36222. {
  36223. int lineStart = 0;
  36224. int lineEnd = owner->lines.size();
  36225. for (;;)
  36226. {
  36227. if (lineEnd - lineStart < 4)
  36228. {
  36229. for (int i = lineStart; i < lineEnd; ++i)
  36230. {
  36231. CodeDocumentLine* const l = owner->lines.getUnchecked (i);
  36232. int index = newPosition - l->lineStartInFile;
  36233. if (index >= 0 && (index < l->lineLength || i == lineEnd - 1))
  36234. {
  36235. line = i;
  36236. indexInLine = jmin (l->lineLengthWithoutNewLines, index);
  36237. characterPos = l->lineStartInFile + indexInLine;
  36238. }
  36239. }
  36240. break;
  36241. }
  36242. else
  36243. {
  36244. const int midIndex = (lineStart + lineEnd + 1) / 2;
  36245. CodeDocumentLine* const mid = owner->lines.getUnchecked (midIndex);
  36246. if (newPosition >= mid->lineStartInFile)
  36247. lineStart = midIndex;
  36248. else
  36249. lineEnd = midIndex;
  36250. }
  36251. }
  36252. }
  36253. }
  36254. void CodeDocument::Position::moveBy (int characterDelta)
  36255. {
  36256. jassert (owner != 0);
  36257. if (characterDelta == 1)
  36258. {
  36259. setPosition (getPosition());
  36260. // If moving right, make sure we don't get stuck between the \r and \n characters..
  36261. if (line < owner->lines.size())
  36262. {
  36263. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36264. if (indexInLine + characterDelta < l->lineLength
  36265. && indexInLine + characterDelta >= l->lineLengthWithoutNewLines + 1)
  36266. ++characterDelta;
  36267. }
  36268. }
  36269. setPosition (characterPos + characterDelta);
  36270. }
  36271. const CodeDocument::Position CodeDocument::Position::movedBy (const int characterDelta) const
  36272. {
  36273. CodeDocument::Position p (*this);
  36274. p.moveBy (characterDelta);
  36275. return p;
  36276. }
  36277. const CodeDocument::Position CodeDocument::Position::movedByLines (const int deltaLines) const
  36278. {
  36279. CodeDocument::Position p (*this);
  36280. p.setLineAndIndex (getLineNumber() + deltaLines, getIndexInLine());
  36281. return p;
  36282. }
  36283. const juce_wchar CodeDocument::Position::getCharacter() const
  36284. {
  36285. const CodeDocumentLine* const l = owner->lines [line];
  36286. return l == 0 ? 0 : l->line [getIndexInLine()];
  36287. }
  36288. const String CodeDocument::Position::getLineText() const
  36289. {
  36290. const CodeDocumentLine* const l = owner->lines [line];
  36291. return l == 0 ? String::empty : l->line;
  36292. }
  36293. void CodeDocument::Position::setPositionMaintained (const bool isMaintained)
  36294. {
  36295. if (isMaintained != positionMaintained)
  36296. {
  36297. positionMaintained = isMaintained;
  36298. if (owner != 0)
  36299. {
  36300. if (isMaintained)
  36301. {
  36302. jassert (! owner->positionsToMaintain.contains (this));
  36303. owner->positionsToMaintain.add (this);
  36304. }
  36305. else
  36306. {
  36307. // If this happens, you may have deleted the document while there are Position objects that are still using it...
  36308. jassert (owner->positionsToMaintain.contains (this));
  36309. owner->positionsToMaintain.removeValue (this);
  36310. }
  36311. }
  36312. }
  36313. }
  36314. CodeDocument::CodeDocument()
  36315. : undoManager (std::numeric_limits<int>::max(), 10000),
  36316. currentActionIndex (0),
  36317. indexOfSavedState (-1),
  36318. maximumLineLength (-1),
  36319. newLineChars ("\r\n")
  36320. {
  36321. }
  36322. CodeDocument::~CodeDocument()
  36323. {
  36324. }
  36325. const String CodeDocument::getAllContent() const
  36326. {
  36327. return getTextBetween (Position (this, 0),
  36328. Position (this, lines.size(), 0));
  36329. }
  36330. const String CodeDocument::getTextBetween (const Position& start, const Position& end) const
  36331. {
  36332. if (end.getPosition() <= start.getPosition())
  36333. return String::empty;
  36334. const int startLine = start.getLineNumber();
  36335. const int endLine = end.getLineNumber();
  36336. if (startLine == endLine)
  36337. {
  36338. CodeDocumentLine* const line = lines [startLine];
  36339. return (line == 0) ? String::empty : line->line.substring (start.getIndexInLine(), end.getIndexInLine());
  36340. }
  36341. String result;
  36342. result.preallocateStorage (end.getPosition() - start.getPosition() + 4);
  36343. String::Concatenator concatenator (result);
  36344. const int maxLine = jmin (lines.size() - 1, endLine);
  36345. for (int i = jmax (0, startLine); i <= maxLine; ++i)
  36346. {
  36347. const CodeDocumentLine* line = lines.getUnchecked(i);
  36348. int len = line->lineLength;
  36349. if (i == startLine)
  36350. {
  36351. const int index = start.getIndexInLine();
  36352. concatenator.append (line->line.substring (index, len));
  36353. }
  36354. else if (i == endLine)
  36355. {
  36356. len = end.getIndexInLine();
  36357. concatenator.append (line->line.substring (0, len));
  36358. }
  36359. else
  36360. {
  36361. concatenator.append (line->line);
  36362. }
  36363. }
  36364. return result;
  36365. }
  36366. int CodeDocument::getNumCharacters() const throw()
  36367. {
  36368. const CodeDocumentLine* const lastLine = lines.getLast();
  36369. return (lastLine == 0) ? 0 : lastLine->lineStartInFile + lastLine->lineLength;
  36370. }
  36371. const String CodeDocument::getLine (const int lineIndex) const throw()
  36372. {
  36373. const CodeDocumentLine* const line = lines [lineIndex];
  36374. return (line == 0) ? String::empty : line->line;
  36375. }
  36376. int CodeDocument::getMaximumLineLength() throw()
  36377. {
  36378. if (maximumLineLength < 0)
  36379. {
  36380. maximumLineLength = 0;
  36381. for (int i = lines.size(); --i >= 0;)
  36382. maximumLineLength = jmax (maximumLineLength, lines.getUnchecked(i)->lineLength);
  36383. }
  36384. return maximumLineLength;
  36385. }
  36386. void CodeDocument::deleteSection (const Position& startPosition, const Position& endPosition)
  36387. {
  36388. remove (startPosition.getPosition(), endPosition.getPosition(), true);
  36389. }
  36390. void CodeDocument::insertText (const Position& position, const String& text)
  36391. {
  36392. insert (text, position.getPosition(), true);
  36393. }
  36394. void CodeDocument::replaceAllContent (const String& newContent)
  36395. {
  36396. remove (0, getNumCharacters(), true);
  36397. insert (newContent, 0, true);
  36398. }
  36399. bool CodeDocument::loadFromStream (InputStream& stream)
  36400. {
  36401. replaceAllContent (stream.readEntireStreamAsString());
  36402. setSavePoint();
  36403. clearUndoHistory();
  36404. return true;
  36405. }
  36406. bool CodeDocument::writeToStream (OutputStream& stream)
  36407. {
  36408. for (int i = 0; i < lines.size(); ++i)
  36409. {
  36410. String temp (lines.getUnchecked(i)->line); // use a copy to avoid bloating the memory footprint of the stored string.
  36411. const char* utf8 = temp.toUTF8();
  36412. if (! stream.write (utf8, (int) strlen (utf8)))
  36413. return false;
  36414. }
  36415. return true;
  36416. }
  36417. void CodeDocument::setNewLineCharacters (const String& newLine) throw()
  36418. {
  36419. jassert (newLine == "\r\n" || newLine == "\n" || newLine == "\r");
  36420. newLineChars = newLine;
  36421. }
  36422. void CodeDocument::newTransaction()
  36423. {
  36424. undoManager.beginNewTransaction (String::empty);
  36425. }
  36426. void CodeDocument::undo()
  36427. {
  36428. newTransaction();
  36429. undoManager.undo();
  36430. }
  36431. void CodeDocument::redo()
  36432. {
  36433. undoManager.redo();
  36434. }
  36435. void CodeDocument::clearUndoHistory()
  36436. {
  36437. undoManager.clearUndoHistory();
  36438. }
  36439. void CodeDocument::setSavePoint() throw()
  36440. {
  36441. indexOfSavedState = currentActionIndex;
  36442. }
  36443. bool CodeDocument::hasChangedSinceSavePoint() const throw()
  36444. {
  36445. return currentActionIndex != indexOfSavedState;
  36446. }
  36447. static int getCodeCharacterCategory (const juce_wchar character) throw()
  36448. {
  36449. return (CharacterFunctions::isLetterOrDigit (character) || character == '_')
  36450. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  36451. }
  36452. const CodeDocument::Position CodeDocument::findWordBreakAfter (const Position& position) const throw()
  36453. {
  36454. Position p (position);
  36455. const int maxDistance = 256;
  36456. int i = 0;
  36457. while (i < maxDistance
  36458. && CharacterFunctions::isWhitespace (p.getCharacter())
  36459. && (i == 0 || (p.getCharacter() != '\n'
  36460. && p.getCharacter() != '\r')))
  36461. {
  36462. ++i;
  36463. p.moveBy (1);
  36464. }
  36465. if (i == 0)
  36466. {
  36467. const int type = getCodeCharacterCategory (p.getCharacter());
  36468. while (i < maxDistance && type == getCodeCharacterCategory (p.getCharacter()))
  36469. {
  36470. ++i;
  36471. p.moveBy (1);
  36472. }
  36473. while (i < maxDistance
  36474. && CharacterFunctions::isWhitespace (p.getCharacter())
  36475. && (i == 0 || (p.getCharacter() != '\n'
  36476. && p.getCharacter() != '\r')))
  36477. {
  36478. ++i;
  36479. p.moveBy (1);
  36480. }
  36481. }
  36482. return p;
  36483. }
  36484. const CodeDocument::Position CodeDocument::findWordBreakBefore (const Position& position) const throw()
  36485. {
  36486. Position p (position);
  36487. const int maxDistance = 256;
  36488. int i = 0;
  36489. bool stoppedAtLineStart = false;
  36490. while (i < maxDistance)
  36491. {
  36492. const juce_wchar c = p.movedBy (-1).getCharacter();
  36493. if (c == '\r' || c == '\n')
  36494. {
  36495. stoppedAtLineStart = true;
  36496. if (i > 0)
  36497. break;
  36498. }
  36499. if (! CharacterFunctions::isWhitespace (c))
  36500. break;
  36501. p.moveBy (-1);
  36502. ++i;
  36503. }
  36504. if (i < maxDistance && ! stoppedAtLineStart)
  36505. {
  36506. const int type = getCodeCharacterCategory (p.movedBy (-1).getCharacter());
  36507. while (i < maxDistance && type == getCodeCharacterCategory (p.movedBy (-1).getCharacter()))
  36508. {
  36509. p.moveBy (-1);
  36510. ++i;
  36511. }
  36512. }
  36513. return p;
  36514. }
  36515. void CodeDocument::checkLastLineStatus()
  36516. {
  36517. while (lines.size() > 0
  36518. && lines.getLast()->lineLength == 0
  36519. && (lines.size() == 1 || ! lines.getUnchecked (lines.size() - 2)->endsWithLineBreak()))
  36520. {
  36521. // remove any empty lines at the end if the preceding line doesn't end in a newline.
  36522. lines.removeLast();
  36523. }
  36524. const CodeDocumentLine* const lastLine = lines.getLast();
  36525. if (lastLine != 0 && lastLine->endsWithLineBreak())
  36526. {
  36527. // check that there's an empty line at the end if the preceding one ends in a newline..
  36528. lines.add (new CodeDocumentLine (String::empty, 0, 0, lastLine->lineStartInFile + lastLine->lineLength));
  36529. }
  36530. }
  36531. void CodeDocument::addListener (CodeDocument::Listener* const listener) throw()
  36532. {
  36533. listeners.add (listener);
  36534. }
  36535. void CodeDocument::removeListener (CodeDocument::Listener* const listener) throw()
  36536. {
  36537. listeners.remove (listener);
  36538. }
  36539. void CodeDocument::sendListenerChangeMessage (const int startLine, const int endLine)
  36540. {
  36541. Position startPos (this, startLine, 0);
  36542. Position endPos (this, endLine, 0);
  36543. listeners.call (&CodeDocument::Listener::codeDocumentChanged, startPos, endPos);
  36544. }
  36545. class CodeDocumentInsertAction : public UndoableAction
  36546. {
  36547. CodeDocument& owner;
  36548. const String text;
  36549. int insertPos;
  36550. CodeDocumentInsertAction (const CodeDocumentInsertAction&);
  36551. CodeDocumentInsertAction& operator= (const CodeDocumentInsertAction&);
  36552. public:
  36553. CodeDocumentInsertAction (CodeDocument& owner_, const String& text_, const int insertPos_) throw()
  36554. : owner (owner_),
  36555. text (text_),
  36556. insertPos (insertPos_)
  36557. {
  36558. }
  36559. ~CodeDocumentInsertAction() {}
  36560. bool perform()
  36561. {
  36562. owner.currentActionIndex++;
  36563. owner.insert (text, insertPos, false);
  36564. return true;
  36565. }
  36566. bool undo()
  36567. {
  36568. owner.currentActionIndex--;
  36569. owner.remove (insertPos, insertPos + text.length(), false);
  36570. return true;
  36571. }
  36572. int getSizeInUnits() { return text.length() + 32; }
  36573. };
  36574. void CodeDocument::insert (const String& text, const int insertPos, const bool undoable)
  36575. {
  36576. if (text.isEmpty())
  36577. return;
  36578. if (undoable)
  36579. {
  36580. undoManager.perform (new CodeDocumentInsertAction (*this, text, insertPos));
  36581. }
  36582. else
  36583. {
  36584. Position pos (this, insertPos);
  36585. const int firstAffectedLine = pos.getLineNumber();
  36586. int lastAffectedLine = firstAffectedLine + 1;
  36587. CodeDocumentLine* const firstLine = lines [firstAffectedLine];
  36588. String textInsideOriginalLine (text);
  36589. if (firstLine != 0)
  36590. {
  36591. const int index = pos.getIndexInLine();
  36592. textInsideOriginalLine = firstLine->line.substring (0, index)
  36593. + textInsideOriginalLine
  36594. + firstLine->line.substring (index);
  36595. }
  36596. maximumLineLength = -1;
  36597. Array <CodeDocumentLine*> newLines;
  36598. CodeDocumentLine::createLines (newLines, textInsideOriginalLine);
  36599. jassert (newLines.size() > 0);
  36600. CodeDocumentLine* const newFirstLine = newLines.getUnchecked (0);
  36601. newFirstLine->lineStartInFile = firstLine != 0 ? firstLine->lineStartInFile : 0;
  36602. lines.set (firstAffectedLine, newFirstLine);
  36603. if (newLines.size() > 1)
  36604. {
  36605. for (int i = 1; i < newLines.size(); ++i)
  36606. {
  36607. CodeDocumentLine* const l = newLines.getUnchecked (i);
  36608. lines.insert (firstAffectedLine + i, l);
  36609. }
  36610. lastAffectedLine = lines.size();
  36611. }
  36612. int i, lineStart = newFirstLine->lineStartInFile;
  36613. for (i = firstAffectedLine; i < lines.size(); ++i)
  36614. {
  36615. CodeDocumentLine* const l = lines.getUnchecked (i);
  36616. l->lineStartInFile = lineStart;
  36617. lineStart += l->lineLength;
  36618. }
  36619. checkLastLineStatus();
  36620. const int newTextLength = text.length();
  36621. for (i = 0; i < positionsToMaintain.size(); ++i)
  36622. {
  36623. CodeDocument::Position* const p = positionsToMaintain.getUnchecked(i);
  36624. if (p->getPosition() >= insertPos)
  36625. p->setPosition (p->getPosition() + newTextLength);
  36626. }
  36627. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36628. }
  36629. }
  36630. class CodeDocumentDeleteAction : public UndoableAction
  36631. {
  36632. CodeDocument& owner;
  36633. int startPos, endPos;
  36634. String removedText;
  36635. CodeDocumentDeleteAction (const CodeDocumentDeleteAction&);
  36636. CodeDocumentDeleteAction& operator= (const CodeDocumentDeleteAction&);
  36637. public:
  36638. CodeDocumentDeleteAction (CodeDocument& owner_, const int startPos_, const int endPos_) throw()
  36639. : owner (owner_),
  36640. startPos (startPos_),
  36641. endPos (endPos_)
  36642. {
  36643. removedText = owner.getTextBetween (CodeDocument::Position (&owner, startPos),
  36644. CodeDocument::Position (&owner, endPos));
  36645. }
  36646. ~CodeDocumentDeleteAction() {}
  36647. bool perform()
  36648. {
  36649. owner.currentActionIndex++;
  36650. owner.remove (startPos, endPos, false);
  36651. return true;
  36652. }
  36653. bool undo()
  36654. {
  36655. owner.currentActionIndex--;
  36656. owner.insert (removedText, startPos, false);
  36657. return true;
  36658. }
  36659. int getSizeInUnits() { return removedText.length() + 32; }
  36660. };
  36661. void CodeDocument::remove (const int startPos, const int endPos, const bool undoable)
  36662. {
  36663. if (endPos <= startPos)
  36664. return;
  36665. if (undoable)
  36666. {
  36667. undoManager.perform (new CodeDocumentDeleteAction (*this, startPos, endPos));
  36668. }
  36669. else
  36670. {
  36671. Position startPosition (this, startPos);
  36672. Position endPosition (this, endPos);
  36673. maximumLineLength = -1;
  36674. const int firstAffectedLine = startPosition.getLineNumber();
  36675. const int endLine = endPosition.getLineNumber();
  36676. int lastAffectedLine = firstAffectedLine + 1;
  36677. CodeDocumentLine* const firstLine = lines.getUnchecked (firstAffectedLine);
  36678. if (firstAffectedLine == endLine)
  36679. {
  36680. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36681. + firstLine->line.substring (endPosition.getIndexInLine());
  36682. firstLine->updateLength();
  36683. }
  36684. else
  36685. {
  36686. lastAffectedLine = lines.size();
  36687. CodeDocumentLine* const lastLine = lines.getUnchecked (endLine);
  36688. jassert (lastLine != 0);
  36689. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36690. + lastLine->line.substring (endPosition.getIndexInLine());
  36691. firstLine->updateLength();
  36692. int numLinesToRemove = endLine - firstAffectedLine;
  36693. lines.removeRange (firstAffectedLine + 1, numLinesToRemove);
  36694. }
  36695. int i;
  36696. for (i = firstAffectedLine + 1; i < lines.size(); ++i)
  36697. {
  36698. CodeDocumentLine* const l = lines.getUnchecked (i);
  36699. const CodeDocumentLine* const previousLine = lines.getUnchecked (i - 1);
  36700. l->lineStartInFile = previousLine->lineStartInFile + previousLine->lineLength;
  36701. }
  36702. checkLastLineStatus();
  36703. const int totalChars = getNumCharacters();
  36704. for (i = 0; i < positionsToMaintain.size(); ++i)
  36705. {
  36706. CodeDocument::Position* p = positionsToMaintain.getUnchecked(i);
  36707. if (p->getPosition() > startPosition.getPosition())
  36708. p->setPosition (jmax (startPos, p->getPosition() + startPos - endPos));
  36709. if (p->getPosition() > totalChars)
  36710. p->setPosition (totalChars);
  36711. }
  36712. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36713. }
  36714. }
  36715. END_JUCE_NAMESPACE
  36716. /*** End of inlined file: juce_CodeDocument.cpp ***/
  36717. /*** Start of inlined file: juce_CodeEditorComponent.cpp ***/
  36718. BEGIN_JUCE_NAMESPACE
  36719. class CodeEditorComponent::CaretComponent : public Component,
  36720. public Timer
  36721. {
  36722. public:
  36723. CaretComponent (CodeEditorComponent& owner_)
  36724. : owner (owner_)
  36725. {
  36726. setAlwaysOnTop (true);
  36727. setInterceptsMouseClicks (false, false);
  36728. }
  36729. ~CaretComponent()
  36730. {
  36731. }
  36732. void paint (Graphics& g)
  36733. {
  36734. g.fillAll (findColour (CodeEditorComponent::caretColourId));
  36735. }
  36736. void timerCallback()
  36737. {
  36738. setVisible (shouldBeShown() && ! isVisible());
  36739. }
  36740. void updatePosition()
  36741. {
  36742. startTimer (400);
  36743. setVisible (shouldBeShown());
  36744. setBounds (owner.getCharacterBounds (owner.getCaretPos()).withWidth (2));
  36745. }
  36746. private:
  36747. CodeEditorComponent& owner;
  36748. CaretComponent (const CaretComponent&);
  36749. CaretComponent& operator= (const CaretComponent&);
  36750. bool shouldBeShown() const { return owner.hasKeyboardFocus (true); }
  36751. };
  36752. class CodeEditorComponent::CodeEditorLine
  36753. {
  36754. public:
  36755. CodeEditorLine() throw()
  36756. : highlightColumnStart (0), highlightColumnEnd (0)
  36757. {
  36758. }
  36759. ~CodeEditorLine() throw()
  36760. {
  36761. }
  36762. bool update (CodeDocument& document, int lineNum,
  36763. CodeDocument::Iterator& source,
  36764. CodeTokeniser* analyser, const int spacesPerTab,
  36765. const CodeDocument::Position& selectionStart,
  36766. const CodeDocument::Position& selectionEnd)
  36767. {
  36768. Array <SyntaxToken> newTokens;
  36769. newTokens.ensureStorageAllocated (8);
  36770. if (analyser == 0)
  36771. {
  36772. newTokens.add (SyntaxToken (document.getLine (lineNum), -1));
  36773. }
  36774. else if (lineNum < document.getNumLines())
  36775. {
  36776. const CodeDocument::Position pos (&document, lineNum, 0);
  36777. createTokens (pos.getPosition(), pos.getLineText(),
  36778. source, analyser, newTokens);
  36779. }
  36780. replaceTabsWithSpaces (newTokens, spacesPerTab);
  36781. int newHighlightStart = 0;
  36782. int newHighlightEnd = 0;
  36783. if (selectionStart.getLineNumber() <= lineNum && selectionEnd.getLineNumber() >= lineNum)
  36784. {
  36785. const String line (document.getLine (lineNum));
  36786. CodeDocument::Position lineStart (&document, lineNum, 0), lineEnd (&document, lineNum + 1, 0);
  36787. newHighlightStart = indexToColumn (jmax (0, selectionStart.getPosition() - lineStart.getPosition()),
  36788. line, spacesPerTab);
  36789. newHighlightEnd = indexToColumn (jmin (lineEnd.getPosition() - lineStart.getPosition(), selectionEnd.getPosition() - lineStart.getPosition()),
  36790. line, spacesPerTab);
  36791. }
  36792. if (newHighlightStart != highlightColumnStart || newHighlightEnd != highlightColumnEnd)
  36793. {
  36794. highlightColumnStart = newHighlightStart;
  36795. highlightColumnEnd = newHighlightEnd;
  36796. }
  36797. else
  36798. {
  36799. if (tokens.size() == newTokens.size())
  36800. {
  36801. bool allTheSame = true;
  36802. for (int i = newTokens.size(); --i >= 0;)
  36803. {
  36804. if (tokens.getReference(i) != newTokens.getReference(i))
  36805. {
  36806. allTheSame = false;
  36807. break;
  36808. }
  36809. }
  36810. if (allTheSame)
  36811. return false;
  36812. }
  36813. }
  36814. tokens.swapWithArray (newTokens);
  36815. return true;
  36816. }
  36817. void draw (CodeEditorComponent& owner, Graphics& g, const Font& font,
  36818. float x, const int y, const int baselineOffset, const int lineHeight,
  36819. const Colour& highlightColour) const
  36820. {
  36821. if (highlightColumnStart < highlightColumnEnd)
  36822. {
  36823. g.setColour (highlightColour);
  36824. g.fillRect (roundToInt (x + highlightColumnStart * owner.getCharWidth()), y,
  36825. roundToInt ((highlightColumnEnd - highlightColumnStart) * owner.getCharWidth()), lineHeight);
  36826. }
  36827. int lastType = std::numeric_limits<int>::min();
  36828. for (int i = 0; i < tokens.size(); ++i)
  36829. {
  36830. SyntaxToken& token = tokens.getReference(i);
  36831. if (lastType != token.tokenType)
  36832. {
  36833. lastType = token.tokenType;
  36834. g.setColour (owner.getColourForTokenType (lastType));
  36835. }
  36836. g.drawSingleLineText (token.text, roundToInt (x), y + baselineOffset);
  36837. if (i < tokens.size() - 1)
  36838. {
  36839. if (token.width < 0)
  36840. token.width = font.getStringWidthFloat (token.text);
  36841. x += token.width;
  36842. }
  36843. }
  36844. }
  36845. private:
  36846. struct SyntaxToken
  36847. {
  36848. String text;
  36849. int tokenType;
  36850. float width;
  36851. SyntaxToken (const String& text_, const int type) throw()
  36852. : text (text_), tokenType (type), width (-1.0f)
  36853. {
  36854. }
  36855. bool operator!= (const SyntaxToken& other) const throw()
  36856. {
  36857. return text != other.text || tokenType != other.tokenType;
  36858. }
  36859. };
  36860. Array <SyntaxToken> tokens;
  36861. int highlightColumnStart, highlightColumnEnd;
  36862. static void createTokens (int startPosition, const String& lineText,
  36863. CodeDocument::Iterator& source,
  36864. CodeTokeniser* analyser,
  36865. Array <SyntaxToken>& newTokens)
  36866. {
  36867. CodeDocument::Iterator lastIterator (source);
  36868. const int lineLength = lineText.length();
  36869. for (;;)
  36870. {
  36871. int tokenType = analyser->readNextToken (source);
  36872. int tokenStart = lastIterator.getPosition();
  36873. int tokenEnd = source.getPosition();
  36874. if (tokenEnd <= tokenStart)
  36875. break;
  36876. tokenEnd -= startPosition;
  36877. if (tokenEnd > 0)
  36878. {
  36879. tokenStart -= startPosition;
  36880. newTokens.add (SyntaxToken (lineText.substring (jmax (0, tokenStart), tokenEnd),
  36881. tokenType));
  36882. if (tokenEnd >= lineLength)
  36883. break;
  36884. }
  36885. lastIterator = source;
  36886. }
  36887. source = lastIterator;
  36888. }
  36889. static void replaceTabsWithSpaces (Array <SyntaxToken>& tokens, const int spacesPerTab)
  36890. {
  36891. int x = 0;
  36892. for (int i = 0; i < tokens.size(); ++i)
  36893. {
  36894. SyntaxToken& t = tokens.getReference(i);
  36895. for (;;)
  36896. {
  36897. int tabPos = t.text.indexOfChar ('\t');
  36898. if (tabPos < 0)
  36899. break;
  36900. const int spacesNeeded = spacesPerTab - ((tabPos + x) % spacesPerTab);
  36901. t.text = t.text.replaceSection (tabPos, 1, String::repeatedString (" ", spacesNeeded));
  36902. }
  36903. x += t.text.length();
  36904. }
  36905. }
  36906. int indexToColumn (int index, const String& line, int spacesPerTab) const throw()
  36907. {
  36908. jassert (index <= line.length());
  36909. int col = 0;
  36910. for (int i = 0; i < index; ++i)
  36911. {
  36912. if (line[i] != '\t')
  36913. ++col;
  36914. else
  36915. col += spacesPerTab - (col % spacesPerTab);
  36916. }
  36917. return col;
  36918. }
  36919. };
  36920. CodeEditorComponent::CodeEditorComponent (CodeDocument& document_,
  36921. CodeTokeniser* const codeTokeniser_)
  36922. : document (document_),
  36923. firstLineOnScreen (0),
  36924. gutter (5),
  36925. spacesPerTab (4),
  36926. lineHeight (0),
  36927. linesOnScreen (0),
  36928. columnsOnScreen (0),
  36929. scrollbarThickness (16),
  36930. columnToTryToMaintain (-1),
  36931. useSpacesForTabs (false),
  36932. xOffset (0),
  36933. codeTokeniser (codeTokeniser_)
  36934. {
  36935. caretPos = CodeDocument::Position (&document_, 0, 0);
  36936. caretPos.setPositionMaintained (true);
  36937. selectionStart = CodeDocument::Position (&document_, 0, 0);
  36938. selectionStart.setPositionMaintained (true);
  36939. selectionEnd = CodeDocument::Position (&document_, 0, 0);
  36940. selectionEnd.setPositionMaintained (true);
  36941. setOpaque (true);
  36942. setMouseCursor (MouseCursor (MouseCursor::IBeamCursor));
  36943. setWantsKeyboardFocus (true);
  36944. addAndMakeVisible (verticalScrollBar = new ScrollBar (true));
  36945. verticalScrollBar->setSingleStepSize (1.0);
  36946. addAndMakeVisible (horizontalScrollBar = new ScrollBar (false));
  36947. horizontalScrollBar->setSingleStepSize (1.0);
  36948. addAndMakeVisible (caret = new CaretComponent (*this));
  36949. Font f (12.0f);
  36950. f.setTypefaceName (Font::getDefaultMonospacedFontName());
  36951. setFont (f);
  36952. resetToDefaultColours();
  36953. verticalScrollBar->addListener (this);
  36954. horizontalScrollBar->addListener (this);
  36955. document.addListener (this);
  36956. }
  36957. CodeEditorComponent::~CodeEditorComponent()
  36958. {
  36959. document.removeListener (this);
  36960. deleteAllChildren();
  36961. }
  36962. void CodeEditorComponent::loadContent (const String& newContent)
  36963. {
  36964. clearCachedIterators (0);
  36965. document.replaceAllContent (newContent);
  36966. document.clearUndoHistory();
  36967. document.setSavePoint();
  36968. caretPos.setPosition (0);
  36969. selectionStart.setPosition (0);
  36970. selectionEnd.setPosition (0);
  36971. scrollToLine (0);
  36972. }
  36973. bool CodeEditorComponent::isTextInputActive() const
  36974. {
  36975. return true;
  36976. }
  36977. void CodeEditorComponent::codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  36978. const CodeDocument::Position& affectedTextEnd)
  36979. {
  36980. clearCachedIterators (affectedTextStart.getLineNumber());
  36981. triggerAsyncUpdate();
  36982. caret->updatePosition();
  36983. columnToTryToMaintain = -1;
  36984. if (affectedTextEnd.getPosition() >= selectionStart.getPosition()
  36985. && affectedTextStart.getPosition() <= selectionEnd.getPosition())
  36986. deselectAll();
  36987. if (caretPos.getPosition() > affectedTextEnd.getPosition()
  36988. || caretPos.getPosition() < affectedTextStart.getPosition())
  36989. moveCaretTo (affectedTextStart, false);
  36990. updateScrollBars();
  36991. }
  36992. void CodeEditorComponent::resized()
  36993. {
  36994. linesOnScreen = (getHeight() - scrollbarThickness) / lineHeight;
  36995. columnsOnScreen = (int) ((getWidth() - scrollbarThickness) / charWidth);
  36996. lines.clear();
  36997. rebuildLineTokens();
  36998. caret->updatePosition();
  36999. verticalScrollBar->setBounds (getWidth() - scrollbarThickness, 0, scrollbarThickness, getHeight() - scrollbarThickness);
  37000. horizontalScrollBar->setBounds (gutter, getHeight() - scrollbarThickness, getWidth() - scrollbarThickness - gutter, scrollbarThickness);
  37001. updateScrollBars();
  37002. }
  37003. void CodeEditorComponent::paint (Graphics& g)
  37004. {
  37005. handleUpdateNowIfNeeded();
  37006. g.fillAll (findColour (CodeEditorComponent::backgroundColourId));
  37007. g.reduceClipRegion (gutter, 0, verticalScrollBar->getX() - gutter, horizontalScrollBar->getY());
  37008. g.setFont (font);
  37009. const int baselineOffset = (int) font.getAscent();
  37010. const Colour defaultColour (findColour (CodeEditorComponent::defaultTextColourId));
  37011. const Colour highlightColour (findColour (CodeEditorComponent::highlightColourId));
  37012. const Rectangle<int> clip (g.getClipBounds());
  37013. const int firstLineToDraw = jmax (0, clip.getY() / lineHeight);
  37014. const int lastLineToDraw = jmin (lines.size(), clip.getBottom() / lineHeight + 1);
  37015. for (int j = firstLineToDraw; j < lastLineToDraw; ++j)
  37016. {
  37017. lines.getUnchecked(j)->draw (*this, g, font,
  37018. (float) (gutter - xOffset * charWidth),
  37019. lineHeight * j, baselineOffset, lineHeight,
  37020. highlightColour);
  37021. }
  37022. }
  37023. void CodeEditorComponent::setScrollbarThickness (const int thickness)
  37024. {
  37025. if (scrollbarThickness != thickness)
  37026. {
  37027. scrollbarThickness = thickness;
  37028. resized();
  37029. }
  37030. }
  37031. void CodeEditorComponent::handleAsyncUpdate()
  37032. {
  37033. rebuildLineTokens();
  37034. }
  37035. void CodeEditorComponent::rebuildLineTokens()
  37036. {
  37037. cancelPendingUpdate();
  37038. const int numNeeded = linesOnScreen + 1;
  37039. int minLineToRepaint = numNeeded;
  37040. int maxLineToRepaint = 0;
  37041. if (numNeeded != lines.size())
  37042. {
  37043. lines.clear();
  37044. for (int i = numNeeded; --i >= 0;)
  37045. lines.add (new CodeEditorLine());
  37046. minLineToRepaint = 0;
  37047. maxLineToRepaint = numNeeded;
  37048. }
  37049. jassert (numNeeded == lines.size());
  37050. CodeDocument::Iterator source (&document);
  37051. getIteratorForPosition (CodeDocument::Position (&document, firstLineOnScreen, 0).getPosition(), source);
  37052. for (int i = 0; i < numNeeded; ++i)
  37053. {
  37054. CodeEditorLine* const line = lines.getUnchecked(i);
  37055. if (line->update (document, firstLineOnScreen + i, source, codeTokeniser, spacesPerTab,
  37056. selectionStart, selectionEnd))
  37057. {
  37058. minLineToRepaint = jmin (minLineToRepaint, i);
  37059. maxLineToRepaint = jmax (maxLineToRepaint, i);
  37060. }
  37061. }
  37062. if (minLineToRepaint <= maxLineToRepaint)
  37063. {
  37064. repaint (gutter, lineHeight * minLineToRepaint - 1,
  37065. verticalScrollBar->getX() - gutter,
  37066. lineHeight * (1 + maxLineToRepaint - minLineToRepaint) + 2);
  37067. }
  37068. }
  37069. void CodeEditorComponent::moveCaretTo (const CodeDocument::Position& newPos, const bool highlighting)
  37070. {
  37071. caretPos = newPos;
  37072. columnToTryToMaintain = -1;
  37073. if (highlighting)
  37074. {
  37075. if (dragType == notDragging)
  37076. {
  37077. if (abs (caretPos.getPosition() - selectionStart.getPosition())
  37078. < abs (caretPos.getPosition() - selectionEnd.getPosition()))
  37079. dragType = draggingSelectionStart;
  37080. else
  37081. dragType = draggingSelectionEnd;
  37082. }
  37083. if (dragType == draggingSelectionStart)
  37084. {
  37085. selectionStart = caretPos;
  37086. if (selectionEnd.getPosition() < selectionStart.getPosition())
  37087. {
  37088. const CodeDocument::Position temp (selectionStart);
  37089. selectionStart = selectionEnd;
  37090. selectionEnd = temp;
  37091. dragType = draggingSelectionEnd;
  37092. }
  37093. }
  37094. else
  37095. {
  37096. selectionEnd = caretPos;
  37097. if (selectionEnd.getPosition() < selectionStart.getPosition())
  37098. {
  37099. const CodeDocument::Position temp (selectionStart);
  37100. selectionStart = selectionEnd;
  37101. selectionEnd = temp;
  37102. dragType = draggingSelectionStart;
  37103. }
  37104. }
  37105. triggerAsyncUpdate();
  37106. }
  37107. else
  37108. {
  37109. deselectAll();
  37110. }
  37111. caret->updatePosition();
  37112. scrollToKeepCaretOnScreen();
  37113. updateScrollBars();
  37114. }
  37115. void CodeEditorComponent::deselectAll()
  37116. {
  37117. if (selectionStart != selectionEnd)
  37118. triggerAsyncUpdate();
  37119. selectionStart = caretPos;
  37120. selectionEnd = caretPos;
  37121. }
  37122. void CodeEditorComponent::updateScrollBars()
  37123. {
  37124. verticalScrollBar->setRangeLimits (0, jmax (document.getNumLines(), firstLineOnScreen + linesOnScreen));
  37125. verticalScrollBar->setCurrentRange (firstLineOnScreen, linesOnScreen);
  37126. horizontalScrollBar->setRangeLimits (0, jmax ((double) document.getMaximumLineLength(), xOffset + columnsOnScreen));
  37127. horizontalScrollBar->setCurrentRange (xOffset, columnsOnScreen);
  37128. }
  37129. void CodeEditorComponent::scrollToLineInternal (int newFirstLineOnScreen)
  37130. {
  37131. newFirstLineOnScreen = jlimit (0, jmax (0, document.getNumLines() - 1),
  37132. newFirstLineOnScreen);
  37133. if (newFirstLineOnScreen != firstLineOnScreen)
  37134. {
  37135. firstLineOnScreen = newFirstLineOnScreen;
  37136. caret->updatePosition();
  37137. updateCachedIterators (firstLineOnScreen);
  37138. triggerAsyncUpdate();
  37139. }
  37140. }
  37141. void CodeEditorComponent::scrollToColumnInternal (double column)
  37142. {
  37143. const double newOffset = jlimit (0.0, document.getMaximumLineLength() + 3.0, column);
  37144. if (xOffset != newOffset)
  37145. {
  37146. xOffset = newOffset;
  37147. caret->updatePosition();
  37148. repaint();
  37149. }
  37150. }
  37151. void CodeEditorComponent::scrollToLine (int newFirstLineOnScreen)
  37152. {
  37153. scrollToLineInternal (newFirstLineOnScreen);
  37154. updateScrollBars();
  37155. }
  37156. void CodeEditorComponent::scrollToColumn (int newFirstColumnOnScreen)
  37157. {
  37158. scrollToColumnInternal (newFirstColumnOnScreen);
  37159. updateScrollBars();
  37160. }
  37161. void CodeEditorComponent::scrollBy (int deltaLines)
  37162. {
  37163. scrollToLine (firstLineOnScreen + deltaLines);
  37164. }
  37165. void CodeEditorComponent::scrollToKeepCaretOnScreen()
  37166. {
  37167. if (caretPos.getLineNumber() < firstLineOnScreen)
  37168. scrollBy (caretPos.getLineNumber() - firstLineOnScreen);
  37169. else if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37170. scrollBy (caretPos.getLineNumber() - (firstLineOnScreen + linesOnScreen - 1));
  37171. const int column = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  37172. if (column >= xOffset + columnsOnScreen - 1)
  37173. scrollToColumn (column + 1 - columnsOnScreen);
  37174. else if (column < xOffset)
  37175. scrollToColumn (column);
  37176. }
  37177. const Rectangle<int> CodeEditorComponent::getCharacterBounds (const CodeDocument::Position& pos) const
  37178. {
  37179. return Rectangle<int> (roundToInt ((gutter - xOffset * charWidth) + indexToColumn (pos.getLineNumber(), pos.getIndexInLine()) * charWidth),
  37180. (pos.getLineNumber() - firstLineOnScreen) * lineHeight,
  37181. roundToInt (charWidth),
  37182. lineHeight);
  37183. }
  37184. const CodeDocument::Position CodeEditorComponent::getPositionAt (int x, int y)
  37185. {
  37186. const int line = y / lineHeight + firstLineOnScreen;
  37187. const int column = roundToInt ((x - (gutter - xOffset * charWidth)) / charWidth);
  37188. const int index = columnToIndex (line, column);
  37189. return CodeDocument::Position (&document, line, index);
  37190. }
  37191. void CodeEditorComponent::insertTextAtCaret (const String& newText)
  37192. {
  37193. document.deleteSection (selectionStart, selectionEnd);
  37194. if (newText.isNotEmpty())
  37195. document.insertText (caretPos, newText);
  37196. scrollToKeepCaretOnScreen();
  37197. }
  37198. void CodeEditorComponent::insertTabAtCaret()
  37199. {
  37200. if (CharacterFunctions::isWhitespace (caretPos.getCharacter())
  37201. && caretPos.getLineNumber() == caretPos.movedBy (1).getLineNumber())
  37202. {
  37203. moveCaretTo (document.findWordBreakAfter (caretPos), false);
  37204. }
  37205. if (useSpacesForTabs)
  37206. {
  37207. const int caretCol = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  37208. const int spacesNeeded = spacesPerTab - (caretCol % spacesPerTab);
  37209. insertTextAtCaret (String::repeatedString (" ", spacesNeeded));
  37210. }
  37211. else
  37212. {
  37213. insertTextAtCaret ("\t");
  37214. }
  37215. }
  37216. void CodeEditorComponent::cut()
  37217. {
  37218. insertTextAtCaret (String::empty);
  37219. }
  37220. void CodeEditorComponent::copy()
  37221. {
  37222. newTransaction();
  37223. const String selection (document.getTextBetween (selectionStart, selectionEnd));
  37224. if (selection.isNotEmpty())
  37225. SystemClipboard::copyTextToClipboard (selection);
  37226. }
  37227. void CodeEditorComponent::copyThenCut()
  37228. {
  37229. copy();
  37230. cut();
  37231. newTransaction();
  37232. }
  37233. void CodeEditorComponent::paste()
  37234. {
  37235. newTransaction();
  37236. const String clip (SystemClipboard::getTextFromClipboard());
  37237. if (clip.isNotEmpty())
  37238. insertTextAtCaret (clip);
  37239. newTransaction();
  37240. }
  37241. void CodeEditorComponent::cursorLeft (const bool moveInWholeWordSteps, const bool selecting)
  37242. {
  37243. newTransaction();
  37244. if (moveInWholeWordSteps)
  37245. moveCaretTo (document.findWordBreakBefore (caretPos), selecting);
  37246. else
  37247. moveCaretTo (caretPos.movedBy (-1), selecting);
  37248. }
  37249. void CodeEditorComponent::cursorRight (const bool moveInWholeWordSteps, const bool selecting)
  37250. {
  37251. newTransaction();
  37252. if (moveInWholeWordSteps)
  37253. moveCaretTo (document.findWordBreakAfter (caretPos), selecting);
  37254. else
  37255. moveCaretTo (caretPos.movedBy (1), selecting);
  37256. }
  37257. void CodeEditorComponent::moveLineDelta (const int delta, const bool selecting)
  37258. {
  37259. CodeDocument::Position pos (caretPos);
  37260. const int newLineNum = pos.getLineNumber() + delta;
  37261. if (columnToTryToMaintain < 0)
  37262. columnToTryToMaintain = indexToColumn (pos.getLineNumber(), pos.getIndexInLine());
  37263. pos.setLineAndIndex (newLineNum, columnToIndex (newLineNum, columnToTryToMaintain));
  37264. const int colToMaintain = columnToTryToMaintain;
  37265. moveCaretTo (pos, selecting);
  37266. columnToTryToMaintain = colToMaintain;
  37267. }
  37268. void CodeEditorComponent::cursorDown (const bool selecting)
  37269. {
  37270. newTransaction();
  37271. if (caretPos.getLineNumber() == document.getNumLines() - 1)
  37272. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37273. else
  37274. moveLineDelta (1, selecting);
  37275. }
  37276. void CodeEditorComponent::cursorUp (const bool selecting)
  37277. {
  37278. newTransaction();
  37279. if (caretPos.getLineNumber() == 0)
  37280. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37281. else
  37282. moveLineDelta (-1, selecting);
  37283. }
  37284. void CodeEditorComponent::pageDown (const bool selecting)
  37285. {
  37286. newTransaction();
  37287. scrollBy (jlimit (0, linesOnScreen, 1 + document.getNumLines() - firstLineOnScreen - linesOnScreen));
  37288. moveLineDelta (linesOnScreen, selecting);
  37289. }
  37290. void CodeEditorComponent::pageUp (const bool selecting)
  37291. {
  37292. newTransaction();
  37293. scrollBy (-linesOnScreen);
  37294. moveLineDelta (-linesOnScreen, selecting);
  37295. }
  37296. void CodeEditorComponent::scrollUp()
  37297. {
  37298. newTransaction();
  37299. scrollBy (1);
  37300. if (caretPos.getLineNumber() < firstLineOnScreen)
  37301. moveLineDelta (1, false);
  37302. }
  37303. void CodeEditorComponent::scrollDown()
  37304. {
  37305. newTransaction();
  37306. scrollBy (-1);
  37307. if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37308. moveLineDelta (-1, false);
  37309. }
  37310. void CodeEditorComponent::goToStartOfDocument (const bool selecting)
  37311. {
  37312. newTransaction();
  37313. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37314. }
  37315. static int findFirstNonWhitespaceChar (const String& line) throw()
  37316. {
  37317. const int len = line.length();
  37318. for (int i = 0; i < len; ++i)
  37319. if (! CharacterFunctions::isWhitespace (line [i]))
  37320. return i;
  37321. return 0;
  37322. }
  37323. void CodeEditorComponent::goToStartOfLine (const bool selecting)
  37324. {
  37325. newTransaction();
  37326. int index = findFirstNonWhitespaceChar (caretPos.getLineText());
  37327. if (index >= caretPos.getIndexInLine() && caretPos.getIndexInLine() > 0)
  37328. index = 0;
  37329. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), index), selecting);
  37330. }
  37331. void CodeEditorComponent::goToEndOfDocument (const bool selecting)
  37332. {
  37333. newTransaction();
  37334. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37335. }
  37336. void CodeEditorComponent::goToEndOfLine (const bool selecting)
  37337. {
  37338. newTransaction();
  37339. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), std::numeric_limits<int>::max()), selecting);
  37340. }
  37341. void CodeEditorComponent::backspace (const bool moveInWholeWordSteps)
  37342. {
  37343. if (moveInWholeWordSteps)
  37344. {
  37345. cut(); // in case something is already highlighted
  37346. moveCaretTo (document.findWordBreakBefore (caretPos), true);
  37347. }
  37348. else
  37349. {
  37350. if (selectionStart == selectionEnd)
  37351. selectionStart.moveBy (-1);
  37352. }
  37353. cut();
  37354. }
  37355. void CodeEditorComponent::deleteForward (const bool moveInWholeWordSteps)
  37356. {
  37357. if (moveInWholeWordSteps)
  37358. {
  37359. cut(); // in case something is already highlighted
  37360. moveCaretTo (document.findWordBreakAfter (caretPos), true);
  37361. }
  37362. else
  37363. {
  37364. if (selectionStart == selectionEnd)
  37365. selectionEnd.moveBy (1);
  37366. else
  37367. newTransaction();
  37368. }
  37369. cut();
  37370. }
  37371. void CodeEditorComponent::selectAll()
  37372. {
  37373. newTransaction();
  37374. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), false);
  37375. moveCaretTo (CodeDocument::Position (&document, 0, 0), true);
  37376. }
  37377. void CodeEditorComponent::undo()
  37378. {
  37379. document.undo();
  37380. scrollToKeepCaretOnScreen();
  37381. }
  37382. void CodeEditorComponent::redo()
  37383. {
  37384. document.redo();
  37385. scrollToKeepCaretOnScreen();
  37386. }
  37387. void CodeEditorComponent::newTransaction()
  37388. {
  37389. document.newTransaction();
  37390. startTimer (600);
  37391. }
  37392. void CodeEditorComponent::timerCallback()
  37393. {
  37394. newTransaction();
  37395. }
  37396. const Range<int> CodeEditorComponent::getHighlightedRegion() const
  37397. {
  37398. return Range<int> (selectionStart.getPosition(), selectionEnd.getPosition());
  37399. }
  37400. void CodeEditorComponent::setHighlightedRegion (const Range<int>& newRange)
  37401. {
  37402. moveCaretTo (CodeDocument::Position (&document, newRange.getStart()), false);
  37403. moveCaretTo (CodeDocument::Position (&document, newRange.getEnd()), true);
  37404. }
  37405. const String CodeEditorComponent::getTextInRange (const Range<int>& range) const
  37406. {
  37407. return document.getTextBetween (CodeDocument::Position (&document, range.getStart()),
  37408. CodeDocument::Position (&document, range.getEnd()));
  37409. }
  37410. bool CodeEditorComponent::keyPressed (const KeyPress& key)
  37411. {
  37412. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  37413. const bool shiftDown = key.getModifiers().isShiftDown();
  37414. if (key.isKeyCode (KeyPress::leftKey))
  37415. {
  37416. cursorLeft (moveInWholeWordSteps, shiftDown);
  37417. }
  37418. else if (key.isKeyCode (KeyPress::rightKey))
  37419. {
  37420. cursorRight (moveInWholeWordSteps, shiftDown);
  37421. }
  37422. else if (key.isKeyCode (KeyPress::upKey))
  37423. {
  37424. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37425. scrollDown();
  37426. #if JUCE_MAC
  37427. else if (key.getModifiers().isCommandDown())
  37428. goToStartOfDocument (shiftDown);
  37429. #endif
  37430. else
  37431. cursorUp (shiftDown);
  37432. }
  37433. else if (key.isKeyCode (KeyPress::downKey))
  37434. {
  37435. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37436. scrollUp();
  37437. #if JUCE_MAC
  37438. else if (key.getModifiers().isCommandDown())
  37439. goToEndOfDocument (shiftDown);
  37440. #endif
  37441. else
  37442. cursorDown (shiftDown);
  37443. }
  37444. else if (key.isKeyCode (KeyPress::pageDownKey))
  37445. {
  37446. pageDown (shiftDown);
  37447. }
  37448. else if (key.isKeyCode (KeyPress::pageUpKey))
  37449. {
  37450. pageUp (shiftDown);
  37451. }
  37452. else if (key.isKeyCode (KeyPress::homeKey))
  37453. {
  37454. if (moveInWholeWordSteps)
  37455. goToStartOfDocument (shiftDown);
  37456. else
  37457. goToStartOfLine (shiftDown);
  37458. }
  37459. else if (key.isKeyCode (KeyPress::endKey))
  37460. {
  37461. if (moveInWholeWordSteps)
  37462. goToEndOfDocument (shiftDown);
  37463. else
  37464. goToEndOfLine (shiftDown);
  37465. }
  37466. else if (key.isKeyCode (KeyPress::backspaceKey))
  37467. {
  37468. backspace (moveInWholeWordSteps);
  37469. }
  37470. else if (key.isKeyCode (KeyPress::deleteKey))
  37471. {
  37472. deleteForward (moveInWholeWordSteps);
  37473. }
  37474. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0))
  37475. {
  37476. copy();
  37477. }
  37478. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  37479. {
  37480. copyThenCut();
  37481. }
  37482. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0))
  37483. {
  37484. paste();
  37485. }
  37486. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  37487. {
  37488. undo();
  37489. }
  37490. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0)
  37491. || key == KeyPress ('z', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0))
  37492. {
  37493. redo();
  37494. }
  37495. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  37496. {
  37497. selectAll();
  37498. }
  37499. else if (key == KeyPress::tabKey || key.getTextCharacter() == '\t')
  37500. {
  37501. insertTabAtCaret();
  37502. }
  37503. else if (key == KeyPress::returnKey)
  37504. {
  37505. newTransaction();
  37506. insertTextAtCaret (document.getNewLineCharacters());
  37507. }
  37508. else if (key.isKeyCode (KeyPress::escapeKey))
  37509. {
  37510. newTransaction();
  37511. }
  37512. else if (key.getTextCharacter() >= ' ')
  37513. {
  37514. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  37515. }
  37516. else
  37517. {
  37518. return false;
  37519. }
  37520. return true;
  37521. }
  37522. void CodeEditorComponent::mouseDown (const MouseEvent& e)
  37523. {
  37524. newTransaction();
  37525. dragType = notDragging;
  37526. if (! e.mods.isPopupMenu())
  37527. {
  37528. beginDragAutoRepeat (100);
  37529. moveCaretTo (getPositionAt (e.x, e.y), e.mods.isShiftDown());
  37530. }
  37531. else
  37532. {
  37533. /*PopupMenu m;
  37534. addPopupMenuItems (m, &e);
  37535. const int result = m.show();
  37536. if (result != 0)
  37537. performPopupMenuAction (result);
  37538. */
  37539. }
  37540. }
  37541. void CodeEditorComponent::mouseDrag (const MouseEvent& e)
  37542. {
  37543. if (! e.mods.isPopupMenu())
  37544. moveCaretTo (getPositionAt (e.x, e.y), true);
  37545. }
  37546. void CodeEditorComponent::mouseUp (const MouseEvent&)
  37547. {
  37548. newTransaction();
  37549. beginDragAutoRepeat (0);
  37550. dragType = notDragging;
  37551. }
  37552. void CodeEditorComponent::mouseDoubleClick (const MouseEvent& e)
  37553. {
  37554. CodeDocument::Position tokenStart (getPositionAt (e.x, e.y));
  37555. CodeDocument::Position tokenEnd (tokenStart);
  37556. if (e.getNumberOfClicks() > 2)
  37557. {
  37558. tokenStart.setLineAndIndex (tokenStart.getLineNumber(), 0);
  37559. tokenEnd.setLineAndIndex (tokenStart.getLineNumber() + 1, 0);
  37560. }
  37561. else
  37562. {
  37563. while (CharacterFunctions::isLetterOrDigit (tokenEnd.getCharacter()))
  37564. tokenEnd.moveBy (1);
  37565. tokenStart = tokenEnd;
  37566. while (tokenStart.getIndexInLine() > 0
  37567. && CharacterFunctions::isLetterOrDigit (tokenStart.movedBy (-1).getCharacter()))
  37568. tokenStart.moveBy (-1);
  37569. }
  37570. moveCaretTo (tokenEnd, false);
  37571. moveCaretTo (tokenStart, true);
  37572. }
  37573. void CodeEditorComponent::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  37574. {
  37575. if ((verticalScrollBar->isVisible() && wheelIncrementY != 0)
  37576. || (horizontalScrollBar->isVisible() && wheelIncrementX != 0))
  37577. {
  37578. verticalScrollBar->mouseWheelMove (e, 0, wheelIncrementY);
  37579. horizontalScrollBar->mouseWheelMove (e, wheelIncrementX, 0);
  37580. }
  37581. else
  37582. {
  37583. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  37584. }
  37585. }
  37586. void CodeEditorComponent::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  37587. {
  37588. if (scrollBarThatHasMoved == verticalScrollBar)
  37589. scrollToLineInternal ((int) newRangeStart);
  37590. else
  37591. scrollToColumnInternal (newRangeStart);
  37592. }
  37593. void CodeEditorComponent::focusGained (FocusChangeType)
  37594. {
  37595. caret->updatePosition();
  37596. }
  37597. void CodeEditorComponent::focusLost (FocusChangeType)
  37598. {
  37599. caret->updatePosition();
  37600. }
  37601. void CodeEditorComponent::setTabSize (const int numSpaces, const bool insertSpaces)
  37602. {
  37603. useSpacesForTabs = insertSpaces;
  37604. if (spacesPerTab != numSpaces)
  37605. {
  37606. spacesPerTab = numSpaces;
  37607. triggerAsyncUpdate();
  37608. }
  37609. }
  37610. int CodeEditorComponent::indexToColumn (int lineNum, int index) const throw()
  37611. {
  37612. const String line (document.getLine (lineNum));
  37613. jassert (index <= line.length());
  37614. int col = 0;
  37615. for (int i = 0; i < index; ++i)
  37616. {
  37617. if (line[i] != '\t')
  37618. ++col;
  37619. else
  37620. col += getTabSize() - (col % getTabSize());
  37621. }
  37622. return col;
  37623. }
  37624. int CodeEditorComponent::columnToIndex (int lineNum, int column) const throw()
  37625. {
  37626. const String line (document.getLine (lineNum));
  37627. const int lineLength = line.length();
  37628. int i, col = 0;
  37629. for (i = 0; i < lineLength; ++i)
  37630. {
  37631. if (line[i] != '\t')
  37632. ++col;
  37633. else
  37634. col += getTabSize() - (col % getTabSize());
  37635. if (col > column)
  37636. break;
  37637. }
  37638. return i;
  37639. }
  37640. void CodeEditorComponent::setFont (const Font& newFont)
  37641. {
  37642. font = newFont;
  37643. charWidth = font.getStringWidthFloat ("0");
  37644. lineHeight = roundToInt (font.getHeight());
  37645. resized();
  37646. }
  37647. void CodeEditorComponent::resetToDefaultColours()
  37648. {
  37649. coloursForTokenCategories.clear();
  37650. if (codeTokeniser != 0)
  37651. {
  37652. for (int i = codeTokeniser->getTokenTypes().size(); --i >= 0;)
  37653. setColourForTokenType (i, codeTokeniser->getDefaultColour (i));
  37654. }
  37655. }
  37656. void CodeEditorComponent::setColourForTokenType (const int tokenType, const Colour& colour)
  37657. {
  37658. jassert (tokenType < 256);
  37659. while (coloursForTokenCategories.size() < tokenType)
  37660. coloursForTokenCategories.add (Colours::black);
  37661. coloursForTokenCategories.set (tokenType, colour);
  37662. repaint();
  37663. }
  37664. const Colour CodeEditorComponent::getColourForTokenType (const int tokenType) const
  37665. {
  37666. if (((unsigned int) tokenType) >= (unsigned int) coloursForTokenCategories.size())
  37667. return findColour (CodeEditorComponent::defaultTextColourId);
  37668. return coloursForTokenCategories.getReference (tokenType);
  37669. }
  37670. void CodeEditorComponent::clearCachedIterators (const int firstLineToBeInvalid)
  37671. {
  37672. int i;
  37673. for (i = cachedIterators.size(); --i >= 0;)
  37674. if (cachedIterators.getUnchecked (i)->getLine() < firstLineToBeInvalid)
  37675. break;
  37676. cachedIterators.removeRange (jmax (0, i - 1), cachedIterators.size());
  37677. }
  37678. void CodeEditorComponent::updateCachedIterators (int maxLineNum)
  37679. {
  37680. const int maxNumCachedPositions = 5000;
  37681. const int linesBetweenCachedSources = jmax (10, document.getNumLines() / maxNumCachedPositions);
  37682. if (cachedIterators.size() == 0)
  37683. cachedIterators.add (new CodeDocument::Iterator (&document));
  37684. if (codeTokeniser == 0)
  37685. return;
  37686. for (;;)
  37687. {
  37688. CodeDocument::Iterator* last = cachedIterators.getLast();
  37689. if (last->getLine() >= maxLineNum)
  37690. break;
  37691. CodeDocument::Iterator* t = new CodeDocument::Iterator (*last);
  37692. cachedIterators.add (t);
  37693. const int targetLine = last->getLine() + linesBetweenCachedSources;
  37694. for (;;)
  37695. {
  37696. codeTokeniser->readNextToken (*t);
  37697. if (t->getLine() >= targetLine)
  37698. break;
  37699. if (t->isEOF())
  37700. return;
  37701. }
  37702. }
  37703. }
  37704. void CodeEditorComponent::getIteratorForPosition (int position, CodeDocument::Iterator& source)
  37705. {
  37706. if (codeTokeniser == 0)
  37707. return;
  37708. for (int i = cachedIterators.size(); --i >= 0;)
  37709. {
  37710. CodeDocument::Iterator* t = cachedIterators.getUnchecked (i);
  37711. if (t->getPosition() <= position)
  37712. {
  37713. source = *t;
  37714. break;
  37715. }
  37716. }
  37717. while (source.getPosition() < position)
  37718. {
  37719. const CodeDocument::Iterator original (source);
  37720. codeTokeniser->readNextToken (source);
  37721. if (source.getPosition() > position || source.isEOF())
  37722. {
  37723. source = original;
  37724. break;
  37725. }
  37726. }
  37727. }
  37728. END_JUCE_NAMESPACE
  37729. /*** End of inlined file: juce_CodeEditorComponent.cpp ***/
  37730. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  37731. BEGIN_JUCE_NAMESPACE
  37732. CPlusPlusCodeTokeniser::CPlusPlusCodeTokeniser()
  37733. {
  37734. }
  37735. CPlusPlusCodeTokeniser::~CPlusPlusCodeTokeniser()
  37736. {
  37737. }
  37738. namespace CppTokeniser
  37739. {
  37740. static bool isIdentifierStart (const juce_wchar c) throw()
  37741. {
  37742. return CharacterFunctions::isLetter (c)
  37743. || c == '_' || c == '@';
  37744. }
  37745. static bool isIdentifierBody (const juce_wchar c) throw()
  37746. {
  37747. return CharacterFunctions::isLetterOrDigit (c)
  37748. || c == '_' || c == '@';
  37749. }
  37750. static bool isReservedKeyword (const juce_wchar* const token, const int tokenLength) throw()
  37751. {
  37752. static const juce_wchar* const keywords2Char[] =
  37753. { JUCE_T("if"), JUCE_T("do"), JUCE_T("or"), JUCE_T("id"), 0 };
  37754. static const juce_wchar* const keywords3Char[] =
  37755. { 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 };
  37756. static const juce_wchar* const keywords4Char[] =
  37757. { JUCE_T("bool"), JUCE_T("void"), JUCE_T("this"), JUCE_T("true"), JUCE_T("long"), JUCE_T("else"), JUCE_T("char"),
  37758. JUCE_T("enum"), JUCE_T("case"), JUCE_T("goto"), JUCE_T("auto"), 0 };
  37759. static const juce_wchar* const keywords5Char[] =
  37760. { JUCE_T("while"), JUCE_T("bitor"), JUCE_T("break"), JUCE_T("catch"), JUCE_T("class"), JUCE_T("compl"), JUCE_T("const"), JUCE_T("false"),
  37761. JUCE_T("float"), JUCE_T("short"), JUCE_T("throw"), JUCE_T("union"), JUCE_T("using"), JUCE_T("or_eq"), 0 };
  37762. static const juce_wchar* const keywords6Char[] =
  37763. { JUCE_T("return"), JUCE_T("struct"), JUCE_T("and_eq"), JUCE_T("bitand"), JUCE_T("delete"), JUCE_T("double"), JUCE_T("extern"),
  37764. JUCE_T("friend"), JUCE_T("inline"), JUCE_T("not_eq"), JUCE_T("public"), JUCE_T("sizeof"), JUCE_T("static"), JUCE_T("signed"),
  37765. JUCE_T("switch"), JUCE_T("typeid"), JUCE_T("wchar_t"), JUCE_T("xor_eq"), 0};
  37766. static const juce_wchar* const keywordsOther[] =
  37767. { JUCE_T("const_cast"), JUCE_T("continue"), JUCE_T("default"), JUCE_T("explicit"), JUCE_T("mutable"), JUCE_T("namespace"),
  37768. JUCE_T("operator"), JUCE_T("private"), JUCE_T("protected"), JUCE_T("register"), JUCE_T("reinterpret_cast"), JUCE_T("static_cast"),
  37769. JUCE_T("template"), JUCE_T("typedef"), JUCE_T("typename"), JUCE_T("unsigned"), JUCE_T("virtual"), JUCE_T("volatile"),
  37770. JUCE_T("@implementation"), JUCE_T("@interface"), JUCE_T("@end"), JUCE_T("@synthesize"), JUCE_T("@dynamic"), JUCE_T("@public"),
  37771. JUCE_T("@private"), JUCE_T("@property"), JUCE_T("@protected"), JUCE_T("@class"), 0 };
  37772. const juce_wchar* const* k;
  37773. switch (tokenLength)
  37774. {
  37775. case 2: k = keywords2Char; break;
  37776. case 3: k = keywords3Char; break;
  37777. case 4: k = keywords4Char; break;
  37778. case 5: k = keywords5Char; break;
  37779. case 6: k = keywords6Char; break;
  37780. default:
  37781. if (tokenLength < 2 || tokenLength > 16)
  37782. return false;
  37783. k = keywordsOther;
  37784. break;
  37785. }
  37786. int i = 0;
  37787. while (k[i] != 0)
  37788. {
  37789. if (k[i][0] == token[0] && CharacterFunctions::compare (k[i], token) == 0)
  37790. return true;
  37791. ++i;
  37792. }
  37793. return false;
  37794. }
  37795. static int parseIdentifier (CodeDocument::Iterator& source) throw()
  37796. {
  37797. int tokenLength = 0;
  37798. juce_wchar possibleIdentifier [19];
  37799. while (isIdentifierBody (source.peekNextChar()))
  37800. {
  37801. const juce_wchar c = source.nextChar();
  37802. if (tokenLength < numElementsInArray (possibleIdentifier) - 1)
  37803. possibleIdentifier [tokenLength] = c;
  37804. ++tokenLength;
  37805. }
  37806. if (tokenLength > 1 && tokenLength <= 16)
  37807. {
  37808. possibleIdentifier [tokenLength] = 0;
  37809. if (isReservedKeyword (possibleIdentifier, tokenLength))
  37810. return CPlusPlusCodeTokeniser::tokenType_builtInKeyword;
  37811. }
  37812. return CPlusPlusCodeTokeniser::tokenType_identifier;
  37813. }
  37814. static bool skipNumberSuffix (CodeDocument::Iterator& source)
  37815. {
  37816. const juce_wchar c = source.peekNextChar();
  37817. if (c == 'l' || c == 'L' || c == 'u' || c == 'U')
  37818. source.skip();
  37819. if (CharacterFunctions::isLetterOrDigit (source.peekNextChar()))
  37820. return false;
  37821. return true;
  37822. }
  37823. static bool isHexDigit (const juce_wchar c) throw()
  37824. {
  37825. return (c >= '0' && c <= '9')
  37826. || (c >= 'a' && c <= 'f')
  37827. || (c >= 'A' && c <= 'F');
  37828. }
  37829. static bool parseHexLiteral (CodeDocument::Iterator& source) throw()
  37830. {
  37831. if (source.nextChar() != '0')
  37832. return false;
  37833. juce_wchar c = source.nextChar();
  37834. if (c != 'x' && c != 'X')
  37835. return false;
  37836. int numDigits = 0;
  37837. while (isHexDigit (source.peekNextChar()))
  37838. {
  37839. ++numDigits;
  37840. source.skip();
  37841. }
  37842. if (numDigits == 0)
  37843. return false;
  37844. return skipNumberSuffix (source);
  37845. }
  37846. static bool isOctalDigit (const juce_wchar c) throw()
  37847. {
  37848. return c >= '0' && c <= '7';
  37849. }
  37850. static bool parseOctalLiteral (CodeDocument::Iterator& source) throw()
  37851. {
  37852. if (source.nextChar() != '0')
  37853. return false;
  37854. if (! isOctalDigit (source.nextChar()))
  37855. return false;
  37856. while (isOctalDigit (source.peekNextChar()))
  37857. source.skip();
  37858. return skipNumberSuffix (source);
  37859. }
  37860. static bool isDecimalDigit (const juce_wchar c) throw()
  37861. {
  37862. return c >= '0' && c <= '9';
  37863. }
  37864. static bool parseDecimalLiteral (CodeDocument::Iterator& source) throw()
  37865. {
  37866. int numChars = 0;
  37867. while (isDecimalDigit (source.peekNextChar()))
  37868. {
  37869. ++numChars;
  37870. source.skip();
  37871. }
  37872. if (numChars == 0)
  37873. return false;
  37874. return skipNumberSuffix (source);
  37875. }
  37876. static bool parseFloatLiteral (CodeDocument::Iterator& source) throw()
  37877. {
  37878. int numDigits = 0;
  37879. while (isDecimalDigit (source.peekNextChar()))
  37880. {
  37881. source.skip();
  37882. ++numDigits;
  37883. }
  37884. const bool hasPoint = (source.peekNextChar() == '.');
  37885. if (hasPoint)
  37886. {
  37887. source.skip();
  37888. while (isDecimalDigit (source.peekNextChar()))
  37889. {
  37890. source.skip();
  37891. ++numDigits;
  37892. }
  37893. }
  37894. if (numDigits == 0)
  37895. return false;
  37896. juce_wchar c = source.peekNextChar();
  37897. const bool hasExponent = (c == 'e' || c == 'E');
  37898. if (hasExponent)
  37899. {
  37900. source.skip();
  37901. c = source.peekNextChar();
  37902. if (c == '+' || c == '-')
  37903. source.skip();
  37904. int numExpDigits = 0;
  37905. while (isDecimalDigit (source.peekNextChar()))
  37906. {
  37907. source.skip();
  37908. ++numExpDigits;
  37909. }
  37910. if (numExpDigits == 0)
  37911. return false;
  37912. }
  37913. c = source.peekNextChar();
  37914. if (c == 'f' || c == 'F')
  37915. source.skip();
  37916. else if (! (hasExponent || hasPoint))
  37917. return false;
  37918. return true;
  37919. }
  37920. static int parseNumber (CodeDocument::Iterator& source)
  37921. {
  37922. const CodeDocument::Iterator original (source);
  37923. if (parseFloatLiteral (source))
  37924. return CPlusPlusCodeTokeniser::tokenType_floatLiteral;
  37925. source = original;
  37926. if (parseHexLiteral (source))
  37927. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37928. source = original;
  37929. if (parseOctalLiteral (source))
  37930. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37931. source = original;
  37932. if (parseDecimalLiteral (source))
  37933. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37934. source = original;
  37935. source.skip();
  37936. return CPlusPlusCodeTokeniser::tokenType_error;
  37937. }
  37938. static void skipQuotedString (CodeDocument::Iterator& source) throw()
  37939. {
  37940. const juce_wchar quote = source.nextChar();
  37941. for (;;)
  37942. {
  37943. const juce_wchar c = source.nextChar();
  37944. if (c == quote || c == 0)
  37945. break;
  37946. if (c == '\\')
  37947. source.skip();
  37948. }
  37949. }
  37950. static void skipComment (CodeDocument::Iterator& source) throw()
  37951. {
  37952. bool lastWasStar = false;
  37953. for (;;)
  37954. {
  37955. const juce_wchar c = source.nextChar();
  37956. if (c == 0 || (c == '/' && lastWasStar))
  37957. break;
  37958. lastWasStar = (c == '*');
  37959. }
  37960. }
  37961. }
  37962. int CPlusPlusCodeTokeniser::readNextToken (CodeDocument::Iterator& source)
  37963. {
  37964. int result = tokenType_error;
  37965. source.skipWhitespace();
  37966. juce_wchar firstChar = source.peekNextChar();
  37967. switch (firstChar)
  37968. {
  37969. case 0:
  37970. source.skip();
  37971. break;
  37972. case '0':
  37973. case '1':
  37974. case '2':
  37975. case '3':
  37976. case '4':
  37977. case '5':
  37978. case '6':
  37979. case '7':
  37980. case '8':
  37981. case '9':
  37982. result = CppTokeniser::parseNumber (source);
  37983. break;
  37984. case '.':
  37985. result = CppTokeniser::parseNumber (source);
  37986. if (result == tokenType_error)
  37987. result = tokenType_punctuation;
  37988. break;
  37989. case ',':
  37990. case ';':
  37991. case ':':
  37992. source.skip();
  37993. result = tokenType_punctuation;
  37994. break;
  37995. case '(':
  37996. case ')':
  37997. case '{':
  37998. case '}':
  37999. case '[':
  38000. case ']':
  38001. source.skip();
  38002. result = tokenType_bracket;
  38003. break;
  38004. case '"':
  38005. case '\'':
  38006. CppTokeniser::skipQuotedString (source);
  38007. result = tokenType_stringLiteral;
  38008. break;
  38009. case '+':
  38010. result = tokenType_operator;
  38011. source.skip();
  38012. if (source.peekNextChar() == '+')
  38013. source.skip();
  38014. else if (source.peekNextChar() == '=')
  38015. source.skip();
  38016. break;
  38017. case '-':
  38018. source.skip();
  38019. result = CppTokeniser::parseNumber (source);
  38020. if (result == tokenType_error)
  38021. {
  38022. result = tokenType_operator;
  38023. if (source.peekNextChar() == '-')
  38024. source.skip();
  38025. else if (source.peekNextChar() == '=')
  38026. source.skip();
  38027. }
  38028. break;
  38029. case '*':
  38030. case '%':
  38031. case '=':
  38032. case '!':
  38033. result = tokenType_operator;
  38034. source.skip();
  38035. if (source.peekNextChar() == '=')
  38036. source.skip();
  38037. break;
  38038. case '/':
  38039. result = tokenType_operator;
  38040. source.skip();
  38041. if (source.peekNextChar() == '=')
  38042. {
  38043. source.skip();
  38044. }
  38045. else if (source.peekNextChar() == '/')
  38046. {
  38047. result = tokenType_comment;
  38048. source.skipToEndOfLine();
  38049. }
  38050. else if (source.peekNextChar() == '*')
  38051. {
  38052. source.skip();
  38053. result = tokenType_comment;
  38054. CppTokeniser::skipComment (source);
  38055. }
  38056. break;
  38057. case '?':
  38058. case '~':
  38059. source.skip();
  38060. result = tokenType_operator;
  38061. break;
  38062. case '<':
  38063. source.skip();
  38064. result = tokenType_operator;
  38065. if (source.peekNextChar() == '=')
  38066. {
  38067. source.skip();
  38068. }
  38069. else if (source.peekNextChar() == '<')
  38070. {
  38071. source.skip();
  38072. if (source.peekNextChar() == '=')
  38073. source.skip();
  38074. }
  38075. break;
  38076. case '>':
  38077. source.skip();
  38078. result = tokenType_operator;
  38079. if (source.peekNextChar() == '=')
  38080. {
  38081. source.skip();
  38082. }
  38083. else if (source.peekNextChar() == '<')
  38084. {
  38085. source.skip();
  38086. if (source.peekNextChar() == '=')
  38087. source.skip();
  38088. }
  38089. break;
  38090. case '|':
  38091. source.skip();
  38092. result = tokenType_operator;
  38093. if (source.peekNextChar() == '=')
  38094. {
  38095. source.skip();
  38096. }
  38097. else if (source.peekNextChar() == '|')
  38098. {
  38099. source.skip();
  38100. if (source.peekNextChar() == '=')
  38101. source.skip();
  38102. }
  38103. break;
  38104. case '&':
  38105. source.skip();
  38106. result = tokenType_operator;
  38107. if (source.peekNextChar() == '=')
  38108. {
  38109. source.skip();
  38110. }
  38111. else if (source.peekNextChar() == '&')
  38112. {
  38113. source.skip();
  38114. if (source.peekNextChar() == '=')
  38115. source.skip();
  38116. }
  38117. break;
  38118. case '^':
  38119. source.skip();
  38120. result = tokenType_operator;
  38121. if (source.peekNextChar() == '=')
  38122. {
  38123. source.skip();
  38124. }
  38125. else if (source.peekNextChar() == '^')
  38126. {
  38127. source.skip();
  38128. if (source.peekNextChar() == '=')
  38129. source.skip();
  38130. }
  38131. break;
  38132. case '#':
  38133. result = tokenType_preprocessor;
  38134. source.skipToEndOfLine();
  38135. break;
  38136. default:
  38137. if (CppTokeniser::isIdentifierStart (firstChar))
  38138. result = CppTokeniser::parseIdentifier (source);
  38139. else
  38140. source.skip();
  38141. break;
  38142. }
  38143. return result;
  38144. }
  38145. const StringArray CPlusPlusCodeTokeniser::getTokenTypes()
  38146. {
  38147. const char* const types[] =
  38148. {
  38149. "Error",
  38150. "Comment",
  38151. "C++ keyword",
  38152. "Identifier",
  38153. "Integer literal",
  38154. "Float literal",
  38155. "String literal",
  38156. "Operator",
  38157. "Bracket",
  38158. "Punctuation",
  38159. "Preprocessor line",
  38160. 0
  38161. };
  38162. return StringArray (types);
  38163. }
  38164. const Colour CPlusPlusCodeTokeniser::getDefaultColour (const int tokenType)
  38165. {
  38166. const uint32 colours[] =
  38167. {
  38168. 0xffcc0000, // error
  38169. 0xff00aa00, // comment
  38170. 0xff0000cc, // keyword
  38171. 0xff000000, // identifier
  38172. 0xff880000, // int literal
  38173. 0xff885500, // float literal
  38174. 0xff990099, // string literal
  38175. 0xff225500, // operator
  38176. 0xff000055, // bracket
  38177. 0xff004400, // punctuation
  38178. 0xff660000 // preprocessor
  38179. };
  38180. if (tokenType >= 0 && tokenType < numElementsInArray (colours))
  38181. return Colour (colours [tokenType]);
  38182. return Colours::black;
  38183. }
  38184. bool CPlusPlusCodeTokeniser::isReservedKeyword (const String& token) throw()
  38185. {
  38186. return CppTokeniser::isReservedKeyword (token, token.length());
  38187. }
  38188. END_JUCE_NAMESPACE
  38189. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  38190. /*** Start of inlined file: juce_ComboBox.cpp ***/
  38191. BEGIN_JUCE_NAMESPACE
  38192. ComboBox::ComboBox (const String& name)
  38193. : Component (name),
  38194. lastCurrentId (0),
  38195. isButtonDown (false),
  38196. separatorPending (false),
  38197. menuActive (false),
  38198. label (0)
  38199. {
  38200. noChoicesMessage = TRANS("(no choices)");
  38201. setRepaintsOnMouseActivity (true);
  38202. lookAndFeelChanged();
  38203. currentId.addListener (this);
  38204. }
  38205. ComboBox::~ComboBox()
  38206. {
  38207. currentId.removeListener (this);
  38208. if (menuActive)
  38209. PopupMenu::dismissAllActiveMenus();
  38210. label = 0;
  38211. deleteAllChildren();
  38212. }
  38213. void ComboBox::setEditableText (const bool isEditable)
  38214. {
  38215. if (label->isEditableOnSingleClick() != isEditable || label->isEditableOnDoubleClick() != isEditable)
  38216. {
  38217. label->setEditable (isEditable, isEditable, false);
  38218. setWantsKeyboardFocus (! isEditable);
  38219. resized();
  38220. }
  38221. }
  38222. bool ComboBox::isTextEditable() const throw()
  38223. {
  38224. return label->isEditable();
  38225. }
  38226. void ComboBox::setJustificationType (const Justification& justification)
  38227. {
  38228. label->setJustificationType (justification);
  38229. }
  38230. const Justification ComboBox::getJustificationType() const throw()
  38231. {
  38232. return label->getJustificationType();
  38233. }
  38234. void ComboBox::setTooltip (const String& newTooltip)
  38235. {
  38236. SettableTooltipClient::setTooltip (newTooltip);
  38237. label->setTooltip (newTooltip);
  38238. }
  38239. void ComboBox::addItem (const String& newItemText, const int newItemId)
  38240. {
  38241. // you can't add empty strings to the list..
  38242. jassert (newItemText.isNotEmpty());
  38243. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  38244. jassert (newItemId != 0);
  38245. // you shouldn't use duplicate item IDs!
  38246. jassert (getItemForId (newItemId) == 0);
  38247. if (newItemText.isNotEmpty() && newItemId != 0)
  38248. {
  38249. if (separatorPending)
  38250. {
  38251. separatorPending = false;
  38252. ItemInfo* const item = new ItemInfo();
  38253. item->itemId = 0;
  38254. item->isEnabled = false;
  38255. item->isHeading = false;
  38256. items.add (item);
  38257. }
  38258. ItemInfo* const item = new ItemInfo();
  38259. item->name = newItemText;
  38260. item->itemId = newItemId;
  38261. item->isEnabled = true;
  38262. item->isHeading = false;
  38263. items.add (item);
  38264. }
  38265. }
  38266. void ComboBox::addSeparator()
  38267. {
  38268. separatorPending = (items.size() > 0);
  38269. }
  38270. void ComboBox::addSectionHeading (const String& headingName)
  38271. {
  38272. // you can't add empty strings to the list..
  38273. jassert (headingName.isNotEmpty());
  38274. if (headingName.isNotEmpty())
  38275. {
  38276. if (separatorPending)
  38277. {
  38278. separatorPending = false;
  38279. ItemInfo* const item = new ItemInfo();
  38280. item->itemId = 0;
  38281. item->isEnabled = false;
  38282. item->isHeading = false;
  38283. items.add (item);
  38284. }
  38285. ItemInfo* const item = new ItemInfo();
  38286. item->name = headingName;
  38287. item->itemId = 0;
  38288. item->isEnabled = true;
  38289. item->isHeading = true;
  38290. items.add (item);
  38291. }
  38292. }
  38293. void ComboBox::setItemEnabled (const int itemId, const bool shouldBeEnabled)
  38294. {
  38295. ItemInfo* const item = getItemForId (itemId);
  38296. if (item != 0)
  38297. item->isEnabled = shouldBeEnabled;
  38298. }
  38299. void ComboBox::changeItemText (const int itemId, const String& newText)
  38300. {
  38301. ItemInfo* const item = getItemForId (itemId);
  38302. jassert (item != 0);
  38303. if (item != 0)
  38304. item->name = newText;
  38305. }
  38306. void ComboBox::clear (const bool dontSendChangeMessage)
  38307. {
  38308. items.clear();
  38309. separatorPending = false;
  38310. if (! label->isEditable())
  38311. setSelectedItemIndex (-1, dontSendChangeMessage);
  38312. }
  38313. bool ComboBox::ItemInfo::isSeparator() const throw()
  38314. {
  38315. return name.isEmpty();
  38316. }
  38317. bool ComboBox::ItemInfo::isRealItem() const throw()
  38318. {
  38319. return ! (isHeading || name.isEmpty());
  38320. }
  38321. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  38322. {
  38323. if (itemId != 0)
  38324. {
  38325. for (int i = items.size(); --i >= 0;)
  38326. if (items.getUnchecked(i)->itemId == itemId)
  38327. return items.getUnchecked(i);
  38328. }
  38329. return 0;
  38330. }
  38331. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  38332. {
  38333. int n = 0;
  38334. for (int i = 0; i < items.size(); ++i)
  38335. {
  38336. ItemInfo* const item = items.getUnchecked(i);
  38337. if (item->isRealItem())
  38338. if (n++ == index)
  38339. return item;
  38340. }
  38341. return 0;
  38342. }
  38343. int ComboBox::getNumItems() const throw()
  38344. {
  38345. int n = 0;
  38346. for (int i = items.size(); --i >= 0;)
  38347. if (items.getUnchecked(i)->isRealItem())
  38348. ++n;
  38349. return n;
  38350. }
  38351. const String ComboBox::getItemText (const int index) const
  38352. {
  38353. const ItemInfo* const item = getItemForIndex (index);
  38354. if (item != 0)
  38355. return item->name;
  38356. return String::empty;
  38357. }
  38358. int ComboBox::getItemId (const int index) const throw()
  38359. {
  38360. const ItemInfo* const item = getItemForIndex (index);
  38361. return (item != 0) ? item->itemId : 0;
  38362. }
  38363. int ComboBox::indexOfItemId (const int itemId) const throw()
  38364. {
  38365. int n = 0;
  38366. for (int i = 0; i < items.size(); ++i)
  38367. {
  38368. const ItemInfo* const item = items.getUnchecked(i);
  38369. if (item->isRealItem())
  38370. {
  38371. if (item->itemId == itemId)
  38372. return n;
  38373. ++n;
  38374. }
  38375. }
  38376. return -1;
  38377. }
  38378. int ComboBox::getSelectedItemIndex() const
  38379. {
  38380. int index = indexOfItemId (currentId.getValue());
  38381. if (getText() != getItemText (index))
  38382. index = -1;
  38383. return index;
  38384. }
  38385. void ComboBox::setSelectedItemIndex (const int index, const bool dontSendChangeMessage)
  38386. {
  38387. setSelectedId (getItemId (index), dontSendChangeMessage);
  38388. }
  38389. int ComboBox::getSelectedId() const throw()
  38390. {
  38391. const ItemInfo* const item = getItemForId (currentId.getValue());
  38392. return (item != 0 && getText() == item->name) ? item->itemId : 0;
  38393. }
  38394. void ComboBox::setSelectedId (const int newItemId, const bool dontSendChangeMessage)
  38395. {
  38396. const ItemInfo* const item = getItemForId (newItemId);
  38397. const String newItemText (item != 0 ? item->name : String::empty);
  38398. if (lastCurrentId != newItemId || label->getText() != newItemText)
  38399. {
  38400. if (! dontSendChangeMessage)
  38401. triggerAsyncUpdate();
  38402. label->setText (newItemText, false);
  38403. lastCurrentId = newItemId;
  38404. currentId = newItemId;
  38405. repaint(); // for the benefit of the 'none selected' text
  38406. }
  38407. }
  38408. void ComboBox::valueChanged (Value&)
  38409. {
  38410. if (lastCurrentId != (int) currentId.getValue())
  38411. setSelectedId (currentId.getValue(), false);
  38412. }
  38413. const String ComboBox::getText() const
  38414. {
  38415. return label->getText();
  38416. }
  38417. void ComboBox::setText (const String& newText, const bool dontSendChangeMessage)
  38418. {
  38419. for (int i = items.size(); --i >= 0;)
  38420. {
  38421. const ItemInfo* const item = items.getUnchecked(i);
  38422. if (item->isRealItem()
  38423. && item->name == newText)
  38424. {
  38425. setSelectedId (item->itemId, dontSendChangeMessage);
  38426. return;
  38427. }
  38428. }
  38429. lastCurrentId = 0;
  38430. currentId = 0;
  38431. if (label->getText() != newText)
  38432. {
  38433. label->setText (newText, false);
  38434. if (! dontSendChangeMessage)
  38435. triggerAsyncUpdate();
  38436. }
  38437. repaint();
  38438. }
  38439. void ComboBox::showEditor()
  38440. {
  38441. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  38442. label->showEditor();
  38443. }
  38444. void ComboBox::setTextWhenNothingSelected (const String& newMessage)
  38445. {
  38446. if (textWhenNothingSelected != newMessage)
  38447. {
  38448. textWhenNothingSelected = newMessage;
  38449. repaint();
  38450. }
  38451. }
  38452. const String ComboBox::getTextWhenNothingSelected() const
  38453. {
  38454. return textWhenNothingSelected;
  38455. }
  38456. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage)
  38457. {
  38458. noChoicesMessage = newMessage;
  38459. }
  38460. const String ComboBox::getTextWhenNoChoicesAvailable() const
  38461. {
  38462. return noChoicesMessage;
  38463. }
  38464. void ComboBox::paint (Graphics& g)
  38465. {
  38466. getLookAndFeel().drawComboBox (g,
  38467. getWidth(),
  38468. getHeight(),
  38469. isButtonDown,
  38470. label->getRight(),
  38471. 0,
  38472. getWidth() - label->getRight(),
  38473. getHeight(),
  38474. *this);
  38475. if (textWhenNothingSelected.isNotEmpty()
  38476. && label->getText().isEmpty()
  38477. && ! label->isBeingEdited())
  38478. {
  38479. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  38480. g.setFont (label->getFont());
  38481. g.drawFittedText (textWhenNothingSelected,
  38482. label->getX() + 2, label->getY() + 1,
  38483. label->getWidth() - 4, label->getHeight() - 2,
  38484. label->getJustificationType(),
  38485. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  38486. }
  38487. }
  38488. void ComboBox::resized()
  38489. {
  38490. if (getHeight() > 0 && getWidth() > 0)
  38491. getLookAndFeel().positionComboBoxText (*this, *label);
  38492. }
  38493. void ComboBox::enablementChanged()
  38494. {
  38495. repaint();
  38496. }
  38497. void ComboBox::lookAndFeelChanged()
  38498. {
  38499. repaint();
  38500. Label* const newLabel = getLookAndFeel().createComboBoxTextBox (*this);
  38501. if (label != 0)
  38502. {
  38503. newLabel->setEditable (label->isEditable());
  38504. newLabel->setJustificationType (label->getJustificationType());
  38505. newLabel->setTooltip (label->getTooltip());
  38506. newLabel->setText (label->getText(), false);
  38507. }
  38508. label = newLabel;
  38509. addAndMakeVisible (newLabel);
  38510. newLabel->addListener (this);
  38511. newLabel->addMouseListener (this, false);
  38512. newLabel->setColour (Label::backgroundColourId, Colours::transparentBlack);
  38513. newLabel->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  38514. newLabel->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  38515. newLabel->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38516. newLabel->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  38517. newLabel->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38518. resized();
  38519. }
  38520. void ComboBox::colourChanged()
  38521. {
  38522. lookAndFeelChanged();
  38523. }
  38524. bool ComboBox::keyPressed (const KeyPress& key)
  38525. {
  38526. bool used = false;
  38527. if (key.isKeyCode (KeyPress::upKey)
  38528. || key.isKeyCode (KeyPress::leftKey))
  38529. {
  38530. setSelectedItemIndex (jmax (0, getSelectedItemIndex() - 1));
  38531. used = true;
  38532. }
  38533. else if (key.isKeyCode (KeyPress::downKey)
  38534. || key.isKeyCode (KeyPress::rightKey))
  38535. {
  38536. setSelectedItemIndex (jmin (getSelectedItemIndex() + 1, getNumItems() - 1));
  38537. used = true;
  38538. }
  38539. else if (key.isKeyCode (KeyPress::returnKey))
  38540. {
  38541. showPopup();
  38542. used = true;
  38543. }
  38544. return used;
  38545. }
  38546. bool ComboBox::keyStateChanged (const bool isKeyDown)
  38547. {
  38548. // only forward key events that aren't used by this component
  38549. return isKeyDown
  38550. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  38551. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  38552. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  38553. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  38554. }
  38555. void ComboBox::focusGained (FocusChangeType)
  38556. {
  38557. repaint();
  38558. }
  38559. void ComboBox::focusLost (FocusChangeType)
  38560. {
  38561. repaint();
  38562. }
  38563. void ComboBox::labelTextChanged (Label*)
  38564. {
  38565. triggerAsyncUpdate();
  38566. }
  38567. class ComboBox::Callback : public ModalComponentManager::Callback
  38568. {
  38569. public:
  38570. Callback (ComboBox* const box_)
  38571. : box (box_)
  38572. {
  38573. }
  38574. void modalStateFinished (int returnValue)
  38575. {
  38576. if (box != 0)
  38577. {
  38578. box->menuActive = false;
  38579. if (returnValue != 0)
  38580. box->setSelectedId (returnValue);
  38581. }
  38582. }
  38583. private:
  38584. Component::SafePointer<ComboBox> box;
  38585. Callback (const Callback&);
  38586. Callback& operator= (const Callback&);
  38587. };
  38588. void ComboBox::showPopup()
  38589. {
  38590. if (! menuActive)
  38591. {
  38592. const int selectedId = getSelectedId();
  38593. PopupMenu menu;
  38594. menu.setLookAndFeel (&getLookAndFeel());
  38595. for (int i = 0; i < items.size(); ++i)
  38596. {
  38597. const ItemInfo* const item = items.getUnchecked(i);
  38598. if (item->isSeparator())
  38599. menu.addSeparator();
  38600. else if (item->isHeading)
  38601. menu.addSectionHeader (item->name);
  38602. else
  38603. menu.addItem (item->itemId, item->name,
  38604. item->isEnabled, item->itemId == selectedId);
  38605. }
  38606. if (items.size() == 0)
  38607. menu.addItem (1, noChoicesMessage, false);
  38608. menuActive = true;
  38609. menu.showAt (this, selectedId, getWidth(), 1, jlimit (12, 24, getHeight()),
  38610. new Callback (this));
  38611. }
  38612. }
  38613. void ComboBox::mouseDown (const MouseEvent& e)
  38614. {
  38615. beginDragAutoRepeat (300);
  38616. isButtonDown = isEnabled();
  38617. if (isButtonDown
  38618. && (e.eventComponent == this || ! label->isEditable()))
  38619. {
  38620. showPopup();
  38621. }
  38622. }
  38623. void ComboBox::mouseDrag (const MouseEvent& e)
  38624. {
  38625. beginDragAutoRepeat (50);
  38626. if (isButtonDown && ! e.mouseWasClicked())
  38627. showPopup();
  38628. }
  38629. void ComboBox::mouseUp (const MouseEvent& e2)
  38630. {
  38631. if (isButtonDown)
  38632. {
  38633. isButtonDown = false;
  38634. repaint();
  38635. const MouseEvent e (e2.getEventRelativeTo (this));
  38636. if (reallyContains (e.x, e.y, true)
  38637. && (e2.eventComponent == this || ! label->isEditable()))
  38638. {
  38639. showPopup();
  38640. }
  38641. }
  38642. }
  38643. void ComboBox::addListener (Listener* const listener)
  38644. {
  38645. listeners.add (listener);
  38646. }
  38647. void ComboBox::removeListener (Listener* const listener)
  38648. {
  38649. listeners.remove (listener);
  38650. }
  38651. void ComboBox::handleAsyncUpdate()
  38652. {
  38653. Component::BailOutChecker checker (this);
  38654. listeners.callChecked (checker, &ComboBoxListener::comboBoxChanged, this); // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  38655. }
  38656. END_JUCE_NAMESPACE
  38657. /*** End of inlined file: juce_ComboBox.cpp ***/
  38658. /*** Start of inlined file: juce_Label.cpp ***/
  38659. BEGIN_JUCE_NAMESPACE
  38660. Label::Label (const String& componentName,
  38661. const String& labelText)
  38662. : Component (componentName),
  38663. textValue (labelText),
  38664. lastTextValue (labelText),
  38665. font (15.0f),
  38666. justification (Justification::centredLeft),
  38667. ownerComponent (0),
  38668. horizontalBorderSize (5),
  38669. verticalBorderSize (1),
  38670. minimumHorizontalScale (0.7f),
  38671. editSingleClick (false),
  38672. editDoubleClick (false),
  38673. lossOfFocusDiscardsChanges (false)
  38674. {
  38675. setColour (TextEditor::textColourId, Colours::black);
  38676. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38677. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38678. textValue.addListener (this);
  38679. }
  38680. Label::~Label()
  38681. {
  38682. textValue.removeListener (this);
  38683. if (ownerComponent != 0)
  38684. ownerComponent->removeComponentListener (this);
  38685. editor = 0;
  38686. }
  38687. void Label::setText (const String& newText,
  38688. const bool broadcastChangeMessage)
  38689. {
  38690. hideEditor (true);
  38691. if (lastTextValue != newText)
  38692. {
  38693. lastTextValue = newText;
  38694. textValue = newText;
  38695. repaint();
  38696. textWasChanged();
  38697. if (ownerComponent != 0)
  38698. componentMovedOrResized (*ownerComponent, true, true);
  38699. if (broadcastChangeMessage)
  38700. callChangeListeners();
  38701. }
  38702. }
  38703. const String Label::getText (const bool returnActiveEditorContents) const
  38704. {
  38705. return (returnActiveEditorContents && isBeingEdited())
  38706. ? editor->getText()
  38707. : textValue.toString();
  38708. }
  38709. void Label::valueChanged (Value&)
  38710. {
  38711. if (lastTextValue != textValue.toString())
  38712. setText (textValue.toString(), true);
  38713. }
  38714. void Label::setFont (const Font& newFont)
  38715. {
  38716. if (font != newFont)
  38717. {
  38718. font = newFont;
  38719. repaint();
  38720. }
  38721. }
  38722. const Font& Label::getFont() const throw()
  38723. {
  38724. return font;
  38725. }
  38726. void Label::setEditable (const bool editOnSingleClick,
  38727. const bool editOnDoubleClick,
  38728. const bool lossOfFocusDiscardsChanges_)
  38729. {
  38730. editSingleClick = editOnSingleClick;
  38731. editDoubleClick = editOnDoubleClick;
  38732. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  38733. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  38734. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  38735. }
  38736. void Label::setJustificationType (const Justification& newJustification)
  38737. {
  38738. if (justification != newJustification)
  38739. {
  38740. justification = newJustification;
  38741. repaint();
  38742. }
  38743. }
  38744. void Label::setBorderSize (int h, int v)
  38745. {
  38746. if (horizontalBorderSize != h || verticalBorderSize != v)
  38747. {
  38748. horizontalBorderSize = h;
  38749. verticalBorderSize = v;
  38750. repaint();
  38751. }
  38752. }
  38753. Component* Label::getAttachedComponent() const
  38754. {
  38755. return static_cast<Component*> (ownerComponent);
  38756. }
  38757. void Label::attachToComponent (Component* owner,
  38758. const bool onLeft)
  38759. {
  38760. if (ownerComponent != 0)
  38761. ownerComponent->removeComponentListener (this);
  38762. ownerComponent = owner;
  38763. leftOfOwnerComp = onLeft;
  38764. if (ownerComponent != 0)
  38765. {
  38766. setVisible (owner->isVisible());
  38767. ownerComponent->addComponentListener (this);
  38768. componentParentHierarchyChanged (*ownerComponent);
  38769. componentMovedOrResized (*ownerComponent, true, true);
  38770. }
  38771. }
  38772. void Label::componentMovedOrResized (Component& component, bool /*wasMoved*/, bool /*wasResized*/)
  38773. {
  38774. if (leftOfOwnerComp)
  38775. {
  38776. setSize (jmin (getFont().getStringWidth (textValue.toString()) + 8, component.getX()),
  38777. component.getHeight());
  38778. setTopRightPosition (component.getX(), component.getY());
  38779. }
  38780. else
  38781. {
  38782. setSize (component.getWidth(),
  38783. 8 + roundToInt (getFont().getHeight()));
  38784. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  38785. }
  38786. }
  38787. void Label::componentParentHierarchyChanged (Component& component)
  38788. {
  38789. if (component.getParentComponent() != 0)
  38790. component.getParentComponent()->addChildComponent (this);
  38791. }
  38792. void Label::componentVisibilityChanged (Component& component)
  38793. {
  38794. setVisible (component.isVisible());
  38795. }
  38796. void Label::textWasEdited()
  38797. {
  38798. }
  38799. void Label::textWasChanged()
  38800. {
  38801. }
  38802. void Label::showEditor()
  38803. {
  38804. if (editor == 0)
  38805. {
  38806. addAndMakeVisible (editor = createEditorComponent());
  38807. editor->setText (getText(), false);
  38808. editor->addListener (this);
  38809. editor->grabKeyboardFocus();
  38810. editor->setHighlightedRegion (Range<int> (0, textValue.toString().length()));
  38811. editor->addListener (this);
  38812. resized();
  38813. repaint();
  38814. editorShown (editor);
  38815. enterModalState (false);
  38816. editor->grabKeyboardFocus();
  38817. }
  38818. }
  38819. void Label::editorShown (TextEditor* /*editorComponent*/)
  38820. {
  38821. }
  38822. void Label::editorAboutToBeHidden (TextEditor* /*editorComponent*/)
  38823. {
  38824. }
  38825. bool Label::updateFromTextEditorContents()
  38826. {
  38827. jassert (editor != 0);
  38828. const String newText (editor->getText());
  38829. if (textValue.toString() != newText)
  38830. {
  38831. lastTextValue = newText;
  38832. textValue = newText;
  38833. repaint();
  38834. textWasChanged();
  38835. if (ownerComponent != 0)
  38836. componentMovedOrResized (*ownerComponent, true, true);
  38837. return true;
  38838. }
  38839. return false;
  38840. }
  38841. void Label::hideEditor (const bool discardCurrentEditorContents)
  38842. {
  38843. if (editor != 0)
  38844. {
  38845. Component::SafePointer<Component> deletionChecker (this);
  38846. editorAboutToBeHidden (editor);
  38847. const bool changed = (! discardCurrentEditorContents)
  38848. && updateFromTextEditorContents();
  38849. editor = 0;
  38850. repaint();
  38851. if (changed)
  38852. textWasEdited();
  38853. if (deletionChecker != 0)
  38854. exitModalState (0);
  38855. if (changed && deletionChecker != 0)
  38856. callChangeListeners();
  38857. }
  38858. }
  38859. void Label::inputAttemptWhenModal()
  38860. {
  38861. if (editor != 0)
  38862. {
  38863. if (lossOfFocusDiscardsChanges)
  38864. textEditorEscapeKeyPressed (*editor);
  38865. else
  38866. textEditorReturnKeyPressed (*editor);
  38867. }
  38868. }
  38869. bool Label::isBeingEdited() const throw()
  38870. {
  38871. return editor != 0;
  38872. }
  38873. TextEditor* Label::createEditorComponent()
  38874. {
  38875. TextEditor* const ed = new TextEditor (getName());
  38876. ed->setFont (font);
  38877. // copy these colours from our own settings..
  38878. const int cols[] = { TextEditor::backgroundColourId,
  38879. TextEditor::textColourId,
  38880. TextEditor::highlightColourId,
  38881. TextEditor::highlightedTextColourId,
  38882. TextEditor::caretColourId,
  38883. TextEditor::outlineColourId,
  38884. TextEditor::focusedOutlineColourId,
  38885. TextEditor::shadowColourId };
  38886. for (int i = 0; i < numElementsInArray (cols); ++i)
  38887. ed->setColour (cols[i], findColour (cols[i]));
  38888. return ed;
  38889. }
  38890. void Label::paint (Graphics& g)
  38891. {
  38892. getLookAndFeel().drawLabel (g, *this);
  38893. }
  38894. void Label::mouseUp (const MouseEvent& e)
  38895. {
  38896. if (editSingleClick
  38897. && e.mouseWasClicked()
  38898. && contains (e.x, e.y)
  38899. && ! e.mods.isPopupMenu())
  38900. {
  38901. showEditor();
  38902. }
  38903. }
  38904. void Label::mouseDoubleClick (const MouseEvent& e)
  38905. {
  38906. if (editDoubleClick && ! e.mods.isPopupMenu())
  38907. showEditor();
  38908. }
  38909. void Label::resized()
  38910. {
  38911. if (editor != 0)
  38912. editor->setBoundsInset (BorderSize (0));
  38913. }
  38914. void Label::focusGained (FocusChangeType cause)
  38915. {
  38916. if (editSingleClick && cause == focusChangedByTabKey)
  38917. showEditor();
  38918. }
  38919. void Label::enablementChanged()
  38920. {
  38921. repaint();
  38922. }
  38923. void Label::colourChanged()
  38924. {
  38925. repaint();
  38926. }
  38927. void Label::setMinimumHorizontalScale (const float newScale)
  38928. {
  38929. if (minimumHorizontalScale != newScale)
  38930. {
  38931. minimumHorizontalScale = newScale;
  38932. repaint();
  38933. }
  38934. }
  38935. // We'll use a custom focus traverser here to make sure focus goes from the
  38936. // text editor to another component rather than back to the label itself.
  38937. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  38938. {
  38939. public:
  38940. LabelKeyboardFocusTraverser() {}
  38941. Component* getNextComponent (Component* current)
  38942. {
  38943. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  38944. ? current->getParentComponent() : current);
  38945. }
  38946. Component* getPreviousComponent (Component* current)
  38947. {
  38948. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  38949. ? current->getParentComponent() : current);
  38950. }
  38951. };
  38952. KeyboardFocusTraverser* Label::createFocusTraverser()
  38953. {
  38954. return new LabelKeyboardFocusTraverser();
  38955. }
  38956. void Label::addListener (Listener* const listener)
  38957. {
  38958. listeners.add (listener);
  38959. }
  38960. void Label::removeListener (Listener* const listener)
  38961. {
  38962. listeners.remove (listener);
  38963. }
  38964. void Label::callChangeListeners()
  38965. {
  38966. Component::BailOutChecker checker (this);
  38967. listeners.callChecked (checker, &LabelListener::labelTextChanged, this); // (can't use Label::Listener due to idiotic VC2005 bug)
  38968. }
  38969. void Label::textEditorTextChanged (TextEditor& ed)
  38970. {
  38971. if (editor != 0)
  38972. {
  38973. jassert (&ed == editor);
  38974. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  38975. {
  38976. if (lossOfFocusDiscardsChanges)
  38977. textEditorEscapeKeyPressed (ed);
  38978. else
  38979. textEditorReturnKeyPressed (ed);
  38980. }
  38981. }
  38982. }
  38983. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  38984. {
  38985. if (editor != 0)
  38986. {
  38987. jassert (&ed == editor);
  38988. (void) ed;
  38989. const bool changed = updateFromTextEditorContents();
  38990. hideEditor (true);
  38991. if (changed)
  38992. {
  38993. Component::SafePointer<Component> deletionChecker (this);
  38994. textWasEdited();
  38995. if (deletionChecker != 0)
  38996. callChangeListeners();
  38997. }
  38998. }
  38999. }
  39000. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  39001. {
  39002. if (editor != 0)
  39003. {
  39004. jassert (&ed == editor);
  39005. (void) ed;
  39006. editor->setText (textValue.toString(), false);
  39007. hideEditor (true);
  39008. }
  39009. }
  39010. void Label::textEditorFocusLost (TextEditor& ed)
  39011. {
  39012. textEditorTextChanged (ed);
  39013. }
  39014. END_JUCE_NAMESPACE
  39015. /*** End of inlined file: juce_Label.cpp ***/
  39016. /*** Start of inlined file: juce_ListBox.cpp ***/
  39017. BEGIN_JUCE_NAMESPACE
  39018. class ListBoxRowComponent : public Component,
  39019. public TooltipClient
  39020. {
  39021. public:
  39022. ListBoxRowComponent (ListBox& owner_)
  39023. : owner (owner_),
  39024. row (-1),
  39025. selected (false),
  39026. isDragging (false)
  39027. {
  39028. }
  39029. ~ListBoxRowComponent()
  39030. {
  39031. deleteAllChildren();
  39032. }
  39033. void paint (Graphics& g)
  39034. {
  39035. if (owner.getModel() != 0)
  39036. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  39037. }
  39038. void update (const int row_, const bool selected_)
  39039. {
  39040. if (row != row_ || selected != selected_)
  39041. {
  39042. repaint();
  39043. row = row_;
  39044. selected = selected_;
  39045. }
  39046. if (owner.getModel() != 0)
  39047. {
  39048. Component* const customComp = owner.getModel()->refreshComponentForRow (row_, selected_, getChildComponent (0));
  39049. if (customComp != 0)
  39050. {
  39051. addAndMakeVisible (customComp);
  39052. customComp->setBounds (getLocalBounds());
  39053. for (int i = getNumChildComponents(); --i >= 0;)
  39054. if (getChildComponent (i) != customComp)
  39055. delete getChildComponent (i);
  39056. }
  39057. else
  39058. {
  39059. deleteAllChildren();
  39060. }
  39061. }
  39062. }
  39063. void mouseDown (const MouseEvent& e)
  39064. {
  39065. isDragging = false;
  39066. selectRowOnMouseUp = false;
  39067. if (isEnabled())
  39068. {
  39069. if (! selected)
  39070. {
  39071. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  39072. if (owner.getModel() != 0)
  39073. owner.getModel()->listBoxItemClicked (row, e);
  39074. }
  39075. else
  39076. {
  39077. selectRowOnMouseUp = true;
  39078. }
  39079. }
  39080. }
  39081. void mouseUp (const MouseEvent& e)
  39082. {
  39083. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  39084. {
  39085. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  39086. if (owner.getModel() != 0)
  39087. owner.getModel()->listBoxItemClicked (row, e);
  39088. }
  39089. }
  39090. void mouseDoubleClick (const MouseEvent& e)
  39091. {
  39092. if (owner.getModel() != 0 && isEnabled())
  39093. owner.getModel()->listBoxItemDoubleClicked (row, e);
  39094. }
  39095. void mouseDrag (const MouseEvent& e)
  39096. {
  39097. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  39098. {
  39099. const SparseSet<int> selectedRows (owner.getSelectedRows());
  39100. if (selectedRows.size() > 0)
  39101. {
  39102. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  39103. if (dragDescription.isNotEmpty())
  39104. {
  39105. isDragging = true;
  39106. owner.startDragAndDrop (e, dragDescription);
  39107. }
  39108. }
  39109. }
  39110. }
  39111. void resized()
  39112. {
  39113. if (getNumChildComponents() > 0)
  39114. getChildComponent(0)->setBounds (getLocalBounds());
  39115. }
  39116. const String getTooltip()
  39117. {
  39118. if (owner.getModel() != 0)
  39119. return owner.getModel()->getTooltipForRow (row);
  39120. return String::empty;
  39121. }
  39122. juce_UseDebuggingNewOperator
  39123. bool neededFlag;
  39124. private:
  39125. ListBox& owner;
  39126. int row;
  39127. bool selected, isDragging, selectRowOnMouseUp;
  39128. ListBoxRowComponent (const ListBoxRowComponent&);
  39129. ListBoxRowComponent& operator= (const ListBoxRowComponent&);
  39130. };
  39131. class ListViewport : public Viewport
  39132. {
  39133. public:
  39134. int firstIndex, firstWholeIndex, lastWholeIndex;
  39135. bool hasUpdated;
  39136. ListViewport (ListBox& owner_)
  39137. : owner (owner_)
  39138. {
  39139. setWantsKeyboardFocus (false);
  39140. setViewedComponent (new Component());
  39141. getViewedComponent()->addMouseListener (this, false);
  39142. getViewedComponent()->setWantsKeyboardFocus (false);
  39143. }
  39144. ~ListViewport()
  39145. {
  39146. getViewedComponent()->removeMouseListener (this);
  39147. getViewedComponent()->deleteAllChildren();
  39148. }
  39149. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  39150. {
  39151. return static_cast <ListBoxRowComponent*>
  39152. (getViewedComponent()->getChildComponent (row % jmax (1, getViewedComponent()->getNumChildComponents())));
  39153. }
  39154. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  39155. {
  39156. const int index = getIndexOfChildComponent (rowComponent);
  39157. const int num = getViewedComponent()->getNumChildComponents();
  39158. for (int i = num; --i >= 0;)
  39159. if (((firstIndex + i) % jmax (1, num)) == index)
  39160. return firstIndex + i;
  39161. return -1;
  39162. }
  39163. Component* getComponentForRowIfOnscreen (const int row) const throw()
  39164. {
  39165. return (row >= firstIndex && row < firstIndex + getViewedComponent()->getNumChildComponents())
  39166. ? getComponentForRow (row) : 0;
  39167. }
  39168. void visibleAreaChanged (int, int, int, int)
  39169. {
  39170. updateVisibleArea (true);
  39171. if (owner.getModel() != 0)
  39172. owner.getModel()->listWasScrolled();
  39173. }
  39174. void updateVisibleArea (const bool makeSureItUpdatesContent)
  39175. {
  39176. hasUpdated = false;
  39177. const int newX = getViewedComponent()->getX();
  39178. int newY = getViewedComponent()->getY();
  39179. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  39180. const int newH = owner.totalItems * owner.getRowHeight();
  39181. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  39182. newY = getMaximumVisibleHeight() - newH;
  39183. getViewedComponent()->setBounds (newX, newY, newW, newH);
  39184. if (makeSureItUpdatesContent && ! hasUpdated)
  39185. updateContents();
  39186. }
  39187. void updateContents()
  39188. {
  39189. hasUpdated = true;
  39190. const int rowHeight = owner.getRowHeight();
  39191. if (rowHeight > 0)
  39192. {
  39193. const int y = getViewPositionY();
  39194. const int w = getViewedComponent()->getWidth();
  39195. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  39196. while (numNeeded > getViewedComponent()->getNumChildComponents())
  39197. getViewedComponent()->addAndMakeVisible (new ListBoxRowComponent (owner));
  39198. jassert (numNeeded >= 0);
  39199. while (numNeeded < getViewedComponent()->getNumChildComponents())
  39200. {
  39201. Component* const rowToRemove
  39202. = getViewedComponent()->getChildComponent (getViewedComponent()->getNumChildComponents() - 1);
  39203. delete rowToRemove;
  39204. }
  39205. firstIndex = y / rowHeight;
  39206. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  39207. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  39208. for (int i = 0; i < numNeeded; ++i)
  39209. {
  39210. const int row = i + firstIndex;
  39211. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  39212. if (rowComp != 0)
  39213. {
  39214. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  39215. rowComp->update (row, owner.isRowSelected (row));
  39216. }
  39217. }
  39218. }
  39219. if (owner.headerComponent != 0)
  39220. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  39221. owner.outlineThickness,
  39222. jmax (owner.getWidth() - owner.outlineThickness * 2,
  39223. getViewedComponent()->getWidth()),
  39224. owner.headerComponent->getHeight());
  39225. }
  39226. void paint (Graphics& g)
  39227. {
  39228. if (isOpaque())
  39229. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  39230. }
  39231. bool keyPressed (const KeyPress& key)
  39232. {
  39233. if (key.isKeyCode (KeyPress::upKey)
  39234. || key.isKeyCode (KeyPress::downKey)
  39235. || key.isKeyCode (KeyPress::pageUpKey)
  39236. || key.isKeyCode (KeyPress::pageDownKey)
  39237. || key.isKeyCode (KeyPress::homeKey)
  39238. || key.isKeyCode (KeyPress::endKey))
  39239. {
  39240. // we want to avoid these keypresses going to the viewport, and instead allow
  39241. // them to pass up to our listbox..
  39242. return false;
  39243. }
  39244. return Viewport::keyPressed (key);
  39245. }
  39246. juce_UseDebuggingNewOperator
  39247. private:
  39248. ListBox& owner;
  39249. ListViewport (const ListViewport&);
  39250. ListViewport& operator= (const ListViewport&);
  39251. };
  39252. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  39253. : Component (name),
  39254. model (model_),
  39255. totalItems (0),
  39256. rowHeight (22),
  39257. minimumRowWidth (0),
  39258. outlineThickness (0),
  39259. lastRowSelected (-1),
  39260. mouseMoveSelects (false),
  39261. multipleSelection (false),
  39262. hasDoneInitialUpdate (false)
  39263. {
  39264. addAndMakeVisible (viewport = new ListViewport (*this));
  39265. setWantsKeyboardFocus (true);
  39266. colourChanged();
  39267. }
  39268. ListBox::~ListBox()
  39269. {
  39270. headerComponent = 0;
  39271. viewport = 0;
  39272. }
  39273. void ListBox::setModel (ListBoxModel* const newModel)
  39274. {
  39275. if (model != newModel)
  39276. {
  39277. model = newModel;
  39278. updateContent();
  39279. }
  39280. }
  39281. void ListBox::setMultipleSelectionEnabled (bool b)
  39282. {
  39283. multipleSelection = b;
  39284. }
  39285. void ListBox::setMouseMoveSelectsRows (bool b)
  39286. {
  39287. mouseMoveSelects = b;
  39288. if (b)
  39289. addMouseListener (this, true);
  39290. }
  39291. void ListBox::paint (Graphics& g)
  39292. {
  39293. if (! hasDoneInitialUpdate)
  39294. updateContent();
  39295. g.fillAll (findColour (backgroundColourId));
  39296. }
  39297. void ListBox::paintOverChildren (Graphics& g)
  39298. {
  39299. if (outlineThickness > 0)
  39300. {
  39301. g.setColour (findColour (outlineColourId));
  39302. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  39303. }
  39304. }
  39305. void ListBox::resized()
  39306. {
  39307. viewport->setBoundsInset (BorderSize (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  39308. outlineThickness,
  39309. outlineThickness,
  39310. outlineThickness));
  39311. viewport->setSingleStepSizes (20, getRowHeight());
  39312. viewport->updateVisibleArea (false);
  39313. }
  39314. void ListBox::visibilityChanged()
  39315. {
  39316. viewport->updateVisibleArea (true);
  39317. }
  39318. Viewport* ListBox::getViewport() const throw()
  39319. {
  39320. return viewport;
  39321. }
  39322. void ListBox::updateContent()
  39323. {
  39324. hasDoneInitialUpdate = true;
  39325. totalItems = (model != 0) ? model->getNumRows() : 0;
  39326. bool selectionChanged = false;
  39327. if (selected [selected.size() - 1] >= totalItems)
  39328. {
  39329. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39330. lastRowSelected = getSelectedRow (0);
  39331. selectionChanged = true;
  39332. }
  39333. viewport->updateVisibleArea (isVisible());
  39334. viewport->resized();
  39335. if (selectionChanged && model != 0)
  39336. model->selectedRowsChanged (lastRowSelected);
  39337. }
  39338. void ListBox::selectRow (const int row,
  39339. bool dontScroll,
  39340. bool deselectOthersFirst)
  39341. {
  39342. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  39343. }
  39344. void ListBox::selectRowInternal (const int row,
  39345. bool dontScroll,
  39346. bool deselectOthersFirst,
  39347. bool isMouseClick)
  39348. {
  39349. if (! multipleSelection)
  39350. deselectOthersFirst = true;
  39351. if ((! isRowSelected (row))
  39352. || (deselectOthersFirst && getNumSelectedRows() > 1))
  39353. {
  39354. if (((unsigned int) row) < (unsigned int) totalItems)
  39355. {
  39356. if (deselectOthersFirst)
  39357. selected.clear();
  39358. selected.addRange (Range<int> (row, row + 1));
  39359. if (getHeight() == 0 || getWidth() == 0)
  39360. dontScroll = true;
  39361. viewport->hasUpdated = false;
  39362. if (row < viewport->firstWholeIndex && ! dontScroll)
  39363. {
  39364. viewport->setViewPosition (viewport->getViewPositionX(),
  39365. row * getRowHeight());
  39366. }
  39367. else if (row >= viewport->lastWholeIndex && ! dontScroll)
  39368. {
  39369. const int rowsOnScreen = viewport->lastWholeIndex - viewport->firstWholeIndex;
  39370. if (row >= lastRowSelected + rowsOnScreen
  39371. && rowsOnScreen < totalItems - 1
  39372. && ! isMouseClick)
  39373. {
  39374. viewport->setViewPosition (viewport->getViewPositionX(),
  39375. jlimit (0, jmax (0, totalItems - rowsOnScreen), row)
  39376. * getRowHeight());
  39377. }
  39378. else
  39379. {
  39380. viewport->setViewPosition (viewport->getViewPositionX(),
  39381. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  39382. }
  39383. }
  39384. if (! viewport->hasUpdated)
  39385. viewport->updateContents();
  39386. lastRowSelected = row;
  39387. model->selectedRowsChanged (row);
  39388. }
  39389. else
  39390. {
  39391. if (deselectOthersFirst)
  39392. deselectAllRows();
  39393. }
  39394. }
  39395. }
  39396. void ListBox::deselectRow (const int row)
  39397. {
  39398. if (selected.contains (row))
  39399. {
  39400. selected.removeRange (Range <int> (row, row + 1));
  39401. if (row == lastRowSelected)
  39402. lastRowSelected = getSelectedRow (0);
  39403. viewport->updateContents();
  39404. model->selectedRowsChanged (lastRowSelected);
  39405. }
  39406. }
  39407. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  39408. const bool sendNotificationEventToModel)
  39409. {
  39410. selected = setOfRowsToBeSelected;
  39411. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39412. if (! isRowSelected (lastRowSelected))
  39413. lastRowSelected = getSelectedRow (0);
  39414. viewport->updateContents();
  39415. if ((model != 0) && sendNotificationEventToModel)
  39416. model->selectedRowsChanged (lastRowSelected);
  39417. }
  39418. const SparseSet<int> ListBox::getSelectedRows() const
  39419. {
  39420. return selected;
  39421. }
  39422. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  39423. {
  39424. if (multipleSelection && (firstRow != lastRow))
  39425. {
  39426. const int numRows = totalItems - 1;
  39427. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  39428. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  39429. selected.addRange (Range <int> (jmin (firstRow, lastRow),
  39430. jmax (firstRow, lastRow) + 1));
  39431. selected.removeRange (Range <int> (lastRow, lastRow + 1));
  39432. }
  39433. selectRowInternal (lastRow, false, false, true);
  39434. }
  39435. void ListBox::flipRowSelection (const int row)
  39436. {
  39437. if (isRowSelected (row))
  39438. deselectRow (row);
  39439. else
  39440. selectRowInternal (row, false, false, true);
  39441. }
  39442. void ListBox::deselectAllRows()
  39443. {
  39444. if (! selected.isEmpty())
  39445. {
  39446. selected.clear();
  39447. lastRowSelected = -1;
  39448. viewport->updateContents();
  39449. if (model != 0)
  39450. model->selectedRowsChanged (lastRowSelected);
  39451. }
  39452. }
  39453. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  39454. const ModifierKeys& mods)
  39455. {
  39456. if (multipleSelection && mods.isCommandDown())
  39457. {
  39458. flipRowSelection (row);
  39459. }
  39460. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  39461. {
  39462. selectRangeOfRows (lastRowSelected, row);
  39463. }
  39464. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  39465. {
  39466. selectRowInternal (row, false, true, true);
  39467. }
  39468. }
  39469. int ListBox::getNumSelectedRows() const
  39470. {
  39471. return selected.size();
  39472. }
  39473. int ListBox::getSelectedRow (const int index) const
  39474. {
  39475. return (((unsigned int) index) < (unsigned int) selected.size())
  39476. ? selected [index] : -1;
  39477. }
  39478. bool ListBox::isRowSelected (const int row) const
  39479. {
  39480. return selected.contains (row);
  39481. }
  39482. int ListBox::getLastRowSelected() const
  39483. {
  39484. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  39485. }
  39486. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  39487. {
  39488. if (((unsigned int) x) < (unsigned int) getWidth())
  39489. {
  39490. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  39491. if (((unsigned int) row) < (unsigned int) totalItems)
  39492. return row;
  39493. }
  39494. return -1;
  39495. }
  39496. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  39497. {
  39498. if (((unsigned int) x) < (unsigned int) getWidth())
  39499. {
  39500. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  39501. return jlimit (0, totalItems, row);
  39502. }
  39503. return -1;
  39504. }
  39505. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  39506. {
  39507. Component* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  39508. return listRowComp != 0 ? listRowComp->getChildComponent (0) : 0;
  39509. }
  39510. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  39511. {
  39512. return viewport->getRowNumberOfComponent (rowComponent);
  39513. }
  39514. const Rectangle<int> ListBox::getRowPosition (const int rowNumber,
  39515. const bool relativeToComponentTopLeft) const throw()
  39516. {
  39517. int y = viewport->getY() + rowHeight * rowNumber;
  39518. if (relativeToComponentTopLeft)
  39519. y -= viewport->getViewPositionY();
  39520. return Rectangle<int> (viewport->getX(), y,
  39521. viewport->getViewedComponent()->getWidth(), rowHeight);
  39522. }
  39523. void ListBox::setVerticalPosition (const double proportion)
  39524. {
  39525. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39526. viewport->setViewPosition (viewport->getViewPositionX(),
  39527. jmax (0, roundToInt (proportion * offscreen)));
  39528. }
  39529. double ListBox::getVerticalPosition() const
  39530. {
  39531. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39532. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  39533. : 0;
  39534. }
  39535. int ListBox::getVisibleRowWidth() const throw()
  39536. {
  39537. return viewport->getViewWidth();
  39538. }
  39539. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  39540. {
  39541. if (row < viewport->firstWholeIndex)
  39542. {
  39543. viewport->setViewPosition (viewport->getViewPositionX(),
  39544. row * getRowHeight());
  39545. }
  39546. else if (row >= viewport->lastWholeIndex)
  39547. {
  39548. viewport->setViewPosition (viewport->getViewPositionX(),
  39549. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  39550. }
  39551. }
  39552. bool ListBox::keyPressed (const KeyPress& key)
  39553. {
  39554. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  39555. const bool multiple = multipleSelection
  39556. && (lastRowSelected >= 0)
  39557. && (key.getModifiers().isShiftDown()
  39558. || key.getModifiers().isCtrlDown()
  39559. || key.getModifiers().isCommandDown());
  39560. if (key.isKeyCode (KeyPress::upKey))
  39561. {
  39562. if (multiple)
  39563. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  39564. else
  39565. selectRow (jmax (0, lastRowSelected - 1));
  39566. }
  39567. else if (key.isKeyCode (KeyPress::returnKey)
  39568. && isRowSelected (lastRowSelected))
  39569. {
  39570. if (model != 0)
  39571. model->returnKeyPressed (lastRowSelected);
  39572. }
  39573. else if (key.isKeyCode (KeyPress::pageUpKey))
  39574. {
  39575. if (multiple)
  39576. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  39577. else
  39578. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  39579. }
  39580. else if (key.isKeyCode (KeyPress::pageDownKey))
  39581. {
  39582. if (multiple)
  39583. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  39584. else
  39585. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  39586. }
  39587. else if (key.isKeyCode (KeyPress::homeKey))
  39588. {
  39589. if (multiple && key.getModifiers().isShiftDown())
  39590. selectRangeOfRows (lastRowSelected, 0);
  39591. else
  39592. selectRow (0);
  39593. }
  39594. else if (key.isKeyCode (KeyPress::endKey))
  39595. {
  39596. if (multiple && key.getModifiers().isShiftDown())
  39597. selectRangeOfRows (lastRowSelected, totalItems - 1);
  39598. else
  39599. selectRow (totalItems - 1);
  39600. }
  39601. else if (key.isKeyCode (KeyPress::downKey))
  39602. {
  39603. if (multiple)
  39604. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  39605. else
  39606. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  39607. }
  39608. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  39609. && isRowSelected (lastRowSelected))
  39610. {
  39611. if (model != 0)
  39612. model->deleteKeyPressed (lastRowSelected);
  39613. }
  39614. else if (multiple && key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  39615. {
  39616. selectRangeOfRows (0, std::numeric_limits<int>::max());
  39617. }
  39618. else
  39619. {
  39620. return false;
  39621. }
  39622. return true;
  39623. }
  39624. bool ListBox::keyStateChanged (const bool isKeyDown)
  39625. {
  39626. return isKeyDown
  39627. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  39628. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  39629. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  39630. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  39631. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  39632. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  39633. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  39634. }
  39635. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  39636. {
  39637. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  39638. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  39639. }
  39640. void ListBox::mouseMove (const MouseEvent& e)
  39641. {
  39642. if (mouseMoveSelects)
  39643. {
  39644. const MouseEvent e2 (e.getEventRelativeTo (this));
  39645. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  39646. }
  39647. }
  39648. void ListBox::mouseExit (const MouseEvent& e)
  39649. {
  39650. mouseMove (e);
  39651. }
  39652. void ListBox::mouseUp (const MouseEvent& e)
  39653. {
  39654. if (e.mouseWasClicked() && model != 0)
  39655. model->backgroundClicked();
  39656. }
  39657. void ListBox::setRowHeight (const int newHeight)
  39658. {
  39659. rowHeight = jmax (1, newHeight);
  39660. viewport->setSingleStepSizes (20, rowHeight);
  39661. updateContent();
  39662. }
  39663. int ListBox::getNumRowsOnScreen() const throw()
  39664. {
  39665. return viewport->getMaximumVisibleHeight() / rowHeight;
  39666. }
  39667. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  39668. {
  39669. minimumRowWidth = newMinimumWidth;
  39670. updateContent();
  39671. }
  39672. int ListBox::getVisibleContentWidth() const throw()
  39673. {
  39674. return viewport->getMaximumVisibleWidth();
  39675. }
  39676. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  39677. {
  39678. return viewport->getVerticalScrollBar();
  39679. }
  39680. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  39681. {
  39682. return viewport->getHorizontalScrollBar();
  39683. }
  39684. void ListBox::colourChanged()
  39685. {
  39686. setOpaque (findColour (backgroundColourId).isOpaque());
  39687. viewport->setOpaque (isOpaque());
  39688. repaint();
  39689. }
  39690. void ListBox::setOutlineThickness (const int outlineThickness_)
  39691. {
  39692. outlineThickness = outlineThickness_;
  39693. resized();
  39694. }
  39695. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  39696. {
  39697. if (newHeaderComponent != headerComponent)
  39698. {
  39699. headerComponent = newHeaderComponent;
  39700. addAndMakeVisible (newHeaderComponent);
  39701. ListBox::resized();
  39702. }
  39703. }
  39704. void ListBox::repaintRow (const int rowNumber) throw()
  39705. {
  39706. repaint (getRowPosition (rowNumber, true));
  39707. }
  39708. const Image ListBox::createSnapshotOfSelectedRows (int& imageX, int& imageY)
  39709. {
  39710. Rectangle<int> imageArea;
  39711. const int firstRow = getRowContainingPosition (0, 0);
  39712. int i;
  39713. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39714. {
  39715. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39716. if (rowComp != 0 && isRowSelected (firstRow + i))
  39717. {
  39718. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  39719. const Rectangle<int> rowRect (pos.getX(), pos.getY(), rowComp->getWidth(), rowComp->getHeight());
  39720. imageArea = imageArea.getUnion (rowRect);
  39721. }
  39722. }
  39723. imageArea = imageArea.getIntersection (getLocalBounds());
  39724. imageX = imageArea.getX();
  39725. imageY = imageArea.getY();
  39726. Image snapshot (Image::ARGB, imageArea.getWidth(), imageArea.getHeight(), true, Image::NativeImage);
  39727. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39728. {
  39729. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39730. if (rowComp != 0 && isRowSelected (firstRow + i))
  39731. {
  39732. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  39733. Graphics g (snapshot);
  39734. g.setOrigin (pos.getX() - imageX, pos.getY() - imageY);
  39735. if (g.reduceClipRegion (0, 0, rowComp->getWidth(), rowComp->getHeight()))
  39736. rowComp->paintEntireComponent (g);
  39737. }
  39738. }
  39739. return snapshot;
  39740. }
  39741. void ListBox::startDragAndDrop (const MouseEvent& e, const String& dragDescription)
  39742. {
  39743. DragAndDropContainer* const dragContainer
  39744. = DragAndDropContainer::findParentDragContainerFor (this);
  39745. if (dragContainer != 0)
  39746. {
  39747. int x, y;
  39748. Image dragImage (createSnapshotOfSelectedRows (x, y));
  39749. dragImage.multiplyAllAlphas (0.6f);
  39750. MouseEvent e2 (e.getEventRelativeTo (this));
  39751. const Point<int> p (x - e2.x, y - e2.y);
  39752. dragContainer->startDragging (dragDescription, this, dragImage, true, &p);
  39753. }
  39754. else
  39755. {
  39756. // to be able to do a drag-and-drop operation, the listbox needs to
  39757. // be inside a component which is also a DragAndDropContainer.
  39758. jassertfalse;
  39759. }
  39760. }
  39761. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  39762. {
  39763. (void) existingComponentToUpdate;
  39764. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  39765. return 0;
  39766. }
  39767. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&)
  39768. {
  39769. }
  39770. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&)
  39771. {
  39772. }
  39773. void ListBoxModel::backgroundClicked()
  39774. {
  39775. }
  39776. void ListBoxModel::selectedRowsChanged (int)
  39777. {
  39778. }
  39779. void ListBoxModel::deleteKeyPressed (int)
  39780. {
  39781. }
  39782. void ListBoxModel::returnKeyPressed (int)
  39783. {
  39784. }
  39785. void ListBoxModel::listWasScrolled()
  39786. {
  39787. }
  39788. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  39789. {
  39790. return String::empty;
  39791. }
  39792. const String ListBoxModel::getTooltipForRow (int)
  39793. {
  39794. return String::empty;
  39795. }
  39796. END_JUCE_NAMESPACE
  39797. /*** End of inlined file: juce_ListBox.cpp ***/
  39798. /*** Start of inlined file: juce_ProgressBar.cpp ***/
  39799. BEGIN_JUCE_NAMESPACE
  39800. ProgressBar::ProgressBar (double& progress_)
  39801. : progress (progress_),
  39802. displayPercentage (true),
  39803. lastCallbackTime (0)
  39804. {
  39805. currentValue = jlimit (0.0, 1.0, progress);
  39806. }
  39807. ProgressBar::~ProgressBar()
  39808. {
  39809. }
  39810. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  39811. {
  39812. displayPercentage = shouldDisplayPercentage;
  39813. repaint();
  39814. }
  39815. void ProgressBar::setTextToDisplay (const String& text)
  39816. {
  39817. displayPercentage = false;
  39818. displayedMessage = text;
  39819. }
  39820. void ProgressBar::lookAndFeelChanged()
  39821. {
  39822. setOpaque (findColour (backgroundColourId).isOpaque());
  39823. }
  39824. void ProgressBar::colourChanged()
  39825. {
  39826. lookAndFeelChanged();
  39827. }
  39828. void ProgressBar::paint (Graphics& g)
  39829. {
  39830. String text;
  39831. if (displayPercentage)
  39832. {
  39833. if (currentValue >= 0 && currentValue <= 1.0)
  39834. text << roundToInt (currentValue * 100.0) << '%';
  39835. }
  39836. else
  39837. {
  39838. text = displayedMessage;
  39839. }
  39840. getLookAndFeel().drawProgressBar (g, *this,
  39841. getWidth(), getHeight(),
  39842. currentValue, text);
  39843. }
  39844. void ProgressBar::visibilityChanged()
  39845. {
  39846. if (isVisible())
  39847. startTimer (30);
  39848. else
  39849. stopTimer();
  39850. }
  39851. void ProgressBar::timerCallback()
  39852. {
  39853. double newProgress = progress;
  39854. const uint32 now = Time::getMillisecondCounter();
  39855. const int timeSinceLastCallback = (int) (now - lastCallbackTime);
  39856. lastCallbackTime = now;
  39857. if (currentValue != newProgress
  39858. || newProgress < 0 || newProgress >= 1.0
  39859. || currentMessage != displayedMessage)
  39860. {
  39861. if (currentValue < newProgress
  39862. && newProgress >= 0 && newProgress < 1.0
  39863. && currentValue >= 0 && currentValue < 1.0)
  39864. {
  39865. newProgress = jmin (currentValue + 0.0008 * timeSinceLastCallback,
  39866. newProgress);
  39867. }
  39868. currentValue = newProgress;
  39869. currentMessage = displayedMessage;
  39870. repaint();
  39871. }
  39872. }
  39873. END_JUCE_NAMESPACE
  39874. /*** End of inlined file: juce_ProgressBar.cpp ***/
  39875. /*** Start of inlined file: juce_Slider.cpp ***/
  39876. BEGIN_JUCE_NAMESPACE
  39877. class SliderPopupDisplayComponent : public BubbleComponent
  39878. {
  39879. public:
  39880. SliderPopupDisplayComponent (Slider* const owner_)
  39881. : owner (owner_),
  39882. font (15.0f, Font::bold)
  39883. {
  39884. setAlwaysOnTop (true);
  39885. }
  39886. ~SliderPopupDisplayComponent()
  39887. {
  39888. }
  39889. void paintContent (Graphics& g, int w, int h)
  39890. {
  39891. g.setFont (font);
  39892. g.setColour (Colours::black);
  39893. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  39894. }
  39895. void getContentSize (int& w, int& h)
  39896. {
  39897. w = font.getStringWidth (text) + 18;
  39898. h = (int) (font.getHeight() * 1.6f);
  39899. }
  39900. void updatePosition (const String& newText)
  39901. {
  39902. if (text != newText)
  39903. {
  39904. text = newText;
  39905. repaint();
  39906. }
  39907. BubbleComponent::setPosition (owner);
  39908. }
  39909. juce_UseDebuggingNewOperator
  39910. private:
  39911. Slider* owner;
  39912. Font font;
  39913. String text;
  39914. SliderPopupDisplayComponent (const SliderPopupDisplayComponent&);
  39915. SliderPopupDisplayComponent& operator= (const SliderPopupDisplayComponent&);
  39916. };
  39917. Slider::Slider (const String& name)
  39918. : Component (name),
  39919. lastCurrentValue (0),
  39920. lastValueMin (0),
  39921. lastValueMax (0),
  39922. minimum (0),
  39923. maximum (10),
  39924. interval (0),
  39925. skewFactor (1.0),
  39926. velocityModeSensitivity (1.0),
  39927. velocityModeOffset (0.0),
  39928. velocityModeThreshold (1),
  39929. rotaryStart (float_Pi * 1.2f),
  39930. rotaryEnd (float_Pi * 2.8f),
  39931. numDecimalPlaces (7),
  39932. sliderRegionStart (0),
  39933. sliderRegionSize (1),
  39934. sliderBeingDragged (-1),
  39935. pixelsForFullDragExtent (250),
  39936. style (LinearHorizontal),
  39937. textBoxPos (TextBoxLeft),
  39938. textBoxWidth (80),
  39939. textBoxHeight (20),
  39940. incDecButtonMode (incDecButtonsNotDraggable),
  39941. editableText (true),
  39942. doubleClickToValue (false),
  39943. isVelocityBased (false),
  39944. userKeyOverridesVelocity (true),
  39945. rotaryStop (true),
  39946. incDecButtonsSideBySide (false),
  39947. sendChangeOnlyOnRelease (false),
  39948. popupDisplayEnabled (false),
  39949. menuEnabled (false),
  39950. menuShown (false),
  39951. scrollWheelEnabled (true),
  39952. snapsToMousePos (true),
  39953. valueBox (0),
  39954. incButton (0),
  39955. decButton (0),
  39956. popupDisplay (0),
  39957. parentForPopupDisplay (0)
  39958. {
  39959. setWantsKeyboardFocus (false);
  39960. setRepaintsOnMouseActivity (true);
  39961. lookAndFeelChanged();
  39962. updateText();
  39963. currentValue.addListener (this);
  39964. valueMin.addListener (this);
  39965. valueMax.addListener (this);
  39966. }
  39967. Slider::~Slider()
  39968. {
  39969. currentValue.removeListener (this);
  39970. valueMin.removeListener (this);
  39971. valueMax.removeListener (this);
  39972. popupDisplay = 0;
  39973. deleteAllChildren();
  39974. }
  39975. void Slider::handleAsyncUpdate()
  39976. {
  39977. cancelPendingUpdate();
  39978. Component::BailOutChecker checker (this);
  39979. listeners.callChecked (checker, &SliderListener::sliderValueChanged, this); // (can't use Slider::Listener due to idiotic VC2005 bug)
  39980. }
  39981. void Slider::sendDragStart()
  39982. {
  39983. startedDragging();
  39984. Component::BailOutChecker checker (this);
  39985. listeners.callChecked (checker, &SliderListener::sliderDragStarted, this);
  39986. }
  39987. void Slider::sendDragEnd()
  39988. {
  39989. stoppedDragging();
  39990. sliderBeingDragged = -1;
  39991. Component::BailOutChecker checker (this);
  39992. listeners.callChecked (checker, &SliderListener::sliderDragEnded, this);
  39993. }
  39994. void Slider::addListener (Listener* const listener)
  39995. {
  39996. listeners.add (listener);
  39997. }
  39998. void Slider::removeListener (Listener* const listener)
  39999. {
  40000. listeners.remove (listener);
  40001. }
  40002. void Slider::setSliderStyle (const SliderStyle newStyle)
  40003. {
  40004. if (style != newStyle)
  40005. {
  40006. style = newStyle;
  40007. repaint();
  40008. lookAndFeelChanged();
  40009. }
  40010. }
  40011. void Slider::setRotaryParameters (const float startAngleRadians,
  40012. const float endAngleRadians,
  40013. const bool stopAtEnd)
  40014. {
  40015. // make sure the values are sensible..
  40016. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  40017. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  40018. jassert (rotaryStart < rotaryEnd);
  40019. rotaryStart = startAngleRadians;
  40020. rotaryEnd = endAngleRadians;
  40021. rotaryStop = stopAtEnd;
  40022. }
  40023. void Slider::setVelocityBasedMode (const bool velBased)
  40024. {
  40025. isVelocityBased = velBased;
  40026. }
  40027. void Slider::setVelocityModeParameters (const double sensitivity,
  40028. const int threshold,
  40029. const double offset,
  40030. const bool userCanPressKeyToSwapMode)
  40031. {
  40032. jassert (threshold >= 0);
  40033. jassert (sensitivity > 0);
  40034. jassert (offset >= 0);
  40035. velocityModeSensitivity = sensitivity;
  40036. velocityModeOffset = offset;
  40037. velocityModeThreshold = threshold;
  40038. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  40039. }
  40040. void Slider::setSkewFactor (const double factor)
  40041. {
  40042. skewFactor = factor;
  40043. }
  40044. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint)
  40045. {
  40046. if (maximum > minimum)
  40047. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  40048. / (maximum - minimum));
  40049. }
  40050. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  40051. {
  40052. jassert (distanceForFullScaleDrag > 0);
  40053. pixelsForFullDragExtent = distanceForFullScaleDrag;
  40054. }
  40055. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  40056. {
  40057. if (incDecButtonMode != mode)
  40058. {
  40059. incDecButtonMode = mode;
  40060. lookAndFeelChanged();
  40061. }
  40062. }
  40063. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  40064. const bool isReadOnly,
  40065. const int textEntryBoxWidth,
  40066. const int textEntryBoxHeight)
  40067. {
  40068. if (textBoxPos != newPosition
  40069. || editableText != (! isReadOnly)
  40070. || textBoxWidth != textEntryBoxWidth
  40071. || textBoxHeight != textEntryBoxHeight)
  40072. {
  40073. textBoxPos = newPosition;
  40074. editableText = ! isReadOnly;
  40075. textBoxWidth = textEntryBoxWidth;
  40076. textBoxHeight = textEntryBoxHeight;
  40077. repaint();
  40078. lookAndFeelChanged();
  40079. }
  40080. }
  40081. void Slider::setTextBoxIsEditable (const bool shouldBeEditable)
  40082. {
  40083. editableText = shouldBeEditable;
  40084. if (valueBox != 0)
  40085. valueBox->setEditable (shouldBeEditable && isEnabled());
  40086. }
  40087. void Slider::showTextBox()
  40088. {
  40089. jassert (editableText); // this should probably be avoided in read-only sliders.
  40090. if (valueBox != 0)
  40091. valueBox->showEditor();
  40092. }
  40093. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  40094. {
  40095. if (valueBox != 0)
  40096. {
  40097. valueBox->hideEditor (discardCurrentEditorContents);
  40098. if (discardCurrentEditorContents)
  40099. updateText();
  40100. }
  40101. }
  40102. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease)
  40103. {
  40104. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  40105. }
  40106. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse)
  40107. {
  40108. snapsToMousePos = shouldSnapToMouse;
  40109. }
  40110. void Slider::setPopupDisplayEnabled (const bool enabled,
  40111. Component* const parentComponentToUse)
  40112. {
  40113. popupDisplayEnabled = enabled;
  40114. parentForPopupDisplay = parentComponentToUse;
  40115. }
  40116. void Slider::colourChanged()
  40117. {
  40118. lookAndFeelChanged();
  40119. }
  40120. void Slider::lookAndFeelChanged()
  40121. {
  40122. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  40123. : getTextFromValue (currentValue.getValue()));
  40124. deleteAllChildren();
  40125. valueBox = 0;
  40126. LookAndFeel& lf = getLookAndFeel();
  40127. if (textBoxPos != NoTextBox)
  40128. {
  40129. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  40130. valueBox->setWantsKeyboardFocus (false);
  40131. valueBox->setText (previousTextBoxContent, false);
  40132. valueBox->setEditable (editableText && isEnabled());
  40133. valueBox->addListener (this);
  40134. if (style == LinearBar)
  40135. valueBox->addMouseListener (this, false);
  40136. valueBox->setTooltip (getTooltip());
  40137. }
  40138. if (style == IncDecButtons)
  40139. {
  40140. addAndMakeVisible (incButton = lf.createSliderButton (true));
  40141. incButton->addButtonListener (this);
  40142. addAndMakeVisible (decButton = lf.createSliderButton (false));
  40143. decButton->addButtonListener (this);
  40144. if (incDecButtonMode != incDecButtonsNotDraggable)
  40145. {
  40146. incButton->addMouseListener (this, false);
  40147. decButton->addMouseListener (this, false);
  40148. }
  40149. else
  40150. {
  40151. incButton->setRepeatSpeed (300, 100, 20);
  40152. incButton->addMouseListener (decButton, false);
  40153. decButton->setRepeatSpeed (300, 100, 20);
  40154. decButton->addMouseListener (incButton, false);
  40155. }
  40156. incButton->setTooltip (getTooltip());
  40157. decButton->setTooltip (getTooltip());
  40158. }
  40159. setComponentEffect (lf.getSliderEffect());
  40160. resized();
  40161. repaint();
  40162. }
  40163. void Slider::setRange (const double newMin,
  40164. const double newMax,
  40165. const double newInt)
  40166. {
  40167. if (minimum != newMin
  40168. || maximum != newMax
  40169. || interval != newInt)
  40170. {
  40171. minimum = newMin;
  40172. maximum = newMax;
  40173. interval = newInt;
  40174. // figure out the number of DPs needed to display all values at this
  40175. // interval setting.
  40176. numDecimalPlaces = 7;
  40177. if (newInt != 0)
  40178. {
  40179. int v = abs ((int) (newInt * 10000000));
  40180. while ((v % 10) == 0)
  40181. {
  40182. --numDecimalPlaces;
  40183. v /= 10;
  40184. }
  40185. }
  40186. // keep the current values inside the new range..
  40187. if (style != TwoValueHorizontal && style != TwoValueVertical)
  40188. {
  40189. setValue (getValue(), false, false);
  40190. }
  40191. else
  40192. {
  40193. setMinValue (getMinValue(), false, false);
  40194. setMaxValue (getMaxValue(), false, false);
  40195. }
  40196. updateText();
  40197. }
  40198. }
  40199. void Slider::triggerChangeMessage (const bool synchronous)
  40200. {
  40201. if (synchronous)
  40202. handleAsyncUpdate();
  40203. else
  40204. triggerAsyncUpdate();
  40205. valueChanged();
  40206. }
  40207. void Slider::valueChanged (Value& value)
  40208. {
  40209. if (value.refersToSameSourceAs (currentValue))
  40210. {
  40211. if (style != TwoValueHorizontal && style != TwoValueVertical)
  40212. setValue (currentValue.getValue(), false, false);
  40213. }
  40214. else if (value.refersToSameSourceAs (valueMin))
  40215. setMinValue (valueMin.getValue(), false, false, true);
  40216. else if (value.refersToSameSourceAs (valueMax))
  40217. setMaxValue (valueMax.getValue(), false, false, true);
  40218. }
  40219. double Slider::getValue() const
  40220. {
  40221. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  40222. // methods to get the two values.
  40223. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  40224. return currentValue.getValue();
  40225. }
  40226. void Slider::setValue (double newValue,
  40227. const bool sendUpdateMessage,
  40228. const bool sendMessageSynchronously)
  40229. {
  40230. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  40231. // methods to set the two values.
  40232. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  40233. newValue = constrainedValue (newValue);
  40234. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40235. {
  40236. jassert ((double) valueMin.getValue() <= (double) valueMax.getValue());
  40237. newValue = jlimit ((double) valueMin.getValue(),
  40238. (double) valueMax.getValue(),
  40239. newValue);
  40240. }
  40241. if (newValue != lastCurrentValue)
  40242. {
  40243. if (valueBox != 0)
  40244. valueBox->hideEditor (true);
  40245. lastCurrentValue = newValue;
  40246. currentValue = newValue;
  40247. updateText();
  40248. repaint();
  40249. if (popupDisplay != 0)
  40250. {
  40251. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40252. ->updatePosition (getTextFromValue (newValue));
  40253. popupDisplay->repaint();
  40254. }
  40255. if (sendUpdateMessage)
  40256. triggerChangeMessage (sendMessageSynchronously);
  40257. }
  40258. }
  40259. double Slider::getMinValue() const
  40260. {
  40261. // The minimum value only applies to sliders that are in two- or three-value mode.
  40262. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40263. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40264. return valueMin.getValue();
  40265. }
  40266. double Slider::getMaxValue() const
  40267. {
  40268. // The maximum value only applies to sliders that are in two- or three-value mode.
  40269. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40270. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40271. return valueMax.getValue();
  40272. }
  40273. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  40274. {
  40275. // The minimum value only applies to sliders that are in two- or three-value mode.
  40276. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40277. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40278. newValue = constrainedValue (newValue);
  40279. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40280. {
  40281. if (allowNudgingOfOtherValues && newValue > (double) valueMax.getValue())
  40282. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40283. newValue = jmin ((double) valueMax.getValue(), newValue);
  40284. }
  40285. else
  40286. {
  40287. if (allowNudgingOfOtherValues && newValue > lastCurrentValue)
  40288. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40289. newValue = jmin (lastCurrentValue, newValue);
  40290. }
  40291. if (lastValueMin != newValue)
  40292. {
  40293. lastValueMin = newValue;
  40294. valueMin = newValue;
  40295. repaint();
  40296. if (popupDisplay != 0)
  40297. {
  40298. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40299. ->updatePosition (getTextFromValue (newValue));
  40300. popupDisplay->repaint();
  40301. }
  40302. if (sendUpdateMessage)
  40303. triggerChangeMessage (sendMessageSynchronously);
  40304. }
  40305. }
  40306. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  40307. {
  40308. // The maximum value only applies to sliders that are in two- or three-value mode.
  40309. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40310. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40311. newValue = constrainedValue (newValue);
  40312. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40313. {
  40314. if (allowNudgingOfOtherValues && newValue < (double) valueMin.getValue())
  40315. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40316. newValue = jmax ((double) valueMin.getValue(), newValue);
  40317. }
  40318. else
  40319. {
  40320. if (allowNudgingOfOtherValues && newValue < lastCurrentValue)
  40321. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40322. newValue = jmax (lastCurrentValue, newValue);
  40323. }
  40324. if (lastValueMax != newValue)
  40325. {
  40326. lastValueMax = newValue;
  40327. valueMax = newValue;
  40328. repaint();
  40329. if (popupDisplay != 0)
  40330. {
  40331. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40332. ->updatePosition (getTextFromValue (valueMax.getValue()));
  40333. popupDisplay->repaint();
  40334. }
  40335. if (sendUpdateMessage)
  40336. triggerChangeMessage (sendMessageSynchronously);
  40337. }
  40338. }
  40339. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  40340. const double valueToSetOnDoubleClick)
  40341. {
  40342. doubleClickToValue = isDoubleClickEnabled;
  40343. doubleClickReturnValue = valueToSetOnDoubleClick;
  40344. }
  40345. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const
  40346. {
  40347. isEnabled_ = doubleClickToValue;
  40348. return doubleClickReturnValue;
  40349. }
  40350. void Slider::updateText()
  40351. {
  40352. if (valueBox != 0)
  40353. valueBox->setText (getTextFromValue (currentValue.getValue()), false);
  40354. }
  40355. void Slider::setTextValueSuffix (const String& suffix)
  40356. {
  40357. if (textSuffix != suffix)
  40358. {
  40359. textSuffix = suffix;
  40360. updateText();
  40361. }
  40362. }
  40363. const String Slider::getTextValueSuffix() const
  40364. {
  40365. return textSuffix;
  40366. }
  40367. const String Slider::getTextFromValue (double v)
  40368. {
  40369. if (getNumDecimalPlacesToDisplay() > 0)
  40370. return String (v, getNumDecimalPlacesToDisplay()) + getTextValueSuffix();
  40371. else
  40372. return String (roundToInt (v)) + getTextValueSuffix();
  40373. }
  40374. double Slider::getValueFromText (const String& text)
  40375. {
  40376. String t (text.trimStart());
  40377. if (t.endsWith (textSuffix))
  40378. t = t.substring (0, t.length() - textSuffix.length());
  40379. while (t.startsWithChar ('+'))
  40380. t = t.substring (1).trimStart();
  40381. return t.initialSectionContainingOnly ("0123456789.,-")
  40382. .getDoubleValue();
  40383. }
  40384. double Slider::proportionOfLengthToValue (double proportion)
  40385. {
  40386. if (skewFactor != 1.0 && proportion > 0.0)
  40387. proportion = exp (log (proportion) / skewFactor);
  40388. return minimum + (maximum - minimum) * proportion;
  40389. }
  40390. double Slider::valueToProportionOfLength (double value)
  40391. {
  40392. const double n = (value - minimum) / (maximum - minimum);
  40393. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  40394. }
  40395. double Slider::snapValue (double attemptedValue, const bool)
  40396. {
  40397. return attemptedValue;
  40398. }
  40399. void Slider::startedDragging()
  40400. {
  40401. }
  40402. void Slider::stoppedDragging()
  40403. {
  40404. }
  40405. void Slider::valueChanged()
  40406. {
  40407. }
  40408. void Slider::enablementChanged()
  40409. {
  40410. repaint();
  40411. }
  40412. void Slider::setPopupMenuEnabled (const bool menuEnabled_)
  40413. {
  40414. menuEnabled = menuEnabled_;
  40415. }
  40416. void Slider::setScrollWheelEnabled (const bool enabled)
  40417. {
  40418. scrollWheelEnabled = enabled;
  40419. }
  40420. void Slider::labelTextChanged (Label* label)
  40421. {
  40422. const double newValue = snapValue (getValueFromText (label->getText()), false);
  40423. if (newValue != (double) currentValue.getValue())
  40424. {
  40425. sendDragStart();
  40426. setValue (newValue, true, true);
  40427. sendDragEnd();
  40428. }
  40429. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  40430. }
  40431. void Slider::buttonClicked (Button* button)
  40432. {
  40433. if (style == IncDecButtons)
  40434. {
  40435. sendDragStart();
  40436. if (button == incButton)
  40437. setValue (snapValue (getValue() + interval, false), true, true);
  40438. else if (button == decButton)
  40439. setValue (snapValue (getValue() - interval, false), true, true);
  40440. sendDragEnd();
  40441. }
  40442. }
  40443. double Slider::constrainedValue (double value) const
  40444. {
  40445. if (interval > 0)
  40446. value = minimum + interval * std::floor ((value - minimum) / interval + 0.5);
  40447. if (value <= minimum || maximum <= minimum)
  40448. value = minimum;
  40449. else if (value >= maximum)
  40450. value = maximum;
  40451. return value;
  40452. }
  40453. float Slider::getLinearSliderPos (const double value)
  40454. {
  40455. double sliderPosProportional;
  40456. if (maximum > minimum)
  40457. {
  40458. if (value < minimum)
  40459. {
  40460. sliderPosProportional = 0.0;
  40461. }
  40462. else if (value > maximum)
  40463. {
  40464. sliderPosProportional = 1.0;
  40465. }
  40466. else
  40467. {
  40468. sliderPosProportional = valueToProportionOfLength (value);
  40469. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  40470. }
  40471. }
  40472. else
  40473. {
  40474. sliderPosProportional = 0.5;
  40475. }
  40476. if (isVertical() || style == IncDecButtons)
  40477. sliderPosProportional = 1.0 - sliderPosProportional;
  40478. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  40479. }
  40480. bool Slider::isHorizontal() const
  40481. {
  40482. return style == LinearHorizontal
  40483. || style == LinearBar
  40484. || style == TwoValueHorizontal
  40485. || style == ThreeValueHorizontal;
  40486. }
  40487. bool Slider::isVertical() const
  40488. {
  40489. return style == LinearVertical
  40490. || style == TwoValueVertical
  40491. || style == ThreeValueVertical;
  40492. }
  40493. bool Slider::incDecDragDirectionIsHorizontal() const
  40494. {
  40495. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  40496. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  40497. }
  40498. float Slider::getPositionOfValue (const double value)
  40499. {
  40500. if (isHorizontal() || isVertical())
  40501. {
  40502. return getLinearSliderPos (value);
  40503. }
  40504. else
  40505. {
  40506. jassertfalse; // not a valid call on a slider that doesn't work linearly!
  40507. return 0.0f;
  40508. }
  40509. }
  40510. void Slider::paint (Graphics& g)
  40511. {
  40512. if (style != IncDecButtons)
  40513. {
  40514. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40515. {
  40516. const float sliderPos = (float) valueToProportionOfLength (lastCurrentValue);
  40517. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  40518. getLookAndFeel().drawRotarySlider (g,
  40519. sliderRect.getX(),
  40520. sliderRect.getY(),
  40521. sliderRect.getWidth(),
  40522. sliderRect.getHeight(),
  40523. sliderPos,
  40524. rotaryStart, rotaryEnd,
  40525. *this);
  40526. }
  40527. else
  40528. {
  40529. getLookAndFeel().drawLinearSlider (g,
  40530. sliderRect.getX(),
  40531. sliderRect.getY(),
  40532. sliderRect.getWidth(),
  40533. sliderRect.getHeight(),
  40534. getLinearSliderPos (lastCurrentValue),
  40535. getLinearSliderPos (lastValueMin),
  40536. getLinearSliderPos (lastValueMax),
  40537. style,
  40538. *this);
  40539. }
  40540. if (style == LinearBar && valueBox == 0)
  40541. {
  40542. g.setColour (findColour (Slider::textBoxOutlineColourId));
  40543. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  40544. }
  40545. }
  40546. }
  40547. void Slider::resized()
  40548. {
  40549. int minXSpace = 0;
  40550. int minYSpace = 0;
  40551. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40552. minXSpace = 30;
  40553. else
  40554. minYSpace = 15;
  40555. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  40556. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  40557. if (style == LinearBar)
  40558. {
  40559. if (valueBox != 0)
  40560. valueBox->setBounds (getLocalBounds());
  40561. }
  40562. else
  40563. {
  40564. if (textBoxPos == NoTextBox)
  40565. {
  40566. sliderRect = getLocalBounds();
  40567. }
  40568. else if (textBoxPos == TextBoxLeft)
  40569. {
  40570. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  40571. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  40572. }
  40573. else if (textBoxPos == TextBoxRight)
  40574. {
  40575. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  40576. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  40577. }
  40578. else if (textBoxPos == TextBoxAbove)
  40579. {
  40580. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  40581. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  40582. }
  40583. else if (textBoxPos == TextBoxBelow)
  40584. {
  40585. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  40586. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  40587. }
  40588. }
  40589. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  40590. if (style == LinearBar)
  40591. {
  40592. const int barIndent = 1;
  40593. sliderRegionStart = barIndent;
  40594. sliderRegionSize = getWidth() - barIndent * 2;
  40595. sliderRect.setBounds (sliderRegionStart, barIndent,
  40596. sliderRegionSize, getHeight() - barIndent * 2);
  40597. }
  40598. else if (isHorizontal())
  40599. {
  40600. sliderRegionStart = sliderRect.getX() + indent;
  40601. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  40602. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  40603. sliderRegionSize, sliderRect.getHeight());
  40604. }
  40605. else if (isVertical())
  40606. {
  40607. sliderRegionStart = sliderRect.getY() + indent;
  40608. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  40609. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  40610. sliderRect.getWidth(), sliderRegionSize);
  40611. }
  40612. else
  40613. {
  40614. sliderRegionStart = 0;
  40615. sliderRegionSize = 100;
  40616. }
  40617. if (style == IncDecButtons)
  40618. {
  40619. Rectangle<int> buttonRect (sliderRect);
  40620. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40621. buttonRect.expand (-2, 0);
  40622. else
  40623. buttonRect.expand (0, -2);
  40624. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  40625. if (incDecButtonsSideBySide)
  40626. {
  40627. decButton->setBounds (buttonRect.getX(),
  40628. buttonRect.getY(),
  40629. buttonRect.getWidth() / 2,
  40630. buttonRect.getHeight());
  40631. decButton->setConnectedEdges (Button::ConnectedOnRight);
  40632. incButton->setBounds (buttonRect.getCentreX(),
  40633. buttonRect.getY(),
  40634. buttonRect.getWidth() / 2,
  40635. buttonRect.getHeight());
  40636. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  40637. }
  40638. else
  40639. {
  40640. incButton->setBounds (buttonRect.getX(),
  40641. buttonRect.getY(),
  40642. buttonRect.getWidth(),
  40643. buttonRect.getHeight() / 2);
  40644. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  40645. decButton->setBounds (buttonRect.getX(),
  40646. buttonRect.getCentreY(),
  40647. buttonRect.getWidth(),
  40648. buttonRect.getHeight() / 2);
  40649. decButton->setConnectedEdges (Button::ConnectedOnTop);
  40650. }
  40651. }
  40652. }
  40653. void Slider::focusOfChildComponentChanged (FocusChangeType)
  40654. {
  40655. repaint();
  40656. }
  40657. void Slider::mouseDown (const MouseEvent& e)
  40658. {
  40659. mouseWasHidden = false;
  40660. incDecDragged = false;
  40661. mouseXWhenLastDragged = e.x;
  40662. mouseYWhenLastDragged = e.y;
  40663. mouseDragStartX = e.getMouseDownX();
  40664. mouseDragStartY = e.getMouseDownY();
  40665. if (isEnabled())
  40666. {
  40667. if (e.mods.isPopupMenu() && menuEnabled)
  40668. {
  40669. menuShown = true;
  40670. PopupMenu m;
  40671. m.setLookAndFeel (&getLookAndFeel());
  40672. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  40673. m.addSeparator();
  40674. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40675. {
  40676. PopupMenu rotaryMenu;
  40677. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  40678. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  40679. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  40680. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  40681. }
  40682. const int r = m.show();
  40683. if (r == 1)
  40684. {
  40685. setVelocityBasedMode (! isVelocityBased);
  40686. }
  40687. else if (r == 2)
  40688. {
  40689. setSliderStyle (Rotary);
  40690. }
  40691. else if (r == 3)
  40692. {
  40693. setSliderStyle (RotaryHorizontalDrag);
  40694. }
  40695. else if (r == 4)
  40696. {
  40697. setSliderStyle (RotaryVerticalDrag);
  40698. }
  40699. }
  40700. else if (maximum > minimum)
  40701. {
  40702. menuShown = false;
  40703. if (valueBox != 0)
  40704. valueBox->hideEditor (true);
  40705. sliderBeingDragged = 0;
  40706. if (style == TwoValueHorizontal
  40707. || style == TwoValueVertical
  40708. || style == ThreeValueHorizontal
  40709. || style == ThreeValueVertical)
  40710. {
  40711. const float mousePos = (float) (isVertical() ? e.y : e.x);
  40712. const float normalPosDistance = std::abs (getLinearSliderPos (currentValue.getValue()) - mousePos);
  40713. const float minPosDistance = std::abs (getLinearSliderPos (valueMin.getValue()) - 0.1f - mousePos);
  40714. const float maxPosDistance = std::abs (getLinearSliderPos (valueMax.getValue()) + 0.1f - mousePos);
  40715. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40716. {
  40717. if (maxPosDistance <= minPosDistance)
  40718. sliderBeingDragged = 2;
  40719. else
  40720. sliderBeingDragged = 1;
  40721. }
  40722. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40723. {
  40724. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  40725. sliderBeingDragged = 1;
  40726. else if (normalPosDistance >= maxPosDistance)
  40727. sliderBeingDragged = 2;
  40728. }
  40729. }
  40730. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40731. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  40732. * valueToProportionOfLength (currentValue.getValue());
  40733. valueWhenLastDragged = ((sliderBeingDragged == 2) ? valueMax
  40734. : ((sliderBeingDragged == 1) ? valueMin
  40735. : currentValue)).getValue();
  40736. valueOnMouseDown = valueWhenLastDragged;
  40737. if (popupDisplayEnabled)
  40738. {
  40739. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  40740. popupDisplay = popup;
  40741. if (parentForPopupDisplay != 0)
  40742. {
  40743. parentForPopupDisplay->addChildComponent (popup);
  40744. }
  40745. else
  40746. {
  40747. popup->addToDesktop (0);
  40748. }
  40749. popup->setVisible (true);
  40750. }
  40751. sendDragStart();
  40752. mouseDrag (e);
  40753. }
  40754. }
  40755. }
  40756. void Slider::mouseUp (const MouseEvent&)
  40757. {
  40758. if (isEnabled()
  40759. && (! menuShown)
  40760. && (maximum > minimum)
  40761. && (style != IncDecButtons || incDecDragged))
  40762. {
  40763. restoreMouseIfHidden();
  40764. if (sendChangeOnlyOnRelease && valueOnMouseDown != (double) currentValue.getValue())
  40765. triggerChangeMessage (false);
  40766. sendDragEnd();
  40767. popupDisplay = 0;
  40768. if (style == IncDecButtons)
  40769. {
  40770. incButton->setState (Button::buttonNormal);
  40771. decButton->setState (Button::buttonNormal);
  40772. }
  40773. }
  40774. }
  40775. void Slider::restoreMouseIfHidden()
  40776. {
  40777. if (mouseWasHidden)
  40778. {
  40779. mouseWasHidden = false;
  40780. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  40781. Desktop::getInstance().getMouseSource(i)->enableUnboundedMouseMovement (false);
  40782. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  40783. : ((sliderBeingDragged == 1) ? getMinValue()
  40784. : (double) currentValue.getValue());
  40785. Point<int> mousePos;
  40786. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40787. {
  40788. mousePos = Desktop::getLastMouseDownPosition();
  40789. if (style == RotaryHorizontalDrag)
  40790. {
  40791. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  40792. mousePos += Point<int> (roundToInt (pixelsForFullDragExtent * posDiff), 0);
  40793. }
  40794. else
  40795. {
  40796. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  40797. mousePos += Point<int> (0, roundToInt (pixelsForFullDragExtent * posDiff));
  40798. }
  40799. }
  40800. else
  40801. {
  40802. const int pixelPos = (int) getLinearSliderPos (pos);
  40803. mousePos = relativePositionToGlobal (Point<int> (isHorizontal() ? pixelPos : (getWidth() / 2),
  40804. isVertical() ? pixelPos : (getHeight() / 2)));
  40805. }
  40806. Desktop::setMousePosition (mousePos);
  40807. }
  40808. }
  40809. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  40810. {
  40811. if (isEnabled()
  40812. && style != IncDecButtons
  40813. && style != Rotary
  40814. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  40815. {
  40816. restoreMouseIfHidden();
  40817. }
  40818. }
  40819. static double smallestAngleBetween (double a1, double a2)
  40820. {
  40821. return jmin (std::abs (a1 - a2),
  40822. std::abs (a1 + double_Pi * 2.0 - a2),
  40823. std::abs (a2 + double_Pi * 2.0 - a1));
  40824. }
  40825. void Slider::mouseDrag (const MouseEvent& e)
  40826. {
  40827. if (isEnabled()
  40828. && (! menuShown)
  40829. && (maximum > minimum))
  40830. {
  40831. if (style == Rotary)
  40832. {
  40833. int dx = e.x - sliderRect.getCentreX();
  40834. int dy = e.y - sliderRect.getCentreY();
  40835. if (dx * dx + dy * dy > 25)
  40836. {
  40837. double angle = std::atan2 ((double) dx, (double) -dy);
  40838. while (angle < 0.0)
  40839. angle += double_Pi * 2.0;
  40840. if (rotaryStop && ! e.mouseWasClicked())
  40841. {
  40842. if (std::abs (angle - lastAngle) > double_Pi)
  40843. {
  40844. if (angle >= lastAngle)
  40845. angle -= double_Pi * 2.0;
  40846. else
  40847. angle += double_Pi * 2.0;
  40848. }
  40849. if (angle >= lastAngle)
  40850. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  40851. else
  40852. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  40853. }
  40854. else
  40855. {
  40856. while (angle < rotaryStart)
  40857. angle += double_Pi * 2.0;
  40858. if (angle > rotaryEnd)
  40859. {
  40860. if (smallestAngleBetween (angle, rotaryStart) <= smallestAngleBetween (angle, rotaryEnd))
  40861. angle = rotaryStart;
  40862. else
  40863. angle = rotaryEnd;
  40864. }
  40865. }
  40866. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  40867. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  40868. lastAngle = angle;
  40869. }
  40870. }
  40871. else
  40872. {
  40873. if (style == LinearBar && e.mouseWasClicked()
  40874. && valueBox != 0 && valueBox->isEditable())
  40875. return;
  40876. if (style == IncDecButtons && ! incDecDragged)
  40877. {
  40878. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  40879. return;
  40880. incDecDragged = true;
  40881. mouseDragStartX = e.x;
  40882. mouseDragStartY = e.y;
  40883. }
  40884. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  40885. : false))
  40886. || ((maximum - minimum) / sliderRegionSize < interval))
  40887. {
  40888. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  40889. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  40890. if (style == RotaryHorizontalDrag
  40891. || style == RotaryVerticalDrag
  40892. || style == IncDecButtons
  40893. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  40894. && ! snapsToMousePos))
  40895. {
  40896. const int mouseDiff = (style == RotaryHorizontalDrag
  40897. || style == LinearHorizontal
  40898. || style == LinearBar
  40899. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40900. ? e.x - mouseDragStartX
  40901. : mouseDragStartY - e.y;
  40902. double newPos = valueToProportionOfLength (valueOnMouseDown)
  40903. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  40904. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  40905. if (style == IncDecButtons)
  40906. {
  40907. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  40908. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  40909. }
  40910. }
  40911. else
  40912. {
  40913. if (isVertical())
  40914. scaledMousePos = 1.0 - scaledMousePos;
  40915. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  40916. }
  40917. }
  40918. else
  40919. {
  40920. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  40921. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40922. ? e.x - mouseXWhenLastDragged
  40923. : e.y - mouseYWhenLastDragged;
  40924. const double maxSpeed = jmax (200, sliderRegionSize);
  40925. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  40926. if (speed != 0)
  40927. {
  40928. speed = 0.2 * velocityModeSensitivity
  40929. * (1.0 + std::sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  40930. + jmax (0.0, (double) (speed - velocityModeThreshold))
  40931. / maxSpeed))));
  40932. if (mouseDiff < 0)
  40933. speed = -speed;
  40934. if (isVertical() || style == RotaryVerticalDrag
  40935. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  40936. speed = -speed;
  40937. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  40938. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  40939. e.source.enableUnboundedMouseMovement (true, false);
  40940. mouseWasHidden = true;
  40941. }
  40942. }
  40943. }
  40944. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  40945. if (sliderBeingDragged == 0)
  40946. {
  40947. setValue (snapValue (valueWhenLastDragged, true),
  40948. ! sendChangeOnlyOnRelease, true);
  40949. }
  40950. else if (sliderBeingDragged == 1)
  40951. {
  40952. setMinValue (snapValue (valueWhenLastDragged, true),
  40953. ! sendChangeOnlyOnRelease, false, true);
  40954. if (e.mods.isShiftDown())
  40955. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  40956. else
  40957. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40958. }
  40959. else
  40960. {
  40961. jassert (sliderBeingDragged == 2);
  40962. setMaxValue (snapValue (valueWhenLastDragged, true),
  40963. ! sendChangeOnlyOnRelease, false, true);
  40964. if (e.mods.isShiftDown())
  40965. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  40966. else
  40967. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40968. }
  40969. mouseXWhenLastDragged = e.x;
  40970. mouseYWhenLastDragged = e.y;
  40971. }
  40972. }
  40973. void Slider::mouseDoubleClick (const MouseEvent&)
  40974. {
  40975. if (doubleClickToValue
  40976. && isEnabled()
  40977. && style != IncDecButtons
  40978. && minimum <= doubleClickReturnValue
  40979. && maximum >= doubleClickReturnValue)
  40980. {
  40981. sendDragStart();
  40982. setValue (doubleClickReturnValue, true, true);
  40983. sendDragEnd();
  40984. }
  40985. }
  40986. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  40987. {
  40988. if (scrollWheelEnabled && isEnabled()
  40989. && style != TwoValueHorizontal
  40990. && style != TwoValueVertical)
  40991. {
  40992. if (maximum > minimum && ! e.mods.isAnyMouseButtonDown())
  40993. {
  40994. if (valueBox != 0)
  40995. valueBox->hideEditor (false);
  40996. const double value = (double) currentValue.getValue();
  40997. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  40998. const double currentPos = valueToProportionOfLength (value);
  40999. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  41000. double delta = (newValue != value)
  41001. ? jmax (std::abs (newValue - value), interval) : 0;
  41002. if (value > newValue)
  41003. delta = -delta;
  41004. sendDragStart();
  41005. setValue (snapValue (value + delta, false), true, true);
  41006. sendDragEnd();
  41007. }
  41008. }
  41009. else
  41010. {
  41011. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  41012. }
  41013. }
  41014. void SliderListener::sliderDragStarted (Slider*) // (can't write Slider::Listener due to idiotic VC2005 bug)
  41015. {
  41016. }
  41017. void SliderListener::sliderDragEnded (Slider*)
  41018. {
  41019. }
  41020. END_JUCE_NAMESPACE
  41021. /*** End of inlined file: juce_Slider.cpp ***/
  41022. /*** Start of inlined file: juce_TableHeaderComponent.cpp ***/
  41023. BEGIN_JUCE_NAMESPACE
  41024. class DragOverlayComp : public Component
  41025. {
  41026. public:
  41027. DragOverlayComp (const Image& image_)
  41028. : image (image_)
  41029. {
  41030. image.duplicateIfShared();
  41031. image.multiplyAllAlphas (0.8f);
  41032. setAlwaysOnTop (true);
  41033. }
  41034. ~DragOverlayComp()
  41035. {
  41036. }
  41037. void paint (Graphics& g)
  41038. {
  41039. g.drawImageAt (image, 0, 0);
  41040. }
  41041. private:
  41042. Image image;
  41043. DragOverlayComp (const DragOverlayComp&);
  41044. DragOverlayComp& operator= (const DragOverlayComp&);
  41045. };
  41046. TableHeaderComponent::TableHeaderComponent()
  41047. : columnsChanged (false),
  41048. columnsResized (false),
  41049. sortChanged (false),
  41050. menuActive (true),
  41051. stretchToFit (false),
  41052. columnIdBeingResized (0),
  41053. columnIdBeingDragged (0),
  41054. columnIdUnderMouse (0),
  41055. lastDeliberateWidth (0)
  41056. {
  41057. }
  41058. TableHeaderComponent::~TableHeaderComponent()
  41059. {
  41060. dragOverlayComp = 0;
  41061. }
  41062. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  41063. {
  41064. menuActive = hasMenu;
  41065. }
  41066. bool TableHeaderComponent::isPopupMenuActive() const { return menuActive; }
  41067. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const
  41068. {
  41069. if (onlyCountVisibleColumns)
  41070. {
  41071. int num = 0;
  41072. for (int i = columns.size(); --i >= 0;)
  41073. if (columns.getUnchecked(i)->isVisible())
  41074. ++num;
  41075. return num;
  41076. }
  41077. else
  41078. {
  41079. return columns.size();
  41080. }
  41081. }
  41082. const String TableHeaderComponent::getColumnName (const int columnId) const
  41083. {
  41084. const ColumnInfo* const ci = getInfoForId (columnId);
  41085. return ci != 0 ? ci->name : String::empty;
  41086. }
  41087. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  41088. {
  41089. ColumnInfo* const ci = getInfoForId (columnId);
  41090. if (ci != 0 && ci->name != newName)
  41091. {
  41092. ci->name = newName;
  41093. sendColumnsChanged();
  41094. }
  41095. }
  41096. void TableHeaderComponent::addColumn (const String& columnName,
  41097. const int columnId,
  41098. const int width,
  41099. const int minimumWidth,
  41100. const int maximumWidth,
  41101. const int propertyFlags,
  41102. const int insertIndex)
  41103. {
  41104. // can't have a duplicate or null ID!
  41105. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  41106. jassert (width > 0);
  41107. ColumnInfo* const ci = new ColumnInfo();
  41108. ci->name = columnName;
  41109. ci->id = columnId;
  41110. ci->width = width;
  41111. ci->lastDeliberateWidth = width;
  41112. ci->minimumWidth = minimumWidth;
  41113. ci->maximumWidth = maximumWidth;
  41114. if (ci->maximumWidth < 0)
  41115. ci->maximumWidth = std::numeric_limits<int>::max();
  41116. jassert (ci->maximumWidth >= ci->minimumWidth);
  41117. ci->propertyFlags = propertyFlags;
  41118. columns.insert (insertIndex, ci);
  41119. sendColumnsChanged();
  41120. }
  41121. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  41122. {
  41123. const int index = getIndexOfColumnId (columnIdToRemove, false);
  41124. if (index >= 0)
  41125. {
  41126. columns.remove (index);
  41127. sortChanged = true;
  41128. sendColumnsChanged();
  41129. }
  41130. }
  41131. void TableHeaderComponent::removeAllColumns()
  41132. {
  41133. if (columns.size() > 0)
  41134. {
  41135. columns.clear();
  41136. sendColumnsChanged();
  41137. }
  41138. }
  41139. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  41140. {
  41141. const int currentIndex = getIndexOfColumnId (columnId, false);
  41142. newIndex = visibleIndexToTotalIndex (newIndex);
  41143. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  41144. {
  41145. columns.move (currentIndex, newIndex);
  41146. sendColumnsChanged();
  41147. }
  41148. }
  41149. int TableHeaderComponent::getColumnWidth (const int columnId) const
  41150. {
  41151. const ColumnInfo* const ci = getInfoForId (columnId);
  41152. return ci != 0 ? ci->width : 0;
  41153. }
  41154. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  41155. {
  41156. ColumnInfo* const ci = getInfoForId (columnId);
  41157. if (ci != 0 && ci->width != newWidth)
  41158. {
  41159. const int numColumns = getNumColumns (true);
  41160. ci->lastDeliberateWidth = ci->width
  41161. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  41162. if (stretchToFit)
  41163. {
  41164. const int index = getIndexOfColumnId (columnId, true) + 1;
  41165. if (((unsigned int) index) < (unsigned int) numColumns)
  41166. {
  41167. const int x = getColumnPosition (index).getX();
  41168. if (lastDeliberateWidth == 0)
  41169. lastDeliberateWidth = getTotalWidth();
  41170. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  41171. }
  41172. }
  41173. repaint();
  41174. columnsResized = true;
  41175. triggerAsyncUpdate();
  41176. }
  41177. }
  41178. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const
  41179. {
  41180. int n = 0;
  41181. for (int i = 0; i < columns.size(); ++i)
  41182. {
  41183. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  41184. {
  41185. if (columns.getUnchecked(i)->id == columnId)
  41186. return n;
  41187. ++n;
  41188. }
  41189. }
  41190. return -1;
  41191. }
  41192. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const
  41193. {
  41194. if (onlyCountVisibleColumns)
  41195. index = visibleIndexToTotalIndex (index);
  41196. const ColumnInfo* const ci = columns [index];
  41197. return (ci != 0) ? ci->id : 0;
  41198. }
  41199. const Rectangle<int> TableHeaderComponent::getColumnPosition (const int index) const
  41200. {
  41201. int x = 0, width = 0, n = 0;
  41202. for (int i = 0; i < columns.size(); ++i)
  41203. {
  41204. x += width;
  41205. if (columns.getUnchecked(i)->isVisible())
  41206. {
  41207. width = columns.getUnchecked(i)->width;
  41208. if (n++ == index)
  41209. break;
  41210. }
  41211. else
  41212. {
  41213. width = 0;
  41214. }
  41215. }
  41216. return Rectangle<int> (x, 0, width, getHeight());
  41217. }
  41218. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const
  41219. {
  41220. if (xToFind >= 0)
  41221. {
  41222. int x = 0;
  41223. for (int i = 0; i < columns.size(); ++i)
  41224. {
  41225. const ColumnInfo* const ci = columns.getUnchecked(i);
  41226. if (ci->isVisible())
  41227. {
  41228. x += ci->width;
  41229. if (xToFind < x)
  41230. return ci->id;
  41231. }
  41232. }
  41233. }
  41234. return 0;
  41235. }
  41236. int TableHeaderComponent::getTotalWidth() const
  41237. {
  41238. int w = 0;
  41239. for (int i = columns.size(); --i >= 0;)
  41240. if (columns.getUnchecked(i)->isVisible())
  41241. w += columns.getUnchecked(i)->width;
  41242. return w;
  41243. }
  41244. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  41245. {
  41246. stretchToFit = shouldStretchToFit;
  41247. lastDeliberateWidth = getTotalWidth();
  41248. resized();
  41249. }
  41250. bool TableHeaderComponent::isStretchToFitActive() const
  41251. {
  41252. return stretchToFit;
  41253. }
  41254. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  41255. {
  41256. if (stretchToFit && getWidth() > 0
  41257. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  41258. {
  41259. lastDeliberateWidth = targetTotalWidth;
  41260. resizeColumnsToFit (0, targetTotalWidth);
  41261. }
  41262. }
  41263. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  41264. {
  41265. targetTotalWidth = jmax (targetTotalWidth, 0);
  41266. StretchableObjectResizer sor;
  41267. int i;
  41268. for (i = firstColumnIndex; i < columns.size(); ++i)
  41269. {
  41270. ColumnInfo* const ci = columns.getUnchecked(i);
  41271. if (ci->isVisible())
  41272. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  41273. }
  41274. sor.resizeToFit (targetTotalWidth);
  41275. int visIndex = 0;
  41276. for (i = firstColumnIndex; i < columns.size(); ++i)
  41277. {
  41278. ColumnInfo* const ci = columns.getUnchecked(i);
  41279. if (ci->isVisible())
  41280. {
  41281. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  41282. (int) std::floor (sor.getItemSize (visIndex++)));
  41283. if (newWidth != ci->width)
  41284. {
  41285. ci->width = newWidth;
  41286. repaint();
  41287. columnsResized = true;
  41288. triggerAsyncUpdate();
  41289. }
  41290. }
  41291. }
  41292. }
  41293. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  41294. {
  41295. ColumnInfo* const ci = getInfoForId (columnId);
  41296. if (ci != 0 && shouldBeVisible != ci->isVisible())
  41297. {
  41298. if (shouldBeVisible)
  41299. ci->propertyFlags |= visible;
  41300. else
  41301. ci->propertyFlags &= ~visible;
  41302. sendColumnsChanged();
  41303. resized();
  41304. }
  41305. }
  41306. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  41307. {
  41308. const ColumnInfo* const ci = getInfoForId (columnId);
  41309. return ci != 0 && ci->isVisible();
  41310. }
  41311. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  41312. {
  41313. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  41314. {
  41315. for (int i = columns.size(); --i >= 0;)
  41316. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  41317. ColumnInfo* const ci = getInfoForId (columnId);
  41318. if (ci != 0)
  41319. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  41320. reSortTable();
  41321. }
  41322. }
  41323. int TableHeaderComponent::getSortColumnId() const
  41324. {
  41325. for (int i = columns.size(); --i >= 0;)
  41326. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  41327. return columns.getUnchecked(i)->id;
  41328. return 0;
  41329. }
  41330. bool TableHeaderComponent::isSortedForwards() const
  41331. {
  41332. for (int i = columns.size(); --i >= 0;)
  41333. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  41334. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  41335. return true;
  41336. }
  41337. void TableHeaderComponent::reSortTable()
  41338. {
  41339. sortChanged = true;
  41340. repaint();
  41341. triggerAsyncUpdate();
  41342. }
  41343. const String TableHeaderComponent::toString() const
  41344. {
  41345. String s;
  41346. XmlElement doc ("TABLELAYOUT");
  41347. doc.setAttribute ("sortedCol", getSortColumnId());
  41348. doc.setAttribute ("sortForwards", isSortedForwards());
  41349. for (int i = 0; i < columns.size(); ++i)
  41350. {
  41351. const ColumnInfo* const ci = columns.getUnchecked (i);
  41352. XmlElement* const e = doc.createNewChildElement ("COLUMN");
  41353. e->setAttribute ("id", ci->id);
  41354. e->setAttribute ("visible", ci->isVisible());
  41355. e->setAttribute ("width", ci->width);
  41356. }
  41357. return doc.createDocument (String::empty, true, false);
  41358. }
  41359. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  41360. {
  41361. XmlDocument doc (storedVersion);
  41362. ScopedPointer <XmlElement> storedXml (doc.getDocumentElement());
  41363. int index = 0;
  41364. if (storedXml != 0 && storedXml->hasTagName ("TABLELAYOUT"))
  41365. {
  41366. forEachXmlChildElement (*storedXml, col)
  41367. {
  41368. const int tabId = col->getIntAttribute ("id");
  41369. ColumnInfo* const ci = getInfoForId (tabId);
  41370. if (ci != 0)
  41371. {
  41372. columns.move (columns.indexOf (ci), index);
  41373. ci->width = col->getIntAttribute ("width");
  41374. setColumnVisible (tabId, col->getBoolAttribute ("visible"));
  41375. }
  41376. ++index;
  41377. }
  41378. columnsResized = true;
  41379. sendColumnsChanged();
  41380. setSortColumnId (storedXml->getIntAttribute ("sortedCol"),
  41381. storedXml->getBoolAttribute ("sortForwards", true));
  41382. }
  41383. }
  41384. void TableHeaderComponent::addListener (Listener* const newListener)
  41385. {
  41386. listeners.addIfNotAlreadyThere (newListener);
  41387. }
  41388. void TableHeaderComponent::removeListener (Listener* const listenerToRemove)
  41389. {
  41390. listeners.removeValue (listenerToRemove);
  41391. }
  41392. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  41393. {
  41394. const ColumnInfo* const ci = getInfoForId (columnId);
  41395. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  41396. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  41397. }
  41398. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  41399. {
  41400. for (int i = 0; i < columns.size(); ++i)
  41401. {
  41402. const ColumnInfo* const ci = columns.getUnchecked(i);
  41403. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  41404. menu.addItem (ci->id, ci->name,
  41405. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  41406. isColumnVisible (ci->id));
  41407. }
  41408. }
  41409. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  41410. {
  41411. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  41412. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  41413. }
  41414. void TableHeaderComponent::paint (Graphics& g)
  41415. {
  41416. LookAndFeel& lf = getLookAndFeel();
  41417. lf.drawTableHeaderBackground (g, *this);
  41418. const Rectangle<int> clip (g.getClipBounds());
  41419. int x = 0;
  41420. for (int i = 0; i < columns.size(); ++i)
  41421. {
  41422. const ColumnInfo* const ci = columns.getUnchecked(i);
  41423. if (ci->isVisible())
  41424. {
  41425. if (x + ci->width > clip.getX()
  41426. && (ci->id != columnIdBeingDragged
  41427. || dragOverlayComp == 0
  41428. || ! dragOverlayComp->isVisible()))
  41429. {
  41430. g.saveState();
  41431. g.setOrigin (x, 0);
  41432. g.reduceClipRegion (0, 0, ci->width, getHeight());
  41433. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  41434. ci->id == columnIdUnderMouse,
  41435. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  41436. ci->propertyFlags);
  41437. g.restoreState();
  41438. }
  41439. x += ci->width;
  41440. if (x >= clip.getRight())
  41441. break;
  41442. }
  41443. }
  41444. }
  41445. void TableHeaderComponent::resized()
  41446. {
  41447. }
  41448. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  41449. {
  41450. updateColumnUnderMouse (e.x, e.y);
  41451. }
  41452. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  41453. {
  41454. updateColumnUnderMouse (e.x, e.y);
  41455. }
  41456. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  41457. {
  41458. updateColumnUnderMouse (e.x, e.y);
  41459. }
  41460. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  41461. {
  41462. repaint();
  41463. columnIdBeingResized = 0;
  41464. columnIdBeingDragged = 0;
  41465. if (columnIdUnderMouse != 0)
  41466. {
  41467. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  41468. if (e.mods.isPopupMenu())
  41469. columnClicked (columnIdUnderMouse, e.mods);
  41470. }
  41471. if (menuActive && e.mods.isPopupMenu())
  41472. showColumnChooserMenu (columnIdUnderMouse);
  41473. }
  41474. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  41475. {
  41476. if (columnIdBeingResized == 0
  41477. && columnIdBeingDragged == 0
  41478. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  41479. {
  41480. dragOverlayComp = 0;
  41481. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  41482. if (columnIdBeingResized != 0)
  41483. {
  41484. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41485. initialColumnWidth = ci->width;
  41486. }
  41487. else
  41488. {
  41489. beginDrag (e);
  41490. }
  41491. }
  41492. if (columnIdBeingResized != 0)
  41493. {
  41494. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41495. if (ci != 0)
  41496. {
  41497. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  41498. initialColumnWidth + e.getDistanceFromDragStartX());
  41499. if (stretchToFit)
  41500. {
  41501. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  41502. int minWidthOnRight = 0;
  41503. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  41504. if (columns.getUnchecked (i)->isVisible())
  41505. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  41506. const Rectangle<int> currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  41507. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  41508. }
  41509. setColumnWidth (columnIdBeingResized, w);
  41510. }
  41511. }
  41512. else if (columnIdBeingDragged != 0)
  41513. {
  41514. if (e.y >= -50 && e.y < getHeight() + 50)
  41515. {
  41516. if (dragOverlayComp != 0)
  41517. {
  41518. dragOverlayComp->setVisible (true);
  41519. dragOverlayComp->setBounds (jlimit (0,
  41520. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  41521. e.x - draggingColumnOffset),
  41522. 0,
  41523. dragOverlayComp->getWidth(),
  41524. getHeight());
  41525. for (int i = columns.size(); --i >= 0;)
  41526. {
  41527. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41528. int newIndex = currentIndex;
  41529. if (newIndex > 0)
  41530. {
  41531. // if the previous column isn't draggable, we can't move our column
  41532. // past it, because that'd change the undraggable column's position..
  41533. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  41534. if ((previous->propertyFlags & draggable) != 0)
  41535. {
  41536. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  41537. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  41538. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  41539. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  41540. {
  41541. --newIndex;
  41542. }
  41543. }
  41544. }
  41545. if (newIndex < columns.size() - 1)
  41546. {
  41547. // if the next column isn't draggable, we can't move our column
  41548. // past it, because that'd change the undraggable column's position..
  41549. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  41550. if ((nextCol->propertyFlags & draggable) != 0)
  41551. {
  41552. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  41553. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  41554. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  41555. > abs (dragOverlayComp->getRight() - rightOfNext))
  41556. {
  41557. ++newIndex;
  41558. }
  41559. }
  41560. }
  41561. if (newIndex != currentIndex)
  41562. moveColumn (columnIdBeingDragged, newIndex);
  41563. else
  41564. break;
  41565. }
  41566. }
  41567. }
  41568. else
  41569. {
  41570. endDrag (draggingColumnOriginalIndex);
  41571. }
  41572. }
  41573. }
  41574. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  41575. {
  41576. if (columnIdBeingDragged == 0)
  41577. {
  41578. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  41579. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  41580. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  41581. {
  41582. columnIdBeingDragged = 0;
  41583. }
  41584. else
  41585. {
  41586. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41587. const Rectangle<int> columnRect (getColumnPosition (draggingColumnOriginalIndex));
  41588. const int temp = columnIdBeingDragged;
  41589. columnIdBeingDragged = 0;
  41590. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  41591. columnIdBeingDragged = temp;
  41592. dragOverlayComp->setBounds (columnRect);
  41593. for (int i = listeners.size(); --i >= 0;)
  41594. {
  41595. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  41596. i = jmin (i, listeners.size() - 1);
  41597. }
  41598. }
  41599. }
  41600. }
  41601. void TableHeaderComponent::endDrag (const int finalIndex)
  41602. {
  41603. if (columnIdBeingDragged != 0)
  41604. {
  41605. moveColumn (columnIdBeingDragged, finalIndex);
  41606. columnIdBeingDragged = 0;
  41607. repaint();
  41608. for (int i = listeners.size(); --i >= 0;)
  41609. {
  41610. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  41611. i = jmin (i, listeners.size() - 1);
  41612. }
  41613. }
  41614. }
  41615. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  41616. {
  41617. mouseDrag (e);
  41618. for (int i = columns.size(); --i >= 0;)
  41619. if (columns.getUnchecked (i)->isVisible())
  41620. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  41621. columnIdBeingResized = 0;
  41622. repaint();
  41623. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  41624. updateColumnUnderMouse (e.x, e.y);
  41625. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  41626. columnClicked (columnIdUnderMouse, e.mods);
  41627. dragOverlayComp = 0;
  41628. }
  41629. const MouseCursor TableHeaderComponent::getMouseCursor()
  41630. {
  41631. if (columnIdBeingResized != 0 || (getResizeDraggerAt (getMouseXYRelative().getX()) != 0 && ! isMouseButtonDown()))
  41632. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  41633. return Component::getMouseCursor();
  41634. }
  41635. bool TableHeaderComponent::ColumnInfo::isVisible() const
  41636. {
  41637. return (propertyFlags & TableHeaderComponent::visible) != 0;
  41638. }
  41639. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const
  41640. {
  41641. for (int i = columns.size(); --i >= 0;)
  41642. if (columns.getUnchecked(i)->id == id)
  41643. return columns.getUnchecked(i);
  41644. return 0;
  41645. }
  41646. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const
  41647. {
  41648. int n = 0;
  41649. for (int i = 0; i < columns.size(); ++i)
  41650. {
  41651. if (columns.getUnchecked(i)->isVisible())
  41652. {
  41653. if (n == visibleIndex)
  41654. return i;
  41655. ++n;
  41656. }
  41657. }
  41658. return -1;
  41659. }
  41660. void TableHeaderComponent::sendColumnsChanged()
  41661. {
  41662. if (stretchToFit && lastDeliberateWidth > 0)
  41663. resizeAllColumnsToFit (lastDeliberateWidth);
  41664. repaint();
  41665. columnsChanged = true;
  41666. triggerAsyncUpdate();
  41667. }
  41668. void TableHeaderComponent::handleAsyncUpdate()
  41669. {
  41670. const bool changed = columnsChanged || sortChanged;
  41671. const bool sized = columnsResized || changed;
  41672. const bool sorted = sortChanged;
  41673. columnsChanged = false;
  41674. columnsResized = false;
  41675. sortChanged = false;
  41676. if (sorted)
  41677. {
  41678. for (int i = listeners.size(); --i >= 0;)
  41679. {
  41680. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  41681. i = jmin (i, listeners.size() - 1);
  41682. }
  41683. }
  41684. if (changed)
  41685. {
  41686. for (int i = listeners.size(); --i >= 0;)
  41687. {
  41688. listeners.getUnchecked(i)->tableColumnsChanged (this);
  41689. i = jmin (i, listeners.size() - 1);
  41690. }
  41691. }
  41692. if (sized)
  41693. {
  41694. for (int i = listeners.size(); --i >= 0;)
  41695. {
  41696. listeners.getUnchecked(i)->tableColumnsResized (this);
  41697. i = jmin (i, listeners.size() - 1);
  41698. }
  41699. }
  41700. }
  41701. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const
  41702. {
  41703. if (((unsigned int) mouseX) < (unsigned int) getWidth())
  41704. {
  41705. const int draggableDistance = 3;
  41706. int x = 0;
  41707. for (int i = 0; i < columns.size(); ++i)
  41708. {
  41709. const ColumnInfo* const ci = columns.getUnchecked(i);
  41710. if (ci->isVisible())
  41711. {
  41712. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  41713. && (ci->propertyFlags & resizable) != 0)
  41714. return ci->id;
  41715. x += ci->width;
  41716. }
  41717. }
  41718. }
  41719. return 0;
  41720. }
  41721. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  41722. {
  41723. const int newCol = (reallyContains (x, y, true) && getResizeDraggerAt (x) == 0)
  41724. ? getColumnIdAtX (x) : 0;
  41725. if (newCol != columnIdUnderMouse)
  41726. {
  41727. columnIdUnderMouse = newCol;
  41728. repaint();
  41729. }
  41730. }
  41731. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  41732. {
  41733. PopupMenu m;
  41734. addMenuItems (m, columnIdClicked);
  41735. if (m.getNumItems() > 0)
  41736. {
  41737. m.setLookAndFeel (&getLookAndFeel());
  41738. const int result = m.show();
  41739. if (result != 0)
  41740. reactToMenuItem (result, columnIdClicked);
  41741. }
  41742. }
  41743. void TableHeaderComponent::Listener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  41744. {
  41745. }
  41746. END_JUCE_NAMESPACE
  41747. /*** End of inlined file: juce_TableHeaderComponent.cpp ***/
  41748. /*** Start of inlined file: juce_TableListBox.cpp ***/
  41749. BEGIN_JUCE_NAMESPACE
  41750. static const char* const tableColumnPropertyTag = "_tableColumnID";
  41751. class TableListRowComp : public Component,
  41752. public TooltipClient
  41753. {
  41754. public:
  41755. TableListRowComp (TableListBox& owner_)
  41756. : owner (owner_),
  41757. row (-1),
  41758. isSelected (false)
  41759. {
  41760. }
  41761. ~TableListRowComp()
  41762. {
  41763. deleteAllChildren();
  41764. }
  41765. void paint (Graphics& g)
  41766. {
  41767. TableListBoxModel* const model = owner.getModel();
  41768. if (model != 0)
  41769. {
  41770. const TableHeaderComponent* const header = owner.getHeader();
  41771. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  41772. const int numColumns = header->getNumColumns (true);
  41773. for (int i = 0; i < numColumns; ++i)
  41774. {
  41775. if (! columnsWithComponents [i])
  41776. {
  41777. const int columnId = header->getColumnIdOfIndex (i, true);
  41778. Rectangle<int> columnRect (header->getColumnPosition (i));
  41779. columnRect.setSize (columnRect.getWidth(), getHeight());
  41780. g.saveState();
  41781. g.reduceClipRegion (columnRect);
  41782. g.setOrigin (columnRect.getX(), 0);
  41783. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  41784. g.restoreState();
  41785. }
  41786. }
  41787. }
  41788. }
  41789. void update (const int newRow, const bool isNowSelected)
  41790. {
  41791. if (newRow != row || isNowSelected != isSelected)
  41792. {
  41793. row = newRow;
  41794. isSelected = isNowSelected;
  41795. repaint();
  41796. deleteAllChildren();
  41797. }
  41798. if (row < owner.getNumRows())
  41799. {
  41800. jassert (row >= 0);
  41801. const Identifier tagPropertyName ("_tableLastUseNum");
  41802. const int newTag = Random::getSystemRandom().nextInt();
  41803. const TableHeaderComponent* const header = owner.getHeader();
  41804. const int numColumns = header->getNumColumns (true);
  41805. columnsWithComponents.clear();
  41806. if (owner.getModel() != 0)
  41807. {
  41808. for (int i = 0; i < numColumns; ++i)
  41809. {
  41810. const int columnId = header->getColumnIdOfIndex (i, true);
  41811. Component* const newComp
  41812. = owner.getModel()->refreshComponentForCell (row, columnId, isSelected,
  41813. findChildComponentForColumn (columnId));
  41814. if (newComp != 0)
  41815. {
  41816. addAndMakeVisible (newComp);
  41817. newComp->getProperties().set (tagPropertyName, newTag);
  41818. newComp->getProperties().set (tableColumnPropertyTag, columnId);
  41819. const Rectangle<int> columnRect (header->getColumnPosition (i));
  41820. newComp->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  41821. columnsWithComponents.setBit (i);
  41822. }
  41823. }
  41824. }
  41825. for (int i = getNumChildComponents(); --i >= 0;)
  41826. {
  41827. Component* const c = getChildComponent (i);
  41828. if ((int) c->getProperties() [tagPropertyName] != newTag)
  41829. delete c;
  41830. }
  41831. }
  41832. else
  41833. {
  41834. columnsWithComponents.clear();
  41835. deleteAllChildren();
  41836. }
  41837. }
  41838. void resized()
  41839. {
  41840. for (int i = getNumChildComponents(); --i >= 0;)
  41841. {
  41842. Component* const c = getChildComponent (i);
  41843. const int columnId = c->getProperties() [tableColumnPropertyTag];
  41844. if (columnId != 0)
  41845. {
  41846. const Rectangle<int> columnRect (owner.getHeader()->getColumnPosition (owner.getHeader()->getIndexOfColumnId (columnId, true)));
  41847. c->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  41848. }
  41849. }
  41850. }
  41851. void mouseDown (const MouseEvent& e)
  41852. {
  41853. isDragging = false;
  41854. selectRowOnMouseUp = false;
  41855. if (isEnabled())
  41856. {
  41857. if (! isSelected)
  41858. {
  41859. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  41860. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41861. if (columnId != 0 && owner.getModel() != 0)
  41862. owner.getModel()->cellClicked (row, columnId, e);
  41863. }
  41864. else
  41865. {
  41866. selectRowOnMouseUp = true;
  41867. }
  41868. }
  41869. }
  41870. void mouseDrag (const MouseEvent& e)
  41871. {
  41872. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  41873. {
  41874. const SparseSet<int> selectedRows (owner.getSelectedRows());
  41875. if (selectedRows.size() > 0)
  41876. {
  41877. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  41878. if (dragDescription.isNotEmpty())
  41879. {
  41880. isDragging = true;
  41881. owner.startDragAndDrop (e, dragDescription);
  41882. }
  41883. }
  41884. }
  41885. }
  41886. void mouseUp (const MouseEvent& e)
  41887. {
  41888. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  41889. {
  41890. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  41891. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41892. if (columnId != 0 && owner.getModel() != 0)
  41893. owner.getModel()->cellClicked (row, columnId, e);
  41894. }
  41895. }
  41896. void mouseDoubleClick (const MouseEvent& e)
  41897. {
  41898. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41899. if (columnId != 0 && owner.getModel() != 0)
  41900. owner.getModel()->cellDoubleClicked (row, columnId, e);
  41901. }
  41902. const String getTooltip()
  41903. {
  41904. const int columnId = owner.getHeader()->getColumnIdAtX (getMouseXYRelative().getX());
  41905. if (columnId != 0 && owner.getModel() != 0)
  41906. return owner.getModel()->getCellTooltip (row, columnId);
  41907. return String::empty;
  41908. }
  41909. Component* findChildComponentForColumn (const int columnId) const
  41910. {
  41911. for (int i = getNumChildComponents(); --i >= 0;)
  41912. {
  41913. Component* const c = getChildComponent (i);
  41914. if ((int) c->getProperties() [tableColumnPropertyTag] == columnId)
  41915. return c;
  41916. }
  41917. return 0;
  41918. }
  41919. juce_UseDebuggingNewOperator
  41920. private:
  41921. TableListBox& owner;
  41922. int row;
  41923. bool isSelected, isDragging, selectRowOnMouseUp;
  41924. BigInteger columnsWithComponents;
  41925. TableListRowComp (const TableListRowComp&);
  41926. TableListRowComp& operator= (const TableListRowComp&);
  41927. };
  41928. class TableListBoxHeader : public TableHeaderComponent
  41929. {
  41930. public:
  41931. TableListBoxHeader (TableListBox& owner_)
  41932. : owner (owner_)
  41933. {
  41934. }
  41935. ~TableListBoxHeader()
  41936. {
  41937. }
  41938. void addMenuItems (PopupMenu& menu, int columnIdClicked)
  41939. {
  41940. if (owner.isAutoSizeMenuOptionShown())
  41941. {
  41942. menu.addItem (0xf836743, TRANS("Auto-size this column"), columnIdClicked != 0);
  41943. menu.addItem (0xf836744, TRANS("Auto-size all columns"), owner.getHeader()->getNumColumns (true) > 0);
  41944. menu.addSeparator();
  41945. }
  41946. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  41947. }
  41948. void reactToMenuItem (int menuReturnId, int columnIdClicked)
  41949. {
  41950. if (menuReturnId == 0xf836743)
  41951. {
  41952. owner.autoSizeColumn (columnIdClicked);
  41953. }
  41954. else if (menuReturnId == 0xf836744)
  41955. {
  41956. owner.autoSizeAllColumns();
  41957. }
  41958. else
  41959. {
  41960. TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked);
  41961. }
  41962. }
  41963. juce_UseDebuggingNewOperator
  41964. private:
  41965. TableListBox& owner;
  41966. TableListBoxHeader (const TableListBoxHeader&);
  41967. TableListBoxHeader& operator= (const TableListBoxHeader&);
  41968. };
  41969. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  41970. : ListBox (name, 0),
  41971. model (model_),
  41972. autoSizeOptionsShown (true)
  41973. {
  41974. ListBox::model = this;
  41975. header = new TableListBoxHeader (*this);
  41976. header->setSize (100, 28);
  41977. header->addListener (this);
  41978. setHeaderComponent (header);
  41979. }
  41980. TableListBox::~TableListBox()
  41981. {
  41982. header = 0;
  41983. }
  41984. void TableListBox::setModel (TableListBoxModel* const newModel)
  41985. {
  41986. if (model != newModel)
  41987. {
  41988. model = newModel;
  41989. updateContent();
  41990. }
  41991. }
  41992. int TableListBox::getHeaderHeight() const
  41993. {
  41994. return header->getHeight();
  41995. }
  41996. void TableListBox::setHeaderHeight (const int newHeight)
  41997. {
  41998. header->setSize (header->getWidth(), newHeight);
  41999. resized();
  42000. }
  42001. void TableListBox::autoSizeColumn (const int columnId)
  42002. {
  42003. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  42004. if (width > 0)
  42005. header->setColumnWidth (columnId, width);
  42006. }
  42007. void TableListBox::autoSizeAllColumns()
  42008. {
  42009. for (int i = 0; i < header->getNumColumns (true); ++i)
  42010. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  42011. }
  42012. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  42013. {
  42014. autoSizeOptionsShown = shouldBeShown;
  42015. }
  42016. bool TableListBox::isAutoSizeMenuOptionShown() const
  42017. {
  42018. return autoSizeOptionsShown;
  42019. }
  42020. const Rectangle<int> TableListBox::getCellPosition (const int columnId,
  42021. const int rowNumber,
  42022. const bool relativeToComponentTopLeft) const
  42023. {
  42024. Rectangle<int> headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  42025. if (relativeToComponentTopLeft)
  42026. headerCell.translate (header->getX(), 0);
  42027. const Rectangle<int> row (getRowPosition (rowNumber, relativeToComponentTopLeft));
  42028. return Rectangle<int> (headerCell.getX(), row.getY(),
  42029. headerCell.getWidth(), row.getHeight());
  42030. }
  42031. Component* TableListBox::getCellComponent (int columnId, int rowNumber) const
  42032. {
  42033. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (rowNumber));
  42034. return rowComp != 0 ? rowComp->findChildComponentForColumn (columnId) : 0;
  42035. }
  42036. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  42037. {
  42038. ScrollBar* const scrollbar = getHorizontalScrollBar();
  42039. if (scrollbar != 0)
  42040. {
  42041. const Rectangle<int> pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  42042. double x = scrollbar->getCurrentRangeStart();
  42043. const double w = scrollbar->getCurrentRangeSize();
  42044. if (pos.getX() < x)
  42045. x = pos.getX();
  42046. else if (pos.getRight() > x + w)
  42047. x += jmax (0.0, pos.getRight() - (x + w));
  42048. scrollbar->setCurrentRangeStart (x);
  42049. }
  42050. }
  42051. int TableListBox::getNumRows()
  42052. {
  42053. return model != 0 ? model->getNumRows() : 0;
  42054. }
  42055. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  42056. {
  42057. }
  42058. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
  42059. {
  42060. if (existingComponentToUpdate == 0)
  42061. existingComponentToUpdate = new TableListRowComp (*this);
  42062. static_cast <TableListRowComp*> (existingComponentToUpdate)->update (rowNumber, isRowSelected_);
  42063. return existingComponentToUpdate;
  42064. }
  42065. void TableListBox::selectedRowsChanged (int row)
  42066. {
  42067. if (model != 0)
  42068. model->selectedRowsChanged (row);
  42069. }
  42070. void TableListBox::deleteKeyPressed (int row)
  42071. {
  42072. if (model != 0)
  42073. model->deleteKeyPressed (row);
  42074. }
  42075. void TableListBox::returnKeyPressed (int row)
  42076. {
  42077. if (model != 0)
  42078. model->returnKeyPressed (row);
  42079. }
  42080. void TableListBox::backgroundClicked()
  42081. {
  42082. if (model != 0)
  42083. model->backgroundClicked();
  42084. }
  42085. void TableListBox::listWasScrolled()
  42086. {
  42087. if (model != 0)
  42088. model->listWasScrolled();
  42089. }
  42090. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  42091. {
  42092. setMinimumContentWidth (header->getTotalWidth());
  42093. repaint();
  42094. updateColumnComponents();
  42095. }
  42096. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  42097. {
  42098. setMinimumContentWidth (header->getTotalWidth());
  42099. repaint();
  42100. updateColumnComponents();
  42101. }
  42102. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  42103. {
  42104. if (model != 0)
  42105. model->sortOrderChanged (header->getSortColumnId(),
  42106. header->isSortedForwards());
  42107. }
  42108. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  42109. {
  42110. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  42111. repaint();
  42112. }
  42113. void TableListBox::resized()
  42114. {
  42115. ListBox::resized();
  42116. header->resizeAllColumnsToFit (getVisibleContentWidth());
  42117. setMinimumContentWidth (header->getTotalWidth());
  42118. }
  42119. void TableListBox::updateColumnComponents() const
  42120. {
  42121. const int firstRow = getRowContainingPosition (0, 0);
  42122. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  42123. {
  42124. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  42125. if (rowComp != 0)
  42126. rowComp->resized();
  42127. }
  42128. }
  42129. void TableListBoxModel::cellClicked (int, int, const MouseEvent&)
  42130. {
  42131. }
  42132. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&)
  42133. {
  42134. }
  42135. void TableListBoxModel::backgroundClicked()
  42136. {
  42137. }
  42138. void TableListBoxModel::sortOrderChanged (int, const bool)
  42139. {
  42140. }
  42141. int TableListBoxModel::getColumnAutoSizeWidth (int)
  42142. {
  42143. return 0;
  42144. }
  42145. void TableListBoxModel::selectedRowsChanged (int)
  42146. {
  42147. }
  42148. void TableListBoxModel::deleteKeyPressed (int)
  42149. {
  42150. }
  42151. void TableListBoxModel::returnKeyPressed (int)
  42152. {
  42153. }
  42154. void TableListBoxModel::listWasScrolled()
  42155. {
  42156. }
  42157. const String TableListBoxModel::getCellTooltip (int /*rowNumber*/, int /*columnId*/)
  42158. {
  42159. return String::empty;
  42160. }
  42161. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  42162. {
  42163. return String::empty;
  42164. }
  42165. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  42166. {
  42167. (void) existingComponentToUpdate;
  42168. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  42169. return 0;
  42170. }
  42171. END_JUCE_NAMESPACE
  42172. /*** End of inlined file: juce_TableListBox.cpp ***/
  42173. /*** Start of inlined file: juce_TextEditor.cpp ***/
  42174. BEGIN_JUCE_NAMESPACE
  42175. // a word or space that can't be broken down any further
  42176. struct TextAtom
  42177. {
  42178. String atomText;
  42179. float width;
  42180. int numChars;
  42181. bool isWhitespace() const { return CharacterFunctions::isWhitespace (atomText[0]); }
  42182. bool isNewLine() const { return atomText[0] == '\r' || atomText[0] == '\n'; }
  42183. const String getText (const juce_wchar passwordCharacter) const
  42184. {
  42185. if (passwordCharacter == 0)
  42186. return atomText;
  42187. else
  42188. return String::repeatedString (String::charToString (passwordCharacter),
  42189. atomText.length());
  42190. }
  42191. const String getTrimmedText (const juce_wchar passwordCharacter) const
  42192. {
  42193. if (passwordCharacter == 0)
  42194. return atomText.substring (0, numChars);
  42195. else if (isNewLine())
  42196. return String::empty;
  42197. else
  42198. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  42199. }
  42200. };
  42201. // a run of text with a single font and colour
  42202. class TextEditor::UniformTextSection
  42203. {
  42204. public:
  42205. UniformTextSection (const String& text,
  42206. const Font& font_,
  42207. const Colour& colour_,
  42208. const juce_wchar passwordCharacter)
  42209. : font (font_),
  42210. colour (colour_)
  42211. {
  42212. initialiseAtoms (text, passwordCharacter);
  42213. }
  42214. UniformTextSection (const UniformTextSection& other)
  42215. : font (other.font),
  42216. colour (other.colour)
  42217. {
  42218. atoms.ensureStorageAllocated (other.atoms.size());
  42219. for (int i = 0; i < other.atoms.size(); ++i)
  42220. atoms.add (new TextAtom (*other.atoms.getUnchecked(i)));
  42221. }
  42222. ~UniformTextSection()
  42223. {
  42224. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  42225. }
  42226. void clear()
  42227. {
  42228. for (int i = atoms.size(); --i >= 0;)
  42229. delete getAtom(i);
  42230. atoms.clear();
  42231. }
  42232. int getNumAtoms() const
  42233. {
  42234. return atoms.size();
  42235. }
  42236. TextAtom* getAtom (const int index) const throw()
  42237. {
  42238. return atoms.getUnchecked (index);
  42239. }
  42240. void append (const UniformTextSection& other, const juce_wchar passwordCharacter)
  42241. {
  42242. if (other.atoms.size() > 0)
  42243. {
  42244. TextAtom* const lastAtom = atoms.getLast();
  42245. int i = 0;
  42246. if (lastAtom != 0)
  42247. {
  42248. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  42249. {
  42250. TextAtom* const first = other.getAtom(0);
  42251. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  42252. {
  42253. lastAtom->atomText += first->atomText;
  42254. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  42255. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  42256. delete first;
  42257. ++i;
  42258. }
  42259. }
  42260. }
  42261. atoms.ensureStorageAllocated (atoms.size() + other.atoms.size() - i);
  42262. while (i < other.atoms.size())
  42263. {
  42264. atoms.add (other.getAtom(i));
  42265. ++i;
  42266. }
  42267. }
  42268. }
  42269. UniformTextSection* split (const int indexToBreakAt,
  42270. const juce_wchar passwordCharacter)
  42271. {
  42272. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  42273. font, colour,
  42274. passwordCharacter);
  42275. int index = 0;
  42276. for (int i = 0; i < atoms.size(); ++i)
  42277. {
  42278. TextAtom* const atom = getAtom(i);
  42279. const int nextIndex = index + atom->numChars;
  42280. if (index == indexToBreakAt)
  42281. {
  42282. int j;
  42283. for (j = i; j < atoms.size(); ++j)
  42284. section2->atoms.add (getAtom (j));
  42285. for (j = atoms.size(); --j >= i;)
  42286. atoms.remove (j);
  42287. break;
  42288. }
  42289. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  42290. {
  42291. TextAtom* const secondAtom = new TextAtom();
  42292. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  42293. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  42294. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  42295. section2->atoms.add (secondAtom);
  42296. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  42297. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  42298. atom->numChars = (uint16) (indexToBreakAt - index);
  42299. int j;
  42300. for (j = i + 1; j < atoms.size(); ++j)
  42301. section2->atoms.add (getAtom (j));
  42302. for (j = atoms.size(); --j > i;)
  42303. atoms.remove (j);
  42304. break;
  42305. }
  42306. index = nextIndex;
  42307. }
  42308. return section2;
  42309. }
  42310. void appendAllText (String::Concatenator& concatenator) const
  42311. {
  42312. for (int i = 0; i < atoms.size(); ++i)
  42313. concatenator.append (getAtom(i)->atomText);
  42314. }
  42315. void appendSubstring (String::Concatenator& concatenator,
  42316. const Range<int>& range) const
  42317. {
  42318. int index = 0;
  42319. for (int i = 0; i < atoms.size(); ++i)
  42320. {
  42321. const TextAtom* const atom = getAtom (i);
  42322. const int nextIndex = index + atom->numChars;
  42323. if (range.getStart() < nextIndex)
  42324. {
  42325. if (range.getEnd() <= index)
  42326. break;
  42327. const Range<int> r ((range - index).getIntersectionWith (Range<int> (0, (int) atom->numChars)));
  42328. if (! r.isEmpty())
  42329. concatenator.append (atom->atomText.substring (r.getStart(), r.getEnd()));
  42330. }
  42331. index = nextIndex;
  42332. }
  42333. }
  42334. int getTotalLength() const
  42335. {
  42336. int total = 0;
  42337. for (int i = atoms.size(); --i >= 0;)
  42338. total += getAtom(i)->numChars;
  42339. return total;
  42340. }
  42341. void setFont (const Font& newFont,
  42342. const juce_wchar passwordCharacter)
  42343. {
  42344. if (font != newFont)
  42345. {
  42346. font = newFont;
  42347. for (int i = atoms.size(); --i >= 0;)
  42348. {
  42349. TextAtom* const atom = atoms.getUnchecked(i);
  42350. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  42351. }
  42352. }
  42353. }
  42354. juce_UseDebuggingNewOperator
  42355. Font font;
  42356. Colour colour;
  42357. private:
  42358. Array <TextAtom*> atoms;
  42359. void initialiseAtoms (const String& textToParse,
  42360. const juce_wchar passwordCharacter)
  42361. {
  42362. int i = 0;
  42363. const int len = textToParse.length();
  42364. const juce_wchar* const text = textToParse;
  42365. while (i < len)
  42366. {
  42367. int start = i;
  42368. // create a whitespace atom unless it starts with non-ws
  42369. if (CharacterFunctions::isWhitespace (text[i])
  42370. && text[i] != '\r'
  42371. && text[i] != '\n')
  42372. {
  42373. while (i < len
  42374. && CharacterFunctions::isWhitespace (text[i])
  42375. && text[i] != '\r'
  42376. && text[i] != '\n')
  42377. {
  42378. ++i;
  42379. }
  42380. }
  42381. else
  42382. {
  42383. if (text[i] == '\r')
  42384. {
  42385. ++i;
  42386. if ((i < len) && (text[i] == '\n'))
  42387. {
  42388. ++start;
  42389. ++i;
  42390. }
  42391. }
  42392. else if (text[i] == '\n')
  42393. {
  42394. ++i;
  42395. }
  42396. else
  42397. {
  42398. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  42399. ++i;
  42400. }
  42401. }
  42402. TextAtom* const atom = new TextAtom();
  42403. atom->atomText = String (text + start, i - start);
  42404. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  42405. atom->numChars = (uint16) (i - start);
  42406. atoms.add (atom);
  42407. }
  42408. }
  42409. UniformTextSection& operator= (const UniformTextSection& other);
  42410. };
  42411. class TextEditor::Iterator
  42412. {
  42413. public:
  42414. Iterator (const Array <UniformTextSection*>& sections_,
  42415. const float wordWrapWidth_,
  42416. const juce_wchar passwordCharacter_)
  42417. : indexInText (0),
  42418. lineY (0),
  42419. lineHeight (0),
  42420. maxDescent (0),
  42421. atomX (0),
  42422. atomRight (0),
  42423. atom (0),
  42424. currentSection (0),
  42425. sections (sections_),
  42426. sectionIndex (0),
  42427. atomIndex (0),
  42428. wordWrapWidth (wordWrapWidth_),
  42429. passwordCharacter (passwordCharacter_)
  42430. {
  42431. jassert (wordWrapWidth_ > 0);
  42432. if (sections.size() > 0)
  42433. {
  42434. currentSection = sections.getUnchecked (sectionIndex);
  42435. if (currentSection != 0)
  42436. beginNewLine();
  42437. }
  42438. }
  42439. Iterator (const Iterator& other)
  42440. : indexInText (other.indexInText),
  42441. lineY (other.lineY),
  42442. lineHeight (other.lineHeight),
  42443. maxDescent (other.maxDescent),
  42444. atomX (other.atomX),
  42445. atomRight (other.atomRight),
  42446. atom (other.atom),
  42447. currentSection (other.currentSection),
  42448. sections (other.sections),
  42449. sectionIndex (other.sectionIndex),
  42450. atomIndex (other.atomIndex),
  42451. wordWrapWidth (other.wordWrapWidth),
  42452. passwordCharacter (other.passwordCharacter),
  42453. tempAtom (other.tempAtom)
  42454. {
  42455. }
  42456. ~Iterator()
  42457. {
  42458. }
  42459. bool next()
  42460. {
  42461. if (atom == &tempAtom)
  42462. {
  42463. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  42464. if (numRemaining > 0)
  42465. {
  42466. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  42467. atomX = 0;
  42468. if (tempAtom.numChars > 0)
  42469. lineY += lineHeight;
  42470. indexInText += tempAtom.numChars;
  42471. GlyphArrangement g;
  42472. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  42473. int split;
  42474. for (split = 0; split < g.getNumGlyphs(); ++split)
  42475. if (shouldWrap (g.getGlyph (split).getRight()))
  42476. break;
  42477. if (split > 0 && split <= numRemaining)
  42478. {
  42479. tempAtom.numChars = (uint16) split;
  42480. tempAtom.width = g.getGlyph (split - 1).getRight();
  42481. atomRight = atomX + tempAtom.width;
  42482. return true;
  42483. }
  42484. }
  42485. }
  42486. bool forceNewLine = false;
  42487. if (sectionIndex >= sections.size())
  42488. {
  42489. moveToEndOfLastAtom();
  42490. return false;
  42491. }
  42492. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  42493. {
  42494. if (atomIndex >= currentSection->getNumAtoms())
  42495. {
  42496. if (++sectionIndex >= sections.size())
  42497. {
  42498. moveToEndOfLastAtom();
  42499. return false;
  42500. }
  42501. atomIndex = 0;
  42502. currentSection = sections.getUnchecked (sectionIndex);
  42503. }
  42504. else
  42505. {
  42506. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  42507. if (! lastAtom->isWhitespace())
  42508. {
  42509. // handle the case where the last atom in a section is actually part of the same
  42510. // word as the first atom of the next section...
  42511. float right = atomRight + lastAtom->width;
  42512. float lineHeight2 = lineHeight;
  42513. float maxDescent2 = maxDescent;
  42514. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  42515. {
  42516. const UniformTextSection* const s = sections.getUnchecked (section);
  42517. if (s->getNumAtoms() == 0)
  42518. break;
  42519. const TextAtom* const nextAtom = s->getAtom (0);
  42520. if (nextAtom->isWhitespace())
  42521. break;
  42522. right += nextAtom->width;
  42523. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  42524. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  42525. if (shouldWrap (right))
  42526. {
  42527. lineHeight = lineHeight2;
  42528. maxDescent = maxDescent2;
  42529. forceNewLine = true;
  42530. break;
  42531. }
  42532. if (s->getNumAtoms() > 1)
  42533. break;
  42534. }
  42535. }
  42536. }
  42537. }
  42538. if (atom != 0)
  42539. {
  42540. atomX = atomRight;
  42541. indexInText += atom->numChars;
  42542. if (atom->isNewLine())
  42543. beginNewLine();
  42544. }
  42545. atom = currentSection->getAtom (atomIndex);
  42546. atomRight = atomX + atom->width;
  42547. ++atomIndex;
  42548. if (shouldWrap (atomRight) || forceNewLine)
  42549. {
  42550. if (atom->isWhitespace())
  42551. {
  42552. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  42553. atomRight = jmin (atomRight, wordWrapWidth);
  42554. }
  42555. else
  42556. {
  42557. atomRight = atom->width;
  42558. if (shouldWrap (atomRight)) // atom too big to fit on a line, so break it up..
  42559. {
  42560. tempAtom = *atom;
  42561. tempAtom.width = 0;
  42562. tempAtom.numChars = 0;
  42563. atom = &tempAtom;
  42564. if (atomX > 0)
  42565. beginNewLine();
  42566. return next();
  42567. }
  42568. beginNewLine();
  42569. return true;
  42570. }
  42571. }
  42572. return true;
  42573. }
  42574. void beginNewLine()
  42575. {
  42576. atomX = 0;
  42577. lineY += lineHeight;
  42578. int tempSectionIndex = sectionIndex;
  42579. int tempAtomIndex = atomIndex;
  42580. const UniformTextSection* section = sections.getUnchecked (tempSectionIndex);
  42581. lineHeight = section->font.getHeight();
  42582. maxDescent = section->font.getDescent();
  42583. float x = (atom != 0) ? atom->width : 0;
  42584. while (! shouldWrap (x))
  42585. {
  42586. if (tempSectionIndex >= sections.size())
  42587. break;
  42588. bool checkSize = false;
  42589. if (tempAtomIndex >= section->getNumAtoms())
  42590. {
  42591. if (++tempSectionIndex >= sections.size())
  42592. break;
  42593. tempAtomIndex = 0;
  42594. section = sections.getUnchecked (tempSectionIndex);
  42595. checkSize = true;
  42596. }
  42597. const TextAtom* const nextAtom = section->getAtom (tempAtomIndex);
  42598. if (nextAtom == 0)
  42599. break;
  42600. x += nextAtom->width;
  42601. if (shouldWrap (x) || nextAtom->isNewLine())
  42602. break;
  42603. if (checkSize)
  42604. {
  42605. lineHeight = jmax (lineHeight, section->font.getHeight());
  42606. maxDescent = jmax (maxDescent, section->font.getDescent());
  42607. }
  42608. ++tempAtomIndex;
  42609. }
  42610. }
  42611. void draw (Graphics& g, const UniformTextSection*& lastSection) const
  42612. {
  42613. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42614. {
  42615. if (lastSection != currentSection)
  42616. {
  42617. lastSection = currentSection;
  42618. g.setColour (currentSection->colour);
  42619. g.setFont (currentSection->font);
  42620. }
  42621. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  42622. GlyphArrangement ga;
  42623. ga.addLineOfText (currentSection->font,
  42624. atom->getTrimmedText (passwordCharacter),
  42625. atomX,
  42626. (float) roundToInt (lineY + lineHeight - maxDescent));
  42627. ga.draw (g);
  42628. }
  42629. }
  42630. void drawSelection (Graphics& g,
  42631. const Range<int>& selection) const
  42632. {
  42633. const int startX = roundToInt (indexToX (selection.getStart()));
  42634. const int endX = roundToInt (indexToX (selection.getEnd()));
  42635. const int y = roundToInt (lineY);
  42636. const int nextY = roundToInt (lineY + lineHeight);
  42637. g.fillRect (startX, y, endX - startX, nextY - y);
  42638. }
  42639. void drawSelectedText (Graphics& g,
  42640. const Range<int>& selection,
  42641. const Colour& selectedTextColour) const
  42642. {
  42643. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42644. {
  42645. GlyphArrangement ga;
  42646. ga.addLineOfText (currentSection->font,
  42647. atom->getTrimmedText (passwordCharacter),
  42648. atomX,
  42649. (float) roundToInt (lineY + lineHeight - maxDescent));
  42650. if (selection.getEnd() < indexInText + atom->numChars)
  42651. {
  42652. GlyphArrangement ga2 (ga);
  42653. ga2.removeRangeOfGlyphs (0, selection.getEnd() - indexInText);
  42654. ga.removeRangeOfGlyphs (selection.getEnd() - indexInText, -1);
  42655. g.setColour (currentSection->colour);
  42656. ga2.draw (g);
  42657. }
  42658. if (selection.getStart() > indexInText)
  42659. {
  42660. GlyphArrangement ga2 (ga);
  42661. ga2.removeRangeOfGlyphs (selection.getStart() - indexInText, -1);
  42662. ga.removeRangeOfGlyphs (0, selection.getStart() - indexInText);
  42663. g.setColour (currentSection->colour);
  42664. ga2.draw (g);
  42665. }
  42666. g.setColour (selectedTextColour);
  42667. ga.draw (g);
  42668. }
  42669. }
  42670. float indexToX (const int indexToFind) const
  42671. {
  42672. if (indexToFind <= indexInText)
  42673. return atomX;
  42674. if (indexToFind >= indexInText + atom->numChars)
  42675. return atomRight;
  42676. GlyphArrangement g;
  42677. g.addLineOfText (currentSection->font,
  42678. atom->getText (passwordCharacter),
  42679. atomX, 0.0f);
  42680. if (indexToFind - indexInText >= g.getNumGlyphs())
  42681. return atomRight;
  42682. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  42683. }
  42684. int xToIndex (const float xToFind) const
  42685. {
  42686. if (xToFind <= atomX || atom->isNewLine())
  42687. return indexInText;
  42688. if (xToFind >= atomRight)
  42689. return indexInText + atom->numChars;
  42690. GlyphArrangement g;
  42691. g.addLineOfText (currentSection->font,
  42692. atom->getText (passwordCharacter),
  42693. atomX, 0.0f);
  42694. int j;
  42695. for (j = 0; j < g.getNumGlyphs(); ++j)
  42696. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  42697. break;
  42698. return indexInText + j;
  42699. }
  42700. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_)
  42701. {
  42702. while (next())
  42703. {
  42704. if (indexInText + atom->numChars > index)
  42705. {
  42706. cx = indexToX (index);
  42707. cy = lineY;
  42708. lineHeight_ = lineHeight;
  42709. return true;
  42710. }
  42711. }
  42712. cx = atomX;
  42713. cy = lineY;
  42714. lineHeight_ = lineHeight;
  42715. return false;
  42716. }
  42717. juce_UseDebuggingNewOperator
  42718. int indexInText;
  42719. float lineY, lineHeight, maxDescent;
  42720. float atomX, atomRight;
  42721. const TextAtom* atom;
  42722. const UniformTextSection* currentSection;
  42723. private:
  42724. const Array <UniformTextSection*>& sections;
  42725. int sectionIndex, atomIndex;
  42726. const float wordWrapWidth;
  42727. const juce_wchar passwordCharacter;
  42728. TextAtom tempAtom;
  42729. Iterator& operator= (const Iterator&);
  42730. void moveToEndOfLastAtom()
  42731. {
  42732. if (atom != 0)
  42733. {
  42734. atomX = atomRight;
  42735. if (atom->isNewLine())
  42736. {
  42737. atomX = 0.0f;
  42738. lineY += lineHeight;
  42739. }
  42740. }
  42741. }
  42742. bool shouldWrap (const float x) const
  42743. {
  42744. return (x - 0.0001f) >= wordWrapWidth;
  42745. }
  42746. };
  42747. class TextEditor::InsertAction : public UndoableAction
  42748. {
  42749. TextEditor& owner;
  42750. const String text;
  42751. const int insertIndex, oldCaretPos, newCaretPos;
  42752. const Font font;
  42753. const Colour colour;
  42754. InsertAction (const InsertAction&);
  42755. InsertAction& operator= (const InsertAction&);
  42756. public:
  42757. InsertAction (TextEditor& owner_,
  42758. const String& text_,
  42759. const int insertIndex_,
  42760. const Font& font_,
  42761. const Colour& colour_,
  42762. const int oldCaretPos_,
  42763. const int newCaretPos_)
  42764. : owner (owner_),
  42765. text (text_),
  42766. insertIndex (insertIndex_),
  42767. oldCaretPos (oldCaretPos_),
  42768. newCaretPos (newCaretPos_),
  42769. font (font_),
  42770. colour (colour_)
  42771. {
  42772. }
  42773. ~InsertAction()
  42774. {
  42775. }
  42776. bool perform()
  42777. {
  42778. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  42779. return true;
  42780. }
  42781. bool undo()
  42782. {
  42783. owner.remove (Range<int> (insertIndex, insertIndex + text.length()), 0, oldCaretPos);
  42784. return true;
  42785. }
  42786. int getSizeInUnits()
  42787. {
  42788. return text.length() + 16;
  42789. }
  42790. };
  42791. class TextEditor::RemoveAction : public UndoableAction
  42792. {
  42793. TextEditor& owner;
  42794. const Range<int> range;
  42795. const int oldCaretPos, newCaretPos;
  42796. Array <UniformTextSection*> removedSections;
  42797. RemoveAction (const RemoveAction&);
  42798. RemoveAction& operator= (const RemoveAction&);
  42799. public:
  42800. RemoveAction (TextEditor& owner_,
  42801. const Range<int> range_,
  42802. const int oldCaretPos_,
  42803. const int newCaretPos_,
  42804. const Array <UniformTextSection*>& removedSections_)
  42805. : owner (owner_),
  42806. range (range_),
  42807. oldCaretPos (oldCaretPos_),
  42808. newCaretPos (newCaretPos_),
  42809. removedSections (removedSections_)
  42810. {
  42811. }
  42812. ~RemoveAction()
  42813. {
  42814. for (int i = removedSections.size(); --i >= 0;)
  42815. {
  42816. UniformTextSection* const section = removedSections.getUnchecked (i);
  42817. section->clear();
  42818. delete section;
  42819. }
  42820. }
  42821. bool perform()
  42822. {
  42823. owner.remove (range, 0, newCaretPos);
  42824. return true;
  42825. }
  42826. bool undo()
  42827. {
  42828. owner.reinsert (range.getStart(), removedSections);
  42829. owner.moveCursorTo (oldCaretPos, false);
  42830. return true;
  42831. }
  42832. int getSizeInUnits()
  42833. {
  42834. int n = 0;
  42835. for (int i = removedSections.size(); --i >= 0;)
  42836. n += removedSections.getUnchecked (i)->getTotalLength();
  42837. return n + 16;
  42838. }
  42839. };
  42840. class TextEditor::TextHolderComponent : public Component,
  42841. public Timer,
  42842. public Value::Listener
  42843. {
  42844. public:
  42845. TextHolderComponent (TextEditor& owner_)
  42846. : owner (owner_)
  42847. {
  42848. setWantsKeyboardFocus (false);
  42849. setInterceptsMouseClicks (false, true);
  42850. owner.getTextValue().addListener (this);
  42851. }
  42852. ~TextHolderComponent()
  42853. {
  42854. owner.getTextValue().removeListener (this);
  42855. }
  42856. void paint (Graphics& g)
  42857. {
  42858. owner.drawContent (g);
  42859. }
  42860. void timerCallback()
  42861. {
  42862. owner.timerCallbackInt();
  42863. }
  42864. const MouseCursor getMouseCursor()
  42865. {
  42866. return owner.getMouseCursor();
  42867. }
  42868. void valueChanged (Value&)
  42869. {
  42870. owner.textWasChangedByValue();
  42871. }
  42872. private:
  42873. TextEditor& owner;
  42874. TextHolderComponent (const TextHolderComponent&);
  42875. TextHolderComponent& operator= (const TextHolderComponent&);
  42876. };
  42877. class TextEditorViewport : public Viewport
  42878. {
  42879. public:
  42880. TextEditorViewport (TextEditor* const owner_)
  42881. : owner (owner_), lastWordWrapWidth (0), rentrant (false)
  42882. {
  42883. }
  42884. ~TextEditorViewport()
  42885. {
  42886. }
  42887. void visibleAreaChanged (int, int, int, int)
  42888. {
  42889. if (! rentrant) // it's rare, but possible to get into a feedback loop as the viewport's scrollbars
  42890. // appear and disappear, causing the wrap width to change.
  42891. {
  42892. const float wordWrapWidth = owner->getWordWrapWidth();
  42893. if (wordWrapWidth != lastWordWrapWidth)
  42894. {
  42895. lastWordWrapWidth = wordWrapWidth;
  42896. rentrant = true;
  42897. owner->updateTextHolderSize();
  42898. rentrant = false;
  42899. }
  42900. }
  42901. }
  42902. private:
  42903. TextEditor* const owner;
  42904. float lastWordWrapWidth;
  42905. bool rentrant;
  42906. TextEditorViewport (const TextEditorViewport&);
  42907. TextEditorViewport& operator= (const TextEditorViewport&);
  42908. };
  42909. namespace TextEditorDefs
  42910. {
  42911. const int flashSpeedIntervalMs = 380;
  42912. const int textChangeMessageId = 0x10003001;
  42913. const int returnKeyMessageId = 0x10003002;
  42914. const int escapeKeyMessageId = 0x10003003;
  42915. const int focusLossMessageId = 0x10003004;
  42916. const int maxActionsPerTransaction = 100;
  42917. static int getCharacterCategory (const juce_wchar character)
  42918. {
  42919. return CharacterFunctions::isLetterOrDigit (character)
  42920. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  42921. }
  42922. }
  42923. TextEditor::TextEditor (const String& name,
  42924. const juce_wchar passwordCharacter_)
  42925. : Component (name),
  42926. borderSize (1, 1, 1, 3),
  42927. readOnly (false),
  42928. multiline (false),
  42929. wordWrap (false),
  42930. returnKeyStartsNewLine (false),
  42931. caretVisible (true),
  42932. popupMenuEnabled (true),
  42933. selectAllTextWhenFocused (false),
  42934. scrollbarVisible (true),
  42935. wasFocused (false),
  42936. caretFlashState (true),
  42937. keepCursorOnScreen (true),
  42938. tabKeyUsed (false),
  42939. menuActive (false),
  42940. valueTextNeedsUpdating (false),
  42941. cursorX (0),
  42942. cursorY (0),
  42943. cursorHeight (0),
  42944. maxTextLength (0),
  42945. leftIndent (4),
  42946. topIndent (4),
  42947. lastTransactionTime (0),
  42948. currentFont (14.0f),
  42949. totalNumChars (0),
  42950. caretPosition (0),
  42951. passwordCharacter (passwordCharacter_),
  42952. dragType (notDragging)
  42953. {
  42954. setOpaque (true);
  42955. addAndMakeVisible (viewport = new TextEditorViewport (this));
  42956. viewport->setViewedComponent (textHolder = new TextHolderComponent (*this));
  42957. viewport->setWantsKeyboardFocus (false);
  42958. viewport->setScrollBarsShown (false, false);
  42959. setMouseCursor (MouseCursor::IBeamCursor);
  42960. setWantsKeyboardFocus (true);
  42961. }
  42962. TextEditor::~TextEditor()
  42963. {
  42964. textValue.referTo (Value());
  42965. clearInternal (0);
  42966. viewport = 0;
  42967. textHolder = 0;
  42968. }
  42969. void TextEditor::newTransaction()
  42970. {
  42971. lastTransactionTime = Time::getApproximateMillisecondCounter();
  42972. undoManager.beginNewTransaction();
  42973. }
  42974. void TextEditor::doUndoRedo (const bool isRedo)
  42975. {
  42976. if (! isReadOnly())
  42977. {
  42978. if (isRedo ? undoManager.redo()
  42979. : undoManager.undo())
  42980. {
  42981. scrollToMakeSureCursorIsVisible();
  42982. repaint();
  42983. textChanged();
  42984. }
  42985. }
  42986. }
  42987. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  42988. const bool shouldWordWrap)
  42989. {
  42990. if (multiline != shouldBeMultiLine
  42991. || wordWrap != (shouldWordWrap && shouldBeMultiLine))
  42992. {
  42993. multiline = shouldBeMultiLine;
  42994. wordWrap = shouldWordWrap && shouldBeMultiLine;
  42995. viewport->setScrollBarsShown (scrollbarVisible && multiline,
  42996. scrollbarVisible && multiline);
  42997. viewport->setViewPosition (0, 0);
  42998. resized();
  42999. scrollToMakeSureCursorIsVisible();
  43000. }
  43001. }
  43002. bool TextEditor::isMultiLine() const
  43003. {
  43004. return multiline;
  43005. }
  43006. void TextEditor::setScrollbarsShown (bool shown)
  43007. {
  43008. if (scrollbarVisible != shown)
  43009. {
  43010. scrollbarVisible = shown;
  43011. shown = shown && isMultiLine();
  43012. viewport->setScrollBarsShown (shown, shown);
  43013. }
  43014. }
  43015. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  43016. {
  43017. if (readOnly != shouldBeReadOnly)
  43018. {
  43019. readOnly = shouldBeReadOnly;
  43020. enablementChanged();
  43021. }
  43022. }
  43023. bool TextEditor::isReadOnly() const
  43024. {
  43025. return readOnly || ! isEnabled();
  43026. }
  43027. bool TextEditor::isTextInputActive() const
  43028. {
  43029. return ! isReadOnly();
  43030. }
  43031. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  43032. {
  43033. returnKeyStartsNewLine = shouldStartNewLine;
  43034. }
  43035. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed)
  43036. {
  43037. tabKeyUsed = shouldTabKeyBeUsed;
  43038. }
  43039. void TextEditor::setPopupMenuEnabled (const bool b)
  43040. {
  43041. popupMenuEnabled = b;
  43042. }
  43043. void TextEditor::setSelectAllWhenFocused (const bool b)
  43044. {
  43045. selectAllTextWhenFocused = b;
  43046. }
  43047. const Font TextEditor::getFont() const
  43048. {
  43049. return currentFont;
  43050. }
  43051. void TextEditor::setFont (const Font& newFont)
  43052. {
  43053. currentFont = newFont;
  43054. scrollToMakeSureCursorIsVisible();
  43055. }
  43056. void TextEditor::applyFontToAllText (const Font& newFont)
  43057. {
  43058. currentFont = newFont;
  43059. const Colour overallColour (findColour (textColourId));
  43060. for (int i = sections.size(); --i >= 0;)
  43061. {
  43062. UniformTextSection* const uts = sections.getUnchecked (i);
  43063. uts->setFont (newFont, passwordCharacter);
  43064. uts->colour = overallColour;
  43065. }
  43066. coalesceSimilarSections();
  43067. updateTextHolderSize();
  43068. scrollToMakeSureCursorIsVisible();
  43069. repaint();
  43070. }
  43071. void TextEditor::colourChanged()
  43072. {
  43073. setOpaque (findColour (backgroundColourId).isOpaque());
  43074. repaint();
  43075. }
  43076. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible)
  43077. {
  43078. caretVisible = shouldCaretBeVisible;
  43079. if (shouldCaretBeVisible)
  43080. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43081. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  43082. : MouseCursor::NormalCursor);
  43083. }
  43084. void TextEditor::setInputRestrictions (const int maxLen,
  43085. const String& chars)
  43086. {
  43087. maxTextLength = jmax (0, maxLen);
  43088. allowedCharacters = chars;
  43089. }
  43090. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse)
  43091. {
  43092. textToShowWhenEmpty = text;
  43093. colourForTextWhenEmpty = colourToUse;
  43094. }
  43095. void TextEditor::setPasswordCharacter (const juce_wchar newPasswordCharacter)
  43096. {
  43097. if (passwordCharacter != newPasswordCharacter)
  43098. {
  43099. passwordCharacter = newPasswordCharacter;
  43100. resized();
  43101. repaint();
  43102. }
  43103. }
  43104. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  43105. {
  43106. viewport->setScrollBarThickness (newThicknessPixels);
  43107. }
  43108. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  43109. {
  43110. viewport->setScrollBarButtonVisibility (buttonsVisible);
  43111. }
  43112. void TextEditor::clear()
  43113. {
  43114. clearInternal (0);
  43115. updateTextHolderSize();
  43116. undoManager.clearUndoHistory();
  43117. }
  43118. void TextEditor::setText (const String& newText,
  43119. const bool sendTextChangeMessage)
  43120. {
  43121. const int newLength = newText.length();
  43122. if (newLength != getTotalNumChars() || getText() != newText)
  43123. {
  43124. const int oldCursorPos = caretPosition;
  43125. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  43126. clearInternal (0);
  43127. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  43128. // if you're adding text with line-feeds to a single-line text editor, it
  43129. // ain't gonna look right!
  43130. jassert (multiline || ! newText.containsAnyOf ("\r\n"));
  43131. if (cursorWasAtEnd && ! isMultiLine())
  43132. moveCursorTo (getTotalNumChars(), false);
  43133. else
  43134. moveCursorTo (oldCursorPos, false);
  43135. if (sendTextChangeMessage)
  43136. textChanged();
  43137. updateTextHolderSize();
  43138. scrollToMakeSureCursorIsVisible();
  43139. undoManager.clearUndoHistory();
  43140. repaint();
  43141. }
  43142. }
  43143. Value& TextEditor::getTextValue()
  43144. {
  43145. if (valueTextNeedsUpdating)
  43146. {
  43147. valueTextNeedsUpdating = false;
  43148. textValue = getText();
  43149. }
  43150. return textValue;
  43151. }
  43152. void TextEditor::textWasChangedByValue()
  43153. {
  43154. if (textValue.getValueSource().getReferenceCount() > 1)
  43155. setText (textValue.getValue());
  43156. }
  43157. void TextEditor::textChanged()
  43158. {
  43159. updateTextHolderSize();
  43160. postCommandMessage (TextEditorDefs::textChangeMessageId);
  43161. if (textValue.getValueSource().getReferenceCount() > 1)
  43162. {
  43163. valueTextNeedsUpdating = false;
  43164. textValue = getText();
  43165. }
  43166. }
  43167. void TextEditor::returnPressed()
  43168. {
  43169. postCommandMessage (TextEditorDefs::returnKeyMessageId);
  43170. }
  43171. void TextEditor::escapePressed()
  43172. {
  43173. postCommandMessage (TextEditorDefs::escapeKeyMessageId);
  43174. }
  43175. void TextEditor::addListener (Listener* const newListener)
  43176. {
  43177. listeners.add (newListener);
  43178. }
  43179. void TextEditor::removeListener (Listener* const listenerToRemove)
  43180. {
  43181. listeners.remove (listenerToRemove);
  43182. }
  43183. void TextEditor::timerCallbackInt()
  43184. {
  43185. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  43186. if (caretFlashState != newState)
  43187. {
  43188. caretFlashState = newState;
  43189. if (caretFlashState)
  43190. wasFocused = true;
  43191. if (caretVisible
  43192. && hasKeyboardFocus (false)
  43193. && ! isReadOnly())
  43194. {
  43195. repaintCaret();
  43196. }
  43197. }
  43198. const unsigned int now = Time::getApproximateMillisecondCounter();
  43199. if (now > lastTransactionTime + 200)
  43200. newTransaction();
  43201. }
  43202. void TextEditor::repaintCaret()
  43203. {
  43204. if (! findColour (caretColourId).isTransparent())
  43205. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundToInt (cursorX) - 1,
  43206. borderSize.getTop() + textHolder->getY() + topIndent + roundToInt (cursorY) - 1,
  43207. 4,
  43208. roundToInt (cursorHeight) + 2);
  43209. }
  43210. void TextEditor::repaintText (const Range<int>& range)
  43211. {
  43212. if (! range.isEmpty())
  43213. {
  43214. float x = 0, y = 0, lh = currentFont.getHeight();
  43215. const float wordWrapWidth = getWordWrapWidth();
  43216. if (wordWrapWidth > 0)
  43217. {
  43218. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43219. i.getCharPosition (range.getStart(), x, y, lh);
  43220. const int y1 = (int) y;
  43221. int y2;
  43222. if (range.getEnd() >= getTotalNumChars())
  43223. {
  43224. y2 = textHolder->getHeight();
  43225. }
  43226. else
  43227. {
  43228. i.getCharPosition (range.getEnd(), x, y, lh);
  43229. y2 = (int) (y + lh * 2.0f);
  43230. }
  43231. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  43232. }
  43233. }
  43234. }
  43235. void TextEditor::moveCaret (int newCaretPos)
  43236. {
  43237. if (newCaretPos < 0)
  43238. newCaretPos = 0;
  43239. else if (newCaretPos > getTotalNumChars())
  43240. newCaretPos = getTotalNumChars();
  43241. if (newCaretPos != getCaretPosition())
  43242. {
  43243. repaintCaret();
  43244. caretFlashState = true;
  43245. caretPosition = newCaretPos;
  43246. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43247. scrollToMakeSureCursorIsVisible();
  43248. repaintCaret();
  43249. }
  43250. }
  43251. void TextEditor::setCaretPosition (const int newIndex)
  43252. {
  43253. moveCursorTo (newIndex, false);
  43254. }
  43255. int TextEditor::getCaretPosition() const
  43256. {
  43257. return caretPosition;
  43258. }
  43259. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  43260. const int desiredCaretY)
  43261. {
  43262. updateCaretPosition();
  43263. int vx = roundToInt (cursorX) - desiredCaretX;
  43264. int vy = roundToInt (cursorY) - desiredCaretY;
  43265. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  43266. {
  43267. vx += desiredCaretX - proportionOfWidth (0.2f);
  43268. }
  43269. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  43270. {
  43271. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  43272. }
  43273. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  43274. if (! isMultiLine())
  43275. {
  43276. vy = viewport->getViewPositionY();
  43277. }
  43278. else
  43279. {
  43280. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  43281. const int curH = roundToInt (cursorHeight);
  43282. if (desiredCaretY < 0)
  43283. {
  43284. vy = jmax (0, desiredCaretY + vy);
  43285. }
  43286. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  43287. {
  43288. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  43289. }
  43290. }
  43291. viewport->setViewPosition (vx, vy);
  43292. }
  43293. const Rectangle<int> TextEditor::getCaretRectangle()
  43294. {
  43295. updateCaretPosition();
  43296. return Rectangle<int> (roundToInt (cursorX) - viewport->getX(),
  43297. roundToInt (cursorY) - viewport->getY(),
  43298. 1, roundToInt (cursorHeight));
  43299. }
  43300. float TextEditor::getWordWrapWidth() const
  43301. {
  43302. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  43303. : 1.0e10f;
  43304. }
  43305. void TextEditor::updateTextHolderSize()
  43306. {
  43307. const float wordWrapWidth = getWordWrapWidth();
  43308. if (wordWrapWidth > 0)
  43309. {
  43310. float maxWidth = 0.0f;
  43311. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43312. while (i.next())
  43313. maxWidth = jmax (maxWidth, i.atomRight);
  43314. const int w = leftIndent + roundToInt (maxWidth);
  43315. const int h = topIndent + roundToInt (jmax (i.lineY + i.lineHeight,
  43316. currentFont.getHeight()));
  43317. textHolder->setSize (w + 1, h + 1);
  43318. }
  43319. }
  43320. int TextEditor::getTextWidth() const
  43321. {
  43322. return textHolder->getWidth();
  43323. }
  43324. int TextEditor::getTextHeight() const
  43325. {
  43326. return textHolder->getHeight();
  43327. }
  43328. void TextEditor::setIndents (const int newLeftIndent,
  43329. const int newTopIndent)
  43330. {
  43331. leftIndent = newLeftIndent;
  43332. topIndent = newTopIndent;
  43333. }
  43334. void TextEditor::setBorder (const BorderSize& border)
  43335. {
  43336. borderSize = border;
  43337. resized();
  43338. }
  43339. const BorderSize TextEditor::getBorder() const
  43340. {
  43341. return borderSize;
  43342. }
  43343. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor)
  43344. {
  43345. keepCursorOnScreen = shouldScrollToShowCursor;
  43346. }
  43347. void TextEditor::updateCaretPosition()
  43348. {
  43349. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  43350. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  43351. }
  43352. void TextEditor::scrollToMakeSureCursorIsVisible()
  43353. {
  43354. updateCaretPosition();
  43355. if (keepCursorOnScreen)
  43356. {
  43357. int x = viewport->getViewPositionX();
  43358. int y = viewport->getViewPositionY();
  43359. const int relativeCursorX = roundToInt (cursorX) - x;
  43360. const int relativeCursorY = roundToInt (cursorY) - y;
  43361. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  43362. {
  43363. x += relativeCursorX - proportionOfWidth (0.2f);
  43364. }
  43365. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  43366. {
  43367. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  43368. }
  43369. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  43370. if (! isMultiLine())
  43371. {
  43372. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  43373. }
  43374. else
  43375. {
  43376. const int curH = roundToInt (cursorHeight);
  43377. if (relativeCursorY < 0)
  43378. {
  43379. y = jmax (0, relativeCursorY + y);
  43380. }
  43381. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  43382. {
  43383. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  43384. }
  43385. }
  43386. viewport->setViewPosition (x, y);
  43387. }
  43388. }
  43389. void TextEditor::moveCursorTo (const int newPosition,
  43390. const bool isSelecting)
  43391. {
  43392. if (isSelecting)
  43393. {
  43394. moveCaret (newPosition);
  43395. const Range<int> oldSelection (selection);
  43396. if (dragType == notDragging)
  43397. {
  43398. if (abs (getCaretPosition() - selection.getStart()) < abs (getCaretPosition() - selection.getEnd()))
  43399. dragType = draggingSelectionStart;
  43400. else
  43401. dragType = draggingSelectionEnd;
  43402. }
  43403. if (dragType == draggingSelectionStart)
  43404. {
  43405. if (getCaretPosition() >= selection.getEnd())
  43406. dragType = draggingSelectionEnd;
  43407. selection = Range<int>::between (getCaretPosition(), selection.getEnd());
  43408. }
  43409. else
  43410. {
  43411. if (getCaretPosition() < selection.getStart())
  43412. dragType = draggingSelectionStart;
  43413. selection = Range<int>::between (getCaretPosition(), selection.getStart());
  43414. }
  43415. repaintText (selection.getUnionWith (oldSelection));
  43416. }
  43417. else
  43418. {
  43419. dragType = notDragging;
  43420. repaintText (selection);
  43421. moveCaret (newPosition);
  43422. selection = Range<int>::emptyRange (getCaretPosition());
  43423. }
  43424. }
  43425. int TextEditor::getTextIndexAt (const int x,
  43426. const int y)
  43427. {
  43428. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  43429. (float) (y + viewport->getViewPositionY() - topIndent));
  43430. }
  43431. void TextEditor::insertTextAtCaret (const String& newText_)
  43432. {
  43433. String newText (newText_);
  43434. if (allowedCharacters.isNotEmpty())
  43435. newText = newText.retainCharacters (allowedCharacters);
  43436. if ((! returnKeyStartsNewLine) && newText == "\n")
  43437. {
  43438. returnPressed();
  43439. return;
  43440. }
  43441. if (! isMultiLine())
  43442. newText = newText.replaceCharacters ("\r\n", " ");
  43443. else
  43444. newText = newText.replace ("\r\n", "\n");
  43445. const int newCaretPos = selection.getStart() + newText.length();
  43446. const int insertIndex = selection.getStart();
  43447. remove (selection, getUndoManager(),
  43448. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  43449. if (maxTextLength > 0)
  43450. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  43451. if (newText.isNotEmpty())
  43452. insert (newText,
  43453. insertIndex,
  43454. currentFont,
  43455. findColour (textColourId),
  43456. getUndoManager(),
  43457. newCaretPos);
  43458. textChanged();
  43459. }
  43460. void TextEditor::setHighlightedRegion (const Range<int>& newSelection)
  43461. {
  43462. moveCursorTo (newSelection.getStart(), false);
  43463. moveCursorTo (newSelection.getEnd(), true);
  43464. }
  43465. void TextEditor::copy()
  43466. {
  43467. if (passwordCharacter == 0)
  43468. {
  43469. const String selectedText (getHighlightedText());
  43470. if (selectedText.isNotEmpty())
  43471. SystemClipboard::copyTextToClipboard (selectedText);
  43472. }
  43473. }
  43474. void TextEditor::paste()
  43475. {
  43476. if (! isReadOnly())
  43477. {
  43478. const String clip (SystemClipboard::getTextFromClipboard());
  43479. if (clip.isNotEmpty())
  43480. insertTextAtCaret (clip);
  43481. }
  43482. }
  43483. void TextEditor::cut()
  43484. {
  43485. if (! isReadOnly())
  43486. {
  43487. moveCaret (selection.getEnd());
  43488. insertTextAtCaret (String::empty);
  43489. }
  43490. }
  43491. void TextEditor::drawContent (Graphics& g)
  43492. {
  43493. const float wordWrapWidth = getWordWrapWidth();
  43494. if (wordWrapWidth > 0)
  43495. {
  43496. g.setOrigin (leftIndent, topIndent);
  43497. const Rectangle<int> clip (g.getClipBounds());
  43498. Colour selectedTextColour;
  43499. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43500. while (i.lineY + 200.0 < clip.getY() && i.next())
  43501. {}
  43502. if (! selection.isEmpty())
  43503. {
  43504. g.setColour (findColour (highlightColourId)
  43505. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  43506. selectedTextColour = findColour (highlightedTextColourId);
  43507. Iterator i2 (i);
  43508. while (i2.next() && i2.lineY < clip.getBottom())
  43509. {
  43510. if (i2.lineY + i2.lineHeight >= clip.getY()
  43511. && selection.intersects (Range<int> (i2.indexInText, i2.indexInText + i2.atom->numChars)))
  43512. {
  43513. i2.drawSelection (g, selection);
  43514. }
  43515. }
  43516. }
  43517. const UniformTextSection* lastSection = 0;
  43518. while (i.next() && i.lineY < clip.getBottom())
  43519. {
  43520. if (i.lineY + i.lineHeight >= clip.getY())
  43521. {
  43522. if (selection.intersects (Range<int> (i.indexInText, i.indexInText + i.atom->numChars)))
  43523. {
  43524. i.drawSelectedText (g, selection, selectedTextColour);
  43525. lastSection = 0;
  43526. }
  43527. else
  43528. {
  43529. i.draw (g, lastSection);
  43530. }
  43531. }
  43532. }
  43533. }
  43534. }
  43535. void TextEditor::paint (Graphics& g)
  43536. {
  43537. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  43538. }
  43539. void TextEditor::paintOverChildren (Graphics& g)
  43540. {
  43541. if (caretFlashState
  43542. && hasKeyboardFocus (false)
  43543. && caretVisible
  43544. && ! isReadOnly())
  43545. {
  43546. g.setColour (findColour (caretColourId));
  43547. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  43548. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  43549. 2.0f, cursorHeight);
  43550. }
  43551. if (textToShowWhenEmpty.isNotEmpty()
  43552. && (! hasKeyboardFocus (false))
  43553. && getTotalNumChars() == 0)
  43554. {
  43555. g.setColour (colourForTextWhenEmpty);
  43556. g.setFont (getFont());
  43557. if (isMultiLine())
  43558. {
  43559. g.drawText (textToShowWhenEmpty,
  43560. 0, 0, getWidth(), getHeight(),
  43561. Justification::centred, true);
  43562. }
  43563. else
  43564. {
  43565. g.drawText (textToShowWhenEmpty,
  43566. leftIndent, topIndent,
  43567. viewport->getWidth() - leftIndent,
  43568. viewport->getHeight() - topIndent,
  43569. Justification::centredLeft, true);
  43570. }
  43571. }
  43572. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  43573. }
  43574. class TextEditorMenuPerformer : public ModalComponentManager::Callback
  43575. {
  43576. public:
  43577. TextEditorMenuPerformer (TextEditor* const editor_)
  43578. : editor (editor_)
  43579. {
  43580. }
  43581. void modalStateFinished (int returnValue)
  43582. {
  43583. if (editor != 0 && returnValue != 0)
  43584. editor->performPopupMenuAction (returnValue);
  43585. }
  43586. private:
  43587. Component::SafePointer<TextEditor> editor;
  43588. TextEditorMenuPerformer (const TextEditorMenuPerformer&);
  43589. TextEditorMenuPerformer& operator= (const TextEditorMenuPerformer&);
  43590. };
  43591. void TextEditor::mouseDown (const MouseEvent& e)
  43592. {
  43593. beginDragAutoRepeat (100);
  43594. newTransaction();
  43595. if (wasFocused || ! selectAllTextWhenFocused)
  43596. {
  43597. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43598. {
  43599. moveCursorTo (getTextIndexAt (e.x, e.y),
  43600. e.mods.isShiftDown());
  43601. }
  43602. else
  43603. {
  43604. PopupMenu m;
  43605. m.setLookAndFeel (&getLookAndFeel());
  43606. addPopupMenuItems (m, &e);
  43607. m.show (0, 0, 0, 0, new TextEditorMenuPerformer (this));
  43608. }
  43609. }
  43610. }
  43611. void TextEditor::mouseDrag (const MouseEvent& e)
  43612. {
  43613. if (wasFocused || ! selectAllTextWhenFocused)
  43614. {
  43615. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43616. {
  43617. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  43618. }
  43619. }
  43620. }
  43621. void TextEditor::mouseUp (const MouseEvent& e)
  43622. {
  43623. newTransaction();
  43624. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43625. if (wasFocused || ! selectAllTextWhenFocused)
  43626. {
  43627. if (e.mouseWasClicked() && ! (popupMenuEnabled && e.mods.isPopupMenu()))
  43628. {
  43629. moveCaret (getTextIndexAt (e.x, e.y));
  43630. }
  43631. }
  43632. wasFocused = true;
  43633. }
  43634. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  43635. {
  43636. int tokenEnd = getTextIndexAt (e.x, e.y);
  43637. int tokenStart = tokenEnd;
  43638. if (e.getNumberOfClicks() > 3)
  43639. {
  43640. tokenStart = 0;
  43641. tokenEnd = getTotalNumChars();
  43642. }
  43643. else
  43644. {
  43645. const String t (getText());
  43646. const int totalLength = getTotalNumChars();
  43647. while (tokenEnd < totalLength)
  43648. {
  43649. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43650. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]) || t [tokenEnd] > 128)
  43651. ++tokenEnd;
  43652. else
  43653. break;
  43654. }
  43655. tokenStart = tokenEnd;
  43656. while (tokenStart > 0)
  43657. {
  43658. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43659. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]) || t [tokenStart - 1] > 128)
  43660. --tokenStart;
  43661. else
  43662. break;
  43663. }
  43664. if (e.getNumberOfClicks() > 2)
  43665. {
  43666. while (tokenEnd < totalLength)
  43667. {
  43668. if (t [tokenEnd] != '\r' && t [tokenEnd] != '\n')
  43669. ++tokenEnd;
  43670. else
  43671. break;
  43672. }
  43673. while (tokenStart > 0)
  43674. {
  43675. if (t [tokenStart - 1] != '\r' && t [tokenStart - 1] != '\n')
  43676. --tokenStart;
  43677. else
  43678. break;
  43679. }
  43680. }
  43681. }
  43682. moveCursorTo (tokenEnd, false);
  43683. moveCursorTo (tokenStart, true);
  43684. }
  43685. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  43686. {
  43687. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  43688. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  43689. }
  43690. bool TextEditor::keyPressed (const KeyPress& key)
  43691. {
  43692. if (isReadOnly() && key != KeyPress ('c', ModifierKeys::commandModifier, 0))
  43693. return false;
  43694. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  43695. if (key.isKeyCode (KeyPress::leftKey)
  43696. || key.isKeyCode (KeyPress::upKey))
  43697. {
  43698. newTransaction();
  43699. int newPos;
  43700. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  43701. newPos = indexAtPosition (cursorX, cursorY - 1);
  43702. else if (moveInWholeWordSteps)
  43703. newPos = findWordBreakBefore (getCaretPosition());
  43704. else
  43705. newPos = getCaretPosition() - 1;
  43706. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43707. }
  43708. else if (key.isKeyCode (KeyPress::rightKey)
  43709. || key.isKeyCode (KeyPress::downKey))
  43710. {
  43711. newTransaction();
  43712. int newPos;
  43713. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  43714. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  43715. else if (moveInWholeWordSteps)
  43716. newPos = findWordBreakAfter (getCaretPosition());
  43717. else
  43718. newPos = getCaretPosition() + 1;
  43719. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43720. }
  43721. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  43722. {
  43723. newTransaction();
  43724. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  43725. key.getModifiers().isShiftDown());
  43726. }
  43727. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  43728. {
  43729. newTransaction();
  43730. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  43731. key.getModifiers().isShiftDown());
  43732. }
  43733. else if (key.isKeyCode (KeyPress::homeKey))
  43734. {
  43735. newTransaction();
  43736. if (isMultiLine() && ! moveInWholeWordSteps)
  43737. moveCursorTo (indexAtPosition (0.0f, cursorY),
  43738. key.getModifiers().isShiftDown());
  43739. else
  43740. moveCursorTo (0, key.getModifiers().isShiftDown());
  43741. }
  43742. else if (key.isKeyCode (KeyPress::endKey))
  43743. {
  43744. newTransaction();
  43745. if (isMultiLine() && ! moveInWholeWordSteps)
  43746. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  43747. key.getModifiers().isShiftDown());
  43748. else
  43749. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  43750. }
  43751. else if (key.isKeyCode (KeyPress::backspaceKey))
  43752. {
  43753. if (moveInWholeWordSteps)
  43754. {
  43755. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  43756. }
  43757. else
  43758. {
  43759. if (selection.isEmpty() && selection.getStart() > 0)
  43760. selection.setStart (selection.getEnd() - 1);
  43761. }
  43762. cut();
  43763. }
  43764. else if (key.isKeyCode (KeyPress::deleteKey))
  43765. {
  43766. if (key.getModifiers().isShiftDown())
  43767. copy();
  43768. if (selection.isEmpty() && selection.getStart() < getTotalNumChars())
  43769. selection.setEnd (selection.getStart() + 1);
  43770. cut();
  43771. }
  43772. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0)
  43773. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  43774. {
  43775. newTransaction();
  43776. copy();
  43777. }
  43778. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  43779. {
  43780. newTransaction();
  43781. copy();
  43782. cut();
  43783. }
  43784. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0)
  43785. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  43786. {
  43787. newTransaction();
  43788. paste();
  43789. }
  43790. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  43791. {
  43792. newTransaction();
  43793. doUndoRedo (false);
  43794. }
  43795. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0))
  43796. {
  43797. newTransaction();
  43798. doUndoRedo (true);
  43799. }
  43800. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  43801. {
  43802. newTransaction();
  43803. moveCursorTo (getTotalNumChars(), false);
  43804. moveCursorTo (0, true);
  43805. }
  43806. else if (key == KeyPress::returnKey)
  43807. {
  43808. newTransaction();
  43809. insertTextAtCaret ("\n");
  43810. }
  43811. else if (key.isKeyCode (KeyPress::escapeKey))
  43812. {
  43813. newTransaction();
  43814. moveCursorTo (getCaretPosition(), false);
  43815. escapePressed();
  43816. }
  43817. else if (key.getTextCharacter() >= ' '
  43818. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  43819. {
  43820. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  43821. lastTransactionTime = Time::getApproximateMillisecondCounter();
  43822. }
  43823. else
  43824. {
  43825. return false;
  43826. }
  43827. return true;
  43828. }
  43829. bool TextEditor::keyStateChanged (const bool isKeyDown)
  43830. {
  43831. if (! isKeyDown)
  43832. return false;
  43833. #if JUCE_WINDOWS
  43834. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  43835. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  43836. #endif
  43837. // (overridden to avoid forwarding key events to the parent)
  43838. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  43839. }
  43840. const int baseMenuItemID = 0x7fff0000;
  43841. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  43842. {
  43843. const bool writable = ! isReadOnly();
  43844. if (passwordCharacter == 0)
  43845. {
  43846. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  43847. m.addItem (baseMenuItemID + 2, TRANS("copy"), ! selection.isEmpty());
  43848. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  43849. }
  43850. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  43851. m.addSeparator();
  43852. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  43853. m.addSeparator();
  43854. if (getUndoManager() != 0)
  43855. {
  43856. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  43857. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  43858. }
  43859. }
  43860. void TextEditor::performPopupMenuAction (const int menuItemID)
  43861. {
  43862. switch (menuItemID)
  43863. {
  43864. case baseMenuItemID + 1:
  43865. copy();
  43866. cut();
  43867. break;
  43868. case baseMenuItemID + 2:
  43869. copy();
  43870. break;
  43871. case baseMenuItemID + 3:
  43872. paste();
  43873. break;
  43874. case baseMenuItemID + 4:
  43875. cut();
  43876. break;
  43877. case baseMenuItemID + 5:
  43878. moveCursorTo (getTotalNumChars(), false);
  43879. moveCursorTo (0, true);
  43880. break;
  43881. case baseMenuItemID + 6:
  43882. doUndoRedo (false);
  43883. break;
  43884. case baseMenuItemID + 7:
  43885. doUndoRedo (true);
  43886. break;
  43887. default:
  43888. break;
  43889. }
  43890. }
  43891. void TextEditor::focusGained (FocusChangeType)
  43892. {
  43893. newTransaction();
  43894. caretFlashState = true;
  43895. if (selectAllTextWhenFocused)
  43896. {
  43897. moveCursorTo (0, false);
  43898. moveCursorTo (getTotalNumChars(), true);
  43899. }
  43900. repaint();
  43901. if (caretVisible)
  43902. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43903. ComponentPeer* const peer = getPeer();
  43904. if (peer != 0 && ! isReadOnly())
  43905. peer->textInputRequired (getScreenPosition() - peer->getScreenPosition());
  43906. }
  43907. void TextEditor::focusLost (FocusChangeType)
  43908. {
  43909. newTransaction();
  43910. wasFocused = false;
  43911. textHolder->stopTimer();
  43912. caretFlashState = false;
  43913. postCommandMessage (TextEditorDefs::focusLossMessageId);
  43914. repaint();
  43915. }
  43916. void TextEditor::resized()
  43917. {
  43918. viewport->setBoundsInset (borderSize);
  43919. viewport->setSingleStepSizes (16, roundToInt (currentFont.getHeight()));
  43920. updateTextHolderSize();
  43921. if (! isMultiLine())
  43922. {
  43923. scrollToMakeSureCursorIsVisible();
  43924. }
  43925. else
  43926. {
  43927. updateCaretPosition();
  43928. }
  43929. }
  43930. void TextEditor::handleCommandMessage (const int commandId)
  43931. {
  43932. Component::BailOutChecker checker (this);
  43933. switch (commandId)
  43934. {
  43935. case TextEditorDefs::textChangeMessageId:
  43936. listeners.callChecked (checker, &TextEditor::Listener::textEditorTextChanged, (TextEditor&) *this);
  43937. break;
  43938. case TextEditorDefs::returnKeyMessageId:
  43939. listeners.callChecked (checker, &TextEditor::Listener::textEditorReturnKeyPressed, (TextEditor&) *this);
  43940. break;
  43941. case TextEditorDefs::escapeKeyMessageId:
  43942. listeners.callChecked (checker, &TextEditor::Listener::textEditorEscapeKeyPressed, (TextEditor&) *this);
  43943. break;
  43944. case TextEditorDefs::focusLossMessageId:
  43945. listeners.callChecked (checker, &TextEditor::Listener::textEditorFocusLost, (TextEditor&) *this);
  43946. break;
  43947. default:
  43948. jassertfalse;
  43949. break;
  43950. }
  43951. }
  43952. void TextEditor::enablementChanged()
  43953. {
  43954. setMouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  43955. : MouseCursor::IBeamCursor);
  43956. repaint();
  43957. }
  43958. UndoManager* TextEditor::getUndoManager() throw()
  43959. {
  43960. return isReadOnly() ? 0 : &undoManager;
  43961. }
  43962. void TextEditor::clearInternal (UndoManager* const um)
  43963. {
  43964. remove (Range<int> (0, getTotalNumChars()), um, caretPosition);
  43965. }
  43966. void TextEditor::insert (const String& text,
  43967. const int insertIndex,
  43968. const Font& font,
  43969. const Colour& colour,
  43970. UndoManager* const um,
  43971. const int caretPositionToMoveTo)
  43972. {
  43973. if (text.isNotEmpty())
  43974. {
  43975. if (um != 0)
  43976. {
  43977. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  43978. newTransaction();
  43979. um->perform (new InsertAction (*this, text, insertIndex, font, colour,
  43980. caretPosition, caretPositionToMoveTo));
  43981. }
  43982. else
  43983. {
  43984. repaintText (Range<int> (insertIndex, getTotalNumChars())); // must do this before and after changing the data, in case
  43985. // a line gets moved due to word wrap
  43986. int index = 0;
  43987. int nextIndex = 0;
  43988. for (int i = 0; i < sections.size(); ++i)
  43989. {
  43990. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  43991. if (insertIndex == index)
  43992. {
  43993. sections.insert (i, new UniformTextSection (text,
  43994. font, colour,
  43995. passwordCharacter));
  43996. break;
  43997. }
  43998. else if (insertIndex > index && insertIndex < nextIndex)
  43999. {
  44000. splitSection (i, insertIndex - index);
  44001. sections.insert (i + 1, new UniformTextSection (text,
  44002. font, colour,
  44003. passwordCharacter));
  44004. break;
  44005. }
  44006. index = nextIndex;
  44007. }
  44008. if (nextIndex == insertIndex)
  44009. sections.add (new UniformTextSection (text,
  44010. font, colour,
  44011. passwordCharacter));
  44012. coalesceSimilarSections();
  44013. totalNumChars = -1;
  44014. valueTextNeedsUpdating = true;
  44015. moveCursorTo (caretPositionToMoveTo, false);
  44016. repaintText (Range<int> (insertIndex, getTotalNumChars()));
  44017. }
  44018. }
  44019. }
  44020. void TextEditor::reinsert (const int insertIndex,
  44021. const Array <UniformTextSection*>& sectionsToInsert)
  44022. {
  44023. int index = 0;
  44024. int nextIndex = 0;
  44025. for (int i = 0; i < sections.size(); ++i)
  44026. {
  44027. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  44028. if (insertIndex == index)
  44029. {
  44030. for (int j = sectionsToInsert.size(); --j >= 0;)
  44031. sections.insert (i, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  44032. break;
  44033. }
  44034. else if (insertIndex > index && insertIndex < nextIndex)
  44035. {
  44036. splitSection (i, insertIndex - index);
  44037. for (int j = sectionsToInsert.size(); --j >= 0;)
  44038. sections.insert (i + 1, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  44039. break;
  44040. }
  44041. index = nextIndex;
  44042. }
  44043. if (nextIndex == insertIndex)
  44044. {
  44045. for (int j = 0; j < sectionsToInsert.size(); ++j)
  44046. sections.add (new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  44047. }
  44048. coalesceSimilarSections();
  44049. totalNumChars = -1;
  44050. valueTextNeedsUpdating = true;
  44051. }
  44052. void TextEditor::remove (const Range<int>& range,
  44053. UndoManager* const um,
  44054. const int caretPositionToMoveTo)
  44055. {
  44056. if (! range.isEmpty())
  44057. {
  44058. int index = 0;
  44059. for (int i = 0; i < sections.size(); ++i)
  44060. {
  44061. const int nextIndex = index + sections.getUnchecked(i)->getTotalLength();
  44062. if (range.getStart() > index && range.getStart() < nextIndex)
  44063. {
  44064. splitSection (i, range.getStart() - index);
  44065. --i;
  44066. }
  44067. else if (range.getEnd() > index && range.getEnd() < nextIndex)
  44068. {
  44069. splitSection (i, range.getEnd() - index);
  44070. --i;
  44071. }
  44072. else
  44073. {
  44074. index = nextIndex;
  44075. if (index > range.getEnd())
  44076. break;
  44077. }
  44078. }
  44079. index = 0;
  44080. if (um != 0)
  44081. {
  44082. Array <UniformTextSection*> removedSections;
  44083. for (int i = 0; i < sections.size(); ++i)
  44084. {
  44085. if (range.getEnd() <= range.getStart())
  44086. break;
  44087. UniformTextSection* const section = sections.getUnchecked (i);
  44088. const int nextIndex = index + section->getTotalLength();
  44089. if (range.getStart() <= index && range.getEnd() >= nextIndex)
  44090. removedSections.add (new UniformTextSection (*section));
  44091. index = nextIndex;
  44092. }
  44093. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  44094. newTransaction();
  44095. um->perform (new RemoveAction (*this, range, caretPosition,
  44096. caretPositionToMoveTo, removedSections));
  44097. }
  44098. else
  44099. {
  44100. Range<int> remainingRange (range);
  44101. for (int i = 0; i < sections.size(); ++i)
  44102. {
  44103. UniformTextSection* const section = sections.getUnchecked (i);
  44104. const int nextIndex = index + section->getTotalLength();
  44105. if (remainingRange.getStart() <= index && remainingRange.getEnd() >= nextIndex)
  44106. {
  44107. sections.remove(i);
  44108. section->clear();
  44109. delete section;
  44110. remainingRange.setEnd (remainingRange.getEnd() - (nextIndex - index));
  44111. if (remainingRange.isEmpty())
  44112. break;
  44113. --i;
  44114. }
  44115. else
  44116. {
  44117. index = nextIndex;
  44118. }
  44119. }
  44120. coalesceSimilarSections();
  44121. totalNumChars = -1;
  44122. valueTextNeedsUpdating = true;
  44123. moveCursorTo (caretPositionToMoveTo, false);
  44124. repaintText (Range<int> (range.getStart(), getTotalNumChars()));
  44125. }
  44126. }
  44127. }
  44128. const String TextEditor::getText() const
  44129. {
  44130. String t;
  44131. t.preallocateStorage (getTotalNumChars());
  44132. String::Concatenator concatenator (t);
  44133. for (int i = 0; i < sections.size(); ++i)
  44134. sections.getUnchecked (i)->appendAllText (concatenator);
  44135. return t;
  44136. }
  44137. const String TextEditor::getTextInRange (const Range<int>& range) const
  44138. {
  44139. String t;
  44140. if (! range.isEmpty())
  44141. {
  44142. t.preallocateStorage (jmin (getTotalNumChars(), range.getLength()));
  44143. String::Concatenator concatenator (t);
  44144. int index = 0;
  44145. for (int i = 0; i < sections.size(); ++i)
  44146. {
  44147. const UniformTextSection* const s = sections.getUnchecked (i);
  44148. const int nextIndex = index + s->getTotalLength();
  44149. if (range.getStart() < nextIndex)
  44150. {
  44151. if (range.getEnd() <= index)
  44152. break;
  44153. s->appendSubstring (concatenator, range - index);
  44154. }
  44155. index = nextIndex;
  44156. }
  44157. }
  44158. return t;
  44159. }
  44160. const String TextEditor::getHighlightedText() const
  44161. {
  44162. return getTextInRange (selection);
  44163. }
  44164. int TextEditor::getTotalNumChars() const
  44165. {
  44166. if (totalNumChars < 0)
  44167. {
  44168. totalNumChars = 0;
  44169. for (int i = sections.size(); --i >= 0;)
  44170. totalNumChars += sections.getUnchecked (i)->getTotalLength();
  44171. }
  44172. return totalNumChars;
  44173. }
  44174. bool TextEditor::isEmpty() const
  44175. {
  44176. return getTotalNumChars() == 0;
  44177. }
  44178. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const
  44179. {
  44180. const float wordWrapWidth = getWordWrapWidth();
  44181. if (wordWrapWidth > 0 && sections.size() > 0)
  44182. {
  44183. Iterator i (sections, wordWrapWidth, passwordCharacter);
  44184. i.getCharPosition (index, cx, cy, lineHeight);
  44185. }
  44186. else
  44187. {
  44188. cx = cy = 0;
  44189. lineHeight = currentFont.getHeight();
  44190. }
  44191. }
  44192. int TextEditor::indexAtPosition (const float x, const float y)
  44193. {
  44194. const float wordWrapWidth = getWordWrapWidth();
  44195. if (wordWrapWidth > 0)
  44196. {
  44197. Iterator i (sections, wordWrapWidth, passwordCharacter);
  44198. while (i.next())
  44199. {
  44200. if (i.lineY + i.lineHeight > y)
  44201. {
  44202. if (i.lineY > y)
  44203. return jmax (0, i.indexInText - 1);
  44204. if (i.atomX >= x)
  44205. return i.indexInText;
  44206. if (x < i.atomRight)
  44207. return i.xToIndex (x);
  44208. }
  44209. }
  44210. }
  44211. return getTotalNumChars();
  44212. }
  44213. int TextEditor::findWordBreakAfter (const int position) const
  44214. {
  44215. const String t (getTextInRange (Range<int> (position, position + 512)));
  44216. const int totalLength = t.length();
  44217. int i = 0;
  44218. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  44219. ++i;
  44220. const int type = TextEditorDefs::getCharacterCategory (t[i]);
  44221. while (i < totalLength && type == TextEditorDefs::getCharacterCategory (t[i]))
  44222. ++i;
  44223. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  44224. ++i;
  44225. return position + i;
  44226. }
  44227. int TextEditor::findWordBreakBefore (const int position) const
  44228. {
  44229. if (position <= 0)
  44230. return 0;
  44231. const int startOfBuffer = jmax (0, position - 512);
  44232. const String t (getTextInRange (Range<int> (startOfBuffer, position)));
  44233. int i = position - startOfBuffer;
  44234. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  44235. --i;
  44236. if (i > 0)
  44237. {
  44238. const int type = TextEditorDefs::getCharacterCategory (t [i - 1]);
  44239. while (i > 0 && type == TextEditorDefs::getCharacterCategory (t [i - 1]))
  44240. --i;
  44241. }
  44242. jassert (startOfBuffer + i >= 0);
  44243. return startOfBuffer + i;
  44244. }
  44245. void TextEditor::splitSection (const int sectionIndex,
  44246. const int charToSplitAt)
  44247. {
  44248. jassert (sections[sectionIndex] != 0);
  44249. sections.insert (sectionIndex + 1,
  44250. sections.getUnchecked (sectionIndex)->split (charToSplitAt, passwordCharacter));
  44251. }
  44252. void TextEditor::coalesceSimilarSections()
  44253. {
  44254. for (int i = 0; i < sections.size() - 1; ++i)
  44255. {
  44256. UniformTextSection* const s1 = sections.getUnchecked (i);
  44257. UniformTextSection* const s2 = sections.getUnchecked (i + 1);
  44258. if (s1->font == s2->font
  44259. && s1->colour == s2->colour)
  44260. {
  44261. s1->append (*s2, passwordCharacter);
  44262. sections.remove (i + 1);
  44263. delete s2;
  44264. --i;
  44265. }
  44266. }
  44267. }
  44268. END_JUCE_NAMESPACE
  44269. /*** End of inlined file: juce_TextEditor.cpp ***/
  44270. /*** Start of inlined file: juce_Toolbar.cpp ***/
  44271. BEGIN_JUCE_NAMESPACE
  44272. const char* const Toolbar::toolbarDragDescriptor = "_toolbarItem_";
  44273. class ToolbarSpacerComp : public ToolbarItemComponent
  44274. {
  44275. public:
  44276. ToolbarSpacerComp (const int itemId_, const float fixedSize_, const bool drawBar_)
  44277. : ToolbarItemComponent (itemId_, String::empty, false),
  44278. fixedSize (fixedSize_),
  44279. drawBar (drawBar_)
  44280. {
  44281. }
  44282. ~ToolbarSpacerComp()
  44283. {
  44284. }
  44285. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  44286. int& preferredSize, int& minSize, int& maxSize)
  44287. {
  44288. if (fixedSize <= 0)
  44289. {
  44290. preferredSize = toolbarThickness * 2;
  44291. minSize = 4;
  44292. maxSize = 32768;
  44293. }
  44294. else
  44295. {
  44296. maxSize = roundToInt (toolbarThickness * fixedSize);
  44297. minSize = drawBar ? maxSize : jmin (4, maxSize);
  44298. preferredSize = maxSize;
  44299. if (getEditingMode() == editableOnPalette)
  44300. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  44301. }
  44302. return true;
  44303. }
  44304. void paintButtonArea (Graphics&, int, int, bool, bool)
  44305. {
  44306. }
  44307. void contentAreaChanged (const Rectangle<int>&)
  44308. {
  44309. }
  44310. int getResizeOrder() const throw()
  44311. {
  44312. return fixedSize <= 0 ? 0 : 1;
  44313. }
  44314. void paint (Graphics& g)
  44315. {
  44316. const int w = getWidth();
  44317. const int h = getHeight();
  44318. if (drawBar)
  44319. {
  44320. g.setColour (findColour (Toolbar::separatorColourId, true));
  44321. const float thickness = 0.2f;
  44322. if (isToolbarVertical())
  44323. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  44324. else
  44325. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  44326. }
  44327. if (getEditingMode() != normalMode && ! drawBar)
  44328. {
  44329. g.setColour (findColour (Toolbar::separatorColourId, true));
  44330. const int indentX = jmin (2, (w - 3) / 2);
  44331. const int indentY = jmin (2, (h - 3) / 2);
  44332. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  44333. if (fixedSize <= 0)
  44334. {
  44335. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  44336. if (isToolbarVertical())
  44337. {
  44338. x1 = w * 0.5f;
  44339. y1 = h * 0.4f;
  44340. x2 = x1;
  44341. y2 = indentX * 2.0f;
  44342. x3 = x1;
  44343. y3 = h * 0.6f;
  44344. x4 = x1;
  44345. y4 = h - y2;
  44346. hw = w * 0.15f;
  44347. hl = w * 0.2f;
  44348. }
  44349. else
  44350. {
  44351. x1 = w * 0.4f;
  44352. y1 = h * 0.5f;
  44353. x2 = indentX * 2.0f;
  44354. y2 = y1;
  44355. x3 = w * 0.6f;
  44356. y3 = y1;
  44357. x4 = w - x2;
  44358. y4 = y1;
  44359. hw = h * 0.15f;
  44360. hl = h * 0.2f;
  44361. }
  44362. Path p;
  44363. p.addArrow (Line<float> (x1, y1, x2, y2), 1.5f, hw, hl);
  44364. p.addArrow (Line<float> (x3, y3, x4, y4), 1.5f, hw, hl);
  44365. g.fillPath (p);
  44366. }
  44367. }
  44368. }
  44369. juce_UseDebuggingNewOperator
  44370. private:
  44371. const float fixedSize;
  44372. const bool drawBar;
  44373. ToolbarSpacerComp (const ToolbarSpacerComp&);
  44374. ToolbarSpacerComp& operator= (const ToolbarSpacerComp&);
  44375. };
  44376. class Toolbar::MissingItemsComponent : public PopupMenuCustomComponent
  44377. {
  44378. public:
  44379. MissingItemsComponent (Toolbar& owner_, const int height_)
  44380. : PopupMenuCustomComponent (true),
  44381. owner (owner_),
  44382. height (height_)
  44383. {
  44384. for (int i = owner_.items.size(); --i >= 0;)
  44385. {
  44386. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  44387. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  44388. {
  44389. oldIndexes.insert (0, i);
  44390. addAndMakeVisible (tc, 0);
  44391. }
  44392. }
  44393. layout (400);
  44394. }
  44395. ~MissingItemsComponent()
  44396. {
  44397. // deleting the toolbar while its menu it open??
  44398. jassert (owner.isValidComponent());
  44399. for (int i = 0; i < getNumChildComponents(); ++i)
  44400. {
  44401. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44402. if (tc != 0)
  44403. {
  44404. tc->setVisible (false);
  44405. const int index = oldIndexes.remove (i);
  44406. owner.addChildComponent (tc, index);
  44407. --i;
  44408. }
  44409. }
  44410. owner.resized();
  44411. }
  44412. void layout (const int preferredWidth)
  44413. {
  44414. const int indent = 8;
  44415. int x = indent;
  44416. int y = indent;
  44417. int maxX = 0;
  44418. for (int i = 0; i < getNumChildComponents(); ++i)
  44419. {
  44420. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44421. if (tc != 0)
  44422. {
  44423. int preferredSize = 1, minSize = 1, maxSize = 1;
  44424. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44425. {
  44426. if (x + preferredSize > preferredWidth && x > indent)
  44427. {
  44428. x = indent;
  44429. y += height;
  44430. }
  44431. tc->setBounds (x, y, preferredSize, height);
  44432. x += preferredSize;
  44433. maxX = jmax (maxX, x);
  44434. }
  44435. }
  44436. }
  44437. setSize (maxX + 8, y + height + 8);
  44438. }
  44439. void getIdealSize (int& idealWidth, int& idealHeight)
  44440. {
  44441. idealWidth = getWidth();
  44442. idealHeight = getHeight();
  44443. }
  44444. juce_UseDebuggingNewOperator
  44445. private:
  44446. Toolbar& owner;
  44447. const int height;
  44448. Array <int> oldIndexes;
  44449. MissingItemsComponent (const MissingItemsComponent&);
  44450. MissingItemsComponent& operator= (const MissingItemsComponent&);
  44451. };
  44452. Toolbar::Toolbar()
  44453. : vertical (false),
  44454. isEditingActive (false),
  44455. toolbarStyle (Toolbar::iconsOnly)
  44456. {
  44457. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  44458. missingItemsButton->setAlwaysOnTop (true);
  44459. missingItemsButton->addButtonListener (this);
  44460. }
  44461. Toolbar::~Toolbar()
  44462. {
  44463. animator.cancelAllAnimations (true);
  44464. deleteAllChildren();
  44465. }
  44466. void Toolbar::setVertical (const bool shouldBeVertical)
  44467. {
  44468. if (vertical != shouldBeVertical)
  44469. {
  44470. vertical = shouldBeVertical;
  44471. resized();
  44472. }
  44473. }
  44474. void Toolbar::clear()
  44475. {
  44476. for (int i = items.size(); --i >= 0;)
  44477. {
  44478. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44479. items.remove (i);
  44480. delete tc;
  44481. }
  44482. resized();
  44483. }
  44484. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  44485. {
  44486. if (itemId == ToolbarItemFactory::separatorBarId)
  44487. return new ToolbarSpacerComp (itemId, 0.1f, true);
  44488. else if (itemId == ToolbarItemFactory::spacerId)
  44489. return new ToolbarSpacerComp (itemId, 0.5f, false);
  44490. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  44491. return new ToolbarSpacerComp (itemId, 0, false);
  44492. return factory.createItem (itemId);
  44493. }
  44494. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  44495. const int itemId,
  44496. const int insertIndex)
  44497. {
  44498. // An ID can't be zero - this might indicate a mistake somewhere?
  44499. jassert (itemId != 0);
  44500. ToolbarItemComponent* const tc = createItem (factory, itemId);
  44501. if (tc != 0)
  44502. {
  44503. #if JUCE_DEBUG
  44504. Array <int> allowedIds;
  44505. factory.getAllToolbarItemIds (allowedIds);
  44506. // If your factory can create an item for a given ID, it must also return
  44507. // that ID from its getAllToolbarItemIds() method!
  44508. jassert (allowedIds.contains (itemId));
  44509. #endif
  44510. items.insert (insertIndex, tc);
  44511. addAndMakeVisible (tc, insertIndex);
  44512. }
  44513. }
  44514. void Toolbar::addItem (ToolbarItemFactory& factory,
  44515. const int itemId,
  44516. const int insertIndex)
  44517. {
  44518. addItemInternal (factory, itemId, insertIndex);
  44519. resized();
  44520. }
  44521. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  44522. {
  44523. Array <int> ids;
  44524. factoryToUse.getDefaultItemSet (ids);
  44525. clear();
  44526. for (int i = 0; i < ids.size(); ++i)
  44527. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  44528. resized();
  44529. }
  44530. void Toolbar::removeToolbarItem (const int itemIndex)
  44531. {
  44532. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  44533. if (tc != 0)
  44534. {
  44535. items.removeValue (tc);
  44536. delete tc;
  44537. resized();
  44538. }
  44539. }
  44540. int Toolbar::getNumItems() const throw()
  44541. {
  44542. return items.size();
  44543. }
  44544. int Toolbar::getItemId (const int itemIndex) const throw()
  44545. {
  44546. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  44547. return tc != 0 ? tc->getItemId() : 0;
  44548. }
  44549. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  44550. {
  44551. return items [itemIndex];
  44552. }
  44553. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  44554. {
  44555. for (;;)
  44556. {
  44557. index += delta;
  44558. ToolbarItemComponent* const tc = getItemComponent (index);
  44559. if (tc == 0)
  44560. break;
  44561. if (tc->isActive)
  44562. return tc;
  44563. }
  44564. return 0;
  44565. }
  44566. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  44567. {
  44568. if (toolbarStyle != newStyle)
  44569. {
  44570. toolbarStyle = newStyle;
  44571. updateAllItemPositions (false);
  44572. }
  44573. }
  44574. const String Toolbar::toString() const
  44575. {
  44576. String s ("TB:");
  44577. for (int i = 0; i < getNumItems(); ++i)
  44578. s << getItemId(i) << ' ';
  44579. return s.trimEnd();
  44580. }
  44581. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  44582. const String& savedVersion)
  44583. {
  44584. if (! savedVersion.startsWith ("TB:"))
  44585. return false;
  44586. StringArray tokens;
  44587. tokens.addTokens (savedVersion.substring (3), false);
  44588. clear();
  44589. for (int i = 0; i < tokens.size(); ++i)
  44590. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  44591. resized();
  44592. return true;
  44593. }
  44594. void Toolbar::paint (Graphics& g)
  44595. {
  44596. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  44597. }
  44598. int Toolbar::getThickness() const throw()
  44599. {
  44600. return vertical ? getWidth() : getHeight();
  44601. }
  44602. int Toolbar::getLength() const throw()
  44603. {
  44604. return vertical ? getHeight() : getWidth();
  44605. }
  44606. void Toolbar::setEditingActive (const bool active)
  44607. {
  44608. if (isEditingActive != active)
  44609. {
  44610. isEditingActive = active;
  44611. updateAllItemPositions (false);
  44612. }
  44613. }
  44614. void Toolbar::resized()
  44615. {
  44616. updateAllItemPositions (false);
  44617. }
  44618. void Toolbar::updateAllItemPositions (const bool animate)
  44619. {
  44620. if (getWidth() > 0 && getHeight() > 0)
  44621. {
  44622. StretchableObjectResizer resizer;
  44623. int i;
  44624. for (i = 0; i < items.size(); ++i)
  44625. {
  44626. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44627. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  44628. : ToolbarItemComponent::normalMode);
  44629. tc->setStyle (toolbarStyle);
  44630. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  44631. int preferredSize = 1, minSize = 1, maxSize = 1;
  44632. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  44633. preferredSize, minSize, maxSize))
  44634. {
  44635. tc->isActive = true;
  44636. resizer.addItem (preferredSize, minSize, maxSize,
  44637. spacer != 0 ? spacer->getResizeOrder() : 2);
  44638. }
  44639. else
  44640. {
  44641. tc->isActive = false;
  44642. tc->setVisible (false);
  44643. }
  44644. }
  44645. resizer.resizeToFit (getLength());
  44646. int totalLength = 0;
  44647. for (i = 0; i < resizer.getNumItems(); ++i)
  44648. totalLength += (int) resizer.getItemSize (i);
  44649. const bool itemsOffTheEnd = totalLength > getLength();
  44650. const int extrasButtonSize = getThickness() / 2;
  44651. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  44652. missingItemsButton->setVisible (itemsOffTheEnd);
  44653. missingItemsButton->setEnabled (! isEditingActive);
  44654. if (vertical)
  44655. missingItemsButton->setCentrePosition (getWidth() / 2,
  44656. getHeight() - 4 - extrasButtonSize / 2);
  44657. else
  44658. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  44659. getHeight() / 2);
  44660. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  44661. : missingItemsButton->getX()) - 4
  44662. : getLength();
  44663. int pos = 0, activeIndex = 0;
  44664. for (i = 0; i < items.size(); ++i)
  44665. {
  44666. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44667. if (tc->isActive)
  44668. {
  44669. const int size = (int) resizer.getItemSize (activeIndex++);
  44670. Rectangle<int> newBounds;
  44671. if (vertical)
  44672. newBounds.setBounds (0, pos, getWidth(), size);
  44673. else
  44674. newBounds.setBounds (pos, 0, size, getHeight());
  44675. if (animate)
  44676. {
  44677. animator.animateComponent (tc, newBounds, 200, 3.0, 0.0);
  44678. }
  44679. else
  44680. {
  44681. animator.cancelAnimation (tc, false);
  44682. tc->setBounds (newBounds);
  44683. }
  44684. pos += size;
  44685. tc->setVisible (pos <= maxLength
  44686. && ((! tc->isBeingDragged)
  44687. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  44688. }
  44689. }
  44690. }
  44691. }
  44692. void Toolbar::buttonClicked (Button*)
  44693. {
  44694. jassert (missingItemsButton->isShowing());
  44695. if (missingItemsButton->isShowing())
  44696. {
  44697. PopupMenu m;
  44698. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  44699. m.showAt (missingItemsButton);
  44700. }
  44701. }
  44702. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  44703. Component* /*sourceComponent*/)
  44704. {
  44705. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  44706. }
  44707. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  44708. {
  44709. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44710. if (tc != 0)
  44711. {
  44712. if (getNumItems() == 0)
  44713. {
  44714. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  44715. {
  44716. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  44717. if (palette != 0)
  44718. palette->replaceComponent (tc);
  44719. }
  44720. else
  44721. {
  44722. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  44723. }
  44724. items.add (tc);
  44725. addChildComponent (tc);
  44726. updateAllItemPositions (false);
  44727. }
  44728. else
  44729. {
  44730. for (int i = getNumItems(); --i >= 0;)
  44731. {
  44732. int currentIndex = getIndexOfChildComponent (tc);
  44733. if (currentIndex < 0)
  44734. {
  44735. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  44736. {
  44737. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  44738. if (palette != 0)
  44739. palette->replaceComponent (tc);
  44740. }
  44741. else
  44742. {
  44743. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  44744. }
  44745. items.add (tc);
  44746. addChildComponent (tc);
  44747. currentIndex = getIndexOfChildComponent (tc);
  44748. updateAllItemPositions (true);
  44749. }
  44750. int newIndex = currentIndex;
  44751. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  44752. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  44753. const Rectangle<int> current (animator.getComponentDestination (getChildComponent (newIndex)));
  44754. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  44755. if (prev != 0)
  44756. {
  44757. const Rectangle<int> previousPos (animator.getComponentDestination (prev));
  44758. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  44759. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  44760. {
  44761. newIndex = getIndexOfChildComponent (prev);
  44762. }
  44763. }
  44764. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  44765. if (next != 0)
  44766. {
  44767. const Rectangle<int> nextPos (animator.getComponentDestination (next));
  44768. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  44769. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  44770. {
  44771. newIndex = getIndexOfChildComponent (next) + 1;
  44772. }
  44773. }
  44774. if (newIndex != currentIndex)
  44775. {
  44776. items.removeValue (tc);
  44777. removeChildComponent (tc);
  44778. addChildComponent (tc, newIndex);
  44779. items.insert (newIndex, tc);
  44780. updateAllItemPositions (true);
  44781. }
  44782. else
  44783. {
  44784. break;
  44785. }
  44786. }
  44787. }
  44788. }
  44789. }
  44790. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  44791. {
  44792. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44793. if (tc != 0)
  44794. {
  44795. if (isParentOf (tc))
  44796. {
  44797. items.removeValue (tc);
  44798. removeChildComponent (tc);
  44799. updateAllItemPositions (true);
  44800. }
  44801. }
  44802. }
  44803. void Toolbar::itemDropped (const String&, Component*, int, int)
  44804. {
  44805. }
  44806. void Toolbar::mouseDown (const MouseEvent& e)
  44807. {
  44808. if (e.mods.isPopupMenu())
  44809. {
  44810. }
  44811. }
  44812. class ToolbarCustomisationDialog : public DialogWindow
  44813. {
  44814. public:
  44815. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  44816. Toolbar* const toolbar_,
  44817. const int optionFlags)
  44818. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  44819. toolbar (toolbar_)
  44820. {
  44821. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  44822. setResizable (true, true);
  44823. setResizeLimits (400, 300, 1500, 1000);
  44824. positionNearBar();
  44825. }
  44826. ~ToolbarCustomisationDialog()
  44827. {
  44828. setContentComponent (0, true);
  44829. }
  44830. void closeButtonPressed()
  44831. {
  44832. setVisible (false);
  44833. }
  44834. bool canModalEventBeSentToComponent (const Component* comp)
  44835. {
  44836. return toolbar->isParentOf (comp);
  44837. }
  44838. void positionNearBar()
  44839. {
  44840. const Rectangle<int> screenSize (toolbar->getParentMonitorArea());
  44841. const int tbx = toolbar->getScreenX();
  44842. const int tby = toolbar->getScreenY();
  44843. const int gap = 8;
  44844. int x, y;
  44845. if (toolbar->isVertical())
  44846. {
  44847. y = tby;
  44848. if (tbx > screenSize.getCentreX())
  44849. x = tbx - getWidth() - gap;
  44850. else
  44851. x = tbx + toolbar->getWidth() + gap;
  44852. }
  44853. else
  44854. {
  44855. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  44856. if (tby > screenSize.getCentreY())
  44857. y = tby - getHeight() - gap;
  44858. else
  44859. y = tby + toolbar->getHeight() + gap;
  44860. }
  44861. setTopLeftPosition (x, y);
  44862. }
  44863. private:
  44864. Toolbar* const toolbar;
  44865. class CustomiserPanel : public Component,
  44866. private ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  44867. private ButtonListener
  44868. {
  44869. public:
  44870. CustomiserPanel (ToolbarItemFactory& factory_,
  44871. Toolbar* const toolbar_,
  44872. const int optionFlags)
  44873. : factory (factory_),
  44874. toolbar (toolbar_),
  44875. styleBox (0),
  44876. defaultButton (0)
  44877. {
  44878. addAndMakeVisible (palette = new ToolbarItemPalette (factory, toolbar));
  44879. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  44880. | Toolbar::allowIconsWithTextChoice
  44881. | Toolbar::allowTextOnlyChoice)) != 0)
  44882. {
  44883. addAndMakeVisible (styleBox = new ComboBox (String::empty));
  44884. styleBox->setEditableText (false);
  44885. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0)
  44886. styleBox->addItem (TRANS("Show icons only"), 1);
  44887. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0)
  44888. styleBox->addItem (TRANS("Show icons and descriptions"), 2);
  44889. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0)
  44890. styleBox->addItem (TRANS("Show descriptions only"), 3);
  44891. if (toolbar_->getStyle() == Toolbar::iconsOnly)
  44892. styleBox->setSelectedId (1);
  44893. else if (toolbar_->getStyle() == Toolbar::iconsWithText)
  44894. styleBox->setSelectedId (2);
  44895. else if (toolbar_->getStyle() == Toolbar::textOnly)
  44896. styleBox->setSelectedId (3);
  44897. styleBox->addListener (this);
  44898. }
  44899. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  44900. {
  44901. addAndMakeVisible (defaultButton = new TextButton (TRANS ("Restore to default set of items")));
  44902. defaultButton->addButtonListener (this);
  44903. }
  44904. addAndMakeVisible (instructions = new Label (String::empty,
  44905. TRANS ("You can drag the items above and drop them onto a toolbar to add them.\n\nItems on the toolbar can also be dragged around to change their order, or dragged off the edge to delete them.")));
  44906. instructions->setFont (Font (13.0f));
  44907. setSize (500, 300);
  44908. }
  44909. ~CustomiserPanel()
  44910. {
  44911. deleteAllChildren();
  44912. }
  44913. void comboBoxChanged (ComboBox*)
  44914. {
  44915. if (styleBox->getSelectedId() == 1)
  44916. toolbar->setStyle (Toolbar::iconsOnly);
  44917. else if (styleBox->getSelectedId() == 2)
  44918. toolbar->setStyle (Toolbar::iconsWithText);
  44919. else if (styleBox->getSelectedId() == 3)
  44920. toolbar->setStyle (Toolbar::textOnly);
  44921. palette->resized(); // to make it update the styles
  44922. }
  44923. void buttonClicked (Button*)
  44924. {
  44925. toolbar->addDefaultItems (factory);
  44926. }
  44927. void paint (Graphics& g)
  44928. {
  44929. Colour background;
  44930. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  44931. if (dw != 0)
  44932. background = dw->getBackgroundColour();
  44933. g.setColour (background.contrasting().withAlpha (0.3f));
  44934. g.fillRect (palette->getX(), palette->getBottom() - 1, palette->getWidth(), 1);
  44935. }
  44936. void resized()
  44937. {
  44938. palette->setBounds (0, 0, getWidth(), getHeight() - 120);
  44939. if (styleBox != 0)
  44940. styleBox->setBounds (10, getHeight() - 110, 200, 22);
  44941. if (defaultButton != 0)
  44942. {
  44943. defaultButton->changeWidthToFitText (22);
  44944. defaultButton->setTopLeftPosition (240, getHeight() - 110);
  44945. }
  44946. instructions->setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  44947. }
  44948. private:
  44949. ToolbarItemFactory& factory;
  44950. Toolbar* const toolbar;
  44951. Label* instructions;
  44952. ToolbarItemPalette* palette;
  44953. ComboBox* styleBox;
  44954. TextButton* defaultButton;
  44955. };
  44956. };
  44957. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  44958. {
  44959. setEditingActive (true);
  44960. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  44961. dw.runModalLoop();
  44962. jassert (isValidComponent()); // ? deleting the toolbar while it's being edited?
  44963. setEditingActive (false);
  44964. }
  44965. END_JUCE_NAMESPACE
  44966. /*** End of inlined file: juce_Toolbar.cpp ***/
  44967. /*** Start of inlined file: juce_ToolbarItemComponent.cpp ***/
  44968. BEGIN_JUCE_NAMESPACE
  44969. ToolbarItemFactory::ToolbarItemFactory()
  44970. {
  44971. }
  44972. ToolbarItemFactory::~ToolbarItemFactory()
  44973. {
  44974. }
  44975. class ItemDragAndDropOverlayComponent : public Component
  44976. {
  44977. public:
  44978. ItemDragAndDropOverlayComponent()
  44979. : isDragging (false)
  44980. {
  44981. setAlwaysOnTop (true);
  44982. setRepaintsOnMouseActivity (true);
  44983. setMouseCursor (MouseCursor::DraggingHandCursor);
  44984. }
  44985. ~ItemDragAndDropOverlayComponent()
  44986. {
  44987. }
  44988. void paint (Graphics& g)
  44989. {
  44990. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  44991. if (isMouseOverOrDragging()
  44992. && tc != 0
  44993. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  44994. {
  44995. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  44996. g.drawRect (0, 0, getWidth(), getHeight(),
  44997. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  44998. }
  44999. }
  45000. void mouseDown (const MouseEvent& e)
  45001. {
  45002. isDragging = false;
  45003. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  45004. if (tc != 0)
  45005. {
  45006. tc->dragOffsetX = e.x;
  45007. tc->dragOffsetY = e.y;
  45008. }
  45009. }
  45010. void mouseDrag (const MouseEvent& e)
  45011. {
  45012. if (! (isDragging || e.mouseWasClicked()))
  45013. {
  45014. isDragging = true;
  45015. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  45016. if (dnd != 0)
  45017. {
  45018. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), Image::null, true);
  45019. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  45020. if (tc != 0)
  45021. {
  45022. tc->isBeingDragged = true;
  45023. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  45024. tc->setVisible (false);
  45025. }
  45026. }
  45027. }
  45028. }
  45029. void mouseUp (const MouseEvent&)
  45030. {
  45031. isDragging = false;
  45032. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  45033. if (tc != 0)
  45034. {
  45035. tc->isBeingDragged = false;
  45036. Toolbar* const tb = tc->getToolbar();
  45037. if (tb != 0)
  45038. tb->updateAllItemPositions (true);
  45039. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  45040. delete tc;
  45041. }
  45042. }
  45043. void parentSizeChanged()
  45044. {
  45045. setBounds (0, 0, getParentWidth(), getParentHeight());
  45046. }
  45047. juce_UseDebuggingNewOperator
  45048. private:
  45049. bool isDragging;
  45050. ItemDragAndDropOverlayComponent (const ItemDragAndDropOverlayComponent&);
  45051. ItemDragAndDropOverlayComponent& operator= (const ItemDragAndDropOverlayComponent&);
  45052. };
  45053. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  45054. const String& labelText,
  45055. const bool isBeingUsedAsAButton_)
  45056. : Button (labelText),
  45057. itemId (itemId_),
  45058. mode (normalMode),
  45059. toolbarStyle (Toolbar::iconsOnly),
  45060. dragOffsetX (0),
  45061. dragOffsetY (0),
  45062. isActive (true),
  45063. isBeingDragged (false),
  45064. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  45065. {
  45066. // Your item ID can't be 0!
  45067. jassert (itemId_ != 0);
  45068. }
  45069. ToolbarItemComponent::~ToolbarItemComponent()
  45070. {
  45071. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  45072. overlayComp = 0;
  45073. }
  45074. Toolbar* ToolbarItemComponent::getToolbar() const
  45075. {
  45076. return dynamic_cast <Toolbar*> (getParentComponent());
  45077. }
  45078. bool ToolbarItemComponent::isToolbarVertical() const
  45079. {
  45080. const Toolbar* const t = getToolbar();
  45081. return t != 0 && t->isVertical();
  45082. }
  45083. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  45084. {
  45085. if (toolbarStyle != newStyle)
  45086. {
  45087. toolbarStyle = newStyle;
  45088. repaint();
  45089. resized();
  45090. }
  45091. }
  45092. void ToolbarItemComponent::paintButton (Graphics& g, const bool over, const bool down)
  45093. {
  45094. if (isBeingUsedAsAButton)
  45095. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  45096. over, down, *this);
  45097. if (toolbarStyle != Toolbar::iconsOnly)
  45098. {
  45099. const int indent = contentArea.getX();
  45100. int y = indent;
  45101. int h = getHeight() - indent * 2;
  45102. if (toolbarStyle == Toolbar::iconsWithText)
  45103. {
  45104. y = contentArea.getBottom() + indent / 2;
  45105. h -= contentArea.getHeight();
  45106. }
  45107. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  45108. getButtonText(), *this);
  45109. }
  45110. if (! contentArea.isEmpty())
  45111. {
  45112. g.saveState();
  45113. g.setOrigin (contentArea.getX(), contentArea.getY());
  45114. g.reduceClipRegion (0, 0, contentArea.getWidth(), contentArea.getHeight());
  45115. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), over, down);
  45116. g.restoreState();
  45117. }
  45118. }
  45119. void ToolbarItemComponent::resized()
  45120. {
  45121. if (toolbarStyle != Toolbar::textOnly)
  45122. {
  45123. const int indent = jmin (proportionOfWidth (0.08f),
  45124. proportionOfHeight (0.08f));
  45125. contentArea = Rectangle<int> (indent, indent,
  45126. getWidth() - indent * 2,
  45127. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  45128. : (getHeight() - indent * 2));
  45129. }
  45130. else
  45131. {
  45132. contentArea = Rectangle<int>();
  45133. }
  45134. contentAreaChanged (contentArea);
  45135. }
  45136. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  45137. {
  45138. if (mode != newMode)
  45139. {
  45140. mode = newMode;
  45141. repaint();
  45142. if (mode == normalMode)
  45143. {
  45144. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  45145. overlayComp = 0;
  45146. }
  45147. else if (overlayComp == 0)
  45148. {
  45149. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  45150. overlayComp->parentSizeChanged();
  45151. }
  45152. resized();
  45153. }
  45154. }
  45155. END_JUCE_NAMESPACE
  45156. /*** End of inlined file: juce_ToolbarItemComponent.cpp ***/
  45157. /*** Start of inlined file: juce_ToolbarItemPalette.cpp ***/
  45158. BEGIN_JUCE_NAMESPACE
  45159. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  45160. Toolbar* const toolbar_)
  45161. : factory (factory_),
  45162. toolbar (toolbar_)
  45163. {
  45164. Component* const itemHolder = new Component();
  45165. Array <int> allIds;
  45166. factory_.getAllToolbarItemIds (allIds);
  45167. for (int i = 0; i < allIds.size(); ++i)
  45168. {
  45169. ToolbarItemComponent* const tc = Toolbar::createItem (factory_, allIds.getUnchecked (i));
  45170. jassert (tc != 0);
  45171. if (tc != 0)
  45172. {
  45173. itemHolder->addAndMakeVisible (tc);
  45174. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  45175. }
  45176. }
  45177. viewport = new Viewport();
  45178. viewport->setViewedComponent (itemHolder);
  45179. addAndMakeVisible (viewport);
  45180. }
  45181. ToolbarItemPalette::~ToolbarItemPalette()
  45182. {
  45183. viewport->getViewedComponent()->deleteAllChildren();
  45184. deleteAllChildren();
  45185. }
  45186. void ToolbarItemPalette::resized()
  45187. {
  45188. viewport->setBoundsInset (BorderSize (1));
  45189. Component* const itemHolder = viewport->getViewedComponent();
  45190. const int indent = 8;
  45191. const int preferredWidth = viewport->getWidth() - viewport->getScrollBarThickness() - indent;
  45192. const int height = toolbar->getThickness();
  45193. int x = indent;
  45194. int y = indent;
  45195. int maxX = 0;
  45196. for (int i = 0; i < itemHolder->getNumChildComponents(); ++i)
  45197. {
  45198. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (itemHolder->getChildComponent (i));
  45199. if (tc != 0)
  45200. {
  45201. tc->setStyle (toolbar->getStyle());
  45202. int preferredSize = 1, minSize = 1, maxSize = 1;
  45203. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  45204. {
  45205. if (x + preferredSize > preferredWidth && x > indent)
  45206. {
  45207. x = indent;
  45208. y += height;
  45209. }
  45210. tc->setBounds (x, y, preferredSize, height);
  45211. x += preferredSize + 8;
  45212. maxX = jmax (maxX, x);
  45213. }
  45214. }
  45215. }
  45216. itemHolder->setSize (maxX, y + height + 8);
  45217. }
  45218. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  45219. {
  45220. ToolbarItemComponent* const tc = Toolbar::createItem (factory, comp->getItemId());
  45221. jassert (tc != 0);
  45222. if (tc != 0)
  45223. {
  45224. tc->setBounds (comp->getBounds());
  45225. tc->setStyle (toolbar->getStyle());
  45226. tc->setEditingMode (comp->getEditingMode());
  45227. viewport->getViewedComponent()->addAndMakeVisible (tc, getIndexOfChildComponent (comp));
  45228. }
  45229. }
  45230. END_JUCE_NAMESPACE
  45231. /*** End of inlined file: juce_ToolbarItemPalette.cpp ***/
  45232. /*** Start of inlined file: juce_TreeView.cpp ***/
  45233. BEGIN_JUCE_NAMESPACE
  45234. class TreeViewContentComponent : public Component,
  45235. public TooltipClient
  45236. {
  45237. public:
  45238. TreeViewContentComponent (TreeView& owner_)
  45239. : owner (owner_),
  45240. buttonUnderMouse (0),
  45241. isDragging (false)
  45242. {
  45243. }
  45244. ~TreeViewContentComponent()
  45245. {
  45246. deleteAllChildren();
  45247. }
  45248. void mouseDown (const MouseEvent& e)
  45249. {
  45250. updateButtonUnderMouse (e);
  45251. isDragging = false;
  45252. needSelectionOnMouseUp = false;
  45253. Rectangle<int> pos;
  45254. TreeViewItem* const item = findItemAt (e.y, pos);
  45255. if (item == 0)
  45256. return;
  45257. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  45258. // as selection clicks)
  45259. if (e.x < pos.getX() && owner.openCloseButtonsVisible)
  45260. {
  45261. if (e.x >= pos.getX() - owner.getIndentSize())
  45262. item->setOpen (! item->isOpen());
  45263. // (clicks to the left of an open/close button are ignored)
  45264. }
  45265. else
  45266. {
  45267. // mouse-down inside the body of the item..
  45268. if (! owner.isMultiSelectEnabled())
  45269. item->setSelected (true, true);
  45270. else if (item->isSelected())
  45271. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  45272. else
  45273. selectBasedOnModifiers (item, e.mods);
  45274. if (e.x >= pos.getX())
  45275. item->itemClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  45276. }
  45277. }
  45278. void mouseUp (const MouseEvent& e)
  45279. {
  45280. updateButtonUnderMouse (e);
  45281. if (needSelectionOnMouseUp && e.mouseWasClicked())
  45282. {
  45283. Rectangle<int> pos;
  45284. TreeViewItem* const item = findItemAt (e.y, pos);
  45285. if (item != 0)
  45286. selectBasedOnModifiers (item, e.mods);
  45287. }
  45288. }
  45289. void mouseDoubleClick (const MouseEvent& e)
  45290. {
  45291. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  45292. {
  45293. Rectangle<int> pos;
  45294. TreeViewItem* const item = findItemAt (e.y, pos);
  45295. if (item != 0 && (e.x >= pos.getX() || ! owner.openCloseButtonsVisible))
  45296. item->itemDoubleClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  45297. }
  45298. }
  45299. void mouseDrag (const MouseEvent& e)
  45300. {
  45301. if (isEnabled()
  45302. && ! (isDragging || e.mouseWasClicked()
  45303. || e.getDistanceFromDragStart() < 5
  45304. || e.mods.isPopupMenu()))
  45305. {
  45306. isDragging = true;
  45307. Rectangle<int> pos;
  45308. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  45309. if (item != 0 && e.getMouseDownX() >= pos.getX())
  45310. {
  45311. const String dragDescription (item->getDragSourceDescription());
  45312. if (dragDescription.isNotEmpty())
  45313. {
  45314. DragAndDropContainer* const dragContainer
  45315. = DragAndDropContainer::findParentDragContainerFor (this);
  45316. if (dragContainer != 0)
  45317. {
  45318. pos.setSize (pos.getWidth(), item->itemHeight);
  45319. Image dragImage (Component::createComponentSnapshot (pos, true));
  45320. dragImage.multiplyAllAlphas (0.6f);
  45321. Point<int> imageOffset (pos.getPosition() - e.getPosition());
  45322. dragContainer->startDragging (dragDescription, &owner, dragImage, true, &imageOffset);
  45323. }
  45324. else
  45325. {
  45326. // to be able to do a drag-and-drop operation, the treeview needs to
  45327. // be inside a component which is also a DragAndDropContainer.
  45328. jassertfalse;
  45329. }
  45330. }
  45331. }
  45332. }
  45333. }
  45334. void mouseMove (const MouseEvent& e)
  45335. {
  45336. updateButtonUnderMouse (e);
  45337. }
  45338. void mouseExit (const MouseEvent& e)
  45339. {
  45340. updateButtonUnderMouse (e);
  45341. }
  45342. void paint (Graphics& g)
  45343. {
  45344. if (owner.rootItem != 0)
  45345. {
  45346. owner.handleAsyncUpdate();
  45347. if (! owner.rootItemVisible)
  45348. g.setOrigin (0, -owner.rootItem->itemHeight);
  45349. owner.rootItem->paintRecursively (g, getWidth());
  45350. }
  45351. }
  45352. TreeViewItem* findItemAt (int y, Rectangle<int>& itemPosition) const
  45353. {
  45354. if (owner.rootItem != 0)
  45355. {
  45356. owner.handleAsyncUpdate();
  45357. if (! owner.rootItemVisible)
  45358. y += owner.rootItem->itemHeight;
  45359. TreeViewItem* const ti = owner.rootItem->findItemRecursively (y);
  45360. if (ti != 0)
  45361. itemPosition = ti->getItemPosition (false);
  45362. return ti;
  45363. }
  45364. return 0;
  45365. }
  45366. void updateComponents()
  45367. {
  45368. const int visibleTop = -getY();
  45369. const int visibleBottom = visibleTop + getParentHeight();
  45370. BigInteger itemsToKeep;
  45371. {
  45372. TreeViewItem* item = owner.rootItem;
  45373. int y = (item != 0 && ! owner.rootItemVisible) ? -item->itemHeight : 0;
  45374. while (item != 0 && y < visibleBottom)
  45375. {
  45376. y += item->itemHeight;
  45377. if (y >= visibleTop)
  45378. {
  45379. const int index = rowComponentIds.indexOf (item->uid);
  45380. if (index < 0)
  45381. {
  45382. Component* const comp = item->createItemComponent();
  45383. if (comp != 0)
  45384. {
  45385. addAndMakeVisible (comp);
  45386. itemsToKeep.setBit (rowComponentItems.size());
  45387. rowComponentItems.add (item);
  45388. rowComponentIds.add (item->uid);
  45389. rowComponents.add (comp);
  45390. }
  45391. }
  45392. else
  45393. {
  45394. itemsToKeep.setBit (index);
  45395. }
  45396. }
  45397. item = item->getNextVisibleItem (true);
  45398. }
  45399. }
  45400. for (int i = rowComponentItems.size(); --i >= 0;)
  45401. {
  45402. Component* const comp = rowComponents.getUnchecked(i);
  45403. bool keep = false;
  45404. if (isParentOf (comp))
  45405. {
  45406. if (itemsToKeep[i])
  45407. {
  45408. const TreeViewItem* const item = rowComponentItems.getUnchecked(i);
  45409. Rectangle<int> pos (item->getItemPosition (false));
  45410. pos.setSize (pos.getWidth(), item->itemHeight);
  45411. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  45412. {
  45413. keep = true;
  45414. comp->setBounds (pos);
  45415. }
  45416. }
  45417. if ((! keep) && isMouseDraggingInChildCompOf (comp))
  45418. {
  45419. keep = true;
  45420. comp->setSize (0, 0);
  45421. }
  45422. }
  45423. if (! keep)
  45424. {
  45425. delete comp;
  45426. rowComponents.remove (i);
  45427. rowComponentIds.remove (i);
  45428. rowComponentItems.remove (i);
  45429. }
  45430. }
  45431. }
  45432. void updateButtonUnderMouse (const MouseEvent& e)
  45433. {
  45434. TreeViewItem* newItem = 0;
  45435. if (owner.openCloseButtonsVisible)
  45436. {
  45437. Rectangle<int> pos;
  45438. TreeViewItem* item = findItemAt (e.y, pos);
  45439. if (item != 0 && e.x < pos.getX() && e.x >= pos.getX() - owner.getIndentSize())
  45440. {
  45441. newItem = item;
  45442. if (! newItem->mightContainSubItems())
  45443. newItem = 0;
  45444. }
  45445. }
  45446. if (buttonUnderMouse != newItem)
  45447. {
  45448. if (buttonUnderMouse != 0 && containsItem (buttonUnderMouse))
  45449. {
  45450. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  45451. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  45452. }
  45453. buttonUnderMouse = newItem;
  45454. if (buttonUnderMouse != 0)
  45455. {
  45456. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  45457. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  45458. }
  45459. }
  45460. }
  45461. bool isMouseOverButton (TreeViewItem* const item) const throw()
  45462. {
  45463. return item == buttonUnderMouse;
  45464. }
  45465. void resized()
  45466. {
  45467. owner.itemsChanged();
  45468. }
  45469. const String getTooltip()
  45470. {
  45471. Rectangle<int> pos;
  45472. TreeViewItem* const item = findItemAt (getMouseXYRelative().getY(), pos);
  45473. if (item != 0)
  45474. return item->getTooltip();
  45475. return owner.getTooltip();
  45476. }
  45477. juce_UseDebuggingNewOperator
  45478. private:
  45479. TreeView& owner;
  45480. Array <TreeViewItem*> rowComponentItems;
  45481. Array <int> rowComponentIds;
  45482. Array <Component*> rowComponents;
  45483. TreeViewItem* buttonUnderMouse;
  45484. bool isDragging, needSelectionOnMouseUp;
  45485. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  45486. {
  45487. TreeViewItem* firstSelected = 0;
  45488. if (modifiers.isShiftDown() && ((firstSelected = owner.getSelectedItem (0)) != 0))
  45489. {
  45490. TreeViewItem* const lastSelected = owner.getSelectedItem (owner.getNumSelectedItems() - 1);
  45491. jassert (lastSelected != 0);
  45492. int rowStart = firstSelected->getRowNumberInTree();
  45493. int rowEnd = lastSelected->getRowNumberInTree();
  45494. if (rowStart > rowEnd)
  45495. swapVariables (rowStart, rowEnd);
  45496. int ourRow = item->getRowNumberInTree();
  45497. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  45498. if (ourRow > otherEnd)
  45499. swapVariables (ourRow, otherEnd);
  45500. for (int i = ourRow; i <= otherEnd; ++i)
  45501. owner.getItemOnRow (i)->setSelected (true, false);
  45502. }
  45503. else
  45504. {
  45505. const bool cmd = modifiers.isCommandDown();
  45506. item->setSelected ((! cmd) || ! item->isSelected(), ! cmd);
  45507. }
  45508. }
  45509. bool containsItem (TreeViewItem* const item) const
  45510. {
  45511. for (int i = rowComponentItems.size(); --i >= 0;)
  45512. if (rowComponentItems.getUnchecked(i) == item)
  45513. return true;
  45514. return false;
  45515. }
  45516. static bool isMouseDraggingInChildCompOf (Component* const comp)
  45517. {
  45518. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  45519. {
  45520. MouseInputSource* const source = Desktop::getInstance().getMouseSource(i);
  45521. if (source->isDragging())
  45522. {
  45523. Component* const underMouse = source->getComponentUnderMouse();
  45524. if (underMouse != 0 && (comp == underMouse || comp->isParentOf (underMouse)))
  45525. return true;
  45526. }
  45527. }
  45528. return false;
  45529. }
  45530. TreeViewContentComponent (const TreeViewContentComponent&);
  45531. TreeViewContentComponent& operator= (const TreeViewContentComponent&);
  45532. };
  45533. class TreeView::TreeViewport : public Viewport
  45534. {
  45535. public:
  45536. TreeViewport() throw() : lastX (-1) {}
  45537. ~TreeViewport() throw() {}
  45538. void updateComponents (const bool triggerResize = false)
  45539. {
  45540. TreeViewContentComponent* const tvc = static_cast <TreeViewContentComponent*> (getViewedComponent());
  45541. if (tvc != 0)
  45542. {
  45543. if (triggerResize)
  45544. tvc->resized();
  45545. else
  45546. tvc->updateComponents();
  45547. }
  45548. repaint();
  45549. }
  45550. void visibleAreaChanged (int x, int, int, int)
  45551. {
  45552. const bool hasScrolledSideways = (x != lastX);
  45553. lastX = x;
  45554. updateComponents (hasScrolledSideways);
  45555. }
  45556. juce_UseDebuggingNewOperator
  45557. private:
  45558. int lastX;
  45559. TreeViewport (const TreeViewport&);
  45560. TreeViewport& operator= (const TreeViewport&);
  45561. };
  45562. TreeView::TreeView (const String& componentName)
  45563. : Component (componentName),
  45564. rootItem (0),
  45565. indentSize (24),
  45566. defaultOpenness (false),
  45567. needsRecalculating (true),
  45568. rootItemVisible (true),
  45569. multiSelectEnabled (false),
  45570. openCloseButtonsVisible (true)
  45571. {
  45572. addAndMakeVisible (viewport = new TreeViewport());
  45573. viewport->setViewedComponent (new TreeViewContentComponent (*this));
  45574. viewport->setWantsKeyboardFocus (false);
  45575. setWantsKeyboardFocus (true);
  45576. }
  45577. TreeView::~TreeView()
  45578. {
  45579. if (rootItem != 0)
  45580. rootItem->setOwnerView (0);
  45581. }
  45582. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  45583. {
  45584. if (rootItem != newRootItem)
  45585. {
  45586. if (newRootItem != 0)
  45587. {
  45588. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  45589. if (newRootItem->ownerView != 0)
  45590. newRootItem->ownerView->setRootItem (0);
  45591. }
  45592. if (rootItem != 0)
  45593. rootItem->setOwnerView (0);
  45594. rootItem = newRootItem;
  45595. if (newRootItem != 0)
  45596. newRootItem->setOwnerView (this);
  45597. needsRecalculating = true;
  45598. handleAsyncUpdate();
  45599. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45600. {
  45601. rootItem->setOpen (false); // force a re-open
  45602. rootItem->setOpen (true);
  45603. }
  45604. }
  45605. }
  45606. void TreeView::deleteRootItem()
  45607. {
  45608. const ScopedPointer <TreeViewItem> deleter (rootItem);
  45609. setRootItem (0);
  45610. }
  45611. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  45612. {
  45613. rootItemVisible = shouldBeVisible;
  45614. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  45615. {
  45616. rootItem->setOpen (false); // force a re-open
  45617. rootItem->setOpen (true);
  45618. }
  45619. itemsChanged();
  45620. }
  45621. void TreeView::colourChanged()
  45622. {
  45623. setOpaque (findColour (backgroundColourId).isOpaque());
  45624. repaint();
  45625. }
  45626. void TreeView::setIndentSize (const int newIndentSize)
  45627. {
  45628. if (indentSize != newIndentSize)
  45629. {
  45630. indentSize = newIndentSize;
  45631. resized();
  45632. }
  45633. }
  45634. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  45635. {
  45636. if (defaultOpenness != isOpenByDefault)
  45637. {
  45638. defaultOpenness = isOpenByDefault;
  45639. itemsChanged();
  45640. }
  45641. }
  45642. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  45643. {
  45644. multiSelectEnabled = canMultiSelect;
  45645. }
  45646. void TreeView::setOpenCloseButtonsVisible (const bool shouldBeVisible)
  45647. {
  45648. if (openCloseButtonsVisible != shouldBeVisible)
  45649. {
  45650. openCloseButtonsVisible = shouldBeVisible;
  45651. itemsChanged();
  45652. }
  45653. }
  45654. Viewport* TreeView::getViewport() const throw()
  45655. {
  45656. return viewport;
  45657. }
  45658. void TreeView::clearSelectedItems()
  45659. {
  45660. if (rootItem != 0)
  45661. rootItem->deselectAllRecursively();
  45662. }
  45663. int TreeView::getNumSelectedItems() const throw()
  45664. {
  45665. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively() : 0;
  45666. }
  45667. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  45668. {
  45669. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  45670. }
  45671. int TreeView::getNumRowsInTree() const
  45672. {
  45673. if (rootItem != 0)
  45674. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  45675. return 0;
  45676. }
  45677. TreeViewItem* TreeView::getItemOnRow (int index) const
  45678. {
  45679. if (! rootItemVisible)
  45680. ++index;
  45681. if (rootItem != 0 && index >= 0)
  45682. return rootItem->getItemOnRow (index);
  45683. return 0;
  45684. }
  45685. TreeViewItem* TreeView::getItemAt (int y) const throw()
  45686. {
  45687. TreeViewContentComponent* const tc = static_cast <TreeViewContentComponent*> (viewport->getViewedComponent());
  45688. Rectangle<int> pos;
  45689. return tc->findItemAt (relativePositionToOtherComponent (tc, Point<int> (0, y)).getY(), pos);
  45690. }
  45691. TreeViewItem* TreeView::findItemFromIdentifierString (const String& identifierString) const
  45692. {
  45693. if (rootItem == 0)
  45694. return 0;
  45695. return rootItem->findItemFromIdentifierString (identifierString);
  45696. }
  45697. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  45698. {
  45699. XmlElement* e = 0;
  45700. if (rootItem != 0)
  45701. {
  45702. e = rootItem->getOpennessState();
  45703. if (e != 0 && alsoIncludeScrollPosition)
  45704. e->setAttribute ("scrollPos", viewport->getViewPositionY());
  45705. }
  45706. return e;
  45707. }
  45708. void TreeView::restoreOpennessState (const XmlElement& newState)
  45709. {
  45710. if (rootItem != 0)
  45711. {
  45712. rootItem->restoreOpennessState (newState);
  45713. if (newState.hasAttribute ("scrollPos"))
  45714. viewport->setViewPosition (viewport->getViewPositionX(),
  45715. newState.getIntAttribute ("scrollPos"));
  45716. }
  45717. }
  45718. void TreeView::paint (Graphics& g)
  45719. {
  45720. g.fillAll (findColour (backgroundColourId));
  45721. }
  45722. void TreeView::resized()
  45723. {
  45724. viewport->setBounds (getLocalBounds());
  45725. itemsChanged();
  45726. handleAsyncUpdate();
  45727. }
  45728. void TreeView::enablementChanged()
  45729. {
  45730. repaint();
  45731. }
  45732. void TreeView::moveSelectedRow (int delta)
  45733. {
  45734. if (delta == 0)
  45735. return;
  45736. int rowSelected = 0;
  45737. TreeViewItem* const firstSelected = getSelectedItem (0);
  45738. if (firstSelected != 0)
  45739. rowSelected = firstSelected->getRowNumberInTree();
  45740. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  45741. for (;;)
  45742. {
  45743. TreeViewItem* item = getItemOnRow (rowSelected);
  45744. if (item != 0)
  45745. {
  45746. if (! item->canBeSelected())
  45747. {
  45748. // if the row we want to highlight doesn't allow it, try skipping
  45749. // to the next item..
  45750. const int nextRowToTry = jlimit (0, getNumRowsInTree() - 1,
  45751. rowSelected + (delta < 0 ? -1 : 1));
  45752. if (rowSelected != nextRowToTry)
  45753. {
  45754. rowSelected = nextRowToTry;
  45755. continue;
  45756. }
  45757. else
  45758. {
  45759. break;
  45760. }
  45761. }
  45762. item->setSelected (true, true);
  45763. scrollToKeepItemVisible (item);
  45764. }
  45765. break;
  45766. }
  45767. }
  45768. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  45769. {
  45770. if (item != 0 && item->ownerView == this)
  45771. {
  45772. handleAsyncUpdate();
  45773. item = item->getDeepestOpenParentItem();
  45774. int y = item->y;
  45775. int viewTop = viewport->getViewPositionY();
  45776. if (y < viewTop)
  45777. {
  45778. viewport->setViewPosition (viewport->getViewPositionX(), y);
  45779. }
  45780. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  45781. {
  45782. viewport->setViewPosition (viewport->getViewPositionX(),
  45783. (y + item->itemHeight) - viewport->getViewHeight());
  45784. }
  45785. }
  45786. }
  45787. bool TreeView::keyPressed (const KeyPress& key)
  45788. {
  45789. if (key.isKeyCode (KeyPress::upKey))
  45790. {
  45791. moveSelectedRow (-1);
  45792. }
  45793. else if (key.isKeyCode (KeyPress::downKey))
  45794. {
  45795. moveSelectedRow (1);
  45796. }
  45797. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  45798. {
  45799. if (rootItem != 0)
  45800. {
  45801. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  45802. if (key.isKeyCode (KeyPress::pageUpKey))
  45803. rowsOnScreen = -rowsOnScreen;
  45804. moveSelectedRow (rowsOnScreen);
  45805. }
  45806. }
  45807. else if (key.isKeyCode (KeyPress::homeKey))
  45808. {
  45809. moveSelectedRow (-0x3fffffff);
  45810. }
  45811. else if (key.isKeyCode (KeyPress::endKey))
  45812. {
  45813. moveSelectedRow (0x3fffffff);
  45814. }
  45815. else if (key.isKeyCode (KeyPress::returnKey))
  45816. {
  45817. TreeViewItem* const firstSelected = getSelectedItem (0);
  45818. if (firstSelected != 0)
  45819. firstSelected->setOpen (! firstSelected->isOpen());
  45820. }
  45821. else if (key.isKeyCode (KeyPress::leftKey))
  45822. {
  45823. TreeViewItem* const firstSelected = getSelectedItem (0);
  45824. if (firstSelected != 0)
  45825. {
  45826. if (firstSelected->isOpen())
  45827. {
  45828. firstSelected->setOpen (false);
  45829. }
  45830. else
  45831. {
  45832. TreeViewItem* parent = firstSelected->parentItem;
  45833. if ((! rootItemVisible) && parent == rootItem)
  45834. parent = 0;
  45835. if (parent != 0)
  45836. {
  45837. parent->setSelected (true, true);
  45838. scrollToKeepItemVisible (parent);
  45839. }
  45840. }
  45841. }
  45842. }
  45843. else if (key.isKeyCode (KeyPress::rightKey))
  45844. {
  45845. TreeViewItem* const firstSelected = getSelectedItem (0);
  45846. if (firstSelected != 0)
  45847. {
  45848. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  45849. moveSelectedRow (1);
  45850. else
  45851. firstSelected->setOpen (true);
  45852. }
  45853. }
  45854. else
  45855. {
  45856. return false;
  45857. }
  45858. return true;
  45859. }
  45860. void TreeView::itemsChanged() throw()
  45861. {
  45862. needsRecalculating = true;
  45863. repaint();
  45864. triggerAsyncUpdate();
  45865. }
  45866. void TreeView::handleAsyncUpdate()
  45867. {
  45868. if (needsRecalculating)
  45869. {
  45870. needsRecalculating = false;
  45871. const ScopedLock sl (nodeAlterationLock);
  45872. if (rootItem != 0)
  45873. rootItem->updatePositions (rootItemVisible ? 0 : -rootItem->itemHeight);
  45874. viewport->updateComponents();
  45875. if (rootItem != 0)
  45876. {
  45877. viewport->getViewedComponent()
  45878. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  45879. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  45880. }
  45881. else
  45882. {
  45883. viewport->getViewedComponent()->setSize (0, 0);
  45884. }
  45885. }
  45886. }
  45887. class TreeView::InsertPointHighlight : public Component
  45888. {
  45889. public:
  45890. InsertPointHighlight()
  45891. : lastItem (0)
  45892. {
  45893. setSize (100, 12);
  45894. setAlwaysOnTop (true);
  45895. setInterceptsMouseClicks (false, false);
  45896. }
  45897. ~InsertPointHighlight() {}
  45898. void setTargetPosition (TreeViewItem* const item, int insertIndex, const int x, const int y, const int width) throw()
  45899. {
  45900. lastItem = item;
  45901. lastIndex = insertIndex;
  45902. const int offset = getHeight() / 2;
  45903. setBounds (x - offset, y - offset, width - (x - offset), getHeight());
  45904. }
  45905. void paint (Graphics& g)
  45906. {
  45907. Path p;
  45908. const float h = (float) getHeight();
  45909. p.addEllipse (2.0f, 2.0f, h - 4.0f, h - 4.0f);
  45910. p.startNewSubPath (h - 2.0f, h / 2.0f);
  45911. p.lineTo ((float) getWidth(), h / 2.0f);
  45912. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45913. g.strokePath (p, PathStrokeType (2.0f));
  45914. }
  45915. TreeViewItem* lastItem;
  45916. int lastIndex;
  45917. private:
  45918. InsertPointHighlight (const InsertPointHighlight&);
  45919. InsertPointHighlight& operator= (const InsertPointHighlight&);
  45920. };
  45921. class TreeView::TargetGroupHighlight : public Component
  45922. {
  45923. public:
  45924. TargetGroupHighlight()
  45925. {
  45926. setAlwaysOnTop (true);
  45927. setInterceptsMouseClicks (false, false);
  45928. }
  45929. ~TargetGroupHighlight() {}
  45930. void setTargetPosition (TreeViewItem* const item) throw()
  45931. {
  45932. Rectangle<int> r (item->getItemPosition (true));
  45933. r.setHeight (item->getItemHeight());
  45934. setBounds (r);
  45935. }
  45936. void paint (Graphics& g)
  45937. {
  45938. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45939. g.drawRoundedRectangle (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 3.0f, 2.0f);
  45940. }
  45941. private:
  45942. TargetGroupHighlight (const TargetGroupHighlight&);
  45943. TargetGroupHighlight& operator= (const TargetGroupHighlight&);
  45944. };
  45945. void TreeView::showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw()
  45946. {
  45947. beginDragAutoRepeat (100);
  45948. if (dragInsertPointHighlight == 0)
  45949. {
  45950. addAndMakeVisible (dragInsertPointHighlight = new InsertPointHighlight());
  45951. addAndMakeVisible (dragTargetGroupHighlight = new TargetGroupHighlight());
  45952. }
  45953. dragInsertPointHighlight->setTargetPosition (item, insertIndex, x, y, viewport->getViewWidth());
  45954. dragTargetGroupHighlight->setTargetPosition (item);
  45955. }
  45956. void TreeView::hideDragHighlight() throw()
  45957. {
  45958. dragInsertPointHighlight = 0;
  45959. dragTargetGroupHighlight = 0;
  45960. }
  45961. TreeViewItem* TreeView::getInsertPosition (int& x, int& y, int& insertIndex,
  45962. const StringArray& files, const String& sourceDescription,
  45963. Component* sourceComponent) const throw()
  45964. {
  45965. insertIndex = 0;
  45966. TreeViewItem* item = getItemAt (y);
  45967. if (item == 0)
  45968. return 0;
  45969. Rectangle<int> itemPos (item->getItemPosition (true));
  45970. insertIndex = item->getIndexInParent();
  45971. const int oldY = y;
  45972. y = itemPos.getY();
  45973. if (item->getNumSubItems() == 0 || ! item->isOpen())
  45974. {
  45975. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  45976. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  45977. {
  45978. // Check if we're trying to drag into an empty group item..
  45979. if (oldY > itemPos.getY() + itemPos.getHeight() / 4
  45980. && oldY < itemPos.getBottom() - itemPos.getHeight() / 4)
  45981. {
  45982. insertIndex = 0;
  45983. x = itemPos.getX() + getIndentSize();
  45984. y = itemPos.getBottom();
  45985. return item;
  45986. }
  45987. }
  45988. }
  45989. if (oldY > itemPos.getCentreY())
  45990. {
  45991. y += item->getItemHeight();
  45992. while (item->isLastOfSiblings() && item->parentItem != 0
  45993. && item->parentItem->parentItem != 0)
  45994. {
  45995. if (x > itemPos.getX())
  45996. break;
  45997. item = item->parentItem;
  45998. itemPos = item->getItemPosition (true);
  45999. insertIndex = item->getIndexInParent();
  46000. }
  46001. ++insertIndex;
  46002. }
  46003. x = itemPos.getX();
  46004. return item->parentItem;
  46005. }
  46006. void TreeView::handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  46007. {
  46008. const bool scrolled = viewport->autoScroll (x, y, 20, 10);
  46009. int insertIndex;
  46010. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  46011. if (item != 0)
  46012. {
  46013. if (scrolled || dragInsertPointHighlight == 0
  46014. || dragInsertPointHighlight->lastItem != item
  46015. || dragInsertPointHighlight->lastIndex != insertIndex)
  46016. {
  46017. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  46018. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  46019. showDragHighlight (item, insertIndex, x, y);
  46020. else
  46021. hideDragHighlight();
  46022. }
  46023. }
  46024. else
  46025. {
  46026. hideDragHighlight();
  46027. }
  46028. }
  46029. void TreeView::handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  46030. {
  46031. hideDragHighlight();
  46032. int insertIndex;
  46033. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  46034. if (item != 0)
  46035. {
  46036. if (files.size() > 0)
  46037. {
  46038. if (item->isInterestedInFileDrag (files))
  46039. item->filesDropped (files, insertIndex);
  46040. }
  46041. else
  46042. {
  46043. if (item->isInterestedInDragSource (sourceDescription, sourceComponent))
  46044. item->itemDropped (sourceDescription, sourceComponent, insertIndex);
  46045. }
  46046. }
  46047. }
  46048. bool TreeView::isInterestedInFileDrag (const StringArray&)
  46049. {
  46050. return true;
  46051. }
  46052. void TreeView::fileDragEnter (const StringArray& files, int x, int y)
  46053. {
  46054. fileDragMove (files, x, y);
  46055. }
  46056. void TreeView::fileDragMove (const StringArray& files, int x, int y)
  46057. {
  46058. handleDrag (files, String::empty, 0, x, y);
  46059. }
  46060. void TreeView::fileDragExit (const StringArray&)
  46061. {
  46062. hideDragHighlight();
  46063. }
  46064. void TreeView::filesDropped (const StringArray& files, int x, int y)
  46065. {
  46066. handleDrop (files, String::empty, 0, x, y);
  46067. }
  46068. bool TreeView::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  46069. {
  46070. return true;
  46071. }
  46072. void TreeView::itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y)
  46073. {
  46074. itemDragMove (sourceDescription, sourceComponent, x, y);
  46075. }
  46076. void TreeView::itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y)
  46077. {
  46078. handleDrag (StringArray(), sourceDescription, sourceComponent, x, y);
  46079. }
  46080. void TreeView::itemDragExit (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  46081. {
  46082. hideDragHighlight();
  46083. }
  46084. void TreeView::itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y)
  46085. {
  46086. handleDrop (StringArray(), sourceDescription, sourceComponent, x, y);
  46087. }
  46088. enum TreeViewOpenness
  46089. {
  46090. opennessDefault = 0,
  46091. opennessClosed = 1,
  46092. opennessOpen = 2
  46093. };
  46094. TreeViewItem::TreeViewItem()
  46095. : ownerView (0),
  46096. parentItem (0),
  46097. y (0),
  46098. itemHeight (0),
  46099. totalHeight (0),
  46100. selected (false),
  46101. redrawNeeded (true),
  46102. drawLinesInside (true),
  46103. drawsInLeftMargin (false),
  46104. openness (opennessDefault)
  46105. {
  46106. static int nextUID = 0;
  46107. uid = nextUID++;
  46108. }
  46109. TreeViewItem::~TreeViewItem()
  46110. {
  46111. }
  46112. const String TreeViewItem::getUniqueName() const
  46113. {
  46114. return String::empty;
  46115. }
  46116. void TreeViewItem::itemOpennessChanged (bool)
  46117. {
  46118. }
  46119. int TreeViewItem::getNumSubItems() const throw()
  46120. {
  46121. return subItems.size();
  46122. }
  46123. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  46124. {
  46125. return subItems [index];
  46126. }
  46127. void TreeViewItem::clearSubItems()
  46128. {
  46129. if (subItems.size() > 0)
  46130. {
  46131. if (ownerView != 0)
  46132. {
  46133. const ScopedLock sl (ownerView->nodeAlterationLock);
  46134. subItems.clear();
  46135. treeHasChanged();
  46136. }
  46137. else
  46138. {
  46139. subItems.clear();
  46140. }
  46141. }
  46142. }
  46143. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  46144. {
  46145. if (newItem != 0)
  46146. {
  46147. newItem->parentItem = this;
  46148. newItem->setOwnerView (ownerView);
  46149. newItem->y = 0;
  46150. newItem->itemHeight = newItem->getItemHeight();
  46151. newItem->totalHeight = 0;
  46152. newItem->itemWidth = newItem->getItemWidth();
  46153. newItem->totalWidth = 0;
  46154. if (ownerView != 0)
  46155. {
  46156. const ScopedLock sl (ownerView->nodeAlterationLock);
  46157. subItems.insert (insertPosition, newItem);
  46158. treeHasChanged();
  46159. if (newItem->isOpen())
  46160. newItem->itemOpennessChanged (true);
  46161. }
  46162. else
  46163. {
  46164. subItems.insert (insertPosition, newItem);
  46165. if (newItem->isOpen())
  46166. newItem->itemOpennessChanged (true);
  46167. }
  46168. }
  46169. }
  46170. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  46171. {
  46172. if (ownerView != 0)
  46173. {
  46174. const ScopedLock sl (ownerView->nodeAlterationLock);
  46175. if (((unsigned int) index) < (unsigned int) subItems.size())
  46176. {
  46177. subItems.remove (index, deleteItem);
  46178. treeHasChanged();
  46179. }
  46180. }
  46181. else
  46182. {
  46183. subItems.remove (index, deleteItem);
  46184. }
  46185. }
  46186. bool TreeViewItem::isOpen() const throw()
  46187. {
  46188. if (openness == opennessDefault)
  46189. return ownerView != 0 && ownerView->defaultOpenness;
  46190. else
  46191. return openness == opennessOpen;
  46192. }
  46193. void TreeViewItem::setOpen (const bool shouldBeOpen)
  46194. {
  46195. if (isOpen() != shouldBeOpen)
  46196. {
  46197. openness = shouldBeOpen ? opennessOpen
  46198. : opennessClosed;
  46199. treeHasChanged();
  46200. itemOpennessChanged (isOpen());
  46201. }
  46202. }
  46203. bool TreeViewItem::isSelected() const throw()
  46204. {
  46205. return selected;
  46206. }
  46207. void TreeViewItem::deselectAllRecursively()
  46208. {
  46209. setSelected (false, false);
  46210. for (int i = 0; i < subItems.size(); ++i)
  46211. subItems.getUnchecked(i)->deselectAllRecursively();
  46212. }
  46213. void TreeViewItem::setSelected (const bool shouldBeSelected,
  46214. const bool deselectOtherItemsFirst)
  46215. {
  46216. if (shouldBeSelected && ! canBeSelected())
  46217. return;
  46218. if (deselectOtherItemsFirst)
  46219. getTopLevelItem()->deselectAllRecursively();
  46220. if (shouldBeSelected != selected)
  46221. {
  46222. selected = shouldBeSelected;
  46223. if (ownerView != 0)
  46224. ownerView->repaint();
  46225. itemSelectionChanged (shouldBeSelected);
  46226. }
  46227. }
  46228. void TreeViewItem::paintItem (Graphics&, int, int)
  46229. {
  46230. }
  46231. void TreeViewItem::paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver)
  46232. {
  46233. ownerView->getLookAndFeel()
  46234. .drawTreeviewPlusMinusBox (g, 0, 0, width, height, ! isOpen(), isMouseOver);
  46235. }
  46236. void TreeViewItem::itemClicked (const MouseEvent&)
  46237. {
  46238. }
  46239. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  46240. {
  46241. if (mightContainSubItems())
  46242. setOpen (! isOpen());
  46243. }
  46244. void TreeViewItem::itemSelectionChanged (bool)
  46245. {
  46246. }
  46247. const String TreeViewItem::getTooltip()
  46248. {
  46249. return String::empty;
  46250. }
  46251. const String TreeViewItem::getDragSourceDescription()
  46252. {
  46253. return String::empty;
  46254. }
  46255. bool TreeViewItem::isInterestedInFileDrag (const StringArray&)
  46256. {
  46257. return false;
  46258. }
  46259. void TreeViewItem::filesDropped (const StringArray& /*files*/, int /*insertIndex*/)
  46260. {
  46261. }
  46262. bool TreeViewItem::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  46263. {
  46264. return false;
  46265. }
  46266. void TreeViewItem::itemDropped (const String& /*sourceDescription*/, Component* /*sourceComponent*/, int /*insertIndex*/)
  46267. {
  46268. }
  46269. const Rectangle<int> TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  46270. {
  46271. const int indentX = getIndentX();
  46272. int width = itemWidth;
  46273. if (ownerView != 0 && width < 0)
  46274. width = ownerView->viewport->getViewWidth() - indentX;
  46275. Rectangle<int> r (indentX, y, jmax (0, width), totalHeight);
  46276. if (relativeToTreeViewTopLeft)
  46277. r -= ownerView->viewport->getViewPosition();
  46278. return r;
  46279. }
  46280. void TreeViewItem::treeHasChanged() const throw()
  46281. {
  46282. if (ownerView != 0)
  46283. ownerView->itemsChanged();
  46284. }
  46285. void TreeViewItem::repaintItem() const
  46286. {
  46287. if (ownerView != 0 && areAllParentsOpen())
  46288. {
  46289. Rectangle<int> r (getItemPosition (true));
  46290. r.setLeft (0);
  46291. ownerView->viewport->repaint (r);
  46292. }
  46293. }
  46294. bool TreeViewItem::areAllParentsOpen() const throw()
  46295. {
  46296. return parentItem == 0
  46297. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  46298. }
  46299. void TreeViewItem::updatePositions (int newY)
  46300. {
  46301. y = newY;
  46302. itemHeight = getItemHeight();
  46303. totalHeight = itemHeight;
  46304. itemWidth = getItemWidth();
  46305. totalWidth = jmax (itemWidth, 0) + getIndentX();
  46306. if (isOpen())
  46307. {
  46308. newY += totalHeight;
  46309. for (int i = 0; i < subItems.size(); ++i)
  46310. {
  46311. TreeViewItem* const ti = subItems.getUnchecked(i);
  46312. ti->updatePositions (newY);
  46313. newY += ti->totalHeight;
  46314. totalHeight += ti->totalHeight;
  46315. totalWidth = jmax (totalWidth, ti->totalWidth);
  46316. }
  46317. }
  46318. }
  46319. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  46320. {
  46321. TreeViewItem* result = this;
  46322. TreeViewItem* item = this;
  46323. while (item->parentItem != 0)
  46324. {
  46325. item = item->parentItem;
  46326. if (! item->isOpen())
  46327. result = item;
  46328. }
  46329. return result;
  46330. }
  46331. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  46332. {
  46333. ownerView = newOwner;
  46334. for (int i = subItems.size(); --i >= 0;)
  46335. subItems.getUnchecked(i)->setOwnerView (newOwner);
  46336. }
  46337. int TreeViewItem::getIndentX() const throw()
  46338. {
  46339. const int indentWidth = ownerView->getIndentSize();
  46340. int x = ownerView->rootItemVisible ? indentWidth : 0;
  46341. if (! ownerView->openCloseButtonsVisible)
  46342. x -= indentWidth;
  46343. TreeViewItem* p = parentItem;
  46344. while (p != 0)
  46345. {
  46346. x += indentWidth;
  46347. p = p->parentItem;
  46348. }
  46349. return x;
  46350. }
  46351. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) throw()
  46352. {
  46353. drawsInLeftMargin = canDrawInLeftMargin;
  46354. }
  46355. void TreeViewItem::paintRecursively (Graphics& g, int width)
  46356. {
  46357. jassert (ownerView != 0);
  46358. if (ownerView == 0)
  46359. return;
  46360. const int indent = getIndentX();
  46361. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  46362. {
  46363. g.saveState();
  46364. g.setOrigin (indent, 0);
  46365. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  46366. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  46367. paintItem (g, itemW, itemHeight);
  46368. g.restoreState();
  46369. }
  46370. g.setColour (ownerView->findColour (TreeView::linesColourId));
  46371. const float halfH = itemHeight * 0.5f;
  46372. int depth = 0;
  46373. TreeViewItem* p = parentItem;
  46374. while (p != 0)
  46375. {
  46376. ++depth;
  46377. p = p->parentItem;
  46378. }
  46379. if (! ownerView->rootItemVisible)
  46380. --depth;
  46381. const int indentWidth = ownerView->getIndentSize();
  46382. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  46383. {
  46384. float x = (depth + 0.5f) * indentWidth;
  46385. if (depth >= 0)
  46386. {
  46387. if (parentItem != 0 && parentItem->drawLinesInside)
  46388. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  46389. if ((parentItem != 0 && parentItem->drawLinesInside)
  46390. || (parentItem == 0 && drawLinesInside))
  46391. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  46392. }
  46393. p = parentItem;
  46394. int d = depth;
  46395. while (p != 0 && --d >= 0)
  46396. {
  46397. x -= (float) indentWidth;
  46398. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  46399. && ! p->isLastOfSiblings())
  46400. {
  46401. g.drawLine (x, 0, x, (float) itemHeight);
  46402. }
  46403. p = p->parentItem;
  46404. }
  46405. if (mightContainSubItems())
  46406. {
  46407. g.saveState();
  46408. g.setOrigin (depth * indentWidth, 0);
  46409. g.reduceClipRegion (0, 0, indentWidth, itemHeight);
  46410. paintOpenCloseButton (g, indentWidth, itemHeight,
  46411. static_cast <TreeViewContentComponent*> (ownerView->viewport->getViewedComponent())
  46412. ->isMouseOverButton (this));
  46413. g.restoreState();
  46414. }
  46415. }
  46416. if (isOpen())
  46417. {
  46418. const Rectangle<int> clip (g.getClipBounds());
  46419. for (int i = 0; i < subItems.size(); ++i)
  46420. {
  46421. TreeViewItem* const ti = subItems.getUnchecked(i);
  46422. const int relY = ti->y - y;
  46423. if (relY >= clip.getBottom())
  46424. break;
  46425. if (relY + ti->totalHeight >= clip.getY())
  46426. {
  46427. g.saveState();
  46428. g.setOrigin (0, relY);
  46429. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  46430. ti->paintRecursively (g, width);
  46431. g.restoreState();
  46432. }
  46433. }
  46434. }
  46435. }
  46436. bool TreeViewItem::isLastOfSiblings() const throw()
  46437. {
  46438. return parentItem == 0
  46439. || parentItem->subItems.getLast() == this;
  46440. }
  46441. int TreeViewItem::getIndexInParent() const throw()
  46442. {
  46443. if (parentItem == 0)
  46444. return 0;
  46445. return parentItem->subItems.indexOf (this);
  46446. }
  46447. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  46448. {
  46449. return (parentItem == 0) ? this
  46450. : parentItem->getTopLevelItem();
  46451. }
  46452. int TreeViewItem::getNumRows() const throw()
  46453. {
  46454. int num = 1;
  46455. if (isOpen())
  46456. {
  46457. for (int i = subItems.size(); --i >= 0;)
  46458. num += subItems.getUnchecked(i)->getNumRows();
  46459. }
  46460. return num;
  46461. }
  46462. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  46463. {
  46464. if (index == 0)
  46465. return this;
  46466. if (index > 0 && isOpen())
  46467. {
  46468. --index;
  46469. for (int i = 0; i < subItems.size(); ++i)
  46470. {
  46471. TreeViewItem* const item = subItems.getUnchecked(i);
  46472. if (index == 0)
  46473. return item;
  46474. const int numRows = item->getNumRows();
  46475. if (numRows > index)
  46476. return item->getItemOnRow (index);
  46477. index -= numRows;
  46478. }
  46479. }
  46480. return 0;
  46481. }
  46482. TreeViewItem* TreeViewItem::findItemRecursively (int targetY) throw()
  46483. {
  46484. if (((unsigned int) targetY) < (unsigned int) totalHeight)
  46485. {
  46486. const int h = itemHeight;
  46487. if (targetY < h)
  46488. return this;
  46489. if (isOpen())
  46490. {
  46491. targetY -= h;
  46492. for (int i = 0; i < subItems.size(); ++i)
  46493. {
  46494. TreeViewItem* const ti = subItems.getUnchecked(i);
  46495. if (targetY < ti->totalHeight)
  46496. return ti->findItemRecursively (targetY);
  46497. targetY -= ti->totalHeight;
  46498. }
  46499. }
  46500. }
  46501. return 0;
  46502. }
  46503. int TreeViewItem::countSelectedItemsRecursively() const throw()
  46504. {
  46505. int total = 0;
  46506. if (isSelected())
  46507. ++total;
  46508. for (int i = subItems.size(); --i >= 0;)
  46509. total += subItems.getUnchecked(i)->countSelectedItemsRecursively();
  46510. return total;
  46511. }
  46512. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  46513. {
  46514. if (isSelected())
  46515. {
  46516. if (index == 0)
  46517. return this;
  46518. --index;
  46519. }
  46520. if (index >= 0)
  46521. {
  46522. for (int i = 0; i < subItems.size(); ++i)
  46523. {
  46524. TreeViewItem* const item = subItems.getUnchecked(i);
  46525. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  46526. if (found != 0)
  46527. return found;
  46528. index -= item->countSelectedItemsRecursively();
  46529. }
  46530. }
  46531. return 0;
  46532. }
  46533. int TreeViewItem::getRowNumberInTree() const throw()
  46534. {
  46535. if (parentItem != 0 && ownerView != 0)
  46536. {
  46537. int n = 1 + parentItem->getRowNumberInTree();
  46538. int ourIndex = parentItem->subItems.indexOf (this);
  46539. jassert (ourIndex >= 0);
  46540. while (--ourIndex >= 0)
  46541. n += parentItem->subItems [ourIndex]->getNumRows();
  46542. if (parentItem->parentItem == 0
  46543. && ! ownerView->rootItemVisible)
  46544. --n;
  46545. return n;
  46546. }
  46547. else
  46548. {
  46549. return 0;
  46550. }
  46551. }
  46552. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  46553. {
  46554. drawLinesInside = drawLines;
  46555. }
  46556. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  46557. {
  46558. if (recurse && isOpen() && subItems.size() > 0)
  46559. return subItems [0];
  46560. if (parentItem != 0)
  46561. {
  46562. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  46563. if (nextIndex >= parentItem->subItems.size())
  46564. return parentItem->getNextVisibleItem (false);
  46565. return parentItem->subItems [nextIndex];
  46566. }
  46567. return 0;
  46568. }
  46569. const String TreeViewItem::getItemIdentifierString() const
  46570. {
  46571. String s;
  46572. if (parentItem != 0)
  46573. s = parentItem->getItemIdentifierString();
  46574. return s + "/" + getUniqueName().replaceCharacter ('/', '\\');
  46575. }
  46576. TreeViewItem* TreeViewItem::findItemFromIdentifierString (const String& identifierString)
  46577. {
  46578. const String thisId (getUniqueName());
  46579. if (thisId == identifierString)
  46580. return this;
  46581. if (identifierString.startsWith (thisId + "/"))
  46582. {
  46583. const String remainingPath (identifierString.substring (thisId.length() + 1));
  46584. bool wasOpen = isOpen();
  46585. setOpen (true);
  46586. for (int i = subItems.size(); --i >= 0;)
  46587. {
  46588. TreeViewItem* item = subItems.getUnchecked(i)->findItemFromIdentifierString (remainingPath);
  46589. if (item != 0)
  46590. return item;
  46591. }
  46592. setOpen (wasOpen);
  46593. }
  46594. return 0;
  46595. }
  46596. void TreeViewItem::restoreOpennessState (const XmlElement& e) throw()
  46597. {
  46598. if (e.hasTagName ("CLOSED"))
  46599. {
  46600. setOpen (false);
  46601. }
  46602. else if (e.hasTagName ("OPEN"))
  46603. {
  46604. setOpen (true);
  46605. forEachXmlChildElement (e, n)
  46606. {
  46607. const String id (n->getStringAttribute ("id"));
  46608. for (int i = 0; i < subItems.size(); ++i)
  46609. {
  46610. TreeViewItem* const ti = subItems.getUnchecked(i);
  46611. if (ti->getUniqueName() == id)
  46612. {
  46613. ti->restoreOpennessState (*n);
  46614. break;
  46615. }
  46616. }
  46617. }
  46618. }
  46619. }
  46620. XmlElement* TreeViewItem::getOpennessState() const throw()
  46621. {
  46622. const String name (getUniqueName());
  46623. if (name.isNotEmpty())
  46624. {
  46625. XmlElement* e;
  46626. if (isOpen())
  46627. {
  46628. e = new XmlElement ("OPEN");
  46629. for (int i = 0; i < subItems.size(); ++i)
  46630. e->addChildElement (subItems.getUnchecked(i)->getOpennessState());
  46631. }
  46632. else
  46633. {
  46634. e = new XmlElement ("CLOSED");
  46635. }
  46636. e->setAttribute ("id", name);
  46637. return e;
  46638. }
  46639. else
  46640. {
  46641. // trying to save the openness for an element that has no name - this won't
  46642. // work because it needs the names to identify what to open.
  46643. jassertfalse;
  46644. }
  46645. return 0;
  46646. }
  46647. END_JUCE_NAMESPACE
  46648. /*** End of inlined file: juce_TreeView.cpp ***/
  46649. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46650. BEGIN_JUCE_NAMESPACE
  46651. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  46652. : fileList (listToShow)
  46653. {
  46654. }
  46655. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  46656. {
  46657. }
  46658. FileBrowserListener::~FileBrowserListener()
  46659. {
  46660. }
  46661. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener)
  46662. {
  46663. listeners.add (listener);
  46664. }
  46665. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener)
  46666. {
  46667. listeners.remove (listener);
  46668. }
  46669. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  46670. {
  46671. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46672. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46673. }
  46674. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  46675. {
  46676. if (fileList.getDirectory().exists())
  46677. {
  46678. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46679. listeners.callChecked (checker, &FileBrowserListener::fileClicked, file, e);
  46680. }
  46681. }
  46682. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  46683. {
  46684. if (fileList.getDirectory().exists())
  46685. {
  46686. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46687. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, file);
  46688. }
  46689. }
  46690. END_JUCE_NAMESPACE
  46691. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46692. /*** Start of inlined file: juce_DirectoryContentsList.cpp ***/
  46693. BEGIN_JUCE_NAMESPACE
  46694. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  46695. TimeSliceThread& thread_)
  46696. : fileFilter (fileFilter_),
  46697. thread (thread_),
  46698. fileTypeFlags (File::ignoreHiddenFiles | File::findFiles),
  46699. fileFindHandle (0),
  46700. shouldStop (true)
  46701. {
  46702. }
  46703. DirectoryContentsList::~DirectoryContentsList()
  46704. {
  46705. clear();
  46706. }
  46707. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  46708. {
  46709. setTypeFlags (shouldIgnoreHiddenFiles ? (fileTypeFlags | File::ignoreHiddenFiles)
  46710. : (fileTypeFlags & ~File::ignoreHiddenFiles));
  46711. }
  46712. bool DirectoryContentsList::ignoresHiddenFiles() const
  46713. {
  46714. return (fileTypeFlags & File::ignoreHiddenFiles) != 0;
  46715. }
  46716. const File& DirectoryContentsList::getDirectory() const
  46717. {
  46718. return root;
  46719. }
  46720. void DirectoryContentsList::setDirectory (const File& directory,
  46721. const bool includeDirectories,
  46722. const bool includeFiles)
  46723. {
  46724. jassert (includeDirectories || includeFiles); // you have to speciify at least one of these!
  46725. if (directory != root)
  46726. {
  46727. clear();
  46728. root = directory;
  46729. // (this forces a refresh when setTypeFlags() is called, rather than triggering two refreshes)
  46730. fileTypeFlags &= ~(File::findDirectories | File::findFiles);
  46731. }
  46732. int newFlags = fileTypeFlags;
  46733. if (includeDirectories) newFlags |= File::findDirectories; else newFlags &= ~File::findDirectories;
  46734. if (includeFiles) newFlags |= File::findFiles; else newFlags &= ~File::findFiles;
  46735. setTypeFlags (newFlags);
  46736. }
  46737. void DirectoryContentsList::setTypeFlags (const int newFlags)
  46738. {
  46739. if (fileTypeFlags != newFlags)
  46740. {
  46741. fileTypeFlags = newFlags;
  46742. refresh();
  46743. }
  46744. }
  46745. void DirectoryContentsList::clear()
  46746. {
  46747. shouldStop = true;
  46748. thread.removeTimeSliceClient (this);
  46749. fileFindHandle = 0;
  46750. if (files.size() > 0)
  46751. {
  46752. files.clear();
  46753. changed();
  46754. }
  46755. }
  46756. void DirectoryContentsList::refresh()
  46757. {
  46758. clear();
  46759. if (root.isDirectory())
  46760. {
  46761. fileFindHandle = new DirectoryIterator (root, false, "*", fileTypeFlags);
  46762. shouldStop = false;
  46763. thread.addTimeSliceClient (this);
  46764. }
  46765. }
  46766. int DirectoryContentsList::getNumFiles() const
  46767. {
  46768. return files.size();
  46769. }
  46770. bool DirectoryContentsList::getFileInfo (const int index,
  46771. FileInfo& result) const
  46772. {
  46773. const ScopedLock sl (fileListLock);
  46774. const FileInfo* const info = files [index];
  46775. if (info != 0)
  46776. {
  46777. result = *info;
  46778. return true;
  46779. }
  46780. return false;
  46781. }
  46782. const File DirectoryContentsList::getFile (const int index) const
  46783. {
  46784. const ScopedLock sl (fileListLock);
  46785. const FileInfo* const info = files [index];
  46786. if (info != 0)
  46787. return root.getChildFile (info->filename);
  46788. return File::nonexistent;
  46789. }
  46790. bool DirectoryContentsList::isStillLoading() const
  46791. {
  46792. return fileFindHandle != 0;
  46793. }
  46794. void DirectoryContentsList::changed()
  46795. {
  46796. sendChangeMessage (this);
  46797. }
  46798. bool DirectoryContentsList::useTimeSlice()
  46799. {
  46800. const uint32 startTime = Time::getApproximateMillisecondCounter();
  46801. bool hasChanged = false;
  46802. for (int i = 100; --i >= 0;)
  46803. {
  46804. if (! checkNextFile (hasChanged))
  46805. {
  46806. if (hasChanged)
  46807. changed();
  46808. return false;
  46809. }
  46810. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  46811. break;
  46812. }
  46813. if (hasChanged)
  46814. changed();
  46815. return true;
  46816. }
  46817. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  46818. {
  46819. if (fileFindHandle != 0)
  46820. {
  46821. bool fileFoundIsDir, isHidden, isReadOnly;
  46822. int64 fileSize;
  46823. Time modTime, creationTime;
  46824. if (fileFindHandle->next (&fileFoundIsDir, &isHidden, &fileSize,
  46825. &modTime, &creationTime, &isReadOnly))
  46826. {
  46827. if (addFile (fileFindHandle->getFile(), fileFoundIsDir,
  46828. fileSize, modTime, creationTime, isReadOnly))
  46829. {
  46830. hasChanged = true;
  46831. }
  46832. return true;
  46833. }
  46834. else
  46835. {
  46836. fileFindHandle = 0;
  46837. }
  46838. }
  46839. return false;
  46840. }
  46841. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  46842. const DirectoryContentsList::FileInfo* const second)
  46843. {
  46844. #if JUCE_WINDOWS
  46845. if (first->isDirectory != second->isDirectory)
  46846. return first->isDirectory ? -1 : 1;
  46847. #endif
  46848. return first->filename.compareIgnoreCase (second->filename);
  46849. }
  46850. bool DirectoryContentsList::addFile (const File& file,
  46851. const bool isDir,
  46852. const int64 fileSize,
  46853. const Time& modTime,
  46854. const Time& creationTime,
  46855. const bool isReadOnly)
  46856. {
  46857. if (fileFilter == 0
  46858. || ((! isDir) && fileFilter->isFileSuitable (file))
  46859. || (isDir && fileFilter->isDirectorySuitable (file)))
  46860. {
  46861. ScopedPointer <FileInfo> info (new FileInfo());
  46862. info->filename = file.getFileName();
  46863. info->fileSize = fileSize;
  46864. info->modificationTime = modTime;
  46865. info->creationTime = creationTime;
  46866. info->isDirectory = isDir;
  46867. info->isReadOnly = isReadOnly;
  46868. const ScopedLock sl (fileListLock);
  46869. for (int i = files.size(); --i >= 0;)
  46870. if (files.getUnchecked(i)->filename == info->filename)
  46871. return false;
  46872. files.addSorted (*this, info.release());
  46873. return true;
  46874. }
  46875. return false;
  46876. }
  46877. END_JUCE_NAMESPACE
  46878. /*** End of inlined file: juce_DirectoryContentsList.cpp ***/
  46879. /*** Start of inlined file: juce_FileBrowserComponent.cpp ***/
  46880. BEGIN_JUCE_NAMESPACE
  46881. FileBrowserComponent::FileBrowserComponent (int flags_,
  46882. const File& initialFileOrDirectory,
  46883. const FileFilter* fileFilter_,
  46884. FilePreviewComponent* previewComp_)
  46885. : FileFilter (String::empty),
  46886. fileFilter (fileFilter_),
  46887. flags (flags_),
  46888. previewComp (previewComp_),
  46889. thread ("Juce FileBrowser")
  46890. {
  46891. // You need to specify one or other of the open/save flags..
  46892. jassert ((flags & (saveMode | openMode)) != 0);
  46893. jassert ((flags & (saveMode | openMode)) != (saveMode | openMode));
  46894. // You need to specify at least one of these flags..
  46895. jassert ((flags & (canSelectFiles | canSelectDirectories)) != 0);
  46896. String filename;
  46897. if (initialFileOrDirectory == File::nonexistent)
  46898. {
  46899. currentRoot = File::getCurrentWorkingDirectory();
  46900. }
  46901. else if (initialFileOrDirectory.isDirectory())
  46902. {
  46903. currentRoot = initialFileOrDirectory;
  46904. }
  46905. else
  46906. {
  46907. chosenFiles.add (initialFileOrDirectory);
  46908. currentRoot = initialFileOrDirectory.getParentDirectory();
  46909. filename = initialFileOrDirectory.getFileName();
  46910. }
  46911. fileList = new DirectoryContentsList (this, thread);
  46912. if ((flags & useTreeView) != 0)
  46913. {
  46914. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  46915. if ((flags & canSelectMultipleItems) != 0)
  46916. tree->setMultiSelectEnabled (true);
  46917. addAndMakeVisible (tree);
  46918. fileListComponent = tree;
  46919. }
  46920. else
  46921. {
  46922. FileListComponent* const list = new FileListComponent (*fileList);
  46923. list->setOutlineThickness (1);
  46924. if ((flags & canSelectMultipleItems) != 0)
  46925. list->setMultipleSelectionEnabled (true);
  46926. addAndMakeVisible (list);
  46927. fileListComponent = list;
  46928. }
  46929. fileListComponent->addListener (this);
  46930. addAndMakeVisible (currentPathBox = new ComboBox ("path"));
  46931. currentPathBox->setEditableText (true);
  46932. StringArray rootNames, rootPaths;
  46933. const BigInteger separators (getRoots (rootNames, rootPaths));
  46934. for (int i = 0; i < rootNames.size(); ++i)
  46935. {
  46936. if (separators [i])
  46937. currentPathBox->addSeparator();
  46938. currentPathBox->addItem (rootNames[i], i + 1);
  46939. }
  46940. currentPathBox->addSeparator();
  46941. currentPathBox->addListener (this);
  46942. addAndMakeVisible (filenameBox = new TextEditor());
  46943. filenameBox->setMultiLine (false);
  46944. filenameBox->setSelectAllWhenFocused (true);
  46945. filenameBox->setText (filename, false);
  46946. filenameBox->addListener (this);
  46947. filenameBox->setReadOnly ((flags & (filenameBoxIsReadOnly | canSelectMultipleItems)) != 0);
  46948. Label* label = new Label ("f", TRANS("file:"));
  46949. addAndMakeVisible (label);
  46950. label->attachToComponent (filenameBox, true);
  46951. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  46952. goUpButton->addButtonListener (this);
  46953. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  46954. if (previewComp != 0)
  46955. addAndMakeVisible (previewComp);
  46956. setRoot (currentRoot);
  46957. thread.startThread (4);
  46958. }
  46959. FileBrowserComponent::~FileBrowserComponent()
  46960. {
  46961. if (previewComp != 0)
  46962. removeChildComponent (previewComp);
  46963. deleteAllChildren();
  46964. fileList = 0;
  46965. thread.stopThread (10000);
  46966. }
  46967. void FileBrowserComponent::addListener (FileBrowserListener* const newListener)
  46968. {
  46969. listeners.add (newListener);
  46970. }
  46971. void FileBrowserComponent::removeListener (FileBrowserListener* const listener)
  46972. {
  46973. listeners.remove (listener);
  46974. }
  46975. bool FileBrowserComponent::isSaveMode() const throw()
  46976. {
  46977. return (flags & saveMode) != 0;
  46978. }
  46979. int FileBrowserComponent::getNumSelectedFiles() const throw()
  46980. {
  46981. if (chosenFiles.size() == 0 && currentFileIsValid())
  46982. return 1;
  46983. return chosenFiles.size();
  46984. }
  46985. const File FileBrowserComponent::getSelectedFile (int index) const throw()
  46986. {
  46987. if ((flags & canSelectDirectories) != 0 && filenameBox->getText().isEmpty())
  46988. return currentRoot;
  46989. if (! filenameBox->isReadOnly())
  46990. return currentRoot.getChildFile (filenameBox->getText());
  46991. return chosenFiles[index];
  46992. }
  46993. bool FileBrowserComponent::currentFileIsValid() const
  46994. {
  46995. if (isSaveMode())
  46996. return ! getSelectedFile (0).isDirectory();
  46997. else
  46998. return getSelectedFile (0).exists();
  46999. }
  47000. const File FileBrowserComponent::getHighlightedFile() const throw()
  47001. {
  47002. return fileListComponent->getSelectedFile (0);
  47003. }
  47004. void FileBrowserComponent::deselectAllFiles()
  47005. {
  47006. fileListComponent->deselectAllFiles();
  47007. }
  47008. bool FileBrowserComponent::isFileSuitable (const File& file) const
  47009. {
  47010. return (flags & canSelectFiles) != 0 ? (fileFilter == 0 || fileFilter->isFileSuitable (file))
  47011. : false;
  47012. }
  47013. bool FileBrowserComponent::isDirectorySuitable (const File&) const
  47014. {
  47015. return true;
  47016. }
  47017. bool FileBrowserComponent::isFileOrDirSuitable (const File& f) const
  47018. {
  47019. if (f.isDirectory())
  47020. return (flags & canSelectDirectories) != 0 && (fileFilter == 0 || fileFilter->isDirectorySuitable (f));
  47021. return (flags & canSelectFiles) != 0 && f.exists()
  47022. && (fileFilter == 0 || fileFilter->isFileSuitable (f));
  47023. }
  47024. const File FileBrowserComponent::getRoot() const
  47025. {
  47026. return currentRoot;
  47027. }
  47028. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  47029. {
  47030. if (currentRoot != newRootDirectory)
  47031. {
  47032. fileListComponent->scrollToTop();
  47033. String path (newRootDirectory.getFullPathName());
  47034. if (path.isEmpty())
  47035. path = File::separatorString;
  47036. StringArray rootNames, rootPaths;
  47037. getRoots (rootNames, rootPaths);
  47038. if (! rootPaths.contains (path, true))
  47039. {
  47040. bool alreadyListed = false;
  47041. for (int i = currentPathBox->getNumItems(); --i >= 0;)
  47042. {
  47043. if (currentPathBox->getItemText (i).equalsIgnoreCase (path))
  47044. {
  47045. alreadyListed = true;
  47046. break;
  47047. }
  47048. }
  47049. if (! alreadyListed)
  47050. currentPathBox->addItem (path, currentPathBox->getNumItems() + 2);
  47051. }
  47052. }
  47053. currentRoot = newRootDirectory;
  47054. fileList->setDirectory (currentRoot, true, true);
  47055. String currentRootName (currentRoot.getFullPathName());
  47056. if (currentRootName.isEmpty())
  47057. currentRootName = File::separatorString;
  47058. currentPathBox->setText (currentRootName, true);
  47059. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  47060. && currentRoot.getParentDirectory() != currentRoot);
  47061. }
  47062. void FileBrowserComponent::goUp()
  47063. {
  47064. setRoot (getRoot().getParentDirectory());
  47065. }
  47066. void FileBrowserComponent::refresh()
  47067. {
  47068. fileList->refresh();
  47069. }
  47070. const String FileBrowserComponent::getActionVerb() const
  47071. {
  47072. return isSaveMode() ? TRANS("Save") : TRANS("Open");
  47073. }
  47074. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  47075. {
  47076. return previewComp;
  47077. }
  47078. void FileBrowserComponent::resized()
  47079. {
  47080. getLookAndFeel()
  47081. .layoutFileBrowserComponent (*this, fileListComponent,
  47082. previewComp, currentPathBox,
  47083. filenameBox, goUpButton);
  47084. }
  47085. void FileBrowserComponent::sendListenerChangeMessage()
  47086. {
  47087. Component::BailOutChecker checker (this);
  47088. if (previewComp != 0)
  47089. previewComp->selectedFileChanged (getSelectedFile (0));
  47090. // You shouldn't delete the browser when the file gets changed!
  47091. jassert (! checker.shouldBailOut());
  47092. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  47093. }
  47094. void FileBrowserComponent::selectionChanged()
  47095. {
  47096. StringArray newFilenames;
  47097. bool resetChosenFiles = true;
  47098. for (int i = 0; i < fileListComponent->getNumSelectedFiles(); ++i)
  47099. {
  47100. const File f (fileListComponent->getSelectedFile (i));
  47101. if (isFileOrDirSuitable (f))
  47102. {
  47103. if (resetChosenFiles)
  47104. {
  47105. chosenFiles.clear();
  47106. resetChosenFiles = false;
  47107. }
  47108. chosenFiles.add (f);
  47109. newFilenames.add (f.getRelativePathFrom (getRoot()));
  47110. }
  47111. }
  47112. if (newFilenames.size() > 0)
  47113. filenameBox->setText (newFilenames.joinIntoString (", "), false);
  47114. sendListenerChangeMessage();
  47115. }
  47116. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  47117. {
  47118. Component::BailOutChecker checker (this);
  47119. listeners.callChecked (checker, &FileBrowserListener::fileClicked, f, e);
  47120. }
  47121. void FileBrowserComponent::fileDoubleClicked (const File& f)
  47122. {
  47123. if (f.isDirectory())
  47124. {
  47125. setRoot (f);
  47126. if ((flags & canSelectDirectories) != 0)
  47127. filenameBox->setText (String::empty);
  47128. }
  47129. else
  47130. {
  47131. Component::BailOutChecker checker (this);
  47132. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, f);
  47133. }
  47134. }
  47135. bool FileBrowserComponent::keyPressed (const KeyPress& key)
  47136. {
  47137. (void) key;
  47138. #if JUCE_LINUX || JUCE_WINDOWS
  47139. if (key.getModifiers().isCommandDown()
  47140. && (key.getKeyCode() == 'H' || key.getKeyCode() == 'h'))
  47141. {
  47142. fileList->setIgnoresHiddenFiles (! fileList->ignoresHiddenFiles());
  47143. fileList->refresh();
  47144. return true;
  47145. }
  47146. #endif
  47147. return false;
  47148. }
  47149. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  47150. {
  47151. sendListenerChangeMessage();
  47152. }
  47153. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  47154. {
  47155. if (filenameBox->getText().containsChar (File::separator))
  47156. {
  47157. const File f (currentRoot.getChildFile (filenameBox->getText()));
  47158. if (f.isDirectory())
  47159. {
  47160. setRoot (f);
  47161. chosenFiles.clear();
  47162. filenameBox->setText (String::empty);
  47163. }
  47164. else
  47165. {
  47166. setRoot (f.getParentDirectory());
  47167. chosenFiles.clear();
  47168. chosenFiles.add (f);
  47169. filenameBox->setText (f.getFileName());
  47170. }
  47171. }
  47172. else
  47173. {
  47174. fileDoubleClicked (getSelectedFile (0));
  47175. }
  47176. }
  47177. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  47178. {
  47179. }
  47180. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  47181. {
  47182. if (! isSaveMode())
  47183. selectionChanged();
  47184. }
  47185. void FileBrowserComponent::buttonClicked (Button*)
  47186. {
  47187. goUp();
  47188. }
  47189. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  47190. {
  47191. const String newText (currentPathBox->getText().trim().unquoted());
  47192. if (newText.isNotEmpty())
  47193. {
  47194. const int index = currentPathBox->getSelectedId() - 1;
  47195. StringArray rootNames, rootPaths;
  47196. getRoots (rootNames, rootPaths);
  47197. if (rootPaths [index].isNotEmpty())
  47198. {
  47199. setRoot (File (rootPaths [index]));
  47200. }
  47201. else
  47202. {
  47203. File f (newText);
  47204. for (;;)
  47205. {
  47206. if (f.isDirectory())
  47207. {
  47208. setRoot (f);
  47209. break;
  47210. }
  47211. if (f.getParentDirectory() == f)
  47212. break;
  47213. f = f.getParentDirectory();
  47214. }
  47215. }
  47216. }
  47217. }
  47218. const BigInteger FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  47219. {
  47220. BigInteger separators;
  47221. #if JUCE_WINDOWS
  47222. Array<File> roots;
  47223. File::findFileSystemRoots (roots);
  47224. rootPaths.clear();
  47225. for (int i = 0; i < roots.size(); ++i)
  47226. {
  47227. const File& drive = roots.getReference(i);
  47228. String name (drive.getFullPathName());
  47229. rootPaths.add (name);
  47230. if (drive.isOnHardDisk())
  47231. {
  47232. String volume (drive.getVolumeLabel());
  47233. if (volume.isEmpty())
  47234. volume = TRANS("Hard Drive");
  47235. name << " [" << drive.getVolumeLabel() << ']';
  47236. }
  47237. else if (drive.isOnCDRomDrive())
  47238. {
  47239. name << TRANS(" [CD/DVD drive]");
  47240. }
  47241. rootNames.add (name);
  47242. }
  47243. separators.setBit (rootPaths.size());
  47244. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  47245. rootNames.add ("Documents");
  47246. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47247. rootNames.add ("Desktop");
  47248. #endif
  47249. #if JUCE_MAC
  47250. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  47251. rootNames.add ("Home folder");
  47252. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  47253. rootNames.add ("Documents");
  47254. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47255. rootNames.add ("Desktop");
  47256. separators.setBit (rootPaths.size());
  47257. Array <File> volumes;
  47258. File vol ("/Volumes");
  47259. vol.findChildFiles (volumes, File::findDirectories, false);
  47260. for (int i = 0; i < volumes.size(); ++i)
  47261. {
  47262. const File& volume = volumes.getReference(i);
  47263. if (volume.isDirectory() && ! volume.getFileName().startsWithChar ('.'))
  47264. {
  47265. rootPaths.add (volume.getFullPathName());
  47266. rootNames.add (volume.getFileName());
  47267. }
  47268. }
  47269. #endif
  47270. #if JUCE_LINUX
  47271. rootPaths.add ("/");
  47272. rootNames.add ("/");
  47273. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  47274. rootNames.add ("Home folder");
  47275. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47276. rootNames.add ("Desktop");
  47277. #endif
  47278. return separators;
  47279. }
  47280. END_JUCE_NAMESPACE
  47281. /*** End of inlined file: juce_FileBrowserComponent.cpp ***/
  47282. /*** Start of inlined file: juce_FileChooser.cpp ***/
  47283. BEGIN_JUCE_NAMESPACE
  47284. FileChooser::FileChooser (const String& chooserBoxTitle,
  47285. const File& currentFileOrDirectory,
  47286. const String& fileFilters,
  47287. const bool useNativeDialogBox_)
  47288. : title (chooserBoxTitle),
  47289. filters (fileFilters),
  47290. startingFile (currentFileOrDirectory),
  47291. useNativeDialogBox (useNativeDialogBox_)
  47292. {
  47293. #if JUCE_LINUX
  47294. useNativeDialogBox = false;
  47295. #endif
  47296. if (! fileFilters.containsNonWhitespaceChars())
  47297. filters = "*";
  47298. }
  47299. FileChooser::~FileChooser()
  47300. {
  47301. }
  47302. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  47303. {
  47304. return showDialog (false, true, false, false, false, previewComponent);
  47305. }
  47306. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  47307. {
  47308. return showDialog (false, true, false, false, true, previewComponent);
  47309. }
  47310. bool FileChooser::browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent)
  47311. {
  47312. return showDialog (true, true, false, false, true, previewComponent);
  47313. }
  47314. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  47315. {
  47316. return showDialog (false, true, true, warnAboutOverwritingExistingFiles, false, 0);
  47317. }
  47318. bool FileChooser::browseForDirectory()
  47319. {
  47320. return showDialog (true, false, false, false, false, 0);
  47321. }
  47322. const File FileChooser::getResult() const
  47323. {
  47324. // if you've used a multiple-file select, you should use the getResults() method
  47325. // to retrieve all the files that were chosen.
  47326. jassert (results.size() <= 1);
  47327. return results.getFirst();
  47328. }
  47329. const Array<File>& FileChooser::getResults() const
  47330. {
  47331. return results;
  47332. }
  47333. bool FileChooser::showDialog (const bool selectsDirectories,
  47334. const bool selectsFiles,
  47335. const bool isSave,
  47336. const bool warnAboutOverwritingExistingFiles,
  47337. const bool selectMultipleFiles,
  47338. FilePreviewComponent* const previewComponent)
  47339. {
  47340. Component::SafePointer<Component> previouslyFocused (Component::getCurrentlyFocusedComponent());
  47341. results.clear();
  47342. // the preview component needs to be the right size before you pass it in here..
  47343. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  47344. && previewComponent->getHeight() > 10));
  47345. #if JUCE_WINDOWS
  47346. if (useNativeDialogBox && ! (selectsFiles && selectsDirectories))
  47347. #elif JUCE_MAC
  47348. if (useNativeDialogBox && (previewComponent == 0))
  47349. #else
  47350. if (false)
  47351. #endif
  47352. {
  47353. showPlatformDialog (results, title, startingFile, filters,
  47354. selectsDirectories, selectsFiles, isSave,
  47355. warnAboutOverwritingExistingFiles,
  47356. selectMultipleFiles,
  47357. previewComponent);
  47358. }
  47359. else
  47360. {
  47361. WildcardFileFilter wildcard (selectsFiles ? filters : String::empty,
  47362. selectsDirectories ? "*" : String::empty,
  47363. String::empty);
  47364. int flags = isSave ? FileBrowserComponent::saveMode
  47365. : FileBrowserComponent::openMode;
  47366. if (selectsFiles)
  47367. flags |= FileBrowserComponent::canSelectFiles;
  47368. if (selectsDirectories)
  47369. {
  47370. flags |= FileBrowserComponent::canSelectDirectories;
  47371. if (! isSave)
  47372. flags |= FileBrowserComponent::filenameBoxIsReadOnly;
  47373. }
  47374. if (selectMultipleFiles)
  47375. flags |= FileBrowserComponent::canSelectMultipleItems;
  47376. FileBrowserComponent browserComponent (flags, startingFile, &wildcard, previewComponent);
  47377. FileChooserDialogBox box (title, String::empty,
  47378. browserComponent,
  47379. warnAboutOverwritingExistingFiles,
  47380. browserComponent.findColour (AlertWindow::backgroundColourId));
  47381. if (box.show())
  47382. {
  47383. for (int i = 0; i < browserComponent.getNumSelectedFiles(); ++i)
  47384. results.add (browserComponent.getSelectedFile (i));
  47385. }
  47386. }
  47387. if (previouslyFocused != 0)
  47388. previouslyFocused->grabKeyboardFocus();
  47389. return results.size() > 0;
  47390. }
  47391. FilePreviewComponent::FilePreviewComponent()
  47392. {
  47393. }
  47394. FilePreviewComponent::~FilePreviewComponent()
  47395. {
  47396. }
  47397. END_JUCE_NAMESPACE
  47398. /*** End of inlined file: juce_FileChooser.cpp ***/
  47399. /*** Start of inlined file: juce_FileChooserDialogBox.cpp ***/
  47400. BEGIN_JUCE_NAMESPACE
  47401. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  47402. const String& instructions,
  47403. FileBrowserComponent& chooserComponent,
  47404. const bool warnAboutOverwritingExistingFiles_,
  47405. const Colour& backgroundColour)
  47406. : ResizableWindow (name, backgroundColour, true),
  47407. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  47408. {
  47409. setContentComponent (content = new ContentComponent (name, instructions, chooserComponent));
  47410. setResizable (true, true);
  47411. setResizeLimits (300, 300, 1200, 1000);
  47412. content->okButton.addButtonListener (this);
  47413. content->cancelButton.addButtonListener (this);
  47414. content->chooserComponent.addListener (this);
  47415. }
  47416. FileChooserDialogBox::~FileChooserDialogBox()
  47417. {
  47418. content->chooserComponent.removeListener (this);
  47419. }
  47420. bool FileChooserDialogBox::show (int w, int h)
  47421. {
  47422. return showAt (-1, -1, w, h);
  47423. }
  47424. bool FileChooserDialogBox::showAt (int x, int y, int w, int h)
  47425. {
  47426. if (w <= 0)
  47427. {
  47428. Component* const previewComp = content->chooserComponent.getPreviewComponent();
  47429. if (previewComp != 0)
  47430. w = 400 + previewComp->getWidth();
  47431. else
  47432. w = 600;
  47433. }
  47434. if (h <= 0)
  47435. h = 500;
  47436. if (x < 0 || y < 0)
  47437. centreWithSize (w, h);
  47438. else
  47439. setBounds (x, y, w, h);
  47440. const bool ok = (runModalLoop() != 0);
  47441. setVisible (false);
  47442. return ok;
  47443. }
  47444. void FileChooserDialogBox::buttonClicked (Button* button)
  47445. {
  47446. if (button == &(content->okButton))
  47447. {
  47448. if (warnAboutOverwritingExistingFiles
  47449. && content->chooserComponent.isSaveMode()
  47450. && content->chooserComponent.getSelectedFile(0).exists())
  47451. {
  47452. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  47453. TRANS("File already exists"),
  47454. TRANS("There's already a file called:")
  47455. + "\n\n" + content->chooserComponent.getSelectedFile(0).getFullPathName()
  47456. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  47457. TRANS("overwrite"),
  47458. TRANS("cancel")))
  47459. {
  47460. return;
  47461. }
  47462. }
  47463. exitModalState (1);
  47464. }
  47465. else if (button == &(content->cancelButton))
  47466. {
  47467. closeButtonPressed();
  47468. }
  47469. }
  47470. void FileChooserDialogBox::closeButtonPressed()
  47471. {
  47472. setVisible (false);
  47473. }
  47474. void FileChooserDialogBox::selectionChanged()
  47475. {
  47476. content->okButton.setEnabled (content->chooserComponent.currentFileIsValid());
  47477. }
  47478. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  47479. {
  47480. }
  47481. void FileChooserDialogBox::fileDoubleClicked (const File&)
  47482. {
  47483. selectionChanged();
  47484. content->okButton.triggerClick();
  47485. }
  47486. FileChooserDialogBox::ContentComponent::ContentComponent (const String& name, const String& instructions_, FileBrowserComponent& chooserComponent_)
  47487. : Component (name), instructions (instructions_),
  47488. chooserComponent (chooserComponent_),
  47489. okButton (chooserComponent_.getActionVerb()),
  47490. cancelButton (TRANS ("Cancel"))
  47491. {
  47492. addAndMakeVisible (&chooserComponent);
  47493. addAndMakeVisible (&okButton);
  47494. okButton.setEnabled (chooserComponent.currentFileIsValid());
  47495. okButton.addShortcut (KeyPress (KeyPress::returnKey, 0, 0));
  47496. addAndMakeVisible (&cancelButton);
  47497. cancelButton.addShortcut (KeyPress (KeyPress::escapeKey, 0, 0));
  47498. setInterceptsMouseClicks (false, true);
  47499. }
  47500. FileChooserDialogBox::ContentComponent::~ContentComponent()
  47501. {
  47502. }
  47503. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  47504. {
  47505. g.setColour (getLookAndFeel().findColour (FileChooserDialogBox::titleTextColourId));
  47506. text.draw (g);
  47507. }
  47508. void FileChooserDialogBox::ContentComponent::resized()
  47509. {
  47510. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  47511. const Rectangle<float> bb (text.getBoundingBox (0, text.getNumGlyphs(), false));
  47512. const int y = roundToInt (bb.getBottom()) + 10;
  47513. const int buttonHeight = 26;
  47514. const int buttonY = getHeight() - buttonHeight - 8;
  47515. chooserComponent.setBounds (0, y, getWidth(), buttonY - y - 20);
  47516. okButton.setBounds (proportionOfWidth (0.25f), buttonY,
  47517. proportionOfWidth (0.2f), buttonHeight);
  47518. cancelButton.setBounds (proportionOfWidth (0.55f), buttonY,
  47519. proportionOfWidth (0.2f), buttonHeight);
  47520. }
  47521. END_JUCE_NAMESPACE
  47522. /*** End of inlined file: juce_FileChooserDialogBox.cpp ***/
  47523. /*** Start of inlined file: juce_FileFilter.cpp ***/
  47524. BEGIN_JUCE_NAMESPACE
  47525. FileFilter::FileFilter (const String& filterDescription)
  47526. : description (filterDescription)
  47527. {
  47528. }
  47529. FileFilter::~FileFilter()
  47530. {
  47531. }
  47532. const String& FileFilter::getDescription() const throw()
  47533. {
  47534. return description;
  47535. }
  47536. END_JUCE_NAMESPACE
  47537. /*** End of inlined file: juce_FileFilter.cpp ***/
  47538. /*** Start of inlined file: juce_FileListComponent.cpp ***/
  47539. BEGIN_JUCE_NAMESPACE
  47540. const Image juce_createIconForFile (const File& file);
  47541. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  47542. : ListBox (String::empty, 0),
  47543. DirectoryContentsDisplayComponent (listToShow)
  47544. {
  47545. setModel (this);
  47546. fileList.addChangeListener (this);
  47547. }
  47548. FileListComponent::~FileListComponent()
  47549. {
  47550. fileList.removeChangeListener (this);
  47551. }
  47552. int FileListComponent::getNumSelectedFiles() const
  47553. {
  47554. return getNumSelectedRows();
  47555. }
  47556. const File FileListComponent::getSelectedFile (int index) const
  47557. {
  47558. return fileList.getFile (getSelectedRow (index));
  47559. }
  47560. void FileListComponent::deselectAllFiles()
  47561. {
  47562. deselectAllRows();
  47563. }
  47564. void FileListComponent::scrollToTop()
  47565. {
  47566. getVerticalScrollBar()->setCurrentRangeStart (0);
  47567. }
  47568. void FileListComponent::changeListenerCallback (void*)
  47569. {
  47570. updateContent();
  47571. if (lastDirectory != fileList.getDirectory())
  47572. {
  47573. lastDirectory = fileList.getDirectory();
  47574. deselectAllRows();
  47575. }
  47576. }
  47577. class FileListItemComponent : public Component,
  47578. public TimeSliceClient,
  47579. public AsyncUpdater
  47580. {
  47581. public:
  47582. FileListItemComponent (FileListComponent& owner_, TimeSliceThread& thread_)
  47583. : owner (owner_), thread (thread_),
  47584. highlighted (false), index (0), icon (0)
  47585. {
  47586. }
  47587. ~FileListItemComponent()
  47588. {
  47589. thread.removeTimeSliceClient (this);
  47590. clearIcon();
  47591. }
  47592. void paint (Graphics& g)
  47593. {
  47594. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  47595. file.getFileName(),
  47596. &icon,
  47597. fileSize, modTime,
  47598. isDirectory, highlighted,
  47599. index, owner);
  47600. }
  47601. void mouseDown (const MouseEvent& e)
  47602. {
  47603. owner.selectRowsBasedOnModifierKeys (index, e.mods);
  47604. owner.sendMouseClickMessage (file, e);
  47605. }
  47606. void mouseDoubleClick (const MouseEvent&)
  47607. {
  47608. owner.sendDoubleClickMessage (file);
  47609. }
  47610. void update (const File& root,
  47611. const DirectoryContentsList::FileInfo* const fileInfo,
  47612. const int index_,
  47613. const bool highlighted_)
  47614. {
  47615. thread.removeTimeSliceClient (this);
  47616. if (highlighted_ != highlighted
  47617. || index_ != index)
  47618. {
  47619. index = index_;
  47620. highlighted = highlighted_;
  47621. repaint();
  47622. }
  47623. File newFile;
  47624. String newFileSize;
  47625. String newModTime;
  47626. if (fileInfo != 0)
  47627. {
  47628. newFile = root.getChildFile (fileInfo->filename);
  47629. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  47630. newModTime = fileInfo->modificationTime.formatted ("%d %b '%y %H:%M");
  47631. }
  47632. if (newFile != file
  47633. || fileSize != newFileSize
  47634. || modTime != newModTime)
  47635. {
  47636. file = newFile;
  47637. fileSize = newFileSize;
  47638. modTime = newModTime;
  47639. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  47640. repaint();
  47641. clearIcon();
  47642. }
  47643. if (file != File::nonexistent && icon.isNull() && ! isDirectory)
  47644. {
  47645. updateIcon (true);
  47646. if (! icon.isValid())
  47647. thread.addTimeSliceClient (this);
  47648. }
  47649. }
  47650. bool useTimeSlice()
  47651. {
  47652. updateIcon (false);
  47653. return false;
  47654. }
  47655. void handleAsyncUpdate()
  47656. {
  47657. repaint();
  47658. }
  47659. juce_UseDebuggingNewOperator
  47660. private:
  47661. FileListComponent& owner;
  47662. TimeSliceThread& thread;
  47663. bool highlighted;
  47664. int index;
  47665. File file;
  47666. String fileSize;
  47667. String modTime;
  47668. Image icon;
  47669. bool isDirectory;
  47670. void clearIcon()
  47671. {
  47672. icon = Image::null;
  47673. }
  47674. void updateIcon (const bool onlyUpdateIfCached)
  47675. {
  47676. if (icon.isNull())
  47677. {
  47678. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47679. Image im (ImageCache::getFromHashCode (hashCode));
  47680. if (im.isNull() && ! onlyUpdateIfCached)
  47681. {
  47682. im = juce_createIconForFile (file);
  47683. if (im.isValid())
  47684. ImageCache::addImageToCache (im, hashCode);
  47685. }
  47686. if (im.isValid())
  47687. {
  47688. icon = im;
  47689. triggerAsyncUpdate();
  47690. }
  47691. }
  47692. }
  47693. };
  47694. int FileListComponent::getNumRows()
  47695. {
  47696. return fileList.getNumFiles();
  47697. }
  47698. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  47699. {
  47700. }
  47701. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  47702. {
  47703. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  47704. if (comp == 0)
  47705. {
  47706. delete existingComponentToUpdate;
  47707. comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  47708. }
  47709. DirectoryContentsList::FileInfo fileInfo;
  47710. if (fileList.getFileInfo (row, fileInfo))
  47711. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  47712. else
  47713. comp->update (fileList.getDirectory(), 0, row, isSelected);
  47714. return comp;
  47715. }
  47716. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  47717. {
  47718. sendSelectionChangeMessage();
  47719. }
  47720. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  47721. {
  47722. }
  47723. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  47724. {
  47725. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  47726. }
  47727. END_JUCE_NAMESPACE
  47728. /*** End of inlined file: juce_FileListComponent.cpp ***/
  47729. /*** Start of inlined file: juce_FilenameComponent.cpp ***/
  47730. BEGIN_JUCE_NAMESPACE
  47731. FilenameComponent::FilenameComponent (const String& name,
  47732. const File& currentFile,
  47733. const bool canEditFilename,
  47734. const bool isDirectory,
  47735. const bool isForSaving,
  47736. const String& fileBrowserWildcard,
  47737. const String& enforcedSuffix_,
  47738. const String& textWhenNothingSelected)
  47739. : Component (name),
  47740. maxRecentFiles (30),
  47741. isDir (isDirectory),
  47742. isSaving (isForSaving),
  47743. isFileDragOver (false),
  47744. wildcard (fileBrowserWildcard),
  47745. enforcedSuffix (enforcedSuffix_)
  47746. {
  47747. addAndMakeVisible (&filenameBox);
  47748. filenameBox.setEditableText (canEditFilename);
  47749. filenameBox.addListener (this);
  47750. filenameBox.setTextWhenNothingSelected (textWhenNothingSelected);
  47751. filenameBox.setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  47752. setBrowseButtonText ("...");
  47753. setCurrentFile (currentFile, true);
  47754. }
  47755. FilenameComponent::~FilenameComponent()
  47756. {
  47757. }
  47758. void FilenameComponent::paintOverChildren (Graphics& g)
  47759. {
  47760. if (isFileDragOver)
  47761. {
  47762. g.setColour (Colours::red.withAlpha (0.2f));
  47763. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  47764. }
  47765. }
  47766. void FilenameComponent::resized()
  47767. {
  47768. getLookAndFeel().layoutFilenameComponent (*this, &filenameBox, browseButton);
  47769. }
  47770. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  47771. {
  47772. browseButtonText = newBrowseButtonText;
  47773. lookAndFeelChanged();
  47774. }
  47775. void FilenameComponent::lookAndFeelChanged()
  47776. {
  47777. browseButton = 0;
  47778. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  47779. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  47780. resized();
  47781. browseButton->addButtonListener (this);
  47782. }
  47783. void FilenameComponent::setTooltip (const String& newTooltip)
  47784. {
  47785. SettableTooltipClient::setTooltip (newTooltip);
  47786. filenameBox.setTooltip (newTooltip);
  47787. }
  47788. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47789. {
  47790. defaultBrowseFile = newDefaultDirectory;
  47791. }
  47792. void FilenameComponent::buttonClicked (Button*)
  47793. {
  47794. FileChooser fc (TRANS("Choose a new file"),
  47795. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  47796. : getCurrentFile(),
  47797. wildcard);
  47798. if (isDir ? fc.browseForDirectory()
  47799. : (isSaving ? fc.browseForFileToSave (false)
  47800. : fc.browseForFileToOpen()))
  47801. {
  47802. setCurrentFile (fc.getResult(), true);
  47803. }
  47804. }
  47805. void FilenameComponent::comboBoxChanged (ComboBox*)
  47806. {
  47807. setCurrentFile (getCurrentFile(), true);
  47808. }
  47809. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  47810. {
  47811. return true;
  47812. }
  47813. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  47814. {
  47815. isFileDragOver = false;
  47816. repaint();
  47817. const File f (filenames[0]);
  47818. if (f.exists() && (f.isDirectory() == isDir))
  47819. setCurrentFile (f, true);
  47820. }
  47821. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  47822. {
  47823. isFileDragOver = true;
  47824. repaint();
  47825. }
  47826. void FilenameComponent::fileDragExit (const StringArray&)
  47827. {
  47828. isFileDragOver = false;
  47829. repaint();
  47830. }
  47831. const File FilenameComponent::getCurrentFile() const
  47832. {
  47833. File f (filenameBox.getText());
  47834. if (enforcedSuffix.isNotEmpty())
  47835. f = f.withFileExtension (enforcedSuffix);
  47836. return f;
  47837. }
  47838. void FilenameComponent::setCurrentFile (File newFile,
  47839. const bool addToRecentlyUsedList,
  47840. const bool sendChangeNotification)
  47841. {
  47842. if (enforcedSuffix.isNotEmpty())
  47843. newFile = newFile.withFileExtension (enforcedSuffix);
  47844. if (newFile.getFullPathName() != lastFilename)
  47845. {
  47846. lastFilename = newFile.getFullPathName();
  47847. if (addToRecentlyUsedList)
  47848. addRecentlyUsedFile (newFile);
  47849. filenameBox.setText (lastFilename, true);
  47850. if (sendChangeNotification)
  47851. triggerAsyncUpdate();
  47852. }
  47853. }
  47854. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  47855. {
  47856. filenameBox.setEditableText (shouldBeEditable);
  47857. }
  47858. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  47859. {
  47860. StringArray names;
  47861. for (int i = 0; i < filenameBox.getNumItems(); ++i)
  47862. names.add (filenameBox.getItemText (i));
  47863. return names;
  47864. }
  47865. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  47866. {
  47867. if (filenames != getRecentlyUsedFilenames())
  47868. {
  47869. filenameBox.clear();
  47870. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  47871. filenameBox.addItem (filenames[i], i + 1);
  47872. }
  47873. }
  47874. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  47875. {
  47876. maxRecentFiles = jmax (1, newMaximum);
  47877. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  47878. }
  47879. void FilenameComponent::addRecentlyUsedFile (const File& file)
  47880. {
  47881. StringArray files (getRecentlyUsedFilenames());
  47882. if (file.getFullPathName().isNotEmpty())
  47883. {
  47884. files.removeString (file.getFullPathName(), true);
  47885. files.insert (0, file.getFullPathName());
  47886. setRecentlyUsedFilenames (files);
  47887. }
  47888. }
  47889. void FilenameComponent::addListener (FilenameComponentListener* const listener)
  47890. {
  47891. listeners.add (listener);
  47892. }
  47893. void FilenameComponent::removeListener (FilenameComponentListener* const listener)
  47894. {
  47895. listeners.remove (listener);
  47896. }
  47897. void FilenameComponent::handleAsyncUpdate()
  47898. {
  47899. Component::BailOutChecker checker (this);
  47900. listeners.callChecked (checker, &FilenameComponentListener::filenameComponentChanged, this);
  47901. }
  47902. END_JUCE_NAMESPACE
  47903. /*** End of inlined file: juce_FilenameComponent.cpp ***/
  47904. /*** Start of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47905. BEGIN_JUCE_NAMESPACE
  47906. FileSearchPathListComponent::FileSearchPathListComponent()
  47907. {
  47908. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  47909. listBox->setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  47910. listBox->setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  47911. listBox->setOutlineThickness (1);
  47912. addAndMakeVisible (addButton = new TextButton ("+"));
  47913. addButton->addButtonListener (this);
  47914. addButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47915. addAndMakeVisible (removeButton = new TextButton ("-"));
  47916. removeButton->addButtonListener (this);
  47917. removeButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47918. addAndMakeVisible (changeButton = new TextButton (TRANS("change...")));
  47919. changeButton->addButtonListener (this);
  47920. addAndMakeVisible (upButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  47921. upButton->addButtonListener (this);
  47922. {
  47923. Path arrowPath;
  47924. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  47925. DrawablePath arrowImage;
  47926. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47927. arrowImage.setPath (arrowPath);
  47928. upButton->setImages (&arrowImage);
  47929. }
  47930. addAndMakeVisible (downButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  47931. downButton->addButtonListener (this);
  47932. {
  47933. Path arrowPath;
  47934. arrowPath.addArrow (Line<float> (50.0f, 0.0f, 50.0f, 100.0f), 40.0f, 100.0f, 50.0f);
  47935. DrawablePath arrowImage;
  47936. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47937. arrowImage.setPath (arrowPath);
  47938. downButton->setImages (&arrowImage);
  47939. }
  47940. updateButtons();
  47941. }
  47942. FileSearchPathListComponent::~FileSearchPathListComponent()
  47943. {
  47944. deleteAllChildren();
  47945. }
  47946. void FileSearchPathListComponent::updateButtons()
  47947. {
  47948. const bool anythingSelected = listBox->getNumSelectedRows() > 0;
  47949. removeButton->setEnabled (anythingSelected);
  47950. changeButton->setEnabled (anythingSelected);
  47951. upButton->setEnabled (anythingSelected);
  47952. downButton->setEnabled (anythingSelected);
  47953. }
  47954. void FileSearchPathListComponent::changed()
  47955. {
  47956. listBox->updateContent();
  47957. listBox->repaint();
  47958. updateButtons();
  47959. }
  47960. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  47961. {
  47962. if (newPath.toString() != path.toString())
  47963. {
  47964. path = newPath;
  47965. changed();
  47966. }
  47967. }
  47968. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47969. {
  47970. defaultBrowseTarget = newDefaultDirectory;
  47971. }
  47972. int FileSearchPathListComponent::getNumRows()
  47973. {
  47974. return path.getNumPaths();
  47975. }
  47976. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  47977. {
  47978. if (rowIsSelected)
  47979. g.fillAll (findColour (TextEditor::highlightColourId));
  47980. g.setColour (findColour (ListBox::textColourId));
  47981. Font f (height * 0.7f);
  47982. f.setHorizontalScale (0.9f);
  47983. g.setFont (f);
  47984. g.drawText (path [rowNumber].getFullPathName(),
  47985. 4, 0, width - 6, height,
  47986. Justification::centredLeft, true);
  47987. }
  47988. void FileSearchPathListComponent::deleteKeyPressed (int row)
  47989. {
  47990. if (((unsigned int) row) < (unsigned int) path.getNumPaths())
  47991. {
  47992. path.remove (row);
  47993. changed();
  47994. }
  47995. }
  47996. void FileSearchPathListComponent::returnKeyPressed (int row)
  47997. {
  47998. FileChooser chooser (TRANS("Change folder..."), path [row], "*");
  47999. if (chooser.browseForDirectory())
  48000. {
  48001. path.remove (row);
  48002. path.add (chooser.getResult(), row);
  48003. changed();
  48004. }
  48005. }
  48006. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  48007. {
  48008. returnKeyPressed (row);
  48009. }
  48010. void FileSearchPathListComponent::selectedRowsChanged (int)
  48011. {
  48012. updateButtons();
  48013. }
  48014. void FileSearchPathListComponent::paint (Graphics& g)
  48015. {
  48016. g.fillAll (findColour (backgroundColourId));
  48017. }
  48018. void FileSearchPathListComponent::resized()
  48019. {
  48020. const int buttonH = 22;
  48021. const int buttonY = getHeight() - buttonH - 4;
  48022. listBox->setBounds (2, 2, getWidth() - 4, buttonY - 5);
  48023. addButton->setBounds (2, buttonY, buttonH, buttonH);
  48024. removeButton->setBounds (addButton->getRight(), buttonY, buttonH, buttonH);
  48025. changeButton->changeWidthToFitText (buttonH);
  48026. downButton->setSize (buttonH * 2, buttonH);
  48027. upButton->setSize (buttonH * 2, buttonH);
  48028. downButton->setTopRightPosition (getWidth() - 2, buttonY);
  48029. upButton->setTopRightPosition (downButton->getX() - 4, buttonY);
  48030. changeButton->setTopRightPosition (upButton->getX() - 8, buttonY);
  48031. }
  48032. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  48033. {
  48034. return true;
  48035. }
  48036. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  48037. {
  48038. for (int i = filenames.size(); --i >= 0;)
  48039. {
  48040. const File f (filenames[i]);
  48041. if (f.isDirectory())
  48042. {
  48043. const int row = listBox->getRowContainingPosition (0, mouseY - listBox->getY());
  48044. path.add (f, row);
  48045. changed();
  48046. }
  48047. }
  48048. }
  48049. void FileSearchPathListComponent::buttonClicked (Button* button)
  48050. {
  48051. const int currentRow = listBox->getSelectedRow();
  48052. if (button == removeButton)
  48053. {
  48054. deleteKeyPressed (currentRow);
  48055. }
  48056. else if (button == addButton)
  48057. {
  48058. File start (defaultBrowseTarget);
  48059. if (start == File::nonexistent)
  48060. start = path [0];
  48061. if (start == File::nonexistent)
  48062. start = File::getCurrentWorkingDirectory();
  48063. FileChooser chooser (TRANS("Add a folder..."), start, "*");
  48064. if (chooser.browseForDirectory())
  48065. {
  48066. path.add (chooser.getResult(), currentRow);
  48067. }
  48068. }
  48069. else if (button == changeButton)
  48070. {
  48071. returnKeyPressed (currentRow);
  48072. }
  48073. else if (button == upButton)
  48074. {
  48075. if (currentRow > 0 && currentRow < path.getNumPaths())
  48076. {
  48077. const File f (path[currentRow]);
  48078. path.remove (currentRow);
  48079. path.add (f, currentRow - 1);
  48080. listBox->selectRow (currentRow - 1);
  48081. }
  48082. }
  48083. else if (button == downButton)
  48084. {
  48085. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  48086. {
  48087. const File f (path[currentRow]);
  48088. path.remove (currentRow);
  48089. path.add (f, currentRow + 1);
  48090. listBox->selectRow (currentRow + 1);
  48091. }
  48092. }
  48093. changed();
  48094. }
  48095. END_JUCE_NAMESPACE
  48096. /*** End of inlined file: juce_FileSearchPathListComponent.cpp ***/
  48097. /*** Start of inlined file: juce_FileTreeComponent.cpp ***/
  48098. BEGIN_JUCE_NAMESPACE
  48099. const Image juce_createIconForFile (const File& file);
  48100. class FileListTreeItem : public TreeViewItem,
  48101. public TimeSliceClient,
  48102. public AsyncUpdater,
  48103. public ChangeListener
  48104. {
  48105. public:
  48106. FileListTreeItem (FileTreeComponent& owner_,
  48107. DirectoryContentsList* const parentContentsList_,
  48108. const int indexInContentsList_,
  48109. const File& file_,
  48110. TimeSliceThread& thread_)
  48111. : file (file_),
  48112. owner (owner_),
  48113. parentContentsList (parentContentsList_),
  48114. indexInContentsList (indexInContentsList_),
  48115. subContentsList (0),
  48116. canDeleteSubContentsList (false),
  48117. thread (thread_),
  48118. icon (0)
  48119. {
  48120. DirectoryContentsList::FileInfo fileInfo;
  48121. if (parentContentsList_ != 0
  48122. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  48123. {
  48124. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  48125. modTime = fileInfo.modificationTime.formatted ("%d %b '%y %H:%M");
  48126. isDirectory = fileInfo.isDirectory;
  48127. }
  48128. else
  48129. {
  48130. isDirectory = true;
  48131. }
  48132. }
  48133. ~FileListTreeItem()
  48134. {
  48135. thread.removeTimeSliceClient (this);
  48136. clearSubItems();
  48137. if (canDeleteSubContentsList)
  48138. delete subContentsList;
  48139. }
  48140. bool mightContainSubItems() { return isDirectory; }
  48141. const String getUniqueName() const { return file.getFullPathName(); }
  48142. int getItemHeight() const { return 22; }
  48143. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  48144. void itemOpennessChanged (bool isNowOpen)
  48145. {
  48146. if (isNowOpen)
  48147. {
  48148. clearSubItems();
  48149. isDirectory = file.isDirectory();
  48150. if (isDirectory)
  48151. {
  48152. if (subContentsList == 0)
  48153. {
  48154. jassert (parentContentsList != 0);
  48155. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  48156. l->setDirectory (file, true, true);
  48157. setSubContentsList (l);
  48158. canDeleteSubContentsList = true;
  48159. }
  48160. changeListenerCallback (0);
  48161. }
  48162. }
  48163. }
  48164. void setSubContentsList (DirectoryContentsList* newList)
  48165. {
  48166. jassert (subContentsList == 0);
  48167. subContentsList = newList;
  48168. newList->addChangeListener (this);
  48169. }
  48170. void changeListenerCallback (void*)
  48171. {
  48172. clearSubItems();
  48173. if (isOpen() && subContentsList != 0)
  48174. {
  48175. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  48176. {
  48177. FileListTreeItem* const item
  48178. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  48179. addSubItem (item);
  48180. }
  48181. }
  48182. }
  48183. void paintItem (Graphics& g, int width, int height)
  48184. {
  48185. if (file != File::nonexistent)
  48186. {
  48187. updateIcon (true);
  48188. if (icon.isNull())
  48189. thread.addTimeSliceClient (this);
  48190. }
  48191. owner.getLookAndFeel()
  48192. .drawFileBrowserRow (g, width, height,
  48193. file.getFileName(),
  48194. &icon, fileSize, modTime,
  48195. isDirectory, isSelected(),
  48196. indexInContentsList, owner);
  48197. }
  48198. void itemClicked (const MouseEvent& e)
  48199. {
  48200. owner.sendMouseClickMessage (file, e);
  48201. }
  48202. void itemDoubleClicked (const MouseEvent& e)
  48203. {
  48204. TreeViewItem::itemDoubleClicked (e);
  48205. owner.sendDoubleClickMessage (file);
  48206. }
  48207. void itemSelectionChanged (bool)
  48208. {
  48209. owner.sendSelectionChangeMessage();
  48210. }
  48211. bool useTimeSlice()
  48212. {
  48213. updateIcon (false);
  48214. thread.removeTimeSliceClient (this);
  48215. return false;
  48216. }
  48217. void handleAsyncUpdate()
  48218. {
  48219. owner.repaint();
  48220. }
  48221. const File file;
  48222. juce_UseDebuggingNewOperator
  48223. private:
  48224. FileTreeComponent& owner;
  48225. DirectoryContentsList* parentContentsList;
  48226. int indexInContentsList;
  48227. DirectoryContentsList* subContentsList;
  48228. bool isDirectory, canDeleteSubContentsList;
  48229. TimeSliceThread& thread;
  48230. Image icon;
  48231. String fileSize;
  48232. String modTime;
  48233. void updateIcon (const bool onlyUpdateIfCached)
  48234. {
  48235. if (icon.isNull())
  48236. {
  48237. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  48238. Image im (ImageCache::getFromHashCode (hashCode));
  48239. if (im.isNull() && ! onlyUpdateIfCached)
  48240. {
  48241. im = juce_createIconForFile (file);
  48242. if (im.isValid())
  48243. ImageCache::addImageToCache (im, hashCode);
  48244. }
  48245. if (im.isValid())
  48246. {
  48247. icon = im;
  48248. triggerAsyncUpdate();
  48249. }
  48250. }
  48251. }
  48252. };
  48253. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  48254. : DirectoryContentsDisplayComponent (listToShow)
  48255. {
  48256. FileListTreeItem* const root
  48257. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  48258. listToShow.getTimeSliceThread());
  48259. root->setSubContentsList (&listToShow);
  48260. setRootItemVisible (false);
  48261. setRootItem (root);
  48262. }
  48263. FileTreeComponent::~FileTreeComponent()
  48264. {
  48265. deleteRootItem();
  48266. }
  48267. const File FileTreeComponent::getSelectedFile (const int index) const
  48268. {
  48269. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  48270. return item != 0 ? item->file
  48271. : File::nonexistent;
  48272. }
  48273. void FileTreeComponent::deselectAllFiles()
  48274. {
  48275. clearSelectedItems();
  48276. }
  48277. void FileTreeComponent::scrollToTop()
  48278. {
  48279. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  48280. }
  48281. void FileTreeComponent::setDragAndDropDescription (const String& description)
  48282. {
  48283. dragAndDropDescription = description;
  48284. }
  48285. END_JUCE_NAMESPACE
  48286. /*** End of inlined file: juce_FileTreeComponent.cpp ***/
  48287. /*** Start of inlined file: juce_ImagePreviewComponent.cpp ***/
  48288. BEGIN_JUCE_NAMESPACE
  48289. ImagePreviewComponent::ImagePreviewComponent()
  48290. {
  48291. }
  48292. ImagePreviewComponent::~ImagePreviewComponent()
  48293. {
  48294. }
  48295. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  48296. {
  48297. const int availableW = proportionOfWidth (0.97f);
  48298. const int availableH = getHeight() - 13 * 4;
  48299. const double scale = jmin (1.0,
  48300. availableW / (double) w,
  48301. availableH / (double) h);
  48302. w = roundToInt (scale * w);
  48303. h = roundToInt (scale * h);
  48304. }
  48305. void ImagePreviewComponent::selectedFileChanged (const File& file)
  48306. {
  48307. if (fileToLoad != file)
  48308. {
  48309. fileToLoad = file;
  48310. startTimer (100);
  48311. }
  48312. }
  48313. void ImagePreviewComponent::timerCallback()
  48314. {
  48315. stopTimer();
  48316. currentThumbnail = Image::null;
  48317. currentDetails = String::empty;
  48318. repaint();
  48319. ScopedPointer <FileInputStream> in (fileToLoad.createInputStream());
  48320. if (in != 0)
  48321. {
  48322. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  48323. if (format != 0)
  48324. {
  48325. currentThumbnail = format->decodeImage (*in);
  48326. if (currentThumbnail.isValid())
  48327. {
  48328. int w = currentThumbnail.getWidth();
  48329. int h = currentThumbnail.getHeight();
  48330. currentDetails
  48331. << fileToLoad.getFileName() << "\n"
  48332. << format->getFormatName() << "\n"
  48333. << w << " x " << h << " pixels\n"
  48334. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  48335. getThumbSize (w, h);
  48336. currentThumbnail = currentThumbnail.rescaled (w, h);
  48337. }
  48338. }
  48339. }
  48340. }
  48341. void ImagePreviewComponent::paint (Graphics& g)
  48342. {
  48343. if (currentThumbnail.isValid())
  48344. {
  48345. g.setFont (13.0f);
  48346. int w = currentThumbnail.getWidth();
  48347. int h = currentThumbnail.getHeight();
  48348. getThumbSize (w, h);
  48349. const int numLines = 4;
  48350. const int totalH = 13 * numLines + h + 4;
  48351. const int y = (getHeight() - totalH) / 2;
  48352. g.drawImageWithin (currentThumbnail,
  48353. (getWidth() - w) / 2, y, w, h,
  48354. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  48355. false);
  48356. g.drawFittedText (currentDetails,
  48357. 0, y + h + 4, getWidth(), 100,
  48358. Justification::centredTop, numLines);
  48359. }
  48360. }
  48361. END_JUCE_NAMESPACE
  48362. /*** End of inlined file: juce_ImagePreviewComponent.cpp ***/
  48363. /*** Start of inlined file: juce_WildcardFileFilter.cpp ***/
  48364. BEGIN_JUCE_NAMESPACE
  48365. WildcardFileFilter::WildcardFileFilter (const String& fileWildcardPatterns,
  48366. const String& directoryWildcardPatterns,
  48367. const String& description_)
  48368. : FileFilter (description_.isEmpty() ? fileWildcardPatterns
  48369. : (description_ + " (" + fileWildcardPatterns + ")"))
  48370. {
  48371. parse (fileWildcardPatterns, fileWildcards);
  48372. parse (directoryWildcardPatterns, directoryWildcards);
  48373. }
  48374. WildcardFileFilter::~WildcardFileFilter()
  48375. {
  48376. }
  48377. bool WildcardFileFilter::isFileSuitable (const File& file) const
  48378. {
  48379. return match (file, fileWildcards);
  48380. }
  48381. bool WildcardFileFilter::isDirectorySuitable (const File& file) const
  48382. {
  48383. return match (file, directoryWildcards);
  48384. }
  48385. void WildcardFileFilter::parse (const String& pattern, StringArray& result)
  48386. {
  48387. result.addTokens (pattern.toLowerCase(), ";,", "\"'");
  48388. result.trim();
  48389. result.removeEmptyStrings();
  48390. // special case for *.*, because people use it to mean "any file", but it
  48391. // would actually ignore files with no extension.
  48392. for (int i = result.size(); --i >= 0;)
  48393. if (result[i] == "*.*")
  48394. result.set (i, "*");
  48395. }
  48396. bool WildcardFileFilter::match (const File& file, const StringArray& wildcards)
  48397. {
  48398. const String filename (file.getFileName());
  48399. for (int i = wildcards.size(); --i >= 0;)
  48400. if (filename.matchesWildcard (wildcards[i], true))
  48401. return true;
  48402. return false;
  48403. }
  48404. END_JUCE_NAMESPACE
  48405. /*** End of inlined file: juce_WildcardFileFilter.cpp ***/
  48406. /*** Start of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48407. BEGIN_JUCE_NAMESPACE
  48408. KeyboardFocusTraverser::KeyboardFocusTraverser()
  48409. {
  48410. }
  48411. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  48412. {
  48413. }
  48414. namespace KeyboardFocusHelpers
  48415. {
  48416. // This will sort a set of components, so that they are ordered in terms of
  48417. // left-to-right and then top-to-bottom.
  48418. class ScreenPositionComparator
  48419. {
  48420. public:
  48421. ScreenPositionComparator() {}
  48422. static int compareElements (const Component* const first, const Component* const second)
  48423. {
  48424. int explicitOrder1 = first->getExplicitFocusOrder();
  48425. if (explicitOrder1 <= 0)
  48426. explicitOrder1 = std::numeric_limits<int>::max() / 2;
  48427. int explicitOrder2 = second->getExplicitFocusOrder();
  48428. if (explicitOrder2 <= 0)
  48429. explicitOrder2 = std::numeric_limits<int>::max() / 2;
  48430. if (explicitOrder1 != explicitOrder2)
  48431. return explicitOrder1 - explicitOrder2;
  48432. const int diff = first->getY() - second->getY();
  48433. return (diff == 0) ? first->getX() - second->getX()
  48434. : diff;
  48435. }
  48436. };
  48437. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  48438. {
  48439. if (parent->getNumChildComponents() > 0)
  48440. {
  48441. Array <Component*> localComps;
  48442. ScreenPositionComparator comparator;
  48443. int i;
  48444. for (i = parent->getNumChildComponents(); --i >= 0;)
  48445. {
  48446. Component* const c = parent->getChildComponent (i);
  48447. if (c->isVisible() && c->isEnabled())
  48448. localComps.addSorted (comparator, c);
  48449. }
  48450. for (i = 0; i < localComps.size(); ++i)
  48451. {
  48452. Component* const c = localComps.getUnchecked (i);
  48453. if (c->getWantsKeyboardFocus())
  48454. comps.add (c);
  48455. if (! c->isFocusContainer())
  48456. findAllFocusableComponents (c, comps);
  48457. }
  48458. }
  48459. }
  48460. }
  48461. static Component* getIncrementedComponent (Component* const current, const int delta)
  48462. {
  48463. Component* focusContainer = current->getParentComponent();
  48464. if (focusContainer != 0)
  48465. {
  48466. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  48467. focusContainer = focusContainer->getParentComponent();
  48468. if (focusContainer != 0)
  48469. {
  48470. Array <Component*> comps;
  48471. KeyboardFocusHelpers::findAllFocusableComponents (focusContainer, comps);
  48472. if (comps.size() > 0)
  48473. {
  48474. const int index = comps.indexOf (current);
  48475. return comps [(index + comps.size() + delta) % comps.size()];
  48476. }
  48477. }
  48478. }
  48479. return 0;
  48480. }
  48481. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  48482. {
  48483. return getIncrementedComponent (current, 1);
  48484. }
  48485. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  48486. {
  48487. return getIncrementedComponent (current, -1);
  48488. }
  48489. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  48490. {
  48491. Array <Component*> comps;
  48492. if (parentComponent != 0)
  48493. KeyboardFocusHelpers::findAllFocusableComponents (parentComponent, comps);
  48494. return comps.getFirst();
  48495. }
  48496. END_JUCE_NAMESPACE
  48497. /*** End of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48498. /*** Start of inlined file: juce_KeyListener.cpp ***/
  48499. BEGIN_JUCE_NAMESPACE
  48500. bool KeyListener::keyStateChanged (const bool, Component*)
  48501. {
  48502. return false;
  48503. }
  48504. END_JUCE_NAMESPACE
  48505. /*** End of inlined file: juce_KeyListener.cpp ***/
  48506. /*** Start of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48507. BEGIN_JUCE_NAMESPACE
  48508. // N.B. these two includes are put here deliberately to avoid problems with
  48509. // old GCCs failing on long include paths
  48510. const int maxKeys = 3;
  48511. class KeyMappingChangeButton : public Button
  48512. {
  48513. public:
  48514. KeyMappingChangeButton (KeyMappingEditorComponent* const owner_,
  48515. const CommandID commandID_,
  48516. const String& keyName,
  48517. const int keyNum_)
  48518. : Button (keyName),
  48519. owner (owner_),
  48520. commandID (commandID_),
  48521. keyNum (keyNum_)
  48522. {
  48523. setWantsKeyboardFocus (false);
  48524. setTriggeredOnMouseDown (keyNum >= 0);
  48525. if (keyNum_ < 0)
  48526. setTooltip (TRANS("adds a new key-mapping"));
  48527. else
  48528. setTooltip (TRANS("click to change this key-mapping"));
  48529. }
  48530. ~KeyMappingChangeButton()
  48531. {
  48532. }
  48533. void paintButton (Graphics& g, bool /*isOver*/, bool /*isDown*/)
  48534. {
  48535. getLookAndFeel().drawKeymapChangeButton (g, getWidth(), getHeight(), *this,
  48536. keyNum >= 0 ? getName() : String::empty);
  48537. }
  48538. void clicked()
  48539. {
  48540. if (keyNum >= 0)
  48541. {
  48542. // existing key clicked..
  48543. PopupMenu m;
  48544. m.addItem (1, TRANS("change this key-mapping"));
  48545. m.addSeparator();
  48546. m.addItem (2, TRANS("remove this key-mapping"));
  48547. const int res = m.show();
  48548. if (res == 1)
  48549. {
  48550. owner->assignNewKey (commandID, keyNum);
  48551. }
  48552. else if (res == 2)
  48553. {
  48554. owner->getMappings()->removeKeyPress (commandID, keyNum);
  48555. }
  48556. }
  48557. else
  48558. {
  48559. // + button pressed..
  48560. owner->assignNewKey (commandID, -1);
  48561. }
  48562. }
  48563. void fitToContent (const int h) throw()
  48564. {
  48565. if (keyNum < 0)
  48566. {
  48567. setSize (h, h);
  48568. }
  48569. else
  48570. {
  48571. Font f (h * 0.6f);
  48572. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  48573. }
  48574. }
  48575. juce_UseDebuggingNewOperator
  48576. private:
  48577. KeyMappingEditorComponent* const owner;
  48578. const CommandID commandID;
  48579. const int keyNum;
  48580. KeyMappingChangeButton (const KeyMappingChangeButton&);
  48581. KeyMappingChangeButton& operator= (const KeyMappingChangeButton&);
  48582. };
  48583. class KeyMappingItemComponent : public Component
  48584. {
  48585. public:
  48586. KeyMappingItemComponent (KeyMappingEditorComponent* const owner_,
  48587. const CommandID commandID_)
  48588. : owner (owner_),
  48589. commandID (commandID_)
  48590. {
  48591. setInterceptsMouseClicks (false, true);
  48592. const bool isReadOnly = owner_->isCommandReadOnly (commandID);
  48593. const Array <KeyPress> keyPresses (owner_->getMappings()->getKeyPressesAssignedToCommand (commandID));
  48594. for (int i = 0; i < jmin (maxKeys, keyPresses.size()); ++i)
  48595. {
  48596. KeyMappingChangeButton* const kb
  48597. = new KeyMappingChangeButton (owner_, commandID,
  48598. owner_->getDescriptionForKeyPress (keyPresses.getReference (i)), i);
  48599. kb->setEnabled (! isReadOnly);
  48600. addAndMakeVisible (kb);
  48601. }
  48602. KeyMappingChangeButton* const kb
  48603. = new KeyMappingChangeButton (owner_, commandID, String::empty, -1);
  48604. addChildComponent (kb);
  48605. kb->setVisible (keyPresses.size() < maxKeys && ! isReadOnly);
  48606. }
  48607. ~KeyMappingItemComponent()
  48608. {
  48609. deleteAllChildren();
  48610. }
  48611. void paint (Graphics& g)
  48612. {
  48613. g.setFont (getHeight() * 0.7f);
  48614. g.setColour (findColour (KeyMappingEditorComponent::textColourId));
  48615. g.drawFittedText (owner->getMappings()->getCommandManager()->getNameOfCommand (commandID),
  48616. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  48617. Justification::centredLeft, true);
  48618. }
  48619. void resized()
  48620. {
  48621. int x = getWidth() - 4;
  48622. for (int i = getNumChildComponents(); --i >= 0;)
  48623. {
  48624. KeyMappingChangeButton* const kb = dynamic_cast <KeyMappingChangeButton*> (getChildComponent (i));
  48625. kb->fitToContent (getHeight() - 2);
  48626. kb->setTopRightPosition (x, 1);
  48627. x -= kb->getWidth() + 5;
  48628. }
  48629. }
  48630. juce_UseDebuggingNewOperator
  48631. private:
  48632. KeyMappingEditorComponent* const owner;
  48633. const CommandID commandID;
  48634. KeyMappingItemComponent (const KeyMappingItemComponent&);
  48635. KeyMappingItemComponent& operator= (const KeyMappingItemComponent&);
  48636. };
  48637. class KeyMappingTreeViewItem : public TreeViewItem
  48638. {
  48639. public:
  48640. KeyMappingTreeViewItem (KeyMappingEditorComponent* const owner_,
  48641. const CommandID commandID_)
  48642. : owner (owner_),
  48643. commandID (commandID_)
  48644. {
  48645. }
  48646. ~KeyMappingTreeViewItem()
  48647. {
  48648. }
  48649. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  48650. bool mightContainSubItems() { return false; }
  48651. int getItemHeight() const { return 20; }
  48652. Component* createItemComponent()
  48653. {
  48654. return new KeyMappingItemComponent (owner, commandID);
  48655. }
  48656. juce_UseDebuggingNewOperator
  48657. private:
  48658. KeyMappingEditorComponent* const owner;
  48659. const CommandID commandID;
  48660. KeyMappingTreeViewItem (const KeyMappingTreeViewItem&);
  48661. KeyMappingTreeViewItem& operator= (const KeyMappingTreeViewItem&);
  48662. };
  48663. class KeyCategoryTreeViewItem : public TreeViewItem
  48664. {
  48665. public:
  48666. KeyCategoryTreeViewItem (KeyMappingEditorComponent* const owner_,
  48667. const String& name)
  48668. : owner (owner_),
  48669. categoryName (name)
  48670. {
  48671. }
  48672. ~KeyCategoryTreeViewItem()
  48673. {
  48674. }
  48675. const String getUniqueName() const { return categoryName + "_cat"; }
  48676. bool mightContainSubItems() { return true; }
  48677. int getItemHeight() const { return 28; }
  48678. void paintItem (Graphics& g, int width, int height)
  48679. {
  48680. g.setFont (height * 0.6f, Font::bold);
  48681. g.setColour (owner->findColour (KeyMappingEditorComponent::textColourId));
  48682. g.drawText (categoryName,
  48683. 2, 0, width - 2, height,
  48684. Justification::centredLeft, true);
  48685. }
  48686. void itemOpennessChanged (bool isNowOpen)
  48687. {
  48688. if (isNowOpen)
  48689. {
  48690. if (getNumSubItems() == 0)
  48691. {
  48692. Array <CommandID> commands (owner->getMappings()->getCommandManager()->getCommandsInCategory (categoryName));
  48693. for (int i = 0; i < commands.size(); ++i)
  48694. {
  48695. if (owner->shouldCommandBeIncluded (commands[i]))
  48696. addSubItem (new KeyMappingTreeViewItem (owner, commands[i]));
  48697. }
  48698. }
  48699. }
  48700. else
  48701. {
  48702. clearSubItems();
  48703. }
  48704. }
  48705. juce_UseDebuggingNewOperator
  48706. private:
  48707. KeyMappingEditorComponent* owner;
  48708. String categoryName;
  48709. KeyCategoryTreeViewItem (const KeyCategoryTreeViewItem&);
  48710. KeyCategoryTreeViewItem& operator= (const KeyCategoryTreeViewItem&);
  48711. };
  48712. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet* const mappingManager,
  48713. const bool showResetToDefaultButton)
  48714. : mappings (mappingManager)
  48715. {
  48716. jassert (mappingManager != 0); // can't be null!
  48717. mappingManager->addChangeListener (this);
  48718. setLinesDrawnForSubItems (false);
  48719. resetButton = 0;
  48720. if (showResetToDefaultButton)
  48721. {
  48722. addAndMakeVisible (resetButton = new TextButton (TRANS("reset to defaults")));
  48723. resetButton->addButtonListener (this);
  48724. }
  48725. addAndMakeVisible (tree = new TreeView());
  48726. tree->setColour (TreeView::backgroundColourId, findColour (backgroundColourId));
  48727. tree->setRootItemVisible (false);
  48728. tree->setDefaultOpenness (true);
  48729. tree->setRootItem (this);
  48730. }
  48731. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  48732. {
  48733. mappings->removeChangeListener (this);
  48734. deleteAllChildren();
  48735. }
  48736. bool KeyMappingEditorComponent::mightContainSubItems()
  48737. {
  48738. return true;
  48739. }
  48740. const String KeyMappingEditorComponent::getUniqueName() const
  48741. {
  48742. return "keys";
  48743. }
  48744. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  48745. const Colour& textColour)
  48746. {
  48747. setColour (backgroundColourId, mainBackground);
  48748. setColour (textColourId, textColour);
  48749. tree->setColour (TreeView::backgroundColourId, mainBackground);
  48750. }
  48751. void KeyMappingEditorComponent::parentHierarchyChanged()
  48752. {
  48753. changeListenerCallback (0);
  48754. }
  48755. void KeyMappingEditorComponent::resized()
  48756. {
  48757. int h = getHeight();
  48758. if (resetButton != 0)
  48759. {
  48760. const int buttonHeight = 20;
  48761. h -= buttonHeight + 8;
  48762. int x = getWidth() - 8;
  48763. resetButton->changeWidthToFitText (buttonHeight);
  48764. resetButton->setTopRightPosition (x, h + 6);
  48765. }
  48766. tree->setBounds (0, 0, getWidth(), h);
  48767. }
  48768. void KeyMappingEditorComponent::buttonClicked (Button* button)
  48769. {
  48770. if (button == resetButton)
  48771. {
  48772. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  48773. TRANS("Reset to defaults"),
  48774. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  48775. TRANS("Reset")))
  48776. {
  48777. mappings->resetToDefaultMappings();
  48778. }
  48779. }
  48780. }
  48781. void KeyMappingEditorComponent::changeListenerCallback (void*)
  48782. {
  48783. ScopedPointer <XmlElement> oldOpenness (tree->getOpennessState (true));
  48784. clearSubItems();
  48785. const StringArray categories (mappings->getCommandManager()->getCommandCategories());
  48786. for (int i = 0; i < categories.size(); ++i)
  48787. {
  48788. const Array <CommandID> commands (mappings->getCommandManager()->getCommandsInCategory (categories[i]));
  48789. int count = 0;
  48790. for (int j = 0; j < commands.size(); ++j)
  48791. if (shouldCommandBeIncluded (commands[j]))
  48792. ++count;
  48793. if (count > 0)
  48794. addSubItem (new KeyCategoryTreeViewItem (this, categories[i]));
  48795. }
  48796. if (oldOpenness != 0)
  48797. tree->restoreOpennessState (*oldOpenness);
  48798. }
  48799. class KeyEntryWindow : public AlertWindow
  48800. {
  48801. public:
  48802. KeyEntryWindow (KeyMappingEditorComponent* const owner_)
  48803. : AlertWindow (TRANS("New key-mapping"),
  48804. TRANS("Please press a key combination now..."),
  48805. AlertWindow::NoIcon),
  48806. owner (owner_)
  48807. {
  48808. addButton (TRANS("ok"), 1);
  48809. addButton (TRANS("cancel"), 0);
  48810. // (avoid return + escape keys getting processed by the buttons..)
  48811. for (int i = getNumChildComponents(); --i >= 0;)
  48812. getChildComponent (i)->setWantsKeyboardFocus (false);
  48813. setWantsKeyboardFocus (true);
  48814. grabKeyboardFocus();
  48815. }
  48816. ~KeyEntryWindow()
  48817. {
  48818. }
  48819. bool keyPressed (const KeyPress& key)
  48820. {
  48821. lastPress = key;
  48822. String message (TRANS("Key: ") + owner->getDescriptionForKeyPress (key));
  48823. const CommandID previousCommand = owner->getMappings()->findCommandForKeyPress (key);
  48824. if (previousCommand != 0)
  48825. {
  48826. message << "\n\n"
  48827. << TRANS("(Currently assigned to \"")
  48828. << owner->getMappings()->getCommandManager()->getNameOfCommand (previousCommand)
  48829. << "\")";
  48830. }
  48831. setMessage (message);
  48832. return true;
  48833. }
  48834. bool keyStateChanged (bool)
  48835. {
  48836. return true;
  48837. }
  48838. KeyPress lastPress;
  48839. juce_UseDebuggingNewOperator
  48840. private:
  48841. KeyMappingEditorComponent* owner;
  48842. KeyEntryWindow (const KeyEntryWindow&);
  48843. KeyEntryWindow& operator= (const KeyEntryWindow&);
  48844. };
  48845. void KeyMappingEditorComponent::assignNewKey (const CommandID commandID, const int index)
  48846. {
  48847. KeyEntryWindow entryWindow (this);
  48848. if (entryWindow.runModalLoop() != 0)
  48849. {
  48850. entryWindow.setVisible (false);
  48851. if (entryWindow.lastPress.isValid())
  48852. {
  48853. const CommandID previousCommand = mappings->findCommandForKeyPress (entryWindow.lastPress);
  48854. if (previousCommand != 0)
  48855. {
  48856. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  48857. TRANS("Change key-mapping"),
  48858. TRANS("This key is already assigned to the command \"")
  48859. + mappings->getCommandManager()->getNameOfCommand (previousCommand)
  48860. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  48861. TRANS("re-assign"),
  48862. TRANS("cancel")))
  48863. {
  48864. return;
  48865. }
  48866. }
  48867. mappings->removeKeyPress (entryWindow.lastPress);
  48868. if (index >= 0)
  48869. mappings->removeKeyPress (commandID, index);
  48870. mappings->addKeyPress (commandID, entryWindow.lastPress, index);
  48871. }
  48872. }
  48873. }
  48874. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  48875. {
  48876. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  48877. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0);
  48878. }
  48879. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  48880. {
  48881. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  48882. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0);
  48883. }
  48884. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  48885. {
  48886. return key.getTextDescription();
  48887. }
  48888. END_JUCE_NAMESPACE
  48889. /*** End of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48890. /*** Start of inlined file: juce_KeyPress.cpp ***/
  48891. BEGIN_JUCE_NAMESPACE
  48892. KeyPress::KeyPress() throw()
  48893. : keyCode (0),
  48894. mods (0),
  48895. textCharacter (0)
  48896. {
  48897. }
  48898. KeyPress::KeyPress (const int keyCode_,
  48899. const ModifierKeys& mods_,
  48900. const juce_wchar textCharacter_) throw()
  48901. : keyCode (keyCode_),
  48902. mods (mods_),
  48903. textCharacter (textCharacter_)
  48904. {
  48905. }
  48906. KeyPress::KeyPress (const int keyCode_) throw()
  48907. : keyCode (keyCode_),
  48908. textCharacter (0)
  48909. {
  48910. }
  48911. KeyPress::KeyPress (const KeyPress& other) throw()
  48912. : keyCode (other.keyCode),
  48913. mods (other.mods),
  48914. textCharacter (other.textCharacter)
  48915. {
  48916. }
  48917. KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  48918. {
  48919. keyCode = other.keyCode;
  48920. mods = other.mods;
  48921. textCharacter = other.textCharacter;
  48922. return *this;
  48923. }
  48924. bool KeyPress::operator== (const KeyPress& other) const throw()
  48925. {
  48926. return mods.getRawFlags() == other.mods.getRawFlags()
  48927. && (textCharacter == other.textCharacter
  48928. || textCharacter == 0
  48929. || other.textCharacter == 0)
  48930. && (keyCode == other.keyCode
  48931. || (keyCode < 256
  48932. && other.keyCode < 256
  48933. && CharacterFunctions::toLowerCase ((juce_wchar) keyCode)
  48934. == CharacterFunctions::toLowerCase ((juce_wchar) other.keyCode)));
  48935. }
  48936. bool KeyPress::operator!= (const KeyPress& other) const throw()
  48937. {
  48938. return ! operator== (other);
  48939. }
  48940. bool KeyPress::isCurrentlyDown() const
  48941. {
  48942. return isKeyCurrentlyDown (keyCode)
  48943. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  48944. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  48945. }
  48946. namespace KeyPressHelpers
  48947. {
  48948. struct KeyNameAndCode
  48949. {
  48950. const char* name;
  48951. int code;
  48952. };
  48953. static const KeyNameAndCode translations[] =
  48954. {
  48955. { "spacebar", KeyPress::spaceKey },
  48956. { "return", KeyPress::returnKey },
  48957. { "escape", KeyPress::escapeKey },
  48958. { "backspace", KeyPress::backspaceKey },
  48959. { "cursor left", KeyPress::leftKey },
  48960. { "cursor right", KeyPress::rightKey },
  48961. { "cursor up", KeyPress::upKey },
  48962. { "cursor down", KeyPress::downKey },
  48963. { "page up", KeyPress::pageUpKey },
  48964. { "page down", KeyPress::pageDownKey },
  48965. { "home", KeyPress::homeKey },
  48966. { "end", KeyPress::endKey },
  48967. { "delete", KeyPress::deleteKey },
  48968. { "insert", KeyPress::insertKey },
  48969. { "tab", KeyPress::tabKey },
  48970. { "play", KeyPress::playKey },
  48971. { "stop", KeyPress::stopKey },
  48972. { "fast forward", KeyPress::fastForwardKey },
  48973. { "rewind", KeyPress::rewindKey }
  48974. };
  48975. static const String numberPadPrefix() { return "numpad "; }
  48976. }
  48977. const KeyPress KeyPress::createFromDescription (const String& desc)
  48978. {
  48979. int modifiers = 0;
  48980. if (desc.containsWholeWordIgnoreCase ("ctrl")
  48981. || desc.containsWholeWordIgnoreCase ("control")
  48982. || desc.containsWholeWordIgnoreCase ("ctl"))
  48983. modifiers |= ModifierKeys::ctrlModifier;
  48984. if (desc.containsWholeWordIgnoreCase ("shift")
  48985. || desc.containsWholeWordIgnoreCase ("shft"))
  48986. modifiers |= ModifierKeys::shiftModifier;
  48987. if (desc.containsWholeWordIgnoreCase ("alt")
  48988. || desc.containsWholeWordIgnoreCase ("option"))
  48989. modifiers |= ModifierKeys::altModifier;
  48990. if (desc.containsWholeWordIgnoreCase ("command")
  48991. || desc.containsWholeWordIgnoreCase ("cmd"))
  48992. modifiers |= ModifierKeys::commandModifier;
  48993. int key = 0;
  48994. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  48995. {
  48996. if (desc.containsWholeWordIgnoreCase (String (KeyPressHelpers::translations[i].name)))
  48997. {
  48998. key = KeyPressHelpers::translations[i].code;
  48999. break;
  49000. }
  49001. }
  49002. if (key == 0)
  49003. {
  49004. // see if it's a numpad key..
  49005. if (desc.containsIgnoreCase (KeyPressHelpers::numberPadPrefix()))
  49006. {
  49007. const juce_wchar lastChar = desc.trimEnd().getLastCharacter();
  49008. if (lastChar >= '0' && lastChar <= '9')
  49009. key = numberPad0 + lastChar - '0';
  49010. else if (lastChar == '+')
  49011. key = numberPadAdd;
  49012. else if (lastChar == '-')
  49013. key = numberPadSubtract;
  49014. else if (lastChar == '*')
  49015. key = numberPadMultiply;
  49016. else if (lastChar == '/')
  49017. key = numberPadDivide;
  49018. else if (lastChar == '.')
  49019. key = numberPadDecimalPoint;
  49020. else if (lastChar == '=')
  49021. key = numberPadEquals;
  49022. else if (desc.endsWith ("separator"))
  49023. key = numberPadSeparator;
  49024. else if (desc.endsWith ("delete"))
  49025. key = numberPadDelete;
  49026. }
  49027. if (key == 0)
  49028. {
  49029. // see if it's a function key..
  49030. if (! desc.containsChar ('#')) // avoid mistaking hex-codes like "#f1"
  49031. for (int i = 1; i <= 12; ++i)
  49032. if (desc.containsWholeWordIgnoreCase ("f" + String (i)))
  49033. key = F1Key + i - 1;
  49034. if (key == 0)
  49035. {
  49036. // give up and use the hex code..
  49037. const int hexCode = desc.fromFirstOccurrenceOf ("#", false, false)
  49038. .toLowerCase()
  49039. .retainCharacters ("0123456789abcdef")
  49040. .getHexValue32();
  49041. if (hexCode > 0)
  49042. key = hexCode;
  49043. else
  49044. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  49045. }
  49046. }
  49047. }
  49048. return KeyPress (key, ModifierKeys (modifiers), 0);
  49049. }
  49050. const String KeyPress::getTextDescription() const
  49051. {
  49052. String desc;
  49053. if (keyCode > 0)
  49054. {
  49055. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  49056. // want to store it as being a slash, not shift+whatever.
  49057. if (textCharacter == '/')
  49058. return "/";
  49059. if (mods.isCtrlDown())
  49060. desc << "ctrl + ";
  49061. if (mods.isShiftDown())
  49062. desc << "shift + ";
  49063. #if JUCE_MAC
  49064. // only do this on the mac, because on Windows ctrl and command are the same,
  49065. // and this would get confusing
  49066. if (mods.isCommandDown())
  49067. desc << "command + ";
  49068. if (mods.isAltDown())
  49069. desc << "option + ";
  49070. #else
  49071. if (mods.isAltDown())
  49072. desc << "alt + ";
  49073. #endif
  49074. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  49075. if (keyCode == KeyPressHelpers::translations[i].code)
  49076. return desc + KeyPressHelpers::translations[i].name;
  49077. if (keyCode >= F1Key && keyCode <= F16Key)
  49078. desc << 'F' << (1 + keyCode - F1Key);
  49079. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  49080. desc << KeyPressHelpers::numberPadPrefix() << (keyCode - numberPad0);
  49081. else if (keyCode >= 33 && keyCode < 176)
  49082. desc += CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  49083. else if (keyCode == numberPadAdd)
  49084. desc << KeyPressHelpers::numberPadPrefix() << '+';
  49085. else if (keyCode == numberPadSubtract)
  49086. desc << KeyPressHelpers::numberPadPrefix() << '-';
  49087. else if (keyCode == numberPadMultiply)
  49088. desc << KeyPressHelpers::numberPadPrefix() << '*';
  49089. else if (keyCode == numberPadDivide)
  49090. desc << KeyPressHelpers::numberPadPrefix() << '/';
  49091. else if (keyCode == numberPadSeparator)
  49092. desc << KeyPressHelpers::numberPadPrefix() << "separator";
  49093. else if (keyCode == numberPadDecimalPoint)
  49094. desc << KeyPressHelpers::numberPadPrefix() << '.';
  49095. else if (keyCode == numberPadDelete)
  49096. desc << KeyPressHelpers::numberPadPrefix() << "delete";
  49097. else
  49098. desc << '#' << String::toHexString (keyCode);
  49099. }
  49100. return desc;
  49101. }
  49102. END_JUCE_NAMESPACE
  49103. /*** End of inlined file: juce_KeyPress.cpp ***/
  49104. /*** Start of inlined file: juce_KeyPressMappingSet.cpp ***/
  49105. BEGIN_JUCE_NAMESPACE
  49106. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_)
  49107. : commandManager (commandManager_)
  49108. {
  49109. // A manager is needed to get the descriptions of commands, and will be called when
  49110. // a command is invoked. So you can't leave this null..
  49111. jassert (commandManager_ != 0);
  49112. Desktop::getInstance().addFocusChangeListener (this);
  49113. }
  49114. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other)
  49115. : commandManager (other.commandManager)
  49116. {
  49117. Desktop::getInstance().addFocusChangeListener (this);
  49118. }
  49119. KeyPressMappingSet::~KeyPressMappingSet()
  49120. {
  49121. Desktop::getInstance().removeFocusChangeListener (this);
  49122. }
  49123. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const
  49124. {
  49125. for (int i = 0; i < mappings.size(); ++i)
  49126. if (mappings.getUnchecked(i)->commandID == commandID)
  49127. return mappings.getUnchecked (i)->keypresses;
  49128. return Array <KeyPress> ();
  49129. }
  49130. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  49131. const KeyPress& newKeyPress,
  49132. int insertIndex)
  49133. {
  49134. // If you specify an upper-case letter but no shift key, how is the user supposed to press it!?
  49135. // Stick to lower-case letters when defining a keypress, to avoid ambiguity.
  49136. jassert (! (CharacterFunctions::isUpperCase (newKeyPress.getTextCharacter())
  49137. && ! newKeyPress.getModifiers().isShiftDown()));
  49138. if (findCommandForKeyPress (newKeyPress) != commandID)
  49139. {
  49140. removeKeyPress (newKeyPress);
  49141. if (newKeyPress.isValid())
  49142. {
  49143. for (int i = mappings.size(); --i >= 0;)
  49144. {
  49145. if (mappings.getUnchecked(i)->commandID == commandID)
  49146. {
  49147. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  49148. sendChangeMessage (this);
  49149. return;
  49150. }
  49151. }
  49152. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49153. if (ci != 0)
  49154. {
  49155. CommandMapping* const cm = new CommandMapping();
  49156. cm->commandID = commandID;
  49157. cm->keypresses.add (newKeyPress);
  49158. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  49159. mappings.add (cm);
  49160. sendChangeMessage (this);
  49161. }
  49162. }
  49163. }
  49164. }
  49165. void KeyPressMappingSet::resetToDefaultMappings()
  49166. {
  49167. mappings.clear();
  49168. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  49169. {
  49170. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  49171. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  49172. {
  49173. addKeyPress (ci->commandID,
  49174. ci->defaultKeypresses.getReference (j));
  49175. }
  49176. }
  49177. sendChangeMessage (this);
  49178. }
  49179. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID)
  49180. {
  49181. clearAllKeyPresses (commandID);
  49182. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49183. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  49184. {
  49185. addKeyPress (ci->commandID,
  49186. ci->defaultKeypresses.getReference (j));
  49187. }
  49188. }
  49189. void KeyPressMappingSet::clearAllKeyPresses()
  49190. {
  49191. if (mappings.size() > 0)
  49192. {
  49193. sendChangeMessage (this);
  49194. mappings.clear();
  49195. }
  49196. }
  49197. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID)
  49198. {
  49199. for (int i = mappings.size(); --i >= 0;)
  49200. {
  49201. if (mappings.getUnchecked(i)->commandID == commandID)
  49202. {
  49203. mappings.remove (i);
  49204. sendChangeMessage (this);
  49205. }
  49206. }
  49207. }
  49208. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress)
  49209. {
  49210. if (keypress.isValid())
  49211. {
  49212. for (int i = mappings.size(); --i >= 0;)
  49213. {
  49214. CommandMapping* const cm = mappings.getUnchecked(i);
  49215. for (int j = cm->keypresses.size(); --j >= 0;)
  49216. {
  49217. if (keypress == cm->keypresses [j])
  49218. {
  49219. cm->keypresses.remove (j);
  49220. sendChangeMessage (this);
  49221. }
  49222. }
  49223. }
  49224. }
  49225. }
  49226. void KeyPressMappingSet::removeKeyPress (const CommandID commandID, const int keyPressIndex)
  49227. {
  49228. for (int i = mappings.size(); --i >= 0;)
  49229. {
  49230. if (mappings.getUnchecked(i)->commandID == commandID)
  49231. {
  49232. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  49233. sendChangeMessage (this);
  49234. break;
  49235. }
  49236. }
  49237. }
  49238. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  49239. {
  49240. for (int i = 0; i < mappings.size(); ++i)
  49241. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  49242. return mappings.getUnchecked(i)->commandID;
  49243. return 0;
  49244. }
  49245. bool KeyPressMappingSet::containsMapping (const CommandID commandID, const KeyPress& keyPress) const throw()
  49246. {
  49247. for (int i = mappings.size(); --i >= 0;)
  49248. if (mappings.getUnchecked(i)->commandID == commandID)
  49249. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  49250. return false;
  49251. }
  49252. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  49253. const KeyPress& key,
  49254. const bool isKeyDown,
  49255. const int millisecsSinceKeyPressed,
  49256. Component* const originatingComponent) const
  49257. {
  49258. ApplicationCommandTarget::InvocationInfo info (commandID);
  49259. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  49260. info.isKeyDown = isKeyDown;
  49261. info.keyPress = key;
  49262. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  49263. info.originatingComponent = originatingComponent;
  49264. commandManager->invoke (info, false);
  49265. }
  49266. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  49267. {
  49268. if (xmlVersion.hasTagName ("KEYMAPPINGS"))
  49269. {
  49270. if (xmlVersion.getBoolAttribute ("basedOnDefaults", true))
  49271. {
  49272. // if the XML was created as a set of differences from the default mappings,
  49273. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  49274. resetToDefaultMappings();
  49275. }
  49276. else
  49277. {
  49278. // if the XML was created calling createXml (false), then we need to clear all
  49279. // the keys and treat the xml as describing the entire set of mappings.
  49280. clearAllKeyPresses();
  49281. }
  49282. forEachXmlChildElement (xmlVersion, map)
  49283. {
  49284. const CommandID commandId = map->getStringAttribute ("commandId").getHexValue32();
  49285. if (commandId != 0)
  49286. {
  49287. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute ("key")));
  49288. if (map->hasTagName ("MAPPING"))
  49289. {
  49290. addKeyPress (commandId, key);
  49291. }
  49292. else if (map->hasTagName ("UNMAPPING"))
  49293. {
  49294. if (containsMapping (commandId, key))
  49295. removeKeyPress (key);
  49296. }
  49297. }
  49298. }
  49299. return true;
  49300. }
  49301. return false;
  49302. }
  49303. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  49304. {
  49305. ScopedPointer <KeyPressMappingSet> defaultSet;
  49306. if (saveDifferencesFromDefaultSet)
  49307. {
  49308. defaultSet = new KeyPressMappingSet (commandManager);
  49309. defaultSet->resetToDefaultMappings();
  49310. }
  49311. XmlElement* const doc = new XmlElement ("KEYMAPPINGS");
  49312. doc->setAttribute ("basedOnDefaults", saveDifferencesFromDefaultSet);
  49313. int i;
  49314. for (i = 0; i < mappings.size(); ++i)
  49315. {
  49316. const CommandMapping* const cm = mappings.getUnchecked(i);
  49317. for (int j = 0; j < cm->keypresses.size(); ++j)
  49318. {
  49319. if (defaultSet == 0
  49320. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  49321. {
  49322. XmlElement* const map = doc->createNewChildElement ("MAPPING");
  49323. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  49324. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  49325. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  49326. }
  49327. }
  49328. }
  49329. if (defaultSet != 0)
  49330. {
  49331. for (i = 0; i < defaultSet->mappings.size(); ++i)
  49332. {
  49333. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  49334. for (int j = 0; j < cm->keypresses.size(); ++j)
  49335. {
  49336. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  49337. {
  49338. XmlElement* const map = doc->createNewChildElement ("UNMAPPING");
  49339. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  49340. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  49341. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  49342. }
  49343. }
  49344. }
  49345. }
  49346. return doc;
  49347. }
  49348. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  49349. Component* originatingComponent)
  49350. {
  49351. bool used = false;
  49352. const CommandID commandID = findCommandForKeyPress (key);
  49353. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49354. if (ci != 0
  49355. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  49356. {
  49357. ApplicationCommandInfo info (0);
  49358. if (commandManager->getTargetForCommand (commandID, info) != 0
  49359. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  49360. {
  49361. invokeCommand (commandID, key, true, 0, originatingComponent);
  49362. used = true;
  49363. }
  49364. else
  49365. {
  49366. if (originatingComponent != 0)
  49367. originatingComponent->getLookAndFeel().playAlertSound();
  49368. }
  49369. }
  49370. return used;
  49371. }
  49372. bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent)
  49373. {
  49374. bool used = false;
  49375. const uint32 now = Time::getMillisecondCounter();
  49376. for (int i = mappings.size(); --i >= 0;)
  49377. {
  49378. CommandMapping* const cm = mappings.getUnchecked(i);
  49379. if (cm->wantsKeyUpDownCallbacks)
  49380. {
  49381. for (int j = cm->keypresses.size(); --j >= 0;)
  49382. {
  49383. const KeyPress key (cm->keypresses.getReference (j));
  49384. const bool isDown = key.isCurrentlyDown();
  49385. int keyPressEntryIndex = 0;
  49386. bool wasDown = false;
  49387. for (int k = keysDown.size(); --k >= 0;)
  49388. {
  49389. if (key == keysDown.getUnchecked(k)->key)
  49390. {
  49391. keyPressEntryIndex = k;
  49392. wasDown = true;
  49393. used = true;
  49394. break;
  49395. }
  49396. }
  49397. if (isDown != wasDown)
  49398. {
  49399. int millisecs = 0;
  49400. if (isDown)
  49401. {
  49402. KeyPressTime* const k = new KeyPressTime();
  49403. k->key = key;
  49404. k->timeWhenPressed = now;
  49405. keysDown.add (k);
  49406. }
  49407. else
  49408. {
  49409. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  49410. if (now > pressTime)
  49411. millisecs = now - pressTime;
  49412. keysDown.remove (keyPressEntryIndex);
  49413. }
  49414. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  49415. used = true;
  49416. }
  49417. }
  49418. }
  49419. }
  49420. return used;
  49421. }
  49422. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  49423. {
  49424. if (focusedComponent != 0)
  49425. focusedComponent->keyStateChanged (false);
  49426. }
  49427. END_JUCE_NAMESPACE
  49428. /*** End of inlined file: juce_KeyPressMappingSet.cpp ***/
  49429. /*** Start of inlined file: juce_ModifierKeys.cpp ***/
  49430. BEGIN_JUCE_NAMESPACE
  49431. ModifierKeys::ModifierKeys (const int flags_) throw()
  49432. : flags (flags_)
  49433. {
  49434. }
  49435. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  49436. : flags (other.flags)
  49437. {
  49438. }
  49439. ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  49440. {
  49441. flags = other.flags;
  49442. return *this;
  49443. }
  49444. ModifierKeys ModifierKeys::currentModifiers;
  49445. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  49446. {
  49447. return currentModifiers;
  49448. }
  49449. int ModifierKeys::getNumMouseButtonsDown() const throw()
  49450. {
  49451. int num = 0;
  49452. if (isLeftButtonDown()) ++num;
  49453. if (isRightButtonDown()) ++num;
  49454. if (isMiddleButtonDown()) ++num;
  49455. return num;
  49456. }
  49457. END_JUCE_NAMESPACE
  49458. /*** End of inlined file: juce_ModifierKeys.cpp ***/
  49459. /*** Start of inlined file: juce_ComponentAnimator.cpp ***/
  49460. BEGIN_JUCE_NAMESPACE
  49461. class ComponentAnimator::AnimationTask
  49462. {
  49463. public:
  49464. AnimationTask (Component* const comp)
  49465. : component (comp)
  49466. {
  49467. }
  49468. bool useTimeslice (const int elapsed)
  49469. {
  49470. if (component == 0)
  49471. return false;
  49472. msElapsed += elapsed;
  49473. double newProgress = msElapsed / (double) msTotal;
  49474. if (newProgress >= 0 && newProgress < 1.0)
  49475. {
  49476. newProgress = timeToDistance (newProgress);
  49477. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  49478. jassert (newProgress >= lastProgress);
  49479. lastProgress = newProgress;
  49480. left += (destination.getX() - left) * delta;
  49481. top += (destination.getY() - top) * delta;
  49482. right += (destination.getRight() - right) * delta;
  49483. bottom += (destination.getBottom() - bottom) * delta;
  49484. if (delta < 1.0)
  49485. {
  49486. const Rectangle<int> newBounds (roundToInt (left),
  49487. roundToInt (top),
  49488. roundToInt (right - left),
  49489. roundToInt (bottom - top));
  49490. if (newBounds != destination)
  49491. {
  49492. component->setBounds (newBounds);
  49493. return true;
  49494. }
  49495. }
  49496. }
  49497. component->setBounds (destination);
  49498. return false;
  49499. }
  49500. void moveToFinalDestination()
  49501. {
  49502. if (component != 0)
  49503. component->setBounds (destination);
  49504. }
  49505. Component::SafePointer<Component> component;
  49506. Rectangle<int> destination;
  49507. int msElapsed, msTotal;
  49508. double startSpeed, midSpeed, endSpeed, lastProgress;
  49509. double left, top, right, bottom;
  49510. private:
  49511. inline double timeToDistance (const double time) const
  49512. {
  49513. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  49514. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  49515. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  49516. }
  49517. };
  49518. ComponentAnimator::ComponentAnimator()
  49519. : lastTime (0)
  49520. {
  49521. }
  49522. ComponentAnimator::~ComponentAnimator()
  49523. {
  49524. }
  49525. ComponentAnimator::AnimationTask* ComponentAnimator::findTaskFor (Component* const component) const
  49526. {
  49527. for (int i = tasks.size(); --i >= 0;)
  49528. if (component == tasks.getUnchecked(i)->component.getComponent())
  49529. return tasks.getUnchecked(i);
  49530. return 0;
  49531. }
  49532. void ComponentAnimator::animateComponent (Component* const component,
  49533. const Rectangle<int>& finalPosition,
  49534. const int millisecondsToSpendMoving,
  49535. const double startSpeed,
  49536. const double endSpeed)
  49537. {
  49538. if (component != 0)
  49539. {
  49540. AnimationTask* at = findTaskFor (component);
  49541. if (at == 0)
  49542. {
  49543. at = new AnimationTask (component);
  49544. tasks.add (at);
  49545. sendChangeMessage (this);
  49546. }
  49547. at->msElapsed = 0;
  49548. at->lastProgress = 0;
  49549. at->msTotal = jmax (1, millisecondsToSpendMoving);
  49550. at->destination = finalPosition;
  49551. // the speeds must be 0 or greater!
  49552. jassert (startSpeed >= 0 && endSpeed >= 0)
  49553. const double invTotalDistance = 4.0 / (startSpeed + endSpeed + 2.0);
  49554. at->startSpeed = jmax (0.0, startSpeed * invTotalDistance);
  49555. at->midSpeed = invTotalDistance;
  49556. at->endSpeed = jmax (0.0, endSpeed * invTotalDistance);
  49557. at->left = component->getX();
  49558. at->top = component->getY();
  49559. at->right = component->getRight();
  49560. at->bottom = component->getBottom();
  49561. if (! isTimerRunning())
  49562. {
  49563. lastTime = Time::getMillisecondCounter();
  49564. startTimer (1000 / 50);
  49565. }
  49566. }
  49567. }
  49568. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  49569. {
  49570. if (tasks.size() > 0)
  49571. {
  49572. if (moveComponentsToTheirFinalPositions)
  49573. for (int i = tasks.size(); --i >= 0;)
  49574. tasks.getUnchecked(i)->moveToFinalDestination();
  49575. tasks.clear();
  49576. sendChangeMessage (this);
  49577. }
  49578. }
  49579. void ComponentAnimator::cancelAnimation (Component* const component,
  49580. const bool moveComponentToItsFinalPosition)
  49581. {
  49582. AnimationTask* const at = findTaskFor (component);
  49583. if (at != 0)
  49584. {
  49585. if (moveComponentToItsFinalPosition)
  49586. at->moveToFinalDestination();
  49587. tasks.removeObject (at);
  49588. sendChangeMessage (this);
  49589. }
  49590. }
  49591. const Rectangle<int> ComponentAnimator::getComponentDestination (Component* const component)
  49592. {
  49593. AnimationTask* const at = findTaskFor (component);
  49594. if (at != 0)
  49595. return at->destination;
  49596. else if (component != 0)
  49597. return component->getBounds();
  49598. return Rectangle<int>();
  49599. }
  49600. bool ComponentAnimator::isAnimating (Component* component) const
  49601. {
  49602. return findTaskFor (component) != 0;
  49603. }
  49604. void ComponentAnimator::timerCallback()
  49605. {
  49606. const uint32 timeNow = Time::getMillisecondCounter();
  49607. if (lastTime == 0 || lastTime == timeNow)
  49608. lastTime = timeNow;
  49609. const int elapsed = timeNow - lastTime;
  49610. for (int i = tasks.size(); --i >= 0;)
  49611. {
  49612. if (! tasks.getUnchecked(i)->useTimeslice (elapsed))
  49613. {
  49614. tasks.remove (i);
  49615. sendChangeMessage (this);
  49616. }
  49617. }
  49618. lastTime = timeNow;
  49619. if (tasks.size() == 0)
  49620. stopTimer();
  49621. }
  49622. END_JUCE_NAMESPACE
  49623. /*** End of inlined file: juce_ComponentAnimator.cpp ***/
  49624. /*** Start of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49625. BEGIN_JUCE_NAMESPACE
  49626. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  49627. : minW (0),
  49628. maxW (0x3fffffff),
  49629. minH (0),
  49630. maxH (0x3fffffff),
  49631. minOffTop (0),
  49632. minOffLeft (0),
  49633. minOffBottom (0),
  49634. minOffRight (0),
  49635. aspectRatio (0.0)
  49636. {
  49637. }
  49638. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  49639. {
  49640. }
  49641. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  49642. {
  49643. minW = minimumWidth;
  49644. }
  49645. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  49646. {
  49647. maxW = maximumWidth;
  49648. }
  49649. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  49650. {
  49651. minH = minimumHeight;
  49652. }
  49653. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  49654. {
  49655. maxH = maximumHeight;
  49656. }
  49657. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  49658. {
  49659. jassert (maxW >= minimumWidth);
  49660. jassert (maxH >= minimumHeight);
  49661. jassert (minimumWidth > 0 && minimumHeight > 0);
  49662. minW = minimumWidth;
  49663. minH = minimumHeight;
  49664. if (minW > maxW)
  49665. maxW = minW;
  49666. if (minH > maxH)
  49667. maxH = minH;
  49668. }
  49669. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  49670. {
  49671. jassert (maximumWidth >= minW);
  49672. jassert (maximumHeight >= minH);
  49673. jassert (maximumWidth > 0 && maximumHeight > 0);
  49674. maxW = jmax (minW, maximumWidth);
  49675. maxH = jmax (minH, maximumHeight);
  49676. }
  49677. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  49678. const int minimumHeight,
  49679. const int maximumWidth,
  49680. const int maximumHeight) throw()
  49681. {
  49682. jassert (maximumWidth >= minimumWidth);
  49683. jassert (maximumHeight >= minimumHeight);
  49684. jassert (maximumWidth > 0 && maximumHeight > 0);
  49685. jassert (minimumWidth > 0 && minimumHeight > 0);
  49686. minW = jmax (0, minimumWidth);
  49687. minH = jmax (0, minimumHeight);
  49688. maxW = jmax (minW, maximumWidth);
  49689. maxH = jmax (minH, maximumHeight);
  49690. }
  49691. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  49692. const int minimumWhenOffTheLeft,
  49693. const int minimumWhenOffTheBottom,
  49694. const int minimumWhenOffTheRight) throw()
  49695. {
  49696. minOffTop = minimumWhenOffTheTop;
  49697. minOffLeft = minimumWhenOffTheLeft;
  49698. minOffBottom = minimumWhenOffTheBottom;
  49699. minOffRight = minimumWhenOffTheRight;
  49700. }
  49701. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  49702. {
  49703. aspectRatio = jmax (0.0, widthOverHeight);
  49704. }
  49705. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  49706. {
  49707. return aspectRatio;
  49708. }
  49709. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  49710. const Rectangle<int>& targetBounds,
  49711. const bool isStretchingTop,
  49712. const bool isStretchingLeft,
  49713. const bool isStretchingBottom,
  49714. const bool isStretchingRight)
  49715. {
  49716. jassert (component != 0);
  49717. Rectangle<int> limits, bounds (targetBounds);
  49718. BorderSize border;
  49719. Component* const parent = component->getParentComponent();
  49720. if (parent == 0)
  49721. {
  49722. ComponentPeer* peer = component->getPeer();
  49723. if (peer != 0)
  49724. border = peer->getFrameSize();
  49725. limits = Desktop::getInstance().getMonitorAreaContaining (bounds.getCentre());
  49726. }
  49727. else
  49728. {
  49729. limits.setSize (parent->getWidth(), parent->getHeight());
  49730. }
  49731. border.addTo (bounds);
  49732. checkBounds (bounds,
  49733. border.addedTo (component->getBounds()), limits,
  49734. isStretchingTop, isStretchingLeft,
  49735. isStretchingBottom, isStretchingRight);
  49736. border.subtractFrom (bounds);
  49737. applyBoundsToComponent (component, bounds);
  49738. }
  49739. void ComponentBoundsConstrainer::checkComponentBounds (Component* component)
  49740. {
  49741. setBoundsForComponent (component, component->getBounds(),
  49742. false, false, false, false);
  49743. }
  49744. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  49745. const Rectangle<int>& bounds)
  49746. {
  49747. component->setBounds (bounds);
  49748. }
  49749. void ComponentBoundsConstrainer::resizeStart()
  49750. {
  49751. }
  49752. void ComponentBoundsConstrainer::resizeEnd()
  49753. {
  49754. }
  49755. void ComponentBoundsConstrainer::checkBounds (Rectangle<int>& bounds,
  49756. const Rectangle<int>& old,
  49757. const Rectangle<int>& limits,
  49758. const bool isStretchingTop,
  49759. const bool isStretchingLeft,
  49760. const bool isStretchingBottom,
  49761. const bool isStretchingRight)
  49762. {
  49763. int x = bounds.getX();
  49764. int y = bounds.getY();
  49765. int w = bounds.getWidth();
  49766. int h = bounds.getHeight();
  49767. // constrain the size if it's being stretched..
  49768. if (isStretchingLeft)
  49769. {
  49770. x = jlimit (old.getRight() - maxW, old.getRight() - minW, x);
  49771. w = old.getRight() - x;
  49772. }
  49773. if (isStretchingRight)
  49774. {
  49775. w = jlimit (minW, maxW, w);
  49776. }
  49777. if (isStretchingTop)
  49778. {
  49779. y = jlimit (old.getBottom() - maxH, old.getBottom() - minH, y);
  49780. h = old.getBottom() - y;
  49781. }
  49782. if (isStretchingBottom)
  49783. {
  49784. h = jlimit (minH, maxH, h);
  49785. }
  49786. // constrain the aspect ratio if one has been specified..
  49787. if (aspectRatio > 0.0 && w > 0 && h > 0)
  49788. {
  49789. bool adjustWidth;
  49790. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49791. {
  49792. adjustWidth = true;
  49793. }
  49794. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49795. {
  49796. adjustWidth = false;
  49797. }
  49798. else
  49799. {
  49800. const double oldRatio = (old.getHeight() > 0) ? std::abs (old.getWidth() / (double) old.getHeight()) : 0.0;
  49801. const double newRatio = std::abs (w / (double) h);
  49802. adjustWidth = (oldRatio > newRatio);
  49803. }
  49804. if (adjustWidth)
  49805. {
  49806. w = roundToInt (h * aspectRatio);
  49807. if (w > maxW || w < minW)
  49808. {
  49809. w = jlimit (minW, maxW, w);
  49810. h = roundToInt (w / aspectRatio);
  49811. }
  49812. }
  49813. else
  49814. {
  49815. h = roundToInt (w / aspectRatio);
  49816. if (h > maxH || h < minH)
  49817. {
  49818. h = jlimit (minH, maxH, h);
  49819. w = roundToInt (h * aspectRatio);
  49820. }
  49821. }
  49822. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49823. {
  49824. x = old.getX() + (old.getWidth() - w) / 2;
  49825. }
  49826. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49827. {
  49828. y = old.getY() + (old.getHeight() - h) / 2;
  49829. }
  49830. else
  49831. {
  49832. if (isStretchingLeft)
  49833. x = old.getRight() - w;
  49834. if (isStretchingTop)
  49835. y = old.getBottom() - h;
  49836. }
  49837. }
  49838. // ...and constrain the position if limits have been set for that.
  49839. if (minOffTop > 0 || minOffLeft > 0 || minOffBottom > 0 || minOffRight > 0)
  49840. {
  49841. if (minOffTop > 0)
  49842. {
  49843. const int limit = limits.getY() + jmin (minOffTop - h, 0);
  49844. if (y < limit)
  49845. {
  49846. if (isStretchingTop)
  49847. h -= (limit - y);
  49848. y = limit;
  49849. }
  49850. }
  49851. if (minOffLeft > 0)
  49852. {
  49853. const int limit = limits.getX() + jmin (minOffLeft - w, 0);
  49854. if (x < limit)
  49855. {
  49856. if (isStretchingLeft)
  49857. w -= (limit - x);
  49858. x = limit;
  49859. }
  49860. }
  49861. if (minOffBottom > 0)
  49862. {
  49863. const int limit = limits.getBottom() - jmin (minOffBottom, h);
  49864. if (y > limit)
  49865. {
  49866. if (isStretchingBottom)
  49867. h += (limit - y);
  49868. else
  49869. y = limit;
  49870. }
  49871. }
  49872. if (minOffRight > 0)
  49873. {
  49874. const int limit = limits.getRight() - jmin (minOffRight, w);
  49875. if (x > limit)
  49876. {
  49877. if (isStretchingRight)
  49878. w += (limit - x);
  49879. else
  49880. x = limit;
  49881. }
  49882. }
  49883. }
  49884. jassert (w >= 0 && h >= 0);
  49885. bounds = Rectangle<int> (x, y, w, h);
  49886. }
  49887. END_JUCE_NAMESPACE
  49888. /*** End of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49889. /*** Start of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49890. BEGIN_JUCE_NAMESPACE
  49891. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  49892. : component (component_),
  49893. lastPeer (0),
  49894. reentrant (false)
  49895. {
  49896. jassert (component != 0); // can't use this with a null pointer..
  49897. component->addComponentListener (this);
  49898. registerWithParentComps();
  49899. }
  49900. ComponentMovementWatcher::~ComponentMovementWatcher()
  49901. {
  49902. component->removeComponentListener (this);
  49903. unregister();
  49904. }
  49905. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  49906. {
  49907. // agh! don't delete the target component without deleting this object first!
  49908. jassert (component != 0);
  49909. if (! reentrant)
  49910. {
  49911. reentrant = true;
  49912. ComponentPeer* const peer = component->getPeer();
  49913. if (peer != lastPeer)
  49914. {
  49915. componentPeerChanged();
  49916. if (component == 0)
  49917. return;
  49918. lastPeer = peer;
  49919. }
  49920. unregister();
  49921. registerWithParentComps();
  49922. reentrant = false;
  49923. componentMovedOrResized (*component, true, true);
  49924. }
  49925. }
  49926. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  49927. {
  49928. // agh! don't delete the target component without deleting this object first!
  49929. jassert (component != 0);
  49930. if (wasMoved)
  49931. {
  49932. const Point<int> pos (component->relativePositionToOtherComponent (component->getTopLevelComponent(), Point<int>()));
  49933. wasMoved = lastBounds.getPosition() != pos;
  49934. lastBounds.setPosition (pos);
  49935. }
  49936. wasResized = (lastBounds.getWidth() != component->getWidth() || lastBounds.getHeight() != component->getHeight());
  49937. lastBounds.setSize (component->getWidth(), component->getHeight());
  49938. if (wasMoved || wasResized)
  49939. componentMovedOrResized (wasMoved, wasResized);
  49940. }
  49941. void ComponentMovementWatcher::registerWithParentComps()
  49942. {
  49943. Component* p = component->getParentComponent();
  49944. while (p != 0)
  49945. {
  49946. p->addComponentListener (this);
  49947. registeredParentComps.add (p);
  49948. p = p->getParentComponent();
  49949. }
  49950. }
  49951. void ComponentMovementWatcher::unregister()
  49952. {
  49953. for (int i = registeredParentComps.size(); --i >= 0;)
  49954. registeredParentComps.getUnchecked(i)->removeComponentListener (this);
  49955. registeredParentComps.clear();
  49956. }
  49957. END_JUCE_NAMESPACE
  49958. /*** End of inlined file: juce_ComponentMovementWatcher.cpp ***/
  49959. /*** Start of inlined file: juce_GroupComponent.cpp ***/
  49960. BEGIN_JUCE_NAMESPACE
  49961. GroupComponent::GroupComponent (const String& componentName,
  49962. const String& labelText)
  49963. : Component (componentName),
  49964. text (labelText),
  49965. justification (Justification::left)
  49966. {
  49967. setInterceptsMouseClicks (false, true);
  49968. }
  49969. GroupComponent::~GroupComponent()
  49970. {
  49971. }
  49972. void GroupComponent::setText (const String& newText)
  49973. {
  49974. if (text != newText)
  49975. {
  49976. text = newText;
  49977. repaint();
  49978. }
  49979. }
  49980. const String GroupComponent::getText() const
  49981. {
  49982. return text;
  49983. }
  49984. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  49985. {
  49986. if (justification != newJustification)
  49987. {
  49988. justification = newJustification;
  49989. repaint();
  49990. }
  49991. }
  49992. void GroupComponent::paint (Graphics& g)
  49993. {
  49994. getLookAndFeel()
  49995. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  49996. text, justification,
  49997. *this);
  49998. }
  49999. void GroupComponent::enablementChanged()
  50000. {
  50001. repaint();
  50002. }
  50003. void GroupComponent::colourChanged()
  50004. {
  50005. repaint();
  50006. }
  50007. END_JUCE_NAMESPACE
  50008. /*** End of inlined file: juce_GroupComponent.cpp ***/
  50009. /*** Start of inlined file: juce_MultiDocumentPanel.cpp ***/
  50010. BEGIN_JUCE_NAMESPACE
  50011. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  50012. : DocumentWindow (String::empty, backgroundColour,
  50013. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  50014. {
  50015. }
  50016. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  50017. {
  50018. }
  50019. void MultiDocumentPanelWindow::maximiseButtonPressed()
  50020. {
  50021. MultiDocumentPanel* const owner = getOwner();
  50022. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  50023. if (owner != 0)
  50024. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  50025. }
  50026. void MultiDocumentPanelWindow::closeButtonPressed()
  50027. {
  50028. MultiDocumentPanel* const owner = getOwner();
  50029. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  50030. if (owner != 0)
  50031. owner->closeDocument (getContentComponent(), true);
  50032. }
  50033. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  50034. {
  50035. DocumentWindow::activeWindowStatusChanged();
  50036. updateOrder();
  50037. }
  50038. void MultiDocumentPanelWindow::broughtToFront()
  50039. {
  50040. DocumentWindow::broughtToFront();
  50041. updateOrder();
  50042. }
  50043. void MultiDocumentPanelWindow::updateOrder()
  50044. {
  50045. MultiDocumentPanel* const owner = getOwner();
  50046. if (owner != 0)
  50047. owner->updateOrder();
  50048. }
  50049. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  50050. {
  50051. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  50052. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  50053. }
  50054. class MDITabbedComponentInternal : public TabbedComponent
  50055. {
  50056. public:
  50057. MDITabbedComponentInternal()
  50058. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  50059. {
  50060. }
  50061. ~MDITabbedComponentInternal()
  50062. {
  50063. }
  50064. void currentTabChanged (int, const String&)
  50065. {
  50066. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  50067. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  50068. if (owner != 0)
  50069. owner->updateOrder();
  50070. }
  50071. };
  50072. MultiDocumentPanel::MultiDocumentPanel()
  50073. : mode (MaximisedWindowsWithTabs),
  50074. backgroundColour (Colours::lightblue),
  50075. maximumNumDocuments (0),
  50076. numDocsBeforeTabsUsed (0)
  50077. {
  50078. setOpaque (true);
  50079. }
  50080. MultiDocumentPanel::~MultiDocumentPanel()
  50081. {
  50082. closeAllDocuments (false);
  50083. }
  50084. static bool shouldDeleteComp (Component* const c)
  50085. {
  50086. return c->getProperties() ["mdiDocumentDelete_"];
  50087. }
  50088. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  50089. {
  50090. while (components.size() > 0)
  50091. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  50092. return false;
  50093. return true;
  50094. }
  50095. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  50096. {
  50097. return new MultiDocumentPanelWindow (backgroundColour);
  50098. }
  50099. void MultiDocumentPanel::addWindow (Component* component)
  50100. {
  50101. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  50102. dw->setResizable (true, false);
  50103. dw->setContentComponent (component, false, true);
  50104. dw->setName (component->getName());
  50105. const var bkg (component->getProperties() ["mdiDocumentBkg_"]);
  50106. dw->setBackgroundColour (bkg.isVoid() ? backgroundColour : Colour ((int) bkg));
  50107. int x = 4;
  50108. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  50109. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  50110. x += 16;
  50111. dw->setTopLeftPosition (x, x);
  50112. const var pos (component->getProperties() ["mdiDocumentPos_"]);
  50113. if (pos.toString().isNotEmpty())
  50114. dw->restoreWindowStateFromString (pos.toString());
  50115. addAndMakeVisible (dw);
  50116. dw->toFront (true);
  50117. }
  50118. bool MultiDocumentPanel::addDocument (Component* const component,
  50119. const Colour& docColour,
  50120. const bool deleteWhenRemoved)
  50121. {
  50122. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  50123. // with a frame-within-a-frame! Just pass in the bare content component.
  50124. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  50125. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  50126. return false;
  50127. components.add (component);
  50128. component->getProperties().set ("mdiDocumentDelete_", deleteWhenRemoved);
  50129. component->getProperties().set ("mdiDocumentBkg_", (int) docColour.getARGB());
  50130. component->addComponentListener (this);
  50131. if (mode == FloatingWindows)
  50132. {
  50133. if (isFullscreenWhenOneDocument())
  50134. {
  50135. if (components.size() == 1)
  50136. {
  50137. addAndMakeVisible (component);
  50138. }
  50139. else
  50140. {
  50141. if (components.size() == 2)
  50142. addWindow (components.getFirst());
  50143. addWindow (component);
  50144. }
  50145. }
  50146. else
  50147. {
  50148. addWindow (component);
  50149. }
  50150. }
  50151. else
  50152. {
  50153. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  50154. {
  50155. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  50156. Array <Component*> temp (components);
  50157. for (int i = 0; i < temp.size(); ++i)
  50158. tabComponent->addTab (temp[i]->getName(), docColour, temp[i], false);
  50159. resized();
  50160. }
  50161. else
  50162. {
  50163. if (tabComponent != 0)
  50164. tabComponent->addTab (component->getName(), docColour, component, false);
  50165. else
  50166. addAndMakeVisible (component);
  50167. }
  50168. setActiveDocument (component);
  50169. }
  50170. resized();
  50171. activeDocumentChanged();
  50172. return true;
  50173. }
  50174. bool MultiDocumentPanel::closeDocument (Component* component,
  50175. const bool checkItsOkToCloseFirst)
  50176. {
  50177. if (components.contains (component))
  50178. {
  50179. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  50180. return false;
  50181. component->removeComponentListener (this);
  50182. const bool shouldDelete = shouldDeleteComp (component);
  50183. component->getProperties().remove ("mdiDocumentDelete_");
  50184. component->getProperties().remove ("mdiDocumentBkg_");
  50185. if (mode == FloatingWindows)
  50186. {
  50187. for (int i = getNumChildComponents(); --i >= 0;)
  50188. {
  50189. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50190. if (dw != 0 && dw->getContentComponent() == component)
  50191. {
  50192. dw->setContentComponent (0, false);
  50193. delete dw;
  50194. break;
  50195. }
  50196. }
  50197. if (shouldDelete)
  50198. delete component;
  50199. components.removeValue (component);
  50200. if (isFullscreenWhenOneDocument() && components.size() == 1)
  50201. {
  50202. for (int i = getNumChildComponents(); --i >= 0;)
  50203. {
  50204. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50205. if (dw != 0)
  50206. {
  50207. dw->setContentComponent (0, false);
  50208. delete dw;
  50209. }
  50210. }
  50211. addAndMakeVisible (components.getFirst());
  50212. }
  50213. }
  50214. else
  50215. {
  50216. jassert (components.indexOf (component) >= 0);
  50217. if (tabComponent != 0)
  50218. {
  50219. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50220. if (tabComponent->getTabContentComponent (i) == component)
  50221. tabComponent->removeTab (i);
  50222. }
  50223. else
  50224. {
  50225. removeChildComponent (component);
  50226. }
  50227. if (shouldDelete)
  50228. delete component;
  50229. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  50230. tabComponent = 0;
  50231. components.removeValue (component);
  50232. if (components.size() > 0 && tabComponent == 0)
  50233. addAndMakeVisible (components.getFirst());
  50234. }
  50235. resized();
  50236. activeDocumentChanged();
  50237. }
  50238. else
  50239. {
  50240. jassertfalse;
  50241. }
  50242. return true;
  50243. }
  50244. int MultiDocumentPanel::getNumDocuments() const throw()
  50245. {
  50246. return components.size();
  50247. }
  50248. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  50249. {
  50250. return components [index];
  50251. }
  50252. Component* MultiDocumentPanel::getActiveDocument() const throw()
  50253. {
  50254. if (mode == FloatingWindows)
  50255. {
  50256. for (int i = getNumChildComponents(); --i >= 0;)
  50257. {
  50258. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50259. if (dw != 0 && dw->isActiveWindow())
  50260. return dw->getContentComponent();
  50261. }
  50262. }
  50263. return components.getLast();
  50264. }
  50265. void MultiDocumentPanel::setActiveDocument (Component* component)
  50266. {
  50267. if (mode == FloatingWindows)
  50268. {
  50269. component = getContainerComp (component);
  50270. if (component != 0)
  50271. component->toFront (true);
  50272. }
  50273. else if (tabComponent != 0)
  50274. {
  50275. jassert (components.indexOf (component) >= 0);
  50276. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50277. {
  50278. if (tabComponent->getTabContentComponent (i) == component)
  50279. {
  50280. tabComponent->setCurrentTabIndex (i);
  50281. break;
  50282. }
  50283. }
  50284. }
  50285. else
  50286. {
  50287. component->grabKeyboardFocus();
  50288. }
  50289. }
  50290. void MultiDocumentPanel::activeDocumentChanged()
  50291. {
  50292. }
  50293. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  50294. {
  50295. maximumNumDocuments = newNumber;
  50296. }
  50297. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  50298. {
  50299. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  50300. }
  50301. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  50302. {
  50303. return numDocsBeforeTabsUsed != 0;
  50304. }
  50305. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  50306. {
  50307. if (mode != newLayoutMode)
  50308. {
  50309. mode = newLayoutMode;
  50310. if (mode == FloatingWindows)
  50311. {
  50312. tabComponent = 0;
  50313. }
  50314. else
  50315. {
  50316. for (int i = getNumChildComponents(); --i >= 0;)
  50317. {
  50318. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50319. if (dw != 0)
  50320. {
  50321. dw->getContentComponent()->getProperties().set ("mdiDocumentPos_", dw->getWindowStateAsString());
  50322. dw->setContentComponent (0, false);
  50323. delete dw;
  50324. }
  50325. }
  50326. }
  50327. resized();
  50328. const Array <Component*> tempComps (components);
  50329. components.clear();
  50330. for (int i = 0; i < tempComps.size(); ++i)
  50331. {
  50332. Component* const c = tempComps.getUnchecked(i);
  50333. addDocument (c,
  50334. Colour ((int) c->getProperties().getWithDefault ("mdiDocumentBkg_", (int) Colours::white.getARGB())),
  50335. shouldDeleteComp (c));
  50336. }
  50337. }
  50338. }
  50339. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  50340. {
  50341. if (backgroundColour != newBackgroundColour)
  50342. {
  50343. backgroundColour = newBackgroundColour;
  50344. setOpaque (newBackgroundColour.isOpaque());
  50345. repaint();
  50346. }
  50347. }
  50348. void MultiDocumentPanel::paint (Graphics& g)
  50349. {
  50350. g.fillAll (backgroundColour);
  50351. }
  50352. void MultiDocumentPanel::resized()
  50353. {
  50354. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  50355. {
  50356. for (int i = getNumChildComponents(); --i >= 0;)
  50357. getChildComponent (i)->setBounds (getLocalBounds());
  50358. }
  50359. setWantsKeyboardFocus (components.size() == 0);
  50360. }
  50361. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  50362. {
  50363. if (mode == FloatingWindows)
  50364. {
  50365. for (int i = 0; i < getNumChildComponents(); ++i)
  50366. {
  50367. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50368. if (dw != 0 && dw->getContentComponent() == c)
  50369. {
  50370. c = dw;
  50371. break;
  50372. }
  50373. }
  50374. }
  50375. return c;
  50376. }
  50377. void MultiDocumentPanel::componentNameChanged (Component&)
  50378. {
  50379. if (mode == FloatingWindows)
  50380. {
  50381. for (int i = 0; i < getNumChildComponents(); ++i)
  50382. {
  50383. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50384. if (dw != 0)
  50385. dw->setName (dw->getContentComponent()->getName());
  50386. }
  50387. }
  50388. else if (tabComponent != 0)
  50389. {
  50390. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50391. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  50392. }
  50393. }
  50394. void MultiDocumentPanel::updateOrder()
  50395. {
  50396. const Array <Component*> oldList (components);
  50397. if (mode == FloatingWindows)
  50398. {
  50399. components.clear();
  50400. for (int i = 0; i < getNumChildComponents(); ++i)
  50401. {
  50402. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50403. if (dw != 0)
  50404. components.add (dw->getContentComponent());
  50405. }
  50406. }
  50407. else
  50408. {
  50409. if (tabComponent != 0)
  50410. {
  50411. Component* const current = tabComponent->getCurrentContentComponent();
  50412. if (current != 0)
  50413. {
  50414. components.removeValue (current);
  50415. components.add (current);
  50416. }
  50417. }
  50418. }
  50419. if (components != oldList)
  50420. activeDocumentChanged();
  50421. }
  50422. END_JUCE_NAMESPACE
  50423. /*** End of inlined file: juce_MultiDocumentPanel.cpp ***/
  50424. /*** Start of inlined file: juce_ResizableBorderComponent.cpp ***/
  50425. BEGIN_JUCE_NAMESPACE
  50426. ResizableBorderComponent::Zone::Zone (int zoneFlags) throw()
  50427. : zone (zoneFlags)
  50428. {
  50429. }
  50430. ResizableBorderComponent::Zone::Zone (const ResizableBorderComponent::Zone& other) throw() : zone (other.zone) {}
  50431. ResizableBorderComponent::Zone& ResizableBorderComponent::Zone::operator= (const ResizableBorderComponent::Zone& other) throw() { zone = other.zone; return *this; }
  50432. bool ResizableBorderComponent::Zone::operator== (const ResizableBorderComponent::Zone& other) const throw() { return zone == other.zone; }
  50433. bool ResizableBorderComponent::Zone::operator!= (const ResizableBorderComponent::Zone& other) const throw() { return zone != other.zone; }
  50434. const ResizableBorderComponent::Zone ResizableBorderComponent::Zone::fromPositionOnBorder (const Rectangle<int>& totalSize,
  50435. const BorderSize& border,
  50436. const Point<int>& position)
  50437. {
  50438. int z = 0;
  50439. if (totalSize.contains (position)
  50440. && ! border.subtractedFrom (totalSize).contains (position))
  50441. {
  50442. const int minW = jmax (totalSize.getWidth() / 10, jmin (10, totalSize.getWidth() / 3));
  50443. if (position.getX() < jmax (border.getLeft(), minW))
  50444. z |= left;
  50445. else if (position.getX() >= totalSize.getWidth() - jmax (border.getRight(), minW))
  50446. z |= right;
  50447. const int minH = jmax (totalSize.getHeight() / 10, jmin (10, totalSize.getHeight() / 3));
  50448. if (position.getY() < jmax (border.getTop(), minH))
  50449. z |= top;
  50450. else if (position.getY() >= totalSize.getHeight() - jmax (border.getBottom(), minH))
  50451. z |= bottom;
  50452. }
  50453. return Zone (z);
  50454. }
  50455. const MouseCursor ResizableBorderComponent::Zone::getMouseCursor() const throw()
  50456. {
  50457. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  50458. switch (zone)
  50459. {
  50460. case (left | top): mc = MouseCursor::TopLeftCornerResizeCursor; break;
  50461. case top: mc = MouseCursor::TopEdgeResizeCursor; break;
  50462. case (right | top): mc = MouseCursor::TopRightCornerResizeCursor; break;
  50463. case left: mc = MouseCursor::LeftEdgeResizeCursor; break;
  50464. case right: mc = MouseCursor::RightEdgeResizeCursor; break;
  50465. case (left | bottom): mc = MouseCursor::BottomLeftCornerResizeCursor; break;
  50466. case bottom: mc = MouseCursor::BottomEdgeResizeCursor; break;
  50467. case (right | bottom): mc = MouseCursor::BottomRightCornerResizeCursor; break;
  50468. default: break;
  50469. }
  50470. return mc;
  50471. }
  50472. const Rectangle<int> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<int> b, const Point<int>& offset) const throw()
  50473. {
  50474. if (isDraggingWholeObject())
  50475. return b + offset;
  50476. if (isDraggingLeftEdge())
  50477. b.setLeft (b.getX() + offset.getX());
  50478. if (isDraggingRightEdge())
  50479. b.setWidth (jmax (0, b.getWidth() + offset.getX()));
  50480. if (isDraggingTopEdge())
  50481. b.setTop (b.getY() + offset.getY());
  50482. if (isDraggingBottomEdge())
  50483. b.setHeight (jmax (0, b.getHeight() + offset.getY()));
  50484. return b;
  50485. }
  50486. const Rectangle<float> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<float> b, const Point<float>& offset) const throw()
  50487. {
  50488. if (isDraggingWholeObject())
  50489. return b + offset;
  50490. if (isDraggingLeftEdge())
  50491. b.setLeft (b.getX() + offset.getX());
  50492. if (isDraggingRightEdge())
  50493. b.setWidth (jmax (0.0f, b.getWidth() + offset.getX()));
  50494. if (isDraggingTopEdge())
  50495. b.setTop (b.getY() + offset.getY());
  50496. if (isDraggingBottomEdge())
  50497. b.setHeight (jmax (0.0f, b.getHeight() + offset.getY()));
  50498. return b;
  50499. }
  50500. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  50501. ComponentBoundsConstrainer* const constrainer_)
  50502. : component (componentToResize),
  50503. constrainer (constrainer_),
  50504. borderSize (5),
  50505. mouseZone (0)
  50506. {
  50507. }
  50508. ResizableBorderComponent::~ResizableBorderComponent()
  50509. {
  50510. }
  50511. void ResizableBorderComponent::paint (Graphics& g)
  50512. {
  50513. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  50514. }
  50515. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  50516. {
  50517. updateMouseZone (e);
  50518. }
  50519. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  50520. {
  50521. updateMouseZone (e);
  50522. }
  50523. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  50524. {
  50525. if (component == 0)
  50526. {
  50527. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50528. return;
  50529. }
  50530. updateMouseZone (e);
  50531. originalBounds = component->getBounds();
  50532. if (constrainer != 0)
  50533. constrainer->resizeStart();
  50534. }
  50535. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  50536. {
  50537. if (component == 0)
  50538. {
  50539. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50540. return;
  50541. }
  50542. const Rectangle<int> bounds (mouseZone.resizeRectangleBy (originalBounds, e.getOffsetFromDragStart()));
  50543. if (constrainer != 0)
  50544. constrainer->setBoundsForComponent (component, bounds,
  50545. mouseZone.isDraggingTopEdge(),
  50546. mouseZone.isDraggingLeftEdge(),
  50547. mouseZone.isDraggingBottomEdge(),
  50548. mouseZone.isDraggingRightEdge());
  50549. else
  50550. component->setBounds (bounds);
  50551. }
  50552. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  50553. {
  50554. if (constrainer != 0)
  50555. constrainer->resizeEnd();
  50556. }
  50557. bool ResizableBorderComponent::hitTest (int x, int y)
  50558. {
  50559. return x < borderSize.getLeft()
  50560. || x >= getWidth() - borderSize.getRight()
  50561. || y < borderSize.getTop()
  50562. || y >= getHeight() - borderSize.getBottom();
  50563. }
  50564. void ResizableBorderComponent::setBorderThickness (const BorderSize& newBorderSize)
  50565. {
  50566. if (borderSize != newBorderSize)
  50567. {
  50568. borderSize = newBorderSize;
  50569. repaint();
  50570. }
  50571. }
  50572. const BorderSize ResizableBorderComponent::getBorderThickness() const
  50573. {
  50574. return borderSize;
  50575. }
  50576. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e)
  50577. {
  50578. Zone newZone (Zone::fromPositionOnBorder (getLocalBounds(), borderSize, e.getPosition()));
  50579. if (mouseZone != newZone)
  50580. {
  50581. mouseZone = newZone;
  50582. setMouseCursor (newZone.getMouseCursor());
  50583. }
  50584. }
  50585. END_JUCE_NAMESPACE
  50586. /*** End of inlined file: juce_ResizableBorderComponent.cpp ***/
  50587. /*** Start of inlined file: juce_ResizableCornerComponent.cpp ***/
  50588. BEGIN_JUCE_NAMESPACE
  50589. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  50590. ComponentBoundsConstrainer* const constrainer_)
  50591. : component (componentToResize),
  50592. constrainer (constrainer_)
  50593. {
  50594. setRepaintsOnMouseActivity (true);
  50595. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  50596. }
  50597. ResizableCornerComponent::~ResizableCornerComponent()
  50598. {
  50599. }
  50600. void ResizableCornerComponent::paint (Graphics& g)
  50601. {
  50602. getLookAndFeel()
  50603. .drawCornerResizer (g, getWidth(), getHeight(),
  50604. isMouseOverOrDragging(),
  50605. isMouseButtonDown());
  50606. }
  50607. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  50608. {
  50609. if (component == 0)
  50610. {
  50611. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50612. return;
  50613. }
  50614. originalBounds = component->getBounds();
  50615. if (constrainer != 0)
  50616. constrainer->resizeStart();
  50617. }
  50618. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  50619. {
  50620. if (component == 0)
  50621. {
  50622. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50623. return;
  50624. }
  50625. Rectangle<int> r (originalBounds.withSize (originalBounds.getWidth() + e.getDistanceFromDragStartX(),
  50626. originalBounds.getHeight() + e.getDistanceFromDragStartY()));
  50627. if (constrainer != 0)
  50628. constrainer->setBoundsForComponent (component, r, false, false, true, true);
  50629. else
  50630. component->setBounds (r);
  50631. }
  50632. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  50633. {
  50634. if (constrainer != 0)
  50635. constrainer->resizeStart();
  50636. }
  50637. bool ResizableCornerComponent::hitTest (int x, int y)
  50638. {
  50639. if (getWidth() <= 0)
  50640. return false;
  50641. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  50642. return y >= yAtX - getHeight() / 4;
  50643. }
  50644. END_JUCE_NAMESPACE
  50645. /*** End of inlined file: juce_ResizableCornerComponent.cpp ***/
  50646. /*** Start of inlined file: juce_ScrollBar.cpp ***/
  50647. BEGIN_JUCE_NAMESPACE
  50648. class ScrollBar::ScrollbarButton : public Button
  50649. {
  50650. public:
  50651. int direction;
  50652. ScrollbarButton (const int direction_, ScrollBar& owner_)
  50653. : Button (String::empty),
  50654. direction (direction_),
  50655. owner (owner_)
  50656. {
  50657. setWantsKeyboardFocus (false);
  50658. }
  50659. ~ScrollbarButton()
  50660. {
  50661. }
  50662. void paintButton (Graphics& g, bool over, bool down)
  50663. {
  50664. getLookAndFeel()
  50665. .drawScrollbarButton (g, owner,
  50666. getWidth(), getHeight(),
  50667. direction,
  50668. owner.isVertical(),
  50669. over, down);
  50670. }
  50671. void clicked()
  50672. {
  50673. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  50674. }
  50675. juce_UseDebuggingNewOperator
  50676. private:
  50677. ScrollBar& owner;
  50678. ScrollbarButton (const ScrollbarButton&);
  50679. ScrollbarButton& operator= (const ScrollbarButton&);
  50680. };
  50681. ScrollBar::ScrollBar (const bool vertical_,
  50682. const bool buttonsAreVisible)
  50683. : totalRange (0.0, 1.0),
  50684. visibleRange (0.0, 0.1),
  50685. singleStepSize (0.1),
  50686. thumbAreaStart (0),
  50687. thumbAreaSize (0),
  50688. thumbStart (0),
  50689. thumbSize (0),
  50690. initialDelayInMillisecs (100),
  50691. repeatDelayInMillisecs (50),
  50692. minimumDelayInMillisecs (10),
  50693. vertical (vertical_),
  50694. isDraggingThumb (false),
  50695. autohides (true)
  50696. {
  50697. setButtonVisibility (buttonsAreVisible);
  50698. setRepaintsOnMouseActivity (true);
  50699. setFocusContainer (true);
  50700. }
  50701. ScrollBar::~ScrollBar()
  50702. {
  50703. upButton = 0;
  50704. downButton = 0;
  50705. }
  50706. void ScrollBar::setRangeLimits (const Range<double>& newRangeLimit)
  50707. {
  50708. if (totalRange != newRangeLimit)
  50709. {
  50710. totalRange = newRangeLimit;
  50711. setCurrentRange (visibleRange);
  50712. updateThumbPosition();
  50713. }
  50714. }
  50715. void ScrollBar::setRangeLimits (const double newMinimum, const double newMaximum)
  50716. {
  50717. jassert (newMaximum >= newMinimum); // these can't be the wrong way round!
  50718. setRangeLimits (Range<double> (newMinimum, newMaximum));
  50719. }
  50720. void ScrollBar::setCurrentRange (const Range<double>& newRange)
  50721. {
  50722. const Range<double> constrainedRange (totalRange.constrainRange (newRange));
  50723. if (visibleRange != constrainedRange)
  50724. {
  50725. visibleRange = constrainedRange;
  50726. updateThumbPosition();
  50727. triggerAsyncUpdate();
  50728. }
  50729. }
  50730. void ScrollBar::setCurrentRange (const double newStart, const double newSize)
  50731. {
  50732. setCurrentRange (Range<double> (newStart, newStart + newSize));
  50733. }
  50734. void ScrollBar::setCurrentRangeStart (const double newStart)
  50735. {
  50736. setCurrentRange (visibleRange.movedToStartAt (newStart));
  50737. }
  50738. void ScrollBar::setSingleStepSize (const double newSingleStepSize)
  50739. {
  50740. singleStepSize = newSingleStepSize;
  50741. }
  50742. void ScrollBar::moveScrollbarInSteps (const int howManySteps)
  50743. {
  50744. setCurrentRange (visibleRange + howManySteps * singleStepSize);
  50745. }
  50746. void ScrollBar::moveScrollbarInPages (const int howManyPages)
  50747. {
  50748. setCurrentRange (visibleRange + howManyPages * visibleRange.getLength());
  50749. }
  50750. void ScrollBar::scrollToTop()
  50751. {
  50752. setCurrentRange (visibleRange.movedToStartAt (getMinimumRangeLimit()));
  50753. }
  50754. void ScrollBar::scrollToBottom()
  50755. {
  50756. setCurrentRange (visibleRange.movedToEndAt (getMaximumRangeLimit()));
  50757. }
  50758. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  50759. const int repeatDelayInMillisecs_,
  50760. const int minimumDelayInMillisecs_)
  50761. {
  50762. initialDelayInMillisecs = initialDelayInMillisecs_;
  50763. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  50764. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  50765. if (upButton != 0)
  50766. {
  50767. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50768. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50769. }
  50770. }
  50771. void ScrollBar::addListener (Listener* const listener)
  50772. {
  50773. listeners.add (listener);
  50774. }
  50775. void ScrollBar::removeListener (Listener* const listener)
  50776. {
  50777. listeners.remove (listener);
  50778. }
  50779. void ScrollBar::handleAsyncUpdate()
  50780. {
  50781. double start = visibleRange.getStart(); // (need to use a temp variable for VC7 compatibility)
  50782. listeners.call (&ScrollBar::Listener::scrollBarMoved, this, start);
  50783. }
  50784. void ScrollBar::updateThumbPosition()
  50785. {
  50786. int newThumbSize = roundToInt (totalRange.getLength() > 0 ? (visibleRange.getLength() * thumbAreaSize) / totalRange.getLength()
  50787. : thumbAreaSize);
  50788. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50789. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  50790. if (newThumbSize > thumbAreaSize)
  50791. newThumbSize = thumbAreaSize;
  50792. int newThumbStart = thumbAreaStart;
  50793. if (totalRange.getLength() > visibleRange.getLength())
  50794. newThumbStart += roundToInt (((visibleRange.getStart() - totalRange.getStart()) * (thumbAreaSize - newThumbSize))
  50795. / (totalRange.getLength() - visibleRange.getLength()));
  50796. setVisible ((! autohides) || (totalRange.getLength() > visibleRange.getLength() && visibleRange.getLength() > 0.0));
  50797. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  50798. {
  50799. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  50800. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  50801. if (vertical)
  50802. repaint (0, repaintStart, getWidth(), repaintSize);
  50803. else
  50804. repaint (repaintStart, 0, repaintSize, getHeight());
  50805. thumbStart = newThumbStart;
  50806. thumbSize = newThumbSize;
  50807. }
  50808. }
  50809. void ScrollBar::setOrientation (const bool shouldBeVertical)
  50810. {
  50811. if (vertical != shouldBeVertical)
  50812. {
  50813. vertical = shouldBeVertical;
  50814. if (upButton != 0)
  50815. {
  50816. upButton->direction = vertical ? 0 : 3;
  50817. downButton->direction = vertical ? 2 : 1;
  50818. }
  50819. updateThumbPosition();
  50820. }
  50821. }
  50822. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  50823. {
  50824. upButton = 0;
  50825. downButton = 0;
  50826. if (buttonsAreVisible)
  50827. {
  50828. addAndMakeVisible (upButton = new ScrollbarButton (vertical ? 0 : 3, *this));
  50829. addAndMakeVisible (downButton = new ScrollbarButton (vertical ? 2 : 1, *this));
  50830. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50831. }
  50832. updateThumbPosition();
  50833. }
  50834. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  50835. {
  50836. autohides = shouldHideWhenFullRange;
  50837. updateThumbPosition();
  50838. }
  50839. bool ScrollBar::autoHides() const throw()
  50840. {
  50841. return autohides;
  50842. }
  50843. void ScrollBar::paint (Graphics& g)
  50844. {
  50845. if (thumbAreaSize > 0)
  50846. {
  50847. LookAndFeel& lf = getLookAndFeel();
  50848. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  50849. ? thumbSize : 0;
  50850. if (vertical)
  50851. {
  50852. lf.drawScrollbar (g, *this,
  50853. 0, thumbAreaStart,
  50854. getWidth(), thumbAreaSize,
  50855. vertical,
  50856. thumbStart, thumb,
  50857. isMouseOver(), isMouseButtonDown());
  50858. }
  50859. else
  50860. {
  50861. lf.drawScrollbar (g, *this,
  50862. thumbAreaStart, 0,
  50863. thumbAreaSize, getHeight(),
  50864. vertical,
  50865. thumbStart, thumb,
  50866. isMouseOver(), isMouseButtonDown());
  50867. }
  50868. }
  50869. }
  50870. void ScrollBar::lookAndFeelChanged()
  50871. {
  50872. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  50873. }
  50874. void ScrollBar::resized()
  50875. {
  50876. const int length = ((vertical) ? getHeight() : getWidth());
  50877. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  50878. : 0;
  50879. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50880. {
  50881. thumbAreaStart = length >> 1;
  50882. thumbAreaSize = 0;
  50883. }
  50884. else
  50885. {
  50886. thumbAreaStart = buttonSize;
  50887. thumbAreaSize = length - (buttonSize << 1);
  50888. }
  50889. if (upButton != 0)
  50890. {
  50891. if (vertical)
  50892. {
  50893. upButton->setBounds (0, 0, getWidth(), buttonSize);
  50894. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  50895. }
  50896. else
  50897. {
  50898. upButton->setBounds (0, 0, buttonSize, getHeight());
  50899. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  50900. }
  50901. }
  50902. updateThumbPosition();
  50903. }
  50904. void ScrollBar::mouseDown (const MouseEvent& e)
  50905. {
  50906. isDraggingThumb = false;
  50907. lastMousePos = vertical ? e.y : e.x;
  50908. dragStartMousePos = lastMousePos;
  50909. dragStartRange = visibleRange.getStart();
  50910. if (dragStartMousePos < thumbStart)
  50911. {
  50912. moveScrollbarInPages (-1);
  50913. startTimer (400);
  50914. }
  50915. else if (dragStartMousePos >= thumbStart + thumbSize)
  50916. {
  50917. moveScrollbarInPages (1);
  50918. startTimer (400);
  50919. }
  50920. else
  50921. {
  50922. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50923. && (thumbAreaSize > thumbSize);
  50924. }
  50925. }
  50926. void ScrollBar::mouseDrag (const MouseEvent& e)
  50927. {
  50928. if (isDraggingThumb)
  50929. {
  50930. const int deltaPixels = ((vertical) ? e.y : e.x) - dragStartMousePos;
  50931. setCurrentRangeStart (dragStartRange
  50932. + deltaPixels * (totalRange.getLength() - visibleRange.getLength())
  50933. / (thumbAreaSize - thumbSize));
  50934. }
  50935. else
  50936. {
  50937. lastMousePos = (vertical) ? e.y : e.x;
  50938. }
  50939. }
  50940. void ScrollBar::mouseUp (const MouseEvent&)
  50941. {
  50942. isDraggingThumb = false;
  50943. stopTimer();
  50944. repaint();
  50945. }
  50946. void ScrollBar::mouseWheelMove (const MouseEvent&,
  50947. float wheelIncrementX,
  50948. float wheelIncrementY)
  50949. {
  50950. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  50951. if (increment < 0)
  50952. increment = jmin (increment * 10.0f, -1.0f);
  50953. else if (increment > 0)
  50954. increment = jmax (increment * 10.0f, 1.0f);
  50955. setCurrentRange (visibleRange - singleStepSize * increment);
  50956. }
  50957. void ScrollBar::timerCallback()
  50958. {
  50959. if (isMouseButtonDown())
  50960. {
  50961. startTimer (40);
  50962. if (lastMousePos < thumbStart)
  50963. setCurrentRange (visibleRange - visibleRange.getLength());
  50964. else if (lastMousePos > thumbStart + thumbSize)
  50965. setCurrentRangeStart (visibleRange.getEnd());
  50966. }
  50967. else
  50968. {
  50969. stopTimer();
  50970. }
  50971. }
  50972. bool ScrollBar::keyPressed (const KeyPress& key)
  50973. {
  50974. if (! isVisible())
  50975. return false;
  50976. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  50977. moveScrollbarInSteps (-1);
  50978. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  50979. moveScrollbarInSteps (1);
  50980. else if (key.isKeyCode (KeyPress::pageUpKey))
  50981. moveScrollbarInPages (-1);
  50982. else if (key.isKeyCode (KeyPress::pageDownKey))
  50983. moveScrollbarInPages (1);
  50984. else if (key.isKeyCode (KeyPress::homeKey))
  50985. scrollToTop();
  50986. else if (key.isKeyCode (KeyPress::endKey))
  50987. scrollToBottom();
  50988. else
  50989. return false;
  50990. return true;
  50991. }
  50992. END_JUCE_NAMESPACE
  50993. /*** End of inlined file: juce_ScrollBar.cpp ***/
  50994. /*** Start of inlined file: juce_StretchableLayoutManager.cpp ***/
  50995. BEGIN_JUCE_NAMESPACE
  50996. StretchableLayoutManager::StretchableLayoutManager()
  50997. : totalSize (0)
  50998. {
  50999. }
  51000. StretchableLayoutManager::~StretchableLayoutManager()
  51001. {
  51002. }
  51003. void StretchableLayoutManager::clearAllItems()
  51004. {
  51005. items.clear();
  51006. totalSize = 0;
  51007. }
  51008. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  51009. const double minimumSize,
  51010. const double maximumSize,
  51011. const double preferredSize)
  51012. {
  51013. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  51014. if (layout == 0)
  51015. {
  51016. layout = new ItemLayoutProperties();
  51017. layout->itemIndex = itemIndex;
  51018. int i;
  51019. for (i = 0; i < items.size(); ++i)
  51020. if (items.getUnchecked (i)->itemIndex > itemIndex)
  51021. break;
  51022. items.insert (i, layout);
  51023. }
  51024. layout->minSize = minimumSize;
  51025. layout->maxSize = maximumSize;
  51026. layout->preferredSize = preferredSize;
  51027. layout->currentSize = 0;
  51028. }
  51029. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  51030. double& minimumSize,
  51031. double& maximumSize,
  51032. double& preferredSize) const
  51033. {
  51034. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  51035. if (layout != 0)
  51036. {
  51037. minimumSize = layout->minSize;
  51038. maximumSize = layout->maxSize;
  51039. preferredSize = layout->preferredSize;
  51040. return true;
  51041. }
  51042. return false;
  51043. }
  51044. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  51045. {
  51046. totalSize = newTotalSize;
  51047. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  51048. }
  51049. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  51050. {
  51051. int pos = 0;
  51052. for (int i = 0; i < itemIndex; ++i)
  51053. {
  51054. const ItemLayoutProperties* const layout = getInfoFor (i);
  51055. if (layout != 0)
  51056. pos += layout->currentSize;
  51057. }
  51058. return pos;
  51059. }
  51060. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  51061. {
  51062. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  51063. if (layout != 0)
  51064. return layout->currentSize;
  51065. return 0;
  51066. }
  51067. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  51068. {
  51069. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  51070. if (layout != 0)
  51071. return -layout->currentSize / (double) totalSize;
  51072. return 0;
  51073. }
  51074. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  51075. int newPosition)
  51076. {
  51077. for (int i = items.size(); --i >= 0;)
  51078. {
  51079. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  51080. if (layout->itemIndex == itemIndex)
  51081. {
  51082. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  51083. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  51084. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  51085. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  51086. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  51087. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  51088. endPos += layout->currentSize;
  51089. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  51090. updatePrefSizesToMatchCurrentPositions();
  51091. break;
  51092. }
  51093. }
  51094. }
  51095. void StretchableLayoutManager::layOutComponents (Component** const components,
  51096. int numComponents,
  51097. int x, int y, int w, int h,
  51098. const bool vertically,
  51099. const bool resizeOtherDimension)
  51100. {
  51101. setTotalSize (vertically ? h : w);
  51102. int pos = vertically ? y : x;
  51103. for (int i = 0; i < numComponents; ++i)
  51104. {
  51105. const ItemLayoutProperties* const layout = getInfoFor (i);
  51106. if (layout != 0)
  51107. {
  51108. Component* const c = components[i];
  51109. if (c != 0)
  51110. {
  51111. if (i == numComponents - 1)
  51112. {
  51113. // if it's the last item, crop it to exactly fit the available space..
  51114. if (resizeOtherDimension)
  51115. {
  51116. if (vertically)
  51117. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  51118. else
  51119. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  51120. }
  51121. else
  51122. {
  51123. if (vertically)
  51124. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  51125. else
  51126. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  51127. }
  51128. }
  51129. else
  51130. {
  51131. if (resizeOtherDimension)
  51132. {
  51133. if (vertically)
  51134. c->setBounds (x, pos, w, layout->currentSize);
  51135. else
  51136. c->setBounds (pos, y, layout->currentSize, h);
  51137. }
  51138. else
  51139. {
  51140. if (vertically)
  51141. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  51142. else
  51143. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  51144. }
  51145. }
  51146. }
  51147. pos += layout->currentSize;
  51148. }
  51149. }
  51150. }
  51151. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  51152. {
  51153. for (int i = items.size(); --i >= 0;)
  51154. if (items.getUnchecked(i)->itemIndex == itemIndex)
  51155. return items.getUnchecked(i);
  51156. return 0;
  51157. }
  51158. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  51159. const int endIndex,
  51160. const int availableSpace,
  51161. int startPos)
  51162. {
  51163. // calculate the total sizes
  51164. int i;
  51165. double totalIdealSize = 0.0;
  51166. int totalMinimums = 0;
  51167. for (i = startIndex; i < endIndex; ++i)
  51168. {
  51169. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51170. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  51171. totalMinimums += layout->currentSize;
  51172. totalIdealSize += sizeToRealSize (layout->preferredSize, totalSize);
  51173. }
  51174. if (totalIdealSize <= 0)
  51175. totalIdealSize = 1.0;
  51176. // now calc the best sizes..
  51177. int extraSpace = availableSpace - totalMinimums;
  51178. while (extraSpace > 0)
  51179. {
  51180. int numWantingMoreSpace = 0;
  51181. int numHavingTakenExtraSpace = 0;
  51182. // first figure out how many comps want a slice of the extra space..
  51183. for (i = startIndex; i < endIndex; ++i)
  51184. {
  51185. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51186. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51187. const int bestSize = jlimit (layout->currentSize,
  51188. jmax (layout->currentSize,
  51189. sizeToRealSize (layout->maxSize, totalSize)),
  51190. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51191. if (bestSize > layout->currentSize)
  51192. ++numWantingMoreSpace;
  51193. }
  51194. // ..share out the extra space..
  51195. for (i = startIndex; i < endIndex; ++i)
  51196. {
  51197. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51198. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51199. int bestSize = jlimit (layout->currentSize,
  51200. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  51201. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51202. const int extraWanted = bestSize - layout->currentSize;
  51203. if (extraWanted > 0)
  51204. {
  51205. const int extraAllowed = jmin (extraWanted,
  51206. extraSpace / jmax (1, numWantingMoreSpace));
  51207. if (extraAllowed > 0)
  51208. {
  51209. ++numHavingTakenExtraSpace;
  51210. --numWantingMoreSpace;
  51211. layout->currentSize += extraAllowed;
  51212. extraSpace -= extraAllowed;
  51213. }
  51214. }
  51215. }
  51216. if (numHavingTakenExtraSpace <= 0)
  51217. break;
  51218. }
  51219. // ..and calculate the end position
  51220. for (i = startIndex; i < endIndex; ++i)
  51221. {
  51222. ItemLayoutProperties* const layout = items.getUnchecked(i);
  51223. startPos += layout->currentSize;
  51224. }
  51225. return startPos;
  51226. }
  51227. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  51228. const int endIndex) const
  51229. {
  51230. int totalMinimums = 0;
  51231. for (int i = startIndex; i < endIndex; ++i)
  51232. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  51233. return totalMinimums;
  51234. }
  51235. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  51236. {
  51237. int totalMaximums = 0;
  51238. for (int i = startIndex; i < endIndex; ++i)
  51239. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  51240. return totalMaximums;
  51241. }
  51242. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  51243. {
  51244. for (int i = 0; i < items.size(); ++i)
  51245. {
  51246. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51247. layout->preferredSize
  51248. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  51249. : getItemCurrentAbsoluteSize (i);
  51250. }
  51251. }
  51252. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  51253. {
  51254. if (size < 0)
  51255. size *= -totalSpace;
  51256. return roundToInt (size);
  51257. }
  51258. END_JUCE_NAMESPACE
  51259. /*** End of inlined file: juce_StretchableLayoutManager.cpp ***/
  51260. /*** Start of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51261. BEGIN_JUCE_NAMESPACE
  51262. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  51263. const int itemIndex_,
  51264. const bool isVertical_)
  51265. : layout (layout_),
  51266. itemIndex (itemIndex_),
  51267. isVertical (isVertical_)
  51268. {
  51269. setRepaintsOnMouseActivity (true);
  51270. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  51271. : MouseCursor::UpDownResizeCursor));
  51272. }
  51273. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  51274. {
  51275. }
  51276. void StretchableLayoutResizerBar::paint (Graphics& g)
  51277. {
  51278. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  51279. getWidth(), getHeight(),
  51280. isVertical,
  51281. isMouseOver(),
  51282. isMouseButtonDown());
  51283. }
  51284. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  51285. {
  51286. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  51287. }
  51288. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  51289. {
  51290. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  51291. : e.getDistanceFromDragStartY());
  51292. layout->setItemPosition (itemIndex, desiredPos);
  51293. hasBeenMoved();
  51294. }
  51295. void StretchableLayoutResizerBar::hasBeenMoved()
  51296. {
  51297. if (getParentComponent() != 0)
  51298. getParentComponent()->resized();
  51299. }
  51300. END_JUCE_NAMESPACE
  51301. /*** End of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51302. /*** Start of inlined file: juce_StretchableObjectResizer.cpp ***/
  51303. BEGIN_JUCE_NAMESPACE
  51304. StretchableObjectResizer::StretchableObjectResizer()
  51305. {
  51306. }
  51307. StretchableObjectResizer::~StretchableObjectResizer()
  51308. {
  51309. }
  51310. void StretchableObjectResizer::addItem (const double size,
  51311. const double minSize, const double maxSize,
  51312. const int order)
  51313. {
  51314. // the order must be >= 0 but less than the maximum integer value.
  51315. jassert (order >= 0 && order < std::numeric_limits<int>::max());
  51316. Item* const item = new Item();
  51317. item->size = size;
  51318. item->minSize = minSize;
  51319. item->maxSize = maxSize;
  51320. item->order = order;
  51321. items.add (item);
  51322. }
  51323. double StretchableObjectResizer::getItemSize (const int index) const throw()
  51324. {
  51325. const Item* const it = items [index];
  51326. return it != 0 ? it->size : 0;
  51327. }
  51328. void StretchableObjectResizer::resizeToFit (const double targetSize)
  51329. {
  51330. int order = 0;
  51331. for (;;)
  51332. {
  51333. double currentSize = 0;
  51334. double minSize = 0;
  51335. double maxSize = 0;
  51336. int nextHighestOrder = std::numeric_limits<int>::max();
  51337. for (int i = 0; i < items.size(); ++i)
  51338. {
  51339. const Item* const it = items.getUnchecked(i);
  51340. currentSize += it->size;
  51341. if (it->order <= order)
  51342. {
  51343. minSize += it->minSize;
  51344. maxSize += it->maxSize;
  51345. }
  51346. else
  51347. {
  51348. minSize += it->size;
  51349. maxSize += it->size;
  51350. nextHighestOrder = jmin (nextHighestOrder, it->order);
  51351. }
  51352. }
  51353. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  51354. if (thisIterationTarget >= currentSize)
  51355. {
  51356. const double availableExtraSpace = maxSize - currentSize;
  51357. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  51358. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  51359. for (int i = 0; i < items.size(); ++i)
  51360. {
  51361. Item* const it = items.getUnchecked(i);
  51362. if (it->order <= order)
  51363. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  51364. }
  51365. }
  51366. else
  51367. {
  51368. const double amountOfSlack = currentSize - minSize;
  51369. const double targetAmountOfSlack = thisIterationTarget - minSize;
  51370. const double scale = targetAmountOfSlack / amountOfSlack;
  51371. for (int i = 0; i < items.size(); ++i)
  51372. {
  51373. Item* const it = items.getUnchecked(i);
  51374. if (it->order <= order)
  51375. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  51376. }
  51377. }
  51378. if (nextHighestOrder < std::numeric_limits<int>::max())
  51379. order = nextHighestOrder;
  51380. else
  51381. break;
  51382. }
  51383. }
  51384. END_JUCE_NAMESPACE
  51385. /*** End of inlined file: juce_StretchableObjectResizer.cpp ***/
  51386. /*** Start of inlined file: juce_TabbedButtonBar.cpp ***/
  51387. BEGIN_JUCE_NAMESPACE
  51388. TabBarButton::TabBarButton (const String& name,
  51389. TabbedButtonBar* const owner_,
  51390. const int index)
  51391. : Button (name),
  51392. owner (owner_),
  51393. tabIndex (index),
  51394. overlapPixels (0)
  51395. {
  51396. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  51397. setComponentEffect (&shadow);
  51398. setWantsKeyboardFocus (false);
  51399. }
  51400. TabBarButton::~TabBarButton()
  51401. {
  51402. }
  51403. void TabBarButton::paintButton (Graphics& g,
  51404. bool isMouseOverButton,
  51405. bool isButtonDown)
  51406. {
  51407. int x, y, w, h;
  51408. getActiveArea (x, y, w, h);
  51409. g.setOrigin (x, y);
  51410. getLookAndFeel()
  51411. .drawTabButton (g, w, h,
  51412. owner->getTabBackgroundColour (tabIndex),
  51413. tabIndex, getButtonText(), *this,
  51414. owner->getOrientation(),
  51415. isMouseOverButton, isButtonDown,
  51416. getToggleState());
  51417. }
  51418. void TabBarButton::clicked (const ModifierKeys& mods)
  51419. {
  51420. if (mods.isPopupMenu())
  51421. owner->popupMenuClickOnTab (tabIndex, getButtonText());
  51422. else
  51423. owner->setCurrentTabIndex (tabIndex);
  51424. }
  51425. bool TabBarButton::hitTest (int mx, int my)
  51426. {
  51427. int x, y, w, h;
  51428. getActiveArea (x, y, w, h);
  51429. if (owner->getOrientation() == TabbedButtonBar::TabsAtLeft
  51430. || owner->getOrientation() == TabbedButtonBar::TabsAtRight)
  51431. {
  51432. if (((unsigned int) mx) < (unsigned int) getWidth()
  51433. && my >= y + overlapPixels
  51434. && my < y + h - overlapPixels)
  51435. return true;
  51436. }
  51437. else
  51438. {
  51439. if (mx >= x + overlapPixels && mx < x + w - overlapPixels
  51440. && ((unsigned int) my) < (unsigned int) getHeight())
  51441. return true;
  51442. }
  51443. Path p;
  51444. getLookAndFeel()
  51445. .createTabButtonShape (p, w, h, tabIndex, getButtonText(), *this,
  51446. owner->getOrientation(),
  51447. false, false, getToggleState());
  51448. return p.contains ((float) (mx - x),
  51449. (float) (my - y));
  51450. }
  51451. int TabBarButton::getBestTabLength (const int depth)
  51452. {
  51453. return jlimit (depth * 2,
  51454. depth * 7,
  51455. getLookAndFeel().getTabButtonBestWidth (tabIndex, getButtonText(), depth, *this));
  51456. }
  51457. void TabBarButton::getActiveArea (int& x, int& y, int& w, int& h)
  51458. {
  51459. x = 0;
  51460. y = 0;
  51461. int r = getWidth();
  51462. int b = getHeight();
  51463. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  51464. if (owner->getOrientation() != TabbedButtonBar::TabsAtLeft)
  51465. r -= spaceAroundImage;
  51466. if (owner->getOrientation() != TabbedButtonBar::TabsAtRight)
  51467. x += spaceAroundImage;
  51468. if (owner->getOrientation() != TabbedButtonBar::TabsAtBottom)
  51469. y += spaceAroundImage;
  51470. if (owner->getOrientation() != TabbedButtonBar::TabsAtTop)
  51471. b -= spaceAroundImage;
  51472. w = r - x;
  51473. h = b - y;
  51474. }
  51475. class TabAreaBehindFrontButtonComponent : public Component
  51476. {
  51477. public:
  51478. TabAreaBehindFrontButtonComponent (TabbedButtonBar* const owner_)
  51479. : owner (owner_)
  51480. {
  51481. setInterceptsMouseClicks (false, false);
  51482. }
  51483. ~TabAreaBehindFrontButtonComponent()
  51484. {
  51485. }
  51486. void paint (Graphics& g)
  51487. {
  51488. getLookAndFeel()
  51489. .drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  51490. *owner, owner->getOrientation());
  51491. }
  51492. void enablementChanged()
  51493. {
  51494. repaint();
  51495. }
  51496. private:
  51497. TabbedButtonBar* const owner;
  51498. TabAreaBehindFrontButtonComponent (const TabAreaBehindFrontButtonComponent&);
  51499. TabAreaBehindFrontButtonComponent& operator= (const TabAreaBehindFrontButtonComponent&);
  51500. };
  51501. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  51502. : orientation (orientation_),
  51503. currentTabIndex (-1)
  51504. {
  51505. setInterceptsMouseClicks (false, true);
  51506. addAndMakeVisible (behindFrontTab = new TabAreaBehindFrontButtonComponent (this));
  51507. setFocusContainer (true);
  51508. }
  51509. TabbedButtonBar::~TabbedButtonBar()
  51510. {
  51511. extraTabsButton = 0;
  51512. deleteAllChildren();
  51513. }
  51514. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  51515. {
  51516. orientation = newOrientation;
  51517. for (int i = getNumChildComponents(); --i >= 0;)
  51518. getChildComponent (i)->resized();
  51519. resized();
  51520. }
  51521. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int index)
  51522. {
  51523. return new TabBarButton (name, this, index);
  51524. }
  51525. void TabbedButtonBar::clearTabs()
  51526. {
  51527. tabs.clear();
  51528. tabColours.clear();
  51529. currentTabIndex = -1;
  51530. extraTabsButton = 0;
  51531. removeChildComponent (behindFrontTab);
  51532. deleteAllChildren();
  51533. addChildComponent (behindFrontTab);
  51534. setCurrentTabIndex (-1);
  51535. }
  51536. void TabbedButtonBar::addTab (const String& tabName,
  51537. const Colour& tabBackgroundColour,
  51538. int insertIndex)
  51539. {
  51540. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  51541. if (tabName.isNotEmpty())
  51542. {
  51543. if (((unsigned int) insertIndex) > (unsigned int) tabs.size())
  51544. insertIndex = tabs.size();
  51545. for (int i = tabs.size(); --i >= insertIndex;)
  51546. {
  51547. TabBarButton* const tb = getTabButton (i);
  51548. if (tb != 0)
  51549. tb->tabIndex++;
  51550. }
  51551. tabs.insert (insertIndex, tabName);
  51552. tabColours.insert (insertIndex, tabBackgroundColour);
  51553. TabBarButton* const tb = createTabButton (tabName, insertIndex);
  51554. jassert (tb != 0); // your createTabButton() mustn't return zero!
  51555. addAndMakeVisible (tb, insertIndex);
  51556. resized();
  51557. if (currentTabIndex < 0)
  51558. setCurrentTabIndex (0);
  51559. }
  51560. }
  51561. void TabbedButtonBar::setTabName (const int tabIndex,
  51562. const String& newName)
  51563. {
  51564. if (((unsigned int) tabIndex) < (unsigned int) tabs.size()
  51565. && tabs[tabIndex] != newName)
  51566. {
  51567. tabs.set (tabIndex, newName);
  51568. TabBarButton* const tb = getTabButton (tabIndex);
  51569. if (tb != 0)
  51570. tb->setButtonText (newName);
  51571. resized();
  51572. }
  51573. }
  51574. void TabbedButtonBar::removeTab (const int tabIndex)
  51575. {
  51576. if (((unsigned int) tabIndex) < (unsigned int) tabs.size())
  51577. {
  51578. const int oldTabIndex = currentTabIndex;
  51579. if (currentTabIndex == tabIndex)
  51580. currentTabIndex = -1;
  51581. tabs.remove (tabIndex);
  51582. tabColours.remove (tabIndex);
  51583. delete getTabButton (tabIndex);
  51584. for (int i = tabIndex + 1; i <= tabs.size(); ++i)
  51585. {
  51586. TabBarButton* const tb = getTabButton (i);
  51587. if (tb != 0)
  51588. tb->tabIndex--;
  51589. }
  51590. resized();
  51591. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  51592. }
  51593. }
  51594. void TabbedButtonBar::moveTab (const int currentIndex,
  51595. const int newIndex)
  51596. {
  51597. tabs.move (currentIndex, newIndex);
  51598. tabColours.move (currentIndex, newIndex);
  51599. resized();
  51600. }
  51601. int TabbedButtonBar::getNumTabs() const
  51602. {
  51603. return tabs.size();
  51604. }
  51605. const StringArray TabbedButtonBar::getTabNames() const
  51606. {
  51607. return tabs;
  51608. }
  51609. void TabbedButtonBar::setCurrentTabIndex (int newIndex, const bool sendChangeMessage_)
  51610. {
  51611. if (currentTabIndex != newIndex)
  51612. {
  51613. if (((unsigned int) newIndex) >= (unsigned int) tabs.size())
  51614. newIndex = -1;
  51615. currentTabIndex = newIndex;
  51616. for (int i = 0; i < getNumChildComponents(); ++i)
  51617. {
  51618. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  51619. if (tb != 0)
  51620. tb->setToggleState (tb->tabIndex == newIndex, false);
  51621. }
  51622. resized();
  51623. if (sendChangeMessage_)
  51624. sendChangeMessage (this);
  51625. currentTabChanged (newIndex, newIndex >= 0 ? tabs [newIndex] : String::empty);
  51626. }
  51627. }
  51628. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  51629. {
  51630. for (int i = getNumChildComponents(); --i >= 0;)
  51631. {
  51632. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  51633. if (tb != 0 && tb->tabIndex == index)
  51634. return tb;
  51635. }
  51636. return 0;
  51637. }
  51638. void TabbedButtonBar::lookAndFeelChanged()
  51639. {
  51640. extraTabsButton = 0;
  51641. resized();
  51642. }
  51643. void TabbedButtonBar::resized()
  51644. {
  51645. const double minimumScale = 0.7;
  51646. int depth = getWidth();
  51647. int length = getHeight();
  51648. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51649. swapVariables (depth, length);
  51650. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  51651. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  51652. int i, totalLength = overlap;
  51653. int numVisibleButtons = tabs.size();
  51654. for (i = 0; i < getNumChildComponents(); ++i)
  51655. {
  51656. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  51657. if (tb != 0)
  51658. {
  51659. totalLength += tb->getBestTabLength (depth) - overlap;
  51660. tb->overlapPixels = overlap / 2;
  51661. }
  51662. }
  51663. double scale = 1.0;
  51664. if (totalLength > length)
  51665. scale = jmax (minimumScale, length / (double) totalLength);
  51666. const bool isTooBig = totalLength * scale > length;
  51667. int tabsButtonPos = 0;
  51668. if (isTooBig)
  51669. {
  51670. if (extraTabsButton == 0)
  51671. {
  51672. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  51673. extraTabsButton->addButtonListener (this);
  51674. extraTabsButton->setAlwaysOnTop (true);
  51675. extraTabsButton->setTriggeredOnMouseDown (true);
  51676. }
  51677. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  51678. extraTabsButton->setSize (buttonSize, buttonSize);
  51679. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51680. {
  51681. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  51682. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  51683. }
  51684. else
  51685. {
  51686. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  51687. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  51688. }
  51689. totalLength = 0;
  51690. for (i = 0; i < tabs.size(); ++i)
  51691. {
  51692. TabBarButton* const tb = getTabButton (i);
  51693. if (tb != 0)
  51694. {
  51695. const int newLength = totalLength + tb->getBestTabLength (depth);
  51696. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  51697. {
  51698. totalLength += overlap;
  51699. break;
  51700. }
  51701. numVisibleButtons = i + 1;
  51702. totalLength = newLength - overlap;
  51703. }
  51704. }
  51705. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  51706. }
  51707. else
  51708. {
  51709. extraTabsButton = 0;
  51710. }
  51711. int pos = 0;
  51712. TabBarButton* frontTab = 0;
  51713. for (i = 0; i < tabs.size(); ++i)
  51714. {
  51715. TabBarButton* const tb = getTabButton (i);
  51716. if (tb != 0)
  51717. {
  51718. const int bestLength = roundToInt (scale * tb->getBestTabLength (depth));
  51719. if (i < numVisibleButtons)
  51720. {
  51721. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51722. tb->setBounds (pos, 0, bestLength, getHeight());
  51723. else
  51724. tb->setBounds (0, pos, getWidth(), bestLength);
  51725. tb->toBack();
  51726. if (tb->tabIndex == currentTabIndex)
  51727. frontTab = tb;
  51728. tb->setVisible (true);
  51729. }
  51730. else
  51731. {
  51732. tb->setVisible (false);
  51733. }
  51734. pos += bestLength - overlap;
  51735. }
  51736. }
  51737. behindFrontTab->setBounds (getLocalBounds());
  51738. if (frontTab != 0)
  51739. {
  51740. frontTab->toFront (false);
  51741. behindFrontTab->toBehind (frontTab);
  51742. }
  51743. }
  51744. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  51745. {
  51746. return tabColours [tabIndex];
  51747. }
  51748. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51749. {
  51750. if (((unsigned int) tabIndex) < (unsigned int) tabColours.size()
  51751. && tabColours [tabIndex] != newColour)
  51752. {
  51753. tabColours.set (tabIndex, newColour);
  51754. repaint();
  51755. }
  51756. }
  51757. void TabbedButtonBar::buttonClicked (Button* button)
  51758. {
  51759. if (button == extraTabsButton)
  51760. {
  51761. PopupMenu m;
  51762. for (int i = 0; i < tabs.size(); ++i)
  51763. {
  51764. TabBarButton* const tb = getTabButton (i);
  51765. if (tb != 0 && ! tb->isVisible())
  51766. m.addItem (tb->tabIndex + 1, tabs[i], true, i == currentTabIndex);
  51767. }
  51768. const int res = m.showAt (extraTabsButton);
  51769. if (res != 0)
  51770. setCurrentTabIndex (res - 1);
  51771. }
  51772. }
  51773. void TabbedButtonBar::currentTabChanged (const int, const String&)
  51774. {
  51775. }
  51776. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  51777. {
  51778. }
  51779. END_JUCE_NAMESPACE
  51780. /*** End of inlined file: juce_TabbedButtonBar.cpp ***/
  51781. /*** Start of inlined file: juce_TabbedComponent.cpp ***/
  51782. BEGIN_JUCE_NAMESPACE
  51783. class TabCompButtonBar : public TabbedButtonBar
  51784. {
  51785. public:
  51786. TabCompButtonBar (TabbedComponent* const owner_,
  51787. const TabbedButtonBar::Orientation orientation_)
  51788. : TabbedButtonBar (orientation_),
  51789. owner (owner_)
  51790. {
  51791. }
  51792. ~TabCompButtonBar()
  51793. {
  51794. }
  51795. void currentTabChanged (int newCurrentTabIndex, const String& newTabName)
  51796. {
  51797. owner->changeCallback (newCurrentTabIndex, newTabName);
  51798. }
  51799. void popupMenuClickOnTab (int tabIndex, const String& tabName)
  51800. {
  51801. owner->popupMenuClickOnTab (tabIndex, tabName);
  51802. }
  51803. const Colour getTabBackgroundColour (const int tabIndex)
  51804. {
  51805. return owner->tabs->getTabBackgroundColour (tabIndex);
  51806. }
  51807. TabBarButton* createTabButton (const String& tabName, int tabIndex)
  51808. {
  51809. return owner->createTabButton (tabName, tabIndex);
  51810. }
  51811. juce_UseDebuggingNewOperator
  51812. private:
  51813. TabbedComponent* const owner;
  51814. TabCompButtonBar (const TabCompButtonBar&);
  51815. TabCompButtonBar& operator= (const TabCompButtonBar&);
  51816. };
  51817. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  51818. : panelComponent (0),
  51819. tabDepth (30),
  51820. outlineThickness (1),
  51821. edgeIndent (0)
  51822. {
  51823. addAndMakeVisible (tabs = new TabCompButtonBar (this, orientation));
  51824. }
  51825. TabbedComponent::~TabbedComponent()
  51826. {
  51827. clearTabs();
  51828. delete tabs;
  51829. }
  51830. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  51831. {
  51832. tabs->setOrientation (orientation);
  51833. resized();
  51834. }
  51835. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  51836. {
  51837. return tabs->getOrientation();
  51838. }
  51839. void TabbedComponent::setTabBarDepth (const int newDepth)
  51840. {
  51841. if (tabDepth != newDepth)
  51842. {
  51843. tabDepth = newDepth;
  51844. resized();
  51845. }
  51846. }
  51847. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int tabIndex)
  51848. {
  51849. return new TabBarButton (tabName, tabs, tabIndex);
  51850. }
  51851. const Identifier TabbedComponent::deleteComponentId ("deleteByTabComp_");
  51852. void TabbedComponent::clearTabs()
  51853. {
  51854. if (panelComponent != 0)
  51855. {
  51856. panelComponent->setVisible (false);
  51857. removeChildComponent (panelComponent);
  51858. panelComponent = 0;
  51859. }
  51860. tabs->clearTabs();
  51861. for (int i = contentComponents.size(); --i >= 0;)
  51862. {
  51863. Component* const c = contentComponents.getUnchecked(i);
  51864. // be careful not to delete these components until they've been removed from the tab component
  51865. jassert (c == 0 || c->isValidComponent());
  51866. if (c != 0 && (bool) c->getProperties() [deleteComponentId])
  51867. delete c;
  51868. }
  51869. contentComponents.clear();
  51870. }
  51871. void TabbedComponent::addTab (const String& tabName,
  51872. const Colour& tabBackgroundColour,
  51873. Component* const contentComponent,
  51874. const bool deleteComponentWhenNotNeeded,
  51875. const int insertIndex)
  51876. {
  51877. contentComponents.insert (insertIndex, contentComponent);
  51878. if (contentComponent != 0)
  51879. contentComponent->getProperties().set (deleteComponentId, deleteComponentWhenNotNeeded);
  51880. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  51881. }
  51882. void TabbedComponent::setTabName (const int tabIndex, const String& newName)
  51883. {
  51884. tabs->setTabName (tabIndex, newName);
  51885. }
  51886. void TabbedComponent::removeTab (const int tabIndex)
  51887. {
  51888. Component* const c = contentComponents [tabIndex];
  51889. if (c != 0 && (bool) c->getProperties() [deleteComponentId])
  51890. {
  51891. if (c == panelComponent)
  51892. panelComponent = 0;
  51893. delete c;
  51894. }
  51895. contentComponents.remove (tabIndex);
  51896. tabs->removeTab (tabIndex);
  51897. }
  51898. int TabbedComponent::getNumTabs() const
  51899. {
  51900. return tabs->getNumTabs();
  51901. }
  51902. const StringArray TabbedComponent::getTabNames() const
  51903. {
  51904. return tabs->getTabNames();
  51905. }
  51906. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  51907. {
  51908. return contentComponents [tabIndex];
  51909. }
  51910. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  51911. {
  51912. return tabs->getTabBackgroundColour (tabIndex);
  51913. }
  51914. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51915. {
  51916. tabs->setTabBackgroundColour (tabIndex, newColour);
  51917. if (getCurrentTabIndex() == tabIndex)
  51918. repaint();
  51919. }
  51920. void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
  51921. {
  51922. tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
  51923. }
  51924. int TabbedComponent::getCurrentTabIndex() const
  51925. {
  51926. return tabs->getCurrentTabIndex();
  51927. }
  51928. const String& TabbedComponent::getCurrentTabName() const
  51929. {
  51930. return tabs->getCurrentTabName();
  51931. }
  51932. void TabbedComponent::setOutline (int thickness)
  51933. {
  51934. outlineThickness = thickness;
  51935. repaint();
  51936. }
  51937. void TabbedComponent::setIndent (const int indentThickness)
  51938. {
  51939. edgeIndent = indentThickness;
  51940. }
  51941. void TabbedComponent::paint (Graphics& g)
  51942. {
  51943. g.fillAll (findColour (backgroundColourId));
  51944. const TabbedButtonBar::Orientation o = getOrientation();
  51945. int x = 0;
  51946. int y = 0;
  51947. int r = getWidth();
  51948. int b = getHeight();
  51949. if (o == TabbedButtonBar::TabsAtTop)
  51950. y += tabDepth;
  51951. else if (o == TabbedButtonBar::TabsAtBottom)
  51952. b -= tabDepth;
  51953. else if (o == TabbedButtonBar::TabsAtLeft)
  51954. x += tabDepth;
  51955. else if (o == TabbedButtonBar::TabsAtRight)
  51956. r -= tabDepth;
  51957. g.reduceClipRegion (x, y, r - x, b - y);
  51958. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  51959. if (outlineThickness > 0)
  51960. {
  51961. if (o == TabbedButtonBar::TabsAtTop)
  51962. --y;
  51963. else if (o == TabbedButtonBar::TabsAtBottom)
  51964. ++b;
  51965. else if (o == TabbedButtonBar::TabsAtLeft)
  51966. --x;
  51967. else if (o == TabbedButtonBar::TabsAtRight)
  51968. ++r;
  51969. g.setColour (findColour (outlineColourId));
  51970. g.drawRect (x, y, r - x, b - y, outlineThickness);
  51971. }
  51972. }
  51973. void TabbedComponent::resized()
  51974. {
  51975. const TabbedButtonBar::Orientation o = getOrientation();
  51976. const int indent = edgeIndent + outlineThickness;
  51977. BorderSize indents (indent);
  51978. if (o == TabbedButtonBar::TabsAtTop)
  51979. {
  51980. tabs->setBounds (0, 0, getWidth(), tabDepth);
  51981. indents.setTop (tabDepth + edgeIndent);
  51982. }
  51983. else if (o == TabbedButtonBar::TabsAtBottom)
  51984. {
  51985. tabs->setBounds (0, getHeight() - tabDepth, getWidth(), tabDepth);
  51986. indents.setBottom (tabDepth + edgeIndent);
  51987. }
  51988. else if (o == TabbedButtonBar::TabsAtLeft)
  51989. {
  51990. tabs->setBounds (0, 0, tabDepth, getHeight());
  51991. indents.setLeft (tabDepth + edgeIndent);
  51992. }
  51993. else if (o == TabbedButtonBar::TabsAtRight)
  51994. {
  51995. tabs->setBounds (getWidth() - tabDepth, 0, tabDepth, getHeight());
  51996. indents.setRight (tabDepth + edgeIndent);
  51997. }
  51998. const Rectangle<int> bounds (indents.subtractedFrom (getLocalBounds()));
  51999. for (int i = contentComponents.size(); --i >= 0;)
  52000. if (contentComponents.getUnchecked (i) != 0)
  52001. contentComponents.getUnchecked (i)->setBounds (bounds);
  52002. }
  52003. void TabbedComponent::lookAndFeelChanged()
  52004. {
  52005. for (int i = contentComponents.size(); --i >= 0;)
  52006. if (contentComponents.getUnchecked (i) != 0)
  52007. contentComponents.getUnchecked (i)->lookAndFeelChanged();
  52008. }
  52009. void TabbedComponent::changeCallback (const int newCurrentTabIndex,
  52010. const String& newTabName)
  52011. {
  52012. if (panelComponent != 0)
  52013. {
  52014. panelComponent->setVisible (false);
  52015. removeChildComponent (panelComponent);
  52016. panelComponent = 0;
  52017. }
  52018. if (getCurrentTabIndex() >= 0)
  52019. {
  52020. panelComponent = contentComponents [getCurrentTabIndex()];
  52021. if (panelComponent != 0)
  52022. {
  52023. // do these ops as two stages instead of addAndMakeVisible() so that the
  52024. // component has always got a parent when it gets the visibilityChanged() callback
  52025. addChildComponent (panelComponent);
  52026. panelComponent->setVisible (true);
  52027. panelComponent->toFront (true);
  52028. }
  52029. repaint();
  52030. }
  52031. resized();
  52032. currentTabChanged (newCurrentTabIndex, newTabName);
  52033. }
  52034. void TabbedComponent::currentTabChanged (const int, const String&)
  52035. {
  52036. }
  52037. void TabbedComponent::popupMenuClickOnTab (const int, const String&)
  52038. {
  52039. }
  52040. END_JUCE_NAMESPACE
  52041. /*** End of inlined file: juce_TabbedComponent.cpp ***/
  52042. /*** Start of inlined file: juce_Viewport.cpp ***/
  52043. BEGIN_JUCE_NAMESPACE
  52044. Viewport::Viewport (const String& componentName)
  52045. : Component (componentName),
  52046. scrollBarThickness (0),
  52047. singleStepX (16),
  52048. singleStepY (16),
  52049. showHScrollbar (true),
  52050. showVScrollbar (true),
  52051. verticalScrollBar (true),
  52052. horizontalScrollBar (false)
  52053. {
  52054. // content holder is used to clip the contents so they don't overlap the scrollbars
  52055. addAndMakeVisible (&contentHolder);
  52056. contentHolder.setInterceptsMouseClicks (false, true);
  52057. addChildComponent (&verticalScrollBar);
  52058. addChildComponent (&horizontalScrollBar);
  52059. verticalScrollBar.addListener (this);
  52060. horizontalScrollBar.addListener (this);
  52061. setInterceptsMouseClicks (false, true);
  52062. setWantsKeyboardFocus (true);
  52063. }
  52064. Viewport::~Viewport()
  52065. {
  52066. contentHolder.deleteAllChildren();
  52067. }
  52068. void Viewport::visibleAreaChanged (int, int, int, int)
  52069. {
  52070. }
  52071. void Viewport::setViewedComponent (Component* const newViewedComponent)
  52072. {
  52073. if (contentComp.getComponent() != newViewedComponent)
  52074. {
  52075. {
  52076. ScopedPointer<Component> oldCompDeleter (contentComp);
  52077. contentComp = 0;
  52078. }
  52079. contentComp = newViewedComponent;
  52080. if (contentComp != 0)
  52081. {
  52082. contentComp->setTopLeftPosition (0, 0);
  52083. contentHolder.addAndMakeVisible (contentComp);
  52084. contentComp->addComponentListener (this);
  52085. }
  52086. updateVisibleArea();
  52087. }
  52088. }
  52089. int Viewport::getMaximumVisibleWidth() const
  52090. {
  52091. return contentHolder.getWidth();
  52092. }
  52093. int Viewport::getMaximumVisibleHeight() const
  52094. {
  52095. return contentHolder.getHeight();
  52096. }
  52097. void Viewport::setViewPosition (const int xPixelsOffset, const int yPixelsOffset)
  52098. {
  52099. if (contentComp != 0)
  52100. contentComp->setTopLeftPosition (jmax (jmin (0, contentHolder.getWidth() - contentComp->getWidth()), jmin (0, -xPixelsOffset)),
  52101. jmax (jmin (0, contentHolder.getHeight() - contentComp->getHeight()), jmin (0, -yPixelsOffset)));
  52102. }
  52103. void Viewport::setViewPosition (const Point<int>& newPosition)
  52104. {
  52105. setViewPosition (newPosition.getX(), newPosition.getY());
  52106. }
  52107. void Viewport::setViewPositionProportionately (const double x, const double y)
  52108. {
  52109. if (contentComp != 0)
  52110. setViewPosition (jmax (0, roundToInt (x * (contentComp->getWidth() - getWidth()))),
  52111. jmax (0, roundToInt (y * (contentComp->getHeight() - getHeight()))));
  52112. }
  52113. bool Viewport::autoScroll (const int mouseX, const int mouseY, const int activeBorderThickness, const int maximumSpeed)
  52114. {
  52115. if (contentComp != 0)
  52116. {
  52117. int dx = 0, dy = 0;
  52118. if (horizontalScrollBar.isVisible() || contentComp->getX() < 0 || contentComp->getRight() > getWidth())
  52119. {
  52120. if (mouseX < activeBorderThickness)
  52121. dx = activeBorderThickness - mouseX;
  52122. else if (mouseX >= contentHolder.getWidth() - activeBorderThickness)
  52123. dx = (contentHolder.getWidth() - activeBorderThickness) - mouseX;
  52124. if (dx < 0)
  52125. dx = jmax (dx, -maximumSpeed, contentHolder.getWidth() - contentComp->getRight());
  52126. else
  52127. dx = jmin (dx, maximumSpeed, -contentComp->getX());
  52128. }
  52129. if (verticalScrollBar.isVisible() || contentComp->getY() < 0 || contentComp->getBottom() > getHeight())
  52130. {
  52131. if (mouseY < activeBorderThickness)
  52132. dy = activeBorderThickness - mouseY;
  52133. else if (mouseY >= contentHolder.getHeight() - activeBorderThickness)
  52134. dy = (contentHolder.getHeight() - activeBorderThickness) - mouseY;
  52135. if (dy < 0)
  52136. dy = jmax (dy, -maximumSpeed, contentHolder.getHeight() - contentComp->getBottom());
  52137. else
  52138. dy = jmin (dy, maximumSpeed, -contentComp->getY());
  52139. }
  52140. if (dx != 0 || dy != 0)
  52141. {
  52142. contentComp->setTopLeftPosition (contentComp->getX() + dx,
  52143. contentComp->getY() + dy);
  52144. return true;
  52145. }
  52146. }
  52147. return false;
  52148. }
  52149. void Viewport::componentMovedOrResized (Component&, bool, bool)
  52150. {
  52151. updateVisibleArea();
  52152. }
  52153. void Viewport::resized()
  52154. {
  52155. updateVisibleArea();
  52156. }
  52157. void Viewport::updateVisibleArea()
  52158. {
  52159. const int scrollbarWidth = getScrollBarThickness();
  52160. const bool canShowAnyBars = getWidth() > scrollbarWidth && getHeight() > scrollbarWidth;
  52161. const bool canShowHBar = showHScrollbar && canShowAnyBars;
  52162. const bool canShowVBar = showVScrollbar && canShowAnyBars;
  52163. bool hBarVisible = canShowHBar && ! horizontalScrollBar.autoHides();
  52164. bool vBarVisible = canShowVBar && ! verticalScrollBar.autoHides();
  52165. Rectangle<int> contentArea (getLocalBounds());
  52166. if (contentComp != 0 && ! contentArea.contains (contentComp->getBounds()))
  52167. {
  52168. hBarVisible = canShowHBar && (hBarVisible || contentComp->getX() < 0 || contentComp->getRight() > contentArea.getWidth());
  52169. vBarVisible = canShowVBar && (vBarVisible || contentComp->getY() < 0 || contentComp->getBottom() > contentArea.getHeight());
  52170. if (vBarVisible)
  52171. contentArea.setWidth (getWidth() - scrollbarWidth);
  52172. if (hBarVisible)
  52173. contentArea.setHeight (getHeight() - scrollbarWidth);
  52174. if (! contentArea.contains (contentComp->getBounds()))
  52175. {
  52176. hBarVisible = canShowHBar && (hBarVisible || contentComp->getRight() > contentArea.getWidth());
  52177. vBarVisible = canShowVBar && (vBarVisible || contentComp->getBottom() > contentArea.getHeight());
  52178. }
  52179. }
  52180. if (vBarVisible)
  52181. contentArea.setWidth (getWidth() - scrollbarWidth);
  52182. if (hBarVisible)
  52183. contentArea.setHeight (getHeight() - scrollbarWidth);
  52184. contentHolder.setBounds (contentArea);
  52185. Rectangle<int> contentBounds;
  52186. if (contentComp != 0)
  52187. contentBounds = contentComp->getBounds();
  52188. const Point<int> visibleOrigin (-contentBounds.getPosition());
  52189. if (hBarVisible)
  52190. {
  52191. horizontalScrollBar.setBounds (0, contentArea.getHeight(), contentArea.getWidth(), scrollbarWidth);
  52192. horizontalScrollBar.setRangeLimits (0.0, contentBounds.getWidth());
  52193. horizontalScrollBar.setCurrentRange (visibleOrigin.getX(), contentArea.getWidth());
  52194. horizontalScrollBar.setSingleStepSize (singleStepX);
  52195. horizontalScrollBar.cancelPendingUpdate();
  52196. }
  52197. if (vBarVisible)
  52198. {
  52199. verticalScrollBar.setBounds (contentArea.getWidth(), 0, scrollbarWidth, contentArea.getHeight());
  52200. verticalScrollBar.setRangeLimits (0.0, contentBounds.getHeight());
  52201. verticalScrollBar.setCurrentRange (visibleOrigin.getY(), contentArea.getHeight());
  52202. verticalScrollBar.setSingleStepSize (singleStepY);
  52203. verticalScrollBar.cancelPendingUpdate();
  52204. }
  52205. // Force the visibility *after* setting the ranges to avoid flicker caused by edge conditions in the numbers.
  52206. horizontalScrollBar.setVisible (hBarVisible);
  52207. verticalScrollBar.setVisible (vBarVisible);
  52208. const Rectangle<int> visibleArea (visibleOrigin.getX(), visibleOrigin.getY(),
  52209. jmin (contentBounds.getWidth() - visibleOrigin.getX(), contentArea.getWidth()),
  52210. jmin (contentBounds.getHeight() - visibleOrigin.getY(), contentArea.getHeight()));
  52211. if (lastVisibleArea != visibleArea)
  52212. {
  52213. lastVisibleArea = visibleArea;
  52214. visibleAreaChanged (visibleArea.getX(), visibleArea.getY(), visibleArea.getWidth(), visibleArea.getHeight());
  52215. }
  52216. horizontalScrollBar.handleUpdateNowIfNeeded();
  52217. verticalScrollBar.handleUpdateNowIfNeeded();
  52218. }
  52219. void Viewport::setSingleStepSizes (const int stepX, const int stepY)
  52220. {
  52221. if (singleStepX != stepX || singleStepY != stepY)
  52222. {
  52223. singleStepX = stepX;
  52224. singleStepY = stepY;
  52225. updateVisibleArea();
  52226. }
  52227. }
  52228. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  52229. const bool showHorizontalScrollbarIfNeeded)
  52230. {
  52231. if (showVScrollbar != showVerticalScrollbarIfNeeded
  52232. || showHScrollbar != showHorizontalScrollbarIfNeeded)
  52233. {
  52234. showVScrollbar = showVerticalScrollbarIfNeeded;
  52235. showHScrollbar = showHorizontalScrollbarIfNeeded;
  52236. updateVisibleArea();
  52237. }
  52238. }
  52239. void Viewport::setScrollBarThickness (const int thickness)
  52240. {
  52241. if (scrollBarThickness != thickness)
  52242. {
  52243. scrollBarThickness = thickness;
  52244. updateVisibleArea();
  52245. }
  52246. }
  52247. int Viewport::getScrollBarThickness() const
  52248. {
  52249. return scrollBarThickness > 0 ? scrollBarThickness
  52250. : getLookAndFeel().getDefaultScrollbarWidth();
  52251. }
  52252. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  52253. {
  52254. verticalScrollBar.setButtonVisibility (buttonsVisible);
  52255. horizontalScrollBar.setButtonVisibility (buttonsVisible);
  52256. }
  52257. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  52258. {
  52259. const int newRangeStartInt = roundToInt (newRangeStart);
  52260. if (scrollBarThatHasMoved == &horizontalScrollBar)
  52261. {
  52262. setViewPosition (newRangeStartInt, getViewPositionY());
  52263. }
  52264. else if (scrollBarThatHasMoved == &verticalScrollBar)
  52265. {
  52266. setViewPosition (getViewPositionX(), newRangeStartInt);
  52267. }
  52268. }
  52269. void Viewport::mouseWheelMove (const MouseEvent& e, const float wheelIncrementX, const float wheelIncrementY)
  52270. {
  52271. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  52272. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  52273. }
  52274. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  52275. {
  52276. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  52277. {
  52278. const bool hasVertBar = verticalScrollBar.isVisible();
  52279. const bool hasHorzBar = horizontalScrollBar.isVisible();
  52280. if (hasHorzBar || hasVertBar)
  52281. {
  52282. if (wheelIncrementX != 0)
  52283. {
  52284. wheelIncrementX *= 14.0f * singleStepX;
  52285. wheelIncrementX = (wheelIncrementX < 0) ? jmin (wheelIncrementX, -1.0f)
  52286. : jmax (wheelIncrementX, 1.0f);
  52287. }
  52288. if (wheelIncrementY != 0)
  52289. {
  52290. wheelIncrementY *= 14.0f * singleStepY;
  52291. wheelIncrementY = (wheelIncrementY < 0) ? jmin (wheelIncrementY, -1.0f)
  52292. : jmax (wheelIncrementY, 1.0f);
  52293. }
  52294. Point<int> pos (getViewPosition());
  52295. if (wheelIncrementX != 0 && wheelIncrementY != 0 && hasHorzBar && hasVertBar)
  52296. {
  52297. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52298. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52299. }
  52300. else if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  52301. {
  52302. if (wheelIncrementX == 0 && ! hasVertBar)
  52303. wheelIncrementX = wheelIncrementY;
  52304. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52305. }
  52306. else if (hasVertBar && wheelIncrementY != 0)
  52307. {
  52308. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52309. }
  52310. if (pos != getViewPosition())
  52311. {
  52312. setViewPosition (pos);
  52313. return true;
  52314. }
  52315. }
  52316. }
  52317. return false;
  52318. }
  52319. bool Viewport::keyPressed (const KeyPress& key)
  52320. {
  52321. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  52322. || key.isKeyCode (KeyPress::downKey)
  52323. || key.isKeyCode (KeyPress::pageUpKey)
  52324. || key.isKeyCode (KeyPress::pageDownKey)
  52325. || key.isKeyCode (KeyPress::homeKey)
  52326. || key.isKeyCode (KeyPress::endKey);
  52327. if (verticalScrollBar.isVisible() && isUpDownKey)
  52328. return verticalScrollBar.keyPressed (key);
  52329. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  52330. || key.isKeyCode (KeyPress::rightKey);
  52331. if (horizontalScrollBar.isVisible() && (isUpDownKey || isLeftRightKey))
  52332. return horizontalScrollBar.keyPressed (key);
  52333. return false;
  52334. }
  52335. END_JUCE_NAMESPACE
  52336. /*** End of inlined file: juce_Viewport.cpp ***/
  52337. /*** Start of inlined file: juce_LookAndFeel.cpp ***/
  52338. BEGIN_JUCE_NAMESPACE
  52339. static const Colour createBaseColour (const Colour& buttonColour,
  52340. const bool hasKeyboardFocus,
  52341. const bool isMouseOverButton,
  52342. const bool isButtonDown) throw()
  52343. {
  52344. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  52345. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  52346. if (isButtonDown)
  52347. return baseColour.contrasting (0.2f);
  52348. else if (isMouseOverButton)
  52349. return baseColour.contrasting (0.1f);
  52350. return baseColour;
  52351. }
  52352. LookAndFeel::LookAndFeel()
  52353. {
  52354. /* if this fails it means you're trying to create a LookAndFeel object before
  52355. the static Colours have been initialised. That ain't gonna work. It probably
  52356. means that you're using a static LookAndFeel object and that your compiler has
  52357. decided to intialise it before the Colours class.
  52358. */
  52359. jassert (Colours::white == Colour (0xffffffff));
  52360. // set up the standard set of colours..
  52361. const int textButtonColour = 0xffbbbbff;
  52362. const int textHighlightColour = 0x401111ee;
  52363. const int standardOutlineColour = 0xb2808080;
  52364. static const int standardColours[] =
  52365. {
  52366. TextButton::buttonColourId, textButtonColour,
  52367. TextButton::buttonOnColourId, 0xff4444ff,
  52368. TextButton::textColourOnId, 0xff000000,
  52369. TextButton::textColourOffId, 0xff000000,
  52370. ComboBox::buttonColourId, 0xffbbbbff,
  52371. ComboBox::outlineColourId, standardOutlineColour,
  52372. ToggleButton::textColourId, 0xff000000,
  52373. TextEditor::backgroundColourId, 0xffffffff,
  52374. TextEditor::textColourId, 0xff000000,
  52375. TextEditor::highlightColourId, textHighlightColour,
  52376. TextEditor::highlightedTextColourId, 0xff000000,
  52377. TextEditor::caretColourId, 0xff000000,
  52378. TextEditor::outlineColourId, 0x00000000,
  52379. TextEditor::focusedOutlineColourId, textButtonColour,
  52380. TextEditor::shadowColourId, 0x38000000,
  52381. Label::backgroundColourId, 0x00000000,
  52382. Label::textColourId, 0xff000000,
  52383. Label::outlineColourId, 0x00000000,
  52384. ScrollBar::backgroundColourId, 0x00000000,
  52385. ScrollBar::thumbColourId, 0xffffffff,
  52386. ScrollBar::trackColourId, 0xffffffff,
  52387. TreeView::linesColourId, 0x4c000000,
  52388. TreeView::backgroundColourId, 0x00000000,
  52389. TreeView::dragAndDropIndicatorColourId, 0x80ff0000,
  52390. PopupMenu::backgroundColourId, 0xffffffff,
  52391. PopupMenu::textColourId, 0xff000000,
  52392. PopupMenu::headerTextColourId, 0xff000000,
  52393. PopupMenu::highlightedTextColourId, 0xffffffff,
  52394. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  52395. ComboBox::textColourId, 0xff000000,
  52396. ComboBox::backgroundColourId, 0xffffffff,
  52397. ComboBox::arrowColourId, 0x99000000,
  52398. ListBox::backgroundColourId, 0xffffffff,
  52399. ListBox::outlineColourId, standardOutlineColour,
  52400. ListBox::textColourId, 0xff000000,
  52401. Slider::backgroundColourId, 0x00000000,
  52402. Slider::thumbColourId, textButtonColour,
  52403. Slider::trackColourId, 0x7fffffff,
  52404. Slider::rotarySliderFillColourId, 0x7f0000ff,
  52405. Slider::rotarySliderOutlineColourId, 0x66000000,
  52406. Slider::textBoxTextColourId, 0xff000000,
  52407. Slider::textBoxBackgroundColourId, 0xffffffff,
  52408. Slider::textBoxHighlightColourId, textHighlightColour,
  52409. Slider::textBoxOutlineColourId, standardOutlineColour,
  52410. ResizableWindow::backgroundColourId, 0xff777777,
  52411. //DocumentWindow::textColourId, 0xff000000, // (this is deliberately not set)
  52412. AlertWindow::backgroundColourId, 0xffededed,
  52413. AlertWindow::textColourId, 0xff000000,
  52414. AlertWindow::outlineColourId, 0xff666666,
  52415. ProgressBar::backgroundColourId, 0xffeeeeee,
  52416. ProgressBar::foregroundColourId, 0xffaaaaee,
  52417. TooltipWindow::backgroundColourId, 0xffeeeebb,
  52418. TooltipWindow::textColourId, 0xff000000,
  52419. TooltipWindow::outlineColourId, 0x4c000000,
  52420. TabbedComponent::backgroundColourId, 0x00000000,
  52421. TabbedComponent::outlineColourId, 0xff777777,
  52422. TabbedButtonBar::tabOutlineColourId, 0x80000000,
  52423. TabbedButtonBar::frontOutlineColourId, 0x90000000,
  52424. Toolbar::backgroundColourId, 0xfff6f8f9,
  52425. Toolbar::separatorColourId, 0x4c000000,
  52426. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  52427. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  52428. Toolbar::labelTextColourId, 0xff000000,
  52429. Toolbar::editingModeOutlineColourId, 0xffff0000,
  52430. HyperlinkButton::textColourId, 0xcc1111ee,
  52431. GroupComponent::outlineColourId, 0x66000000,
  52432. GroupComponent::textColourId, 0xff000000,
  52433. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  52434. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  52435. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  52436. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  52437. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  52438. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  52439. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  52440. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  52441. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  52442. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  52443. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  52444. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  52445. CodeEditorComponent::backgroundColourId, 0xffffffff,
  52446. CodeEditorComponent::caretColourId, 0xff000000,
  52447. CodeEditorComponent::highlightColourId, textHighlightColour,
  52448. CodeEditorComponent::defaultTextColourId, 0xff000000,
  52449. ColourSelector::backgroundColourId, 0xffe5e5e5,
  52450. ColourSelector::labelTextColourId, 0xff000000,
  52451. KeyMappingEditorComponent::backgroundColourId, 0x00000000,
  52452. KeyMappingEditorComponent::textColourId, 0xff000000,
  52453. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  52454. FileChooserDialogBox::titleTextColourId, 0xff000000,
  52455. DrawableButton::textColourId, 0xff000000,
  52456. };
  52457. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  52458. setColour (standardColours [i], Colour (standardColours [i + 1]));
  52459. static String defaultSansName, defaultSerifName, defaultFixedName;
  52460. if (defaultSansName.isEmpty())
  52461. Font::getPlatformDefaultFontNames (defaultSansName, defaultSerifName, defaultFixedName);
  52462. defaultSans = defaultSansName;
  52463. defaultSerif = defaultSerifName;
  52464. defaultFixed = defaultFixedName;
  52465. }
  52466. LookAndFeel::~LookAndFeel()
  52467. {
  52468. }
  52469. const Colour LookAndFeel::findColour (const int colourId) const throw()
  52470. {
  52471. const int index = colourIds.indexOf (colourId);
  52472. if (index >= 0)
  52473. return colours [index];
  52474. jassertfalse;
  52475. return Colours::black;
  52476. }
  52477. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  52478. {
  52479. const int index = colourIds.indexOf (colourId);
  52480. if (index >= 0)
  52481. {
  52482. colours.set (index, colour);
  52483. }
  52484. else
  52485. {
  52486. colourIds.add (colourId);
  52487. colours.add (colour);
  52488. }
  52489. }
  52490. bool LookAndFeel::isColourSpecified (const int colourId) const throw()
  52491. {
  52492. return colourIds.contains (colourId);
  52493. }
  52494. static LookAndFeel* defaultLF = 0;
  52495. static LookAndFeel* currentDefaultLF = 0;
  52496. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  52497. {
  52498. // if this happens, your app hasn't initialised itself properly.. if you're
  52499. // trying to hack your own main() function, have a look at
  52500. // JUCEApplication::initialiseForGUI()
  52501. jassert (currentDefaultLF != 0);
  52502. return *currentDefaultLF;
  52503. }
  52504. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  52505. {
  52506. if (newDefaultLookAndFeel == 0)
  52507. {
  52508. if (defaultLF == 0)
  52509. defaultLF = new LookAndFeel();
  52510. newDefaultLookAndFeel = defaultLF;
  52511. }
  52512. currentDefaultLF = newDefaultLookAndFeel;
  52513. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  52514. {
  52515. Component* const c = Desktop::getInstance().getComponent (i);
  52516. if (c != 0)
  52517. c->sendLookAndFeelChange();
  52518. }
  52519. }
  52520. void LookAndFeel::clearDefaultLookAndFeel() throw()
  52521. {
  52522. if (currentDefaultLF == defaultLF)
  52523. currentDefaultLF = 0;
  52524. deleteAndZero (defaultLF);
  52525. }
  52526. const Typeface::Ptr LookAndFeel::getTypefaceForFont (const Font& font)
  52527. {
  52528. String faceName (font.getTypefaceName());
  52529. if (faceName == Font::getDefaultSansSerifFontName())
  52530. faceName = defaultSans;
  52531. else if (faceName == Font::getDefaultSerifFontName())
  52532. faceName = defaultSerif;
  52533. else if (faceName == Font::getDefaultMonospacedFontName())
  52534. faceName = defaultFixed;
  52535. Font f (font);
  52536. f.setTypefaceName (faceName);
  52537. return Typeface::createSystemTypefaceFor (f);
  52538. }
  52539. void LookAndFeel::setDefaultSansSerifTypefaceName (const String& newName)
  52540. {
  52541. defaultSans = newName;
  52542. }
  52543. const MouseCursor LookAndFeel::getMouseCursorFor (Component& component)
  52544. {
  52545. return component.getMouseCursor();
  52546. }
  52547. void LookAndFeel::drawButtonBackground (Graphics& g,
  52548. Button& button,
  52549. const Colour& backgroundColour,
  52550. bool isMouseOverButton,
  52551. bool isButtonDown)
  52552. {
  52553. const int width = button.getWidth();
  52554. const int height = button.getHeight();
  52555. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  52556. const float halfThickness = outlineThickness * 0.5f;
  52557. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  52558. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  52559. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  52560. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  52561. const Colour baseColour (createBaseColour (backgroundColour,
  52562. button.hasKeyboardFocus (true),
  52563. isMouseOverButton, isButtonDown)
  52564. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52565. drawGlassLozenge (g,
  52566. indentL,
  52567. indentT,
  52568. width - indentL - indentR,
  52569. height - indentT - indentB,
  52570. baseColour, outlineThickness, -1.0f,
  52571. button.isConnectedOnLeft(),
  52572. button.isConnectedOnRight(),
  52573. button.isConnectedOnTop(),
  52574. button.isConnectedOnBottom());
  52575. }
  52576. const Font LookAndFeel::getFontForTextButton (TextButton& button)
  52577. {
  52578. return button.getFont();
  52579. }
  52580. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  52581. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  52582. {
  52583. Font font (getFontForTextButton (button));
  52584. g.setFont (font);
  52585. g.setColour (button.findColour (button.getToggleState() ? TextButton::textColourOnId
  52586. : TextButton::textColourOffId)
  52587. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52588. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  52589. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  52590. const int fontHeight = roundToInt (font.getHeight() * 0.6f);
  52591. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  52592. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  52593. g.drawFittedText (button.getButtonText(),
  52594. leftIndent,
  52595. yIndent,
  52596. button.getWidth() - leftIndent - rightIndent,
  52597. button.getHeight() - yIndent * 2,
  52598. Justification::centred, 2);
  52599. }
  52600. void LookAndFeel::drawTickBox (Graphics& g,
  52601. Component& component,
  52602. float x, float y, float w, float h,
  52603. const bool ticked,
  52604. const bool isEnabled,
  52605. const bool isMouseOverButton,
  52606. const bool isButtonDown)
  52607. {
  52608. const float boxSize = w * 0.7f;
  52609. drawGlassSphere (g, x, y + (h - boxSize) * 0.5f, boxSize,
  52610. createBaseColour (component.findColour (TextButton::buttonColourId)
  52611. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  52612. true,
  52613. isMouseOverButton,
  52614. isButtonDown),
  52615. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  52616. if (ticked)
  52617. {
  52618. Path tick;
  52619. tick.startNewSubPath (1.5f, 3.0f);
  52620. tick.lineTo (3.0f, 6.0f);
  52621. tick.lineTo (6.0f, 0.0f);
  52622. g.setColour (isEnabled ? Colours::black : Colours::grey);
  52623. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  52624. .translated (x, y));
  52625. g.strokePath (tick, PathStrokeType (2.5f), trans);
  52626. }
  52627. }
  52628. void LookAndFeel::drawToggleButton (Graphics& g,
  52629. ToggleButton& button,
  52630. bool isMouseOverButton,
  52631. bool isButtonDown)
  52632. {
  52633. if (button.hasKeyboardFocus (true))
  52634. {
  52635. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  52636. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  52637. }
  52638. float fontSize = jmin (15.0f, button.getHeight() * 0.75f);
  52639. const float tickWidth = fontSize * 1.1f;
  52640. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  52641. tickWidth, tickWidth,
  52642. button.getToggleState(),
  52643. button.isEnabled(),
  52644. isMouseOverButton,
  52645. isButtonDown);
  52646. g.setColour (button.findColour (ToggleButton::textColourId));
  52647. g.setFont (fontSize);
  52648. if (! button.isEnabled())
  52649. g.setOpacity (0.5f);
  52650. const int textX = (int) tickWidth + 5;
  52651. g.drawFittedText (button.getButtonText(),
  52652. textX, 0,
  52653. button.getWidth() - textX - 2, button.getHeight(),
  52654. Justification::centredLeft, 10);
  52655. }
  52656. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  52657. {
  52658. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  52659. const int tickWidth = jmin (24, button.getHeight());
  52660. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  52661. button.getHeight());
  52662. }
  52663. AlertWindow* LookAndFeel::createAlertWindow (const String& title,
  52664. const String& message,
  52665. const String& button1,
  52666. const String& button2,
  52667. const String& button3,
  52668. AlertWindow::AlertIconType iconType,
  52669. int numButtons,
  52670. Component* associatedComponent)
  52671. {
  52672. AlertWindow* aw = new AlertWindow (title, message, iconType, associatedComponent);
  52673. if (numButtons == 1)
  52674. {
  52675. aw->addButton (button1, 0,
  52676. KeyPress (KeyPress::escapeKey, 0, 0),
  52677. KeyPress (KeyPress::returnKey, 0, 0));
  52678. }
  52679. else
  52680. {
  52681. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  52682. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  52683. if (button1ShortCut == button2ShortCut)
  52684. button2ShortCut = KeyPress();
  52685. if (numButtons == 2)
  52686. {
  52687. aw->addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  52688. aw->addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  52689. }
  52690. else if (numButtons == 3)
  52691. {
  52692. aw->addButton (button1, 1, button1ShortCut);
  52693. aw->addButton (button2, 2, button2ShortCut);
  52694. aw->addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  52695. }
  52696. }
  52697. return aw;
  52698. }
  52699. void LookAndFeel::drawAlertBox (Graphics& g,
  52700. AlertWindow& alert,
  52701. const Rectangle<int>& textArea,
  52702. TextLayout& textLayout)
  52703. {
  52704. g.fillAll (alert.findColour (AlertWindow::backgroundColourId));
  52705. int iconSpaceUsed = 0;
  52706. Justification alignment (Justification::horizontallyCentred);
  52707. const int iconWidth = 80;
  52708. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  52709. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  52710. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  52711. const Rectangle<int> iconRect (iconSize / -10, iconSize / -10,
  52712. iconSize, iconSize);
  52713. if (alert.getAlertType() != AlertWindow::NoIcon)
  52714. {
  52715. Path icon;
  52716. uint32 colour;
  52717. char character;
  52718. if (alert.getAlertType() == AlertWindow::WarningIcon)
  52719. {
  52720. colour = 0x55ff5555;
  52721. character = '!';
  52722. icon.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f, (float) iconRect.getY(),
  52723. (float) iconRect.getRight(), (float) iconRect.getBottom(),
  52724. (float) iconRect.getX(), (float) iconRect.getBottom());
  52725. icon = icon.createPathWithRoundedCorners (5.0f);
  52726. }
  52727. else
  52728. {
  52729. colour = alert.getAlertType() == AlertWindow::InfoIcon ? 0x605555ff : 0x40b69900;
  52730. character = alert.getAlertType() == AlertWindow::InfoIcon ? 'i' : '?';
  52731. icon.addEllipse ((float) iconRect.getX(), (float) iconRect.getY(),
  52732. (float) iconRect.getWidth(), (float) iconRect.getHeight());
  52733. }
  52734. GlyphArrangement ga;
  52735. ga.addFittedText (Font (iconRect.getHeight() * 0.9f, Font::bold),
  52736. String::charToString (character),
  52737. (float) iconRect.getX(), (float) iconRect.getY(),
  52738. (float) iconRect.getWidth(), (float) iconRect.getHeight(),
  52739. Justification::centred, false);
  52740. ga.createPath (icon);
  52741. icon.setUsingNonZeroWinding (false);
  52742. g.setColour (Colour (colour));
  52743. g.fillPath (icon);
  52744. iconSpaceUsed = iconWidth;
  52745. alignment = Justification::left;
  52746. }
  52747. g.setColour (alert.findColour (AlertWindow::textColourId));
  52748. textLayout.drawWithin (g,
  52749. textArea.getX() + iconSpaceUsed, textArea.getY(),
  52750. textArea.getWidth() - iconSpaceUsed, textArea.getHeight(),
  52751. alignment.getFlags() | Justification::top);
  52752. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  52753. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  52754. }
  52755. int LookAndFeel::getAlertBoxWindowFlags()
  52756. {
  52757. return ComponentPeer::windowAppearsOnTaskbar
  52758. | ComponentPeer::windowHasDropShadow;
  52759. }
  52760. int LookAndFeel::getAlertWindowButtonHeight()
  52761. {
  52762. return 28;
  52763. }
  52764. const Font LookAndFeel::getAlertWindowFont()
  52765. {
  52766. return Font (12.0f);
  52767. }
  52768. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  52769. int width, int height,
  52770. double progress, const String& textToShow)
  52771. {
  52772. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  52773. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  52774. g.fillAll (background);
  52775. if (progress >= 0.0f && progress < 1.0f)
  52776. {
  52777. drawGlassLozenge (g, 1.0f, 1.0f,
  52778. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  52779. (float) (height - 2),
  52780. foreground,
  52781. 0.5f, 0.0f,
  52782. true, true, true, true);
  52783. }
  52784. else
  52785. {
  52786. // spinning bar..
  52787. g.setColour (foreground);
  52788. const int stripeWidth = height * 2;
  52789. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  52790. Path p;
  52791. for (float x = (float) (- position); x < width + stripeWidth; x += stripeWidth)
  52792. p.addQuadrilateral (x, 0.0f,
  52793. x + stripeWidth * 0.5f, 0.0f,
  52794. x, (float) height,
  52795. x - stripeWidth * 0.5f, (float) height);
  52796. Image im (Image::ARGB, width, height, true);
  52797. {
  52798. Graphics g2 (im);
  52799. drawGlassLozenge (g2, 1.0f, 1.0f,
  52800. (float) (width - 2),
  52801. (float) (height - 2),
  52802. foreground,
  52803. 0.5f, 0.0f,
  52804. true, true, true, true);
  52805. }
  52806. g.setTiledImageFill (im, 0, 0, 0.85f);
  52807. g.fillPath (p);
  52808. }
  52809. if (textToShow.isNotEmpty())
  52810. {
  52811. g.setColour (Colour::contrasting (background, foreground));
  52812. g.setFont (height * 0.6f);
  52813. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  52814. }
  52815. }
  52816. void LookAndFeel::drawSpinningWaitAnimation (Graphics& g, const Colour& colour, int x, int y, int w, int h)
  52817. {
  52818. const float radius = jmin (w, h) * 0.4f;
  52819. const float thickness = radius * 0.15f;
  52820. Path p;
  52821. p.addRoundedRectangle (radius * 0.4f, thickness * -0.5f,
  52822. radius * 0.6f, thickness,
  52823. thickness * 0.5f);
  52824. const float cx = x + w * 0.5f;
  52825. const float cy = y + h * 0.5f;
  52826. const uint32 animationIndex = (Time::getMillisecondCounter() / (1000 / 10)) % 12;
  52827. for (int i = 0; i < 12; ++i)
  52828. {
  52829. const int n = (i + 12 - animationIndex) % 12;
  52830. g.setColour (colour.withMultipliedAlpha ((n + 1) / 12.0f));
  52831. g.fillPath (p, AffineTransform::rotation (i * (float_Pi / 6.0f))
  52832. .translated (cx, cy));
  52833. }
  52834. }
  52835. void LookAndFeel::drawScrollbarButton (Graphics& g,
  52836. ScrollBar& scrollbar,
  52837. int width, int height,
  52838. int buttonDirection,
  52839. bool /*isScrollbarVertical*/,
  52840. bool /*isMouseOverButton*/,
  52841. bool isButtonDown)
  52842. {
  52843. Path p;
  52844. if (buttonDirection == 0)
  52845. p.addTriangle (width * 0.5f, height * 0.2f,
  52846. width * 0.1f, height * 0.7f,
  52847. width * 0.9f, height * 0.7f);
  52848. else if (buttonDirection == 1)
  52849. p.addTriangle (width * 0.8f, height * 0.5f,
  52850. width * 0.3f, height * 0.1f,
  52851. width * 0.3f, height * 0.9f);
  52852. else if (buttonDirection == 2)
  52853. p.addTriangle (width * 0.5f, height * 0.8f,
  52854. width * 0.1f, height * 0.3f,
  52855. width * 0.9f, height * 0.3f);
  52856. else if (buttonDirection == 3)
  52857. p.addTriangle (width * 0.2f, height * 0.5f,
  52858. width * 0.7f, height * 0.1f,
  52859. width * 0.7f, height * 0.9f);
  52860. if (isButtonDown)
  52861. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  52862. else
  52863. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52864. g.fillPath (p);
  52865. g.setColour (Colour (0x80000000));
  52866. g.strokePath (p, PathStrokeType (0.5f));
  52867. }
  52868. void LookAndFeel::drawScrollbar (Graphics& g,
  52869. ScrollBar& scrollbar,
  52870. int x, int y,
  52871. int width, int height,
  52872. bool isScrollbarVertical,
  52873. int thumbStartPosition,
  52874. int thumbSize,
  52875. bool /*isMouseOver*/,
  52876. bool /*isMouseDown*/)
  52877. {
  52878. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  52879. Path slotPath, thumbPath;
  52880. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  52881. const float slotIndentx2 = slotIndent * 2.0f;
  52882. const float thumbIndent = slotIndent + 1.0f;
  52883. const float thumbIndentx2 = thumbIndent * 2.0f;
  52884. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  52885. if (isScrollbarVertical)
  52886. {
  52887. slotPath.addRoundedRectangle (x + slotIndent,
  52888. y + slotIndent,
  52889. width - slotIndentx2,
  52890. height - slotIndentx2,
  52891. (width - slotIndentx2) * 0.5f);
  52892. if (thumbSize > 0)
  52893. thumbPath.addRoundedRectangle (x + thumbIndent,
  52894. thumbStartPosition + thumbIndent,
  52895. width - thumbIndentx2,
  52896. thumbSize - thumbIndentx2,
  52897. (width - thumbIndentx2) * 0.5f);
  52898. gx1 = (float) x;
  52899. gx2 = x + width * 0.7f;
  52900. }
  52901. else
  52902. {
  52903. slotPath.addRoundedRectangle (x + slotIndent,
  52904. y + slotIndent,
  52905. width - slotIndentx2,
  52906. height - slotIndentx2,
  52907. (height - slotIndentx2) * 0.5f);
  52908. if (thumbSize > 0)
  52909. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  52910. y + thumbIndent,
  52911. thumbSize - thumbIndentx2,
  52912. height - thumbIndentx2,
  52913. (height - thumbIndentx2) * 0.5f);
  52914. gy1 = (float) y;
  52915. gy2 = y + height * 0.7f;
  52916. }
  52917. const Colour thumbColour (scrollbar.findColour (ScrollBar::thumbColourId));
  52918. g.setGradientFill (ColourGradient (thumbColour.overlaidWith (Colour (0x44000000)), gx1, gy1,
  52919. thumbColour.overlaidWith (Colour (0x19000000)), gx2, gy2, false));
  52920. g.fillPath (slotPath);
  52921. if (isScrollbarVertical)
  52922. {
  52923. gx1 = x + width * 0.6f;
  52924. gx2 = (float) x + width;
  52925. }
  52926. else
  52927. {
  52928. gy1 = y + height * 0.6f;
  52929. gy2 = (float) y + height;
  52930. }
  52931. g.setGradientFill (ColourGradient (Colours::transparentBlack,gx1, gy1,
  52932. Colour (0x19000000), gx2, gy2, false));
  52933. g.fillPath (slotPath);
  52934. g.setColour (thumbColour);
  52935. g.fillPath (thumbPath);
  52936. g.setGradientFill (ColourGradient (Colour (0x10000000), gx1, gy1,
  52937. Colours::transparentBlack, gx2, gy2, false));
  52938. g.saveState();
  52939. if (isScrollbarVertical)
  52940. g.reduceClipRegion (x + width / 2, y, width, height);
  52941. else
  52942. g.reduceClipRegion (x, y + height / 2, width, height);
  52943. g.fillPath (thumbPath);
  52944. g.restoreState();
  52945. g.setColour (Colour (0x4c000000));
  52946. g.strokePath (thumbPath, PathStrokeType (0.4f));
  52947. }
  52948. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  52949. {
  52950. return 0;
  52951. }
  52952. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  52953. {
  52954. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  52955. }
  52956. int LookAndFeel::getDefaultScrollbarWidth()
  52957. {
  52958. return 18;
  52959. }
  52960. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  52961. {
  52962. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  52963. : scrollbar.getHeight());
  52964. }
  52965. const Path LookAndFeel::getTickShape (const float height)
  52966. {
  52967. static const unsigned char tickShapeData[] =
  52968. {
  52969. 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,
  52970. 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,
  52971. 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,
  52972. 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,
  52973. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  52974. };
  52975. Path p;
  52976. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  52977. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52978. return p;
  52979. }
  52980. const Path LookAndFeel::getCrossShape (const float height)
  52981. {
  52982. static const unsigned char crossShapeData[] =
  52983. {
  52984. 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,
  52985. 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,
  52986. 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,
  52987. 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,
  52988. 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,
  52989. 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,
  52990. 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
  52991. };
  52992. Path p;
  52993. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  52994. p.scaleToFit (0, 0, height * 2.0f, height, true);
  52995. return p;
  52996. }
  52997. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool /*isMouseOver*/)
  52998. {
  52999. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  53000. x += (w - boxSize) >> 1;
  53001. y += (h - boxSize) >> 1;
  53002. w = boxSize;
  53003. h = boxSize;
  53004. g.setColour (Colour (0xe5ffffff));
  53005. g.fillRect (x, y, w, h);
  53006. g.setColour (Colour (0x80000000));
  53007. g.drawRect (x, y, w, h);
  53008. const float size = boxSize / 2 + 1.0f;
  53009. const float centre = (float) (boxSize / 2);
  53010. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  53011. if (isPlus)
  53012. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  53013. }
  53014. void LookAndFeel::drawBubble (Graphics& g,
  53015. float tipX, float tipY,
  53016. float boxX, float boxY,
  53017. float boxW, float boxH)
  53018. {
  53019. int side = 0;
  53020. if (tipX < boxX)
  53021. side = 1;
  53022. else if (tipX > boxX + boxW)
  53023. side = 3;
  53024. else if (tipY > boxY + boxH)
  53025. side = 2;
  53026. const float indent = 2.0f;
  53027. Path p;
  53028. p.addBubble (boxX + indent,
  53029. boxY + indent,
  53030. boxW - indent * 2.0f,
  53031. boxH - indent * 2.0f,
  53032. 5.0f,
  53033. tipX, tipY,
  53034. side,
  53035. 0.5f,
  53036. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  53037. //xxx need to take comp as param for colour
  53038. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  53039. g.fillPath (p);
  53040. //xxx as above
  53041. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  53042. g.strokePath (p, PathStrokeType (1.33f));
  53043. }
  53044. const Font LookAndFeel::getPopupMenuFont()
  53045. {
  53046. return Font (17.0f);
  53047. }
  53048. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  53049. const bool isSeparator,
  53050. int standardMenuItemHeight,
  53051. int& idealWidth,
  53052. int& idealHeight)
  53053. {
  53054. if (isSeparator)
  53055. {
  53056. idealWidth = 50;
  53057. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  53058. }
  53059. else
  53060. {
  53061. Font font (getPopupMenuFont());
  53062. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  53063. font.setHeight (standardMenuItemHeight / 1.3f);
  53064. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundToInt (font.getHeight() * 1.3f);
  53065. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  53066. }
  53067. }
  53068. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  53069. {
  53070. const Colour background (findColour (PopupMenu::backgroundColourId));
  53071. g.fillAll (background);
  53072. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  53073. for (int i = 0; i < height; i += 3)
  53074. g.fillRect (0, i, width, 1);
  53075. #if ! JUCE_MAC
  53076. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  53077. g.drawRect (0, 0, width, height);
  53078. #endif
  53079. }
  53080. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  53081. int width, int height,
  53082. bool isScrollUpArrow)
  53083. {
  53084. const Colour background (findColour (PopupMenu::backgroundColourId));
  53085. g.setGradientFill (ColourGradient (background, 0.0f, height * 0.5f,
  53086. background.withAlpha (0.0f),
  53087. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  53088. false));
  53089. g.fillRect (1, 1, width - 2, height - 2);
  53090. const float hw = width * 0.5f;
  53091. const float arrowW = height * 0.3f;
  53092. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  53093. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  53094. Path p;
  53095. p.addTriangle (hw - arrowW, y1,
  53096. hw + arrowW, y1,
  53097. hw, y2);
  53098. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  53099. g.fillPath (p);
  53100. }
  53101. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  53102. int width, int height,
  53103. const bool isSeparator,
  53104. const bool isActive,
  53105. const bool isHighlighted,
  53106. const bool isTicked,
  53107. const bool hasSubMenu,
  53108. const String& text,
  53109. const String& shortcutKeyText,
  53110. Image* image,
  53111. const Colour* const textColourToUse)
  53112. {
  53113. const float halfH = height * 0.5f;
  53114. if (isSeparator)
  53115. {
  53116. const float separatorIndent = 5.5f;
  53117. g.setColour (Colour (0x33000000));
  53118. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  53119. g.setColour (Colour (0x66ffffff));
  53120. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  53121. }
  53122. else
  53123. {
  53124. Colour textColour (findColour (PopupMenu::textColourId));
  53125. if (textColourToUse != 0)
  53126. textColour = *textColourToUse;
  53127. if (isHighlighted)
  53128. {
  53129. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  53130. g.fillRect (1, 1, width - 2, height - 2);
  53131. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  53132. }
  53133. else
  53134. {
  53135. g.setColour (textColour);
  53136. }
  53137. if (! isActive)
  53138. g.setOpacity (0.3f);
  53139. Font font (getPopupMenuFont());
  53140. if (font.getHeight() > height / 1.3f)
  53141. font.setHeight (height / 1.3f);
  53142. g.setFont (font);
  53143. const int leftBorder = (height * 5) / 4;
  53144. const int rightBorder = 4;
  53145. if (image != 0)
  53146. {
  53147. g.drawImageWithin (*image,
  53148. 2, 1, leftBorder - 4, height - 2,
  53149. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  53150. }
  53151. else if (isTicked)
  53152. {
  53153. const Path tick (getTickShape (1.0f));
  53154. const float th = font.getAscent();
  53155. const float ty = halfH - th * 0.5f;
  53156. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  53157. th, true));
  53158. }
  53159. g.drawFittedText (text,
  53160. leftBorder, 0,
  53161. width - (leftBorder + rightBorder), height,
  53162. Justification::centredLeft, 1);
  53163. if (shortcutKeyText.isNotEmpty())
  53164. {
  53165. Font f2 (font);
  53166. f2.setHeight (f2.getHeight() * 0.75f);
  53167. f2.setHorizontalScale (0.95f);
  53168. g.setFont (f2);
  53169. g.drawText (shortcutKeyText,
  53170. leftBorder,
  53171. 0,
  53172. width - (leftBorder + rightBorder + 4),
  53173. height,
  53174. Justification::centredRight,
  53175. true);
  53176. }
  53177. if (hasSubMenu)
  53178. {
  53179. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  53180. const float x = width - height * 0.6f;
  53181. Path p;
  53182. p.addTriangle (x, halfH - arrowH * 0.5f,
  53183. x, halfH + arrowH * 0.5f,
  53184. x + arrowH * 0.6f, halfH);
  53185. g.fillPath (p);
  53186. }
  53187. }
  53188. }
  53189. int LookAndFeel::getMenuWindowFlags()
  53190. {
  53191. return ComponentPeer::windowHasDropShadow;
  53192. }
  53193. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  53194. bool, MenuBarComponent& menuBar)
  53195. {
  53196. const Colour baseColour (createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  53197. if (menuBar.isEnabled())
  53198. {
  53199. drawShinyButtonShape (g,
  53200. -4.0f, 0.0f,
  53201. width + 8.0f, (float) height,
  53202. 0.0f,
  53203. baseColour,
  53204. 0.4f,
  53205. true, true, true, true);
  53206. }
  53207. else
  53208. {
  53209. g.fillAll (baseColour);
  53210. }
  53211. }
  53212. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  53213. {
  53214. return Font (menuBar.getHeight() * 0.7f);
  53215. }
  53216. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  53217. {
  53218. return getMenuBarFont (menuBar, itemIndex, itemText)
  53219. .getStringWidth (itemText) + menuBar.getHeight();
  53220. }
  53221. void LookAndFeel::drawMenuBarItem (Graphics& g,
  53222. int width, int height,
  53223. int itemIndex,
  53224. const String& itemText,
  53225. bool isMouseOverItem,
  53226. bool isMenuOpen,
  53227. bool /*isMouseOverBar*/,
  53228. MenuBarComponent& menuBar)
  53229. {
  53230. if (! menuBar.isEnabled())
  53231. {
  53232. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  53233. .withMultipliedAlpha (0.5f));
  53234. }
  53235. else if (isMenuOpen || isMouseOverItem)
  53236. {
  53237. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  53238. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  53239. }
  53240. else
  53241. {
  53242. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  53243. }
  53244. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  53245. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  53246. }
  53247. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  53248. TextEditor& textEditor)
  53249. {
  53250. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  53251. }
  53252. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  53253. {
  53254. if (textEditor.isEnabled())
  53255. {
  53256. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  53257. {
  53258. const int border = 2;
  53259. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  53260. g.drawRect (0, 0, width, height, border);
  53261. g.setOpacity (1.0f);
  53262. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  53263. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  53264. }
  53265. else
  53266. {
  53267. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  53268. g.drawRect (0, 0, width, height);
  53269. g.setOpacity (1.0f);
  53270. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  53271. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  53272. }
  53273. }
  53274. }
  53275. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  53276. const bool isButtonDown,
  53277. int buttonX, int buttonY,
  53278. int buttonW, int buttonH,
  53279. ComboBox& box)
  53280. {
  53281. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  53282. if (box.isEnabled() && box.hasKeyboardFocus (false))
  53283. {
  53284. g.setColour (box.findColour (TextButton::buttonColourId));
  53285. g.drawRect (0, 0, width, height, 2);
  53286. }
  53287. else
  53288. {
  53289. g.setColour (box.findColour (ComboBox::outlineColourId));
  53290. g.drawRect (0, 0, width, height);
  53291. }
  53292. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  53293. const Colour baseColour (createBaseColour (box.findColour (ComboBox::buttonColourId),
  53294. box.hasKeyboardFocus (true),
  53295. false, isButtonDown)
  53296. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  53297. drawGlassLozenge (g,
  53298. buttonX + outlineThickness, buttonY + outlineThickness,
  53299. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  53300. baseColour, outlineThickness, -1.0f,
  53301. true, true, true, true);
  53302. if (box.isEnabled())
  53303. {
  53304. const float arrowX = 0.3f;
  53305. const float arrowH = 0.2f;
  53306. Path p;
  53307. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  53308. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  53309. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  53310. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  53311. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  53312. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  53313. g.setColour (box.findColour (ComboBox::arrowColourId));
  53314. g.fillPath (p);
  53315. }
  53316. }
  53317. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  53318. {
  53319. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  53320. }
  53321. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  53322. {
  53323. return new Label (String::empty, String::empty);
  53324. }
  53325. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  53326. {
  53327. label.setBounds (1, 1,
  53328. box.getWidth() + 3 - box.getHeight(),
  53329. box.getHeight() - 2);
  53330. label.setFont (getComboBoxFont (box));
  53331. }
  53332. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  53333. {
  53334. g.fillAll (label.findColour (Label::backgroundColourId));
  53335. if (! label.isBeingEdited())
  53336. {
  53337. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  53338. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  53339. g.setFont (label.getFont());
  53340. g.drawFittedText (label.getText(),
  53341. label.getHorizontalBorderSize(),
  53342. label.getVerticalBorderSize(),
  53343. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  53344. label.getHeight() - 2 * label.getVerticalBorderSize(),
  53345. label.getJustificationType(),
  53346. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  53347. label.getMinimumHorizontalScale());
  53348. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  53349. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53350. }
  53351. else if (label.isEnabled())
  53352. {
  53353. g.setColour (label.findColour (Label::outlineColourId));
  53354. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53355. }
  53356. }
  53357. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  53358. int x, int y,
  53359. int width, int height,
  53360. float /*sliderPos*/,
  53361. float /*minSliderPos*/,
  53362. float /*maxSliderPos*/,
  53363. const Slider::SliderStyle /*style*/,
  53364. Slider& slider)
  53365. {
  53366. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53367. const Colour trackColour (slider.findColour (Slider::trackColourId));
  53368. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  53369. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  53370. Path indent;
  53371. if (slider.isHorizontal())
  53372. {
  53373. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  53374. const float ih = sliderRadius;
  53375. g.setGradientFill (ColourGradient (gradCol1, 0.0f, iy,
  53376. gradCol2, 0.0f, iy + ih, false));
  53377. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  53378. width + sliderRadius, ih,
  53379. 5.0f);
  53380. g.fillPath (indent);
  53381. }
  53382. else
  53383. {
  53384. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  53385. const float iw = sliderRadius;
  53386. g.setGradientFill (ColourGradient (gradCol1, ix, 0.0f,
  53387. gradCol2, ix + iw, 0.0f, false));
  53388. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  53389. iw, height + sliderRadius,
  53390. 5.0f);
  53391. g.fillPath (indent);
  53392. }
  53393. g.setColour (Colour (0x4c000000));
  53394. g.strokePath (indent, PathStrokeType (0.5f));
  53395. }
  53396. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  53397. int x, int y,
  53398. int width, int height,
  53399. float sliderPos,
  53400. float minSliderPos,
  53401. float maxSliderPos,
  53402. const Slider::SliderStyle style,
  53403. Slider& slider)
  53404. {
  53405. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53406. Colour knobColour (createBaseColour (slider.findColour (Slider::thumbColourId),
  53407. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  53408. slider.isMouseOverOrDragging() && slider.isEnabled(),
  53409. slider.isMouseButtonDown() && slider.isEnabled()));
  53410. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  53411. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  53412. {
  53413. float kx, ky;
  53414. if (style == Slider::LinearVertical)
  53415. {
  53416. kx = x + width * 0.5f;
  53417. ky = sliderPos;
  53418. }
  53419. else
  53420. {
  53421. kx = sliderPos;
  53422. ky = y + height * 0.5f;
  53423. }
  53424. drawGlassSphere (g,
  53425. kx - sliderRadius,
  53426. ky - sliderRadius,
  53427. sliderRadius * 2.0f,
  53428. knobColour, outlineThickness);
  53429. }
  53430. else
  53431. {
  53432. if (style == Slider::ThreeValueVertical)
  53433. {
  53434. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  53435. sliderPos - sliderRadius,
  53436. sliderRadius * 2.0f,
  53437. knobColour, outlineThickness);
  53438. }
  53439. else if (style == Slider::ThreeValueHorizontal)
  53440. {
  53441. drawGlassSphere (g,sliderPos - sliderRadius,
  53442. y + height * 0.5f - sliderRadius,
  53443. sliderRadius * 2.0f,
  53444. knobColour, outlineThickness);
  53445. }
  53446. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  53447. {
  53448. const float sr = jmin (sliderRadius, width * 0.4f);
  53449. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  53450. minSliderPos - sliderRadius,
  53451. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  53452. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  53453. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  53454. }
  53455. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  53456. {
  53457. const float sr = jmin (sliderRadius, height * 0.4f);
  53458. drawGlassPointer (g, minSliderPos - sr,
  53459. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  53460. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  53461. drawGlassPointer (g, maxSliderPos - sliderRadius,
  53462. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  53463. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  53464. }
  53465. }
  53466. }
  53467. void LookAndFeel::drawLinearSlider (Graphics& g,
  53468. int x, int y,
  53469. int width, int height,
  53470. float sliderPos,
  53471. float minSliderPos,
  53472. float maxSliderPos,
  53473. const Slider::SliderStyle style,
  53474. Slider& slider)
  53475. {
  53476. g.fillAll (slider.findColour (Slider::backgroundColourId));
  53477. if (style == Slider::LinearBar)
  53478. {
  53479. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53480. Colour baseColour (createBaseColour (slider.findColour (Slider::thumbColourId)
  53481. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  53482. false,
  53483. isMouseOver,
  53484. isMouseOver || slider.isMouseButtonDown()));
  53485. drawShinyButtonShape (g,
  53486. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  53487. baseColour,
  53488. slider.isEnabled() ? 0.9f : 0.3f,
  53489. true, true, true, true);
  53490. }
  53491. else
  53492. {
  53493. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53494. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53495. }
  53496. }
  53497. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  53498. {
  53499. return jmin (7,
  53500. slider.getHeight() / 2,
  53501. slider.getWidth() / 2) + 2;
  53502. }
  53503. void LookAndFeel::drawRotarySlider (Graphics& g,
  53504. int x, int y,
  53505. int width, int height,
  53506. float sliderPos,
  53507. const float rotaryStartAngle,
  53508. const float rotaryEndAngle,
  53509. Slider& slider)
  53510. {
  53511. const float radius = jmin (width / 2, height / 2) - 2.0f;
  53512. const float centreX = x + width * 0.5f;
  53513. const float centreY = y + height * 0.5f;
  53514. const float rx = centreX - radius;
  53515. const float ry = centreY - radius;
  53516. const float rw = radius * 2.0f;
  53517. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  53518. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53519. if (radius > 12.0f)
  53520. {
  53521. if (slider.isEnabled())
  53522. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53523. else
  53524. g.setColour (Colour (0x80808080));
  53525. const float thickness = 0.7f;
  53526. {
  53527. Path filledArc;
  53528. filledArc.addPieSegment (rx, ry, rw, rw,
  53529. rotaryStartAngle,
  53530. angle,
  53531. thickness);
  53532. g.fillPath (filledArc);
  53533. }
  53534. if (thickness > 0)
  53535. {
  53536. const float innerRadius = radius * 0.2f;
  53537. Path p;
  53538. p.addTriangle (-innerRadius, 0.0f,
  53539. 0.0f, -radius * thickness * 1.1f,
  53540. innerRadius, 0.0f);
  53541. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  53542. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53543. }
  53544. if (slider.isEnabled())
  53545. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  53546. else
  53547. g.setColour (Colour (0x80808080));
  53548. Path outlineArc;
  53549. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  53550. outlineArc.closeSubPath();
  53551. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  53552. }
  53553. else
  53554. {
  53555. if (slider.isEnabled())
  53556. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53557. else
  53558. g.setColour (Colour (0x80808080));
  53559. Path p;
  53560. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  53561. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  53562. p.addLineSegment (Line<float> (0.0f, 0.0f, 0.0f, -radius), rw * 0.2f);
  53563. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53564. }
  53565. }
  53566. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  53567. {
  53568. return new TextButton (isIncrement ? "+" : "-", String::empty);
  53569. }
  53570. class SliderLabelComp : public Label
  53571. {
  53572. public:
  53573. SliderLabelComp() : Label (String::empty, String::empty) {}
  53574. ~SliderLabelComp() {}
  53575. void mouseWheelMove (const MouseEvent&, float, float) {}
  53576. };
  53577. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  53578. {
  53579. Label* const l = new SliderLabelComp();
  53580. l->setJustificationType (Justification::centred);
  53581. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53582. l->setColour (Label::backgroundColourId,
  53583. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  53584. : slider.findColour (Slider::textBoxBackgroundColourId));
  53585. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53586. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53587. l->setColour (TextEditor::backgroundColourId,
  53588. slider.findColour (Slider::textBoxBackgroundColourId)
  53589. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  53590. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53591. return l;
  53592. }
  53593. ImageEffectFilter* LookAndFeel::getSliderEffect()
  53594. {
  53595. return 0;
  53596. }
  53597. static const TextLayout layoutTooltipText (const String& text) throw()
  53598. {
  53599. const float tooltipFontSize = 12.0f;
  53600. const int maxToolTipWidth = 400;
  53601. const Font f (tooltipFontSize, Font::bold);
  53602. TextLayout tl (text, f);
  53603. tl.layout (maxToolTipWidth, Justification::left, true);
  53604. return tl;
  53605. }
  53606. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  53607. {
  53608. const TextLayout tl (layoutTooltipText (tipText));
  53609. width = tl.getWidth() + 14;
  53610. height = tl.getHeight() + 6;
  53611. }
  53612. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  53613. {
  53614. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  53615. const Colour textCol (findColour (TooltipWindow::textColourId));
  53616. #if ! JUCE_MAC // The mac windows already have a non-optional 1 pix outline, so don't double it here..
  53617. g.setColour (findColour (TooltipWindow::outlineColourId));
  53618. g.drawRect (0, 0, width, height, 1);
  53619. #endif
  53620. const TextLayout tl (layoutTooltipText (text));
  53621. g.setColour (findColour (TooltipWindow::textColourId));
  53622. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  53623. }
  53624. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  53625. {
  53626. return new TextButton (text, TRANS("click to browse for a different file"));
  53627. }
  53628. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  53629. ComboBox* filenameBox,
  53630. Button* browseButton)
  53631. {
  53632. browseButton->setSize (80, filenameComp.getHeight());
  53633. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  53634. if (tb != 0)
  53635. tb->changeWidthToFitText();
  53636. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  53637. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  53638. }
  53639. void LookAndFeel::drawImageButton (Graphics& g, Image* image,
  53640. int imageX, int imageY, int imageW, int imageH,
  53641. const Colour& overlayColour,
  53642. float imageOpacity,
  53643. ImageButton& button)
  53644. {
  53645. if (! button.isEnabled())
  53646. imageOpacity *= 0.3f;
  53647. if (! overlayColour.isOpaque())
  53648. {
  53649. g.setOpacity (imageOpacity);
  53650. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53651. 0, 0, image->getWidth(), image->getHeight(), false);
  53652. }
  53653. if (! overlayColour.isTransparent())
  53654. {
  53655. g.setColour (overlayColour);
  53656. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53657. 0, 0, image->getWidth(), image->getHeight(), true);
  53658. }
  53659. }
  53660. void LookAndFeel::drawCornerResizer (Graphics& g,
  53661. int w, int h,
  53662. bool /*isMouseOver*/,
  53663. bool /*isMouseDragging*/)
  53664. {
  53665. const float lineThickness = jmin (w, h) * 0.075f;
  53666. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  53667. {
  53668. g.setColour (Colours::lightgrey);
  53669. g.drawLine (w * i,
  53670. h + 1.0f,
  53671. w + 1.0f,
  53672. h * i,
  53673. lineThickness);
  53674. g.setColour (Colours::darkgrey);
  53675. g.drawLine (w * i + lineThickness,
  53676. h + 1.0f,
  53677. w + 1.0f,
  53678. h * i + lineThickness,
  53679. lineThickness);
  53680. }
  53681. }
  53682. void LookAndFeel::drawResizableFrame (Graphics& g, int w, int h, const BorderSize& border)
  53683. {
  53684. if (! border.isEmpty())
  53685. {
  53686. const Rectangle<int> fullSize (0, 0, w, h);
  53687. const Rectangle<int> centreArea (border.subtractedFrom (fullSize));
  53688. g.saveState();
  53689. g.excludeClipRegion (centreArea);
  53690. g.setColour (Colour (0x50000000));
  53691. g.drawRect (fullSize);
  53692. g.setColour (Colour (0x19000000));
  53693. g.drawRect (centreArea.expanded (1, 1));
  53694. g.restoreState();
  53695. }
  53696. }
  53697. void LookAndFeel::fillResizableWindowBackground (Graphics& g, int /*w*/, int /*h*/,
  53698. const BorderSize& /*border*/, ResizableWindow& window)
  53699. {
  53700. g.fillAll (window.getBackgroundColour());
  53701. }
  53702. void LookAndFeel::drawResizableWindowBorder (Graphics&, int /*w*/, int /*h*/,
  53703. const BorderSize& /*border*/, ResizableWindow&)
  53704. {
  53705. }
  53706. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  53707. Graphics& g, int w, int h,
  53708. int titleSpaceX, int titleSpaceW,
  53709. const Image* icon,
  53710. bool drawTitleTextOnLeft)
  53711. {
  53712. const bool isActive = window.isActiveWindow();
  53713. g.setGradientFill (ColourGradient (window.getBackgroundColour(),
  53714. 0.0f, 0.0f,
  53715. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  53716. 0.0f, (float) h, false));
  53717. g.fillAll();
  53718. Font font (h * 0.65f, Font::bold);
  53719. g.setFont (font);
  53720. int textW = font.getStringWidth (window.getName());
  53721. int iconW = 0;
  53722. int iconH = 0;
  53723. if (icon != 0)
  53724. {
  53725. iconH = (int) font.getHeight();
  53726. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  53727. }
  53728. textW = jmin (titleSpaceW, textW + iconW);
  53729. int textX = drawTitleTextOnLeft ? titleSpaceX
  53730. : jmax (titleSpaceX, (w - textW) / 2);
  53731. if (textX + textW > titleSpaceX + titleSpaceW)
  53732. textX = titleSpaceX + titleSpaceW - textW;
  53733. if (icon != 0)
  53734. {
  53735. g.setOpacity (isActive ? 1.0f : 0.6f);
  53736. g.drawImageWithin (*icon, textX, (h - iconH) / 2, iconW, iconH,
  53737. RectanglePlacement::centred, false);
  53738. textX += iconW;
  53739. textW -= iconW;
  53740. }
  53741. if (window.isColourSpecified (DocumentWindow::textColourId) || isColourSpecified (DocumentWindow::textColourId))
  53742. g.setColour (findColour (DocumentWindow::textColourId));
  53743. else
  53744. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  53745. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  53746. }
  53747. class GlassWindowButton : public Button
  53748. {
  53749. public:
  53750. GlassWindowButton (const String& name, const Colour& col,
  53751. const Path& normalShape_,
  53752. const Path& toggledShape_) throw()
  53753. : Button (name),
  53754. colour (col),
  53755. normalShape (normalShape_),
  53756. toggledShape (toggledShape_)
  53757. {
  53758. }
  53759. ~GlassWindowButton()
  53760. {
  53761. }
  53762. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  53763. {
  53764. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  53765. if (! isEnabled())
  53766. alpha *= 0.5f;
  53767. float x = 0, y = 0, diam;
  53768. if (getWidth() < getHeight())
  53769. {
  53770. diam = (float) getWidth();
  53771. y = (getHeight() - getWidth()) * 0.5f;
  53772. }
  53773. else
  53774. {
  53775. diam = (float) getHeight();
  53776. y = (getWidth() - getHeight()) * 0.5f;
  53777. }
  53778. x += diam * 0.05f;
  53779. y += diam * 0.05f;
  53780. diam *= 0.9f;
  53781. g.setGradientFill (ColourGradient (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  53782. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false));
  53783. g.fillEllipse (x, y, diam, diam);
  53784. x += 2.0f;
  53785. y += 2.0f;
  53786. diam -= 4.0f;
  53787. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  53788. Path& p = getToggleState() ? toggledShape : normalShape;
  53789. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  53790. diam * 0.4f, diam * 0.4f, true));
  53791. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  53792. g.fillPath (p, t);
  53793. }
  53794. juce_UseDebuggingNewOperator
  53795. private:
  53796. Colour colour;
  53797. Path normalShape, toggledShape;
  53798. GlassWindowButton (const GlassWindowButton&);
  53799. GlassWindowButton& operator= (const GlassWindowButton&);
  53800. };
  53801. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  53802. {
  53803. Path shape;
  53804. const float crossThickness = 0.25f;
  53805. if (buttonType == DocumentWindow::closeButton)
  53806. {
  53807. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), crossThickness * 1.4f);
  53808. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), crossThickness * 1.4f);
  53809. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  53810. }
  53811. else if (buttonType == DocumentWindow::minimiseButton)
  53812. {
  53813. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53814. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  53815. }
  53816. else if (buttonType == DocumentWindow::maximiseButton)
  53817. {
  53818. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), crossThickness);
  53819. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53820. Path fullscreenShape;
  53821. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  53822. fullscreenShape.lineTo (0.0f, 100.0f);
  53823. fullscreenShape.lineTo (0.0f, 0.0f);
  53824. fullscreenShape.lineTo (100.0f, 0.0f);
  53825. fullscreenShape.lineTo (100.0f, 45.0f);
  53826. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  53827. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  53828. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  53829. }
  53830. jassertfalse;
  53831. return 0;
  53832. }
  53833. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  53834. int titleBarX,
  53835. int titleBarY,
  53836. int titleBarW,
  53837. int titleBarH,
  53838. Button* minimiseButton,
  53839. Button* maximiseButton,
  53840. Button* closeButton,
  53841. bool positionTitleBarButtonsOnLeft)
  53842. {
  53843. const int buttonW = titleBarH - titleBarH / 8;
  53844. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  53845. : titleBarX + titleBarW - buttonW - buttonW / 4;
  53846. if (closeButton != 0)
  53847. {
  53848. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53849. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  53850. }
  53851. if (positionTitleBarButtonsOnLeft)
  53852. swapVariables (minimiseButton, maximiseButton);
  53853. if (maximiseButton != 0)
  53854. {
  53855. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53856. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  53857. }
  53858. if (minimiseButton != 0)
  53859. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  53860. }
  53861. int LookAndFeel::getDefaultMenuBarHeight()
  53862. {
  53863. return 24;
  53864. }
  53865. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  53866. {
  53867. return new DropShadower (0.4f, 1, 5, 10);
  53868. }
  53869. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  53870. int w, int h,
  53871. bool /*isVerticalBar*/,
  53872. bool isMouseOver,
  53873. bool isMouseDragging)
  53874. {
  53875. float alpha = 0.5f;
  53876. if (isMouseOver || isMouseDragging)
  53877. {
  53878. g.fillAll (Colour (0x190000ff));
  53879. alpha = 1.0f;
  53880. }
  53881. const float cx = w * 0.5f;
  53882. const float cy = h * 0.5f;
  53883. const float cr = jmin (w, h) * 0.4f;
  53884. g.setGradientFill (ColourGradient (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  53885. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  53886. true));
  53887. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  53888. }
  53889. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  53890. const String& text,
  53891. const Justification& position,
  53892. GroupComponent& group)
  53893. {
  53894. const float textH = 15.0f;
  53895. const float indent = 3.0f;
  53896. const float textEdgeGap = 4.0f;
  53897. float cs = 5.0f;
  53898. Font f (textH);
  53899. Path p;
  53900. float x = indent;
  53901. float y = f.getAscent() - 3.0f;
  53902. float w = jmax (0.0f, width - x * 2.0f);
  53903. float h = jmax (0.0f, height - y - indent);
  53904. cs = jmin (cs, w * 0.5f, h * 0.5f);
  53905. const float cs2 = 2.0f * cs;
  53906. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  53907. float textX = cs + textEdgeGap;
  53908. if (position.testFlags (Justification::horizontallyCentred))
  53909. textX = cs + (w - cs2 - textW) * 0.5f;
  53910. else if (position.testFlags (Justification::right))
  53911. textX = w - cs - textW - textEdgeGap;
  53912. p.startNewSubPath (x + textX + textW, y);
  53913. p.lineTo (x + w - cs, y);
  53914. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  53915. p.lineTo (x + w, y + h - cs);
  53916. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  53917. p.lineTo (x + cs, y + h);
  53918. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  53919. p.lineTo (x, y + cs);
  53920. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  53921. p.lineTo (x + textX, y);
  53922. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  53923. g.setColour (group.findColour (GroupComponent::outlineColourId)
  53924. .withMultipliedAlpha (alpha));
  53925. g.strokePath (p, PathStrokeType (2.0f));
  53926. g.setColour (group.findColour (GroupComponent::textColourId)
  53927. .withMultipliedAlpha (alpha));
  53928. g.setFont (f);
  53929. g.drawText (text,
  53930. roundToInt (x + textX), 0,
  53931. roundToInt (textW),
  53932. roundToInt (textH),
  53933. Justification::centred, true);
  53934. }
  53935. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  53936. {
  53937. return 1 + tabDepth / 3;
  53938. }
  53939. int LookAndFeel::getTabButtonSpaceAroundImage()
  53940. {
  53941. return 4;
  53942. }
  53943. void LookAndFeel::createTabButtonShape (Path& p,
  53944. int width, int height,
  53945. int /*tabIndex*/,
  53946. const String& /*text*/,
  53947. Button& /*button*/,
  53948. TabbedButtonBar::Orientation orientation,
  53949. const bool /*isMouseOver*/,
  53950. const bool /*isMouseDown*/,
  53951. const bool /*isFrontTab*/)
  53952. {
  53953. const float w = (float) width;
  53954. const float h = (float) height;
  53955. float length = w;
  53956. float depth = h;
  53957. if (orientation == TabbedButtonBar::TabsAtLeft
  53958. || orientation == TabbedButtonBar::TabsAtRight)
  53959. {
  53960. swapVariables (length, depth);
  53961. }
  53962. const float indent = (float) getTabButtonOverlap ((int) depth);
  53963. const float overhang = 4.0f;
  53964. if (orientation == TabbedButtonBar::TabsAtLeft)
  53965. {
  53966. p.startNewSubPath (w, 0.0f);
  53967. p.lineTo (0.0f, indent);
  53968. p.lineTo (0.0f, h - indent);
  53969. p.lineTo (w, h);
  53970. p.lineTo (w + overhang, h + overhang);
  53971. p.lineTo (w + overhang, -overhang);
  53972. }
  53973. else if (orientation == TabbedButtonBar::TabsAtRight)
  53974. {
  53975. p.startNewSubPath (0.0f, 0.0f);
  53976. p.lineTo (w, indent);
  53977. p.lineTo (w, h - indent);
  53978. p.lineTo (0.0f, h);
  53979. p.lineTo (-overhang, h + overhang);
  53980. p.lineTo (-overhang, -overhang);
  53981. }
  53982. else if (orientation == TabbedButtonBar::TabsAtBottom)
  53983. {
  53984. p.startNewSubPath (0.0f, 0.0f);
  53985. p.lineTo (indent, h);
  53986. p.lineTo (w - indent, h);
  53987. p.lineTo (w, 0.0f);
  53988. p.lineTo (w + overhang, -overhang);
  53989. p.lineTo (-overhang, -overhang);
  53990. }
  53991. else
  53992. {
  53993. p.startNewSubPath (0.0f, h);
  53994. p.lineTo (indent, 0.0f);
  53995. p.lineTo (w - indent, 0.0f);
  53996. p.lineTo (w, h);
  53997. p.lineTo (w + overhang, h + overhang);
  53998. p.lineTo (-overhang, h + overhang);
  53999. }
  54000. p.closeSubPath();
  54001. p = p.createPathWithRoundedCorners (3.0f);
  54002. }
  54003. void LookAndFeel::fillTabButtonShape (Graphics& g,
  54004. const Path& path,
  54005. const Colour& preferredColour,
  54006. int /*tabIndex*/,
  54007. const String& /*text*/,
  54008. Button& button,
  54009. TabbedButtonBar::Orientation /*orientation*/,
  54010. const bool /*isMouseOver*/,
  54011. const bool /*isMouseDown*/,
  54012. const bool isFrontTab)
  54013. {
  54014. g.setColour (isFrontTab ? preferredColour
  54015. : preferredColour.withMultipliedAlpha (0.9f));
  54016. g.fillPath (path);
  54017. g.setColour (button.findColour (isFrontTab ? TabbedButtonBar::frontOutlineColourId
  54018. : TabbedButtonBar::tabOutlineColourId, false)
  54019. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  54020. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  54021. }
  54022. void LookAndFeel::drawTabButtonText (Graphics& g,
  54023. int x, int y, int w, int h,
  54024. const Colour& preferredBackgroundColour,
  54025. int /*tabIndex*/,
  54026. const String& text,
  54027. Button& button,
  54028. TabbedButtonBar::Orientation orientation,
  54029. const bool isMouseOver,
  54030. const bool isMouseDown,
  54031. const bool isFrontTab)
  54032. {
  54033. int length = w;
  54034. int depth = h;
  54035. if (orientation == TabbedButtonBar::TabsAtLeft
  54036. || orientation == TabbedButtonBar::TabsAtRight)
  54037. {
  54038. swapVariables (length, depth);
  54039. }
  54040. Font font (depth * 0.6f);
  54041. font.setUnderline (button.hasKeyboardFocus (false));
  54042. GlyphArrangement textLayout;
  54043. textLayout.addFittedText (font, text.trim(),
  54044. 0.0f, 0.0f, (float) length, (float) depth,
  54045. Justification::centred,
  54046. jmax (1, depth / 12));
  54047. AffineTransform transform;
  54048. if (orientation == TabbedButtonBar::TabsAtLeft)
  54049. {
  54050. transform = transform.rotated (float_Pi * -0.5f)
  54051. .translated ((float) x, (float) (y + h));
  54052. }
  54053. else if (orientation == TabbedButtonBar::TabsAtRight)
  54054. {
  54055. transform = transform.rotated (float_Pi * 0.5f)
  54056. .translated ((float) (x + w), (float) y);
  54057. }
  54058. else
  54059. {
  54060. transform = transform.translated ((float) x, (float) y);
  54061. }
  54062. if (isFrontTab && (button.isColourSpecified (TabbedButtonBar::frontTextColourId) || isColourSpecified (TabbedButtonBar::frontTextColourId)))
  54063. g.setColour (findColour (TabbedButtonBar::frontTextColourId));
  54064. else if (button.isColourSpecified (TabbedButtonBar::tabTextColourId) || isColourSpecified (TabbedButtonBar::tabTextColourId))
  54065. g.setColour (findColour (TabbedButtonBar::tabTextColourId));
  54066. else
  54067. g.setColour (preferredBackgroundColour.contrasting());
  54068. if (! (isMouseOver || isMouseDown))
  54069. g.setOpacity (0.8f);
  54070. if (! button.isEnabled())
  54071. g.setOpacity (0.3f);
  54072. textLayout.draw (g, transform);
  54073. }
  54074. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  54075. const String& text,
  54076. int tabDepth,
  54077. Button&)
  54078. {
  54079. Font f (tabDepth * 0.6f);
  54080. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  54081. }
  54082. void LookAndFeel::drawTabButton (Graphics& g,
  54083. int w, int h,
  54084. const Colour& preferredColour,
  54085. int tabIndex,
  54086. const String& text,
  54087. Button& button,
  54088. TabbedButtonBar::Orientation orientation,
  54089. const bool isMouseOver,
  54090. const bool isMouseDown,
  54091. const bool isFrontTab)
  54092. {
  54093. int length = w;
  54094. int depth = h;
  54095. if (orientation == TabbedButtonBar::TabsAtLeft
  54096. || orientation == TabbedButtonBar::TabsAtRight)
  54097. {
  54098. swapVariables (length, depth);
  54099. }
  54100. Path tabShape;
  54101. createTabButtonShape (tabShape, w, h,
  54102. tabIndex, text, button, orientation,
  54103. isMouseOver, isMouseDown, isFrontTab);
  54104. fillTabButtonShape (g, tabShape, preferredColour,
  54105. tabIndex, text, button, orientation,
  54106. isMouseOver, isMouseDown, isFrontTab);
  54107. const int indent = getTabButtonOverlap (depth);
  54108. int x = 0, y = 0;
  54109. if (orientation == TabbedButtonBar::TabsAtLeft
  54110. || orientation == TabbedButtonBar::TabsAtRight)
  54111. {
  54112. y += indent;
  54113. h -= indent * 2;
  54114. }
  54115. else
  54116. {
  54117. x += indent;
  54118. w -= indent * 2;
  54119. }
  54120. drawTabButtonText (g, x, y, w, h, preferredColour,
  54121. tabIndex, text, button, orientation,
  54122. isMouseOver, isMouseDown, isFrontTab);
  54123. }
  54124. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  54125. int w, int h,
  54126. TabbedButtonBar& tabBar,
  54127. TabbedButtonBar::Orientation orientation)
  54128. {
  54129. const float shadowSize = 0.2f;
  54130. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  54131. Rectangle<int> shadowRect;
  54132. if (orientation == TabbedButtonBar::TabsAtLeft)
  54133. {
  54134. x1 = (float) w;
  54135. x2 = w * (1.0f - shadowSize);
  54136. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  54137. }
  54138. else if (orientation == TabbedButtonBar::TabsAtRight)
  54139. {
  54140. x2 = w * shadowSize;
  54141. shadowRect.setBounds (0, 0, (int) x2, h);
  54142. }
  54143. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54144. {
  54145. y2 = h * shadowSize;
  54146. shadowRect.setBounds (0, 0, w, (int) y2);
  54147. }
  54148. else
  54149. {
  54150. y1 = (float) h;
  54151. y2 = h * (1.0f - shadowSize);
  54152. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  54153. }
  54154. g.setGradientFill (ColourGradient (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  54155. Colours::transparentBlack, x2, y2, false));
  54156. shadowRect.expand (2, 2);
  54157. g.fillRect (shadowRect);
  54158. g.setColour (Colour (0x80000000));
  54159. if (orientation == TabbedButtonBar::TabsAtLeft)
  54160. {
  54161. g.fillRect (w - 1, 0, 1, h);
  54162. }
  54163. else if (orientation == TabbedButtonBar::TabsAtRight)
  54164. {
  54165. g.fillRect (0, 0, 1, h);
  54166. }
  54167. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54168. {
  54169. g.fillRect (0, 0, w, 1);
  54170. }
  54171. else
  54172. {
  54173. g.fillRect (0, h - 1, w, 1);
  54174. }
  54175. }
  54176. Button* LookAndFeel::createTabBarExtrasButton()
  54177. {
  54178. const float thickness = 7.0f;
  54179. const float indent = 22.0f;
  54180. Path p;
  54181. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  54182. DrawablePath ellipse;
  54183. ellipse.setPath (p);
  54184. ellipse.setFill (Colour (0x99ffffff));
  54185. p.clear();
  54186. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54187. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54188. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54189. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54190. p.setUsingNonZeroWinding (false);
  54191. DrawablePath dp;
  54192. dp.setPath (p);
  54193. dp.setFill (Colour (0x59000000));
  54194. DrawableComposite normalImage;
  54195. normalImage.insertDrawable (ellipse);
  54196. normalImage.insertDrawable (dp);
  54197. dp.setFill (Colour (0xcc000000));
  54198. DrawableComposite overImage;
  54199. overImage.insertDrawable (ellipse);
  54200. overImage.insertDrawable (dp);
  54201. DrawableButton* db = new DrawableButton ("tabs", DrawableButton::ImageFitted);
  54202. db->setImages (&normalImage, &overImage, 0);
  54203. return db;
  54204. }
  54205. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  54206. {
  54207. g.fillAll (Colours::white);
  54208. const int w = header.getWidth();
  54209. const int h = header.getHeight();
  54210. g.setGradientFill (ColourGradient (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  54211. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  54212. false));
  54213. g.fillRect (0, h / 2, w, h);
  54214. g.setColour (Colour (0x33000000));
  54215. g.fillRect (0, h - 1, w, 1);
  54216. for (int i = header.getNumColumns (true); --i >= 0;)
  54217. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  54218. }
  54219. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  54220. int width, int height,
  54221. bool isMouseOver, bool isMouseDown,
  54222. int columnFlags)
  54223. {
  54224. if (isMouseDown)
  54225. g.fillAll (Colour (0x8899aadd));
  54226. else if (isMouseOver)
  54227. g.fillAll (Colour (0x5599aadd));
  54228. int rightOfText = width - 4;
  54229. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  54230. {
  54231. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  54232. const float bottom = height - top;
  54233. const float w = height * 0.5f;
  54234. const float x = rightOfText - (w * 1.25f);
  54235. rightOfText = (int) x;
  54236. Path sortArrow;
  54237. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  54238. g.setColour (Colour (0x99000000));
  54239. g.fillPath (sortArrow);
  54240. }
  54241. g.setColour (Colours::black);
  54242. g.setFont (height * 0.5f, Font::bold);
  54243. const int textX = 4;
  54244. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  54245. }
  54246. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  54247. {
  54248. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  54249. g.setGradientFill (ColourGradient (background, 0.0f, 0.0f,
  54250. background.darker (0.1f),
  54251. toolbar.isVertical() ? w - 1.0f : 0.0f,
  54252. toolbar.isVertical() ? 0.0f : h - 1.0f,
  54253. false));
  54254. g.fillAll();
  54255. }
  54256. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  54257. {
  54258. return createTabBarExtrasButton();
  54259. }
  54260. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  54261. bool isMouseOver, bool isMouseDown,
  54262. ToolbarItemComponent& component)
  54263. {
  54264. if (isMouseDown)
  54265. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  54266. else if (isMouseOver)
  54267. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  54268. }
  54269. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  54270. const String& text, ToolbarItemComponent& component)
  54271. {
  54272. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  54273. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  54274. const float fontHeight = jmin (14.0f, height * 0.85f);
  54275. g.setFont (fontHeight);
  54276. g.drawFittedText (text,
  54277. x, y, width, height,
  54278. Justification::centred,
  54279. jmax (1, height / (int) fontHeight));
  54280. }
  54281. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  54282. bool isOpen, int width, int height)
  54283. {
  54284. const int buttonSize = (height * 3) / 4;
  54285. const int buttonIndent = (height - buttonSize) / 2;
  54286. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen, false);
  54287. const int textX = buttonIndent * 2 + buttonSize + 2;
  54288. g.setColour (Colours::black);
  54289. g.setFont (height * 0.7f, Font::bold);
  54290. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  54291. }
  54292. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  54293. PropertyComponent&)
  54294. {
  54295. g.setColour (Colour (0x66ffffff));
  54296. g.fillRect (0, 0, width, height - 1);
  54297. }
  54298. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  54299. PropertyComponent& component)
  54300. {
  54301. g.setColour (Colours::black);
  54302. if (! component.isEnabled())
  54303. g.setOpacity (0.6f);
  54304. g.setFont (jmin (height, 24) * 0.65f);
  54305. const Rectangle<int> r (getPropertyComponentContentPosition (component));
  54306. g.drawFittedText (component.getName(),
  54307. 3, r.getY(), r.getX() - 5, r.getHeight(),
  54308. Justification::centredLeft, 2);
  54309. }
  54310. const Rectangle<int> LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  54311. {
  54312. return Rectangle<int> (component.getWidth() / 3, 1,
  54313. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  54314. }
  54315. void LookAndFeel::drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path)
  54316. {
  54317. Image content (Image::ARGB, box.getWidth(), box.getHeight(), true);
  54318. {
  54319. Graphics g2 (content);
  54320. g2.setColour (Colour::greyLevel (0.23f).withAlpha (0.9f));
  54321. g2.fillPath (path);
  54322. g2.setColour (Colours::white.withAlpha (0.8f));
  54323. g2.strokePath (path, PathStrokeType (2.0f));
  54324. }
  54325. DropShadowEffect shadow;
  54326. shadow.setShadowProperties (5.0f, 0.4f, 0, 2);
  54327. shadow.applyEffect (content, g);
  54328. }
  54329. void LookAndFeel::createFileChooserHeaderText (const String& title,
  54330. const String& instructions,
  54331. GlyphArrangement& text,
  54332. int width)
  54333. {
  54334. text.clear();
  54335. text.addJustifiedText (Font (17.0f, Font::bold), title,
  54336. 8.0f, 22.0f, width - 16.0f,
  54337. Justification::centred);
  54338. text.addJustifiedText (Font (14.0f), instructions,
  54339. 8.0f, 24.0f + 16.0f, width - 16.0f,
  54340. Justification::centred);
  54341. }
  54342. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  54343. const String& filename, Image* icon,
  54344. const String& fileSizeDescription,
  54345. const String& fileTimeDescription,
  54346. const bool isDirectory,
  54347. const bool isItemSelected,
  54348. const int /*itemIndex*/,
  54349. DirectoryContentsDisplayComponent&)
  54350. {
  54351. if (isItemSelected)
  54352. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  54353. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  54354. g.setFont (height * 0.7f);
  54355. Image im;
  54356. if (icon != 0)
  54357. im = *icon;
  54358. if (im.isNull())
  54359. im = isDirectory ? getDefaultFolderImage()
  54360. : getDefaultDocumentFileImage();
  54361. const int x = 32;
  54362. if (im.isValid())
  54363. {
  54364. g.drawImageWithin (im, 2, 2, x - 4, height - 4,
  54365. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  54366. false);
  54367. }
  54368. if (width > 450 && ! isDirectory)
  54369. {
  54370. const int sizeX = roundToInt (width * 0.7f);
  54371. const int dateX = roundToInt (width * 0.8f);
  54372. g.drawFittedText (filename,
  54373. x, 0, sizeX - x, height,
  54374. Justification::centredLeft, 1);
  54375. g.setFont (height * 0.5f);
  54376. g.setColour (Colours::darkgrey);
  54377. if (! isDirectory)
  54378. {
  54379. g.drawFittedText (fileSizeDescription,
  54380. sizeX, 0, dateX - sizeX - 8, height,
  54381. Justification::centredRight, 1);
  54382. g.drawFittedText (fileTimeDescription,
  54383. dateX, 0, width - 8 - dateX, height,
  54384. Justification::centredRight, 1);
  54385. }
  54386. }
  54387. else
  54388. {
  54389. g.drawFittedText (filename,
  54390. x, 0, width - x, height,
  54391. Justification::centredLeft, 1);
  54392. }
  54393. }
  54394. Button* LookAndFeel::createFileBrowserGoUpButton()
  54395. {
  54396. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  54397. Path arrowPath;
  54398. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  54399. DrawablePath arrowImage;
  54400. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  54401. arrowImage.setPath (arrowPath);
  54402. goUpButton->setImages (&arrowImage);
  54403. return goUpButton;
  54404. }
  54405. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  54406. DirectoryContentsDisplayComponent* fileListComponent,
  54407. FilePreviewComponent* previewComp,
  54408. ComboBox* currentPathBox,
  54409. TextEditor* filenameBox,
  54410. Button* goUpButton)
  54411. {
  54412. const int x = 8;
  54413. int w = browserComp.getWidth() - x - x;
  54414. if (previewComp != 0)
  54415. {
  54416. const int previewWidth = w / 3;
  54417. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  54418. w -= previewWidth + 4;
  54419. }
  54420. int y = 4;
  54421. const int controlsHeight = 22;
  54422. const int bottomSectionHeight = controlsHeight + 8;
  54423. const int upButtonWidth = 50;
  54424. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  54425. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  54426. y += controlsHeight + 4;
  54427. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  54428. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  54429. y = listAsComp->getBottom() + 4;
  54430. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  54431. }
  54432. const Image LookAndFeel::getDefaultFolderImage()
  54433. {
  54434. static const unsigned char foldericon_png[] = { 137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,32,0,0,0,28,8,6,0,0,0,0,194,189,34,0,0,0,4,103,65,77,65,0,0,175,200,55,5,
  54435. 138,233,0,0,0,25,116,69,88,116,83,111,102,116,119,97,114,101,0,65,100,111,98,101,32,73,109,97,103,101,82,101,97,100,121,113,201,101,60,0,0,9,46,73,68,65,84,120,218,98,252,255,255,63,3,50,240,41,95,192,
  54436. 197,205,198,32,202,204,202,33,241,254,235,47,133,47,191,24,180,213,164,133,152,69,24,222,44,234,42,77,188,245,31,170,129,145,145,145,1,29,128,164,226,91,86,113,252,248,207,200,171,37,39,204,239,170,43,
  54437. 254,206,218,88,231,61,62,61,0,1,196,2,149,96,116,200,158,102,194,202,201,227,197,193,206,166,194,204,193,33,195,202,204,38,42,197,197,42,196,193,202,33,240,241,231,15,134,151,95,127,9,2,149,22,0,241,47,
  54438. 152,230,128,134,245,204,63,191,188,103,83,144,16,16,228,229,102,151,76,239,217,32,199,204,198,169,205,254,159,65,245,203,79,6,169,131,151,30,47,1,42,91,10,196,127,208,236,101,76,235,90,43,101,160,40,242,
  54439. 19,32,128,64,78,98,52,12,41,149,145,215,52,89,162,38,35,107,39,196,203,203,192,206,194,206,192,197,198,202,192,203,197,198,192,205,193,206,240,252,227,103,134,139,55,175,191,127,243,242,78,219,187,207,
  54440. 63,215,255,98,23,48,228,227,96,83,98,102,102,85,225,224,228,80,20,224,230,86,226,225,228,150,103,101,97,101,230,227,228,96,224,0,234,191,243,252,5,195,222,19,199,38,191,127,112,161,83,66,199,86,141,131,
  54441. 149,69,146,133,153,69,137,149,133,89,157,141,131,77,83,140,143,243,219,255,31,159,123,0,2,136,69,90,207,129,157,71,68,42,66,71,73,209,210,81,91,27,24,142,140,12,127,255,253,103,0,185,236,31,3,144,6,50,
  54442. 148,68,216,25,216,24,117,4,239,11,243,214,49,50,51,84,178,48,114,240,112,177,114,177,240,115,113,49,241,112,112,48,176,179,178,51,176,48,49,3,85,255,99,248,253,247,15,195,247,159,191,25,30,191,126,253,
  54443. 71,74,76,200,66,75,197,119,138,168,144,160,150,168,0,183,160,152,32,15,175,188,184,32,199,175,191,127,25,214,31,184,120,247,236,209,253,159,0,2,136,133,95,70,93,74,88,80,196,83,69,66,130,149,9,104,219,
  54444. 151,31,191,193,150,194,146,6,136,102,102,98,100,16,227,231,103,16,23,210,230,101,101,102,100,248,255,143,137,225,223,63,6,6,22,102,38,134,239,191,126,49,220,123,241,134,225,227,247,175,64,7,252,101,96,
  54445. 97,249,207,192,193,198,200,160,171,34,192,108,165,235,104,42,204,207,101,42,194,199,197,192,199,201,198,192,197,193,202,192,198,202,194,176,247,194,3,134,155,183,110,61,188,127,124,221,19,128,0,92,146,
  54446. 49,14,64,64,16,69,63,153,85,16,52,18,74,71,112,6,87,119,0,165,160,86,138,32,172,216,29,49,182,84,253,169,94,94,230,127,17,87,133,34,146,174,3,88,126,240,219,164,147,113,31,145,244,152,112,179,211,130,
  54447. 34,31,203,113,162,233,6,36,49,163,174,74,124,140,60,141,144,165,161,220,228,25,3,24,105,255,17,168,101,1,139,245,188,93,104,251,73,239,235,50,90,189,111,175,0,98,249,254,254,249,175,239,223,190,126,6,
  54448. 5,27,19,47,90,170,102,0,249,158,129,129,141,133,25,228,20,6,38,38,72,74,7,185,243,243,247,239,12,23,31,60,98,228,231,253,207,144,227,107,206,32,202,199,193,240,249,251,127,134,95,191,255,49,124,249,250,
  54449. 159,225,237,239,95,12,63,127,1,35,229,31,194,71,32,71,63,123,251,245,223,197,27,183,159,189,187,178,103,61,80,232,59,64,0,177,48,252,5,134,225,255,191,223,126,254,250,13,182,132,1,41,167,176,3,53,128,
  54450. 188,254,226,253,103,96,212,252,96,120,247,249,203,255,79,223,191,254,255,250,235,199,191,239,63,191,255,87,145,17,100,73,116,181,100,252,249,243,63,195,149,123,223,193,14,132,101,55,96,52,3,125,255,15,
  54451. 204,254,15,132,160,232,253,13,20,124,248,226,227,223,23,207,30,221,120,119,255,226,109,160,210,31,0,1,196,242,231,219,135,175,140,255,126,190,7,197,37,35,19,34,216,65,248,211,143,111,255,79,223,121,240,
  54452. 255,211,183,79,76,220,156,172,12,236,204,140,140,252,124,28,140,250,226,82,140,106,82,34,140,124,156,156,12,175,222,253,1,90,4,137,162,63,127,33,161,6,178,242,215,239,255,224,160,255,15,198,12,64,7,48,
  54453. 128,211,200,253,151,111,254,254,248,240,236,44,80,217,71,80,246,4,8,32,160,31,255,255,100,102,248,243,238,199,159,63,16,221,16,19,128,248,31,195,181,199,207,254,255,253,247,133,49,212,78,27,104,8,11,40,
  54454. 94,25,184,216,89,129,108,38,70,144,242,183,31,17,105,230,63,148,248,15,97,49,252,248,249,15,20,85,72,105,9,148,187,254,49,220,127,254,242,207,243,75,135,14,128,130,31,84,64,1,4,16,203,247,143,175,127,
  54455. 48,253,254,246,234,7,48,206,96,137,13,4,64,65,248,234,195,7,6,7,3,57,70,33,46,97,134,111,63,254,50,252,5,250,244,51,216,103,255,192,185,0,150,91,80,44,135,242,127,253,129,164,23,24,96,102,250,207,112,
  54456. 255,213,219,255,247,31,63,188,251,246,201,173,199,176,2,13,32,128,88,62,188,121,241,243,211,231,207,31,126,2,147,236,63,168,6,144,193,223,190,255,254,207,198,198,192,40,35,44,206,240,252,205,79,6,132,
  54457. 223,24,224,150,32,251,28,25,128,211,29,19,170,24,51,48,88,111,61,127,206,248,254,245,179,139,192,18,247,219,239,239,95,192,249,9,32,128,88,126,124,249,248,231,203,183,111,159,128,33,240,15,24,68,160,180,
  54458. 2,204,223,140,12,111,63,127,102,16,228,229,4,6,53,35,195,31,176,119,25,112,3,70,84,55,0,203,50,112,33,134,108,249,103,160,7,159,189,126,253,235,235,227,203,7,255,255,251,247,13,86,63,0,4,16,168,46,248,
  54459. 199,250,231,243,235,159,191,126,254,248,245,251,47,23,11,51,51,48,184,152,24,94,127,250,248,95,68,136,151,241,243,55,96,208,51,160,218,255,31,139,27,144,197,254,98,201,202,79,223,124,96,120,245,232,250,
  54460. 185,119,143,174,95,250,243,243,219,119,152,60,64,0,129,2,234,223,183,215,15,95,48,254,255,253,3,146,109,192,229,5,195,135,47,159,25,248,184,121,24,126,0,227,29,88,240,49,252,101,36,14,255,1,90,249,7,156,
  54461. 222,17,24,24,164,12,207,223,189,99,248,250,252,230,97,96,229,245,2,104,231,111,152,3,0,2,8,228,128,191,15,239,220,120,255,255,223,159,47,160,116,0,42,44,222,124,250,244,239,207,255,63,12,236,108,236,64,
  54462. 67,65,81,0,52,244,63,113,248,47,52,10,96,14,98,2,230,191,119,223,127,48,60,121,254,248,235,151,55,207,46,1,163,252,35,114,128,1,4,16,40,10,254,191,121,249,252,199,175,159,63,191,254,2,230,45,118,22,22,
  54463. 134,219,207,94,252,231,224,100,103,250,247,15,148,32,64,85,12,34,14,254,227,72,6,255,225,9,240,63,138,26,46,96,214,189,249,244,37,195,139,167,143,30,124,253,246,253,9,40,245,255,71,202,30,0,1,196,2,226,
  54464. 0,243,232,159,239,63,127,124,253,11,202,94,64,169,23,31,62,50,138,137,242,49,50,0,211,195,223,255,80,7,252,199,159,6,224,137,145,9,146,231,153,160,165,218,23,96,29,240,244,237,59,134,111,175,31,95,250,
  54465. 252,230,241,83,244,182,1,64,0,177,192,28,14,76,132,31,128,169,19,88,220,126,253,207,206,198,196,32,38,36,0,244,61,11,176,148,251,139,145,3,208,29,0,178,16,82,228,66,42,174,223,192,26,8,152,162,25,222,
  54466. 125,248,200,240,242,253,39,134,151,79,238,126,254,242,242,238,177,15,47,30,190,5,215,242,72,0,32,128,224,14,96,254,255,231,61,168,92,123,241,254,253,127,1,62,78,6,78,110,78,134,223,64,195,254,50,98,183,
  54467. 24,36,12,202,179,224,202,9,88,228,253,132,90,250,246,211,71,134,55,175,94,254,122,255,250,249,247,15,175,159,126,249,251,237,195,135,95,175,110,31,122,117,251,244,49,160,150,111,255,209,218,128,0,1,152,
  54468. 44,183,21,0,65,32,136,110,247,254,255,243,122,9,187,64,105,174,74,22,138,25,173,80,208,194,188,238,156,151,217,217,15,32,182,197,37,83,201,4,31,243,178,169,232,242,214,224,223,252,103,175,35,85,1,41,129,
  54469. 228,148,142,8,214,30,32,149,6,161,204,109,182,53,236,184,156,78,142,147,195,153,89,35,198,3,87,166,249,220,227,198,59,218,48,252,223,185,111,30,1,132,228,128,127,31,222,124,248,248,27,24,152,28,60,220,
  54470. 220,12,44,172,172,224,224,103,5,102,98,144,133,160,236,244,229,231,47,134,239,223,127,49,188,121,251,158,225,241,179,103,12,31,223,189,254,251,227,221,139,55,191,62,188,120,246,235,205,189,59,207,238,
  54471. 94,58,241,228,254,109,144,101,159,128,248,51,40,9,32,97,80,217,255,15,221,1,0,1,4,143,130,207,159,191,126,252,246,234,213,111,94,126,94,118,73,94,9,198,127,64,223,126,252,246,147,225,243,215,239,12,223,
  54472. 128,229,198,251,15,239,24,62,189,126,249,227,203,171,135,47,63,189,122,252,228,235,155,199,247,95,63,188,118,227,197,227,123,247,127,255,250,249,30,104,198,7,32,126,11,181,252,7,212,183,160,4,247,7,155,
  54473. 197,48,0,16,64,112,7,60,121,241,238,189,16,207,15,134,63,63,216,25,95,125,248,198,112,227,241,27,134,15,239,223,50,124,126,245,228,253,143,55,143,158,191,123,116,237,226,171,135,55,175,126,253,252,225,
  54474. 229,183,47,159,95,254,253,245,227,253,175,159,223,223,193,124,7,181,20,84,105,252,70,143,103,124,0,32,128,224,14,224,102,253,251,81,144,253,223,235,167,207,30,254,124,127,231,252,155,143,175,159,188,250,
  54475. 246,254,249,125,96,60,62,248,250,233,253,147,119,207,238,221,6,150,214,175,129,106,191,130,18,19,146,133,120,125,72,8,0,4,16,34,27,190,121,112,251,3,211,159,69,143,110,223,229,120,255,232,230,221,215,
  54476. 79,239,62,4,102,203,207,72,241,9,11,218,63,72,89,137,20,207,98,100,93,16,0,8,32,70,144,1,64,14,168,209,199,7,196,194,160,166,27,212,135,95,96,65,10,173,95,254,34,219,6,51,128,88,7,96,235,21,129,0,64,0,
  54477. 193,28,192,8,174,53,33,152,1,155,133,184,12,196,165,4,151,133,232,0,32,192,0,151,97,210,163,246,134,208,52,0,0,0,0,73,69,78,68,174,66,96,130,0,0};
  54478. return ImageCache::getFromMemory (foldericon_png, sizeof (foldericon_png));
  54479. }
  54480. const Image LookAndFeel::getDefaultDocumentFileImage()
  54481. {
  54482. static const unsigned char fileicon_png[] = { 137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,0,32,0,0,0,32,8,6,0,0,0,115,122,122,244,0,0,0,4,103,65,77,65,0,0,175,200,55,5,
  54483. 138,233,0,0,0,25,116,69,88,116,83,111,102,116,119,97,114,101,0,65,100,111,98,101,32,73,109,97,103,101,82,101,97,100,121,113,201,101,60,0,0,4,99,73,68,65,84,120,218,98,252,255,255,63,3,12,48,50,50,50,1,
  54484. 169,127,200,98,148,2,160,153,204,64,243,254,226,146,7,8,32,22,52,203,255,107,233,233,91,76,93,176,184,232,239,239,95,127,24,40,112,8,19,51,203,255,179,23,175,108,1,90,190,28,104,54,43,80,232,207,127,44,
  54485. 62,3,8,32,6,144,24,84,156,25,132,189,252,3,146,255,83,9,220,127,254,242,134,162,138,170,10,208,92,144,3,152,97,118,33,99,128,0,98,66,114,11,200,1,92,255,254,252,225,32,215,215,32,127,64,240,127,80,60,
  54486. 50,40,72,136,169,47,95,179,118,130,136,148,140,0,40,80,128,33,193,136,174,7,32,128,144,29,192,8,117,41,59,209,22,66,241,191,255,16,12,244,19,195,63,48,134,240,255,0,9,115,125,93,239,252,130,130,108,168,
  54487. 249,44,232,102,0,4,16,19,22,62,51,33,11,255,195,44,4,211,255,25,96,16,33,6,117,24,56,226,25,24,202,139,10,75,226,51,115,66,160,105,13,197,17,0,1,196,68,172,79,255,33,91,206,192,192,128,176,22,17,10,200,
  54488. 234,32,161,240,31,24,10,255,24,152,153,153,184,39,244,247,117,107,234,234,105,131,66,1,154,224,193,0,32,128,240,58,0,22,180,255,144,18,13,40,136,33,113,140,36,255,15,17,26,48,12,81,15,145,255,254,251,
  54489. 31,131,0,59,171,84,81,73,105,33,208,216,191,200,161,12,16,64,44,248,131,251,63,10,31,198,253,143,38,6,83,7,11,33,228,232,2,123,4,202,226,228,96,151,132,166,49,144,35,126,131,196,0,2,136,5,103,60,51,252,
  54490. 71,49,12,213,130,255,168,226,232,150,254,255,15,143,6,80,202,3,133,16,200,198,63,127,193,229,17,39,16,127,135,217,7,16,64,88,67,0,28,143,255,25,225,46,135,249,18,155,133,240,178,4,205,145,8,62,52,186,
  54491. 32,234,152,160,118,194,179,35,64,0,177,96,11,123,144,236,95,104,92,162,228,113,36,11,81,125,140,112,56,186,131,96,226,176,172,137,148,229,193,0,32,128,88,112,167,248,255,112,223,48,34,165,110,6,124,190,
  54492. 253,143,61,106,192,9,19,73,28,25,0,4,16,206,40,248,251,15,45,104,209,130,21,51,222,145,18,238,127,180,68,8,244,250,95,164,16,66,6,0,1,196,130,45,253,195,12,250,135,53,206,255,195,131,18,213,98,236,81,
  54493. 243,31,154,11,144,115,8,50,0,8,32,156,81,0,203,227,12,80,223,98,230,4,68,72,96,38,78,84,11,65,9,250,47,146,3,145,1,64,0,97,117,192,95,112,34,68,138,130,255,176,224,251,143,226,51,6,6,68,29,192,136,20,
  54494. 77,200,69,54,35,3,36,49,255,69,77,132,112,0,16,64,44,56,139,94,36,7,96,102,59,164,108,249,31,181,82,98,64,203,174,255,144,234,142,127,88,146,33,64,0,97,205,134,240,120,67,75,76,136,224,198,140,22,6,44,
  54495. 142,66,201,41,255,177,231,2,128,0,194,25,5,255,254,161,134,192,127,6,28,229,0,129,242,1,150,56,33,81,138,209,28,96,0,8,32,172,81,0,78,3,104,190,68,182,224,31,146,197,224,56,6,146,140,176,202,135,17,169,
  54496. 96,130,40,64,56,0,139,93,0,1,132,61,10,64,248,31,106,156,162,199,55,204,65,255,144,178,38,74,84,252,71,51,239,63,246,68,8,16,64,44,216,74,1,88,217,13,203,191,32,1,80,58,7,133,224,127,6,68,114,6,241,65,
  54497. 81,197,8,101,255,71,114,33,92,237,127,228,52,128,233,2,128,0,98,193,149,3,64,117,193,255,127,255,81,75,191,127,168,5,18,136,255,31,45,161,49,32,151,134,72,252,127,12,216,203,98,128,0,98,193,210,144,135,
  54498. 248,30,201,242,127,208,252,140,145,27,160,113,206,136,148,197,192,121,159,17,53,184,225,149,17,22,23,0,4,16,11,182,150,237,63,168,207,96,142,248,143,163,72,6,203,253,67,13,61,6,104,14,66,46,17,254,65,
  54499. 19,40,182,16,0,8,32,22,108,109,235,255,176,234,24,35,79,255,199,222,30,64,81,135,90,35,194,211,4,142,92,0,16,64,88,29,0,107,7,254,251,247,31,53,78,241,54,207,80,29,135,209,96,249,143,189,46,0,8,32,116,
  54500. 7,252,101,102,103,103,228,103,99,96,248,193,198,137,53,248,49,125,204,128,225,227,255,88,18,54,47,176,25,202,205,195,205,6,109,11,194,149,0,4,16,35,204,85,208,254,27,159,128,176,176,142,166,182,142,21,
  54501. 48,4,248,129,41,143,13,217,16,70,52,95,147,0,254,0,187,69,95,223,188,122,125,235,206,141,107,7,129,252,247,64,123,193,237,66,128,0,66,118,0,168,189,198,3,196,252,32,135,64,105,54,228,230,19,185,29,100,
  54502. 168,175,191,0,241,7,32,254,4,196,159,129,246,254,2,73,2,4,16,11,90,72,125,135,210,63,161,138,153,169,212,75,255,15,117,196,15,40,134,119,215,1,2,12,0,187,0,132,247,216,161,197,124,0,0,0,0,73,69,78,68,
  54503. 174,66,96,130,0,0};
  54504. return ImageCache::getFromMemory (fileicon_png, sizeof (fileicon_png));
  54505. }
  54506. void LookAndFeel::playAlertSound()
  54507. {
  54508. PlatformUtilities::beep();
  54509. }
  54510. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  54511. {
  54512. g.setColour (Colours::white.withAlpha (0.7f));
  54513. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  54514. g.setColour (Colours::black.withAlpha (0.2f));
  54515. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  54516. const int totalBlocks = 7;
  54517. const int numBlocks = roundToInt (totalBlocks * level);
  54518. const float w = (width - 6.0f) / (float) totalBlocks;
  54519. for (int i = 0; i < totalBlocks; ++i)
  54520. {
  54521. if (i >= numBlocks)
  54522. g.setColour (Colours::lightblue.withAlpha (0.6f));
  54523. else
  54524. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  54525. : Colours::red);
  54526. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  54527. }
  54528. }
  54529. void LookAndFeel::drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription)
  54530. {
  54531. const Colour textColour (button.findColour (KeyMappingEditorComponent::textColourId, true));
  54532. if (keyDescription.isNotEmpty())
  54533. {
  54534. if (button.isEnabled())
  54535. {
  54536. const float alpha = button.isDown() ? 0.3f : (button.isOver() ? 0.15f : 0.08f);
  54537. g.fillAll (textColour.withAlpha (alpha));
  54538. g.setOpacity (0.3f);
  54539. g.drawBevel (0, 0, width, height, 2);
  54540. }
  54541. g.setColour (textColour);
  54542. g.setFont (height * 0.6f);
  54543. g.drawFittedText (keyDescription,
  54544. 3, 0, width - 6, height,
  54545. Justification::centred, 1);
  54546. }
  54547. else
  54548. {
  54549. const float thickness = 7.0f;
  54550. const float indent = 22.0f;
  54551. Path p;
  54552. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54553. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54554. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54555. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54556. p.setUsingNonZeroWinding (false);
  54557. g.setColour (textColour.withAlpha (button.isDown() ? 0.7f : (button.isOver() ? 0.5f : 0.3f)));
  54558. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, width - 4.0f, height - 4.0f, true));
  54559. }
  54560. if (button.hasKeyboardFocus (false))
  54561. {
  54562. g.setColour (textColour.withAlpha (0.4f));
  54563. g.drawRect (0, 0, width, height);
  54564. }
  54565. }
  54566. static void createRoundedPath (Path& p,
  54567. const float x, const float y,
  54568. const float w, const float h,
  54569. const float cs,
  54570. const bool curveTopLeft, const bool curveTopRight,
  54571. const bool curveBottomLeft, const bool curveBottomRight) throw()
  54572. {
  54573. const float cs2 = 2.0f * cs;
  54574. if (curveTopLeft)
  54575. {
  54576. p.startNewSubPath (x, y + cs);
  54577. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  54578. }
  54579. else
  54580. {
  54581. p.startNewSubPath (x, y);
  54582. }
  54583. if (curveTopRight)
  54584. {
  54585. p.lineTo (x + w - cs, y);
  54586. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  54587. }
  54588. else
  54589. {
  54590. p.lineTo (x + w, y);
  54591. }
  54592. if (curveBottomRight)
  54593. {
  54594. p.lineTo (x + w, y + h - cs);
  54595. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  54596. }
  54597. else
  54598. {
  54599. p.lineTo (x + w, y + h);
  54600. }
  54601. if (curveBottomLeft)
  54602. {
  54603. p.lineTo (x + cs, y + h);
  54604. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  54605. }
  54606. else
  54607. {
  54608. p.lineTo (x, y + h);
  54609. }
  54610. p.closeSubPath();
  54611. }
  54612. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  54613. float x, float y, float w, float h,
  54614. float maxCornerSize,
  54615. const Colour& baseColour,
  54616. const float strokeWidth,
  54617. const bool flatOnLeft,
  54618. const bool flatOnRight,
  54619. const bool flatOnTop,
  54620. const bool flatOnBottom) throw()
  54621. {
  54622. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  54623. return;
  54624. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  54625. Path outline;
  54626. createRoundedPath (outline, x, y, w, h, cs,
  54627. ! (flatOnLeft || flatOnTop),
  54628. ! (flatOnRight || flatOnTop),
  54629. ! (flatOnLeft || flatOnBottom),
  54630. ! (flatOnRight || flatOnBottom));
  54631. ColourGradient cg (baseColour, 0.0f, y,
  54632. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  54633. false);
  54634. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  54635. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  54636. g.setGradientFill (cg);
  54637. g.fillPath (outline);
  54638. g.setColour (Colour (0x80000000));
  54639. g.strokePath (outline, PathStrokeType (strokeWidth));
  54640. }
  54641. void LookAndFeel::drawGlassSphere (Graphics& g,
  54642. const float x, const float y,
  54643. const float diameter,
  54644. const Colour& colour,
  54645. const float outlineThickness) throw()
  54646. {
  54647. if (diameter <= outlineThickness)
  54648. return;
  54649. Path p;
  54650. p.addEllipse (x, y, diameter, diameter);
  54651. {
  54652. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54653. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54654. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54655. g.setGradientFill (cg);
  54656. g.fillPath (p);
  54657. }
  54658. g.setGradientFill (ColourGradient (Colours::white, 0, y + diameter * 0.06f,
  54659. Colours::transparentWhite, 0, y + diameter * 0.3f, false));
  54660. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  54661. ColourGradient cg (Colours::transparentBlack,
  54662. x + diameter * 0.5f, y + diameter * 0.5f,
  54663. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54664. x, y + diameter * 0.5f, true);
  54665. cg.addColour (0.7, Colours::transparentBlack);
  54666. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  54667. g.setGradientFill (cg);
  54668. g.fillPath (p);
  54669. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54670. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  54671. }
  54672. void LookAndFeel::drawGlassPointer (Graphics& g,
  54673. const float x, const float y,
  54674. const float diameter,
  54675. const Colour& colour, const float outlineThickness,
  54676. const int direction) throw()
  54677. {
  54678. if (diameter <= outlineThickness)
  54679. return;
  54680. Path p;
  54681. p.startNewSubPath (x + diameter * 0.5f, y);
  54682. p.lineTo (x + diameter, y + diameter * 0.6f);
  54683. p.lineTo (x + diameter, y + diameter);
  54684. p.lineTo (x, y + diameter);
  54685. p.lineTo (x, y + diameter * 0.6f);
  54686. p.closeSubPath();
  54687. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  54688. {
  54689. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54690. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54691. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54692. g.setGradientFill (cg);
  54693. g.fillPath (p);
  54694. }
  54695. ColourGradient cg (Colours::transparentBlack,
  54696. x + diameter * 0.5f, y + diameter * 0.5f,
  54697. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54698. x - diameter * 0.2f, y + diameter * 0.5f, true);
  54699. cg.addColour (0.5, Colours::transparentBlack);
  54700. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  54701. g.setGradientFill (cg);
  54702. g.fillPath (p);
  54703. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54704. g.strokePath (p, PathStrokeType (outlineThickness));
  54705. }
  54706. void LookAndFeel::drawGlassLozenge (Graphics& g,
  54707. const float x, const float y,
  54708. const float width, const float height,
  54709. const Colour& colour,
  54710. const float outlineThickness,
  54711. const float cornerSize,
  54712. const bool flatOnLeft,
  54713. const bool flatOnRight,
  54714. const bool flatOnTop,
  54715. const bool flatOnBottom) throw()
  54716. {
  54717. if (width <= outlineThickness || height <= outlineThickness)
  54718. return;
  54719. const int intX = (int) x;
  54720. const int intY = (int) y;
  54721. const int intW = (int) width;
  54722. const int intH = (int) height;
  54723. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  54724. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  54725. const int intEdge = (int) edgeBlurRadius;
  54726. Path outline;
  54727. createRoundedPath (outline, x, y, width, height, cs,
  54728. ! (flatOnLeft || flatOnTop),
  54729. ! (flatOnRight || flatOnTop),
  54730. ! (flatOnLeft || flatOnBottom),
  54731. ! (flatOnRight || flatOnBottom));
  54732. {
  54733. ColourGradient cg (colour.darker (0.2f), 0, y,
  54734. colour.darker (0.2f), 0, y + height, false);
  54735. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  54736. cg.addColour (0.4, colour);
  54737. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  54738. g.setGradientFill (cg);
  54739. g.fillPath (outline);
  54740. }
  54741. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  54742. colour.darker (0.2f), x, y + height * 0.5f, true);
  54743. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  54744. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  54745. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  54746. {
  54747. g.saveState();
  54748. g.setGradientFill (cg);
  54749. g.reduceClipRegion (intX, intY, intEdge, intH);
  54750. g.fillPath (outline);
  54751. g.restoreState();
  54752. }
  54753. if (! (flatOnRight || flatOnTop || flatOnBottom))
  54754. {
  54755. cg.point1.setX (x + width - edgeBlurRadius);
  54756. cg.point2.setX (x + width);
  54757. g.saveState();
  54758. g.setGradientFill (cg);
  54759. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  54760. g.fillPath (outline);
  54761. g.restoreState();
  54762. }
  54763. {
  54764. const float leftIndent = flatOnLeft ? 0.0f : cs * 0.4f;
  54765. const float rightIndent = flatOnRight ? 0.0f : cs * 0.4f;
  54766. Path highlight;
  54767. createRoundedPath (highlight,
  54768. x + leftIndent,
  54769. y + cs * 0.1f,
  54770. width - (leftIndent + rightIndent),
  54771. height * 0.4f, cs * 0.4f,
  54772. ! (flatOnLeft || flatOnTop),
  54773. ! (flatOnRight || flatOnTop),
  54774. ! (flatOnLeft || flatOnBottom),
  54775. ! (flatOnRight || flatOnBottom));
  54776. g.setGradientFill (ColourGradient (colour.brighter (10.0f), 0, y + height * 0.06f,
  54777. Colours::transparentWhite, 0, y + height * 0.4f, false));
  54778. g.fillPath (highlight);
  54779. }
  54780. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  54781. g.strokePath (outline, PathStrokeType (outlineThickness));
  54782. }
  54783. END_JUCE_NAMESPACE
  54784. /*** End of inlined file: juce_LookAndFeel.cpp ***/
  54785. /*** Start of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  54786. BEGIN_JUCE_NAMESPACE
  54787. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  54788. {
  54789. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  54790. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  54791. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  54792. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  54793. setColour (Slider::thumbColourId, Colours::white);
  54794. setColour (Slider::trackColourId, Colour (0x7f000000));
  54795. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  54796. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  54797. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  54798. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  54799. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  54800. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  54801. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  54802. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  54803. }
  54804. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  54805. {
  54806. }
  54807. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  54808. Button& button,
  54809. const Colour& backgroundColour,
  54810. bool isMouseOverButton,
  54811. bool isButtonDown)
  54812. {
  54813. const int width = button.getWidth();
  54814. const int height = button.getHeight();
  54815. const float indent = 2.0f;
  54816. const int cornerSize = jmin (roundToInt (width * 0.4f),
  54817. roundToInt (height * 0.4f));
  54818. Path p;
  54819. p.addRoundedRectangle (indent, indent,
  54820. width - indent * 2.0f,
  54821. height - indent * 2.0f,
  54822. (float) cornerSize);
  54823. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  54824. if (isMouseOverButton)
  54825. {
  54826. if (isButtonDown)
  54827. bc = bc.brighter();
  54828. else if (bc.getBrightness() > 0.5f)
  54829. bc = bc.darker (0.1f);
  54830. else
  54831. bc = bc.brighter (0.1f);
  54832. }
  54833. g.setColour (bc);
  54834. g.fillPath (p);
  54835. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  54836. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  54837. }
  54838. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  54839. Component& /*component*/,
  54840. float x, float y, float w, float h,
  54841. const bool ticked,
  54842. const bool isEnabled,
  54843. const bool /*isMouseOverButton*/,
  54844. const bool isButtonDown)
  54845. {
  54846. Path box;
  54847. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  54848. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  54849. : Colours::lightgrey.withAlpha (0.1f));
  54850. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f).translated (x, y));
  54851. g.fillPath (box, trans);
  54852. g.setColour (Colours::black.withAlpha (0.6f));
  54853. g.strokePath (box, PathStrokeType (0.9f), trans);
  54854. if (ticked)
  54855. {
  54856. Path tick;
  54857. tick.startNewSubPath (1.5f, 3.0f);
  54858. tick.lineTo (3.0f, 6.0f);
  54859. tick.lineTo (6.0f, 0.0f);
  54860. g.setColour (isEnabled ? Colours::black : Colours::grey);
  54861. g.strokePath (tick, PathStrokeType (2.5f), trans);
  54862. }
  54863. }
  54864. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  54865. ToggleButton& button,
  54866. bool isMouseOverButton,
  54867. bool isButtonDown)
  54868. {
  54869. if (button.hasKeyboardFocus (true))
  54870. {
  54871. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  54872. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  54873. }
  54874. const int tickWidth = jmin (20, button.getHeight() - 4);
  54875. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  54876. (float) tickWidth, (float) tickWidth,
  54877. button.getToggleState(),
  54878. button.isEnabled(),
  54879. isMouseOverButton,
  54880. isButtonDown);
  54881. g.setColour (button.findColour (ToggleButton::textColourId));
  54882. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  54883. if (! button.isEnabled())
  54884. g.setOpacity (0.5f);
  54885. const int textX = tickWidth + 5;
  54886. g.drawFittedText (button.getButtonText(),
  54887. textX, 4,
  54888. button.getWidth() - textX - 2, button.getHeight() - 8,
  54889. Justification::centredLeft, 10);
  54890. }
  54891. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  54892. int width, int height,
  54893. double progress, const String& textToShow)
  54894. {
  54895. if (progress < 0 || progress >= 1.0)
  54896. {
  54897. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  54898. }
  54899. else
  54900. {
  54901. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  54902. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  54903. g.fillAll (background);
  54904. g.setColour (foreground);
  54905. g.fillRect (1, 1,
  54906. jlimit (0, width - 2, roundToInt (progress * (width - 2))),
  54907. height - 2);
  54908. if (textToShow.isNotEmpty())
  54909. {
  54910. g.setColour (Colour::contrasting (background, foreground));
  54911. g.setFont (height * 0.6f);
  54912. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  54913. }
  54914. }
  54915. }
  54916. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  54917. ScrollBar& bar,
  54918. int width, int height,
  54919. int buttonDirection,
  54920. bool isScrollbarVertical,
  54921. bool isMouseOverButton,
  54922. bool isButtonDown)
  54923. {
  54924. if (isScrollbarVertical)
  54925. width -= 2;
  54926. else
  54927. height -= 2;
  54928. Path p;
  54929. if (buttonDirection == 0)
  54930. p.addTriangle (width * 0.5f, height * 0.2f,
  54931. width * 0.1f, height * 0.7f,
  54932. width * 0.9f, height * 0.7f);
  54933. else if (buttonDirection == 1)
  54934. p.addTriangle (width * 0.8f, height * 0.5f,
  54935. width * 0.3f, height * 0.1f,
  54936. width * 0.3f, height * 0.9f);
  54937. else if (buttonDirection == 2)
  54938. p.addTriangle (width * 0.5f, height * 0.8f,
  54939. width * 0.1f, height * 0.3f,
  54940. width * 0.9f, height * 0.3f);
  54941. else if (buttonDirection == 3)
  54942. p.addTriangle (width * 0.2f, height * 0.5f,
  54943. width * 0.7f, height * 0.1f,
  54944. width * 0.7f, height * 0.9f);
  54945. if (isButtonDown)
  54946. g.setColour (Colours::white);
  54947. else if (isMouseOverButton)
  54948. g.setColour (Colours::white.withAlpha (0.7f));
  54949. else
  54950. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  54951. g.fillPath (p);
  54952. g.setColour (Colours::black.withAlpha (0.5f));
  54953. g.strokePath (p, PathStrokeType (0.5f));
  54954. }
  54955. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  54956. ScrollBar& bar,
  54957. int x, int y,
  54958. int width, int height,
  54959. bool isScrollbarVertical,
  54960. int thumbStartPosition,
  54961. int thumbSize,
  54962. bool isMouseOver,
  54963. bool isMouseDown)
  54964. {
  54965. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  54966. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54967. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  54968. if (thumbSize > 0.0f)
  54969. {
  54970. Rectangle<int> thumb;
  54971. if (isScrollbarVertical)
  54972. {
  54973. width -= 2;
  54974. g.fillRect (x + roundToInt (width * 0.35f), y,
  54975. roundToInt (width * 0.3f), height);
  54976. thumb.setBounds (x + 1, thumbStartPosition,
  54977. width - 2, thumbSize);
  54978. }
  54979. else
  54980. {
  54981. height -= 2;
  54982. g.fillRect (x, y + roundToInt (height * 0.35f),
  54983. width, roundToInt (height * 0.3f));
  54984. thumb.setBounds (thumbStartPosition, y + 1,
  54985. thumbSize, height - 2);
  54986. }
  54987. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  54988. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  54989. g.fillRect (thumb);
  54990. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  54991. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  54992. if (thumbSize > 16)
  54993. {
  54994. for (int i = 3; --i >= 0;)
  54995. {
  54996. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  54997. g.setColour (Colours::black.withAlpha (0.15f));
  54998. if (isScrollbarVertical)
  54999. {
  55000. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  55001. g.setColour (Colours::white.withAlpha (0.15f));
  55002. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  55003. }
  55004. else
  55005. {
  55006. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  55007. g.setColour (Colours::white.withAlpha (0.15f));
  55008. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  55009. }
  55010. }
  55011. }
  55012. }
  55013. }
  55014. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  55015. {
  55016. return &scrollbarShadow;
  55017. }
  55018. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  55019. {
  55020. g.fillAll (findColour (PopupMenu::backgroundColourId));
  55021. g.setColour (Colours::black.withAlpha (0.6f));
  55022. g.drawRect (0, 0, width, height);
  55023. }
  55024. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  55025. bool, MenuBarComponent& menuBar)
  55026. {
  55027. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  55028. }
  55029. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  55030. {
  55031. if (textEditor.isEnabled())
  55032. {
  55033. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  55034. g.drawRect (0, 0, width, height);
  55035. }
  55036. }
  55037. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  55038. const bool isButtonDown,
  55039. int buttonX, int buttonY,
  55040. int buttonW, int buttonH,
  55041. ComboBox& box)
  55042. {
  55043. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  55044. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  55045. : ComboBox::backgroundColourId));
  55046. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  55047. g.setColour (box.findColour (ComboBox::outlineColourId));
  55048. g.drawRect (0, 0, width, height);
  55049. const float arrowX = 0.2f;
  55050. const float arrowH = 0.3f;
  55051. if (box.isEnabled())
  55052. {
  55053. Path p;
  55054. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  55055. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  55056. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  55057. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  55058. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  55059. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  55060. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  55061. : ComboBox::buttonColourId));
  55062. g.fillPath (p);
  55063. }
  55064. }
  55065. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  55066. {
  55067. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  55068. f.setHorizontalScale (0.9f);
  55069. return f;
  55070. }
  55071. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  55072. {
  55073. Path p;
  55074. p.addTriangle (x1, y1, x2, y2, x3, y3);
  55075. g.setColour (fill);
  55076. g.fillPath (p);
  55077. g.setColour (outline);
  55078. g.strokePath (p, PathStrokeType (0.3f));
  55079. }
  55080. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  55081. int x, int y,
  55082. int w, int h,
  55083. float sliderPos,
  55084. float minSliderPos,
  55085. float maxSliderPos,
  55086. const Slider::SliderStyle style,
  55087. Slider& slider)
  55088. {
  55089. g.fillAll (slider.findColour (Slider::backgroundColourId));
  55090. if (style == Slider::LinearBar)
  55091. {
  55092. g.setColour (slider.findColour (Slider::thumbColourId));
  55093. g.fillRect (x, y, (int) sliderPos - x, h);
  55094. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  55095. g.drawRect (x, y, (int) sliderPos - x, h);
  55096. }
  55097. else
  55098. {
  55099. g.setColour (slider.findColour (Slider::trackColourId)
  55100. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  55101. if (slider.isHorizontal())
  55102. {
  55103. g.fillRect (x, y + roundToInt (h * 0.6f),
  55104. w, roundToInt (h * 0.2f));
  55105. }
  55106. else
  55107. {
  55108. g.fillRect (x + roundToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  55109. jmin (4, roundToInt (w * 0.2f)), h);
  55110. }
  55111. float alpha = 0.35f;
  55112. if (slider.isEnabled())
  55113. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  55114. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  55115. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  55116. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  55117. {
  55118. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  55119. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  55120. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  55121. fill, outline);
  55122. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  55123. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  55124. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  55125. fill, outline);
  55126. }
  55127. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  55128. {
  55129. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  55130. minSliderPos - 7.0f, y + h * 0.9f ,
  55131. minSliderPos, y + h * 0.9f,
  55132. fill, outline);
  55133. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  55134. maxSliderPos, y + h * 0.9f,
  55135. maxSliderPos + 7.0f, y + h * 0.9f,
  55136. fill, outline);
  55137. }
  55138. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  55139. {
  55140. drawTriangle (g, sliderPos, y + h * 0.9f,
  55141. sliderPos - 7.0f, y + h * 0.2f,
  55142. sliderPos + 7.0f, y + h * 0.2f,
  55143. fill, outline);
  55144. }
  55145. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  55146. {
  55147. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  55148. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  55149. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  55150. fill, outline);
  55151. }
  55152. }
  55153. }
  55154. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  55155. {
  55156. if (isIncrement)
  55157. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  55158. else
  55159. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  55160. }
  55161. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  55162. {
  55163. return &scrollbarShadow;
  55164. }
  55165. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  55166. {
  55167. return 8;
  55168. }
  55169. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  55170. int w, int h,
  55171. bool isMouseOver,
  55172. bool isMouseDragging)
  55173. {
  55174. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  55175. : Colours::darkgrey);
  55176. const float lineThickness = jmin (w, h) * 0.1f;
  55177. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  55178. {
  55179. g.drawLine (w * i,
  55180. h + 1.0f,
  55181. w + 1.0f,
  55182. h * i,
  55183. lineThickness);
  55184. }
  55185. }
  55186. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  55187. {
  55188. Path shape;
  55189. if (buttonType == DocumentWindow::closeButton)
  55190. {
  55191. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), 0.35f);
  55192. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), 0.35f);
  55193. ShapeButton* const b = new ShapeButton ("close",
  55194. Colour (0x7fff3333),
  55195. Colour (0xd7ff3333),
  55196. Colour (0xf7ff3333));
  55197. b->setShape (shape, true, true, true);
  55198. return b;
  55199. }
  55200. else if (buttonType == DocumentWindow::minimiseButton)
  55201. {
  55202. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  55203. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  55204. DrawablePath dp;
  55205. dp.setPath (shape);
  55206. dp.setFill (Colours::black.withAlpha (0.3f));
  55207. b->setImages (&dp);
  55208. return b;
  55209. }
  55210. else if (buttonType == DocumentWindow::maximiseButton)
  55211. {
  55212. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), 0.25f);
  55213. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  55214. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  55215. DrawablePath dp;
  55216. dp.setPath (shape);
  55217. dp.setFill (Colours::black.withAlpha (0.3f));
  55218. b->setImages (&dp);
  55219. return b;
  55220. }
  55221. jassertfalse;
  55222. return 0;
  55223. }
  55224. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  55225. int titleBarX,
  55226. int titleBarY,
  55227. int titleBarW,
  55228. int titleBarH,
  55229. Button* minimiseButton,
  55230. Button* maximiseButton,
  55231. Button* closeButton,
  55232. bool positionTitleBarButtonsOnLeft)
  55233. {
  55234. titleBarY += titleBarH / 8;
  55235. titleBarH -= titleBarH / 4;
  55236. const int buttonW = titleBarH;
  55237. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  55238. : titleBarX + titleBarW - buttonW - 4;
  55239. if (closeButton != 0)
  55240. {
  55241. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  55242. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  55243. : -(buttonW + buttonW / 5);
  55244. }
  55245. if (positionTitleBarButtonsOnLeft)
  55246. swapVariables (minimiseButton, maximiseButton);
  55247. if (maximiseButton != 0)
  55248. {
  55249. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55250. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  55251. }
  55252. if (minimiseButton != 0)
  55253. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55254. }
  55255. END_JUCE_NAMESPACE
  55256. /*** End of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  55257. /*** Start of inlined file: juce_MenuBarComponent.cpp ***/
  55258. BEGIN_JUCE_NAMESPACE
  55259. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  55260. : model (0),
  55261. itemUnderMouse (-1),
  55262. currentPopupIndex (-1),
  55263. topLevelIndexClicked (0),
  55264. lastMouseX (0),
  55265. lastMouseY (0)
  55266. {
  55267. setRepaintsOnMouseActivity (true);
  55268. setWantsKeyboardFocus (false);
  55269. setMouseClickGrabsKeyboardFocus (false);
  55270. setModel (model_);
  55271. }
  55272. MenuBarComponent::~MenuBarComponent()
  55273. {
  55274. setModel (0);
  55275. Desktop::getInstance().removeGlobalMouseListener (this);
  55276. }
  55277. MenuBarModel* MenuBarComponent::getModel() const throw()
  55278. {
  55279. return model;
  55280. }
  55281. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  55282. {
  55283. if (model != newModel)
  55284. {
  55285. if (model != 0)
  55286. model->removeListener (this);
  55287. model = newModel;
  55288. if (model != 0)
  55289. model->addListener (this);
  55290. repaint();
  55291. menuBarItemsChanged (0);
  55292. }
  55293. }
  55294. void MenuBarComponent::paint (Graphics& g)
  55295. {
  55296. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  55297. getLookAndFeel().drawMenuBarBackground (g,
  55298. getWidth(),
  55299. getHeight(),
  55300. isMouseOverBar,
  55301. *this);
  55302. if (model != 0)
  55303. {
  55304. for (int i = 0; i < menuNames.size(); ++i)
  55305. {
  55306. g.saveState();
  55307. g.setOrigin (xPositions [i], 0);
  55308. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  55309. getLookAndFeel().drawMenuBarItem (g,
  55310. xPositions[i + 1] - xPositions[i],
  55311. getHeight(),
  55312. i,
  55313. menuNames[i],
  55314. i == itemUnderMouse,
  55315. i == currentPopupIndex,
  55316. isMouseOverBar,
  55317. *this);
  55318. g.restoreState();
  55319. }
  55320. }
  55321. }
  55322. void MenuBarComponent::resized()
  55323. {
  55324. xPositions.clear();
  55325. int x = 0;
  55326. xPositions.add (x);
  55327. for (int i = 0; i < menuNames.size(); ++i)
  55328. {
  55329. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  55330. xPositions.add (x);
  55331. }
  55332. }
  55333. int MenuBarComponent::getItemAt (const int x, const int y)
  55334. {
  55335. for (int i = 0; i < xPositions.size(); ++i)
  55336. if (x >= xPositions[i] && x < xPositions[i + 1])
  55337. return reallyContains (x, y, true) ? i : -1;
  55338. return -1;
  55339. }
  55340. void MenuBarComponent::repaintMenuItem (int index)
  55341. {
  55342. if (((unsigned int) index) < (unsigned int) xPositions.size())
  55343. {
  55344. const int x1 = xPositions [index];
  55345. const int x2 = xPositions [index + 1];
  55346. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  55347. }
  55348. }
  55349. void MenuBarComponent::setItemUnderMouse (const int index)
  55350. {
  55351. if (itemUnderMouse != index)
  55352. {
  55353. repaintMenuItem (itemUnderMouse);
  55354. itemUnderMouse = index;
  55355. repaintMenuItem (itemUnderMouse);
  55356. }
  55357. }
  55358. void MenuBarComponent::setOpenItem (int index)
  55359. {
  55360. if (currentPopupIndex != index)
  55361. {
  55362. repaintMenuItem (currentPopupIndex);
  55363. currentPopupIndex = index;
  55364. repaintMenuItem (currentPopupIndex);
  55365. if (index >= 0)
  55366. Desktop::getInstance().addGlobalMouseListener (this);
  55367. else
  55368. Desktop::getInstance().removeGlobalMouseListener (this);
  55369. }
  55370. }
  55371. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  55372. {
  55373. setItemUnderMouse (getItemAt (x, y));
  55374. }
  55375. class MenuBarComponent::AsyncCallback : public ModalComponentManager::Callback
  55376. {
  55377. public:
  55378. AsyncCallback (MenuBarComponent* const bar_, const int topLevelIndex_)
  55379. : bar (bar_), topLevelIndex (topLevelIndex_)
  55380. {
  55381. }
  55382. ~AsyncCallback() {}
  55383. void modalStateFinished (int returnValue)
  55384. {
  55385. if (bar != 0)
  55386. bar->menuDismissed (topLevelIndex, returnValue);
  55387. }
  55388. private:
  55389. Component::SafePointer<MenuBarComponent> bar;
  55390. const int topLevelIndex;
  55391. AsyncCallback (const AsyncCallback&);
  55392. AsyncCallback& operator= (const AsyncCallback&);
  55393. };
  55394. void MenuBarComponent::showMenu (int index)
  55395. {
  55396. if (index != currentPopupIndex)
  55397. {
  55398. PopupMenu::dismissAllActiveMenus();
  55399. menuBarItemsChanged (0);
  55400. setOpenItem (index);
  55401. setItemUnderMouse (index);
  55402. if (index >= 0)
  55403. {
  55404. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  55405. menuNames [itemUnderMouse]));
  55406. if (m.lookAndFeel == 0)
  55407. m.setLookAndFeel (&getLookAndFeel());
  55408. const Rectangle<int> itemPos (xPositions [index], 0, xPositions [index + 1] - xPositions [index], getHeight());
  55409. m.showMenu (itemPos + getScreenPosition(),
  55410. 0, itemPos.getWidth(), 0, 0, true, this,
  55411. new AsyncCallback (this, index));
  55412. }
  55413. }
  55414. }
  55415. void MenuBarComponent::menuDismissed (int topLevelIndex, int itemId)
  55416. {
  55417. topLevelIndexClicked = topLevelIndex;
  55418. postCommandMessage (itemId);
  55419. }
  55420. void MenuBarComponent::handleCommandMessage (int commandId)
  55421. {
  55422. const Point<int> mousePos (getMouseXYRelative());
  55423. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55424. if (currentPopupIndex == topLevelIndexClicked)
  55425. setOpenItem (-1);
  55426. if (commandId != 0 && model != 0)
  55427. model->menuItemSelected (commandId, topLevelIndexClicked);
  55428. }
  55429. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  55430. {
  55431. if (e.eventComponent == this)
  55432. updateItemUnderMouse (e.x, e.y);
  55433. }
  55434. void MenuBarComponent::mouseExit (const MouseEvent& e)
  55435. {
  55436. if (e.eventComponent == this)
  55437. updateItemUnderMouse (e.x, e.y);
  55438. }
  55439. void MenuBarComponent::mouseDown (const MouseEvent& e)
  55440. {
  55441. if (currentPopupIndex < 0)
  55442. {
  55443. const MouseEvent e2 (e.getEventRelativeTo (this));
  55444. updateItemUnderMouse (e2.x, e2.y);
  55445. currentPopupIndex = -2;
  55446. showMenu (itemUnderMouse);
  55447. }
  55448. }
  55449. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  55450. {
  55451. const MouseEvent e2 (e.getEventRelativeTo (this));
  55452. const int item = getItemAt (e2.x, e2.y);
  55453. if (item >= 0)
  55454. showMenu (item);
  55455. }
  55456. void MenuBarComponent::mouseUp (const MouseEvent& e)
  55457. {
  55458. const MouseEvent e2 (e.getEventRelativeTo (this));
  55459. updateItemUnderMouse (e2.x, e2.y);
  55460. if (itemUnderMouse < 0 && getLocalBounds().contains (e2.x, e2.y))
  55461. {
  55462. setOpenItem (-1);
  55463. PopupMenu::dismissAllActiveMenus();
  55464. }
  55465. }
  55466. void MenuBarComponent::mouseMove (const MouseEvent& e)
  55467. {
  55468. const MouseEvent e2 (e.getEventRelativeTo (this));
  55469. if (lastMouseX != e2.x || lastMouseY != e2.y)
  55470. {
  55471. if (currentPopupIndex >= 0)
  55472. {
  55473. const int item = getItemAt (e2.x, e2.y);
  55474. if (item >= 0)
  55475. showMenu (item);
  55476. }
  55477. else
  55478. {
  55479. updateItemUnderMouse (e2.x, e2.y);
  55480. }
  55481. lastMouseX = e2.x;
  55482. lastMouseY = e2.y;
  55483. }
  55484. }
  55485. bool MenuBarComponent::keyPressed (const KeyPress& key)
  55486. {
  55487. bool used = false;
  55488. const int numMenus = menuNames.size();
  55489. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  55490. if (key.isKeyCode (KeyPress::leftKey))
  55491. {
  55492. showMenu ((currentIndex + numMenus - 1) % numMenus);
  55493. used = true;
  55494. }
  55495. else if (key.isKeyCode (KeyPress::rightKey))
  55496. {
  55497. showMenu ((currentIndex + 1) % numMenus);
  55498. used = true;
  55499. }
  55500. return used;
  55501. }
  55502. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  55503. {
  55504. StringArray newNames;
  55505. if (model != 0)
  55506. newNames = model->getMenuBarNames();
  55507. if (newNames != menuNames)
  55508. {
  55509. menuNames = newNames;
  55510. repaint();
  55511. resized();
  55512. }
  55513. }
  55514. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  55515. const ApplicationCommandTarget::InvocationInfo& info)
  55516. {
  55517. if (model == 0 || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  55518. return;
  55519. for (int i = 0; i < menuNames.size(); ++i)
  55520. {
  55521. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  55522. if (menu.containsCommandItem (info.commandID))
  55523. {
  55524. setItemUnderMouse (i);
  55525. startTimer (200);
  55526. break;
  55527. }
  55528. }
  55529. }
  55530. void MenuBarComponent::timerCallback()
  55531. {
  55532. stopTimer();
  55533. const Point<int> mousePos (getMouseXYRelative());
  55534. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55535. }
  55536. END_JUCE_NAMESPACE
  55537. /*** End of inlined file: juce_MenuBarComponent.cpp ***/
  55538. /*** Start of inlined file: juce_MenuBarModel.cpp ***/
  55539. BEGIN_JUCE_NAMESPACE
  55540. MenuBarModel::MenuBarModel() throw()
  55541. : manager (0)
  55542. {
  55543. }
  55544. MenuBarModel::~MenuBarModel()
  55545. {
  55546. setApplicationCommandManagerToWatch (0);
  55547. }
  55548. void MenuBarModel::menuItemsChanged()
  55549. {
  55550. triggerAsyncUpdate();
  55551. }
  55552. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  55553. {
  55554. if (manager != newManager)
  55555. {
  55556. if (manager != 0)
  55557. manager->removeListener (this);
  55558. manager = newManager;
  55559. if (manager != 0)
  55560. manager->addListener (this);
  55561. }
  55562. }
  55563. void MenuBarModel::addListener (Listener* const newListener) throw()
  55564. {
  55565. listeners.add (newListener);
  55566. }
  55567. void MenuBarModel::removeListener (Listener* const listenerToRemove) throw()
  55568. {
  55569. // Trying to remove a listener that isn't on the list!
  55570. // If this assertion happens because this object is a dangling pointer, make sure you've not
  55571. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  55572. jassert (listeners.contains (listenerToRemove));
  55573. listeners.remove (listenerToRemove);
  55574. }
  55575. void MenuBarModel::handleAsyncUpdate()
  55576. {
  55577. listeners.call (&MenuBarModel::Listener::menuBarItemsChanged, this);
  55578. }
  55579. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  55580. {
  55581. listeners.call (&MenuBarModel::Listener::menuCommandInvoked, this, info);
  55582. }
  55583. void MenuBarModel::applicationCommandListChanged()
  55584. {
  55585. menuItemsChanged();
  55586. }
  55587. END_JUCE_NAMESPACE
  55588. /*** End of inlined file: juce_MenuBarModel.cpp ***/
  55589. /*** Start of inlined file: juce_PopupMenu.cpp ***/
  55590. BEGIN_JUCE_NAMESPACE
  55591. class PopupMenu::Item
  55592. {
  55593. public:
  55594. Item()
  55595. : itemId (0), active (true), isSeparator (true), isTicked (false),
  55596. usesColour (false), customComp (0), commandManager (0)
  55597. {
  55598. }
  55599. Item (const int itemId_,
  55600. const String& text_,
  55601. const bool active_,
  55602. const bool isTicked_,
  55603. const Image& im,
  55604. const Colour& textColour_,
  55605. const bool usesColour_,
  55606. PopupMenuCustomComponent* const customComp_,
  55607. const PopupMenu* const subMenu_,
  55608. ApplicationCommandManager* const commandManager_)
  55609. : itemId (itemId_), text (text_), textColour (textColour_),
  55610. active (active_), isSeparator (false), isTicked (isTicked_),
  55611. usesColour (usesColour_), image (im), customComp (customComp_),
  55612. commandManager (commandManager_)
  55613. {
  55614. if (subMenu_ != 0)
  55615. subMenu = new PopupMenu (*subMenu_);
  55616. if (commandManager_ != 0 && itemId_ != 0)
  55617. {
  55618. String shortcutKey;
  55619. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  55620. ->getKeyPressesAssignedToCommand (itemId_));
  55621. for (int i = 0; i < keyPresses.size(); ++i)
  55622. {
  55623. const String key (keyPresses.getReference(i).getTextDescription());
  55624. if (shortcutKey.isNotEmpty())
  55625. shortcutKey << ", ";
  55626. if (key.length() == 1)
  55627. shortcutKey << "shortcut: '" << key << '\'';
  55628. else
  55629. shortcutKey << key;
  55630. }
  55631. shortcutKey = shortcutKey.trim();
  55632. if (shortcutKey.isNotEmpty())
  55633. text << "<end>" << shortcutKey;
  55634. }
  55635. }
  55636. Item (const Item& other)
  55637. : itemId (other.itemId),
  55638. text (other.text),
  55639. textColour (other.textColour),
  55640. active (other.active),
  55641. isSeparator (other.isSeparator),
  55642. isTicked (other.isTicked),
  55643. usesColour (other.usesColour),
  55644. image (other.image),
  55645. customComp (other.customComp),
  55646. commandManager (other.commandManager)
  55647. {
  55648. if (other.subMenu != 0)
  55649. subMenu = new PopupMenu (*(other.subMenu));
  55650. }
  55651. ~Item()
  55652. {
  55653. customComp = 0;
  55654. }
  55655. bool canBeTriggered() const throw()
  55656. {
  55657. return active && ! (isSeparator || (subMenu != 0));
  55658. }
  55659. bool hasActiveSubMenu() const throw()
  55660. {
  55661. return active && (subMenu != 0);
  55662. }
  55663. const int itemId;
  55664. String text;
  55665. const Colour textColour;
  55666. const bool active, isSeparator, isTicked, usesColour;
  55667. Image image;
  55668. ReferenceCountedObjectPtr <PopupMenuCustomComponent> customComp;
  55669. ScopedPointer <PopupMenu> subMenu;
  55670. ApplicationCommandManager* const commandManager;
  55671. juce_UseDebuggingNewOperator
  55672. private:
  55673. Item& operator= (const Item&);
  55674. };
  55675. class PopupMenu::ItemComponent : public Component
  55676. {
  55677. public:
  55678. ItemComponent (const PopupMenu::Item& itemInfo_)
  55679. : itemInfo (itemInfo_),
  55680. isHighlighted (false)
  55681. {
  55682. if (itemInfo.customComp != 0)
  55683. addAndMakeVisible (itemInfo.customComp);
  55684. }
  55685. ~ItemComponent()
  55686. {
  55687. if (itemInfo.customComp != 0)
  55688. removeChildComponent (itemInfo.customComp);
  55689. }
  55690. void getIdealSize (int& idealWidth,
  55691. int& idealHeight,
  55692. const int standardItemHeight)
  55693. {
  55694. if (itemInfo.customComp != 0)
  55695. {
  55696. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  55697. }
  55698. else
  55699. {
  55700. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  55701. itemInfo.isSeparator,
  55702. standardItemHeight,
  55703. idealWidth,
  55704. idealHeight);
  55705. }
  55706. }
  55707. void paint (Graphics& g)
  55708. {
  55709. if (itemInfo.customComp == 0)
  55710. {
  55711. String mainText (itemInfo.text);
  55712. String endText;
  55713. const int endIndex = mainText.indexOf ("<end>");
  55714. if (endIndex >= 0)
  55715. {
  55716. endText = mainText.substring (endIndex + 5).trim();
  55717. mainText = mainText.substring (0, endIndex);
  55718. }
  55719. getLookAndFeel()
  55720. .drawPopupMenuItem (g, getWidth(), getHeight(),
  55721. itemInfo.isSeparator,
  55722. itemInfo.active,
  55723. isHighlighted,
  55724. itemInfo.isTicked,
  55725. itemInfo.subMenu != 0,
  55726. mainText, endText,
  55727. itemInfo.image.isValid() ? &itemInfo.image : 0,
  55728. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  55729. }
  55730. }
  55731. void resized()
  55732. {
  55733. if (getNumChildComponents() > 0)
  55734. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  55735. }
  55736. void setHighlighted (bool shouldBeHighlighted)
  55737. {
  55738. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  55739. if (isHighlighted != shouldBeHighlighted)
  55740. {
  55741. isHighlighted = shouldBeHighlighted;
  55742. if (itemInfo.customComp != 0)
  55743. {
  55744. itemInfo.customComp->isHighlighted = shouldBeHighlighted;
  55745. itemInfo.customComp->repaint();
  55746. }
  55747. repaint();
  55748. }
  55749. }
  55750. PopupMenu::Item itemInfo;
  55751. juce_UseDebuggingNewOperator
  55752. private:
  55753. bool isHighlighted;
  55754. ItemComponent (const ItemComponent&);
  55755. ItemComponent& operator= (const ItemComponent&);
  55756. };
  55757. namespace PopupMenuSettings
  55758. {
  55759. static const int scrollZone = 24;
  55760. static const int borderSize = 2;
  55761. static const int timerInterval = 50;
  55762. static const int dismissCommandId = 0x6287345f;
  55763. }
  55764. class PopupMenu::Window : public Component,
  55765. private Timer
  55766. {
  55767. public:
  55768. Window()
  55769. : Component ("menu"),
  55770. owner (0),
  55771. currentChild (0),
  55772. activeSubMenu (0),
  55773. managerOfChosenCommand (0),
  55774. minimumWidth (0),
  55775. maximumNumColumns (7),
  55776. standardItemHeight (0),
  55777. isOver (false),
  55778. hasBeenOver (false),
  55779. isDown (false),
  55780. needsToScroll (false),
  55781. hideOnExit (false),
  55782. disableMouseMoves (false),
  55783. hasAnyJuceCompHadFocus (false),
  55784. numColumns (0),
  55785. contentHeight (0),
  55786. childYOffset (0),
  55787. timeEnteredCurrentChildComp (0),
  55788. scrollAcceleration (1.0)
  55789. {
  55790. menuCreationTime = lastFocused = lastScroll = Time::getMillisecondCounter();
  55791. setWantsKeyboardFocus (true);
  55792. setMouseClickGrabsKeyboardFocus (false);
  55793. setAlwaysOnTop (true);
  55794. Desktop::getInstance().addGlobalMouseListener (this);
  55795. getActiveWindows().add (this);
  55796. }
  55797. ~Window()
  55798. {
  55799. getActiveWindows().removeValue (this);
  55800. Desktop::getInstance().removeGlobalMouseListener (this);
  55801. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55802. activeSubMenu = 0;
  55803. deleteAllChildren();
  55804. }
  55805. static Window* create (const PopupMenu& menu,
  55806. const bool dismissOnMouseUp,
  55807. Window* const owner_,
  55808. const Rectangle<int>& target,
  55809. const int minimumWidth,
  55810. const int maximumNumColumns,
  55811. const int standardItemHeight,
  55812. const bool alignToRectangle,
  55813. const int itemIdThatMustBeVisible,
  55814. ApplicationCommandManager** managerOfChosenCommand,
  55815. Component* const componentAttachedTo)
  55816. {
  55817. if (menu.items.size() > 0)
  55818. {
  55819. int totalItems = 0;
  55820. ScopedPointer <Window> mw (new Window());
  55821. mw->setLookAndFeel (menu.lookAndFeel);
  55822. mw->setWantsKeyboardFocus (false);
  55823. mw->setOpaque (mw->getLookAndFeel().findColour (PopupMenu::backgroundColourId).isOpaque() || ! Desktop::canUseSemiTransparentWindows());
  55824. mw->minimumWidth = minimumWidth;
  55825. mw->maximumNumColumns = maximumNumColumns;
  55826. mw->standardItemHeight = standardItemHeight;
  55827. mw->dismissOnMouseUp = dismissOnMouseUp;
  55828. for (int i = 0; i < menu.items.size(); ++i)
  55829. {
  55830. PopupMenu::Item* const item = menu.items.getUnchecked(i);
  55831. mw->addItem (*item);
  55832. ++totalItems;
  55833. }
  55834. if (totalItems > 0)
  55835. {
  55836. mw->owner = owner_;
  55837. mw->managerOfChosenCommand = managerOfChosenCommand;
  55838. mw->componentAttachedTo = componentAttachedTo;
  55839. mw->componentAttachedToOriginal = componentAttachedTo;
  55840. mw->calculateWindowPos (target, alignToRectangle);
  55841. mw->setTopLeftPosition (mw->windowPos.getX(),
  55842. mw->windowPos.getY());
  55843. mw->updateYPositions();
  55844. if (itemIdThatMustBeVisible != 0)
  55845. {
  55846. const int y = target.getY() - mw->windowPos.getY();
  55847. mw->ensureItemIsVisible (itemIdThatMustBeVisible,
  55848. (((unsigned int) y) < (unsigned int) mw->windowPos.getHeight()) ? y : -1);
  55849. }
  55850. mw->resizeToBestWindowPos();
  55851. mw->addToDesktop (ComponentPeer::windowIsTemporary
  55852. | mw->getLookAndFeel().getMenuWindowFlags());
  55853. return mw.release();
  55854. }
  55855. }
  55856. return 0;
  55857. }
  55858. void paint (Graphics& g)
  55859. {
  55860. if (isOpaque())
  55861. g.fillAll (Colours::white);
  55862. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  55863. }
  55864. void paintOverChildren (Graphics& g)
  55865. {
  55866. if (isScrolling())
  55867. {
  55868. LookAndFeel& lf = getLookAndFeel();
  55869. if (isScrollZoneActive (false))
  55870. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, true);
  55871. if (isScrollZoneActive (true))
  55872. {
  55873. g.setOrigin (0, getHeight() - PopupMenuSettings::scrollZone);
  55874. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, false);
  55875. }
  55876. }
  55877. }
  55878. bool isScrollZoneActive (bool bottomOne) const
  55879. {
  55880. return isScrolling()
  55881. && (bottomOne
  55882. ? childYOffset < contentHeight - windowPos.getHeight()
  55883. : childYOffset > 0);
  55884. }
  55885. void addItem (const PopupMenu::Item& item)
  55886. {
  55887. PopupMenu::ItemComponent* const mic = new PopupMenu::ItemComponent (item);
  55888. addAndMakeVisible (mic);
  55889. int itemW = 80;
  55890. int itemH = 16;
  55891. mic->getIdealSize (itemW, itemH, standardItemHeight);
  55892. mic->setSize (itemW, jlimit (2, 600, itemH));
  55893. mic->addMouseListener (this, false);
  55894. }
  55895. // hide this and all sub-comps
  55896. void hide (const PopupMenu::Item* const item)
  55897. {
  55898. if (isVisible())
  55899. {
  55900. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55901. activeSubMenu = 0;
  55902. currentChild = 0;
  55903. exitModalState (item != 0 ? item->itemId : 0);
  55904. setVisible (false);
  55905. if (item != 0
  55906. && item->commandManager != 0
  55907. && item->itemId != 0)
  55908. {
  55909. *managerOfChosenCommand = item->commandManager;
  55910. }
  55911. }
  55912. }
  55913. void dismissMenu (const PopupMenu::Item* const item)
  55914. {
  55915. if (owner != 0)
  55916. {
  55917. owner->dismissMenu (item);
  55918. }
  55919. else
  55920. {
  55921. if (item != 0)
  55922. {
  55923. // need a copy of this on the stack as the one passed in will get deleted during this call
  55924. const PopupMenu::Item mi (*item);
  55925. hide (&mi);
  55926. }
  55927. else
  55928. {
  55929. hide (0);
  55930. }
  55931. }
  55932. }
  55933. void mouseMove (const MouseEvent&)
  55934. {
  55935. timerCallback();
  55936. }
  55937. void mouseDown (const MouseEvent&)
  55938. {
  55939. timerCallback();
  55940. }
  55941. void mouseDrag (const MouseEvent&)
  55942. {
  55943. timerCallback();
  55944. }
  55945. void mouseUp (const MouseEvent&)
  55946. {
  55947. timerCallback();
  55948. }
  55949. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  55950. {
  55951. alterChildYPos (roundToInt (-10.0f * amountY * PopupMenuSettings::scrollZone));
  55952. lastMouse = Point<int> (-1, -1);
  55953. }
  55954. bool keyPressed (const KeyPress& key)
  55955. {
  55956. if (key.isKeyCode (KeyPress::downKey))
  55957. {
  55958. selectNextItem (1);
  55959. }
  55960. else if (key.isKeyCode (KeyPress::upKey))
  55961. {
  55962. selectNextItem (-1);
  55963. }
  55964. else if (key.isKeyCode (KeyPress::leftKey))
  55965. {
  55966. if (owner != 0)
  55967. {
  55968. Component::SafePointer<Window> parentWindow (owner);
  55969. PopupMenu::ItemComponent* currentChildOfParent = parentWindow->currentChild;
  55970. hide (0);
  55971. if (parentWindow != 0)
  55972. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  55973. disableTimerUntilMouseMoves();
  55974. }
  55975. else if (componentAttachedTo != 0)
  55976. {
  55977. componentAttachedTo->keyPressed (key);
  55978. }
  55979. }
  55980. else if (key.isKeyCode (KeyPress::rightKey))
  55981. {
  55982. disableTimerUntilMouseMoves();
  55983. if (showSubMenuFor (currentChild))
  55984. {
  55985. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55986. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  55987. activeSubMenu->selectNextItem (1);
  55988. }
  55989. else if (componentAttachedTo != 0)
  55990. {
  55991. componentAttachedTo->keyPressed (key);
  55992. }
  55993. }
  55994. else if (key.isKeyCode (KeyPress::returnKey))
  55995. {
  55996. triggerCurrentlyHighlightedItem();
  55997. }
  55998. else if (key.isKeyCode (KeyPress::escapeKey))
  55999. {
  56000. dismissMenu (0);
  56001. }
  56002. else
  56003. {
  56004. return false;
  56005. }
  56006. return true;
  56007. }
  56008. void inputAttemptWhenModal()
  56009. {
  56010. Component::SafePointer<Component> deletionChecker (this);
  56011. timerCallback();
  56012. if (deletionChecker != 0 && ! isOverAnyMenu())
  56013. {
  56014. if (componentAttachedTo != 0)
  56015. {
  56016. // we want to dismiss the menu, but if we do it synchronously, then
  56017. // the mouse-click will be allowed to pass through. That's good, except
  56018. // when the user clicks on the button that orginally popped the menu up,
  56019. // as they'll expect the menu to go away, and in fact it'll just
  56020. // come back. So only dismiss synchronously if they're not on the original
  56021. // comp that we're attached to.
  56022. const Point<int> mousePos (componentAttachedTo->getMouseXYRelative());
  56023. if (componentAttachedTo->reallyContains (mousePos.getX(), mousePos.getY(), true))
  56024. {
  56025. postCommandMessage (PopupMenuSettings::dismissCommandId); // dismiss asynchrounously
  56026. return;
  56027. }
  56028. }
  56029. dismissMenu (0);
  56030. }
  56031. }
  56032. void handleCommandMessage (int commandId)
  56033. {
  56034. Component::handleCommandMessage (commandId);
  56035. if (commandId == PopupMenuSettings::dismissCommandId)
  56036. dismissMenu (0);
  56037. }
  56038. void timerCallback()
  56039. {
  56040. if (! isVisible())
  56041. return;
  56042. if (componentAttachedTo != componentAttachedToOriginal)
  56043. {
  56044. dismissMenu (0);
  56045. return;
  56046. }
  56047. Window* currentlyModalWindow = dynamic_cast <Window*> (Component::getCurrentlyModalComponent());
  56048. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  56049. return;
  56050. startTimer (PopupMenuSettings::timerInterval); // do this in case it was called from a mouse
  56051. // move rather than a real timer callback
  56052. const Point<int> globalMousePos (Desktop::getMousePosition());
  56053. const Point<int> localMousePos (globalPositionToRelative (globalMousePos));
  56054. const uint32 now = Time::getMillisecondCounter();
  56055. if (now > timeEnteredCurrentChildComp + 100
  56056. && reallyContains (localMousePos.getX(), localMousePos.getY(), true)
  56057. && currentChild->isValidComponent()
  56058. && (! disableMouseMoves)
  56059. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  56060. {
  56061. showSubMenuFor (currentChild);
  56062. }
  56063. if (globalMousePos != lastMouse || now > lastMouseMoveTime + 350)
  56064. {
  56065. highlightItemUnderMouse (globalMousePos, localMousePos);
  56066. }
  56067. bool overScrollArea = false;
  56068. if (isScrolling()
  56069. && (isOver || (isDown && ((unsigned int) localMousePos.getX()) < (unsigned int) getWidth()))
  56070. && ((isScrollZoneActive (false) && localMousePos.getY() < PopupMenuSettings::scrollZone)
  56071. || (isScrollZoneActive (true) && localMousePos.getY() > getHeight() - PopupMenuSettings::scrollZone)))
  56072. {
  56073. if (now > lastScroll + 20)
  56074. {
  56075. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  56076. int amount = 0;
  56077. for (int i = 0; i < getNumChildComponents() && amount == 0; ++i)
  56078. amount = ((int) scrollAcceleration) * getChildComponent (i)->getHeight();
  56079. alterChildYPos (localMousePos.getY() < PopupMenuSettings::scrollZone ? -amount : amount);
  56080. lastScroll = now;
  56081. }
  56082. overScrollArea = true;
  56083. lastMouse = Point<int> (-1, -1); // trigger a mouse-move
  56084. }
  56085. else
  56086. {
  56087. scrollAcceleration = 1.0;
  56088. }
  56089. const bool wasDown = isDown;
  56090. bool isOverAny = isOverAnyMenu();
  56091. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  56092. {
  56093. activeSubMenu->updateMouseOverStatus (globalMousePos);
  56094. isOverAny = isOverAnyMenu();
  56095. }
  56096. if (hideOnExit && hasBeenOver && ! isOverAny)
  56097. {
  56098. hide (0);
  56099. }
  56100. else
  56101. {
  56102. isDown = hasBeenOver
  56103. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  56104. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  56105. bool anyFocused = Process::isForegroundProcess();
  56106. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  56107. {
  56108. // because no component at all may have focus, our test here will
  56109. // only be triggered when something has focus and then loses it.
  56110. anyFocused = ! hasAnyJuceCompHadFocus;
  56111. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  56112. {
  56113. if (ComponentPeer::getPeer (i)->isFocused())
  56114. {
  56115. anyFocused = true;
  56116. hasAnyJuceCompHadFocus = true;
  56117. break;
  56118. }
  56119. }
  56120. }
  56121. if (! anyFocused)
  56122. {
  56123. if (now > lastFocused + 10)
  56124. {
  56125. wasHiddenBecauseOfAppChange() = true;
  56126. dismissMenu (0);
  56127. return; // may have been deleted by the previous call..
  56128. }
  56129. }
  56130. else if (wasDown && now > menuCreationTime + 250
  56131. && ! (isDown || overScrollArea))
  56132. {
  56133. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  56134. if (isOver)
  56135. {
  56136. triggerCurrentlyHighlightedItem();
  56137. }
  56138. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  56139. {
  56140. dismissMenu (0);
  56141. }
  56142. return; // may have been deleted by the previous calls..
  56143. }
  56144. else
  56145. {
  56146. lastFocused = now;
  56147. }
  56148. }
  56149. }
  56150. static Array<Window*>& getActiveWindows()
  56151. {
  56152. static Array<Window*> activeMenuWindows;
  56153. return activeMenuWindows;
  56154. }
  56155. static bool& wasHiddenBecauseOfAppChange() throw()
  56156. {
  56157. static bool b = false;
  56158. return b;
  56159. }
  56160. juce_UseDebuggingNewOperator
  56161. private:
  56162. Window* owner;
  56163. PopupMenu::ItemComponent* currentChild;
  56164. ScopedPointer <Window> activeSubMenu;
  56165. ApplicationCommandManager** managerOfChosenCommand;
  56166. Component::SafePointer<Component> componentAttachedTo;
  56167. Component* componentAttachedToOriginal;
  56168. Rectangle<int> windowPos;
  56169. Point<int> lastMouse;
  56170. int minimumWidth, maximumNumColumns, standardItemHeight;
  56171. bool isOver, hasBeenOver, isDown, needsToScroll;
  56172. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  56173. int numColumns, contentHeight, childYOffset;
  56174. Array <int> columnWidths;
  56175. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  56176. double scrollAcceleration;
  56177. bool overlaps (const Rectangle<int>& r) const
  56178. {
  56179. return r.intersects (getBounds())
  56180. || (owner != 0 && owner->overlaps (r));
  56181. }
  56182. bool isOverAnyMenu() const
  56183. {
  56184. return (owner != 0) ? owner->isOverAnyMenu()
  56185. : isOverChildren();
  56186. }
  56187. bool isOverChildren() const
  56188. {
  56189. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  56190. return isVisible()
  56191. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  56192. }
  56193. void updateMouseOverStatus (const Point<int>& globalMousePos)
  56194. {
  56195. const Point<int> relPos (globalPositionToRelative (globalMousePos));
  56196. isOver = reallyContains (relPos.getX(), relPos.getY(), true);
  56197. if (activeSubMenu != 0)
  56198. activeSubMenu->updateMouseOverStatus (globalMousePos);
  56199. }
  56200. bool treeContains (const Window* const window) const throw()
  56201. {
  56202. const Window* mw = this;
  56203. while (mw->owner != 0)
  56204. mw = mw->owner;
  56205. while (mw != 0)
  56206. {
  56207. if (mw == window)
  56208. return true;
  56209. mw = mw->activeSubMenu;
  56210. }
  56211. return false;
  56212. }
  56213. void calculateWindowPos (const Rectangle<int>& target, const bool alignToRectangle)
  56214. {
  56215. const Rectangle<int> mon (Desktop::getInstance()
  56216. .getMonitorAreaContaining (target.getCentre(),
  56217. #if JUCE_MAC
  56218. true));
  56219. #else
  56220. false)); // on windows, don't stop the menu overlapping the taskbar
  56221. #endif
  56222. int x, y, widthToUse, heightToUse;
  56223. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  56224. if (alignToRectangle)
  56225. {
  56226. x = target.getX();
  56227. const int spaceUnder = mon.getHeight() - (target.getBottom() - mon.getY());
  56228. const int spaceOver = target.getY() - mon.getY();
  56229. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  56230. y = target.getBottom();
  56231. else
  56232. y = target.getY() - heightToUse;
  56233. }
  56234. else
  56235. {
  56236. bool tendTowardsRight = target.getCentreX() < mon.getCentreX();
  56237. if (owner != 0)
  56238. {
  56239. if (owner->owner != 0)
  56240. {
  56241. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  56242. > owner->owner->getX() + owner->owner->getWidth() / 2);
  56243. if (ownerGoingRight && target.getRight() + widthToUse < mon.getRight() - 4)
  56244. tendTowardsRight = true;
  56245. else if ((! ownerGoingRight) && target.getX() > widthToUse + 4)
  56246. tendTowardsRight = false;
  56247. }
  56248. else if (target.getRight() + widthToUse < mon.getRight() - 32)
  56249. {
  56250. tendTowardsRight = true;
  56251. }
  56252. }
  56253. const int biggestSpace = jmax (mon.getRight() - target.getRight(),
  56254. target.getX() - mon.getX()) - 32;
  56255. if (biggestSpace < widthToUse)
  56256. {
  56257. layoutMenuItems (biggestSpace + target.getWidth() / 3, widthToUse, heightToUse);
  56258. if (numColumns > 1)
  56259. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  56260. tendTowardsRight = (mon.getRight() - target.getRight()) >= (target.getX() - mon.getX());
  56261. }
  56262. if (tendTowardsRight)
  56263. x = jmin (mon.getRight() - widthToUse - 4, target.getRight());
  56264. else
  56265. x = jmax (mon.getX() + 4, target.getX() - widthToUse);
  56266. y = target.getY();
  56267. if (target.getCentreY() > mon.getCentreY())
  56268. y = jmax (mon.getY(), target.getBottom() - heightToUse);
  56269. }
  56270. x = jmax (mon.getX() + 1, jmin (mon.getRight() - (widthToUse + 6), x));
  56271. y = jmax (mon.getY() + 1, jmin (mon.getBottom() - (heightToUse + 6), y));
  56272. windowPos.setBounds (x, y, widthToUse, heightToUse);
  56273. // sets this flag if it's big enough to obscure any of its parent menus
  56274. hideOnExit = (owner != 0)
  56275. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  56276. }
  56277. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  56278. {
  56279. numColumns = 0;
  56280. contentHeight = 0;
  56281. const int maxMenuH = getParentHeight() - 24;
  56282. int totalW;
  56283. do
  56284. {
  56285. ++numColumns;
  56286. totalW = workOutBestSize (maxMenuW);
  56287. if (totalW > maxMenuW)
  56288. {
  56289. numColumns = jmax (1, numColumns - 1);
  56290. totalW = workOutBestSize (maxMenuW); // to update col widths
  56291. break;
  56292. }
  56293. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  56294. {
  56295. break;
  56296. }
  56297. } while (numColumns < maximumNumColumns);
  56298. const int actualH = jmin (contentHeight, maxMenuH);
  56299. needsToScroll = contentHeight > actualH;
  56300. width = updateYPositions();
  56301. height = actualH + PopupMenuSettings::borderSize * 2;
  56302. }
  56303. int workOutBestSize (const int maxMenuW)
  56304. {
  56305. int totalW = 0;
  56306. contentHeight = 0;
  56307. int childNum = 0;
  56308. for (int col = 0; col < numColumns; ++col)
  56309. {
  56310. int i, colW = 50, colH = 0;
  56311. const int numChildren = jmin (getNumChildComponents() - childNum,
  56312. (getNumChildComponents() + numColumns - 1) / numColumns);
  56313. for (i = numChildren; --i >= 0;)
  56314. {
  56315. colW = jmax (colW, getChildComponent (childNum + i)->getWidth());
  56316. colH += getChildComponent (childNum + i)->getHeight();
  56317. }
  56318. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + PopupMenuSettings::borderSize * 2);
  56319. columnWidths.set (col, colW);
  56320. totalW += colW;
  56321. contentHeight = jmax (contentHeight, colH);
  56322. childNum += numChildren;
  56323. }
  56324. if (totalW < minimumWidth)
  56325. {
  56326. totalW = minimumWidth;
  56327. for (int col = 0; col < numColumns; ++col)
  56328. columnWidths.set (0, totalW / numColumns);
  56329. }
  56330. return totalW;
  56331. }
  56332. void ensureItemIsVisible (const int itemId, int wantedY)
  56333. {
  56334. jassert (itemId != 0)
  56335. for (int i = getNumChildComponents(); --i >= 0;)
  56336. {
  56337. PopupMenu::ItemComponent* const m = static_cast <PopupMenu::ItemComponent*> (getChildComponent (i));
  56338. if (m != 0
  56339. && m->itemInfo.itemId == itemId
  56340. && windowPos.getHeight() > PopupMenuSettings::scrollZone * 4)
  56341. {
  56342. const int currentY = m->getY();
  56343. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  56344. {
  56345. if (wantedY < 0)
  56346. wantedY = jlimit (PopupMenuSettings::scrollZone,
  56347. jmax (PopupMenuSettings::scrollZone,
  56348. windowPos.getHeight() - (PopupMenuSettings::scrollZone + m->getHeight())),
  56349. currentY);
  56350. const Rectangle<int> mon (Desktop::getInstance().getMonitorAreaContaining (windowPos.getPosition(), true));
  56351. int deltaY = wantedY - currentY;
  56352. windowPos.setSize (jmin (windowPos.getWidth(), mon.getWidth()),
  56353. jmin (windowPos.getHeight(), mon.getHeight()));
  56354. const int newY = jlimit (mon.getY(),
  56355. mon.getBottom() - windowPos.getHeight(),
  56356. windowPos.getY() + deltaY);
  56357. deltaY -= newY - windowPos.getY();
  56358. childYOffset -= deltaY;
  56359. windowPos.setPosition (windowPos.getX(), newY);
  56360. updateYPositions();
  56361. }
  56362. break;
  56363. }
  56364. }
  56365. }
  56366. void resizeToBestWindowPos()
  56367. {
  56368. Rectangle<int> r (windowPos);
  56369. if (childYOffset < 0)
  56370. {
  56371. r.setBounds (r.getX(), r.getY() - childYOffset,
  56372. r.getWidth(), r.getHeight() + childYOffset);
  56373. }
  56374. else if (childYOffset > 0)
  56375. {
  56376. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  56377. if (spaceAtBottom > 0)
  56378. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  56379. }
  56380. setBounds (r);
  56381. updateYPositions();
  56382. }
  56383. void alterChildYPos (const int delta)
  56384. {
  56385. if (isScrolling())
  56386. {
  56387. childYOffset += delta;
  56388. if (delta < 0)
  56389. {
  56390. childYOffset = jmax (childYOffset, 0);
  56391. }
  56392. else if (delta > 0)
  56393. {
  56394. childYOffset = jmin (childYOffset,
  56395. contentHeight - windowPos.getHeight() + PopupMenuSettings::borderSize);
  56396. }
  56397. updateYPositions();
  56398. }
  56399. else
  56400. {
  56401. childYOffset = 0;
  56402. }
  56403. resizeToBestWindowPos();
  56404. repaint();
  56405. }
  56406. int updateYPositions()
  56407. {
  56408. int x = 0;
  56409. int childNum = 0;
  56410. for (int col = 0; col < numColumns; ++col)
  56411. {
  56412. const int numChildren = jmin (getNumChildComponents() - childNum,
  56413. (getNumChildComponents() + numColumns - 1) / numColumns);
  56414. const int colW = columnWidths [col];
  56415. int y = PopupMenuSettings::borderSize - (childYOffset + (getY() - windowPos.getY()));
  56416. for (int i = 0; i < numChildren; ++i)
  56417. {
  56418. Component* const c = getChildComponent (childNum + i);
  56419. c->setBounds (x, y, colW, c->getHeight());
  56420. y += c->getHeight();
  56421. }
  56422. x += colW;
  56423. childNum += numChildren;
  56424. }
  56425. return x;
  56426. }
  56427. bool isScrolling() const throw()
  56428. {
  56429. return childYOffset != 0 || needsToScroll;
  56430. }
  56431. void setCurrentlyHighlightedChild (PopupMenu::ItemComponent* const child)
  56432. {
  56433. if (currentChild->isValidComponent())
  56434. currentChild->setHighlighted (false);
  56435. currentChild = child;
  56436. if (currentChild != 0)
  56437. {
  56438. currentChild->setHighlighted (true);
  56439. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  56440. }
  56441. }
  56442. bool showSubMenuFor (PopupMenu::ItemComponent* const childComp)
  56443. {
  56444. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  56445. activeSubMenu = 0;
  56446. if (childComp->isValidComponent() && childComp->itemInfo.hasActiveSubMenu())
  56447. {
  56448. activeSubMenu = Window::create (*(childComp->itemInfo.subMenu),
  56449. dismissOnMouseUp,
  56450. this,
  56451. childComp->getScreenBounds(),
  56452. 0, maximumNumColumns,
  56453. standardItemHeight,
  56454. false, 0, managerOfChosenCommand,
  56455. componentAttachedTo);
  56456. if (activeSubMenu != 0)
  56457. {
  56458. activeSubMenu->setVisible (true);
  56459. activeSubMenu->enterModalState (false);
  56460. activeSubMenu->toFront (false);
  56461. return true;
  56462. }
  56463. }
  56464. return false;
  56465. }
  56466. void highlightItemUnderMouse (const Point<int>& globalMousePos, const Point<int>& localMousePos)
  56467. {
  56468. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  56469. if (isOver)
  56470. hasBeenOver = true;
  56471. if (lastMouse.getDistanceFrom (globalMousePos) > 2)
  56472. {
  56473. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  56474. if (disableMouseMoves && isOver)
  56475. disableMouseMoves = false;
  56476. }
  56477. if (disableMouseMoves || (activeSubMenu != 0 && activeSubMenu->isOverChildren()))
  56478. return;
  56479. bool isMovingTowardsMenu = false;
  56480. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent())
  56481. if (isOver && (activeSubMenu != 0) && globalMousePos != lastMouse)
  56482. {
  56483. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  56484. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  56485. // extends from the last mouse pos to the submenu's rectangle..
  56486. float subX = (float) activeSubMenu->getScreenX();
  56487. if (activeSubMenu->getX() > getX())
  56488. {
  56489. lastMouse -= Point<int> (2, 0); // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  56490. }
  56491. else
  56492. {
  56493. lastMouse += Point<int> (2, 0);
  56494. subX += activeSubMenu->getWidth();
  56495. }
  56496. Path areaTowardsSubMenu;
  56497. areaTowardsSubMenu.addTriangle ((float) lastMouse.getX(),
  56498. (float) lastMouse.getY(),
  56499. subX,
  56500. (float) activeSubMenu->getScreenY(),
  56501. subX,
  56502. (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  56503. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) globalMousePos.getX(), (float) globalMousePos.getY());
  56504. }
  56505. lastMouse = globalMousePos;
  56506. if (! isMovingTowardsMenu)
  56507. {
  56508. Component* c = getComponentAt (localMousePos.getX(), localMousePos.getY());
  56509. if (c == this)
  56510. c = 0;
  56511. PopupMenu::ItemComponent* mic = dynamic_cast <PopupMenu::ItemComponent*> (c);
  56512. if (mic == 0 && c != 0)
  56513. mic = c->findParentComponentOfClass ((PopupMenu::ItemComponent*) 0);
  56514. if (mic != currentChild
  56515. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  56516. {
  56517. if (isOver && (c != 0) && (activeSubMenu != 0))
  56518. {
  56519. activeSubMenu->hide (0);
  56520. }
  56521. if (! isOver)
  56522. mic = 0;
  56523. setCurrentlyHighlightedChild (mic);
  56524. }
  56525. }
  56526. }
  56527. void triggerCurrentlyHighlightedItem()
  56528. {
  56529. if (currentChild->isValidComponent()
  56530. && currentChild->itemInfo.canBeTriggered()
  56531. && (currentChild->itemInfo.customComp == 0
  56532. || currentChild->itemInfo.customComp->isTriggeredAutomatically))
  56533. {
  56534. dismissMenu (&currentChild->itemInfo);
  56535. }
  56536. }
  56537. void selectNextItem (const int delta)
  56538. {
  56539. disableTimerUntilMouseMoves();
  56540. PopupMenu::ItemComponent* mic = 0;
  56541. bool wasLastOne = (currentChild == 0);
  56542. const int numItems = getNumChildComponents();
  56543. for (int i = 0; i < numItems + 1; ++i)
  56544. {
  56545. int index = (delta > 0) ? i : (numItems - 1 - i);
  56546. index = (index + numItems) % numItems;
  56547. mic = dynamic_cast <PopupMenu::ItemComponent*> (getChildComponent (index));
  56548. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  56549. && wasLastOne)
  56550. break;
  56551. if (mic == currentChild)
  56552. wasLastOne = true;
  56553. }
  56554. setCurrentlyHighlightedChild (mic);
  56555. }
  56556. void disableTimerUntilMouseMoves()
  56557. {
  56558. disableMouseMoves = true;
  56559. if (owner != 0)
  56560. owner->disableTimerUntilMouseMoves();
  56561. }
  56562. Window (const Window&);
  56563. Window& operator= (const Window&);
  56564. };
  56565. PopupMenu::PopupMenu()
  56566. : lookAndFeel (0),
  56567. separatorPending (false)
  56568. {
  56569. }
  56570. PopupMenu::PopupMenu (const PopupMenu& other)
  56571. : lookAndFeel (other.lookAndFeel),
  56572. separatorPending (false)
  56573. {
  56574. items.addCopiesOf (other.items);
  56575. }
  56576. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  56577. {
  56578. if (this != &other)
  56579. {
  56580. lookAndFeel = other.lookAndFeel;
  56581. clear();
  56582. items.addCopiesOf (other.items);
  56583. }
  56584. return *this;
  56585. }
  56586. PopupMenu::~PopupMenu()
  56587. {
  56588. clear();
  56589. }
  56590. void PopupMenu::clear()
  56591. {
  56592. items.clear();
  56593. separatorPending = false;
  56594. }
  56595. void PopupMenu::addSeparatorIfPending()
  56596. {
  56597. if (separatorPending)
  56598. {
  56599. separatorPending = false;
  56600. if (items.size() > 0)
  56601. items.add (new Item());
  56602. }
  56603. }
  56604. void PopupMenu::addItem (const int itemResultId,
  56605. const String& itemText,
  56606. const bool isActive,
  56607. const bool isTicked,
  56608. const Image& iconToUse)
  56609. {
  56610. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56611. // didn't pick anything, so you shouldn't use it as the id
  56612. // for an item..
  56613. addSeparatorIfPending();
  56614. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56615. Colours::black, false, 0, 0, 0));
  56616. }
  56617. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  56618. const int commandID,
  56619. const String& displayName)
  56620. {
  56621. jassert (commandManager != 0 && commandID != 0);
  56622. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  56623. if (registeredInfo != 0)
  56624. {
  56625. ApplicationCommandInfo info (*registeredInfo);
  56626. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  56627. addSeparatorIfPending();
  56628. items.add (new Item (commandID,
  56629. displayName.isNotEmpty() ? displayName
  56630. : info.shortName,
  56631. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  56632. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  56633. Image::null,
  56634. Colours::black,
  56635. false,
  56636. 0, 0,
  56637. commandManager));
  56638. }
  56639. }
  56640. void PopupMenu::addColouredItem (const int itemResultId,
  56641. const String& itemText,
  56642. const Colour& itemTextColour,
  56643. const bool isActive,
  56644. const bool isTicked,
  56645. const Image& iconToUse)
  56646. {
  56647. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56648. // didn't pick anything, so you shouldn't use it as the id
  56649. // for an item..
  56650. addSeparatorIfPending();
  56651. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56652. itemTextColour, true, 0, 0, 0));
  56653. }
  56654. void PopupMenu::addCustomItem (const int itemResultId,
  56655. PopupMenuCustomComponent* const customComponent)
  56656. {
  56657. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56658. // didn't pick anything, so you shouldn't use it as the id
  56659. // for an item..
  56660. addSeparatorIfPending();
  56661. items.add (new Item (itemResultId, String::empty, true, false, Image::null,
  56662. Colours::black, false, customComponent, 0, 0));
  56663. }
  56664. class NormalComponentWrapper : public PopupMenuCustomComponent
  56665. {
  56666. public:
  56667. NormalComponentWrapper (Component* const comp,
  56668. const int w, const int h,
  56669. const bool triggerMenuItemAutomaticallyWhenClicked)
  56670. : PopupMenuCustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  56671. width (w),
  56672. height (h)
  56673. {
  56674. addAndMakeVisible (comp);
  56675. }
  56676. ~NormalComponentWrapper() {}
  56677. void getIdealSize (int& idealWidth, int& idealHeight)
  56678. {
  56679. idealWidth = width;
  56680. idealHeight = height;
  56681. }
  56682. void resized()
  56683. {
  56684. if (getChildComponent(0) != 0)
  56685. getChildComponent(0)->setBounds (getLocalBounds());
  56686. }
  56687. juce_UseDebuggingNewOperator
  56688. private:
  56689. const int width, height;
  56690. NormalComponentWrapper (const NormalComponentWrapper&);
  56691. NormalComponentWrapper& operator= (const NormalComponentWrapper&);
  56692. };
  56693. void PopupMenu::addCustomItem (const int itemResultId,
  56694. Component* customComponent,
  56695. int idealWidth, int idealHeight,
  56696. const bool triggerMenuItemAutomaticallyWhenClicked)
  56697. {
  56698. addCustomItem (itemResultId,
  56699. new NormalComponentWrapper (customComponent,
  56700. idealWidth, idealHeight,
  56701. triggerMenuItemAutomaticallyWhenClicked));
  56702. }
  56703. void PopupMenu::addSubMenu (const String& subMenuName,
  56704. const PopupMenu& subMenu,
  56705. const bool isActive,
  56706. const Image& iconToUse,
  56707. const bool isTicked)
  56708. {
  56709. addSeparatorIfPending();
  56710. items.add (new Item (0, subMenuName, isActive && (subMenu.getNumItems() > 0), isTicked,
  56711. iconToUse, Colours::black, false, 0, &subMenu, 0));
  56712. }
  56713. void PopupMenu::addSeparator()
  56714. {
  56715. separatorPending = true;
  56716. }
  56717. class HeaderItemComponent : public PopupMenuCustomComponent
  56718. {
  56719. public:
  56720. HeaderItemComponent (const String& name)
  56721. : PopupMenuCustomComponent (false)
  56722. {
  56723. setName (name);
  56724. }
  56725. ~HeaderItemComponent()
  56726. {
  56727. }
  56728. void paint (Graphics& g)
  56729. {
  56730. Font f (getLookAndFeel().getPopupMenuFont());
  56731. f.setBold (true);
  56732. g.setFont (f);
  56733. g.setColour (findColour (PopupMenu::headerTextColourId));
  56734. g.drawFittedText (getName(),
  56735. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  56736. Justification::bottomLeft, 1);
  56737. }
  56738. void getIdealSize (int& idealWidth,
  56739. int& idealHeight)
  56740. {
  56741. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  56742. idealHeight += idealHeight / 2;
  56743. idealWidth += idealWidth / 4;
  56744. }
  56745. juce_UseDebuggingNewOperator
  56746. };
  56747. void PopupMenu::addSectionHeader (const String& title)
  56748. {
  56749. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  56750. }
  56751. // This invokes any command manager commands and deletes the menu window when it is dismissed
  56752. class PopupMenuCompletionCallback : public ModalComponentManager::Callback
  56753. {
  56754. public:
  56755. PopupMenuCompletionCallback()
  56756. : managerOfChosenCommand (0)
  56757. {
  56758. }
  56759. ~PopupMenuCompletionCallback() {}
  56760. void modalStateFinished (int result)
  56761. {
  56762. if (managerOfChosenCommand != 0 && result != 0)
  56763. {
  56764. ApplicationCommandTarget::InvocationInfo info (result);
  56765. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  56766. managerOfChosenCommand->invoke (info, true);
  56767. }
  56768. }
  56769. ApplicationCommandManager* managerOfChosenCommand;
  56770. ScopedPointer<Component> component;
  56771. private:
  56772. PopupMenuCompletionCallback (const PopupMenuCompletionCallback&);
  56773. PopupMenuCompletionCallback& operator= (const PopupMenuCompletionCallback&);
  56774. };
  56775. int PopupMenu::showMenu (const Rectangle<int>& target,
  56776. const int itemIdThatMustBeVisible,
  56777. const int minimumWidth,
  56778. const int maximumNumColumns,
  56779. const int standardItemHeight,
  56780. const bool alignToRectangle,
  56781. Component* const componentAttachedTo,
  56782. ModalComponentManager::Callback* userCallback)
  56783. {
  56784. ScopedPointer<ModalComponentManager::Callback> userCallbackDeleter (userCallback);
  56785. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  56786. Component::SafePointer<Component> prevTopLevel ((prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0);
  56787. Window::wasHiddenBecauseOfAppChange() = false;
  56788. PopupMenuCompletionCallback* callback = new PopupMenuCompletionCallback();
  56789. ScopedPointer<PopupMenuCompletionCallback> callbackDeleter (callback);
  56790. callback->component = Window::create (*this, ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  56791. 0, target, minimumWidth, maximumNumColumns > 0 ? maximumNumColumns : 7,
  56792. standardItemHeight, alignToRectangle, itemIdThatMustBeVisible,
  56793. &callback->managerOfChosenCommand, componentAttachedTo);
  56794. if (callback->component == 0)
  56795. return 0;
  56796. callbackDeleter.release();
  56797. callback->component->enterModalState (false, userCallbackDeleter.release());
  56798. callback->component->toFront (false); // need to do this after making it modal, or it could
  56799. // be stuck behind other comps that are already modal..
  56800. ModalComponentManager::getInstance()->attachCallback (callback->component, callback);
  56801. if (userCallback != 0)
  56802. return 0;
  56803. const int result = callback->component->runModalLoop();
  56804. if (! Window::wasHiddenBecauseOfAppChange())
  56805. {
  56806. if (prevTopLevel != 0)
  56807. prevTopLevel->toFront (true);
  56808. if (prevFocused != 0)
  56809. prevFocused->grabKeyboardFocus();
  56810. }
  56811. return result;
  56812. }
  56813. int PopupMenu::show (const int itemIdThatMustBeVisible,
  56814. const int minimumWidth,
  56815. const int maximumNumColumns,
  56816. const int standardItemHeight,
  56817. ModalComponentManager::Callback* callback)
  56818. {
  56819. const Point<int> mousePos (Desktop::getMousePosition());
  56820. return showAt (mousePos.getX(), mousePos.getY(),
  56821. itemIdThatMustBeVisible,
  56822. minimumWidth,
  56823. maximumNumColumns,
  56824. standardItemHeight,
  56825. callback);
  56826. }
  56827. int PopupMenu::showAt (const int screenX,
  56828. const int screenY,
  56829. const int itemIdThatMustBeVisible,
  56830. const int minimumWidth,
  56831. const int maximumNumColumns,
  56832. const int standardItemHeight,
  56833. ModalComponentManager::Callback* callback)
  56834. {
  56835. return showMenu (Rectangle<int> (screenX, screenY, 1, 1),
  56836. itemIdThatMustBeVisible,
  56837. minimumWidth, maximumNumColumns,
  56838. standardItemHeight,
  56839. false, 0, callback);
  56840. }
  56841. int PopupMenu::showAt (Component* componentToAttachTo,
  56842. const int itemIdThatMustBeVisible,
  56843. const int minimumWidth,
  56844. const int maximumNumColumns,
  56845. const int standardItemHeight,
  56846. ModalComponentManager::Callback* callback)
  56847. {
  56848. if (componentToAttachTo != 0)
  56849. {
  56850. return showMenu (componentToAttachTo->getScreenBounds(),
  56851. itemIdThatMustBeVisible,
  56852. minimumWidth,
  56853. maximumNumColumns,
  56854. standardItemHeight,
  56855. true, componentToAttachTo, callback);
  56856. }
  56857. else
  56858. {
  56859. return show (itemIdThatMustBeVisible,
  56860. minimumWidth,
  56861. maximumNumColumns,
  56862. standardItemHeight,
  56863. callback);
  56864. }
  56865. }
  56866. void JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus()
  56867. {
  56868. for (int i = Window::getActiveWindows().size(); --i >= 0;)
  56869. {
  56870. Window* const pmw = Window::getActiveWindows()[i];
  56871. if (pmw != 0)
  56872. pmw->dismissMenu (0);
  56873. }
  56874. }
  56875. int PopupMenu::getNumItems() const throw()
  56876. {
  56877. int num = 0;
  56878. for (int i = items.size(); --i >= 0;)
  56879. if (! (items.getUnchecked(i))->isSeparator)
  56880. ++num;
  56881. return num;
  56882. }
  56883. bool PopupMenu::containsCommandItem (const int commandID) const
  56884. {
  56885. for (int i = items.size(); --i >= 0;)
  56886. {
  56887. const Item* mi = items.getUnchecked (i);
  56888. if ((mi->itemId == commandID && mi->commandManager != 0)
  56889. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  56890. {
  56891. return true;
  56892. }
  56893. }
  56894. return false;
  56895. }
  56896. bool PopupMenu::containsAnyActiveItems() const throw()
  56897. {
  56898. for (int i = items.size(); --i >= 0;)
  56899. {
  56900. const Item* const mi = items.getUnchecked (i);
  56901. if (mi->subMenu != 0)
  56902. {
  56903. if (mi->subMenu->containsAnyActiveItems())
  56904. return true;
  56905. }
  56906. else if (mi->active)
  56907. {
  56908. return true;
  56909. }
  56910. }
  56911. return false;
  56912. }
  56913. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  56914. {
  56915. lookAndFeel = newLookAndFeel;
  56916. }
  56917. PopupMenuCustomComponent::PopupMenuCustomComponent (const bool isTriggeredAutomatically_)
  56918. : isHighlighted (false),
  56919. isTriggeredAutomatically (isTriggeredAutomatically_)
  56920. {
  56921. }
  56922. PopupMenuCustomComponent::~PopupMenuCustomComponent()
  56923. {
  56924. }
  56925. void PopupMenuCustomComponent::triggerMenuItem()
  56926. {
  56927. PopupMenu::ItemComponent* const mic = dynamic_cast <PopupMenu::ItemComponent*> (getParentComponent());
  56928. if (mic != 0)
  56929. {
  56930. PopupMenu::Window* const pmw = dynamic_cast <PopupMenu::Window*> (mic->getParentComponent());
  56931. if (pmw != 0)
  56932. {
  56933. pmw->dismissMenu (&mic->itemInfo);
  56934. }
  56935. else
  56936. {
  56937. // something must have gone wrong with the component hierarchy if this happens..
  56938. jassertfalse;
  56939. }
  56940. }
  56941. else
  56942. {
  56943. // why isn't this component inside a menu? Not much point triggering the item if
  56944. // there's no menu.
  56945. jassertfalse;
  56946. }
  56947. }
  56948. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_)
  56949. : subMenu (0),
  56950. itemId (0),
  56951. isSeparator (false),
  56952. isTicked (false),
  56953. isEnabled (false),
  56954. isCustomComponent (false),
  56955. isSectionHeader (false),
  56956. customColour (0),
  56957. customImage (0),
  56958. menu (menu_),
  56959. index (0)
  56960. {
  56961. }
  56962. PopupMenu::MenuItemIterator::~MenuItemIterator()
  56963. {
  56964. }
  56965. bool PopupMenu::MenuItemIterator::next()
  56966. {
  56967. if (index >= menu.items.size())
  56968. return false;
  56969. const Item* const item = menu.items.getUnchecked (index);
  56970. ++index;
  56971. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  56972. subMenu = item->subMenu;
  56973. itemId = item->itemId;
  56974. isSeparator = item->isSeparator;
  56975. isTicked = item->isTicked;
  56976. isEnabled = item->active;
  56977. isSectionHeader = dynamic_cast <HeaderItemComponent*> ((PopupMenuCustomComponent*) item->customComp) != 0;
  56978. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  56979. customColour = item->usesColour ? &(item->textColour) : 0;
  56980. customImage = item->image;
  56981. commandManager = item->commandManager;
  56982. return true;
  56983. }
  56984. END_JUCE_NAMESPACE
  56985. /*** End of inlined file: juce_PopupMenu.cpp ***/
  56986. /*** Start of inlined file: juce_ComponentDragger.cpp ***/
  56987. BEGIN_JUCE_NAMESPACE
  56988. ComponentDragger::ComponentDragger()
  56989. : constrainer (0)
  56990. {
  56991. }
  56992. ComponentDragger::~ComponentDragger()
  56993. {
  56994. }
  56995. void ComponentDragger::startDraggingComponent (Component* const componentToDrag,
  56996. ComponentBoundsConstrainer* const constrainer_)
  56997. {
  56998. jassert (componentToDrag->isValidComponent());
  56999. if (componentToDrag != 0)
  57000. {
  57001. constrainer = constrainer_;
  57002. originalPos = componentToDrag->relativePositionToGlobal (Point<int>());
  57003. }
  57004. }
  57005. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e)
  57006. {
  57007. jassert (componentToDrag->isValidComponent());
  57008. jassert (e.mods.isAnyMouseButtonDown()); // (the event has to be a drag event..)
  57009. if (componentToDrag != 0)
  57010. {
  57011. Rectangle<int> bounds (componentToDrag->getBounds().withPosition (originalPos));
  57012. const Component* const parentComp = componentToDrag->getParentComponent();
  57013. if (parentComp != 0)
  57014. bounds.setPosition (parentComp->globalPositionToRelative (originalPos));
  57015. bounds.setPosition (bounds.getPosition() + e.getOffsetFromDragStart());
  57016. if (constrainer != 0)
  57017. constrainer->setBoundsForComponent (componentToDrag, bounds, false, false, false, false);
  57018. else
  57019. componentToDrag->setBounds (bounds);
  57020. }
  57021. }
  57022. END_JUCE_NAMESPACE
  57023. /*** End of inlined file: juce_ComponentDragger.cpp ***/
  57024. /*** Start of inlined file: juce_DragAndDropContainer.cpp ***/
  57025. BEGIN_JUCE_NAMESPACE
  57026. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  57027. bool juce_performDragDropText (const String& text, bool& shouldStop);
  57028. class DragImageComponent : public Component,
  57029. public Timer
  57030. {
  57031. public:
  57032. DragImageComponent (const Image& im,
  57033. const String& desc,
  57034. Component* const sourceComponent,
  57035. Component* const mouseDragSource_,
  57036. DragAndDropContainer* const o,
  57037. const Point<int>& imageOffset_)
  57038. : image (im),
  57039. source (sourceComponent),
  57040. mouseDragSource (mouseDragSource_),
  57041. owner (o),
  57042. dragDesc (desc),
  57043. imageOffset (imageOffset_),
  57044. hasCheckedForExternalDrag (false),
  57045. drawImage (true)
  57046. {
  57047. setSize (im.getWidth(), im.getHeight());
  57048. if (mouseDragSource == 0)
  57049. mouseDragSource = source;
  57050. mouseDragSource->addMouseListener (this, false);
  57051. startTimer (200);
  57052. setInterceptsMouseClicks (false, false);
  57053. setAlwaysOnTop (true);
  57054. }
  57055. ~DragImageComponent()
  57056. {
  57057. if (owner->dragImageComponent == this)
  57058. owner->dragImageComponent.release();
  57059. if (mouseDragSource != 0)
  57060. {
  57061. mouseDragSource->removeMouseListener (this);
  57062. if (getCurrentlyOver() != 0 && getCurrentlyOver()->isInterestedInDragSource (dragDesc, source))
  57063. getCurrentlyOver()->itemDragExit (dragDesc, source);
  57064. }
  57065. }
  57066. void paint (Graphics& g)
  57067. {
  57068. if (isOpaque())
  57069. g.fillAll (Colours::white);
  57070. if (drawImage)
  57071. {
  57072. g.setOpacity (1.0f);
  57073. g.drawImageAt (image, 0, 0);
  57074. }
  57075. }
  57076. DragAndDropTarget* findTarget (const Point<int>& screenPos, Point<int>& relativePos)
  57077. {
  57078. Component* hit = getParentComponent();
  57079. if (hit == 0)
  57080. {
  57081. hit = Desktop::getInstance().findComponentAt (screenPos);
  57082. }
  57083. else
  57084. {
  57085. const Point<int> relPos (hit->globalPositionToRelative (screenPos));
  57086. hit = hit->getComponentAt (relPos.getX(), relPos.getY());
  57087. }
  57088. // (note: use a local copy of the dragDesc member in case the callback runs
  57089. // a modal loop and deletes this object before the method completes)
  57090. const String dragDescLocal (dragDesc);
  57091. while (hit != 0)
  57092. {
  57093. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  57094. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  57095. {
  57096. relativePos = hit->globalPositionToRelative (screenPos);
  57097. return ddt;
  57098. }
  57099. hit = hit->getParentComponent();
  57100. }
  57101. return 0;
  57102. }
  57103. void mouseUp (const MouseEvent& e)
  57104. {
  57105. if (e.originalComponent != this)
  57106. {
  57107. if (mouseDragSource != 0)
  57108. mouseDragSource->removeMouseListener (this);
  57109. bool dropAccepted = false;
  57110. DragAndDropTarget* ddt = 0;
  57111. Point<int> relPos;
  57112. if (isVisible())
  57113. {
  57114. setVisible (false);
  57115. ddt = findTarget (e.getScreenPosition(), relPos);
  57116. // fade this component and remove it - it'll be deleted later by the timer callback
  57117. dropAccepted = ddt != 0;
  57118. setVisible (true);
  57119. if (dropAccepted || source == 0)
  57120. {
  57121. fadeOutComponent (120);
  57122. }
  57123. else
  57124. {
  57125. const Point<int> target (source->relativePositionToGlobal (Point<int> (source->getWidth() / 2,
  57126. source->getHeight() / 2)));
  57127. const Point<int> ourCentre (relativePositionToGlobal (Point<int> (getWidth() / 2,
  57128. getHeight() / 2)));
  57129. fadeOutComponent (120,
  57130. target.getX() - ourCentre.getX(),
  57131. target.getY() - ourCentre.getY());
  57132. }
  57133. }
  57134. if (getParentComponent() != 0)
  57135. getParentComponent()->removeChildComponent (this);
  57136. if (dropAccepted && ddt != 0)
  57137. {
  57138. // (note: use a local copy of the dragDesc member in case the callback runs
  57139. // a modal loop and deletes this object before the method completes)
  57140. const String dragDescLocal (dragDesc);
  57141. currentlyOverComp = 0;
  57142. ddt->itemDropped (dragDescLocal, source, relPos.getX(), relPos.getY());
  57143. }
  57144. // careful - this object could now be deleted..
  57145. }
  57146. }
  57147. void updateLocation (const bool canDoExternalDrag, const Point<int>& screenPos)
  57148. {
  57149. // (note: use a local copy of the dragDesc member in case the callback runs
  57150. // a modal loop and deletes this object before it returns)
  57151. const String dragDescLocal (dragDesc);
  57152. Point<int> newPos (screenPos + imageOffset);
  57153. if (getParentComponent() != 0)
  57154. newPos = getParentComponent()->globalPositionToRelative (newPos);
  57155. //if (newX != getX() || newY != getY())
  57156. {
  57157. setTopLeftPosition (newPos.getX(), newPos.getY());
  57158. Point<int> relPos;
  57159. DragAndDropTarget* const ddt = findTarget (screenPos, relPos);
  57160. Component* ddtComp = dynamic_cast <Component*> (ddt);
  57161. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  57162. if (ddtComp != currentlyOverComp)
  57163. {
  57164. if (currentlyOverComp != 0 && source != 0
  57165. && getCurrentlyOver()->isInterestedInDragSource (dragDescLocal, source))
  57166. {
  57167. getCurrentlyOver()->itemDragExit (dragDescLocal, source);
  57168. }
  57169. currentlyOverComp = ddtComp;
  57170. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  57171. ddt->itemDragEnter (dragDescLocal, source, relPos.getX(), relPos.getY());
  57172. }
  57173. DragAndDropTarget* target = getCurrentlyOver();
  57174. if (target != 0 && target->isInterestedInDragSource (dragDescLocal, source))
  57175. target->itemDragMove (dragDescLocal, source, relPos.getX(), relPos.getY());
  57176. if (getCurrentlyOver() == 0 && canDoExternalDrag && ! hasCheckedForExternalDrag)
  57177. {
  57178. if (Desktop::getInstance().findComponentAt (screenPos) == 0)
  57179. {
  57180. hasCheckedForExternalDrag = true;
  57181. StringArray files;
  57182. bool canMoveFiles = false;
  57183. if (owner->shouldDropFilesWhenDraggedExternally (dragDescLocal, source, files, canMoveFiles)
  57184. && files.size() > 0)
  57185. {
  57186. Component::SafePointer<Component> cdw (this);
  57187. setVisible (false);
  57188. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  57189. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  57190. if (cdw != 0)
  57191. delete this;
  57192. return;
  57193. }
  57194. }
  57195. }
  57196. }
  57197. }
  57198. void mouseDrag (const MouseEvent& e)
  57199. {
  57200. if (e.originalComponent != this)
  57201. updateLocation (true, e.getScreenPosition());
  57202. }
  57203. void timerCallback()
  57204. {
  57205. if (source == 0)
  57206. {
  57207. delete this;
  57208. }
  57209. else if (! isMouseButtonDownAnywhere())
  57210. {
  57211. if (mouseDragSource != 0)
  57212. mouseDragSource->removeMouseListener (this);
  57213. delete this;
  57214. }
  57215. }
  57216. private:
  57217. Image image;
  57218. Component::SafePointer<Component> source;
  57219. Component::SafePointer<Component> mouseDragSource;
  57220. DragAndDropContainer* const owner;
  57221. Component::SafePointer<Component> currentlyOverComp;
  57222. DragAndDropTarget* getCurrentlyOver()
  57223. {
  57224. return dynamic_cast <DragAndDropTarget*> (static_cast <Component*> (currentlyOverComp));
  57225. }
  57226. String dragDesc;
  57227. const Point<int> imageOffset;
  57228. bool hasCheckedForExternalDrag, drawImage;
  57229. DragImageComponent (const DragImageComponent&);
  57230. DragImageComponent& operator= (const DragImageComponent&);
  57231. };
  57232. DragAndDropContainer::DragAndDropContainer()
  57233. {
  57234. }
  57235. DragAndDropContainer::~DragAndDropContainer()
  57236. {
  57237. dragImageComponent = 0;
  57238. }
  57239. void DragAndDropContainer::startDragging (const String& sourceDescription,
  57240. Component* sourceComponent,
  57241. const Image& dragImage_,
  57242. const bool allowDraggingToExternalWindows,
  57243. const Point<int>* imageOffsetFromMouse)
  57244. {
  57245. Image dragImage (dragImage_);
  57246. if (dragImageComponent == 0)
  57247. {
  57248. Component* const thisComp = dynamic_cast <Component*> (this);
  57249. if (thisComp == 0)
  57250. {
  57251. jassertfalse; // Your DragAndDropContainer needs to be a Component!
  57252. return;
  57253. }
  57254. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource (0);
  57255. if (draggingSource == 0 || ! draggingSource->isDragging())
  57256. {
  57257. jassertfalse; // You must call startDragging() from within a mouseDown or mouseDrag callback!
  57258. return;
  57259. }
  57260. const Point<int> lastMouseDown (Desktop::getLastMouseDownPosition());
  57261. Point<int> imageOffset;
  57262. if (dragImage.isNull())
  57263. {
  57264. dragImage = sourceComponent->createComponentSnapshot (sourceComponent->getLocalBounds())
  57265. .convertedToFormat (Image::ARGB);
  57266. dragImage.multiplyAllAlphas (0.6f);
  57267. const int lo = 150;
  57268. const int hi = 400;
  57269. Point<int> relPos (sourceComponent->globalPositionToRelative (lastMouseDown));
  57270. Point<int> clipped (dragImage.getBounds().getConstrainedPoint (relPos));
  57271. for (int y = dragImage.getHeight(); --y >= 0;)
  57272. {
  57273. const double dy = (y - clipped.getY()) * (y - clipped.getY());
  57274. for (int x = dragImage.getWidth(); --x >= 0;)
  57275. {
  57276. const int dx = x - clipped.getX();
  57277. const int distance = roundToInt (std::sqrt (dx * dx + dy));
  57278. if (distance > lo)
  57279. {
  57280. const float alpha = (distance > hi) ? 0
  57281. : (hi - distance) / (float) (hi - lo)
  57282. + Random::getSystemRandom().nextFloat() * 0.008f;
  57283. dragImage.multiplyAlphaAt (x, y, alpha);
  57284. }
  57285. }
  57286. }
  57287. imageOffset = -clipped;
  57288. }
  57289. else
  57290. {
  57291. if (imageOffsetFromMouse == 0)
  57292. imageOffset = -dragImage.getBounds().getCentre();
  57293. else
  57294. imageOffset = -(dragImage.getBounds().getConstrainedPoint (-*imageOffsetFromMouse));
  57295. }
  57296. dragImageComponent = new DragImageComponent (dragImage, sourceDescription, sourceComponent,
  57297. draggingSource->getComponentUnderMouse(), this, imageOffset);
  57298. currentDragDesc = sourceDescription;
  57299. if (allowDraggingToExternalWindows)
  57300. {
  57301. if (! Desktop::canUseSemiTransparentWindows())
  57302. dragImageComponent->setOpaque (true);
  57303. dragImageComponent->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  57304. | ComponentPeer::windowIsTemporary
  57305. | ComponentPeer::windowIgnoresKeyPresses);
  57306. }
  57307. else
  57308. thisComp->addChildComponent (dragImageComponent);
  57309. static_cast <DragImageComponent*> (static_cast <Component*> (dragImageComponent))->updateLocation (false, lastMouseDown);
  57310. dragImageComponent->setVisible (true);
  57311. }
  57312. }
  57313. bool DragAndDropContainer::isDragAndDropActive() const
  57314. {
  57315. return dragImageComponent != 0;
  57316. }
  57317. const String DragAndDropContainer::getCurrentDragDescription() const
  57318. {
  57319. return (dragImageComponent != 0) ? currentDragDesc
  57320. : String::empty;
  57321. }
  57322. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  57323. {
  57324. return c == 0 ? 0 : c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  57325. }
  57326. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  57327. {
  57328. return false;
  57329. }
  57330. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  57331. {
  57332. }
  57333. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  57334. {
  57335. }
  57336. void DragAndDropTarget::itemDragExit (const String&, Component*)
  57337. {
  57338. }
  57339. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  57340. {
  57341. return true;
  57342. }
  57343. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  57344. {
  57345. }
  57346. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  57347. {
  57348. }
  57349. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  57350. {
  57351. }
  57352. END_JUCE_NAMESPACE
  57353. /*** End of inlined file: juce_DragAndDropContainer.cpp ***/
  57354. /*** Start of inlined file: juce_MouseCursor.cpp ***/
  57355. BEGIN_JUCE_NAMESPACE
  57356. class MouseCursor::SharedCursorHandle
  57357. {
  57358. public:
  57359. explicit SharedCursorHandle (const MouseCursor::StandardCursorType type)
  57360. : handle (createStandardMouseCursor (type)),
  57361. refCount (1),
  57362. standardType (type),
  57363. isStandard (true)
  57364. {
  57365. }
  57366. SharedCursorHandle (const Image& image, const int hotSpotX, const int hotSpotY)
  57367. : handle (createMouseCursorFromImage (image, hotSpotX, hotSpotY)),
  57368. refCount (1),
  57369. standardType (MouseCursor::NormalCursor),
  57370. isStandard (false)
  57371. {
  57372. }
  57373. static SharedCursorHandle* createStandard (const MouseCursor::StandardCursorType type)
  57374. {
  57375. const ScopedLock sl (getLock());
  57376. for (int i = 0; i < getCursors().size(); ++i)
  57377. {
  57378. SharedCursorHandle* const sc = getCursors().getUnchecked(i);
  57379. if (sc->standardType == type)
  57380. return sc->retain();
  57381. }
  57382. SharedCursorHandle* const sc = new SharedCursorHandle (type);
  57383. getCursors().add (sc);
  57384. return sc;
  57385. }
  57386. SharedCursorHandle* retain() throw()
  57387. {
  57388. ++refCount;
  57389. return this;
  57390. }
  57391. void release()
  57392. {
  57393. if (--refCount == 0)
  57394. {
  57395. if (isStandard)
  57396. {
  57397. const ScopedLock sl (getLock());
  57398. getCursors().removeValue (this);
  57399. }
  57400. delete this;
  57401. }
  57402. }
  57403. void* getHandle() const throw() { return handle; }
  57404. juce_UseDebuggingNewOperator
  57405. private:
  57406. void* const handle;
  57407. Atomic <int> refCount;
  57408. const MouseCursor::StandardCursorType standardType;
  57409. const bool isStandard;
  57410. static CriticalSection& getLock()
  57411. {
  57412. static CriticalSection lock;
  57413. return lock;
  57414. }
  57415. static Array <SharedCursorHandle*>& getCursors()
  57416. {
  57417. static Array <SharedCursorHandle*> cursors;
  57418. return cursors;
  57419. }
  57420. ~SharedCursorHandle()
  57421. {
  57422. deleteMouseCursor (handle, isStandard);
  57423. }
  57424. SharedCursorHandle& operator= (const SharedCursorHandle&);
  57425. };
  57426. MouseCursor::MouseCursor()
  57427. : cursorHandle (SharedCursorHandle::createStandard (NormalCursor))
  57428. {
  57429. jassert (cursorHandle != 0);
  57430. }
  57431. MouseCursor::MouseCursor (const StandardCursorType type)
  57432. : cursorHandle (SharedCursorHandle::createStandard (type))
  57433. {
  57434. jassert (cursorHandle != 0);
  57435. }
  57436. MouseCursor::MouseCursor (const Image& image, const int hotSpotX, const int hotSpotY)
  57437. : cursorHandle (new SharedCursorHandle (image, hotSpotX, hotSpotY))
  57438. {
  57439. }
  57440. MouseCursor::MouseCursor (const MouseCursor& other)
  57441. : cursorHandle (other.cursorHandle->retain())
  57442. {
  57443. }
  57444. MouseCursor::~MouseCursor()
  57445. {
  57446. cursorHandle->release();
  57447. }
  57448. MouseCursor& MouseCursor::operator= (const MouseCursor& other)
  57449. {
  57450. other.cursorHandle->retain();
  57451. cursorHandle->release();
  57452. cursorHandle = other.cursorHandle;
  57453. return *this;
  57454. }
  57455. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  57456. {
  57457. return getHandle() == other.getHandle();
  57458. }
  57459. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  57460. {
  57461. return getHandle() != other.getHandle();
  57462. }
  57463. void* MouseCursor::getHandle() const throw()
  57464. {
  57465. return cursorHandle->getHandle();
  57466. }
  57467. void MouseCursor::showWaitCursor()
  57468. {
  57469. Desktop::getInstance().getMainMouseSource().showMouseCursor (MouseCursor::WaitCursor);
  57470. }
  57471. void MouseCursor::hideWaitCursor()
  57472. {
  57473. Desktop::getInstance().getMainMouseSource().revealCursor();
  57474. }
  57475. END_JUCE_NAMESPACE
  57476. /*** End of inlined file: juce_MouseCursor.cpp ***/
  57477. /*** Start of inlined file: juce_MouseEvent.cpp ***/
  57478. BEGIN_JUCE_NAMESPACE
  57479. MouseEvent::MouseEvent (MouseInputSource& source_,
  57480. const Point<int>& position,
  57481. const ModifierKeys& mods_,
  57482. Component* const eventComponent_,
  57483. Component* const originator,
  57484. const Time& eventTime_,
  57485. const Point<int> mouseDownPos_,
  57486. const Time& mouseDownTime_,
  57487. const int numberOfClicks_,
  57488. const bool mouseWasDragged) throw()
  57489. : x (position.getX()),
  57490. y (position.getY()),
  57491. mods (mods_),
  57492. eventComponent (eventComponent_),
  57493. originalComponent (originator),
  57494. eventTime (eventTime_),
  57495. source (source_),
  57496. mouseDownPos (mouseDownPos_),
  57497. mouseDownTime (mouseDownTime_),
  57498. numberOfClicks (numberOfClicks_),
  57499. wasMovedSinceMouseDown (mouseWasDragged)
  57500. {
  57501. }
  57502. MouseEvent::~MouseEvent() throw()
  57503. {
  57504. }
  57505. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  57506. {
  57507. if (otherComponent == 0)
  57508. {
  57509. jassertfalse;
  57510. return *this;
  57511. }
  57512. return MouseEvent (source, eventComponent->relativePositionToOtherComponent (otherComponent, getPosition()),
  57513. mods, otherComponent, originalComponent, eventTime,
  57514. eventComponent->relativePositionToOtherComponent (otherComponent, mouseDownPos),
  57515. mouseDownTime, numberOfClicks, wasMovedSinceMouseDown);
  57516. }
  57517. const MouseEvent MouseEvent::withNewPosition (const Point<int>& newPosition) const throw()
  57518. {
  57519. return MouseEvent (source, newPosition, mods, eventComponent, originalComponent,
  57520. eventTime, mouseDownPos, mouseDownTime,
  57521. numberOfClicks, wasMovedSinceMouseDown);
  57522. }
  57523. bool MouseEvent::mouseWasClicked() const throw()
  57524. {
  57525. return ! wasMovedSinceMouseDown;
  57526. }
  57527. int MouseEvent::getMouseDownX() const throw()
  57528. {
  57529. return mouseDownPos.getX();
  57530. }
  57531. int MouseEvent::getMouseDownY() const throw()
  57532. {
  57533. return mouseDownPos.getY();
  57534. }
  57535. const Point<int> MouseEvent::getMouseDownPosition() const throw()
  57536. {
  57537. return mouseDownPos;
  57538. }
  57539. int MouseEvent::getDistanceFromDragStartX() const throw()
  57540. {
  57541. return x - mouseDownPos.getX();
  57542. }
  57543. int MouseEvent::getDistanceFromDragStartY() const throw()
  57544. {
  57545. return y - mouseDownPos.getY();
  57546. }
  57547. int MouseEvent::getDistanceFromDragStart() const throw()
  57548. {
  57549. return mouseDownPos.getDistanceFrom (getPosition());
  57550. }
  57551. const Point<int> MouseEvent::getOffsetFromDragStart() const throw()
  57552. {
  57553. return getPosition() - mouseDownPos;
  57554. }
  57555. int MouseEvent::getLengthOfMousePress() const throw()
  57556. {
  57557. if (mouseDownTime.toMilliseconds() > 0)
  57558. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  57559. return 0;
  57560. }
  57561. const Point<int> MouseEvent::getPosition() const throw()
  57562. {
  57563. return Point<int> (x, y);
  57564. }
  57565. int MouseEvent::getScreenX() const
  57566. {
  57567. return getScreenPosition().getX();
  57568. }
  57569. int MouseEvent::getScreenY() const
  57570. {
  57571. return getScreenPosition().getY();
  57572. }
  57573. const Point<int> MouseEvent::getScreenPosition() const
  57574. {
  57575. return eventComponent->relativePositionToGlobal (Point<int> (x, y));
  57576. }
  57577. int MouseEvent::getMouseDownScreenX() const
  57578. {
  57579. return getMouseDownScreenPosition().getX();
  57580. }
  57581. int MouseEvent::getMouseDownScreenY() const
  57582. {
  57583. return getMouseDownScreenPosition().getY();
  57584. }
  57585. const Point<int> MouseEvent::getMouseDownScreenPosition() const
  57586. {
  57587. return eventComponent->relativePositionToGlobal (mouseDownPos);
  57588. }
  57589. int MouseEvent::doubleClickTimeOutMs = 400;
  57590. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  57591. {
  57592. doubleClickTimeOutMs = newTime;
  57593. }
  57594. int MouseEvent::getDoubleClickTimeout() throw()
  57595. {
  57596. return doubleClickTimeOutMs;
  57597. }
  57598. END_JUCE_NAMESPACE
  57599. /*** End of inlined file: juce_MouseEvent.cpp ***/
  57600. /*** Start of inlined file: juce_MouseInputSource.cpp ***/
  57601. BEGIN_JUCE_NAMESPACE
  57602. class MouseInputSourceInternal : public AsyncUpdater
  57603. {
  57604. public:
  57605. MouseInputSourceInternal (MouseInputSource& source_, const int index_, const bool isMouseDevice_)
  57606. : index (index_), isMouseDevice (isMouseDevice_), source (source_), lastPeer (0), lastTime (0),
  57607. isUnboundedMouseModeOn (false), isCursorVisibleUntilOffscreen (false), currentCursorHandle (0),
  57608. mouseEventCounter (0)
  57609. {
  57610. zerostruct (mouseDowns);
  57611. }
  57612. ~MouseInputSourceInternal()
  57613. {
  57614. }
  57615. bool isDragging() const throw()
  57616. {
  57617. return buttonState.isAnyMouseButtonDown();
  57618. }
  57619. Component* getComponentUnderMouse() const
  57620. {
  57621. return static_cast <Component*> (componentUnderMouse);
  57622. }
  57623. const ModifierKeys getCurrentModifiers() const
  57624. {
  57625. return ModifierKeys::getCurrentModifiers().withoutMouseButtons().withFlags (buttonState.getRawFlags());
  57626. }
  57627. ComponentPeer* getPeer()
  57628. {
  57629. if (! ComponentPeer::isValidPeer (lastPeer))
  57630. lastPeer = 0;
  57631. return lastPeer;
  57632. }
  57633. Component* findComponentAt (const Point<int>& screenPos)
  57634. {
  57635. ComponentPeer* const peer = getPeer();
  57636. if (peer != 0)
  57637. {
  57638. Component* const comp = peer->getComponent();
  57639. const Point<int> relativePos (comp->globalPositionToRelative (screenPos));
  57640. // (the contains() call is needed to test for overlapping desktop windows)
  57641. if (comp->contains (relativePos.getX(), relativePos.getY()))
  57642. return comp->getComponentAt (relativePos);
  57643. }
  57644. return 0;
  57645. }
  57646. const Point<int> getScreenPosition() const throw()
  57647. {
  57648. return lastScreenPos + unboundedMouseOffset;
  57649. }
  57650. void sendMouseEnter (Component* const comp, const Point<int>& screenPos, const int64 time)
  57651. {
  57652. //DBG ("Mouse " + String (source.getIndex()) + " enter: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57653. comp->internalMouseEnter (source, comp->globalPositionToRelative (screenPos), time);
  57654. }
  57655. void sendMouseExit (Component* const comp, const Point<int>& screenPos, const int64 time)
  57656. {
  57657. //DBG ("Mouse " + String (source.getIndex()) + " exit: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57658. comp->internalMouseExit (source, comp->globalPositionToRelative (screenPos), time);
  57659. }
  57660. void sendMouseMove (Component* const comp, const Point<int>& screenPos, const int64 time)
  57661. {
  57662. //DBG ("Mouse " + String (source.getIndex()) + " move: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57663. comp->internalMouseMove (source, comp->globalPositionToRelative (screenPos), time);
  57664. }
  57665. void sendMouseDown (Component* const comp, const Point<int>& screenPos, const int64 time)
  57666. {
  57667. //DBG ("Mouse " + String (source.getIndex()) + " down: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57668. comp->internalMouseDown (source, comp->globalPositionToRelative (screenPos), time);
  57669. }
  57670. void sendMouseDrag (Component* const comp, const Point<int>& screenPos, const int64 time)
  57671. {
  57672. //DBG ("Mouse " + String (source.getIndex()) + " drag: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57673. comp->internalMouseDrag (source, comp->globalPositionToRelative (screenPos), time);
  57674. }
  57675. void sendMouseUp (Component* const comp, const Point<int>& screenPos, const int64 time)
  57676. {
  57677. //DBG ("Mouse " + String (source.getIndex()) + " up: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57678. comp->internalMouseUp (source, comp->globalPositionToRelative (screenPos), time, getCurrentModifiers());
  57679. }
  57680. void sendMouseWheel (Component* const comp, const Point<int>& screenPos, const int64 time, float x, float y)
  57681. {
  57682. //DBG ("Mouse " + String (source.getIndex()) + " wheel: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57683. comp->internalMouseWheel (source, comp->globalPositionToRelative (screenPos), time, x, y);
  57684. }
  57685. // (returns true if the button change caused a modal event loop)
  57686. bool setButtons (const Point<int>& screenPos, const int64 time, const ModifierKeys& newButtonState)
  57687. {
  57688. if (buttonState == newButtonState)
  57689. return false;
  57690. setScreenPos (screenPos, time, false);
  57691. // (ignore secondary clicks when there's already a button down)
  57692. if (buttonState.isAnyMouseButtonDown() == newButtonState.isAnyMouseButtonDown())
  57693. {
  57694. buttonState = newButtonState;
  57695. return false;
  57696. }
  57697. const int lastCounter = mouseEventCounter;
  57698. if (buttonState.isAnyMouseButtonDown())
  57699. {
  57700. Component* const current = getComponentUnderMouse();
  57701. if (current != 0)
  57702. sendMouseUp (current, screenPos + unboundedMouseOffset, time);
  57703. enableUnboundedMouseMovement (false, false);
  57704. }
  57705. buttonState = newButtonState;
  57706. if (buttonState.isAnyMouseButtonDown())
  57707. {
  57708. Desktop::getInstance().incrementMouseClickCounter();
  57709. Component* const current = getComponentUnderMouse();
  57710. if (current != 0)
  57711. {
  57712. registerMouseDown (screenPos, time, current);
  57713. sendMouseDown (current, screenPos, time);
  57714. }
  57715. }
  57716. return lastCounter != mouseEventCounter;
  57717. }
  57718. void setComponentUnderMouse (Component* const newComponent, const Point<int>& screenPos, const int64 time)
  57719. {
  57720. Component* current = getComponentUnderMouse();
  57721. if (newComponent != current)
  57722. {
  57723. Component::SafePointer<Component> safeNewComp (newComponent);
  57724. const ModifierKeys originalButtonState (buttonState);
  57725. if (current != 0)
  57726. {
  57727. setButtons (screenPos, time, ModifierKeys());
  57728. sendMouseExit (current, screenPos, time);
  57729. buttonState = originalButtonState;
  57730. }
  57731. componentUnderMouse = safeNewComp;
  57732. current = getComponentUnderMouse();
  57733. if (current != 0)
  57734. sendMouseEnter (current, screenPos, time);
  57735. revealCursor (false);
  57736. setButtons (screenPos, time, originalButtonState);
  57737. }
  57738. }
  57739. void setPeer (ComponentPeer* const newPeer, const Point<int>& screenPos, const int64 time)
  57740. {
  57741. ModifierKeys::updateCurrentModifiers();
  57742. if (newPeer != lastPeer)
  57743. {
  57744. setComponentUnderMouse (0, screenPos, time);
  57745. lastPeer = newPeer;
  57746. setComponentUnderMouse (findComponentAt (screenPos), screenPos, time);
  57747. }
  57748. }
  57749. void setScreenPos (const Point<int>& newScreenPos, const int64 time, const bool forceUpdate)
  57750. {
  57751. if (! isDragging())
  57752. setComponentUnderMouse (findComponentAt (newScreenPos), newScreenPos, time);
  57753. if (newScreenPos != lastScreenPos || forceUpdate)
  57754. {
  57755. cancelPendingUpdate();
  57756. lastScreenPos = newScreenPos;
  57757. Component* const current = getComponentUnderMouse();
  57758. if (current != 0)
  57759. {
  57760. if (isDragging())
  57761. {
  57762. registerMouseDrag (newScreenPos);
  57763. sendMouseDrag (current, newScreenPos + unboundedMouseOffset, time);
  57764. if (isUnboundedMouseModeOn)
  57765. handleUnboundedDrag (current);
  57766. }
  57767. else
  57768. {
  57769. sendMouseMove (current, newScreenPos, time);
  57770. }
  57771. }
  57772. revealCursor (false);
  57773. }
  57774. }
  57775. void handleEvent (ComponentPeer* const newPeer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& newMods)
  57776. {
  57777. jassert (newPeer != 0);
  57778. lastTime = time;
  57779. ++mouseEventCounter;
  57780. const Point<int> screenPos (newPeer->relativePositionToGlobal (positionWithinPeer));
  57781. if (isDragging() && newMods.isAnyMouseButtonDown())
  57782. {
  57783. setScreenPos (screenPos, time, false);
  57784. }
  57785. else
  57786. {
  57787. setPeer (newPeer, screenPos, time);
  57788. ComponentPeer* peer = getPeer();
  57789. if (peer != 0)
  57790. {
  57791. if (setButtons (screenPos, time, newMods))
  57792. return; // some modal events have been dispatched, so the current event is now out-of-date
  57793. peer = getPeer();
  57794. if (peer != 0)
  57795. setScreenPos (screenPos, time, false);
  57796. }
  57797. }
  57798. }
  57799. void handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, int64 time, float x, float y)
  57800. {
  57801. jassert (peer != 0);
  57802. lastTime = time;
  57803. ++mouseEventCounter;
  57804. const Point<int> screenPos (peer->relativePositionToGlobal (positionWithinPeer));
  57805. setPeer (peer, screenPos, time);
  57806. setScreenPos (screenPos, time, false);
  57807. triggerFakeMove();
  57808. if (! isDragging())
  57809. {
  57810. Component* current = getComponentUnderMouse();
  57811. if (current != 0)
  57812. sendMouseWheel (current, screenPos, time, x, y);
  57813. }
  57814. }
  57815. const Time getLastMouseDownTime() const throw()
  57816. {
  57817. return Time (mouseDowns[0].time);
  57818. }
  57819. const Point<int> getLastMouseDownPosition() const throw()
  57820. {
  57821. return mouseDowns[0].position;
  57822. }
  57823. int getNumberOfMultipleClicks() const throw()
  57824. {
  57825. int numClicks = 0;
  57826. if (mouseDowns[0].time != 0)
  57827. {
  57828. if (! mouseMovedSignificantlySincePressed)
  57829. ++numClicks;
  57830. for (int i = 1; i < numElementsInArray (mouseDowns); ++i)
  57831. {
  57832. if (mouseDowns[0].time - mouseDowns[i].time < (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))
  57833. && abs (mouseDowns[0].position.getX() - mouseDowns[i].position.getX()) < 8
  57834. && abs (mouseDowns[0].position.getY() - mouseDowns[i].position.getY()) < 8)
  57835. {
  57836. ++numClicks;
  57837. }
  57838. else
  57839. {
  57840. break;
  57841. }
  57842. }
  57843. }
  57844. return numClicks;
  57845. }
  57846. bool hasMouseMovedSignificantlySincePressed() const throw()
  57847. {
  57848. return mouseMovedSignificantlySincePressed
  57849. || lastTime > mouseDowns[0].time + 300;
  57850. }
  57851. void triggerFakeMove()
  57852. {
  57853. triggerAsyncUpdate();
  57854. }
  57855. void handleAsyncUpdate()
  57856. {
  57857. setScreenPos (lastScreenPos, jmax (lastTime, Time::currentTimeMillis()), true);
  57858. }
  57859. void enableUnboundedMouseMovement (bool enable, bool keepCursorVisibleUntilOffscreen)
  57860. {
  57861. enable = enable && isDragging();
  57862. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  57863. if (enable != isUnboundedMouseModeOn)
  57864. {
  57865. if ((! enable) && ((! isCursorVisibleUntilOffscreen) || ! unboundedMouseOffset.isOrigin()))
  57866. {
  57867. // when released, return the mouse to within the component's bounds
  57868. Component* current = getComponentUnderMouse();
  57869. if (current != 0)
  57870. Desktop::setMousePosition (current->getScreenBounds()
  57871. .getConstrainedPoint (lastScreenPos));
  57872. }
  57873. isUnboundedMouseModeOn = enable;
  57874. unboundedMouseOffset = Point<int>();
  57875. revealCursor (true);
  57876. }
  57877. }
  57878. void handleUnboundedDrag (Component* current)
  57879. {
  57880. const Rectangle<int> screenArea (current->getParentMonitorArea().expanded (-2, -2));
  57881. if (! screenArea.contains (lastScreenPos))
  57882. {
  57883. const Point<int> componentCentre (current->getScreenBounds().getCentre());
  57884. unboundedMouseOffset += (lastScreenPos - componentCentre);
  57885. Desktop::setMousePosition (componentCentre);
  57886. }
  57887. else if (isCursorVisibleUntilOffscreen
  57888. && (! unboundedMouseOffset.isOrigin())
  57889. && screenArea.contains (lastScreenPos + unboundedMouseOffset))
  57890. {
  57891. Desktop::setMousePosition (lastScreenPos + unboundedMouseOffset);
  57892. unboundedMouseOffset = Point<int>();
  57893. }
  57894. }
  57895. void showMouseCursor (MouseCursor cursor, bool forcedUpdate)
  57896. {
  57897. if (isUnboundedMouseModeOn && ((! unboundedMouseOffset.isOrigin()) || ! isCursorVisibleUntilOffscreen))
  57898. {
  57899. cursor = MouseCursor::NoCursor;
  57900. forcedUpdate = true;
  57901. }
  57902. if (forcedUpdate || cursor.getHandle() != currentCursorHandle)
  57903. {
  57904. currentCursorHandle = cursor.getHandle();
  57905. cursor.showInWindow (getPeer());
  57906. }
  57907. }
  57908. void hideCursor()
  57909. {
  57910. showMouseCursor (MouseCursor::NoCursor, true);
  57911. }
  57912. void revealCursor (bool forcedUpdate)
  57913. {
  57914. MouseCursor mc (MouseCursor::NormalCursor);
  57915. Component* current = getComponentUnderMouse();
  57916. if (current != 0)
  57917. mc = current->getLookAndFeel().getMouseCursorFor (*current);
  57918. showMouseCursor (mc, forcedUpdate);
  57919. }
  57920. int index;
  57921. bool isMouseDevice;
  57922. Point<int> lastScreenPos;
  57923. ModifierKeys buttonState;
  57924. private:
  57925. MouseInputSource& source;
  57926. Component::SafePointer<Component> componentUnderMouse;
  57927. ComponentPeer* lastPeer;
  57928. Point<int> unboundedMouseOffset;
  57929. bool isUnboundedMouseModeOn, isCursorVisibleUntilOffscreen;
  57930. void* currentCursorHandle;
  57931. int mouseEventCounter;
  57932. struct RecentMouseDown
  57933. {
  57934. Point<int> position;
  57935. int64 time;
  57936. Component* component;
  57937. };
  57938. RecentMouseDown mouseDowns[4];
  57939. bool mouseMovedSignificantlySincePressed;
  57940. int64 lastTime;
  57941. void registerMouseDown (const Point<int>& screenPos, const int64 time, Component* const component) throw()
  57942. {
  57943. for (int i = numElementsInArray (mouseDowns); --i > 0;)
  57944. mouseDowns[i] = mouseDowns[i - 1];
  57945. mouseDowns[0].position = screenPos;
  57946. mouseDowns[0].time = time;
  57947. mouseDowns[0].component = component;
  57948. mouseMovedSignificantlySincePressed = false;
  57949. }
  57950. void registerMouseDrag (const Point<int>& screenPos) throw()
  57951. {
  57952. mouseMovedSignificantlySincePressed = mouseMovedSignificantlySincePressed
  57953. || mouseDowns[0].position.getDistanceFrom (screenPos) >= 4;
  57954. }
  57955. MouseInputSourceInternal (const MouseInputSourceInternal&);
  57956. MouseInputSourceInternal& operator= (const MouseInputSourceInternal&);
  57957. };
  57958. MouseInputSource::MouseInputSource (const int index, const bool isMouseDevice)
  57959. {
  57960. pimpl = new MouseInputSourceInternal (*this, index, isMouseDevice);
  57961. }
  57962. MouseInputSource::~MouseInputSource()
  57963. {
  57964. }
  57965. bool MouseInputSource::isMouse() const { return pimpl->isMouseDevice; }
  57966. bool MouseInputSource::isTouch() const { return ! isMouse(); }
  57967. bool MouseInputSource::canHover() const { return isMouse(); }
  57968. bool MouseInputSource::hasMouseWheel() const { return isMouse(); }
  57969. int MouseInputSource::getIndex() const { return pimpl->index; }
  57970. bool MouseInputSource::isDragging() const { return pimpl->isDragging(); }
  57971. const Point<int> MouseInputSource::getScreenPosition() const { return pimpl->getScreenPosition(); }
  57972. const ModifierKeys MouseInputSource::getCurrentModifiers() const { return pimpl->getCurrentModifiers(); }
  57973. Component* MouseInputSource::getComponentUnderMouse() const { return pimpl->getComponentUnderMouse(); }
  57974. void MouseInputSource::triggerFakeMove() const { pimpl->triggerFakeMove(); }
  57975. int MouseInputSource::getNumberOfMultipleClicks() const throw() { return pimpl->getNumberOfMultipleClicks(); }
  57976. const Time MouseInputSource::getLastMouseDownTime() const throw() { return pimpl->getLastMouseDownTime(); }
  57977. const Point<int> MouseInputSource::getLastMouseDownPosition() const throw() { return pimpl->getLastMouseDownPosition(); }
  57978. bool MouseInputSource::hasMouseMovedSignificantlySincePressed() const throw() { return pimpl->hasMouseMovedSignificantlySincePressed(); }
  57979. bool MouseInputSource::canDoUnboundedMovement() const throw() { return isMouse(); }
  57980. void MouseInputSource::enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen) { pimpl->enableUnboundedMouseMovement (isEnabled, keepCursorVisibleUntilOffscreen); }
  57981. bool MouseInputSource::hasMouseCursor() const throw() { return isMouse(); }
  57982. void MouseInputSource::showMouseCursor (const MouseCursor& cursor) { pimpl->showMouseCursor (cursor, false); }
  57983. void MouseInputSource::hideCursor() { pimpl->hideCursor(); }
  57984. void MouseInputSource::revealCursor() { pimpl->revealCursor (false); }
  57985. void MouseInputSource::forceMouseCursorUpdate() { pimpl->revealCursor (true); }
  57986. void MouseInputSource::handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& mods)
  57987. {
  57988. pimpl->handleEvent (peer, positionWithinPeer, time, mods.withOnlyMouseButtons());
  57989. }
  57990. void MouseInputSource::handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  57991. {
  57992. pimpl->handleWheel (peer, positionWithinPeer, time, x, y);
  57993. }
  57994. END_JUCE_NAMESPACE
  57995. /*** End of inlined file: juce_MouseInputSource.cpp ***/
  57996. /*** Start of inlined file: juce_MouseHoverDetector.cpp ***/
  57997. BEGIN_JUCE_NAMESPACE
  57998. MouseHoverDetector::MouseHoverDetector (const int hoverTimeMillisecs_)
  57999. : source (0),
  58000. hoverTimeMillisecs (hoverTimeMillisecs_),
  58001. hasJustHovered (false)
  58002. {
  58003. internalTimer.owner = this;
  58004. }
  58005. MouseHoverDetector::~MouseHoverDetector()
  58006. {
  58007. setHoverComponent (0);
  58008. }
  58009. void MouseHoverDetector::setHoverTimeMillisecs (const int newTimeInMillisecs)
  58010. {
  58011. hoverTimeMillisecs = newTimeInMillisecs;
  58012. }
  58013. void MouseHoverDetector::setHoverComponent (Component* const newSourceComponent)
  58014. {
  58015. if (source != newSourceComponent)
  58016. {
  58017. internalTimer.stopTimer();
  58018. hasJustHovered = false;
  58019. if (source != 0)
  58020. {
  58021. // ! you need to delete the hover detector before deleting its component
  58022. jassert (source->isValidComponent());
  58023. source->removeMouseListener (&internalTimer);
  58024. }
  58025. source = newSourceComponent;
  58026. if (newSourceComponent != 0)
  58027. newSourceComponent->addMouseListener (&internalTimer, false);
  58028. }
  58029. }
  58030. void MouseHoverDetector::hoverTimerCallback()
  58031. {
  58032. internalTimer.stopTimer();
  58033. if (source != 0)
  58034. {
  58035. const Point<int> pos (source->getMouseXYRelative());
  58036. if (source->reallyContains (pos.getX(), pos.getY(), false))
  58037. {
  58038. hasJustHovered = true;
  58039. mouseHovered (pos.getX(), pos.getY());
  58040. }
  58041. }
  58042. }
  58043. void MouseHoverDetector::checkJustHoveredCallback()
  58044. {
  58045. if (hasJustHovered)
  58046. {
  58047. hasJustHovered = false;
  58048. mouseMovedAfterHover();
  58049. }
  58050. }
  58051. void MouseHoverDetector::HoverDetectorInternal::timerCallback()
  58052. {
  58053. owner->hoverTimerCallback();
  58054. }
  58055. void MouseHoverDetector::HoverDetectorInternal::mouseEnter (const MouseEvent&)
  58056. {
  58057. stopTimer();
  58058. owner->checkJustHoveredCallback();
  58059. }
  58060. void MouseHoverDetector::HoverDetectorInternal::mouseExit (const MouseEvent&)
  58061. {
  58062. stopTimer();
  58063. owner->checkJustHoveredCallback();
  58064. }
  58065. void MouseHoverDetector::HoverDetectorInternal::mouseDown (const MouseEvent&)
  58066. {
  58067. stopTimer();
  58068. owner->checkJustHoveredCallback();
  58069. }
  58070. void MouseHoverDetector::HoverDetectorInternal::mouseUp (const MouseEvent&)
  58071. {
  58072. stopTimer();
  58073. owner->checkJustHoveredCallback();
  58074. }
  58075. void MouseHoverDetector::HoverDetectorInternal::mouseMove (const MouseEvent& e)
  58076. {
  58077. if (lastX != e.x || lastY != e.y) // to avoid fake mouse-moves setting it off
  58078. {
  58079. lastX = e.x;
  58080. lastY = e.y;
  58081. if (owner->source != 0)
  58082. startTimer (owner->hoverTimeMillisecs);
  58083. owner->checkJustHoveredCallback();
  58084. }
  58085. }
  58086. void MouseHoverDetector::HoverDetectorInternal::mouseWheelMove (const MouseEvent&, float, float)
  58087. {
  58088. stopTimer();
  58089. owner->checkJustHoveredCallback();
  58090. }
  58091. END_JUCE_NAMESPACE
  58092. /*** End of inlined file: juce_MouseHoverDetector.cpp ***/
  58093. /*** Start of inlined file: juce_MouseListener.cpp ***/
  58094. BEGIN_JUCE_NAMESPACE
  58095. void MouseListener::mouseEnter (const MouseEvent&)
  58096. {
  58097. }
  58098. void MouseListener::mouseExit (const MouseEvent&)
  58099. {
  58100. }
  58101. void MouseListener::mouseDown (const MouseEvent&)
  58102. {
  58103. }
  58104. void MouseListener::mouseUp (const MouseEvent&)
  58105. {
  58106. }
  58107. void MouseListener::mouseDrag (const MouseEvent&)
  58108. {
  58109. }
  58110. void MouseListener::mouseMove (const MouseEvent&)
  58111. {
  58112. }
  58113. void MouseListener::mouseDoubleClick (const MouseEvent&)
  58114. {
  58115. }
  58116. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  58117. {
  58118. }
  58119. END_JUCE_NAMESPACE
  58120. /*** End of inlined file: juce_MouseListener.cpp ***/
  58121. /*** Start of inlined file: juce_BooleanPropertyComponent.cpp ***/
  58122. BEGIN_JUCE_NAMESPACE
  58123. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  58124. const String& buttonTextWhenTrue,
  58125. const String& buttonTextWhenFalse)
  58126. : PropertyComponent (name),
  58127. onText (buttonTextWhenTrue),
  58128. offText (buttonTextWhenFalse)
  58129. {
  58130. addAndMakeVisible (&button);
  58131. button.setClickingTogglesState (false);
  58132. button.addButtonListener (this);
  58133. }
  58134. BooleanPropertyComponent::BooleanPropertyComponent (const Value& valueToControl,
  58135. const String& name,
  58136. const String& buttonText)
  58137. : PropertyComponent (name),
  58138. onText (buttonText),
  58139. offText (buttonText)
  58140. {
  58141. addAndMakeVisible (&button);
  58142. button.setClickingTogglesState (false);
  58143. button.setButtonText (buttonText);
  58144. button.getToggleStateValue().referTo (valueToControl);
  58145. button.setClickingTogglesState (true);
  58146. }
  58147. BooleanPropertyComponent::~BooleanPropertyComponent()
  58148. {
  58149. }
  58150. void BooleanPropertyComponent::setState (const bool newState)
  58151. {
  58152. button.setToggleState (newState, true);
  58153. }
  58154. bool BooleanPropertyComponent::getState() const
  58155. {
  58156. return button.getToggleState();
  58157. }
  58158. void BooleanPropertyComponent::paint (Graphics& g)
  58159. {
  58160. PropertyComponent::paint (g);
  58161. g.setColour (Colours::white);
  58162. g.fillRect (button.getBounds());
  58163. g.setColour (findColour (ComboBox::outlineColourId));
  58164. g.drawRect (button.getBounds());
  58165. }
  58166. void BooleanPropertyComponent::refresh()
  58167. {
  58168. button.setToggleState (getState(), false);
  58169. button.setButtonText (button.getToggleState() ? onText : offText);
  58170. }
  58171. void BooleanPropertyComponent::buttonClicked (Button*)
  58172. {
  58173. setState (! getState());
  58174. }
  58175. END_JUCE_NAMESPACE
  58176. /*** End of inlined file: juce_BooleanPropertyComponent.cpp ***/
  58177. /*** Start of inlined file: juce_ButtonPropertyComponent.cpp ***/
  58178. BEGIN_JUCE_NAMESPACE
  58179. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  58180. const bool triggerOnMouseDown)
  58181. : PropertyComponent (name)
  58182. {
  58183. addAndMakeVisible (&button);
  58184. button.setTriggeredOnMouseDown (triggerOnMouseDown);
  58185. button.addButtonListener (this);
  58186. }
  58187. ButtonPropertyComponent::~ButtonPropertyComponent()
  58188. {
  58189. }
  58190. void ButtonPropertyComponent::refresh()
  58191. {
  58192. button.setButtonText (getButtonText());
  58193. }
  58194. void ButtonPropertyComponent::buttonClicked (Button*)
  58195. {
  58196. buttonClicked();
  58197. }
  58198. END_JUCE_NAMESPACE
  58199. /*** End of inlined file: juce_ButtonPropertyComponent.cpp ***/
  58200. /*** Start of inlined file: juce_ChoicePropertyComponent.cpp ***/
  58201. BEGIN_JUCE_NAMESPACE
  58202. class ChoicePropertyComponent::RemapperValueSource : public Value::ValueSource,
  58203. public Value::Listener
  58204. {
  58205. public:
  58206. RemapperValueSource (const Value& sourceValue_, const Array<var>& mappings_)
  58207. : sourceValue (sourceValue_),
  58208. mappings (mappings_)
  58209. {
  58210. sourceValue.addListener (this);
  58211. }
  58212. ~RemapperValueSource() {}
  58213. const var getValue() const
  58214. {
  58215. return mappings.indexOf (sourceValue.getValue()) + 1;
  58216. }
  58217. void setValue (const var& newValue)
  58218. {
  58219. const var remappedVal (mappings [(int) newValue - 1]);
  58220. if (remappedVal != sourceValue)
  58221. sourceValue = remappedVal;
  58222. }
  58223. void valueChanged (Value&)
  58224. {
  58225. sendChangeMessage (true);
  58226. }
  58227. juce_UseDebuggingNewOperator
  58228. protected:
  58229. Value sourceValue;
  58230. Array<var> mappings;
  58231. RemapperValueSource (const RemapperValueSource&);
  58232. const RemapperValueSource& operator= (const RemapperValueSource&);
  58233. };
  58234. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  58235. : PropertyComponent (name),
  58236. isCustomClass (true)
  58237. {
  58238. }
  58239. ChoicePropertyComponent::ChoicePropertyComponent (const Value& valueToControl,
  58240. const String& name,
  58241. const StringArray& choices_,
  58242. const Array <var>& correspondingValues)
  58243. : PropertyComponent (name),
  58244. choices (choices_),
  58245. isCustomClass (false)
  58246. {
  58247. // The array of corresponding values must contain one value for each of the items in
  58248. // the choices array!
  58249. jassert (correspondingValues.size() == choices.size());
  58250. createComboBox();
  58251. comboBox.getSelectedIdAsValue().referTo (Value (new RemapperValueSource (valueToControl, correspondingValues)));
  58252. }
  58253. ChoicePropertyComponent::~ChoicePropertyComponent()
  58254. {
  58255. }
  58256. void ChoicePropertyComponent::createComboBox()
  58257. {
  58258. addAndMakeVisible (&comboBox);
  58259. for (int i = 0; i < choices.size(); ++i)
  58260. {
  58261. if (choices[i].isNotEmpty())
  58262. comboBox.addItem (choices[i], i + 1);
  58263. else
  58264. comboBox.addSeparator();
  58265. }
  58266. comboBox.setEditableText (false);
  58267. }
  58268. void ChoicePropertyComponent::setIndex (const int /*newIndex*/)
  58269. {
  58270. jassertfalse; // you need to override this method in your subclass!
  58271. }
  58272. int ChoicePropertyComponent::getIndex() const
  58273. {
  58274. jassertfalse; // you need to override this method in your subclass!
  58275. return -1;
  58276. }
  58277. const StringArray& ChoicePropertyComponent::getChoices() const
  58278. {
  58279. return choices;
  58280. }
  58281. void ChoicePropertyComponent::refresh()
  58282. {
  58283. if (isCustomClass)
  58284. {
  58285. if (! comboBox.isVisible())
  58286. {
  58287. createComboBox();
  58288. comboBox.addListener (this);
  58289. }
  58290. comboBox.setSelectedId (getIndex() + 1, true);
  58291. }
  58292. }
  58293. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  58294. {
  58295. if (isCustomClass)
  58296. {
  58297. const int newIndex = comboBox.getSelectedId() - 1;
  58298. if (newIndex != getIndex())
  58299. setIndex (newIndex);
  58300. }
  58301. }
  58302. END_JUCE_NAMESPACE
  58303. /*** End of inlined file: juce_ChoicePropertyComponent.cpp ***/
  58304. /*** Start of inlined file: juce_PropertyComponent.cpp ***/
  58305. BEGIN_JUCE_NAMESPACE
  58306. PropertyComponent::PropertyComponent (const String& name,
  58307. const int preferredHeight_)
  58308. : Component (name),
  58309. preferredHeight (preferredHeight_)
  58310. {
  58311. jassert (name.isNotEmpty());
  58312. }
  58313. PropertyComponent::~PropertyComponent()
  58314. {
  58315. }
  58316. void PropertyComponent::paint (Graphics& g)
  58317. {
  58318. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  58319. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  58320. }
  58321. void PropertyComponent::resized()
  58322. {
  58323. if (getNumChildComponents() > 0)
  58324. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  58325. }
  58326. void PropertyComponent::enablementChanged()
  58327. {
  58328. repaint();
  58329. }
  58330. END_JUCE_NAMESPACE
  58331. /*** End of inlined file: juce_PropertyComponent.cpp ***/
  58332. /*** Start of inlined file: juce_PropertyPanel.cpp ***/
  58333. BEGIN_JUCE_NAMESPACE
  58334. class PropertyPanel::PropertyHolderComponent : public Component
  58335. {
  58336. public:
  58337. PropertyHolderComponent()
  58338. {
  58339. }
  58340. ~PropertyHolderComponent()
  58341. {
  58342. deleteAllChildren();
  58343. }
  58344. void paint (Graphics&)
  58345. {
  58346. }
  58347. void updateLayout (int width);
  58348. void refreshAll() const;
  58349. private:
  58350. PropertyHolderComponent (const PropertyHolderComponent&);
  58351. PropertyHolderComponent& operator= (const PropertyHolderComponent&);
  58352. };
  58353. class PropertySectionComponent : public Component
  58354. {
  58355. public:
  58356. PropertySectionComponent (const String& sectionTitle,
  58357. const Array <PropertyComponent*>& newProperties,
  58358. const bool open)
  58359. : Component (sectionTitle),
  58360. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  58361. isOpen_ (open)
  58362. {
  58363. for (int i = newProperties.size(); --i >= 0;)
  58364. {
  58365. addAndMakeVisible (newProperties.getUnchecked(i));
  58366. newProperties.getUnchecked(i)->refresh();
  58367. }
  58368. }
  58369. ~PropertySectionComponent()
  58370. {
  58371. deleteAllChildren();
  58372. }
  58373. void paint (Graphics& g)
  58374. {
  58375. if (titleHeight > 0)
  58376. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  58377. }
  58378. void resized()
  58379. {
  58380. int y = titleHeight;
  58381. for (int i = getNumChildComponents(); --i >= 0;)
  58382. {
  58383. PropertyComponent* const pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58384. if (pec != 0)
  58385. {
  58386. const int prefH = pec->getPreferredHeight();
  58387. pec->setBounds (1, y, getWidth() - 2, prefH);
  58388. y += prefH;
  58389. }
  58390. }
  58391. }
  58392. int getPreferredHeight() const
  58393. {
  58394. int y = titleHeight;
  58395. if (isOpen())
  58396. {
  58397. for (int i = 0; i < getNumChildComponents(); ++i)
  58398. {
  58399. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58400. if (pec != 0)
  58401. y += pec->getPreferredHeight();
  58402. }
  58403. }
  58404. return y;
  58405. }
  58406. void setOpen (const bool open)
  58407. {
  58408. if (isOpen_ != open)
  58409. {
  58410. isOpen_ = open;
  58411. for (int i = 0; i < getNumChildComponents(); ++i)
  58412. {
  58413. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58414. if (pec != 0)
  58415. pec->setVisible (open);
  58416. }
  58417. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  58418. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  58419. if (pp != 0)
  58420. pp->resized();
  58421. }
  58422. }
  58423. bool isOpen() const
  58424. {
  58425. return isOpen_;
  58426. }
  58427. void refreshAll() const
  58428. {
  58429. for (int i = 0; i < getNumChildComponents(); ++i)
  58430. {
  58431. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58432. if (pec != 0)
  58433. pec->refresh();
  58434. }
  58435. }
  58436. void mouseDown (const MouseEvent&)
  58437. {
  58438. }
  58439. void mouseUp (const MouseEvent& e)
  58440. {
  58441. if (e.getMouseDownX() < titleHeight
  58442. && e.x < titleHeight
  58443. && e.y < titleHeight
  58444. && e.getNumberOfClicks() != 2)
  58445. {
  58446. setOpen (! isOpen());
  58447. }
  58448. }
  58449. void mouseDoubleClick (const MouseEvent& e)
  58450. {
  58451. if (e.y < titleHeight)
  58452. setOpen (! isOpen());
  58453. }
  58454. private:
  58455. int titleHeight;
  58456. bool isOpen_;
  58457. PropertySectionComponent (const PropertySectionComponent&);
  58458. PropertySectionComponent& operator= (const PropertySectionComponent&);
  58459. };
  58460. void PropertyPanel::PropertyHolderComponent::updateLayout (const int width)
  58461. {
  58462. int y = 0;
  58463. for (int i = getNumChildComponents(); --i >= 0;)
  58464. {
  58465. PropertySectionComponent* const section
  58466. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  58467. if (section != 0)
  58468. {
  58469. const int prefH = section->getPreferredHeight();
  58470. section->setBounds (0, y, width, prefH);
  58471. y += prefH;
  58472. }
  58473. }
  58474. setSize (width, y);
  58475. repaint();
  58476. }
  58477. void PropertyPanel::PropertyHolderComponent::refreshAll() const
  58478. {
  58479. for (int i = getNumChildComponents(); --i >= 0;)
  58480. {
  58481. PropertySectionComponent* const section
  58482. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  58483. if (section != 0)
  58484. section->refreshAll();
  58485. }
  58486. }
  58487. PropertyPanel::PropertyPanel()
  58488. {
  58489. messageWhenEmpty = TRANS("(nothing selected)");
  58490. addAndMakeVisible (&viewport);
  58491. viewport.setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  58492. viewport.setFocusContainer (true);
  58493. }
  58494. PropertyPanel::~PropertyPanel()
  58495. {
  58496. clear();
  58497. }
  58498. void PropertyPanel::paint (Graphics& g)
  58499. {
  58500. if (propertyHolderComponent->getNumChildComponents() == 0)
  58501. {
  58502. g.setColour (Colours::black.withAlpha (0.5f));
  58503. g.setFont (14.0f);
  58504. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  58505. Justification::centred, true);
  58506. }
  58507. }
  58508. void PropertyPanel::resized()
  58509. {
  58510. viewport.setBounds (getLocalBounds());
  58511. updatePropHolderLayout();
  58512. }
  58513. void PropertyPanel::clear()
  58514. {
  58515. if (propertyHolderComponent->getNumChildComponents() > 0)
  58516. {
  58517. propertyHolderComponent->deleteAllChildren();
  58518. repaint();
  58519. }
  58520. }
  58521. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  58522. {
  58523. if (propertyHolderComponent->getNumChildComponents() == 0)
  58524. repaint();
  58525. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (String::empty,
  58526. newProperties,
  58527. true), 0);
  58528. updatePropHolderLayout();
  58529. }
  58530. void PropertyPanel::addSection (const String& sectionTitle,
  58531. const Array <PropertyComponent*>& newProperties,
  58532. const bool shouldBeOpen)
  58533. {
  58534. jassert (sectionTitle.isNotEmpty());
  58535. if (propertyHolderComponent->getNumChildComponents() == 0)
  58536. repaint();
  58537. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (sectionTitle,
  58538. newProperties,
  58539. shouldBeOpen), 0);
  58540. updatePropHolderLayout();
  58541. }
  58542. void PropertyPanel::updatePropHolderLayout() const
  58543. {
  58544. const int maxWidth = viewport.getMaximumVisibleWidth();
  58545. propertyHolderComponent->updateLayout (maxWidth);
  58546. const int newMaxWidth = viewport.getMaximumVisibleWidth();
  58547. if (maxWidth != newMaxWidth)
  58548. {
  58549. // need to do this twice because of scrollbars changing the size, etc.
  58550. propertyHolderComponent->updateLayout (newMaxWidth);
  58551. }
  58552. }
  58553. void PropertyPanel::refreshAll() const
  58554. {
  58555. propertyHolderComponent->refreshAll();
  58556. }
  58557. const StringArray PropertyPanel::getSectionNames() const
  58558. {
  58559. StringArray s;
  58560. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58561. {
  58562. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58563. if (section != 0 && section->getName().isNotEmpty())
  58564. s.add (section->getName());
  58565. }
  58566. return s;
  58567. }
  58568. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  58569. {
  58570. int index = 0;
  58571. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58572. {
  58573. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58574. if (section != 0 && section->getName().isNotEmpty())
  58575. {
  58576. if (index == sectionIndex)
  58577. return section->isOpen();
  58578. ++index;
  58579. }
  58580. }
  58581. return false;
  58582. }
  58583. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  58584. {
  58585. int index = 0;
  58586. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58587. {
  58588. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58589. if (section != 0 && section->getName().isNotEmpty())
  58590. {
  58591. if (index == sectionIndex)
  58592. {
  58593. section->setOpen (shouldBeOpen);
  58594. break;
  58595. }
  58596. ++index;
  58597. }
  58598. }
  58599. }
  58600. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  58601. {
  58602. int index = 0;
  58603. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58604. {
  58605. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58606. if (section != 0 && section->getName().isNotEmpty())
  58607. {
  58608. if (index == sectionIndex)
  58609. {
  58610. section->setEnabled (shouldBeEnabled);
  58611. break;
  58612. }
  58613. ++index;
  58614. }
  58615. }
  58616. }
  58617. XmlElement* PropertyPanel::getOpennessState() const
  58618. {
  58619. XmlElement* const xml = new XmlElement ("PROPERTYPANELSTATE");
  58620. xml->setAttribute ("scrollPos", viewport.getViewPositionY());
  58621. const StringArray sections (getSectionNames());
  58622. for (int i = 0; i < sections.size(); ++i)
  58623. {
  58624. if (sections[i].isNotEmpty())
  58625. {
  58626. XmlElement* const e = xml->createNewChildElement ("SECTION");
  58627. e->setAttribute ("name", sections[i]);
  58628. e->setAttribute ("open", isSectionOpen (i) ? 1 : 0);
  58629. }
  58630. }
  58631. return xml;
  58632. }
  58633. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  58634. {
  58635. if (xml.hasTagName ("PROPERTYPANELSTATE"))
  58636. {
  58637. const StringArray sections (getSectionNames());
  58638. forEachXmlChildElementWithTagName (xml, e, "SECTION")
  58639. {
  58640. setSectionOpen (sections.indexOf (e->getStringAttribute ("name")),
  58641. e->getBoolAttribute ("open"));
  58642. }
  58643. viewport.setViewPosition (viewport.getViewPositionX(),
  58644. xml.getIntAttribute ("scrollPos", viewport.getViewPositionY()));
  58645. }
  58646. }
  58647. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  58648. {
  58649. if (messageWhenEmpty != newMessage)
  58650. {
  58651. messageWhenEmpty = newMessage;
  58652. repaint();
  58653. }
  58654. }
  58655. const String& PropertyPanel::getMessageWhenEmpty() const
  58656. {
  58657. return messageWhenEmpty;
  58658. }
  58659. END_JUCE_NAMESPACE
  58660. /*** End of inlined file: juce_PropertyPanel.cpp ***/
  58661. /*** Start of inlined file: juce_SliderPropertyComponent.cpp ***/
  58662. BEGIN_JUCE_NAMESPACE
  58663. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  58664. const double rangeMin,
  58665. const double rangeMax,
  58666. const double interval,
  58667. const double skewFactor)
  58668. : PropertyComponent (name)
  58669. {
  58670. addAndMakeVisible (&slider);
  58671. slider.setRange (rangeMin, rangeMax, interval);
  58672. slider.setSkewFactor (skewFactor);
  58673. slider.setSliderStyle (Slider::LinearBar);
  58674. slider.addListener (this);
  58675. }
  58676. SliderPropertyComponent::SliderPropertyComponent (const Value& valueToControl,
  58677. const String& name,
  58678. const double rangeMin,
  58679. const double rangeMax,
  58680. const double interval,
  58681. const double skewFactor)
  58682. : PropertyComponent (name)
  58683. {
  58684. addAndMakeVisible (&slider);
  58685. slider.setRange (rangeMin, rangeMax, interval);
  58686. slider.setSkewFactor (skewFactor);
  58687. slider.setSliderStyle (Slider::LinearBar);
  58688. slider.getValueObject().referTo (valueToControl);
  58689. }
  58690. SliderPropertyComponent::~SliderPropertyComponent()
  58691. {
  58692. }
  58693. void SliderPropertyComponent::setValue (const double /*newValue*/)
  58694. {
  58695. }
  58696. double SliderPropertyComponent::getValue() const
  58697. {
  58698. return slider.getValue();
  58699. }
  58700. void SliderPropertyComponent::refresh()
  58701. {
  58702. slider.setValue (getValue(), false);
  58703. }
  58704. void SliderPropertyComponent::sliderValueChanged (Slider*)
  58705. {
  58706. if (getValue() != slider.getValue())
  58707. setValue (slider.getValue());
  58708. }
  58709. END_JUCE_NAMESPACE
  58710. /*** End of inlined file: juce_SliderPropertyComponent.cpp ***/
  58711. /*** Start of inlined file: juce_TextPropertyComponent.cpp ***/
  58712. BEGIN_JUCE_NAMESPACE
  58713. class TextPropLabel : public Label
  58714. {
  58715. TextPropertyComponent& owner;
  58716. int maxChars;
  58717. bool isMultiline;
  58718. public:
  58719. TextPropLabel (TextPropertyComponent& owner_,
  58720. const int maxChars_, const bool isMultiline_)
  58721. : Label (String::empty, String::empty),
  58722. owner (owner_),
  58723. maxChars (maxChars_),
  58724. isMultiline (isMultiline_)
  58725. {
  58726. setEditable (true, true, false);
  58727. setColour (backgroundColourId, Colours::white);
  58728. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  58729. }
  58730. ~TextPropLabel()
  58731. {
  58732. }
  58733. TextEditor* createEditorComponent()
  58734. {
  58735. TextEditor* const textEditor = Label::createEditorComponent();
  58736. textEditor->setInputRestrictions (maxChars);
  58737. if (isMultiline)
  58738. {
  58739. textEditor->setMultiLine (true, true);
  58740. textEditor->setReturnKeyStartsNewLine (true);
  58741. }
  58742. return textEditor;
  58743. }
  58744. void textWasEdited()
  58745. {
  58746. owner.textWasEdited();
  58747. }
  58748. };
  58749. TextPropertyComponent::TextPropertyComponent (const String& name,
  58750. const int maxNumChars,
  58751. const bool isMultiLine)
  58752. : PropertyComponent (name)
  58753. {
  58754. createEditor (maxNumChars, isMultiLine);
  58755. }
  58756. TextPropertyComponent::TextPropertyComponent (const Value& valueToControl,
  58757. const String& name,
  58758. const int maxNumChars,
  58759. const bool isMultiLine)
  58760. : PropertyComponent (name)
  58761. {
  58762. createEditor (maxNumChars, isMultiLine);
  58763. textEditor->getTextValue().referTo (valueToControl);
  58764. }
  58765. TextPropertyComponent::~TextPropertyComponent()
  58766. {
  58767. deleteAllChildren();
  58768. }
  58769. void TextPropertyComponent::setText (const String& newText)
  58770. {
  58771. textEditor->setText (newText, true);
  58772. }
  58773. const String TextPropertyComponent::getText() const
  58774. {
  58775. return textEditor->getText();
  58776. }
  58777. void TextPropertyComponent::createEditor (const int maxNumChars, const bool isMultiLine)
  58778. {
  58779. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  58780. if (isMultiLine)
  58781. {
  58782. textEditor->setJustificationType (Justification::topLeft);
  58783. preferredHeight = 120;
  58784. }
  58785. }
  58786. void TextPropertyComponent::refresh()
  58787. {
  58788. textEditor->setText (getText(), false);
  58789. }
  58790. void TextPropertyComponent::textWasEdited()
  58791. {
  58792. const String newText (textEditor->getText());
  58793. if (getText() != newText)
  58794. setText (newText);
  58795. }
  58796. END_JUCE_NAMESPACE
  58797. /*** End of inlined file: juce_TextPropertyComponent.cpp ***/
  58798. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  58799. BEGIN_JUCE_NAMESPACE
  58800. class SimpleDeviceManagerInputLevelMeter : public Component,
  58801. public Timer
  58802. {
  58803. public:
  58804. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  58805. : manager (manager_),
  58806. level (0)
  58807. {
  58808. startTimer (50);
  58809. manager->enableInputLevelMeasurement (true);
  58810. }
  58811. ~SimpleDeviceManagerInputLevelMeter()
  58812. {
  58813. manager->enableInputLevelMeasurement (false);
  58814. }
  58815. void timerCallback()
  58816. {
  58817. const float newLevel = (float) manager->getCurrentInputLevel();
  58818. if (std::abs (level - newLevel) > 0.005f)
  58819. {
  58820. level = newLevel;
  58821. repaint();
  58822. }
  58823. }
  58824. void paint (Graphics& g)
  58825. {
  58826. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(),
  58827. (float) exp (log (level) / 3.0)); // (add a bit of a skew to make the level more obvious)
  58828. }
  58829. private:
  58830. AudioDeviceManager* const manager;
  58831. float level;
  58832. SimpleDeviceManagerInputLevelMeter (const SimpleDeviceManagerInputLevelMeter&);
  58833. SimpleDeviceManagerInputLevelMeter& operator= (const SimpleDeviceManagerInputLevelMeter&);
  58834. };
  58835. class AudioDeviceSelectorComponent::MidiInputSelectorComponentListBox : public ListBox,
  58836. public ListBoxModel
  58837. {
  58838. public:
  58839. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  58840. const String& noItemsMessage_,
  58841. const int minNumber_,
  58842. const int maxNumber_)
  58843. : ListBox (String::empty, 0),
  58844. deviceManager (deviceManager_),
  58845. noItemsMessage (noItemsMessage_),
  58846. minNumber (minNumber_),
  58847. maxNumber (maxNumber_)
  58848. {
  58849. items = MidiInput::getDevices();
  58850. setModel (this);
  58851. setOutlineThickness (1);
  58852. }
  58853. ~MidiInputSelectorComponentListBox()
  58854. {
  58855. }
  58856. int getNumRows()
  58857. {
  58858. return items.size();
  58859. }
  58860. void paintListBoxItem (int row,
  58861. Graphics& g,
  58862. int width, int height,
  58863. bool rowIsSelected)
  58864. {
  58865. if (((unsigned int) row) < (unsigned int) items.size())
  58866. {
  58867. if (rowIsSelected)
  58868. g.fillAll (findColour (TextEditor::highlightColourId)
  58869. .withMultipliedAlpha (0.3f));
  58870. const String item (items [row]);
  58871. bool enabled = deviceManager.isMidiInputEnabled (item);
  58872. const int x = getTickX();
  58873. const float tickW = height * 0.75f;
  58874. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58875. enabled, true, true, false);
  58876. g.setFont (height * 0.6f);
  58877. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58878. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58879. }
  58880. }
  58881. void listBoxItemClicked (int row, const MouseEvent& e)
  58882. {
  58883. selectRow (row);
  58884. if (e.x < getTickX())
  58885. flipEnablement (row);
  58886. }
  58887. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  58888. {
  58889. flipEnablement (row);
  58890. }
  58891. void returnKeyPressed (int row)
  58892. {
  58893. flipEnablement (row);
  58894. }
  58895. void paint (Graphics& g)
  58896. {
  58897. ListBox::paint (g);
  58898. if (items.size() == 0)
  58899. {
  58900. g.setColour (Colours::grey);
  58901. g.setFont (13.0f);
  58902. g.drawText (noItemsMessage,
  58903. 0, 0, getWidth(), getHeight() / 2,
  58904. Justification::centred, true);
  58905. }
  58906. }
  58907. int getBestHeight (const int preferredHeight)
  58908. {
  58909. const int extra = getOutlineThickness() * 2;
  58910. return jmax (getRowHeight() * 2 + extra,
  58911. jmin (getRowHeight() * getNumRows() + extra,
  58912. preferredHeight));
  58913. }
  58914. juce_UseDebuggingNewOperator
  58915. private:
  58916. AudioDeviceManager& deviceManager;
  58917. const String noItemsMessage;
  58918. StringArray items;
  58919. int minNumber, maxNumber;
  58920. void flipEnablement (const int row)
  58921. {
  58922. if (((unsigned int) row) < (unsigned int) items.size())
  58923. {
  58924. const String item (items [row]);
  58925. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  58926. }
  58927. }
  58928. int getTickX() const
  58929. {
  58930. return getRowHeight() + 5;
  58931. }
  58932. MidiInputSelectorComponentListBox (const MidiInputSelectorComponentListBox&);
  58933. MidiInputSelectorComponentListBox& operator= (const MidiInputSelectorComponentListBox&);
  58934. };
  58935. class AudioDeviceSettingsPanel : public Component,
  58936. public ChangeListener,
  58937. public ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  58938. public ButtonListener
  58939. {
  58940. public:
  58941. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  58942. AudioIODeviceType::DeviceSetupDetails& setup_,
  58943. const bool hideAdvancedOptionsWithButton)
  58944. : type (type_),
  58945. setup (setup_)
  58946. {
  58947. if (hideAdvancedOptionsWithButton)
  58948. {
  58949. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  58950. showAdvancedSettingsButton->addButtonListener (this);
  58951. }
  58952. type->scanForDevices();
  58953. setup.manager->addChangeListener (this);
  58954. changeListenerCallback (0);
  58955. }
  58956. ~AudioDeviceSettingsPanel()
  58957. {
  58958. setup.manager->removeChangeListener (this);
  58959. }
  58960. void resized()
  58961. {
  58962. const int lx = proportionOfWidth (0.35f);
  58963. const int w = proportionOfWidth (0.4f);
  58964. const int h = 24;
  58965. const int space = 6;
  58966. const int dh = h + space;
  58967. int y = 0;
  58968. if (outputDeviceDropDown != 0)
  58969. {
  58970. outputDeviceDropDown->setBounds (lx, y, w, h);
  58971. if (testButton != 0)
  58972. testButton->setBounds (proportionOfWidth (0.77f),
  58973. outputDeviceDropDown->getY(),
  58974. proportionOfWidth (0.18f),
  58975. h);
  58976. y += dh;
  58977. }
  58978. if (inputDeviceDropDown != 0)
  58979. {
  58980. inputDeviceDropDown->setBounds (lx, y, w, h);
  58981. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  58982. inputDeviceDropDown->getY(),
  58983. proportionOfWidth (0.18f),
  58984. h);
  58985. y += dh;
  58986. }
  58987. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  58988. if (outputChanList != 0)
  58989. {
  58990. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  58991. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58992. y += bh + space;
  58993. }
  58994. if (inputChanList != 0)
  58995. {
  58996. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  58997. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  58998. y += bh + space;
  58999. }
  59000. y += space * 2;
  59001. if (showAdvancedSettingsButton != 0)
  59002. {
  59003. showAdvancedSettingsButton->changeWidthToFitText (h);
  59004. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  59005. }
  59006. if (sampleRateDropDown != 0)
  59007. {
  59008. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  59009. || ! showAdvancedSettingsButton->isVisible());
  59010. sampleRateDropDown->setBounds (lx, y, w, h);
  59011. y += dh;
  59012. }
  59013. if (bufferSizeDropDown != 0)
  59014. {
  59015. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  59016. || ! showAdvancedSettingsButton->isVisible());
  59017. bufferSizeDropDown->setBounds (lx, y, w, h);
  59018. y += dh;
  59019. }
  59020. if (showUIButton != 0)
  59021. {
  59022. showUIButton->setVisible (showAdvancedSettingsButton == 0
  59023. || ! showAdvancedSettingsButton->isVisible());
  59024. showUIButton->changeWidthToFitText (h);
  59025. showUIButton->setTopLeftPosition (lx, y);
  59026. }
  59027. }
  59028. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  59029. {
  59030. if (comboBoxThatHasChanged == 0)
  59031. return;
  59032. AudioDeviceManager::AudioDeviceSetup config;
  59033. setup.manager->getAudioDeviceSetup (config);
  59034. String error;
  59035. if (comboBoxThatHasChanged == outputDeviceDropDown
  59036. || comboBoxThatHasChanged == inputDeviceDropDown)
  59037. {
  59038. if (outputDeviceDropDown != 0)
  59039. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  59040. : outputDeviceDropDown->getText();
  59041. if (inputDeviceDropDown != 0)
  59042. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  59043. : inputDeviceDropDown->getText();
  59044. if (! type->hasSeparateInputsAndOutputs())
  59045. config.inputDeviceName = config.outputDeviceName;
  59046. if (comboBoxThatHasChanged == inputDeviceDropDown)
  59047. config.useDefaultInputChannels = true;
  59048. else
  59049. config.useDefaultOutputChannels = true;
  59050. error = setup.manager->setAudioDeviceSetup (config, true);
  59051. showCorrectDeviceName (inputDeviceDropDown, true);
  59052. showCorrectDeviceName (outputDeviceDropDown, false);
  59053. updateControlPanelButton();
  59054. resized();
  59055. }
  59056. else if (comboBoxThatHasChanged == sampleRateDropDown)
  59057. {
  59058. if (sampleRateDropDown->getSelectedId() > 0)
  59059. {
  59060. config.sampleRate = sampleRateDropDown->getSelectedId();
  59061. error = setup.manager->setAudioDeviceSetup (config, true);
  59062. }
  59063. }
  59064. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  59065. {
  59066. if (bufferSizeDropDown->getSelectedId() > 0)
  59067. {
  59068. config.bufferSize = bufferSizeDropDown->getSelectedId();
  59069. error = setup.manager->setAudioDeviceSetup (config, true);
  59070. }
  59071. }
  59072. if (error.isNotEmpty())
  59073. {
  59074. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  59075. "Error when trying to open audio device!",
  59076. error);
  59077. }
  59078. }
  59079. void buttonClicked (Button* button)
  59080. {
  59081. if (button == showAdvancedSettingsButton)
  59082. {
  59083. showAdvancedSettingsButton->setVisible (false);
  59084. resized();
  59085. }
  59086. else if (button == showUIButton)
  59087. {
  59088. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  59089. if (device != 0 && device->showControlPanel())
  59090. {
  59091. setup.manager->closeAudioDevice();
  59092. setup.manager->restartLastAudioDevice();
  59093. getTopLevelComponent()->toFront (true);
  59094. }
  59095. }
  59096. else if (button == testButton && testButton != 0)
  59097. {
  59098. setup.manager->playTestSound();
  59099. }
  59100. }
  59101. void updateControlPanelButton()
  59102. {
  59103. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  59104. showUIButton = 0;
  59105. if (currentDevice != 0 && currentDevice->hasControlPanel())
  59106. {
  59107. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  59108. TRANS ("opens the device's own control panel")));
  59109. showUIButton->addButtonListener (this);
  59110. }
  59111. resized();
  59112. }
  59113. void changeListenerCallback (void*)
  59114. {
  59115. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  59116. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  59117. {
  59118. if (outputDeviceDropDown == 0)
  59119. {
  59120. outputDeviceDropDown = new ComboBox (String::empty);
  59121. outputDeviceDropDown->addListener (this);
  59122. addAndMakeVisible (outputDeviceDropDown);
  59123. outputDeviceLabel = new Label (String::empty,
  59124. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  59125. : TRANS ("device:"));
  59126. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  59127. if (setup.maxNumOutputChannels > 0)
  59128. {
  59129. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  59130. testButton->addButtonListener (this);
  59131. }
  59132. }
  59133. addNamesToDeviceBox (*outputDeviceDropDown, false);
  59134. }
  59135. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  59136. {
  59137. if (inputDeviceDropDown == 0)
  59138. {
  59139. inputDeviceDropDown = new ComboBox (String::empty);
  59140. inputDeviceDropDown->addListener (this);
  59141. addAndMakeVisible (inputDeviceDropDown);
  59142. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  59143. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  59144. addAndMakeVisible (inputLevelMeter
  59145. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  59146. }
  59147. addNamesToDeviceBox (*inputDeviceDropDown, true);
  59148. }
  59149. updateControlPanelButton();
  59150. showCorrectDeviceName (inputDeviceDropDown, true);
  59151. showCorrectDeviceName (outputDeviceDropDown, false);
  59152. if (currentDevice != 0)
  59153. {
  59154. if (setup.maxNumOutputChannels > 0
  59155. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  59156. {
  59157. if (outputChanList == 0)
  59158. {
  59159. addAndMakeVisible (outputChanList
  59160. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  59161. TRANS ("(no audio output channels found)")));
  59162. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  59163. outputChanLabel->attachToComponent (outputChanList, true);
  59164. }
  59165. outputChanList->refresh();
  59166. }
  59167. else
  59168. {
  59169. outputChanLabel = 0;
  59170. outputChanList = 0;
  59171. }
  59172. if (setup.maxNumInputChannels > 0
  59173. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  59174. {
  59175. if (inputChanList == 0)
  59176. {
  59177. addAndMakeVisible (inputChanList
  59178. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  59179. TRANS ("(no audio input channels found)")));
  59180. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  59181. inputChanLabel->attachToComponent (inputChanList, true);
  59182. }
  59183. inputChanList->refresh();
  59184. }
  59185. else
  59186. {
  59187. inputChanLabel = 0;
  59188. inputChanList = 0;
  59189. }
  59190. // sample rate..
  59191. {
  59192. if (sampleRateDropDown == 0)
  59193. {
  59194. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  59195. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  59196. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  59197. }
  59198. else
  59199. {
  59200. sampleRateDropDown->clear();
  59201. sampleRateDropDown->removeListener (this);
  59202. }
  59203. const int numRates = currentDevice->getNumSampleRates();
  59204. for (int i = 0; i < numRates; ++i)
  59205. {
  59206. const int rate = roundToInt (currentDevice->getSampleRate (i));
  59207. sampleRateDropDown->addItem (String (rate) + " Hz", rate);
  59208. }
  59209. sampleRateDropDown->setSelectedId (roundToInt (currentDevice->getCurrentSampleRate()), true);
  59210. sampleRateDropDown->addListener (this);
  59211. }
  59212. // buffer size
  59213. {
  59214. if (bufferSizeDropDown == 0)
  59215. {
  59216. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  59217. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  59218. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  59219. }
  59220. else
  59221. {
  59222. bufferSizeDropDown->clear();
  59223. bufferSizeDropDown->removeListener (this);
  59224. }
  59225. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  59226. double currentRate = currentDevice->getCurrentSampleRate();
  59227. if (currentRate == 0)
  59228. currentRate = 48000.0;
  59229. for (int i = 0; i < numBufferSizes; ++i)
  59230. {
  59231. const int bs = currentDevice->getBufferSizeSamples (i);
  59232. bufferSizeDropDown->addItem (String (bs)
  59233. + " samples ("
  59234. + String (bs * 1000.0 / currentRate, 1)
  59235. + " ms)",
  59236. bs);
  59237. }
  59238. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  59239. bufferSizeDropDown->addListener (this);
  59240. }
  59241. }
  59242. else
  59243. {
  59244. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  59245. sampleRateLabel = 0;
  59246. bufferSizeLabel = 0;
  59247. sampleRateDropDown = 0;
  59248. bufferSizeDropDown = 0;
  59249. if (outputDeviceDropDown != 0)
  59250. outputDeviceDropDown->setSelectedId (-1, true);
  59251. if (inputDeviceDropDown != 0)
  59252. inputDeviceDropDown->setSelectedId (-1, true);
  59253. }
  59254. resized();
  59255. setSize (getWidth(), getLowestY() + 4);
  59256. }
  59257. private:
  59258. AudioIODeviceType* const type;
  59259. const AudioIODeviceType::DeviceSetupDetails setup;
  59260. ScopedPointer<ComboBox> outputDeviceDropDown, inputDeviceDropDown, sampleRateDropDown, bufferSizeDropDown;
  59261. ScopedPointer<Label> outputDeviceLabel, inputDeviceLabel, sampleRateLabel, bufferSizeLabel, inputChanLabel, outputChanLabel;
  59262. ScopedPointer<TextButton> testButton;
  59263. ScopedPointer<Component> inputLevelMeter;
  59264. ScopedPointer<TextButton> showUIButton, showAdvancedSettingsButton;
  59265. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  59266. {
  59267. if (box != 0)
  59268. {
  59269. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  59270. const int index = type->getIndexOfDevice (currentDevice, isInput);
  59271. box->setSelectedId (index + 1, true);
  59272. if (testButton != 0 && ! isInput)
  59273. testButton->setEnabled (index >= 0);
  59274. }
  59275. }
  59276. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  59277. {
  59278. const StringArray devs (type->getDeviceNames (isInputs));
  59279. combo.clear (true);
  59280. for (int i = 0; i < devs.size(); ++i)
  59281. combo.addItem (devs[i], i + 1);
  59282. combo.addItem (TRANS("<< none >>"), -1);
  59283. combo.setSelectedId (-1, true);
  59284. }
  59285. int getLowestY() const
  59286. {
  59287. int y = 0;
  59288. for (int i = getNumChildComponents(); --i >= 0;)
  59289. y = jmax (y, getChildComponent (i)->getBottom());
  59290. return y;
  59291. }
  59292. public:
  59293. class ChannelSelectorListBox : public ListBox,
  59294. public ListBoxModel
  59295. {
  59296. public:
  59297. enum BoxType
  59298. {
  59299. audioInputType,
  59300. audioOutputType
  59301. };
  59302. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  59303. const BoxType type_,
  59304. const String& noItemsMessage_)
  59305. : ListBox (String::empty, 0),
  59306. setup (setup_),
  59307. type (type_),
  59308. noItemsMessage (noItemsMessage_)
  59309. {
  59310. refresh();
  59311. setModel (this);
  59312. setOutlineThickness (1);
  59313. }
  59314. ~ChannelSelectorListBox()
  59315. {
  59316. }
  59317. void refresh()
  59318. {
  59319. items.clear();
  59320. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  59321. if (currentDevice != 0)
  59322. {
  59323. if (type == audioInputType)
  59324. items = currentDevice->getInputChannelNames();
  59325. else if (type == audioOutputType)
  59326. items = currentDevice->getOutputChannelNames();
  59327. if (setup.useStereoPairs)
  59328. {
  59329. StringArray pairs;
  59330. for (int i = 0; i < items.size(); i += 2)
  59331. {
  59332. const String name (items[i]);
  59333. const String name2 (items[i + 1]);
  59334. String commonBit;
  59335. for (int j = 0; j < name.length(); ++j)
  59336. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  59337. commonBit = name.substring (0, j);
  59338. // Make sure we only split the name at a space, because otherwise, things
  59339. // like "input 11" + "input 12" would become "input 11 + 2"
  59340. while (commonBit.isNotEmpty() && ! CharacterFunctions::isWhitespace (commonBit.getLastCharacter()))
  59341. commonBit = commonBit.dropLastCharacters (1);
  59342. pairs.add (name.trim() + " + " + name2.substring (commonBit.length()).trim());
  59343. }
  59344. items = pairs;
  59345. }
  59346. }
  59347. updateContent();
  59348. repaint();
  59349. }
  59350. int getNumRows()
  59351. {
  59352. return items.size();
  59353. }
  59354. void paintListBoxItem (int row,
  59355. Graphics& g,
  59356. int width, int height,
  59357. bool rowIsSelected)
  59358. {
  59359. if (((unsigned int) row) < (unsigned int) items.size())
  59360. {
  59361. if (rowIsSelected)
  59362. g.fillAll (findColour (TextEditor::highlightColourId)
  59363. .withMultipliedAlpha (0.3f));
  59364. const String item (items [row]);
  59365. bool enabled = false;
  59366. AudioDeviceManager::AudioDeviceSetup config;
  59367. setup.manager->getAudioDeviceSetup (config);
  59368. if (setup.useStereoPairs)
  59369. {
  59370. if (type == audioInputType)
  59371. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  59372. else if (type == audioOutputType)
  59373. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  59374. }
  59375. else
  59376. {
  59377. if (type == audioInputType)
  59378. enabled = config.inputChannels [row];
  59379. else if (type == audioOutputType)
  59380. enabled = config.outputChannels [row];
  59381. }
  59382. const int x = getTickX();
  59383. const float tickW = height * 0.75f;
  59384. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  59385. enabled, true, true, false);
  59386. g.setFont (height * 0.6f);
  59387. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  59388. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  59389. }
  59390. }
  59391. void listBoxItemClicked (int row, const MouseEvent& e)
  59392. {
  59393. selectRow (row);
  59394. if (e.x < getTickX())
  59395. flipEnablement (row);
  59396. }
  59397. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  59398. {
  59399. flipEnablement (row);
  59400. }
  59401. void returnKeyPressed (int row)
  59402. {
  59403. flipEnablement (row);
  59404. }
  59405. void paint (Graphics& g)
  59406. {
  59407. ListBox::paint (g);
  59408. if (items.size() == 0)
  59409. {
  59410. g.setColour (Colours::grey);
  59411. g.setFont (13.0f);
  59412. g.drawText (noItemsMessage,
  59413. 0, 0, getWidth(), getHeight() / 2,
  59414. Justification::centred, true);
  59415. }
  59416. }
  59417. int getBestHeight (int maxHeight)
  59418. {
  59419. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  59420. getNumRows())
  59421. + getOutlineThickness() * 2;
  59422. }
  59423. juce_UseDebuggingNewOperator
  59424. private:
  59425. const AudioIODeviceType::DeviceSetupDetails setup;
  59426. const BoxType type;
  59427. const String noItemsMessage;
  59428. StringArray items;
  59429. void flipEnablement (const int row)
  59430. {
  59431. jassert (type == audioInputType || type == audioOutputType);
  59432. if (((unsigned int) row) < (unsigned int) items.size())
  59433. {
  59434. AudioDeviceManager::AudioDeviceSetup config;
  59435. setup.manager->getAudioDeviceSetup (config);
  59436. if (setup.useStereoPairs)
  59437. {
  59438. BigInteger bits;
  59439. BigInteger& original = (type == audioInputType ? config.inputChannels
  59440. : config.outputChannels);
  59441. int i;
  59442. for (i = 0; i < 256; i += 2)
  59443. bits.setBit (i / 2, original [i] || original [i + 1]);
  59444. if (type == audioInputType)
  59445. {
  59446. config.useDefaultInputChannels = false;
  59447. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  59448. }
  59449. else
  59450. {
  59451. config.useDefaultOutputChannels = false;
  59452. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  59453. }
  59454. for (i = 0; i < 256; ++i)
  59455. original.setBit (i, bits [i / 2]);
  59456. }
  59457. else
  59458. {
  59459. if (type == audioInputType)
  59460. {
  59461. config.useDefaultInputChannels = false;
  59462. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  59463. }
  59464. else
  59465. {
  59466. config.useDefaultOutputChannels = false;
  59467. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  59468. }
  59469. }
  59470. String error (setup.manager->setAudioDeviceSetup (config, true));
  59471. if (! error.isEmpty())
  59472. {
  59473. //xxx
  59474. }
  59475. }
  59476. }
  59477. static void flipBit (BigInteger& chans, int index, int minNumber, int maxNumber)
  59478. {
  59479. const int numActive = chans.countNumberOfSetBits();
  59480. if (chans [index])
  59481. {
  59482. if (numActive > minNumber)
  59483. chans.setBit (index, false);
  59484. }
  59485. else
  59486. {
  59487. if (numActive >= maxNumber)
  59488. {
  59489. const int firstActiveChan = chans.findNextSetBit();
  59490. chans.setBit (index > firstActiveChan
  59491. ? firstActiveChan : chans.getHighestBit(),
  59492. false);
  59493. }
  59494. chans.setBit (index, true);
  59495. }
  59496. }
  59497. int getTickX() const
  59498. {
  59499. return getRowHeight() + 5;
  59500. }
  59501. ChannelSelectorListBox (const ChannelSelectorListBox&);
  59502. ChannelSelectorListBox& operator= (const ChannelSelectorListBox&);
  59503. };
  59504. private:
  59505. ScopedPointer<ChannelSelectorListBox> inputChanList, outputChanList;
  59506. AudioDeviceSettingsPanel (const AudioDeviceSettingsPanel&);
  59507. AudioDeviceSettingsPanel& operator= (const AudioDeviceSettingsPanel&);
  59508. };
  59509. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  59510. const int minInputChannels_,
  59511. const int maxInputChannels_,
  59512. const int minOutputChannels_,
  59513. const int maxOutputChannels_,
  59514. const bool showMidiInputOptions,
  59515. const bool showMidiOutputSelector,
  59516. const bool showChannelsAsStereoPairs_,
  59517. const bool hideAdvancedOptionsWithButton_)
  59518. : deviceManager (deviceManager_),
  59519. deviceTypeDropDown (0),
  59520. deviceTypeDropDownLabel (0),
  59521. minOutputChannels (minOutputChannels_),
  59522. maxOutputChannels (maxOutputChannels_),
  59523. minInputChannels (minInputChannels_),
  59524. maxInputChannels (maxInputChannels_),
  59525. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  59526. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  59527. {
  59528. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  59529. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  59530. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  59531. {
  59532. deviceTypeDropDown = new ComboBox (String::empty);
  59533. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  59534. {
  59535. deviceTypeDropDown
  59536. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  59537. i + 1);
  59538. }
  59539. addAndMakeVisible (deviceTypeDropDown);
  59540. deviceTypeDropDown->addListener (this);
  59541. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  59542. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  59543. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  59544. }
  59545. if (showMidiInputOptions)
  59546. {
  59547. addAndMakeVisible (midiInputsList
  59548. = new MidiInputSelectorComponentListBox (deviceManager,
  59549. TRANS("(no midi inputs available)"),
  59550. 0, 0));
  59551. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  59552. midiInputsLabel->setJustificationType (Justification::topRight);
  59553. midiInputsLabel->attachToComponent (midiInputsList, true);
  59554. }
  59555. else
  59556. {
  59557. midiInputsList = 0;
  59558. midiInputsLabel = 0;
  59559. }
  59560. if (showMidiOutputSelector)
  59561. {
  59562. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  59563. midiOutputSelector->addListener (this);
  59564. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  59565. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  59566. }
  59567. else
  59568. {
  59569. midiOutputSelector = 0;
  59570. midiOutputLabel = 0;
  59571. }
  59572. deviceManager_.addChangeListener (this);
  59573. changeListenerCallback (0);
  59574. }
  59575. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  59576. {
  59577. deviceManager.removeChangeListener (this);
  59578. }
  59579. void AudioDeviceSelectorComponent::resized()
  59580. {
  59581. const int lx = proportionOfWidth (0.35f);
  59582. const int w = proportionOfWidth (0.4f);
  59583. const int h = 24;
  59584. const int space = 6;
  59585. const int dh = h + space;
  59586. int y = 15;
  59587. if (deviceTypeDropDown != 0)
  59588. {
  59589. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  59590. y += dh + space * 2;
  59591. }
  59592. if (audioDeviceSettingsComp != 0)
  59593. {
  59594. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  59595. y += audioDeviceSettingsComp->getHeight() + space;
  59596. }
  59597. if (midiInputsList != 0)
  59598. {
  59599. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  59600. midiInputsList->setBounds (lx, y, w, bh);
  59601. y += bh + space;
  59602. }
  59603. if (midiOutputSelector != 0)
  59604. midiOutputSelector->setBounds (lx, y, w, h);
  59605. }
  59606. void AudioDeviceSelectorComponent::childBoundsChanged (Component* child)
  59607. {
  59608. if (child == audioDeviceSettingsComp)
  59609. resized();
  59610. }
  59611. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  59612. {
  59613. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  59614. if (device != 0 && device->hasControlPanel())
  59615. {
  59616. if (device->showControlPanel())
  59617. deviceManager.restartLastAudioDevice();
  59618. getTopLevelComponent()->toFront (true);
  59619. }
  59620. }
  59621. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  59622. {
  59623. if (comboBoxThatHasChanged == deviceTypeDropDown)
  59624. {
  59625. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  59626. if (type != 0)
  59627. {
  59628. audioDeviceSettingsComp = 0;
  59629. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  59630. changeListenerCallback (0); // needed in case the type hasn't actally changed
  59631. }
  59632. }
  59633. else if (comboBoxThatHasChanged == midiOutputSelector)
  59634. {
  59635. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  59636. }
  59637. }
  59638. void AudioDeviceSelectorComponent::changeListenerCallback (void*)
  59639. {
  59640. if (deviceTypeDropDown != 0)
  59641. {
  59642. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  59643. }
  59644. if (audioDeviceSettingsComp == 0
  59645. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  59646. {
  59647. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  59648. audioDeviceSettingsComp = 0;
  59649. AudioIODeviceType* const type
  59650. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  59651. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  59652. if (type != 0)
  59653. {
  59654. AudioIODeviceType::DeviceSetupDetails details;
  59655. details.manager = &deviceManager;
  59656. details.minNumInputChannels = minInputChannels;
  59657. details.maxNumInputChannels = maxInputChannels;
  59658. details.minNumOutputChannels = minOutputChannels;
  59659. details.maxNumOutputChannels = maxOutputChannels;
  59660. details.useStereoPairs = showChannelsAsStereoPairs;
  59661. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  59662. if (audioDeviceSettingsComp != 0)
  59663. {
  59664. addAndMakeVisible (audioDeviceSettingsComp);
  59665. audioDeviceSettingsComp->resized();
  59666. }
  59667. }
  59668. }
  59669. if (midiInputsList != 0)
  59670. {
  59671. midiInputsList->updateContent();
  59672. midiInputsList->repaint();
  59673. }
  59674. if (midiOutputSelector != 0)
  59675. {
  59676. midiOutputSelector->clear();
  59677. const StringArray midiOuts (MidiOutput::getDevices());
  59678. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  59679. midiOutputSelector->addSeparator();
  59680. for (int i = 0; i < midiOuts.size(); ++i)
  59681. midiOutputSelector->addItem (midiOuts[i], i + 1);
  59682. int current = -1;
  59683. if (deviceManager.getDefaultMidiOutput() != 0)
  59684. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  59685. midiOutputSelector->setSelectedId (current, true);
  59686. }
  59687. resized();
  59688. }
  59689. END_JUCE_NAMESPACE
  59690. /*** End of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  59691. /*** Start of inlined file: juce_BubbleComponent.cpp ***/
  59692. BEGIN_JUCE_NAMESPACE
  59693. BubbleComponent::BubbleComponent()
  59694. : side (0),
  59695. allowablePlacements (above | below | left | right),
  59696. arrowTipX (0.0f),
  59697. arrowTipY (0.0f)
  59698. {
  59699. setInterceptsMouseClicks (false, false);
  59700. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  59701. setComponentEffect (&shadow);
  59702. }
  59703. BubbleComponent::~BubbleComponent()
  59704. {
  59705. }
  59706. void BubbleComponent::paint (Graphics& g)
  59707. {
  59708. int x = content.getX();
  59709. int y = content.getY();
  59710. int w = content.getWidth();
  59711. int h = content.getHeight();
  59712. int cw, ch;
  59713. getContentSize (cw, ch);
  59714. if (side == 3)
  59715. x += w - cw;
  59716. else if (side != 1)
  59717. x += (w - cw) / 2;
  59718. w = cw;
  59719. if (side == 2)
  59720. y += h - ch;
  59721. else if (side != 0)
  59722. y += (h - ch) / 2;
  59723. h = ch;
  59724. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  59725. (float) x, (float) y,
  59726. (float) w, (float) h);
  59727. const int cx = x + (w - cw) / 2;
  59728. const int cy = y + (h - ch) / 2;
  59729. const int indent = 3;
  59730. g.setOrigin (cx + indent, cy + indent);
  59731. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  59732. paintContent (g, cw - indent * 2, ch - indent * 2);
  59733. }
  59734. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  59735. {
  59736. allowablePlacements = newPlacement;
  59737. }
  59738. void BubbleComponent::setPosition (Component* componentToPointTo)
  59739. {
  59740. jassert (componentToPointTo->isValidComponent());
  59741. Point<int> pos;
  59742. if (getParentComponent() != 0)
  59743. pos = componentToPointTo->relativePositionToOtherComponent (getParentComponent(), pos);
  59744. else
  59745. pos = componentToPointTo->relativePositionToGlobal (pos);
  59746. setPosition (Rectangle<int> (pos.getX(), pos.getY(), componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  59747. }
  59748. void BubbleComponent::setPosition (const int arrowTipX_,
  59749. const int arrowTipY_)
  59750. {
  59751. setPosition (Rectangle<int> (arrowTipX_, arrowTipY_, 1, 1));
  59752. }
  59753. void BubbleComponent::setPosition (const Rectangle<int>& rectangleToPointTo)
  59754. {
  59755. Rectangle<int> availableSpace;
  59756. if (getParentComponent() != 0)
  59757. {
  59758. availableSpace.setSize (getParentComponent()->getWidth(),
  59759. getParentComponent()->getHeight());
  59760. }
  59761. else
  59762. {
  59763. availableSpace = getParentMonitorArea();
  59764. }
  59765. int x = 0;
  59766. int y = 0;
  59767. int w = 150;
  59768. int h = 30;
  59769. getContentSize (w, h);
  59770. w += 30;
  59771. h += 30;
  59772. const float edgeIndent = 2.0f;
  59773. const int arrowLength = jmin (10, h / 3, w / 3);
  59774. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  59775. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  59776. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  59777. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  59778. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  59779. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  59780. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  59781. {
  59782. spaceLeft = spaceRight = 0;
  59783. }
  59784. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  59785. && (spaceLeft > w + 20 || spaceRight > w + 20))
  59786. {
  59787. spaceAbove = spaceBelow = 0;
  59788. }
  59789. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  59790. {
  59791. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  59792. arrowTipX = w * 0.5f;
  59793. content.setSize (w, h - arrowLength);
  59794. if (spaceAbove >= spaceBelow)
  59795. {
  59796. // above
  59797. y = rectangleToPointTo.getY() - h;
  59798. content.setPosition (0, 0);
  59799. arrowTipY = h - edgeIndent;
  59800. side = 2;
  59801. }
  59802. else
  59803. {
  59804. // below
  59805. y = rectangleToPointTo.getBottom();
  59806. content.setPosition (0, arrowLength);
  59807. arrowTipY = edgeIndent;
  59808. side = 0;
  59809. }
  59810. }
  59811. else
  59812. {
  59813. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  59814. arrowTipY = h * 0.5f;
  59815. content.setSize (w - arrowLength, h);
  59816. if (spaceLeft > spaceRight)
  59817. {
  59818. // on the left
  59819. x = rectangleToPointTo.getX() - w;
  59820. content.setPosition (0, 0);
  59821. arrowTipX = w - edgeIndent;
  59822. side = 3;
  59823. }
  59824. else
  59825. {
  59826. // on the right
  59827. x = rectangleToPointTo.getRight();
  59828. content.setPosition (arrowLength, 0);
  59829. arrowTipX = edgeIndent;
  59830. side = 1;
  59831. }
  59832. }
  59833. setBounds (x, y, w, h);
  59834. }
  59835. END_JUCE_NAMESPACE
  59836. /*** End of inlined file: juce_BubbleComponent.cpp ***/
  59837. /*** Start of inlined file: juce_BubbleMessageComponent.cpp ***/
  59838. BEGIN_JUCE_NAMESPACE
  59839. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  59840. : fadeOutLength (fadeOutLengthMs),
  59841. deleteAfterUse (false)
  59842. {
  59843. }
  59844. BubbleMessageComponent::~BubbleMessageComponent()
  59845. {
  59846. fadeOutComponent (fadeOutLength);
  59847. }
  59848. void BubbleMessageComponent::showAt (int x, int y,
  59849. const String& text,
  59850. const int numMillisecondsBeforeRemoving,
  59851. const bool removeWhenMouseClicked,
  59852. const bool deleteSelfAfterUse)
  59853. {
  59854. textLayout.clear();
  59855. textLayout.setText (text, Font (14.0f));
  59856. textLayout.layout (256, Justification::centredLeft, true);
  59857. setPosition (x, y);
  59858. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59859. }
  59860. void BubbleMessageComponent::showAt (Component* const component,
  59861. const String& text,
  59862. const int numMillisecondsBeforeRemoving,
  59863. const bool removeWhenMouseClicked,
  59864. const bool deleteSelfAfterUse)
  59865. {
  59866. textLayout.clear();
  59867. textLayout.setText (text, Font (14.0f));
  59868. textLayout.layout (256, Justification::centredLeft, true);
  59869. setPosition (component);
  59870. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59871. }
  59872. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  59873. const bool removeWhenMouseClicked,
  59874. const bool deleteSelfAfterUse)
  59875. {
  59876. setVisible (true);
  59877. deleteAfterUse = deleteSelfAfterUse;
  59878. if (numMillisecondsBeforeRemoving > 0)
  59879. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  59880. else
  59881. expiryTime = 0;
  59882. startTimer (77);
  59883. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  59884. if (! (removeWhenMouseClicked && isShowing()))
  59885. mouseClickCounter += 0xfffff;
  59886. repaint();
  59887. }
  59888. void BubbleMessageComponent::getContentSize (int& w, int& h)
  59889. {
  59890. w = textLayout.getWidth() + 16;
  59891. h = textLayout.getHeight() + 16;
  59892. }
  59893. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  59894. {
  59895. g.setColour (findColour (TooltipWindow::textColourId));
  59896. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  59897. }
  59898. void BubbleMessageComponent::timerCallback()
  59899. {
  59900. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  59901. {
  59902. stopTimer();
  59903. setVisible (false);
  59904. if (deleteAfterUse)
  59905. delete this;
  59906. }
  59907. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  59908. {
  59909. stopTimer();
  59910. fadeOutComponent (fadeOutLength);
  59911. if (deleteAfterUse)
  59912. delete this;
  59913. }
  59914. }
  59915. END_JUCE_NAMESPACE
  59916. /*** End of inlined file: juce_BubbleMessageComponent.cpp ***/
  59917. /*** Start of inlined file: juce_ColourSelector.cpp ***/
  59918. BEGIN_JUCE_NAMESPACE
  59919. class ColourComponentSlider : public Slider
  59920. {
  59921. public:
  59922. ColourComponentSlider (const String& name)
  59923. : Slider (name)
  59924. {
  59925. setRange (0.0, 255.0, 1.0);
  59926. }
  59927. ~ColourComponentSlider()
  59928. {
  59929. }
  59930. const String getTextFromValue (double value)
  59931. {
  59932. return String::toHexString ((int) value).toUpperCase().paddedLeft ('0', 2);
  59933. }
  59934. double getValueFromText (const String& text)
  59935. {
  59936. return (double) text.getHexValue32();
  59937. }
  59938. private:
  59939. ColourComponentSlider (const ColourComponentSlider&);
  59940. ColourComponentSlider& operator= (const ColourComponentSlider&);
  59941. };
  59942. class ColourSpaceMarker : public Component
  59943. {
  59944. public:
  59945. ColourSpaceMarker()
  59946. {
  59947. setInterceptsMouseClicks (false, false);
  59948. }
  59949. ~ColourSpaceMarker()
  59950. {
  59951. }
  59952. void paint (Graphics& g)
  59953. {
  59954. g.setColour (Colour::greyLevel (0.1f));
  59955. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  59956. g.setColour (Colour::greyLevel (0.9f));
  59957. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  59958. }
  59959. private:
  59960. ColourSpaceMarker (const ColourSpaceMarker&);
  59961. ColourSpaceMarker& operator= (const ColourSpaceMarker&);
  59962. };
  59963. class ColourSelector::ColourSpaceView : public Component
  59964. {
  59965. public:
  59966. ColourSpaceView (ColourSelector* owner_,
  59967. float& h_, float& s_, float& v_,
  59968. const int edgeSize)
  59969. : owner (owner_),
  59970. h (h_), s (s_), v (v_),
  59971. lastHue (0.0f),
  59972. edge (edgeSize)
  59973. {
  59974. addAndMakeVisible (&marker);
  59975. setMouseCursor (MouseCursor::CrosshairCursor);
  59976. }
  59977. ~ColourSpaceView()
  59978. {
  59979. }
  59980. void paint (Graphics& g)
  59981. {
  59982. if (colours.isNull())
  59983. {
  59984. const int width = getWidth() / 2;
  59985. const int height = getHeight() / 2;
  59986. colours = Image (Image::RGB, width, height, false);
  59987. Image::BitmapData pixels (colours, true);
  59988. for (int y = 0; y < height; ++y)
  59989. {
  59990. const float val = 1.0f - y / (float) height;
  59991. for (int x = 0; x < width; ++x)
  59992. {
  59993. const float sat = x / (float) width;
  59994. pixels.setPixelColour (x, y, Colour (h, sat, val, 1.0f));
  59995. }
  59996. }
  59997. }
  59998. g.setOpacity (1.0f);
  59999. g.drawImage (colours, edge, edge, getWidth() - edge * 2, getHeight() - edge * 2,
  60000. 0, 0, colours.getWidth(), colours.getHeight());
  60001. }
  60002. void mouseDown (const MouseEvent& e)
  60003. {
  60004. mouseDrag (e);
  60005. }
  60006. void mouseDrag (const MouseEvent& e)
  60007. {
  60008. const float sat = (e.x - edge) / (float) (getWidth() - edge * 2);
  60009. const float val = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  60010. owner->setSV (sat, val);
  60011. }
  60012. void updateIfNeeded()
  60013. {
  60014. if (lastHue != h)
  60015. {
  60016. lastHue = h;
  60017. colours = Image::null;
  60018. repaint();
  60019. }
  60020. updateMarker();
  60021. }
  60022. void resized()
  60023. {
  60024. colours = Image::null;
  60025. updateMarker();
  60026. }
  60027. private:
  60028. ColourSelector* const owner;
  60029. float& h;
  60030. float& s;
  60031. float& v;
  60032. float lastHue;
  60033. ColourSpaceMarker marker;
  60034. const int edge;
  60035. Image colours;
  60036. void updateMarker()
  60037. {
  60038. marker.setBounds (roundToInt ((getWidth() - edge * 2) * s),
  60039. roundToInt ((getHeight() - edge * 2) * (1.0f - v)),
  60040. edge * 2, edge * 2);
  60041. }
  60042. ColourSpaceView (const ColourSpaceView&);
  60043. ColourSpaceView& operator= (const ColourSpaceView&);
  60044. };
  60045. class HueSelectorMarker : public Component
  60046. {
  60047. public:
  60048. HueSelectorMarker()
  60049. {
  60050. setInterceptsMouseClicks (false, false);
  60051. }
  60052. ~HueSelectorMarker()
  60053. {
  60054. }
  60055. void paint (Graphics& g)
  60056. {
  60057. Path p;
  60058. p.addTriangle (1.0f, 1.0f,
  60059. getWidth() * 0.3f, getHeight() * 0.5f,
  60060. 1.0f, getHeight() - 1.0f);
  60061. p.addTriangle (getWidth() - 1.0f, 1.0f,
  60062. getWidth() * 0.7f, getHeight() * 0.5f,
  60063. getWidth() - 1.0f, getHeight() - 1.0f);
  60064. g.setColour (Colours::white.withAlpha (0.75f));
  60065. g.fillPath (p);
  60066. g.setColour (Colours::black.withAlpha (0.75f));
  60067. g.strokePath (p, PathStrokeType (1.2f));
  60068. }
  60069. private:
  60070. HueSelectorMarker (const HueSelectorMarker&);
  60071. HueSelectorMarker& operator= (const HueSelectorMarker&);
  60072. };
  60073. class ColourSelector::HueSelectorComp : public Component
  60074. {
  60075. public:
  60076. HueSelectorComp (ColourSelector* owner_,
  60077. float& h_, float& s_, float& v_,
  60078. const int edgeSize)
  60079. : owner (owner_),
  60080. h (h_), s (s_), v (v_),
  60081. lastHue (0.0f),
  60082. edge (edgeSize)
  60083. {
  60084. addAndMakeVisible (&marker);
  60085. }
  60086. ~HueSelectorComp()
  60087. {
  60088. }
  60089. void paint (Graphics& g)
  60090. {
  60091. const float yScale = 1.0f / (getHeight() - edge * 2);
  60092. const Rectangle<int> clip (g.getClipBounds());
  60093. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  60094. {
  60095. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  60096. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  60097. }
  60098. }
  60099. void resized()
  60100. {
  60101. marker.setBounds (0, roundToInt ((getHeight() - edge * 2) * h),
  60102. getWidth(), edge * 2);
  60103. }
  60104. void mouseDown (const MouseEvent& e)
  60105. {
  60106. mouseDrag (e);
  60107. }
  60108. void mouseDrag (const MouseEvent& e)
  60109. {
  60110. const float hue = (e.y - edge) / (float) (getHeight() - edge * 2);
  60111. owner->setHue (hue);
  60112. }
  60113. void updateIfNeeded()
  60114. {
  60115. resized();
  60116. }
  60117. private:
  60118. ColourSelector* const owner;
  60119. float& h;
  60120. float& s;
  60121. float& v;
  60122. float lastHue;
  60123. HueSelectorMarker marker;
  60124. const int edge;
  60125. HueSelectorComp (const HueSelectorComp&);
  60126. HueSelectorComp& operator= (const HueSelectorComp&);
  60127. };
  60128. class ColourSelector::SwatchComponent : public Component
  60129. {
  60130. public:
  60131. SwatchComponent (ColourSelector* owner_, int index_)
  60132. : owner (owner_),
  60133. index (index_)
  60134. {
  60135. }
  60136. ~SwatchComponent()
  60137. {
  60138. }
  60139. void paint (Graphics& g)
  60140. {
  60141. const Colour colour (owner->getSwatchColour (index));
  60142. g.fillCheckerBoard (getLocalBounds(), 6, 6,
  60143. Colour (0xffdddddd).overlaidWith (colour),
  60144. Colour (0xffffffff).overlaidWith (colour));
  60145. }
  60146. void mouseDown (const MouseEvent&)
  60147. {
  60148. PopupMenu m;
  60149. m.addItem (1, TRANS("Use this swatch as the current colour"));
  60150. m.addSeparator();
  60151. m.addItem (2, TRANS("Set this swatch to the current colour"));
  60152. const int r = m.showAt (this);
  60153. if (r == 1)
  60154. {
  60155. owner->setCurrentColour (owner->getSwatchColour (index));
  60156. }
  60157. else if (r == 2)
  60158. {
  60159. if (owner->getSwatchColour (index) != owner->getCurrentColour())
  60160. {
  60161. owner->setSwatchColour (index, owner->getCurrentColour());
  60162. repaint();
  60163. }
  60164. }
  60165. }
  60166. private:
  60167. ColourSelector* const owner;
  60168. const int index;
  60169. SwatchComponent (const SwatchComponent&);
  60170. SwatchComponent& operator= (const SwatchComponent&);
  60171. };
  60172. ColourSelector::ColourSelector (const int flags_,
  60173. const int edgeGap_,
  60174. const int gapAroundColourSpaceComponent)
  60175. : colour (Colours::white),
  60176. colourSpace (0),
  60177. hueSelector (0),
  60178. flags (flags_),
  60179. edgeGap (edgeGap_)
  60180. {
  60181. // not much point having a selector with no components in it!
  60182. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  60183. updateHSV();
  60184. if ((flags & showSliders) != 0)
  60185. {
  60186. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  60187. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  60188. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  60189. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  60190. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  60191. for (int i = 4; --i >= 0;)
  60192. sliders[i]->addListener (this);
  60193. }
  60194. else
  60195. {
  60196. zeromem (sliders, sizeof (sliders));
  60197. }
  60198. if ((flags & showColourspace) != 0)
  60199. {
  60200. addAndMakeVisible (colourSpace = new ColourSpaceView (this, h, s, v, gapAroundColourSpaceComponent));
  60201. addAndMakeVisible (hueSelector = new HueSelectorComp (this, h, s, v, gapAroundColourSpaceComponent));
  60202. }
  60203. update();
  60204. }
  60205. ColourSelector::~ColourSelector()
  60206. {
  60207. dispatchPendingMessages();
  60208. swatchComponents.clear();
  60209. deleteAllChildren();
  60210. }
  60211. const Colour ColourSelector::getCurrentColour() const
  60212. {
  60213. return ((flags & showAlphaChannel) != 0) ? colour
  60214. : colour.withAlpha ((uint8) 0xff);
  60215. }
  60216. void ColourSelector::setCurrentColour (const Colour& c)
  60217. {
  60218. if (c != colour)
  60219. {
  60220. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  60221. updateHSV();
  60222. update();
  60223. }
  60224. }
  60225. void ColourSelector::setHue (float newH)
  60226. {
  60227. newH = jlimit (0.0f, 1.0f, newH);
  60228. if (h != newH)
  60229. {
  60230. h = newH;
  60231. colour = Colour (h, s, v, colour.getFloatAlpha());
  60232. update();
  60233. }
  60234. }
  60235. void ColourSelector::setSV (float newS, float newV)
  60236. {
  60237. newS = jlimit (0.0f, 1.0f, newS);
  60238. newV = jlimit (0.0f, 1.0f, newV);
  60239. if (s != newS || v != newV)
  60240. {
  60241. s = newS;
  60242. v = newV;
  60243. colour = Colour (h, s, v, colour.getFloatAlpha());
  60244. update();
  60245. }
  60246. }
  60247. void ColourSelector::updateHSV()
  60248. {
  60249. colour.getHSB (h, s, v);
  60250. }
  60251. void ColourSelector::update()
  60252. {
  60253. if (sliders[0] != 0)
  60254. {
  60255. sliders[0]->setValue ((int) colour.getRed());
  60256. sliders[1]->setValue ((int) colour.getGreen());
  60257. sliders[2]->setValue ((int) colour.getBlue());
  60258. sliders[3]->setValue ((int) colour.getAlpha());
  60259. }
  60260. if (colourSpace != 0)
  60261. {
  60262. colourSpace->updateIfNeeded();
  60263. hueSelector->updateIfNeeded();
  60264. }
  60265. if ((flags & showColourAtTop) != 0)
  60266. repaint (previewArea);
  60267. sendChangeMessage (this);
  60268. }
  60269. void ColourSelector::paint (Graphics& g)
  60270. {
  60271. g.fillAll (findColour (backgroundColourId));
  60272. if ((flags & showColourAtTop) != 0)
  60273. {
  60274. const Colour currentColour (getCurrentColour());
  60275. g.fillCheckerBoard (previewArea, 10, 10,
  60276. Colour (0xffdddddd).overlaidWith (currentColour),
  60277. Colour (0xffffffff).overlaidWith (currentColour));
  60278. g.setColour (Colours::white.overlaidWith (currentColour).contrasting());
  60279. g.setFont (14.0f, true);
  60280. g.drawText (currentColour.toDisplayString ((flags & showAlphaChannel) != 0),
  60281. previewArea.getX(), previewArea.getY(), previewArea.getWidth(), previewArea.getHeight(),
  60282. Justification::centred, false);
  60283. }
  60284. if ((flags & showSliders) != 0)
  60285. {
  60286. g.setColour (findColour (labelTextColourId));
  60287. g.setFont (11.0f);
  60288. for (int i = 4; --i >= 0;)
  60289. {
  60290. if (sliders[i]->isVisible())
  60291. g.drawText (sliders[i]->getName() + ":",
  60292. 0, sliders[i]->getY(),
  60293. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  60294. Justification::centredRight, false);
  60295. }
  60296. }
  60297. }
  60298. void ColourSelector::resized()
  60299. {
  60300. const int swatchesPerRow = 8;
  60301. const int swatchHeight = 22;
  60302. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  60303. const int numSwatches = getNumSwatches();
  60304. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  60305. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  60306. const int topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  60307. previewArea.setBounds (edgeGap, edgeGap, getWidth() - edgeGap * 2, topSpace - edgeGap * 2);
  60308. int y = topSpace;
  60309. if ((flags & showColourspace) != 0)
  60310. {
  60311. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  60312. colourSpace->setBounds (edgeGap, y,
  60313. getWidth() - hueWidth - edgeGap - 4,
  60314. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  60315. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  60316. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  60317. colourSpace->getHeight());
  60318. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  60319. }
  60320. if ((flags & showSliders) != 0)
  60321. {
  60322. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  60323. for (int i = 0; i < numSliders; ++i)
  60324. {
  60325. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  60326. proportionOfWidth (0.72f), sliderHeight - 2);
  60327. y += sliderHeight;
  60328. }
  60329. }
  60330. if (numSwatches > 0)
  60331. {
  60332. const int startX = 8;
  60333. const int xGap = 4;
  60334. const int yGap = 4;
  60335. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  60336. y += edgeGap;
  60337. if (swatchComponents.size() != numSwatches)
  60338. {
  60339. swatchComponents.clear();
  60340. for (int i = 0; i < numSwatches; ++i)
  60341. {
  60342. SwatchComponent* const sc = new SwatchComponent (this, i);
  60343. swatchComponents.add (sc);
  60344. addAndMakeVisible (sc);
  60345. }
  60346. }
  60347. int x = startX;
  60348. for (int i = 0; i < swatchComponents.size(); ++i)
  60349. {
  60350. SwatchComponent* const sc = swatchComponents.getUnchecked(i);
  60351. sc->setBounds (x + xGap / 2,
  60352. y + yGap / 2,
  60353. swatchWidth - xGap,
  60354. swatchHeight - yGap);
  60355. if (((i + 1) % swatchesPerRow) == 0)
  60356. {
  60357. x = startX;
  60358. y += swatchHeight;
  60359. }
  60360. else
  60361. {
  60362. x += swatchWidth;
  60363. }
  60364. }
  60365. }
  60366. }
  60367. void ColourSelector::sliderValueChanged (Slider*)
  60368. {
  60369. if (sliders[0] != 0)
  60370. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  60371. (uint8) sliders[1]->getValue(),
  60372. (uint8) sliders[2]->getValue(),
  60373. (uint8) sliders[3]->getValue()));
  60374. }
  60375. int ColourSelector::getNumSwatches() const
  60376. {
  60377. return 0;
  60378. }
  60379. const Colour ColourSelector::getSwatchColour (const int) const
  60380. {
  60381. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  60382. return Colours::black;
  60383. }
  60384. void ColourSelector::setSwatchColour (const int, const Colour&) const
  60385. {
  60386. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  60387. }
  60388. END_JUCE_NAMESPACE
  60389. /*** End of inlined file: juce_ColourSelector.cpp ***/
  60390. /*** Start of inlined file: juce_DropShadower.cpp ***/
  60391. BEGIN_JUCE_NAMESPACE
  60392. class ShadowWindow : public Component
  60393. {
  60394. Component* owner;
  60395. Image shadowImageSections [12];
  60396. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  60397. public:
  60398. ShadowWindow (Component* const owner_,
  60399. const int type_,
  60400. const Image shadowImageSections_ [12])
  60401. : owner (owner_),
  60402. type (type_)
  60403. {
  60404. for (int i = 0; i < numElementsInArray (shadowImageSections); ++i)
  60405. shadowImageSections [i] = shadowImageSections_ [i];
  60406. setInterceptsMouseClicks (false, false);
  60407. if (owner_->isOnDesktop())
  60408. {
  60409. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  60410. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  60411. | ComponentPeer::windowIsTemporary
  60412. | ComponentPeer::windowIgnoresKeyPresses);
  60413. }
  60414. else if (owner_->getParentComponent() != 0)
  60415. {
  60416. owner_->getParentComponent()->addChildComponent (this);
  60417. }
  60418. }
  60419. ~ShadowWindow()
  60420. {
  60421. }
  60422. void paint (Graphics& g)
  60423. {
  60424. const Image& topLeft = shadowImageSections [type * 3];
  60425. const Image& bottomRight = shadowImageSections [type * 3 + 1];
  60426. const Image& filler = shadowImageSections [type * 3 + 2];
  60427. g.setOpacity (1.0f);
  60428. if (type < 2)
  60429. {
  60430. int imH = jmin (topLeft.getHeight(), getHeight() / 2);
  60431. g.drawImage (topLeft,
  60432. 0, 0, topLeft.getWidth(), imH,
  60433. 0, 0, topLeft.getWidth(), imH);
  60434. imH = jmin (bottomRight.getHeight(), getHeight() - getHeight() / 2);
  60435. g.drawImage (bottomRight,
  60436. 0, getHeight() - imH, bottomRight.getWidth(), imH,
  60437. 0, bottomRight.getHeight() - imH, bottomRight.getWidth(), imH);
  60438. g.setTiledImageFill (filler, 0, 0, 1.0f);
  60439. g.fillRect (0, topLeft.getHeight(), getWidth(), getHeight() - (topLeft.getHeight() + bottomRight.getHeight()));
  60440. }
  60441. else
  60442. {
  60443. int imW = jmin (topLeft.getWidth(), getWidth() / 2);
  60444. g.drawImage (topLeft,
  60445. 0, 0, imW, topLeft.getHeight(),
  60446. 0, 0, imW, topLeft.getHeight());
  60447. imW = jmin (bottomRight.getWidth(), getWidth() - getWidth() / 2);
  60448. g.drawImage (bottomRight,
  60449. getWidth() - imW, 0, imW, bottomRight.getHeight(),
  60450. bottomRight.getWidth() - imW, 0, imW, bottomRight.getHeight());
  60451. g.setTiledImageFill (filler, 0, 0, 1.0f);
  60452. g.fillRect (topLeft.getWidth(), 0, getWidth() - (topLeft.getWidth() + bottomRight.getWidth()), getHeight());
  60453. }
  60454. }
  60455. void resized()
  60456. {
  60457. repaint(); // (needed for correct repainting)
  60458. }
  60459. private:
  60460. ShadowWindow (const ShadowWindow&);
  60461. ShadowWindow& operator= (const ShadowWindow&);
  60462. };
  60463. DropShadower::DropShadower (const float alpha_,
  60464. const int xOffset_,
  60465. const int yOffset_,
  60466. const float blurRadius_)
  60467. : owner (0),
  60468. numShadows (0),
  60469. shadowEdge (jmax (xOffset_, yOffset_) + (int) blurRadius_),
  60470. xOffset (xOffset_),
  60471. yOffset (yOffset_),
  60472. alpha (alpha_),
  60473. blurRadius (blurRadius_),
  60474. inDestructor (false),
  60475. reentrant (false)
  60476. {
  60477. }
  60478. DropShadower::~DropShadower()
  60479. {
  60480. if (owner != 0)
  60481. owner->removeComponentListener (this);
  60482. inDestructor = true;
  60483. deleteShadowWindows();
  60484. }
  60485. void DropShadower::deleteShadowWindows()
  60486. {
  60487. if (numShadows > 0)
  60488. {
  60489. int i;
  60490. for (i = numShadows; --i >= 0;)
  60491. delete shadowWindows[i];
  60492. numShadows = 0;
  60493. }
  60494. }
  60495. void DropShadower::setOwner (Component* componentToFollow)
  60496. {
  60497. if (componentToFollow != owner)
  60498. {
  60499. if (owner != 0)
  60500. owner->removeComponentListener (this);
  60501. // (the component can't be null)
  60502. jassert (componentToFollow != 0);
  60503. owner = componentToFollow;
  60504. jassert (owner != 0);
  60505. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  60506. owner->addComponentListener (this);
  60507. updateShadows();
  60508. }
  60509. }
  60510. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  60511. {
  60512. updateShadows();
  60513. }
  60514. void DropShadower::componentBroughtToFront (Component&)
  60515. {
  60516. bringShadowWindowsToFront();
  60517. }
  60518. void DropShadower::componentChildrenChanged (Component&)
  60519. {
  60520. }
  60521. void DropShadower::componentParentHierarchyChanged (Component&)
  60522. {
  60523. deleteShadowWindows();
  60524. updateShadows();
  60525. }
  60526. void DropShadower::componentVisibilityChanged (Component&)
  60527. {
  60528. updateShadows();
  60529. }
  60530. void DropShadower::updateShadows()
  60531. {
  60532. if (reentrant || inDestructor || (owner == 0))
  60533. return;
  60534. reentrant = true;
  60535. ComponentPeer* const nw = owner->getPeer();
  60536. const bool isOwnerVisible = owner->isVisible()
  60537. && (nw == 0 || ! nw->isMinimised());
  60538. const bool createShadowWindows = numShadows == 0
  60539. && owner->getWidth() > 0
  60540. && owner->getHeight() > 0
  60541. && isOwnerVisible
  60542. && (Desktop::canUseSemiTransparentWindows()
  60543. || owner->getParentComponent() != 0);
  60544. if (createShadowWindows)
  60545. {
  60546. // keep a cached version of the image to save doing the gaussian too often
  60547. String imageId;
  60548. imageId << shadowEdge << ',' << xOffset << ',' << yOffset << ',' << alpha;
  60549. const int hash = imageId.hashCode();
  60550. Image bigIm (ImageCache::getFromHashCode (hash));
  60551. if (bigIm.isNull())
  60552. {
  60553. bigIm = Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true, Image::NativeImage);
  60554. Graphics bigG (bigIm);
  60555. bigG.setColour (Colours::black.withAlpha (alpha));
  60556. bigG.fillRect (shadowEdge + xOffset,
  60557. shadowEdge + yOffset,
  60558. bigIm.getWidth() - (shadowEdge * 2),
  60559. bigIm.getHeight() - (shadowEdge * 2));
  60560. ImageConvolutionKernel blurKernel (roundToInt (blurRadius * 2.0f));
  60561. blurKernel.createGaussianBlur (blurRadius);
  60562. blurKernel.applyToImage (bigIm, bigIm,
  60563. Rectangle<int> (xOffset, yOffset,
  60564. bigIm.getWidth(), bigIm.getHeight()));
  60565. ImageCache::addImageToCache (bigIm, hash);
  60566. }
  60567. const int iw = bigIm.getWidth();
  60568. const int ih = bigIm.getHeight();
  60569. const int shadowEdge2 = shadowEdge * 2;
  60570. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  60571. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  60572. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  60573. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  60574. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  60575. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  60576. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  60577. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  60578. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  60579. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  60580. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  60581. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  60582. for (int i = 0; i < 4; ++i)
  60583. {
  60584. shadowWindows[numShadows] = new ShadowWindow (owner, i, shadowImageSections);
  60585. ++numShadows;
  60586. }
  60587. }
  60588. if (numShadows > 0)
  60589. {
  60590. for (int i = numShadows; --i >= 0;)
  60591. {
  60592. shadowWindows[i]->setAlwaysOnTop (owner->isAlwaysOnTop());
  60593. shadowWindows[i]->setVisible (isOwnerVisible);
  60594. }
  60595. const int x = owner->getX();
  60596. const int y = owner->getY() - shadowEdge;
  60597. const int w = owner->getWidth();
  60598. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  60599. shadowWindows[0]->setBounds (x - shadowEdge,
  60600. y,
  60601. shadowEdge,
  60602. h);
  60603. shadowWindows[1]->setBounds (x + w,
  60604. y,
  60605. shadowEdge,
  60606. h);
  60607. shadowWindows[2]->setBounds (x,
  60608. y,
  60609. w,
  60610. shadowEdge);
  60611. shadowWindows[3]->setBounds (x,
  60612. owner->getBottom(),
  60613. w,
  60614. shadowEdge);
  60615. }
  60616. reentrant = false;
  60617. if (createShadowWindows)
  60618. bringShadowWindowsToFront();
  60619. }
  60620. void DropShadower::setShadowImage (const Image& src, const int num, const int w, const int h,
  60621. const int sx, const int sy)
  60622. {
  60623. shadowImageSections[num] = Image (Image::ARGB, w, h, true, Image::NativeImage);
  60624. Graphics g (shadowImageSections[num]);
  60625. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  60626. }
  60627. void DropShadower::bringShadowWindowsToFront()
  60628. {
  60629. if (! (inDestructor || reentrant))
  60630. {
  60631. updateShadows();
  60632. reentrant = true;
  60633. for (int i = numShadows; --i >= 0;)
  60634. shadowWindows[i]->toBehind (owner);
  60635. reentrant = false;
  60636. }
  60637. }
  60638. END_JUCE_NAMESPACE
  60639. /*** End of inlined file: juce_DropShadower.cpp ***/
  60640. /*** Start of inlined file: juce_MagnifierComponent.cpp ***/
  60641. BEGIN_JUCE_NAMESPACE
  60642. class MagnifyingPeer : public ComponentPeer
  60643. {
  60644. public:
  60645. MagnifyingPeer (Component* const component_,
  60646. MagnifierComponent* const magnifierComp_)
  60647. : ComponentPeer (component_, 0),
  60648. magnifierComp (magnifierComp_)
  60649. {
  60650. }
  60651. ~MagnifyingPeer()
  60652. {
  60653. }
  60654. void* getNativeHandle() const { return 0; }
  60655. void setVisible (bool) {}
  60656. void setTitle (const String&) {}
  60657. void setPosition (int, int) {}
  60658. void setSize (int, int) {}
  60659. void setBounds (int, int, int, int, bool) {}
  60660. void setMinimised (bool) {}
  60661. bool isMinimised() const { return false; }
  60662. void setFullScreen (bool) {}
  60663. bool isFullScreen() const { return false; }
  60664. const BorderSize getFrameSize() const { return BorderSize (0); }
  60665. bool setAlwaysOnTop (bool) { return true; }
  60666. void toFront (bool) {}
  60667. void toBehind (ComponentPeer*) {}
  60668. void setIcon (const Image&) {}
  60669. bool isFocused() const
  60670. {
  60671. return magnifierComp->hasKeyboardFocus (true);
  60672. }
  60673. void grabFocus()
  60674. {
  60675. ComponentPeer* peer = magnifierComp->getPeer();
  60676. if (peer != 0)
  60677. peer->grabFocus();
  60678. }
  60679. void textInputRequired (const Point<int>& position)
  60680. {
  60681. ComponentPeer* peer = magnifierComp->getPeer();
  60682. if (peer != 0)
  60683. peer->textInputRequired (position);
  60684. }
  60685. const Rectangle<int> getBounds() const
  60686. {
  60687. return Rectangle<int> (magnifierComp->getScreenX(), magnifierComp->getScreenY(),
  60688. component->getWidth(), component->getHeight());
  60689. }
  60690. const Point<int> getScreenPosition() const
  60691. {
  60692. return magnifierComp->getScreenPosition();
  60693. }
  60694. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  60695. {
  60696. const double zoom = magnifierComp->getScaleFactor();
  60697. return magnifierComp->relativePositionToGlobal (Point<int> (roundToInt (relativePosition.getX() * zoom),
  60698. roundToInt (relativePosition.getY() * zoom)));
  60699. }
  60700. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  60701. {
  60702. const Point<int> p (magnifierComp->globalPositionToRelative (screenPosition));
  60703. const double zoom = magnifierComp->getScaleFactor();
  60704. return Point<int> (roundToInt (p.getX() / zoom),
  60705. roundToInt (p.getY() / zoom));
  60706. }
  60707. bool contains (const Point<int>& position, bool) const
  60708. {
  60709. return ((unsigned int) position.getX()) < (unsigned int) magnifierComp->getWidth()
  60710. && ((unsigned int) position.getY()) < (unsigned int) magnifierComp->getHeight();
  60711. }
  60712. void repaint (const Rectangle<int>& area)
  60713. {
  60714. const double zoom = magnifierComp->getScaleFactor();
  60715. magnifierComp->repaint ((int) (area.getX() * zoom),
  60716. (int) (area.getY() * zoom),
  60717. roundToInt (area.getWidth() * zoom) + 1,
  60718. roundToInt (area.getHeight() * zoom) + 1);
  60719. }
  60720. void performAnyPendingRepaintsNow()
  60721. {
  60722. }
  60723. juce_UseDebuggingNewOperator
  60724. private:
  60725. MagnifierComponent* const magnifierComp;
  60726. MagnifyingPeer (const MagnifyingPeer&);
  60727. MagnifyingPeer& operator= (const MagnifyingPeer&);
  60728. };
  60729. class PeerHolderComp : public Component
  60730. {
  60731. public:
  60732. PeerHolderComp (MagnifierComponent* const magnifierComp_)
  60733. : magnifierComp (magnifierComp_)
  60734. {
  60735. setVisible (true);
  60736. }
  60737. ~PeerHolderComp()
  60738. {
  60739. }
  60740. ComponentPeer* createNewPeer (int, void*)
  60741. {
  60742. return new MagnifyingPeer (this, magnifierComp);
  60743. }
  60744. void childBoundsChanged (Component* c)
  60745. {
  60746. if (c != 0)
  60747. {
  60748. setSize (c->getWidth(), c->getHeight());
  60749. magnifierComp->childBoundsChanged (this);
  60750. }
  60751. }
  60752. void mouseWheelMove (const MouseEvent& e, float ix, float iy)
  60753. {
  60754. // unhandled mouse wheel moves can be referred upwards to the parent comp..
  60755. Component* const p = magnifierComp->getParentComponent();
  60756. if (p != 0)
  60757. p->mouseWheelMove (e.getEventRelativeTo (p), ix, iy);
  60758. }
  60759. private:
  60760. MagnifierComponent* const magnifierComp;
  60761. PeerHolderComp (const PeerHolderComp&);
  60762. PeerHolderComp& operator= (const PeerHolderComp&);
  60763. };
  60764. MagnifierComponent::MagnifierComponent (Component* const content_,
  60765. const bool deleteContentCompWhenNoLongerNeeded)
  60766. : content (content_),
  60767. scaleFactor (0.0),
  60768. peer (0),
  60769. deleteContent (deleteContentCompWhenNoLongerNeeded),
  60770. quality (Graphics::lowResamplingQuality),
  60771. mouseSource (0, true)
  60772. {
  60773. holderComp = new PeerHolderComp (this);
  60774. setScaleFactor (1.0);
  60775. }
  60776. MagnifierComponent::~MagnifierComponent()
  60777. {
  60778. delete holderComp;
  60779. if (deleteContent)
  60780. delete content;
  60781. }
  60782. void MagnifierComponent::setScaleFactor (double newScaleFactor)
  60783. {
  60784. jassert (newScaleFactor > 0.0); // hmm - unlikely to work well with a negative scale factor
  60785. newScaleFactor = jlimit (1.0 / 8.0, 1000.0, newScaleFactor);
  60786. if (scaleFactor != newScaleFactor)
  60787. {
  60788. scaleFactor = newScaleFactor;
  60789. if (scaleFactor == 1.0)
  60790. {
  60791. holderComp->removeFromDesktop();
  60792. peer = 0;
  60793. addChildComponent (content);
  60794. childBoundsChanged (content);
  60795. }
  60796. else
  60797. {
  60798. holderComp->addAndMakeVisible (content);
  60799. holderComp->childBoundsChanged (content);
  60800. childBoundsChanged (holderComp);
  60801. holderComp->addToDesktop (0);
  60802. peer = holderComp->getPeer();
  60803. }
  60804. repaint();
  60805. }
  60806. }
  60807. void MagnifierComponent::setResamplingQuality (Graphics::ResamplingQuality newQuality)
  60808. {
  60809. quality = newQuality;
  60810. }
  60811. void MagnifierComponent::paint (Graphics& g)
  60812. {
  60813. const int w = holderComp->getWidth();
  60814. const int h = holderComp->getHeight();
  60815. if (w == 0 || h == 0)
  60816. return;
  60817. const Rectangle<int> r (g.getClipBounds());
  60818. const int srcX = (int) (r.getX() / scaleFactor);
  60819. const int srcY = (int) (r.getY() / scaleFactor);
  60820. int srcW = roundToInt (r.getRight() / scaleFactor) - srcX;
  60821. int srcH = roundToInt (r.getBottom() / scaleFactor) - srcY;
  60822. if (scaleFactor >= 1.0)
  60823. {
  60824. ++srcW;
  60825. ++srcH;
  60826. }
  60827. Image temp (Image::ARGB, jmax (w, srcX + srcW), jmax (h, srcY + srcH), false);
  60828. temp.clear (Rectangle<int> (srcX, srcY, srcW, srcH));
  60829. {
  60830. Graphics g2 (temp);
  60831. g2.reduceClipRegion (srcX, srcY, srcW, srcH);
  60832. holderComp->paintEntireComponent (g2);
  60833. }
  60834. g.setImageResamplingQuality (quality);
  60835. g.drawImageTransformed (temp, AffineTransform::scale ((float) scaleFactor, (float) scaleFactor), false);
  60836. }
  60837. void MagnifierComponent::childBoundsChanged (Component* c)
  60838. {
  60839. if (c != 0)
  60840. setSize (roundToInt (c->getWidth() * scaleFactor),
  60841. roundToInt (c->getHeight() * scaleFactor));
  60842. }
  60843. void MagnifierComponent::passOnMouseEventToPeer (const MouseEvent& e)
  60844. {
  60845. if (peer != 0)
  60846. mouseSource.handleEvent (peer, Point<int> (scaleInt (e.x), scaleInt (e.y)),
  60847. e.eventTime.toMilliseconds(), ModifierKeys::getCurrentModifiers());
  60848. }
  60849. void MagnifierComponent::mouseDown (const MouseEvent& e)
  60850. {
  60851. passOnMouseEventToPeer (e);
  60852. }
  60853. void MagnifierComponent::mouseUp (const MouseEvent& e)
  60854. {
  60855. passOnMouseEventToPeer (e);
  60856. }
  60857. void MagnifierComponent::mouseDrag (const MouseEvent& e)
  60858. {
  60859. passOnMouseEventToPeer (e);
  60860. }
  60861. void MagnifierComponent::mouseMove (const MouseEvent& e)
  60862. {
  60863. passOnMouseEventToPeer (e);
  60864. }
  60865. void MagnifierComponent::mouseEnter (const MouseEvent& e)
  60866. {
  60867. passOnMouseEventToPeer (e);
  60868. }
  60869. void MagnifierComponent::mouseExit (const MouseEvent& e)
  60870. {
  60871. passOnMouseEventToPeer (e);
  60872. }
  60873. void MagnifierComponent::mouseWheelMove (const MouseEvent& e, float ix, float iy)
  60874. {
  60875. if (peer != 0)
  60876. peer->handleMouseWheel (e.source.getIndex(),
  60877. Point<int> (scaleInt (e.x), scaleInt (e.y)), e.eventTime.toMilliseconds(),
  60878. ix * 256.0f, iy * 256.0f);
  60879. else
  60880. Component::mouseWheelMove (e, ix, iy);
  60881. }
  60882. int MagnifierComponent::scaleInt (const int n) const
  60883. {
  60884. return roundToInt (n / scaleFactor);
  60885. }
  60886. END_JUCE_NAMESPACE
  60887. /*** End of inlined file: juce_MagnifierComponent.cpp ***/
  60888. /*** Start of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60889. BEGIN_JUCE_NAMESPACE
  60890. class MidiKeyboardUpDownButton : public Button
  60891. {
  60892. public:
  60893. MidiKeyboardUpDownButton (MidiKeyboardComponent* const owner_,
  60894. const int delta_)
  60895. : Button (String::empty),
  60896. owner (owner_),
  60897. delta (delta_)
  60898. {
  60899. setOpaque (true);
  60900. }
  60901. ~MidiKeyboardUpDownButton()
  60902. {
  60903. }
  60904. void clicked()
  60905. {
  60906. int note = owner->getLowestVisibleKey();
  60907. if (delta < 0)
  60908. note = (note - 1) / 12;
  60909. else
  60910. note = note / 12 + 1;
  60911. owner->setLowestVisibleKey (note * 12);
  60912. }
  60913. void paintButton (Graphics& g,
  60914. bool isMouseOverButton,
  60915. bool isButtonDown)
  60916. {
  60917. owner->drawUpDownButton (g, getWidth(), getHeight(),
  60918. isMouseOverButton, isButtonDown,
  60919. delta > 0);
  60920. }
  60921. private:
  60922. MidiKeyboardComponent* const owner;
  60923. const int delta;
  60924. MidiKeyboardUpDownButton (const MidiKeyboardUpDownButton&);
  60925. MidiKeyboardUpDownButton& operator= (const MidiKeyboardUpDownButton&);
  60926. };
  60927. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  60928. const Orientation orientation_)
  60929. : state (state_),
  60930. xOffset (0),
  60931. blackNoteLength (1),
  60932. keyWidth (16.0f),
  60933. orientation (orientation_),
  60934. midiChannel (1),
  60935. midiInChannelMask (0xffff),
  60936. velocity (1.0f),
  60937. noteUnderMouse (-1),
  60938. mouseDownNote (-1),
  60939. rangeStart (0),
  60940. rangeEnd (127),
  60941. firstKey (12 * 4),
  60942. canScroll (true),
  60943. mouseDragging (false),
  60944. useMousePositionForVelocity (true),
  60945. keyMappingOctave (6),
  60946. octaveNumForMiddleC (3)
  60947. {
  60948. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (this, -1));
  60949. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (this, 1));
  60950. // initialise with a default set of querty key-mappings..
  60951. const char* const keymap = "awsedftgyhujkolp;";
  60952. for (int i = String (keymap).length(); --i >= 0;)
  60953. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  60954. setOpaque (true);
  60955. setWantsKeyboardFocus (true);
  60956. state.addListener (this);
  60957. }
  60958. MidiKeyboardComponent::~MidiKeyboardComponent()
  60959. {
  60960. state.removeListener (this);
  60961. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  60962. deleteAllChildren();
  60963. }
  60964. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  60965. {
  60966. keyWidth = widthInPixels;
  60967. resized();
  60968. }
  60969. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  60970. {
  60971. if (orientation != newOrientation)
  60972. {
  60973. orientation = newOrientation;
  60974. resized();
  60975. }
  60976. }
  60977. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  60978. const int highestNote)
  60979. {
  60980. jassert (lowestNote >= 0 && lowestNote <= 127);
  60981. jassert (highestNote >= 0 && highestNote <= 127);
  60982. jassert (lowestNote <= highestNote);
  60983. if (rangeStart != lowestNote || rangeEnd != highestNote)
  60984. {
  60985. rangeStart = jlimit (0, 127, lowestNote);
  60986. rangeEnd = jlimit (0, 127, highestNote);
  60987. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  60988. resized();
  60989. }
  60990. }
  60991. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  60992. {
  60993. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  60994. if (noteNumber != firstKey)
  60995. {
  60996. firstKey = noteNumber;
  60997. sendChangeMessage (this);
  60998. resized();
  60999. }
  61000. }
  61001. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  61002. {
  61003. if (canScroll != canScroll_)
  61004. {
  61005. canScroll = canScroll_;
  61006. resized();
  61007. }
  61008. }
  61009. void MidiKeyboardComponent::colourChanged()
  61010. {
  61011. repaint();
  61012. }
  61013. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  61014. {
  61015. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  61016. if (midiChannel != midiChannelNumber)
  61017. {
  61018. resetAnyKeysInUse();
  61019. midiChannel = jlimit (1, 16, midiChannelNumber);
  61020. }
  61021. }
  61022. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  61023. {
  61024. midiInChannelMask = midiChannelMask;
  61025. triggerAsyncUpdate();
  61026. }
  61027. void MidiKeyboardComponent::setVelocity (const float velocity_, const bool useMousePositionForVelocity_)
  61028. {
  61029. velocity = jlimit (0.0f, 1.0f, velocity_);
  61030. useMousePositionForVelocity = useMousePositionForVelocity_;
  61031. }
  61032. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth_, int& x, int& w) const
  61033. {
  61034. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  61035. static const float blackNoteWidth = 0.7f;
  61036. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  61037. 1.0f, 2 - blackNoteWidth * 0.4f,
  61038. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  61039. 4.0f, 5 - blackNoteWidth * 0.5f,
  61040. 5.0f, 6 - blackNoteWidth * 0.3f,
  61041. 6.0f };
  61042. static const float widths[] = { 1.0f, blackNoteWidth,
  61043. 1.0f, blackNoteWidth,
  61044. 1.0f, 1.0f, blackNoteWidth,
  61045. 1.0f, blackNoteWidth,
  61046. 1.0f, blackNoteWidth,
  61047. 1.0f };
  61048. const int octave = midiNoteNumber / 12;
  61049. const int note = midiNoteNumber % 12;
  61050. x = roundToInt (octave * 7.0f * keyWidth_ + notePos [note] * keyWidth_);
  61051. w = roundToInt (widths [note] * keyWidth_);
  61052. }
  61053. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  61054. {
  61055. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  61056. int rx, rw;
  61057. getKeyPosition (rangeStart, keyWidth, rx, rw);
  61058. x -= xOffset + rx;
  61059. }
  61060. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  61061. {
  61062. int x, y;
  61063. getKeyPos (midiNoteNumber, x, y);
  61064. return x;
  61065. }
  61066. const uint8 MidiKeyboardComponent::whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  61067. const uint8 MidiKeyboardComponent::blackNotes[] = { 1, 3, 6, 8, 10 };
  61068. int MidiKeyboardComponent::xyToNote (const Point<int>& pos, float& mousePositionVelocity)
  61069. {
  61070. if (! reallyContains (pos.getX(), pos.getY(), false))
  61071. return -1;
  61072. Point<int> p (pos);
  61073. if (orientation != horizontalKeyboard)
  61074. {
  61075. p = Point<int> (p.getY(), p.getX());
  61076. if (orientation == verticalKeyboardFacingLeft)
  61077. p = Point<int> (p.getX(), getWidth() - p.getY());
  61078. else
  61079. p = Point<int> (getHeight() - p.getX(), p.getY());
  61080. }
  61081. return remappedXYToNote (p + Point<int> (xOffset, 0), mousePositionVelocity);
  61082. }
  61083. int MidiKeyboardComponent::remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const
  61084. {
  61085. if (pos.getY() < blackNoteLength)
  61086. {
  61087. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  61088. {
  61089. for (int i = 0; i < 5; ++i)
  61090. {
  61091. const int note = octaveStart + blackNotes [i];
  61092. if (note >= rangeStart && note <= rangeEnd)
  61093. {
  61094. int kx, kw;
  61095. getKeyPos (note, kx, kw);
  61096. kx += xOffset;
  61097. if (pos.getX() >= kx && pos.getX() < kx + kw)
  61098. {
  61099. mousePositionVelocity = pos.getY() / (float) blackNoteLength;
  61100. return note;
  61101. }
  61102. }
  61103. }
  61104. }
  61105. }
  61106. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  61107. {
  61108. for (int i = 0; i < 7; ++i)
  61109. {
  61110. const int note = octaveStart + whiteNotes [i];
  61111. if (note >= rangeStart && note <= rangeEnd)
  61112. {
  61113. int kx, kw;
  61114. getKeyPos (note, kx, kw);
  61115. kx += xOffset;
  61116. if (pos.getX() >= kx && pos.getX() < kx + kw)
  61117. {
  61118. const int whiteNoteLength = (orientation == horizontalKeyboard) ? getHeight() : getWidth();
  61119. mousePositionVelocity = pos.getY() / (float) whiteNoteLength;
  61120. return note;
  61121. }
  61122. }
  61123. }
  61124. }
  61125. mousePositionVelocity = 0;
  61126. return -1;
  61127. }
  61128. void MidiKeyboardComponent::repaintNote (const int noteNum)
  61129. {
  61130. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  61131. {
  61132. int x, w;
  61133. getKeyPos (noteNum, x, w);
  61134. if (orientation == horizontalKeyboard)
  61135. repaint (x, 0, w, getHeight());
  61136. else if (orientation == verticalKeyboardFacingLeft)
  61137. repaint (0, x, getWidth(), w);
  61138. else if (orientation == verticalKeyboardFacingRight)
  61139. repaint (0, getHeight() - x - w, getWidth(), w);
  61140. }
  61141. }
  61142. void MidiKeyboardComponent::paint (Graphics& g)
  61143. {
  61144. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  61145. const Colour lineColour (findColour (keySeparatorLineColourId));
  61146. const Colour textColour (findColour (textLabelColourId));
  61147. int x, w, octave;
  61148. for (octave = 0; octave < 128; octave += 12)
  61149. {
  61150. for (int white = 0; white < 7; ++white)
  61151. {
  61152. const int noteNum = octave + whiteNotes [white];
  61153. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  61154. {
  61155. getKeyPos (noteNum, x, w);
  61156. if (orientation == horizontalKeyboard)
  61157. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  61158. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61159. noteUnderMouse == noteNum,
  61160. lineColour, textColour);
  61161. else if (orientation == verticalKeyboardFacingLeft)
  61162. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  61163. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61164. noteUnderMouse == noteNum,
  61165. lineColour, textColour);
  61166. else if (orientation == verticalKeyboardFacingRight)
  61167. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  61168. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61169. noteUnderMouse == noteNum,
  61170. lineColour, textColour);
  61171. }
  61172. }
  61173. }
  61174. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  61175. if (orientation == verticalKeyboardFacingLeft)
  61176. {
  61177. x1 = getWidth() - 1.0f;
  61178. x2 = getWidth() - 5.0f;
  61179. }
  61180. else if (orientation == verticalKeyboardFacingRight)
  61181. x2 = 5.0f;
  61182. else
  61183. y2 = 5.0f;
  61184. g.setGradientFill (ColourGradient (Colours::black.withAlpha (0.3f), x1, y1,
  61185. Colours::transparentBlack, x2, y2, false));
  61186. getKeyPos (rangeEnd, x, w);
  61187. x += w;
  61188. if (orientation == verticalKeyboardFacingLeft)
  61189. g.fillRect (getWidth() - 5, 0, 5, x);
  61190. else if (orientation == verticalKeyboardFacingRight)
  61191. g.fillRect (0, 0, 5, x);
  61192. else
  61193. g.fillRect (0, 0, x, 5);
  61194. g.setColour (lineColour);
  61195. if (orientation == verticalKeyboardFacingLeft)
  61196. g.fillRect (0, 0, 1, x);
  61197. else if (orientation == verticalKeyboardFacingRight)
  61198. g.fillRect (getWidth() - 1, 0, 1, x);
  61199. else
  61200. g.fillRect (0, getHeight() - 1, x, 1);
  61201. const Colour blackNoteColour (findColour (blackNoteColourId));
  61202. for (octave = 0; octave < 128; octave += 12)
  61203. {
  61204. for (int black = 0; black < 5; ++black)
  61205. {
  61206. const int noteNum = octave + blackNotes [black];
  61207. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  61208. {
  61209. getKeyPos (noteNum, x, w);
  61210. if (orientation == horizontalKeyboard)
  61211. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  61212. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61213. noteUnderMouse == noteNum,
  61214. blackNoteColour);
  61215. else if (orientation == verticalKeyboardFacingLeft)
  61216. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  61217. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61218. noteUnderMouse == noteNum,
  61219. blackNoteColour);
  61220. else if (orientation == verticalKeyboardFacingRight)
  61221. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  61222. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61223. noteUnderMouse == noteNum,
  61224. blackNoteColour);
  61225. }
  61226. }
  61227. }
  61228. }
  61229. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  61230. Graphics& g, int x, int y, int w, int h,
  61231. bool isDown, bool isOver,
  61232. const Colour& lineColour,
  61233. const Colour& textColour)
  61234. {
  61235. Colour c (Colours::transparentWhite);
  61236. if (isDown)
  61237. c = findColour (keyDownOverlayColourId);
  61238. if (isOver)
  61239. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  61240. g.setColour (c);
  61241. g.fillRect (x, y, w, h);
  61242. const String text (getWhiteNoteText (midiNoteNumber));
  61243. if (! text.isEmpty())
  61244. {
  61245. g.setColour (textColour);
  61246. Font f (jmin (12.0f, keyWidth * 0.9f));
  61247. f.setHorizontalScale (0.8f);
  61248. g.setFont (f);
  61249. Justification justification (Justification::centredBottom);
  61250. if (orientation == verticalKeyboardFacingLeft)
  61251. justification = Justification::centredLeft;
  61252. else if (orientation == verticalKeyboardFacingRight)
  61253. justification = Justification::centredRight;
  61254. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  61255. }
  61256. g.setColour (lineColour);
  61257. if (orientation == horizontalKeyboard)
  61258. g.fillRect (x, y, 1, h);
  61259. else if (orientation == verticalKeyboardFacingLeft)
  61260. g.fillRect (x, y, w, 1);
  61261. else if (orientation == verticalKeyboardFacingRight)
  61262. g.fillRect (x, y + h - 1, w, 1);
  61263. if (midiNoteNumber == rangeEnd)
  61264. {
  61265. if (orientation == horizontalKeyboard)
  61266. g.fillRect (x + w, y, 1, h);
  61267. else if (orientation == verticalKeyboardFacingLeft)
  61268. g.fillRect (x, y + h, w, 1);
  61269. else if (orientation == verticalKeyboardFacingRight)
  61270. g.fillRect (x, y - 1, w, 1);
  61271. }
  61272. }
  61273. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  61274. Graphics& g, int x, int y, int w, int h,
  61275. bool isDown, bool isOver,
  61276. const Colour& noteFillColour)
  61277. {
  61278. Colour c (noteFillColour);
  61279. if (isDown)
  61280. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  61281. if (isOver)
  61282. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  61283. g.setColour (c);
  61284. g.fillRect (x, y, w, h);
  61285. if (isDown)
  61286. {
  61287. g.setColour (noteFillColour);
  61288. g.drawRect (x, y, w, h);
  61289. }
  61290. else
  61291. {
  61292. const int xIndent = jmax (1, jmin (w, h) / 8);
  61293. g.setColour (c.brighter());
  61294. if (orientation == horizontalKeyboard)
  61295. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  61296. else if (orientation == verticalKeyboardFacingLeft)
  61297. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  61298. else if (orientation == verticalKeyboardFacingRight)
  61299. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  61300. }
  61301. }
  61302. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_)
  61303. {
  61304. octaveNumForMiddleC = octaveNumForMiddleC_;
  61305. repaint();
  61306. }
  61307. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  61308. {
  61309. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  61310. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  61311. return String::empty;
  61312. }
  61313. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  61314. const bool isMouseOver_,
  61315. const bool isButtonDown,
  61316. const bool movesOctavesUp)
  61317. {
  61318. g.fillAll (findColour (upDownButtonBackgroundColourId));
  61319. float angle;
  61320. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  61321. angle = movesOctavesUp ? 0.0f : 0.5f;
  61322. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  61323. angle = movesOctavesUp ? 0.25f : 0.75f;
  61324. else
  61325. angle = movesOctavesUp ? 0.75f : 0.25f;
  61326. Path path;
  61327. path.lineTo (0.0f, 1.0f);
  61328. path.lineTo (1.0f, 0.5f);
  61329. path.closeSubPath();
  61330. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  61331. g.setColour (findColour (upDownButtonArrowColourId)
  61332. .withAlpha (isButtonDown ? 1.0f : (isMouseOver_ ? 0.6f : 0.4f)));
  61333. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  61334. w - 2.0f,
  61335. h - 2.0f,
  61336. true));
  61337. }
  61338. void MidiKeyboardComponent::resized()
  61339. {
  61340. int w = getWidth();
  61341. int h = getHeight();
  61342. if (w > 0 && h > 0)
  61343. {
  61344. if (orientation != horizontalKeyboard)
  61345. swapVariables (w, h);
  61346. blackNoteLength = roundToInt (h * 0.7f);
  61347. int kx2, kw2;
  61348. getKeyPos (rangeEnd, kx2, kw2);
  61349. kx2 += kw2;
  61350. if (firstKey != rangeStart)
  61351. {
  61352. int kx1, kw1;
  61353. getKeyPos (rangeStart, kx1, kw1);
  61354. if (kx2 - kx1 <= w)
  61355. {
  61356. firstKey = rangeStart;
  61357. sendChangeMessage (this);
  61358. repaint();
  61359. }
  61360. }
  61361. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  61362. scrollDown->setVisible (showScrollButtons);
  61363. scrollUp->setVisible (showScrollButtons);
  61364. xOffset = 0;
  61365. if (showScrollButtons)
  61366. {
  61367. const int scrollButtonW = jmin (12, w / 2);
  61368. if (orientation == horizontalKeyboard)
  61369. {
  61370. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  61371. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  61372. }
  61373. else if (orientation == verticalKeyboardFacingLeft)
  61374. {
  61375. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  61376. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  61377. }
  61378. else if (orientation == verticalKeyboardFacingRight)
  61379. {
  61380. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  61381. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  61382. }
  61383. int endOfLastKey, kw;
  61384. getKeyPos (rangeEnd, endOfLastKey, kw);
  61385. endOfLastKey += kw;
  61386. float mousePositionVelocity;
  61387. const int spaceAvailable = w - scrollButtonW * 2;
  61388. const int lastStartKey = remappedXYToNote (Point<int> (endOfLastKey - spaceAvailable, 0), mousePositionVelocity) + 1;
  61389. if (lastStartKey >= 0 && firstKey > lastStartKey)
  61390. {
  61391. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  61392. sendChangeMessage (this);
  61393. }
  61394. int newOffset = 0;
  61395. getKeyPos (firstKey, newOffset, kw);
  61396. xOffset = newOffset - scrollButtonW;
  61397. }
  61398. else
  61399. {
  61400. firstKey = rangeStart;
  61401. }
  61402. timerCallback();
  61403. repaint();
  61404. }
  61405. }
  61406. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  61407. {
  61408. triggerAsyncUpdate();
  61409. }
  61410. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  61411. {
  61412. triggerAsyncUpdate();
  61413. }
  61414. void MidiKeyboardComponent::handleAsyncUpdate()
  61415. {
  61416. for (int i = rangeStart; i <= rangeEnd; ++i)
  61417. {
  61418. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  61419. {
  61420. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  61421. repaintNote (i);
  61422. }
  61423. }
  61424. }
  61425. void MidiKeyboardComponent::resetAnyKeysInUse()
  61426. {
  61427. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  61428. {
  61429. state.allNotesOff (midiChannel);
  61430. keysPressed.clear();
  61431. mouseDownNote = -1;
  61432. }
  61433. }
  61434. void MidiKeyboardComponent::updateNoteUnderMouse (const Point<int>& pos)
  61435. {
  61436. float mousePositionVelocity = 0.0f;
  61437. const int newNote = (mouseDragging || isMouseOver())
  61438. ? xyToNote (pos, mousePositionVelocity) : -1;
  61439. if (noteUnderMouse != newNote)
  61440. {
  61441. if (mouseDownNote >= 0)
  61442. {
  61443. state.noteOff (midiChannel, mouseDownNote);
  61444. mouseDownNote = -1;
  61445. }
  61446. if (mouseDragging && newNote >= 0)
  61447. {
  61448. if (! useMousePositionForVelocity)
  61449. mousePositionVelocity = 1.0f;
  61450. state.noteOn (midiChannel, newNote, mousePositionVelocity * velocity);
  61451. mouseDownNote = newNote;
  61452. }
  61453. repaintNote (noteUnderMouse);
  61454. noteUnderMouse = newNote;
  61455. repaintNote (noteUnderMouse);
  61456. }
  61457. else if (mouseDownNote >= 0 && ! mouseDragging)
  61458. {
  61459. state.noteOff (midiChannel, mouseDownNote);
  61460. mouseDownNote = -1;
  61461. }
  61462. }
  61463. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  61464. {
  61465. updateNoteUnderMouse (e.getPosition());
  61466. stopTimer();
  61467. }
  61468. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  61469. {
  61470. float mousePositionVelocity;
  61471. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  61472. if (newNote >= 0)
  61473. mouseDraggedToKey (newNote, e);
  61474. updateNoteUnderMouse (e.getPosition());
  61475. }
  61476. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  61477. {
  61478. return true;
  61479. }
  61480. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  61481. {
  61482. }
  61483. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  61484. {
  61485. float mousePositionVelocity;
  61486. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  61487. mouseDragging = false;
  61488. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  61489. {
  61490. repaintNote (noteUnderMouse);
  61491. noteUnderMouse = -1;
  61492. mouseDragging = true;
  61493. updateNoteUnderMouse (e.getPosition());
  61494. startTimer (500);
  61495. }
  61496. }
  61497. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  61498. {
  61499. mouseDragging = false;
  61500. updateNoteUnderMouse (e.getPosition());
  61501. stopTimer();
  61502. }
  61503. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  61504. {
  61505. updateNoteUnderMouse (e.getPosition());
  61506. }
  61507. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  61508. {
  61509. updateNoteUnderMouse (e.getPosition());
  61510. }
  61511. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  61512. {
  61513. setLowestVisibleKey (getLowestVisibleKey() + roundToInt ((ix != 0 ? ix : iy) * 5.0f));
  61514. }
  61515. void MidiKeyboardComponent::timerCallback()
  61516. {
  61517. updateNoteUnderMouse (getMouseXYRelative());
  61518. }
  61519. void MidiKeyboardComponent::clearKeyMappings()
  61520. {
  61521. resetAnyKeysInUse();
  61522. keyPressNotes.clear();
  61523. keyPresses.clear();
  61524. }
  61525. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  61526. const int midiNoteOffsetFromC)
  61527. {
  61528. removeKeyPressForNote (midiNoteOffsetFromC);
  61529. keyPressNotes.add (midiNoteOffsetFromC);
  61530. keyPresses.add (key);
  61531. }
  61532. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  61533. {
  61534. for (int i = keyPressNotes.size(); --i >= 0;)
  61535. {
  61536. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  61537. {
  61538. keyPressNotes.remove (i);
  61539. keyPresses.remove (i);
  61540. }
  61541. }
  61542. }
  61543. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  61544. {
  61545. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  61546. keyMappingOctave = newOctaveNumber;
  61547. }
  61548. bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
  61549. {
  61550. bool keyPressUsed = false;
  61551. for (int i = keyPresses.size(); --i >= 0;)
  61552. {
  61553. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  61554. if (keyPresses.getReference(i).isCurrentlyDown())
  61555. {
  61556. if (! keysPressed [note])
  61557. {
  61558. keysPressed.setBit (note);
  61559. state.noteOn (midiChannel, note, velocity);
  61560. keyPressUsed = true;
  61561. }
  61562. }
  61563. else
  61564. {
  61565. if (keysPressed [note])
  61566. {
  61567. keysPressed.clearBit (note);
  61568. state.noteOff (midiChannel, note);
  61569. keyPressUsed = true;
  61570. }
  61571. }
  61572. }
  61573. return keyPressUsed;
  61574. }
  61575. void MidiKeyboardComponent::focusLost (FocusChangeType)
  61576. {
  61577. resetAnyKeysInUse();
  61578. }
  61579. END_JUCE_NAMESPACE
  61580. /*** End of inlined file: juce_MidiKeyboardComponent.cpp ***/
  61581. /*** Start of inlined file: juce_OpenGLComponent.cpp ***/
  61582. #if JUCE_OPENGL
  61583. BEGIN_JUCE_NAMESPACE
  61584. extern void juce_glViewport (const int w, const int h);
  61585. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  61586. const int alphaBits_,
  61587. const int depthBufferBits_,
  61588. const int stencilBufferBits_)
  61589. : redBits (bitsPerRGBComponent),
  61590. greenBits (bitsPerRGBComponent),
  61591. blueBits (bitsPerRGBComponent),
  61592. alphaBits (alphaBits_),
  61593. depthBufferBits (depthBufferBits_),
  61594. stencilBufferBits (stencilBufferBits_),
  61595. accumulationBufferRedBits (0),
  61596. accumulationBufferGreenBits (0),
  61597. accumulationBufferBlueBits (0),
  61598. accumulationBufferAlphaBits (0),
  61599. fullSceneAntiAliasingNumSamples (0)
  61600. {
  61601. }
  61602. OpenGLPixelFormat::OpenGLPixelFormat (const OpenGLPixelFormat& other)
  61603. : redBits (other.redBits),
  61604. greenBits (other.greenBits),
  61605. blueBits (other.blueBits),
  61606. alphaBits (other.alphaBits),
  61607. depthBufferBits (other.depthBufferBits),
  61608. stencilBufferBits (other.stencilBufferBits),
  61609. accumulationBufferRedBits (other.accumulationBufferRedBits),
  61610. accumulationBufferGreenBits (other.accumulationBufferGreenBits),
  61611. accumulationBufferBlueBits (other.accumulationBufferBlueBits),
  61612. accumulationBufferAlphaBits (other.accumulationBufferAlphaBits),
  61613. fullSceneAntiAliasingNumSamples (other.fullSceneAntiAliasingNumSamples)
  61614. {
  61615. }
  61616. OpenGLPixelFormat& OpenGLPixelFormat::operator= (const OpenGLPixelFormat& other)
  61617. {
  61618. redBits = other.redBits;
  61619. greenBits = other.greenBits;
  61620. blueBits = other.blueBits;
  61621. alphaBits = other.alphaBits;
  61622. depthBufferBits = other.depthBufferBits;
  61623. stencilBufferBits = other.stencilBufferBits;
  61624. accumulationBufferRedBits = other.accumulationBufferRedBits;
  61625. accumulationBufferGreenBits = other.accumulationBufferGreenBits;
  61626. accumulationBufferBlueBits = other.accumulationBufferBlueBits;
  61627. accumulationBufferAlphaBits = other.accumulationBufferAlphaBits;
  61628. fullSceneAntiAliasingNumSamples = other.fullSceneAntiAliasingNumSamples;
  61629. return *this;
  61630. }
  61631. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const
  61632. {
  61633. return redBits == other.redBits
  61634. && greenBits == other.greenBits
  61635. && blueBits == other.blueBits
  61636. && alphaBits == other.alphaBits
  61637. && depthBufferBits == other.depthBufferBits
  61638. && stencilBufferBits == other.stencilBufferBits
  61639. && accumulationBufferRedBits == other.accumulationBufferRedBits
  61640. && accumulationBufferGreenBits == other.accumulationBufferGreenBits
  61641. && accumulationBufferBlueBits == other.accumulationBufferBlueBits
  61642. && accumulationBufferAlphaBits == other.accumulationBufferAlphaBits
  61643. && fullSceneAntiAliasingNumSamples == other.fullSceneAntiAliasingNumSamples;
  61644. }
  61645. static Array<OpenGLContext*> knownContexts;
  61646. OpenGLContext::OpenGLContext() throw()
  61647. {
  61648. knownContexts.add (this);
  61649. }
  61650. OpenGLContext::~OpenGLContext()
  61651. {
  61652. knownContexts.removeValue (this);
  61653. }
  61654. OpenGLContext* OpenGLContext::getCurrentContext()
  61655. {
  61656. for (int i = knownContexts.size(); --i >= 0;)
  61657. {
  61658. OpenGLContext* const oglc = knownContexts.getUnchecked(i);
  61659. if (oglc->isActive())
  61660. return oglc;
  61661. }
  61662. return 0;
  61663. }
  61664. class OpenGLComponent::OpenGLComponentWatcher : public ComponentMovementWatcher
  61665. {
  61666. public:
  61667. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  61668. : ComponentMovementWatcher (owner_),
  61669. owner (owner_),
  61670. wasShowing (false)
  61671. {
  61672. }
  61673. ~OpenGLComponentWatcher() {}
  61674. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  61675. {
  61676. owner->updateContextPosition();
  61677. }
  61678. void componentPeerChanged()
  61679. {
  61680. const ScopedLock sl (owner->getContextLock());
  61681. owner->deleteContext();
  61682. }
  61683. void componentVisibilityChanged (Component&)
  61684. {
  61685. const bool isShowingNow = owner->isShowing();
  61686. if (wasShowing != isShowingNow)
  61687. {
  61688. wasShowing = isShowingNow;
  61689. if (! isShowingNow)
  61690. {
  61691. const ScopedLock sl (owner->getContextLock());
  61692. owner->deleteContext();
  61693. }
  61694. }
  61695. }
  61696. juce_UseDebuggingNewOperator
  61697. private:
  61698. OpenGLComponent* const owner;
  61699. bool wasShowing;
  61700. };
  61701. OpenGLComponent::OpenGLComponent (const OpenGLType type_)
  61702. : type (type_),
  61703. contextToShareListsWith (0),
  61704. needToUpdateViewport (true)
  61705. {
  61706. setOpaque (true);
  61707. componentWatcher = new OpenGLComponentWatcher (this);
  61708. }
  61709. OpenGLComponent::~OpenGLComponent()
  61710. {
  61711. deleteContext();
  61712. componentWatcher = 0;
  61713. }
  61714. void OpenGLComponent::deleteContext()
  61715. {
  61716. const ScopedLock sl (contextLock);
  61717. context = 0;
  61718. }
  61719. void OpenGLComponent::updateContextPosition()
  61720. {
  61721. needToUpdateViewport = true;
  61722. if (getWidth() > 0 && getHeight() > 0)
  61723. {
  61724. Component* const topComp = getTopLevelComponent();
  61725. if (topComp->getPeer() != 0)
  61726. {
  61727. const ScopedLock sl (contextLock);
  61728. if (context != 0)
  61729. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  61730. getScreenY() - topComp->getScreenY(),
  61731. getWidth(),
  61732. getHeight(),
  61733. topComp->getHeight());
  61734. }
  61735. }
  61736. }
  61737. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  61738. {
  61739. OpenGLPixelFormat pf;
  61740. const ScopedLock sl (contextLock);
  61741. if (context != 0)
  61742. pf = context->getPixelFormat();
  61743. return pf;
  61744. }
  61745. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  61746. {
  61747. if (! (preferredPixelFormat == formatToUse))
  61748. {
  61749. const ScopedLock sl (contextLock);
  61750. deleteContext();
  61751. preferredPixelFormat = formatToUse;
  61752. }
  61753. }
  61754. void OpenGLComponent::shareWith (OpenGLContext* c)
  61755. {
  61756. if (contextToShareListsWith != c)
  61757. {
  61758. const ScopedLock sl (contextLock);
  61759. deleteContext();
  61760. contextToShareListsWith = c;
  61761. }
  61762. }
  61763. bool OpenGLComponent::makeCurrentContextActive()
  61764. {
  61765. if (context == 0)
  61766. {
  61767. const ScopedLock sl (contextLock);
  61768. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  61769. {
  61770. context = createContext();
  61771. if (context != 0)
  61772. {
  61773. updateContextPosition();
  61774. if (context->makeActive())
  61775. newOpenGLContextCreated();
  61776. }
  61777. }
  61778. }
  61779. return context != 0 && context->makeActive();
  61780. }
  61781. void OpenGLComponent::makeCurrentContextInactive()
  61782. {
  61783. if (context != 0)
  61784. context->makeInactive();
  61785. }
  61786. bool OpenGLComponent::isActiveContext() const throw()
  61787. {
  61788. return context != 0 && context->isActive();
  61789. }
  61790. void OpenGLComponent::swapBuffers()
  61791. {
  61792. if (context != 0)
  61793. context->swapBuffers();
  61794. }
  61795. void OpenGLComponent::paint (Graphics&)
  61796. {
  61797. if (renderAndSwapBuffers())
  61798. {
  61799. ComponentPeer* const peer = getPeer();
  61800. if (peer != 0)
  61801. {
  61802. const Point<int> topLeft (getScreenPosition() - peer->getScreenPosition());
  61803. peer->addMaskedRegion (topLeft.getX(), topLeft.getY(), getWidth(), getHeight());
  61804. }
  61805. }
  61806. }
  61807. bool OpenGLComponent::renderAndSwapBuffers()
  61808. {
  61809. const ScopedLock sl (contextLock);
  61810. if (! makeCurrentContextActive())
  61811. return false;
  61812. if (needToUpdateViewport)
  61813. {
  61814. needToUpdateViewport = false;
  61815. juce_glViewport (getWidth(), getHeight());
  61816. }
  61817. renderOpenGL();
  61818. swapBuffers();
  61819. return true;
  61820. }
  61821. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  61822. {
  61823. Component::internalRepaint (x, y, w, h);
  61824. if (context != 0)
  61825. context->repaint();
  61826. }
  61827. END_JUCE_NAMESPACE
  61828. #endif
  61829. /*** End of inlined file: juce_OpenGLComponent.cpp ***/
  61830. /*** Start of inlined file: juce_PreferencesPanel.cpp ***/
  61831. BEGIN_JUCE_NAMESPACE
  61832. PreferencesPanel::PreferencesPanel()
  61833. : buttonSize (70)
  61834. {
  61835. }
  61836. PreferencesPanel::~PreferencesPanel()
  61837. {
  61838. currentPage = 0;
  61839. deleteAllChildren();
  61840. }
  61841. void PreferencesPanel::addSettingsPage (const String& title,
  61842. const Drawable* icon,
  61843. const Drawable* overIcon,
  61844. const Drawable* downIcon)
  61845. {
  61846. DrawableButton* button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  61847. button->setImages (icon, overIcon, downIcon);
  61848. button->setRadioGroupId (1);
  61849. button->addButtonListener (this);
  61850. button->setClickingTogglesState (true);
  61851. button->setWantsKeyboardFocus (false);
  61852. addAndMakeVisible (button);
  61853. resized();
  61854. if (currentPage == 0)
  61855. setCurrentPage (title);
  61856. }
  61857. void PreferencesPanel::addSettingsPage (const String& title,
  61858. const void* imageData,
  61859. const int imageDataSize)
  61860. {
  61861. DrawableImage icon, iconOver, iconDown;
  61862. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61863. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61864. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  61865. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61866. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  61867. addSettingsPage (title, &icon, &iconOver, &iconDown);
  61868. }
  61869. class PrefsDialogWindow : public DialogWindow
  61870. {
  61871. public:
  61872. PrefsDialogWindow (const String& dialogtitle,
  61873. const Colour& backgroundColour)
  61874. : DialogWindow (dialogtitle, backgroundColour, true)
  61875. {
  61876. }
  61877. ~PrefsDialogWindow()
  61878. {
  61879. }
  61880. void closeButtonPressed()
  61881. {
  61882. exitModalState (0);
  61883. }
  61884. private:
  61885. PrefsDialogWindow (const PrefsDialogWindow&);
  61886. PrefsDialogWindow& operator= (const PrefsDialogWindow&);
  61887. };
  61888. void PreferencesPanel::showInDialogBox (const String& dialogtitle,
  61889. int dialogWidth,
  61890. int dialogHeight,
  61891. const Colour& backgroundColour)
  61892. {
  61893. setSize (dialogWidth, dialogHeight);
  61894. PrefsDialogWindow dw (dialogtitle, backgroundColour);
  61895. dw.setContentComponent (this, true, true);
  61896. dw.centreAroundComponent (0, dw.getWidth(), dw.getHeight());
  61897. dw.runModalLoop();
  61898. dw.setContentComponent (0, false, false);
  61899. }
  61900. void PreferencesPanel::resized()
  61901. {
  61902. int x = 0;
  61903. for (int i = 0; i < getNumChildComponents(); ++i)
  61904. {
  61905. Component* c = getChildComponent (i);
  61906. if (dynamic_cast <DrawableButton*> (c) == 0)
  61907. {
  61908. c->setBounds (0, buttonSize + 5, getWidth(), getHeight() - buttonSize - 5);
  61909. }
  61910. else
  61911. {
  61912. c->setBounds (x, 0, buttonSize, buttonSize);
  61913. x += buttonSize;
  61914. }
  61915. }
  61916. }
  61917. void PreferencesPanel::paint (Graphics& g)
  61918. {
  61919. g.setColour (Colours::grey);
  61920. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  61921. }
  61922. void PreferencesPanel::setCurrentPage (const String& pageName)
  61923. {
  61924. if (currentPageName != pageName)
  61925. {
  61926. currentPageName = pageName;
  61927. currentPage = 0;
  61928. currentPage = createComponentForPage (pageName);
  61929. if (currentPage != 0)
  61930. {
  61931. addAndMakeVisible (currentPage);
  61932. currentPage->toBack();
  61933. resized();
  61934. }
  61935. for (int i = 0; i < getNumChildComponents(); ++i)
  61936. {
  61937. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  61938. if (db != 0 && db->getName() == pageName)
  61939. {
  61940. db->setToggleState (true, false);
  61941. break;
  61942. }
  61943. }
  61944. }
  61945. }
  61946. void PreferencesPanel::buttonClicked (Button*)
  61947. {
  61948. for (int i = 0; i < getNumChildComponents(); ++i)
  61949. {
  61950. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  61951. if (db != 0 && db->getToggleState())
  61952. {
  61953. setCurrentPage (db->getName());
  61954. break;
  61955. }
  61956. }
  61957. }
  61958. END_JUCE_NAMESPACE
  61959. /*** End of inlined file: juce_PreferencesPanel.cpp ***/
  61960. /*** Start of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61961. #if JUCE_WINDOWS || JUCE_LINUX
  61962. BEGIN_JUCE_NAMESPACE
  61963. SystemTrayIconComponent::SystemTrayIconComponent()
  61964. {
  61965. addToDesktop (0);
  61966. }
  61967. SystemTrayIconComponent::~SystemTrayIconComponent()
  61968. {
  61969. }
  61970. END_JUCE_NAMESPACE
  61971. #endif
  61972. /*** End of inlined file: juce_SystemTrayIconComponent.cpp ***/
  61973. /*** Start of inlined file: juce_AlertWindow.cpp ***/
  61974. BEGIN_JUCE_NAMESPACE
  61975. class AlertWindowTextEditor : public TextEditor
  61976. {
  61977. public:
  61978. AlertWindowTextEditor (const String& name, const bool isPasswordBox)
  61979. : TextEditor (name, isPasswordBox ? getDefaultPasswordChar() : 0)
  61980. {
  61981. setSelectAllWhenFocused (true);
  61982. }
  61983. ~AlertWindowTextEditor()
  61984. {
  61985. }
  61986. void returnPressed()
  61987. {
  61988. // pass these up the component hierarchy to be trigger the buttons
  61989. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, '\n'));
  61990. }
  61991. void escapePressed()
  61992. {
  61993. // pass these up the component hierarchy to be trigger the buttons
  61994. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  61995. }
  61996. private:
  61997. AlertWindowTextEditor (const AlertWindowTextEditor&);
  61998. AlertWindowTextEditor& operator= (const AlertWindowTextEditor&);
  61999. static juce_wchar getDefaultPasswordChar() throw()
  62000. {
  62001. #if JUCE_LINUX
  62002. return 0x2022;
  62003. #else
  62004. return 0x25cf;
  62005. #endif
  62006. }
  62007. };
  62008. AlertWindow::AlertWindow (const String& title,
  62009. const String& message,
  62010. AlertIconType iconType,
  62011. Component* associatedComponent_)
  62012. : TopLevelWindow (title, true),
  62013. alertIconType (iconType),
  62014. associatedComponent (associatedComponent_)
  62015. {
  62016. if (message.isEmpty())
  62017. text = " "; // to force an update if the message is empty
  62018. setMessage (message);
  62019. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  62020. {
  62021. Component* const c = Desktop::getInstance().getComponent (i);
  62022. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  62023. {
  62024. setAlwaysOnTop (true);
  62025. break;
  62026. }
  62027. }
  62028. if (! JUCEApplication::isStandaloneApp())
  62029. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62030. lookAndFeelChanged();
  62031. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  62032. }
  62033. AlertWindow::~AlertWindow()
  62034. {
  62035. for (int i = customComps.size(); --i >= 0;)
  62036. removeChildComponent ((Component*) customComps[i]);
  62037. deleteAllChildren();
  62038. }
  62039. void AlertWindow::userTriedToCloseWindow()
  62040. {
  62041. exitModalState (0);
  62042. }
  62043. void AlertWindow::setMessage (const String& message)
  62044. {
  62045. const String newMessage (message.substring (0, 2048));
  62046. if (text != newMessage)
  62047. {
  62048. text = newMessage;
  62049. font.setHeight (15.0f);
  62050. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  62051. textLayout.setText (getName() + "\n\n", titleFont);
  62052. textLayout.appendText (text, font);
  62053. updateLayout (true);
  62054. repaint();
  62055. }
  62056. }
  62057. void AlertWindow::buttonClicked (Button* button)
  62058. {
  62059. for (int i = 0; i < buttons.size(); i++)
  62060. {
  62061. TextButton* const c = (TextButton*) buttons[i];
  62062. if (button->getName() == c->getName())
  62063. {
  62064. if (c->getParentComponent() != 0)
  62065. c->getParentComponent()->exitModalState (c->getCommandID());
  62066. break;
  62067. }
  62068. }
  62069. }
  62070. void AlertWindow::addButton (const String& name,
  62071. const int returnValue,
  62072. const KeyPress& shortcutKey1,
  62073. const KeyPress& shortcutKey2)
  62074. {
  62075. TextButton* const b = new TextButton (name, String::empty);
  62076. b->setWantsKeyboardFocus (true);
  62077. b->setMouseClickGrabsKeyboardFocus (false);
  62078. b->setCommandToTrigger (0, returnValue, false);
  62079. b->addShortcut (shortcutKey1);
  62080. b->addShortcut (shortcutKey2);
  62081. b->addButtonListener (this);
  62082. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  62083. addAndMakeVisible (b, 0);
  62084. buttons.add (b);
  62085. updateLayout (false);
  62086. }
  62087. int AlertWindow::getNumButtons() const
  62088. {
  62089. return buttons.size();
  62090. }
  62091. void AlertWindow::triggerButtonClick (const String& buttonName)
  62092. {
  62093. for (int i = buttons.size(); --i >= 0;)
  62094. {
  62095. TextButton* const b = (TextButton*) buttons[i];
  62096. if (buttonName == b->getName())
  62097. {
  62098. b->triggerClick();
  62099. break;
  62100. }
  62101. }
  62102. }
  62103. void AlertWindow::addTextEditor (const String& name,
  62104. const String& initialContents,
  62105. const String& onScreenLabel,
  62106. const bool isPasswordBox)
  62107. {
  62108. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  62109. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  62110. tc->setFont (font);
  62111. tc->setText (initialContents);
  62112. tc->setCaretPosition (initialContents.length());
  62113. addAndMakeVisible (tc);
  62114. textBoxes.add (tc);
  62115. allComps.add (tc);
  62116. textboxNames.add (onScreenLabel);
  62117. updateLayout (false);
  62118. }
  62119. TextEditor* AlertWindow::getTextEditor (const String& nameOfTextEditor) const
  62120. {
  62121. for (int i = textBoxes.size(); --i >= 0;)
  62122. if (static_cast <TextEditor*> (textBoxes.getUnchecked(i))->getName() == nameOfTextEditor)
  62123. return static_cast <TextEditor*> (textBoxes.getUnchecked(i));
  62124. return 0;
  62125. }
  62126. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  62127. {
  62128. TextEditor* const t = getTextEditor (nameOfTextEditor);
  62129. return t != 0 ? t->getText() : String::empty;
  62130. }
  62131. void AlertWindow::addComboBox (const String& name,
  62132. const StringArray& items,
  62133. const String& onScreenLabel)
  62134. {
  62135. ComboBox* const cb = new ComboBox (name);
  62136. for (int i = 0; i < items.size(); ++i)
  62137. cb->addItem (items[i], i + 1);
  62138. addAndMakeVisible (cb);
  62139. cb->setSelectedItemIndex (0);
  62140. comboBoxes.add (cb);
  62141. allComps.add (cb);
  62142. comboBoxNames.add (onScreenLabel);
  62143. updateLayout (false);
  62144. }
  62145. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  62146. {
  62147. for (int i = comboBoxes.size(); --i >= 0;)
  62148. if (((ComboBox*) comboBoxes[i])->getName() == nameOfList)
  62149. return (ComboBox*) comboBoxes[i];
  62150. return 0;
  62151. }
  62152. class AlertTextComp : public TextEditor
  62153. {
  62154. public:
  62155. AlertTextComp (const String& message,
  62156. const Font& font)
  62157. {
  62158. setReadOnly (true);
  62159. setMultiLine (true, true);
  62160. setCaretVisible (false);
  62161. setScrollbarsShown (true);
  62162. lookAndFeelChanged();
  62163. setWantsKeyboardFocus (false);
  62164. setFont (font);
  62165. setText (message, false);
  62166. bestWidth = 2 * (int) std::sqrt (font.getHeight() * font.getStringWidth (message));
  62167. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  62168. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  62169. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  62170. }
  62171. ~AlertTextComp()
  62172. {
  62173. }
  62174. int getPreferredWidth() const throw() { return bestWidth; }
  62175. void updateLayout (const int width)
  62176. {
  62177. TextLayout text;
  62178. text.appendText (getText(), getFont());
  62179. text.layout (width - 8, Justification::topLeft, true);
  62180. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  62181. }
  62182. private:
  62183. int bestWidth;
  62184. AlertTextComp (const AlertTextComp&);
  62185. AlertTextComp& operator= (const AlertTextComp&);
  62186. };
  62187. void AlertWindow::addTextBlock (const String& textBlock)
  62188. {
  62189. AlertTextComp* const c = new AlertTextComp (textBlock, font);
  62190. textBlocks.add (c);
  62191. allComps.add (c);
  62192. addAndMakeVisible (c);
  62193. updateLayout (false);
  62194. }
  62195. void AlertWindow::addProgressBarComponent (double& progressValue)
  62196. {
  62197. ProgressBar* const pb = new ProgressBar (progressValue);
  62198. progressBars.add (pb);
  62199. allComps.add (pb);
  62200. addAndMakeVisible (pb);
  62201. updateLayout (false);
  62202. }
  62203. void AlertWindow::addCustomComponent (Component* const component)
  62204. {
  62205. customComps.add (component);
  62206. allComps.add (component);
  62207. addAndMakeVisible (component);
  62208. updateLayout (false);
  62209. }
  62210. int AlertWindow::getNumCustomComponents() const
  62211. {
  62212. return customComps.size();
  62213. }
  62214. Component* AlertWindow::getCustomComponent (const int index) const
  62215. {
  62216. return (Component*) customComps [index];
  62217. }
  62218. Component* AlertWindow::removeCustomComponent (const int index)
  62219. {
  62220. Component* const c = getCustomComponent (index);
  62221. if (c != 0)
  62222. {
  62223. customComps.removeValue (c);
  62224. allComps.removeValue (c);
  62225. removeChildComponent (c);
  62226. updateLayout (false);
  62227. }
  62228. return c;
  62229. }
  62230. void AlertWindow::paint (Graphics& g)
  62231. {
  62232. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  62233. g.setColour (findColour (textColourId));
  62234. g.setFont (getLookAndFeel().getAlertWindowFont());
  62235. int i;
  62236. for (i = textBoxes.size(); --i >= 0;)
  62237. {
  62238. const TextEditor* const te = (TextEditor*) textBoxes[i];
  62239. g.drawFittedText (textboxNames[i],
  62240. te->getX(), te->getY() - 14,
  62241. te->getWidth(), 14,
  62242. Justification::centredLeft, 1);
  62243. }
  62244. for (i = comboBoxNames.size(); --i >= 0;)
  62245. {
  62246. const ComboBox* const cb = (ComboBox*) comboBoxes[i];
  62247. g.drawFittedText (comboBoxNames[i],
  62248. cb->getX(), cb->getY() - 14,
  62249. cb->getWidth(), 14,
  62250. Justification::centredLeft, 1);
  62251. }
  62252. for (i = customComps.size(); --i >= 0;)
  62253. {
  62254. const Component* const c = (Component*) customComps[i];
  62255. g.drawFittedText (c->getName(),
  62256. c->getX(), c->getY() - 14,
  62257. c->getWidth(), 14,
  62258. Justification::centredLeft, 1);
  62259. }
  62260. }
  62261. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  62262. {
  62263. const int titleH = 24;
  62264. const int iconWidth = 80;
  62265. const int wid = jmax (font.getStringWidth (text),
  62266. font.getStringWidth (getName()));
  62267. const int sw = (int) std::sqrt (font.getHeight() * wid);
  62268. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  62269. const int edgeGap = 10;
  62270. const int labelHeight = 18;
  62271. int iconSpace;
  62272. if (alertIconType == NoIcon)
  62273. {
  62274. textLayout.layout (w, Justification::horizontallyCentred, true);
  62275. iconSpace = 0;
  62276. }
  62277. else
  62278. {
  62279. textLayout.layout (w, Justification::left, true);
  62280. iconSpace = iconWidth;
  62281. }
  62282. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  62283. w = jmin (w, (int) (getParentWidth() * 0.7f));
  62284. const int textLayoutH = textLayout.getHeight();
  62285. const int textBottom = 16 + titleH + textLayoutH;
  62286. int h = textBottom;
  62287. int buttonW = 40;
  62288. int i;
  62289. for (i = 0; i < buttons.size(); ++i)
  62290. buttonW += 16 + ((const TextButton*) buttons[i])->getWidth();
  62291. w = jmax (buttonW, w);
  62292. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  62293. if (buttons.size() > 0)
  62294. h += 20 + ((TextButton*) buttons[0])->getHeight();
  62295. for (i = customComps.size(); --i >= 0;)
  62296. {
  62297. Component* c = (Component*) customComps[i];
  62298. w = jmax (w, (c->getWidth() * 100) / 80);
  62299. h += 10 + c->getHeight();
  62300. if (c->getName().isNotEmpty())
  62301. h += labelHeight;
  62302. }
  62303. for (i = textBlocks.size(); --i >= 0;)
  62304. {
  62305. const AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  62306. w = jmax (w, ac->getPreferredWidth());
  62307. }
  62308. w = jmin (w, (int) (getParentWidth() * 0.7f));
  62309. for (i = textBlocks.size(); --i >= 0;)
  62310. {
  62311. AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  62312. ac->updateLayout ((int) (w * 0.8f));
  62313. h += ac->getHeight() + 10;
  62314. }
  62315. h = jmin (getParentHeight() - 50, h);
  62316. if (onlyIncreaseSize)
  62317. {
  62318. w = jmax (w, getWidth());
  62319. h = jmax (h, getHeight());
  62320. }
  62321. if (! isVisible())
  62322. {
  62323. centreAroundComponent (associatedComponent, w, h);
  62324. }
  62325. else
  62326. {
  62327. const int cx = getX() + getWidth() / 2;
  62328. const int cy = getY() + getHeight() / 2;
  62329. setBounds (cx - w / 2,
  62330. cy - h / 2,
  62331. w, h);
  62332. }
  62333. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  62334. const int spacer = 16;
  62335. int totalWidth = -spacer;
  62336. for (i = buttons.size(); --i >= 0;)
  62337. totalWidth += ((TextButton*) buttons[i])->getWidth() + spacer;
  62338. int x = (w - totalWidth) / 2;
  62339. int y = (int) (getHeight() * 0.95f);
  62340. for (i = 0; i < buttons.size(); ++i)
  62341. {
  62342. TextButton* const c = (TextButton*) buttons[i];
  62343. int ny = proportionOfHeight (0.95f) - c->getHeight();
  62344. c->setTopLeftPosition (x, ny);
  62345. if (ny < y)
  62346. y = ny;
  62347. x += c->getWidth() + spacer;
  62348. c->toFront (false);
  62349. }
  62350. y = textBottom;
  62351. for (i = 0; i < allComps.size(); ++i)
  62352. {
  62353. Component* const c = (Component*) allComps[i];
  62354. h = 22;
  62355. const int comboIndex = comboBoxes.indexOf (c);
  62356. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  62357. y += labelHeight;
  62358. const int tbIndex = textBoxes.indexOf (c);
  62359. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  62360. y += labelHeight;
  62361. if (customComps.contains (c))
  62362. {
  62363. if (c->getName().isNotEmpty())
  62364. y += labelHeight;
  62365. c->setTopLeftPosition (proportionOfWidth (0.1f), y);
  62366. h = c->getHeight();
  62367. }
  62368. else if (textBlocks.contains (c))
  62369. {
  62370. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  62371. h = c->getHeight();
  62372. }
  62373. else
  62374. {
  62375. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  62376. }
  62377. y += h + 10;
  62378. }
  62379. setWantsKeyboardFocus (getNumChildComponents() == 0);
  62380. }
  62381. bool AlertWindow::containsAnyExtraComponents() const
  62382. {
  62383. return textBoxes.size()
  62384. + comboBoxes.size()
  62385. + progressBars.size()
  62386. + customComps.size() > 0;
  62387. }
  62388. void AlertWindow::mouseDown (const MouseEvent&)
  62389. {
  62390. dragger.startDraggingComponent (this, &constrainer);
  62391. }
  62392. void AlertWindow::mouseDrag (const MouseEvent& e)
  62393. {
  62394. dragger.dragComponent (this, e);
  62395. }
  62396. bool AlertWindow::keyPressed (const KeyPress& key)
  62397. {
  62398. for (int i = buttons.size(); --i >= 0;)
  62399. {
  62400. TextButton* const b = (TextButton*) buttons[i];
  62401. if (b->isRegisteredForShortcut (key))
  62402. {
  62403. b->triggerClick();
  62404. return true;
  62405. }
  62406. }
  62407. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  62408. {
  62409. exitModalState (0);
  62410. return true;
  62411. }
  62412. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  62413. {
  62414. ((TextButton*) buttons.getFirst())->triggerClick();
  62415. return true;
  62416. }
  62417. return false;
  62418. }
  62419. void AlertWindow::lookAndFeelChanged()
  62420. {
  62421. const int newFlags = getLookAndFeel().getAlertBoxWindowFlags();
  62422. setUsingNativeTitleBar ((newFlags & ComponentPeer::windowHasTitleBar) != 0);
  62423. setDropShadowEnabled (isOpaque() && (newFlags & ComponentPeer::windowHasDropShadow) != 0);
  62424. }
  62425. int AlertWindow::getDesktopWindowStyleFlags() const
  62426. {
  62427. return getLookAndFeel().getAlertBoxWindowFlags();
  62428. }
  62429. struct AlertWindowInfo
  62430. {
  62431. String title, message, button1, button2, button3;
  62432. AlertWindow::AlertIconType iconType;
  62433. int numButtons;
  62434. Component::SafePointer<Component> associatedComponent;
  62435. int run() const
  62436. {
  62437. return (int) (pointer_sized_int)
  62438. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  62439. }
  62440. private:
  62441. int show() const
  62442. {
  62443. LookAndFeel& lf = associatedComponent != 0 ? associatedComponent->getLookAndFeel()
  62444. : LookAndFeel::getDefaultLookAndFeel();
  62445. ScopedPointer <Component> alertBox (lf.createAlertWindow (title, message, button1, button2, button3,
  62446. iconType, numButtons, associatedComponent));
  62447. jassert (alertBox != 0); // you have to return one of these!
  62448. return alertBox->runModalLoop();
  62449. }
  62450. static void* showCallback (void* userData)
  62451. {
  62452. return (void*) (pointer_sized_int) ((const AlertWindowInfo*) userData)->show();
  62453. }
  62454. };
  62455. void AlertWindow::showMessageBox (AlertIconType iconType,
  62456. const String& title,
  62457. const String& message,
  62458. const String& buttonText,
  62459. Component* associatedComponent)
  62460. {
  62461. AlertWindowInfo info;
  62462. info.title = title;
  62463. info.message = message;
  62464. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  62465. info.iconType = iconType;
  62466. info.numButtons = 1;
  62467. info.associatedComponent = associatedComponent;
  62468. info.run();
  62469. }
  62470. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  62471. const String& title,
  62472. const String& message,
  62473. const String& button1Text,
  62474. const String& button2Text,
  62475. Component* associatedComponent)
  62476. {
  62477. AlertWindowInfo info;
  62478. info.title = title;
  62479. info.message = message;
  62480. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  62481. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  62482. info.iconType = iconType;
  62483. info.numButtons = 2;
  62484. info.associatedComponent = associatedComponent;
  62485. return info.run() != 0;
  62486. }
  62487. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  62488. const String& title,
  62489. const String& message,
  62490. const String& button1Text,
  62491. const String& button2Text,
  62492. const String& button3Text,
  62493. Component* associatedComponent)
  62494. {
  62495. AlertWindowInfo info;
  62496. info.title = title;
  62497. info.message = message;
  62498. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  62499. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  62500. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  62501. info.iconType = iconType;
  62502. info.numButtons = 3;
  62503. info.associatedComponent = associatedComponent;
  62504. return info.run();
  62505. }
  62506. END_JUCE_NAMESPACE
  62507. /*** End of inlined file: juce_AlertWindow.cpp ***/
  62508. /*** Start of inlined file: juce_CallOutBox.cpp ***/
  62509. BEGIN_JUCE_NAMESPACE
  62510. CallOutBox::CallOutBox (Component& contentComponent,
  62511. Component& componentToPointTo,
  62512. Component* const parentComponent)
  62513. : borderSpace (20), arrowSize (16.0f), content (contentComponent)
  62514. {
  62515. addAndMakeVisible (&content);
  62516. if (parentComponent != 0)
  62517. {
  62518. updatePosition (parentComponent->getLocalBounds(),
  62519. componentToPointTo.getLocalBounds()
  62520. + componentToPointTo.relativePositionToOtherComponent (parentComponent, Point<int>()));
  62521. parentComponent->addAndMakeVisible (this);
  62522. }
  62523. else
  62524. {
  62525. if (! JUCEApplication::isStandaloneApp())
  62526. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62527. updatePosition (componentToPointTo.getScreenBounds(),
  62528. componentToPointTo.getParentMonitorArea());
  62529. addToDesktop (ComponentPeer::windowIsTemporary);
  62530. }
  62531. }
  62532. CallOutBox::~CallOutBox()
  62533. {
  62534. }
  62535. void CallOutBox::setArrowSize (const float newSize)
  62536. {
  62537. arrowSize = newSize;
  62538. borderSpace = jmax (20, (int) arrowSize);
  62539. refreshPath();
  62540. }
  62541. void CallOutBox::paint (Graphics& g)
  62542. {
  62543. if (background.isNull())
  62544. {
  62545. background = Image (Image::ARGB, getWidth(), getHeight(), true);
  62546. Graphics g (background);
  62547. getLookAndFeel().drawCallOutBoxBackground (*this, g, outline);
  62548. }
  62549. g.setColour (Colours::black);
  62550. g.drawImageAt (background, 0, 0);
  62551. }
  62552. void CallOutBox::resized()
  62553. {
  62554. content.setTopLeftPosition (borderSpace, borderSpace);
  62555. refreshPath();
  62556. }
  62557. void CallOutBox::moved()
  62558. {
  62559. refreshPath();
  62560. }
  62561. void CallOutBox::childBoundsChanged (Component*)
  62562. {
  62563. updatePosition (targetArea, availableArea);
  62564. }
  62565. bool CallOutBox::hitTest (int x, int y)
  62566. {
  62567. return outline.contains ((float) x, (float) y);
  62568. }
  62569. enum { callOutBoxDismissCommandId = 0x4f83a04b };
  62570. void CallOutBox::inputAttemptWhenModal()
  62571. {
  62572. const Point<int> mousePos (getMouseXYRelative() + getBounds().getPosition());
  62573. if (targetArea.contains (mousePos))
  62574. {
  62575. // if you click on the area that originally popped-up the callout, you expect it
  62576. // to get rid of the box, but deleting the box here allows the click to pass through and
  62577. // probably re-trigger it, so we need to dismiss the box asynchronously to consume the click..
  62578. postCommandMessage (callOutBoxDismissCommandId);
  62579. }
  62580. else
  62581. {
  62582. exitModalState (0);
  62583. setVisible (false);
  62584. }
  62585. }
  62586. void CallOutBox::handleCommandMessage (int commandId)
  62587. {
  62588. Component::handleCommandMessage (commandId);
  62589. if (commandId == callOutBoxDismissCommandId)
  62590. {
  62591. exitModalState (0);
  62592. setVisible (false);
  62593. }
  62594. }
  62595. bool CallOutBox::keyPressed (const KeyPress& key)
  62596. {
  62597. if (key.isKeyCode (KeyPress::escapeKey))
  62598. {
  62599. inputAttemptWhenModal();
  62600. return true;
  62601. }
  62602. return false;
  62603. }
  62604. void CallOutBox::updatePosition (const Rectangle<int>& newAreaToPointTo, const Rectangle<int>& newAreaToFitIn)
  62605. {
  62606. targetArea = newAreaToPointTo;
  62607. availableArea = newAreaToFitIn;
  62608. Rectangle<int> bounds (0, 0,
  62609. content.getWidth() + borderSpace * 2,
  62610. content.getHeight() + borderSpace * 2);
  62611. const int hw = bounds.getWidth() / 2;
  62612. const int hh = bounds.getHeight() / 2;
  62613. const float hwReduced = (float) (hw - borderSpace * 3);
  62614. const float hhReduced = (float) (hh - borderSpace * 3);
  62615. const float arrowIndent = borderSpace - arrowSize;
  62616. Point<float> targets[4] = { Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getBottom()),
  62617. Point<float> ((float) targetArea.getRight(), (float) targetArea.getCentreY()),
  62618. Point<float> ((float) targetArea.getX(), (float) targetArea.getCentreY()),
  62619. Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getY()) };
  62620. Line<float> lines[4] = { Line<float> (targets[0].translated (-hwReduced, hh - arrowIndent), targets[0].translated (hwReduced, hh - arrowIndent)),
  62621. Line<float> (targets[1].translated (hw - arrowIndent, -hhReduced), targets[1].translated (hw - arrowIndent, hhReduced)),
  62622. Line<float> (targets[2].translated (-(hw - arrowIndent), -hhReduced), targets[2].translated (-(hw - arrowIndent), hhReduced)),
  62623. Line<float> (targets[3].translated (-hwReduced, -(hh - arrowIndent)), targets[3].translated (hwReduced, -(hh - arrowIndent))) };
  62624. const Rectangle<float> centrePointArea (newAreaToFitIn.reduced (hw, hh).toFloat());
  62625. float nearest = 1.0e9f;
  62626. for (int i = 0; i < 4; ++i)
  62627. {
  62628. Line<float> constrainedLine (centrePointArea.getConstrainedPoint (lines[i].getStart()),
  62629. centrePointArea.getConstrainedPoint (lines[i].getEnd()));
  62630. const Point<float> centre (constrainedLine.findNearestPointTo (centrePointArea.getCentre()));
  62631. float distanceFromCentre = centre.getDistanceFrom (centrePointArea.getCentre());
  62632. if (! (centrePointArea.contains (lines[i].getStart()) || centrePointArea.contains (lines[i].getEnd())))
  62633. distanceFromCentre *= 2.0f;
  62634. if (distanceFromCentre < nearest)
  62635. {
  62636. nearest = distanceFromCentre;
  62637. targetPoint = targets[i];
  62638. bounds.setPosition ((int) (centre.getX() - hw),
  62639. (int) (centre.getY() - hh));
  62640. }
  62641. }
  62642. setBounds (bounds);
  62643. }
  62644. void CallOutBox::refreshPath()
  62645. {
  62646. repaint();
  62647. background = Image::null;
  62648. outline.clear();
  62649. const float gap = 4.5f;
  62650. const float cornerSize = 9.0f;
  62651. const float cornerSize2 = 2.0f * cornerSize;
  62652. const float arrowBaseWidth = arrowSize * 0.7f;
  62653. const float left = content.getX() - gap, top = content.getY() - gap, right = content.getRight() + gap, bottom = content.getBottom() + gap;
  62654. const float targetX = targetPoint.getX() - getX(), targetY = targetPoint.getY() - getY();
  62655. outline.startNewSubPath (left + cornerSize, top);
  62656. if (targetY <= top)
  62657. {
  62658. outline.lineTo (targetX - arrowBaseWidth, top);
  62659. outline.lineTo (targetX, targetY);
  62660. outline.lineTo (targetX + arrowBaseWidth, top);
  62661. }
  62662. outline.lineTo (right - cornerSize, top);
  62663. outline.addArc (right - cornerSize2, top, cornerSize2, cornerSize2, 0, float_Pi * 0.5f);
  62664. if (targetX >= right)
  62665. {
  62666. outline.lineTo (right, targetY - arrowBaseWidth);
  62667. outline.lineTo (targetX, targetY);
  62668. outline.lineTo (right, targetY + arrowBaseWidth);
  62669. }
  62670. outline.lineTo (right, bottom - cornerSize);
  62671. outline.addArc (right - cornerSize2, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi * 0.5f, float_Pi);
  62672. if (targetY >= bottom)
  62673. {
  62674. outline.lineTo (targetX + arrowBaseWidth, bottom);
  62675. outline.lineTo (targetX, targetY);
  62676. outline.lineTo (targetX - arrowBaseWidth, bottom);
  62677. }
  62678. outline.lineTo (left + cornerSize, bottom);
  62679. outline.addArc (left, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi, float_Pi * 1.5f);
  62680. if (targetX <= left)
  62681. {
  62682. outline.lineTo (left, targetY + arrowBaseWidth);
  62683. outline.lineTo (targetX, targetY);
  62684. outline.lineTo (left, targetY - arrowBaseWidth);
  62685. }
  62686. outline.lineTo (left, top + cornerSize);
  62687. outline.addArc (left, top, cornerSize2, cornerSize2, float_Pi * 1.5f, float_Pi * 2.0f - 0.05f);
  62688. outline.closeSubPath();
  62689. }
  62690. END_JUCE_NAMESPACE
  62691. /*** End of inlined file: juce_CallOutBox.cpp ***/
  62692. /*** Start of inlined file: juce_ComponentPeer.cpp ***/
  62693. BEGIN_JUCE_NAMESPACE
  62694. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  62695. static Array <ComponentPeer*> heavyweightPeers;
  62696. ComponentPeer::ComponentPeer (Component* const component_, const int styleFlags_)
  62697. : component (component_),
  62698. styleFlags (styleFlags_),
  62699. lastPaintTime (0),
  62700. constrainer (0),
  62701. lastDragAndDropCompUnderMouse (0),
  62702. fakeMouseMessageSent (false),
  62703. isWindowMinimised (false)
  62704. {
  62705. heavyweightPeers.add (this);
  62706. }
  62707. ComponentPeer::~ComponentPeer()
  62708. {
  62709. heavyweightPeers.removeValue (this);
  62710. Desktop::getInstance().triggerFocusCallback();
  62711. }
  62712. int ComponentPeer::getNumPeers() throw()
  62713. {
  62714. return heavyweightPeers.size();
  62715. }
  62716. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  62717. {
  62718. return heavyweightPeers [index];
  62719. }
  62720. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  62721. {
  62722. for (int i = heavyweightPeers.size(); --i >= 0;)
  62723. {
  62724. ComponentPeer* const peer = heavyweightPeers.getUnchecked(i);
  62725. if (peer->getComponent() == component)
  62726. return peer;
  62727. }
  62728. return 0;
  62729. }
  62730. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  62731. {
  62732. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  62733. }
  62734. void ComponentPeer::updateCurrentModifiers() throw()
  62735. {
  62736. ModifierKeys::updateCurrentModifiers();
  62737. }
  62738. void ComponentPeer::handleMouseEvent (const int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, const int64 time)
  62739. {
  62740. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  62741. jassert (mouse != 0); // not enough sources!
  62742. mouse->handleEvent (this, positionWithinPeer, time, newMods);
  62743. }
  62744. void ComponentPeer::handleMouseWheel (const int touchIndex, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  62745. {
  62746. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  62747. jassert (mouse != 0); // not enough sources!
  62748. mouse->handleWheel (this, positionWithinPeer, time, x, y);
  62749. }
  62750. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  62751. {
  62752. Graphics g (&contextToPaintTo);
  62753. #if JUCE_ENABLE_REPAINT_DEBUGGING
  62754. g.saveState();
  62755. #endif
  62756. JUCE_TRY
  62757. {
  62758. component->paintEntireComponent (g);
  62759. }
  62760. JUCE_CATCH_EXCEPTION
  62761. #if JUCE_ENABLE_REPAINT_DEBUGGING
  62762. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  62763. // clearly when things are being repainted.
  62764. {
  62765. g.restoreState();
  62766. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  62767. (uint8) Random::getSystemRandom().nextInt (255),
  62768. (uint8) Random::getSystemRandom().nextInt (255),
  62769. (uint8) 0x50));
  62770. }
  62771. #endif
  62772. /** If this fails, it's probably be because your CPU floating-point precision mode has
  62773. been set to low.. This setting is sometimes changed by things like Direct3D, and can
  62774. mess up a lot of the calculations that the library needs to do.
  62775. */
  62776. jassert (roundToInt (10.1f) == 10);
  62777. }
  62778. bool ComponentPeer::handleKeyPress (const int keyCode,
  62779. const juce_wchar textCharacter)
  62780. {
  62781. updateCurrentModifiers();
  62782. Component* target = Component::getCurrentlyFocusedComponent() != 0
  62783. ? Component::getCurrentlyFocusedComponent()
  62784. : component;
  62785. if (target->isCurrentlyBlockedByAnotherModalComponent())
  62786. {
  62787. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  62788. if (currentModalComp != 0)
  62789. target = currentModalComp;
  62790. }
  62791. const KeyPress keyInfo (keyCode,
  62792. ModifierKeys::getCurrentModifiers().getRawFlags()
  62793. & ModifierKeys::allKeyboardModifiers,
  62794. textCharacter);
  62795. bool keyWasUsed = false;
  62796. while (target != 0)
  62797. {
  62798. const Component::SafePointer<Component> deletionChecker (target);
  62799. if (target->keyListeners_ != 0)
  62800. {
  62801. for (int i = target->keyListeners_->size(); --i >= 0;)
  62802. {
  62803. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyPressed (keyInfo, target);
  62804. if (keyWasUsed || deletionChecker == 0)
  62805. return keyWasUsed;
  62806. i = jmin (i, target->keyListeners_->size());
  62807. }
  62808. }
  62809. keyWasUsed = target->keyPressed (keyInfo);
  62810. if (keyWasUsed || deletionChecker == 0)
  62811. break;
  62812. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  62813. {
  62814. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  62815. currentlyFocused->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  62816. keyWasUsed = (currentlyFocused != Component::getCurrentlyFocusedComponent());
  62817. break;
  62818. }
  62819. target = target->parentComponent_;
  62820. }
  62821. return keyWasUsed;
  62822. }
  62823. bool ComponentPeer::handleKeyUpOrDown (const bool isKeyDown)
  62824. {
  62825. updateCurrentModifiers();
  62826. Component* target = Component::getCurrentlyFocusedComponent() != 0
  62827. ? Component::getCurrentlyFocusedComponent()
  62828. : component;
  62829. if (target->isCurrentlyBlockedByAnotherModalComponent())
  62830. {
  62831. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  62832. if (currentModalComp != 0)
  62833. target = currentModalComp;
  62834. }
  62835. bool keyWasUsed = false;
  62836. while (target != 0)
  62837. {
  62838. const Component::SafePointer<Component> deletionChecker (target);
  62839. keyWasUsed = target->keyStateChanged (isKeyDown);
  62840. if (keyWasUsed || deletionChecker == 0)
  62841. break;
  62842. if (target->keyListeners_ != 0)
  62843. {
  62844. for (int i = target->keyListeners_->size(); --i >= 0;)
  62845. {
  62846. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyStateChanged (isKeyDown, target);
  62847. if (keyWasUsed || deletionChecker == 0)
  62848. return keyWasUsed;
  62849. i = jmin (i, target->keyListeners_->size());
  62850. }
  62851. }
  62852. target = target->parentComponent_;
  62853. }
  62854. return keyWasUsed;
  62855. }
  62856. void ComponentPeer::handleModifierKeysChange()
  62857. {
  62858. updateCurrentModifiers();
  62859. Component* target = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  62860. if (target == 0)
  62861. target = Component::getCurrentlyFocusedComponent();
  62862. if (target == 0)
  62863. target = component;
  62864. if (target != 0)
  62865. target->internalModifierKeysChanged();
  62866. }
  62867. TextInputTarget* ComponentPeer::findCurrentTextInputTarget()
  62868. {
  62869. Component* const c = Component::getCurrentlyFocusedComponent();
  62870. if (component->isParentOf (c))
  62871. {
  62872. TextInputTarget* const ti = dynamic_cast <TextInputTarget*> (c);
  62873. if (ti != 0 && ti->isTextInputActive())
  62874. return ti;
  62875. }
  62876. return 0;
  62877. }
  62878. void ComponentPeer::handleBroughtToFront()
  62879. {
  62880. updateCurrentModifiers();
  62881. if (component != 0)
  62882. component->internalBroughtToFront();
  62883. }
  62884. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  62885. {
  62886. constrainer = newConstrainer;
  62887. }
  62888. void ComponentPeer::handleMovedOrResized()
  62889. {
  62890. jassert (component->isValidComponent());
  62891. updateCurrentModifiers();
  62892. const bool nowMinimised = isMinimised();
  62893. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  62894. {
  62895. const Component::SafePointer<Component> deletionChecker (component);
  62896. const Rectangle<int> newBounds (getBounds());
  62897. const bool wasMoved = (component->getPosition() != newBounds.getPosition());
  62898. const bool wasResized = (component->getWidth() != newBounds.getWidth() || component->getHeight() != newBounds.getHeight());
  62899. if (wasMoved || wasResized)
  62900. {
  62901. component->bounds_ = newBounds;
  62902. if (wasResized)
  62903. component->repaint();
  62904. component->sendMovedResizedMessages (wasMoved, wasResized);
  62905. if (deletionChecker == 0)
  62906. return;
  62907. }
  62908. }
  62909. if (isWindowMinimised != nowMinimised)
  62910. {
  62911. isWindowMinimised = nowMinimised;
  62912. component->minimisationStateChanged (nowMinimised);
  62913. component->sendVisibilityChangeMessage();
  62914. }
  62915. if (! isFullScreen())
  62916. lastNonFullscreenBounds = component->getBounds();
  62917. }
  62918. void ComponentPeer::handleFocusGain()
  62919. {
  62920. updateCurrentModifiers();
  62921. if (component->isParentOf (lastFocusedComponent))
  62922. {
  62923. Component::currentlyFocusedComponent = lastFocusedComponent;
  62924. Desktop::getInstance().triggerFocusCallback();
  62925. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  62926. }
  62927. else
  62928. {
  62929. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  62930. component->grabKeyboardFocus();
  62931. else
  62932. Component::bringModalComponentToFront();
  62933. }
  62934. }
  62935. void ComponentPeer::handleFocusLoss()
  62936. {
  62937. updateCurrentModifiers();
  62938. if (component->hasKeyboardFocus (true))
  62939. {
  62940. lastFocusedComponent = Component::currentlyFocusedComponent;
  62941. if (lastFocusedComponent != 0)
  62942. {
  62943. Component::currentlyFocusedComponent = 0;
  62944. Desktop::getInstance().triggerFocusCallback();
  62945. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  62946. }
  62947. }
  62948. }
  62949. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  62950. {
  62951. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  62952. ? static_cast <Component*> (lastFocusedComponent)
  62953. : component;
  62954. }
  62955. void ComponentPeer::handleScreenSizeChange()
  62956. {
  62957. updateCurrentModifiers();
  62958. component->parentSizeChanged();
  62959. handleMovedOrResized();
  62960. }
  62961. void ComponentPeer::setNonFullScreenBounds (const Rectangle<int>& newBounds) throw()
  62962. {
  62963. lastNonFullscreenBounds = newBounds;
  62964. }
  62965. const Rectangle<int>& ComponentPeer::getNonFullScreenBounds() const throw()
  62966. {
  62967. return lastNonFullscreenBounds;
  62968. }
  62969. static FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  62970. const StringArray& files,
  62971. FileDragAndDropTarget* const lastOne)
  62972. {
  62973. while (c != 0)
  62974. {
  62975. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  62976. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  62977. return t;
  62978. c = c->getParentComponent();
  62979. }
  62980. return 0;
  62981. }
  62982. void ComponentPeer::handleFileDragMove (const StringArray& files, const Point<int>& position)
  62983. {
  62984. updateCurrentModifiers();
  62985. FileDragAndDropTarget* lastTarget
  62986. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  62987. FileDragAndDropTarget* newTarget = 0;
  62988. Component* const compUnderMouse = component->getComponentAt (position);
  62989. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  62990. {
  62991. lastDragAndDropCompUnderMouse = compUnderMouse;
  62992. newTarget = findDragAndDropTarget (compUnderMouse, files, lastTarget);
  62993. if (newTarget != lastTarget)
  62994. {
  62995. if (lastTarget != 0)
  62996. lastTarget->fileDragExit (files);
  62997. dragAndDropTargetComponent = 0;
  62998. if (newTarget != 0)
  62999. {
  63000. dragAndDropTargetComponent = dynamic_cast <Component*> (newTarget);
  63001. const Point<int> pos (component->relativePositionToOtherComponent (dragAndDropTargetComponent, position));
  63002. newTarget->fileDragEnter (files, pos.getX(), pos.getY());
  63003. }
  63004. }
  63005. }
  63006. else
  63007. {
  63008. newTarget = lastTarget;
  63009. }
  63010. if (newTarget != 0)
  63011. {
  63012. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  63013. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  63014. newTarget->fileDragMove (files, pos.getX(), pos.getY());
  63015. }
  63016. }
  63017. void ComponentPeer::handleFileDragExit (const StringArray& files)
  63018. {
  63019. handleFileDragMove (files, Point<int> (-1, -1));
  63020. jassert (dragAndDropTargetComponent == 0);
  63021. lastDragAndDropCompUnderMouse = 0;
  63022. }
  63023. void ComponentPeer::handleFileDragDrop (const StringArray& files, const Point<int>& position)
  63024. {
  63025. handleFileDragMove (files, position);
  63026. if (dragAndDropTargetComponent != 0)
  63027. {
  63028. FileDragAndDropTarget* const target
  63029. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  63030. dragAndDropTargetComponent = 0;
  63031. lastDragAndDropCompUnderMouse = 0;
  63032. if (target != 0)
  63033. {
  63034. Component* const targetComp = dynamic_cast <Component*> (target);
  63035. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  63036. {
  63037. targetComp->internalModalInputAttempt();
  63038. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  63039. return;
  63040. }
  63041. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  63042. target->filesDropped (files, pos.getX(), pos.getY());
  63043. }
  63044. }
  63045. }
  63046. void ComponentPeer::handleUserClosingWindow()
  63047. {
  63048. updateCurrentModifiers();
  63049. component->userTriedToCloseWindow();
  63050. }
  63051. void ComponentPeer::bringModalComponentToFront()
  63052. {
  63053. Component::bringModalComponentToFront();
  63054. }
  63055. void ComponentPeer::clearMaskedRegion()
  63056. {
  63057. maskedRegion.clear();
  63058. }
  63059. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h)
  63060. {
  63061. maskedRegion.add (x, y, w, h);
  63062. }
  63063. const StringArray ComponentPeer::getAvailableRenderingEngines()
  63064. {
  63065. StringArray s;
  63066. s.add ("Software Renderer");
  63067. return s;
  63068. }
  63069. int ComponentPeer::getCurrentRenderingEngine() throw()
  63070. {
  63071. return 0;
  63072. }
  63073. void ComponentPeer::setCurrentRenderingEngine (int /*index*/)
  63074. {
  63075. }
  63076. END_JUCE_NAMESPACE
  63077. /*** End of inlined file: juce_ComponentPeer.cpp ***/
  63078. /*** Start of inlined file: juce_DialogWindow.cpp ***/
  63079. BEGIN_JUCE_NAMESPACE
  63080. DialogWindow::DialogWindow (const String& name,
  63081. const Colour& backgroundColour_,
  63082. const bool escapeKeyTriggersCloseButton_,
  63083. const bool addToDesktop_)
  63084. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  63085. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  63086. {
  63087. }
  63088. DialogWindow::~DialogWindow()
  63089. {
  63090. }
  63091. void DialogWindow::resized()
  63092. {
  63093. DocumentWindow::resized();
  63094. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  63095. if (escapeKeyTriggersCloseButton
  63096. && getCloseButton() != 0
  63097. && ! getCloseButton()->isRegisteredForShortcut (esc))
  63098. {
  63099. getCloseButton()->addShortcut (esc);
  63100. }
  63101. }
  63102. class TempDialogWindow : public DialogWindow
  63103. {
  63104. public:
  63105. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  63106. : DialogWindow (title, colour, escapeCloses, true)
  63107. {
  63108. if (! JUCEApplication::isStandaloneApp())
  63109. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  63110. }
  63111. ~TempDialogWindow()
  63112. {
  63113. }
  63114. void closeButtonPressed()
  63115. {
  63116. setVisible (false);
  63117. }
  63118. private:
  63119. TempDialogWindow (const TempDialogWindow&);
  63120. TempDialogWindow& operator= (const TempDialogWindow&);
  63121. };
  63122. int DialogWindow::showModalDialog (const String& dialogTitle,
  63123. Component* contentComponent,
  63124. Component* componentToCentreAround,
  63125. const Colour& colour,
  63126. const bool escapeKeyTriggersCloseButton,
  63127. const bool shouldBeResizable,
  63128. const bool useBottomRightCornerResizer)
  63129. {
  63130. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  63131. dw.setContentComponent (contentComponent, true, true);
  63132. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  63133. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  63134. const int result = dw.runModalLoop();
  63135. dw.setContentComponent (0, false);
  63136. return result;
  63137. }
  63138. END_JUCE_NAMESPACE
  63139. /*** End of inlined file: juce_DialogWindow.cpp ***/
  63140. /*** Start of inlined file: juce_DocumentWindow.cpp ***/
  63141. BEGIN_JUCE_NAMESPACE
  63142. class DocumentWindow::ButtonListenerProxy : public ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  63143. {
  63144. public:
  63145. ButtonListenerProxy (DocumentWindow& owner_)
  63146. : owner (owner_)
  63147. {
  63148. }
  63149. void buttonClicked (Button* button)
  63150. {
  63151. if (button == owner.getMinimiseButton())
  63152. owner.minimiseButtonPressed();
  63153. else if (button == owner.getMaximiseButton())
  63154. owner.maximiseButtonPressed();
  63155. else if (button == owner.getCloseButton())
  63156. owner.closeButtonPressed();
  63157. }
  63158. juce_UseDebuggingNewOperator
  63159. private:
  63160. DocumentWindow& owner;
  63161. ButtonListenerProxy (const ButtonListenerProxy&);
  63162. ButtonListenerProxy& operator= (const ButtonListenerProxy&);
  63163. };
  63164. DocumentWindow::DocumentWindow (const String& title,
  63165. const Colour& backgroundColour,
  63166. const int requiredButtons_,
  63167. const bool addToDesktop_)
  63168. : ResizableWindow (title, backgroundColour, addToDesktop_),
  63169. titleBarHeight (26),
  63170. menuBarHeight (24),
  63171. requiredButtons (requiredButtons_),
  63172. #if JUCE_MAC
  63173. positionTitleBarButtonsOnLeft (true),
  63174. #else
  63175. positionTitleBarButtonsOnLeft (false),
  63176. #endif
  63177. drawTitleTextCentred (true),
  63178. menuBarModel (0)
  63179. {
  63180. setResizeLimits (128, 128, 32768, 32768);
  63181. lookAndFeelChanged();
  63182. }
  63183. DocumentWindow::~DocumentWindow()
  63184. {
  63185. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  63186. titleBarButtons[i] = 0;
  63187. menuBar = 0;
  63188. }
  63189. void DocumentWindow::repaintTitleBar()
  63190. {
  63191. repaint (getTitleBarArea());
  63192. }
  63193. void DocumentWindow::setName (const String& newName)
  63194. {
  63195. if (newName != getName())
  63196. {
  63197. Component::setName (newName);
  63198. repaintTitleBar();
  63199. }
  63200. }
  63201. void DocumentWindow::setIcon (const Image& imageToUse)
  63202. {
  63203. titleBarIcon = imageToUse;
  63204. repaintTitleBar();
  63205. }
  63206. void DocumentWindow::setTitleBarHeight (const int newHeight)
  63207. {
  63208. titleBarHeight = newHeight;
  63209. resized();
  63210. repaintTitleBar();
  63211. }
  63212. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  63213. const bool positionTitleBarButtonsOnLeft_)
  63214. {
  63215. requiredButtons = requiredButtons_;
  63216. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  63217. lookAndFeelChanged();
  63218. }
  63219. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  63220. {
  63221. drawTitleTextCentred = textShouldBeCentred;
  63222. repaintTitleBar();
  63223. }
  63224. void DocumentWindow::setMenuBar (MenuBarModel* menuBarModel_,
  63225. const int menuBarHeight_)
  63226. {
  63227. if (menuBarModel != menuBarModel_)
  63228. {
  63229. menuBar = 0;
  63230. menuBarModel = menuBarModel_;
  63231. menuBarHeight = (menuBarHeight_ > 0) ? menuBarHeight_
  63232. : getLookAndFeel().getDefaultMenuBarHeight();
  63233. if (menuBarModel != 0)
  63234. {
  63235. // (call the Component method directly to avoid the assertion in ResizableWindow)
  63236. Component::addAndMakeVisible (menuBar = new MenuBarComponent (menuBarModel));
  63237. menuBar->setEnabled (isActiveWindow());
  63238. }
  63239. resized();
  63240. }
  63241. }
  63242. void DocumentWindow::closeButtonPressed()
  63243. {
  63244. /* If you've got a close button, you have to override this method to get
  63245. rid of your window!
  63246. If the window is just a pop-up, you should override this method and make
  63247. it delete the window in whatever way is appropriate for your app. E.g. you
  63248. might just want to call "delete this".
  63249. If your app is centred around this window such that the whole app should quit when
  63250. the window is closed, then you will probably want to use this method as an opportunity
  63251. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  63252. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  63253. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  63254. or closing it via the taskbar icon on Windows).
  63255. */
  63256. jassertfalse;
  63257. }
  63258. void DocumentWindow::minimiseButtonPressed()
  63259. {
  63260. setMinimised (true);
  63261. }
  63262. void DocumentWindow::maximiseButtonPressed()
  63263. {
  63264. setFullScreen (! isFullScreen());
  63265. }
  63266. void DocumentWindow::paint (Graphics& g)
  63267. {
  63268. ResizableWindow::paint (g);
  63269. if (resizableBorder == 0)
  63270. {
  63271. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  63272. const BorderSize border (getBorderThickness());
  63273. g.fillRect (0, 0, getWidth(), border.getTop());
  63274. g.fillRect (0, border.getTop(), border.getLeft(), getHeight() - border.getTopAndBottom());
  63275. g.fillRect (getWidth() - border.getRight(), border.getTop(), border.getRight(), getHeight() - border.getTopAndBottom());
  63276. g.fillRect (0, getHeight() - border.getBottom(), getWidth(), border.getBottom());
  63277. }
  63278. const Rectangle<int> titleBarArea (getTitleBarArea());
  63279. g.setOrigin (titleBarArea.getX(), titleBarArea.getY());
  63280. g.reduceClipRegion (0, 0, titleBarArea.getWidth(), titleBarArea.getHeight());
  63281. int titleSpaceX1 = 6;
  63282. int titleSpaceX2 = titleBarArea.getWidth() - 6;
  63283. for (int i = 0; i < 3; ++i)
  63284. {
  63285. if (titleBarButtons[i] != 0)
  63286. {
  63287. if (positionTitleBarButtonsOnLeft)
  63288. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  63289. else
  63290. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  63291. }
  63292. }
  63293. getLookAndFeel().drawDocumentWindowTitleBar (*this, g,
  63294. titleBarArea.getWidth(),
  63295. titleBarArea.getHeight(),
  63296. titleSpaceX1,
  63297. jmax (1, titleSpaceX2 - titleSpaceX1),
  63298. titleBarIcon.isValid() ? &titleBarIcon : 0,
  63299. ! drawTitleTextCentred);
  63300. }
  63301. void DocumentWindow::resized()
  63302. {
  63303. ResizableWindow::resized();
  63304. if (titleBarButtons[1] != 0)
  63305. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  63306. const Rectangle<int> titleBarArea (getTitleBarArea());
  63307. getLookAndFeel()
  63308. .positionDocumentWindowButtons (*this,
  63309. titleBarArea.getX(), titleBarArea.getY(),
  63310. titleBarArea.getWidth(), titleBarArea.getHeight(),
  63311. titleBarButtons[0],
  63312. titleBarButtons[1],
  63313. titleBarButtons[2],
  63314. positionTitleBarButtonsOnLeft);
  63315. if (menuBar != 0)
  63316. menuBar->setBounds (titleBarArea.getX(), titleBarArea.getBottom(),
  63317. titleBarArea.getWidth(), menuBarHeight);
  63318. }
  63319. const BorderSize DocumentWindow::getBorderThickness()
  63320. {
  63321. return BorderSize ((isFullScreen() || isUsingNativeTitleBar())
  63322. ? 0 : (resizableBorder != 0 ? 4 : 1));
  63323. }
  63324. const BorderSize DocumentWindow::getContentComponentBorder()
  63325. {
  63326. BorderSize border (getBorderThickness());
  63327. border.setTop (border.getTop()
  63328. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  63329. + (menuBar != 0 ? menuBarHeight : 0));
  63330. return border;
  63331. }
  63332. int DocumentWindow::getTitleBarHeight() const
  63333. {
  63334. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  63335. }
  63336. const Rectangle<int> DocumentWindow::getTitleBarArea()
  63337. {
  63338. const BorderSize border (getBorderThickness());
  63339. return Rectangle<int> (border.getLeft(), border.getTop(),
  63340. getWidth() - border.getLeftAndRight(),
  63341. getTitleBarHeight());
  63342. }
  63343. Button* DocumentWindow::getCloseButton() const throw()
  63344. {
  63345. return titleBarButtons[2];
  63346. }
  63347. Button* DocumentWindow::getMinimiseButton() const throw()
  63348. {
  63349. return titleBarButtons[0];
  63350. }
  63351. Button* DocumentWindow::getMaximiseButton() const throw()
  63352. {
  63353. return titleBarButtons[1];
  63354. }
  63355. int DocumentWindow::getDesktopWindowStyleFlags() const
  63356. {
  63357. int styleFlags = ResizableWindow::getDesktopWindowStyleFlags();
  63358. if ((requiredButtons & minimiseButton) != 0)
  63359. styleFlags |= ComponentPeer::windowHasMinimiseButton;
  63360. if ((requiredButtons & maximiseButton) != 0)
  63361. styleFlags |= ComponentPeer::windowHasMaximiseButton;
  63362. if ((requiredButtons & closeButton) != 0)
  63363. styleFlags |= ComponentPeer::windowHasCloseButton;
  63364. return styleFlags;
  63365. }
  63366. void DocumentWindow::lookAndFeelChanged()
  63367. {
  63368. int i;
  63369. for (i = numElementsInArray (titleBarButtons); --i >= 0;)
  63370. titleBarButtons[i] = 0;
  63371. if (! isUsingNativeTitleBar())
  63372. {
  63373. titleBarButtons[0] = ((requiredButtons & minimiseButton) != 0)
  63374. ? getLookAndFeel().createDocumentWindowButton (minimiseButton) : 0;
  63375. titleBarButtons[1] = ((requiredButtons & maximiseButton) != 0)
  63376. ? getLookAndFeel().createDocumentWindowButton (maximiseButton) : 0;
  63377. titleBarButtons[2] = ((requiredButtons & closeButton) != 0)
  63378. ? getLookAndFeel().createDocumentWindowButton (closeButton) : 0;
  63379. for (i = 0; i < 3; ++i)
  63380. {
  63381. if (titleBarButtons[i] != 0)
  63382. {
  63383. if (buttonListener == 0)
  63384. buttonListener = new ButtonListenerProxy (*this);
  63385. titleBarButtons[i]->addButtonListener (buttonListener);
  63386. titleBarButtons[i]->setWantsKeyboardFocus (false);
  63387. // (call the Component method directly to avoid the assertion in ResizableWindow)
  63388. Component::addAndMakeVisible (titleBarButtons[i]);
  63389. }
  63390. }
  63391. if (getCloseButton() != 0)
  63392. {
  63393. #if JUCE_MAC
  63394. getCloseButton()->addShortcut (KeyPress ('w', ModifierKeys::commandModifier, 0));
  63395. #else
  63396. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  63397. #endif
  63398. }
  63399. }
  63400. activeWindowStatusChanged();
  63401. ResizableWindow::lookAndFeelChanged();
  63402. }
  63403. void DocumentWindow::parentHierarchyChanged()
  63404. {
  63405. lookAndFeelChanged();
  63406. }
  63407. void DocumentWindow::activeWindowStatusChanged()
  63408. {
  63409. ResizableWindow::activeWindowStatusChanged();
  63410. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  63411. if (titleBarButtons[i] != 0)
  63412. titleBarButtons[i]->setEnabled (isActiveWindow());
  63413. if (menuBar != 0)
  63414. menuBar->setEnabled (isActiveWindow());
  63415. }
  63416. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  63417. {
  63418. if (getTitleBarArea().contains (e.x, e.y)
  63419. && getMaximiseButton() != 0)
  63420. {
  63421. getMaximiseButton()->triggerClick();
  63422. }
  63423. }
  63424. void DocumentWindow::userTriedToCloseWindow()
  63425. {
  63426. closeButtonPressed();
  63427. }
  63428. END_JUCE_NAMESPACE
  63429. /*** End of inlined file: juce_DocumentWindow.cpp ***/
  63430. /*** Start of inlined file: juce_ResizableWindow.cpp ***/
  63431. BEGIN_JUCE_NAMESPACE
  63432. ResizableWindow::ResizableWindow (const String& name,
  63433. const bool addToDesktop_)
  63434. : TopLevelWindow (name, addToDesktop_),
  63435. resizeToFitContent (false),
  63436. fullscreen (false),
  63437. lastNonFullScreenPos (50, 50, 256, 256),
  63438. constrainer (0)
  63439. #if JUCE_DEBUG
  63440. , hasBeenResized (false)
  63441. #endif
  63442. {
  63443. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  63444. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  63445. if (addToDesktop_)
  63446. Component::addToDesktop (getDesktopWindowStyleFlags());
  63447. }
  63448. ResizableWindow::ResizableWindow (const String& name,
  63449. const Colour& backgroundColour_,
  63450. const bool addToDesktop_)
  63451. : TopLevelWindow (name, addToDesktop_),
  63452. resizeToFitContent (false),
  63453. fullscreen (false),
  63454. lastNonFullScreenPos (50, 50, 256, 256),
  63455. constrainer (0)
  63456. #if JUCE_DEBUG
  63457. , hasBeenResized (false)
  63458. #endif
  63459. {
  63460. setBackgroundColour (backgroundColour_);
  63461. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  63462. if (addToDesktop_)
  63463. Component::addToDesktop (getDesktopWindowStyleFlags());
  63464. }
  63465. ResizableWindow::~ResizableWindow()
  63466. {
  63467. resizableCorner = 0;
  63468. resizableBorder = 0;
  63469. contentComponent.deleteAndZero();
  63470. // have you been adding your own components directly to this window..? tut tut tut.
  63471. // Read the instructions for using a ResizableWindow!
  63472. jassert (getNumChildComponents() == 0);
  63473. }
  63474. int ResizableWindow::getDesktopWindowStyleFlags() const
  63475. {
  63476. int styleFlags = TopLevelWindow::getDesktopWindowStyleFlags();
  63477. if (isResizable() && (styleFlags & ComponentPeer::windowHasTitleBar) != 0)
  63478. styleFlags |= ComponentPeer::windowIsResizable;
  63479. return styleFlags;
  63480. }
  63481. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  63482. const bool deleteOldOne,
  63483. const bool resizeToFit)
  63484. {
  63485. resizeToFitContent = resizeToFit;
  63486. if (newContentComponent != static_cast <Component*> (contentComponent))
  63487. {
  63488. if (deleteOldOne)
  63489. contentComponent.deleteAndZero(); // (avoid using a scoped pointer for this, so that it survives
  63490. // external deletion of the content comp)
  63491. else
  63492. removeChildComponent (contentComponent);
  63493. contentComponent = newContentComponent;
  63494. Component::addAndMakeVisible (contentComponent);
  63495. }
  63496. if (resizeToFit)
  63497. childBoundsChanged (contentComponent);
  63498. resized(); // must always be called to position the new content comp
  63499. }
  63500. void ResizableWindow::setContentComponentSize (int width, int height)
  63501. {
  63502. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  63503. const BorderSize border (getContentComponentBorder());
  63504. setSize (width + border.getLeftAndRight(),
  63505. height + border.getTopAndBottom());
  63506. }
  63507. const BorderSize ResizableWindow::getBorderThickness()
  63508. {
  63509. return BorderSize (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  63510. }
  63511. const BorderSize ResizableWindow::getContentComponentBorder()
  63512. {
  63513. return getBorderThickness();
  63514. }
  63515. void ResizableWindow::moved()
  63516. {
  63517. updateLastPos();
  63518. }
  63519. void ResizableWindow::visibilityChanged()
  63520. {
  63521. TopLevelWindow::visibilityChanged();
  63522. updateLastPos();
  63523. }
  63524. void ResizableWindow::resized()
  63525. {
  63526. if (resizableBorder != 0)
  63527. {
  63528. #if JUCE_WINDOWS || JUCE_LINUX
  63529. // hide the resizable border if the OS already provides one..
  63530. resizableBorder->setVisible (! (isFullScreen() || isUsingNativeTitleBar()));
  63531. #else
  63532. resizableBorder->setVisible (! isFullScreen());
  63533. #endif
  63534. resizableBorder->setBorderThickness (getBorderThickness());
  63535. resizableBorder->setSize (getWidth(), getHeight());
  63536. resizableBorder->toBack();
  63537. }
  63538. if (resizableCorner != 0)
  63539. {
  63540. #if JUCE_MAC
  63541. // hide the resizable border if the OS already provides one..
  63542. resizableCorner->setVisible (! (isFullScreen() || isUsingNativeTitleBar()));
  63543. #else
  63544. resizableCorner->setVisible (! isFullScreen());
  63545. #endif
  63546. const int resizerSize = 18;
  63547. resizableCorner->setBounds (getWidth() - resizerSize,
  63548. getHeight() - resizerSize,
  63549. resizerSize, resizerSize);
  63550. }
  63551. if (contentComponent != 0)
  63552. contentComponent->setBoundsInset (getContentComponentBorder());
  63553. updateLastPos();
  63554. #if JUCE_DEBUG
  63555. hasBeenResized = true;
  63556. #endif
  63557. }
  63558. void ResizableWindow::childBoundsChanged (Component* child)
  63559. {
  63560. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  63561. {
  63562. // not going to look very good if this component has a zero size..
  63563. jassert (child->getWidth() > 0);
  63564. jassert (child->getHeight() > 0);
  63565. const BorderSize borders (getContentComponentBorder());
  63566. setSize (child->getWidth() + borders.getLeftAndRight(),
  63567. child->getHeight() + borders.getTopAndBottom());
  63568. }
  63569. }
  63570. void ResizableWindow::activeWindowStatusChanged()
  63571. {
  63572. const BorderSize border (getContentComponentBorder());
  63573. Rectangle<int> area (getLocalBounds());
  63574. repaint (area.removeFromTop (border.getTop()));
  63575. repaint (area.removeFromLeft (border.getLeft()));
  63576. repaint (area.removeFromRight (border.getRight()));
  63577. repaint (area.removeFromBottom (border.getBottom()));
  63578. }
  63579. void ResizableWindow::setResizable (const bool shouldBeResizable,
  63580. const bool useBottomRightCornerResizer)
  63581. {
  63582. if (shouldBeResizable)
  63583. {
  63584. if (useBottomRightCornerResizer)
  63585. {
  63586. resizableBorder = 0;
  63587. if (resizableCorner == 0)
  63588. {
  63589. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  63590. resizableCorner->setAlwaysOnTop (true);
  63591. }
  63592. }
  63593. else
  63594. {
  63595. resizableCorner = 0;
  63596. if (resizableBorder == 0)
  63597. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  63598. }
  63599. }
  63600. else
  63601. {
  63602. resizableCorner = 0;
  63603. resizableBorder = 0;
  63604. }
  63605. if (isUsingNativeTitleBar())
  63606. recreateDesktopWindow();
  63607. childBoundsChanged (contentComponent);
  63608. resized();
  63609. }
  63610. bool ResizableWindow::isResizable() const throw()
  63611. {
  63612. return resizableCorner != 0
  63613. || resizableBorder != 0;
  63614. }
  63615. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  63616. const int newMinimumHeight,
  63617. const int newMaximumWidth,
  63618. const int newMaximumHeight) throw()
  63619. {
  63620. // if you've set up a custom constrainer then these settings won't have any effect..
  63621. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  63622. if (constrainer == 0)
  63623. setConstrainer (&defaultConstrainer);
  63624. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  63625. newMaximumWidth, newMaximumHeight);
  63626. setBoundsConstrained (getBounds());
  63627. }
  63628. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  63629. {
  63630. if (constrainer != newConstrainer)
  63631. {
  63632. constrainer = newConstrainer;
  63633. const bool useBottomRightCornerResizer = resizableCorner != 0;
  63634. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  63635. resizableCorner = 0;
  63636. resizableBorder = 0;
  63637. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  63638. ComponentPeer* const peer = getPeer();
  63639. if (peer != 0)
  63640. peer->setConstrainer (newConstrainer);
  63641. }
  63642. }
  63643. void ResizableWindow::setBoundsConstrained (const Rectangle<int>& bounds)
  63644. {
  63645. if (constrainer != 0)
  63646. constrainer->setBoundsForComponent (this, bounds, false, false, false, false);
  63647. else
  63648. setBounds (bounds);
  63649. }
  63650. void ResizableWindow::paint (Graphics& g)
  63651. {
  63652. getLookAndFeel().fillResizableWindowBackground (g, getWidth(), getHeight(),
  63653. getBorderThickness(), *this);
  63654. if (! isFullScreen())
  63655. {
  63656. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  63657. getBorderThickness(), *this);
  63658. }
  63659. #if JUCE_DEBUG
  63660. /* If this fails, then you've probably written a subclass with a resized()
  63661. callback but forgotten to make it call its parent class's resized() method.
  63662. It's important when you override methods like resized(), moved(),
  63663. etc., that you make sure the base class methods also get called.
  63664. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  63665. because your content should all be inside the content component - and it's the
  63666. content component's resized() method that you should be using to do your
  63667. layout.
  63668. */
  63669. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  63670. #endif
  63671. }
  63672. void ResizableWindow::lookAndFeelChanged()
  63673. {
  63674. resized();
  63675. if (isOnDesktop())
  63676. {
  63677. Component::addToDesktop (getDesktopWindowStyleFlags());
  63678. ComponentPeer* const peer = getPeer();
  63679. if (peer != 0)
  63680. peer->setConstrainer (constrainer);
  63681. }
  63682. }
  63683. const Colour ResizableWindow::getBackgroundColour() const throw()
  63684. {
  63685. return findColour (backgroundColourId, false);
  63686. }
  63687. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  63688. {
  63689. Colour backgroundColour (newColour);
  63690. if (! Desktop::canUseSemiTransparentWindows())
  63691. backgroundColour = newColour.withAlpha (1.0f);
  63692. setColour (backgroundColourId, backgroundColour);
  63693. setOpaque (backgroundColour.isOpaque());
  63694. repaint();
  63695. }
  63696. bool ResizableWindow::isFullScreen() const
  63697. {
  63698. if (isOnDesktop())
  63699. {
  63700. ComponentPeer* const peer = getPeer();
  63701. return peer != 0 && peer->isFullScreen();
  63702. }
  63703. return fullscreen;
  63704. }
  63705. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  63706. {
  63707. if (shouldBeFullScreen != isFullScreen())
  63708. {
  63709. updateLastPos();
  63710. fullscreen = shouldBeFullScreen;
  63711. if (isOnDesktop())
  63712. {
  63713. ComponentPeer* const peer = getPeer();
  63714. if (peer != 0)
  63715. {
  63716. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  63717. const Rectangle<int> lastPos (lastNonFullScreenPos);
  63718. peer->setFullScreen (shouldBeFullScreen);
  63719. if (! shouldBeFullScreen)
  63720. setBounds (lastPos);
  63721. }
  63722. else
  63723. {
  63724. jassertfalse;
  63725. }
  63726. }
  63727. else
  63728. {
  63729. if (shouldBeFullScreen)
  63730. setBounds (0, 0, getParentWidth(), getParentHeight());
  63731. else
  63732. setBounds (lastNonFullScreenPos);
  63733. }
  63734. resized();
  63735. }
  63736. }
  63737. bool ResizableWindow::isMinimised() const
  63738. {
  63739. ComponentPeer* const peer = getPeer();
  63740. return (peer != 0) && peer->isMinimised();
  63741. }
  63742. void ResizableWindow::setMinimised (const bool shouldMinimise)
  63743. {
  63744. if (shouldMinimise != isMinimised())
  63745. {
  63746. ComponentPeer* const peer = getPeer();
  63747. if (peer != 0)
  63748. {
  63749. updateLastPos();
  63750. peer->setMinimised (shouldMinimise);
  63751. }
  63752. else
  63753. {
  63754. jassertfalse;
  63755. }
  63756. }
  63757. }
  63758. void ResizableWindow::updateLastPos()
  63759. {
  63760. if (isShowing() && ! (isFullScreen() || isMinimised()))
  63761. {
  63762. lastNonFullScreenPos = getBounds();
  63763. }
  63764. }
  63765. void ResizableWindow::parentSizeChanged()
  63766. {
  63767. if (isFullScreen() && getParentComponent() != 0)
  63768. {
  63769. setBounds (0, 0, getParentWidth(), getParentHeight());
  63770. }
  63771. }
  63772. const String ResizableWindow::getWindowStateAsString()
  63773. {
  63774. updateLastPos();
  63775. return (isFullScreen() ? "fs " : "") + lastNonFullScreenPos.toString();
  63776. }
  63777. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  63778. {
  63779. StringArray tokens;
  63780. tokens.addTokens (s, false);
  63781. tokens.removeEmptyStrings();
  63782. tokens.trim();
  63783. const bool fs = tokens[0].startsWithIgnoreCase ("fs");
  63784. const int firstCoord = fs ? 1 : 0;
  63785. if (tokens.size() != firstCoord + 4)
  63786. return false;
  63787. Rectangle<int> newPos (tokens[firstCoord].getIntValue(),
  63788. tokens[firstCoord + 1].getIntValue(),
  63789. tokens[firstCoord + 2].getIntValue(),
  63790. tokens[firstCoord + 3].getIntValue());
  63791. if (newPos.isEmpty())
  63792. return false;
  63793. const Rectangle<int> screen (Desktop::getInstance().getMonitorAreaContaining (newPos.getCentre()));
  63794. ComponentPeer* const peer = isOnDesktop() ? getPeer() : 0;
  63795. if (peer != 0)
  63796. peer->getFrameSize().addTo (newPos);
  63797. if (! screen.contains (newPos))
  63798. {
  63799. newPos.setSize (jmin (newPos.getWidth(), screen.getWidth()),
  63800. jmin (newPos.getHeight(), screen.getHeight()));
  63801. newPos.setPosition (jlimit (screen.getX(), screen.getRight() - newPos.getWidth(), newPos.getX()),
  63802. jlimit (screen.getY(), screen.getBottom() - newPos.getHeight(), newPos.getY()));
  63803. }
  63804. if (peer != 0)
  63805. {
  63806. peer->getFrameSize().subtractFrom (newPos);
  63807. peer->setNonFullScreenBounds (newPos);
  63808. }
  63809. lastNonFullScreenPos = newPos;
  63810. setFullScreen (fs);
  63811. if (! fs)
  63812. setBoundsConstrained (newPos);
  63813. return true;
  63814. }
  63815. void ResizableWindow::mouseDown (const MouseEvent&)
  63816. {
  63817. if (! isFullScreen())
  63818. dragger.startDraggingComponent (this, constrainer);
  63819. }
  63820. void ResizableWindow::mouseDrag (const MouseEvent& e)
  63821. {
  63822. if (! isFullScreen())
  63823. dragger.dragComponent (this, e);
  63824. }
  63825. #if JUCE_DEBUG
  63826. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  63827. {
  63828. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63829. manages its child components automatically, and if you add your own it'll cause
  63830. trouble. Instead, use setContentComponent() to give it a component which
  63831. will be automatically resized and kept in the right place - then you can add
  63832. subcomponents to the content comp. See the notes for the ResizableWindow class
  63833. for more info.
  63834. If you really know what you're doing and want to avoid this assertion, just call
  63835. Component::addChildComponent directly.
  63836. */
  63837. jassertfalse;
  63838. Component::addChildComponent (child, zOrder);
  63839. }
  63840. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  63841. {
  63842. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63843. manages its child components automatically, and if you add your own it'll cause
  63844. trouble. Instead, use setContentComponent() to give it a component which
  63845. will be automatically resized and kept in the right place - then you can add
  63846. subcomponents to the content comp. See the notes for the ResizableWindow class
  63847. for more info.
  63848. If you really know what you're doing and want to avoid this assertion, just call
  63849. Component::addAndMakeVisible directly.
  63850. */
  63851. jassertfalse;
  63852. Component::addAndMakeVisible (child, zOrder);
  63853. }
  63854. #endif
  63855. END_JUCE_NAMESPACE
  63856. /*** End of inlined file: juce_ResizableWindow.cpp ***/
  63857. /*** Start of inlined file: juce_SplashScreen.cpp ***/
  63858. BEGIN_JUCE_NAMESPACE
  63859. SplashScreen::SplashScreen()
  63860. {
  63861. setOpaque (true);
  63862. }
  63863. SplashScreen::~SplashScreen()
  63864. {
  63865. }
  63866. void SplashScreen::show (const String& title,
  63867. const Image& backgroundImage_,
  63868. const int minimumTimeToDisplayFor,
  63869. const bool useDropShadow,
  63870. const bool removeOnMouseClick)
  63871. {
  63872. backgroundImage = backgroundImage_;
  63873. jassert (backgroundImage_.isValid());
  63874. if (backgroundImage_.isValid())
  63875. {
  63876. setOpaque (! backgroundImage_.hasAlphaChannel());
  63877. show (title,
  63878. backgroundImage_.getWidth(),
  63879. backgroundImage_.getHeight(),
  63880. minimumTimeToDisplayFor,
  63881. useDropShadow,
  63882. removeOnMouseClick);
  63883. }
  63884. }
  63885. void SplashScreen::show (const String& title,
  63886. const int width,
  63887. const int height,
  63888. const int minimumTimeToDisplayFor,
  63889. const bool useDropShadow,
  63890. const bool removeOnMouseClick)
  63891. {
  63892. setName (title);
  63893. setAlwaysOnTop (true);
  63894. setVisible (true);
  63895. centreWithSize (width, height);
  63896. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  63897. toFront (false);
  63898. MessageManager::getInstance()->runDispatchLoopUntil (300);
  63899. repaint();
  63900. originalClickCounter = removeOnMouseClick
  63901. ? Desktop::getMouseButtonClickCounter()
  63902. : std::numeric_limits<int>::max();
  63903. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  63904. startTimer (50);
  63905. }
  63906. void SplashScreen::paint (Graphics& g)
  63907. {
  63908. g.setOpacity (1.0f);
  63909. g.drawImage (backgroundImage,
  63910. 0, 0, getWidth(), getHeight(),
  63911. 0, 0, backgroundImage.getWidth(), backgroundImage.getHeight());
  63912. }
  63913. void SplashScreen::timerCallback()
  63914. {
  63915. if (Time::getCurrentTime() > earliestTimeToDelete
  63916. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  63917. {
  63918. delete this;
  63919. }
  63920. }
  63921. END_JUCE_NAMESPACE
  63922. /*** End of inlined file: juce_SplashScreen.cpp ***/
  63923. /*** Start of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63924. BEGIN_JUCE_NAMESPACE
  63925. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  63926. const bool hasProgressBar,
  63927. const bool hasCancelButton,
  63928. const int timeOutMsWhenCancelling_,
  63929. const String& cancelButtonText)
  63930. : Thread ("Juce Progress Window"),
  63931. progress (0.0),
  63932. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  63933. {
  63934. alertWindow = LookAndFeel::getDefaultLookAndFeel()
  63935. .createAlertWindow (title, String::empty, cancelButtonText,
  63936. String::empty, String::empty,
  63937. AlertWindow::NoIcon, hasCancelButton ? 1 : 0, 0);
  63938. if (hasProgressBar)
  63939. alertWindow->addProgressBarComponent (progress);
  63940. }
  63941. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  63942. {
  63943. stopThread (timeOutMsWhenCancelling);
  63944. }
  63945. bool ThreadWithProgressWindow::runThread (const int priority)
  63946. {
  63947. startThread (priority);
  63948. startTimer (100);
  63949. {
  63950. const ScopedLock sl (messageLock);
  63951. alertWindow->setMessage (message);
  63952. }
  63953. const bool finishedNaturally = alertWindow->runModalLoop() != 0;
  63954. stopThread (timeOutMsWhenCancelling);
  63955. alertWindow->setVisible (false);
  63956. return finishedNaturally;
  63957. }
  63958. void ThreadWithProgressWindow::setProgress (const double newProgress)
  63959. {
  63960. progress = newProgress;
  63961. }
  63962. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  63963. {
  63964. const ScopedLock sl (messageLock);
  63965. message = newStatusMessage;
  63966. }
  63967. void ThreadWithProgressWindow::timerCallback()
  63968. {
  63969. if (! isThreadRunning())
  63970. {
  63971. // thread has finished normally..
  63972. alertWindow->exitModalState (1);
  63973. alertWindow->setVisible (false);
  63974. }
  63975. else
  63976. {
  63977. const ScopedLock sl (messageLock);
  63978. alertWindow->setMessage (message);
  63979. }
  63980. }
  63981. END_JUCE_NAMESPACE
  63982. /*** End of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63983. /*** Start of inlined file: juce_TooltipWindow.cpp ***/
  63984. BEGIN_JUCE_NAMESPACE
  63985. TooltipWindow::TooltipWindow (Component* const parentComponent,
  63986. const int millisecondsBeforeTipAppears_)
  63987. : Component ("tooltip"),
  63988. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  63989. mouseClicks (0),
  63990. lastHideTime (0),
  63991. lastComponentUnderMouse (0),
  63992. changedCompsSinceShown (true)
  63993. {
  63994. if (Desktop::getInstance().getMainMouseSource().canHover())
  63995. startTimer (123);
  63996. setAlwaysOnTop (true);
  63997. setOpaque (true);
  63998. if (parentComponent != 0)
  63999. parentComponent->addChildComponent (this);
  64000. }
  64001. TooltipWindow::~TooltipWindow()
  64002. {
  64003. hide();
  64004. }
  64005. void TooltipWindow::setMillisecondsBeforeTipAppears (const int newTimeMs) throw()
  64006. {
  64007. millisecondsBeforeTipAppears = newTimeMs;
  64008. }
  64009. void TooltipWindow::paint (Graphics& g)
  64010. {
  64011. getLookAndFeel().drawTooltip (g, tipShowing, getWidth(), getHeight());
  64012. }
  64013. void TooltipWindow::mouseEnter (const MouseEvent&)
  64014. {
  64015. hide();
  64016. }
  64017. void TooltipWindow::showFor (const String& tip)
  64018. {
  64019. jassert (tip.isNotEmpty());
  64020. if (tipShowing != tip)
  64021. repaint();
  64022. tipShowing = tip;
  64023. Point<int> mousePos (Desktop::getMousePosition());
  64024. if (getParentComponent() != 0)
  64025. mousePos = getParentComponent()->globalPositionToRelative (mousePos);
  64026. int x, y, w, h;
  64027. getLookAndFeel().getTooltipSize (tip, w, h);
  64028. if (mousePos.getX() > getParentWidth() / 2)
  64029. x = mousePos.getX() - (w + 12);
  64030. else
  64031. x = mousePos.getX() + 24;
  64032. if (mousePos.getY() > getParentHeight() / 2)
  64033. y = mousePos.getY() - (h + 6);
  64034. else
  64035. y = mousePos.getY() + 6;
  64036. setBounds (x, y, w, h);
  64037. setVisible (true);
  64038. if (getParentComponent() == 0)
  64039. {
  64040. addToDesktop (ComponentPeer::windowHasDropShadow
  64041. | ComponentPeer::windowIsTemporary
  64042. | ComponentPeer::windowIgnoresKeyPresses);
  64043. }
  64044. toFront (false);
  64045. }
  64046. const String TooltipWindow::getTipFor (Component* const c)
  64047. {
  64048. if (c != 0
  64049. && Process::isForegroundProcess()
  64050. && ! Component::isMouseButtonDownAnywhere())
  64051. {
  64052. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  64053. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  64054. return ttc->getTooltip();
  64055. }
  64056. return String::empty;
  64057. }
  64058. void TooltipWindow::hide()
  64059. {
  64060. tipShowing = String::empty;
  64061. removeFromDesktop();
  64062. setVisible (false);
  64063. }
  64064. void TooltipWindow::timerCallback()
  64065. {
  64066. const unsigned int now = Time::getApproximateMillisecondCounter();
  64067. Component* const newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  64068. const String newTip (getTipFor (newComp));
  64069. const bool tipChanged = (newTip != lastTipUnderMouse || newComp != lastComponentUnderMouse);
  64070. lastComponentUnderMouse = newComp;
  64071. lastTipUnderMouse = newTip;
  64072. const int clickCount = Desktop::getInstance().getMouseButtonClickCounter();
  64073. const bool mouseWasClicked = clickCount > mouseClicks;
  64074. mouseClicks = clickCount;
  64075. const Point<int> mousePos (Desktop::getMousePosition());
  64076. const bool mouseMovedQuickly = mousePos.getDistanceFrom (lastMousePos) > 12;
  64077. lastMousePos = mousePos;
  64078. if (tipChanged || mouseWasClicked || mouseMovedQuickly)
  64079. lastCompChangeTime = now;
  64080. if (isVisible() || now < lastHideTime + 500)
  64081. {
  64082. // if a tip is currently visible (or has just disappeared), update to a new one
  64083. // immediately if needed..
  64084. if (newComp == 0 || mouseWasClicked || newTip.isEmpty())
  64085. {
  64086. if (isVisible())
  64087. {
  64088. lastHideTime = now;
  64089. hide();
  64090. }
  64091. }
  64092. else if (tipChanged)
  64093. {
  64094. showFor (newTip);
  64095. }
  64096. }
  64097. else
  64098. {
  64099. // if there isn't currently a tip, but one is needed, only let it
  64100. // appear after a timeout..
  64101. if (newTip.isNotEmpty()
  64102. && newTip != tipShowing
  64103. && now > lastCompChangeTime + millisecondsBeforeTipAppears)
  64104. {
  64105. showFor (newTip);
  64106. }
  64107. }
  64108. }
  64109. END_JUCE_NAMESPACE
  64110. /*** End of inlined file: juce_TooltipWindow.cpp ***/
  64111. /*** Start of inlined file: juce_TopLevelWindow.cpp ***/
  64112. BEGIN_JUCE_NAMESPACE
  64113. /** Keeps track of the active top level window.
  64114. */
  64115. class TopLevelWindowManager : public Timer,
  64116. public DeletedAtShutdown
  64117. {
  64118. public:
  64119. TopLevelWindowManager()
  64120. : currentActive (0)
  64121. {
  64122. }
  64123. ~TopLevelWindowManager()
  64124. {
  64125. clearSingletonInstance();
  64126. }
  64127. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  64128. void timerCallback()
  64129. {
  64130. startTimer (jmin (1731, getTimerInterval() * 2));
  64131. TopLevelWindow* active = 0;
  64132. if (Process::isForegroundProcess())
  64133. {
  64134. active = currentActive;
  64135. Component* const c = Component::getCurrentlyFocusedComponent();
  64136. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  64137. if (tlw == 0 && c != 0)
  64138. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  64139. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  64140. if (tlw != 0)
  64141. active = tlw;
  64142. }
  64143. if (active != currentActive)
  64144. {
  64145. currentActive = active;
  64146. for (int i = windows.size(); --i >= 0;)
  64147. {
  64148. TopLevelWindow* const tlw = windows.getUnchecked (i);
  64149. tlw->setWindowActive (isWindowActive (tlw));
  64150. i = jmin (i, windows.size() - 1);
  64151. }
  64152. Desktop::getInstance().triggerFocusCallback();
  64153. }
  64154. }
  64155. bool addWindow (TopLevelWindow* const w)
  64156. {
  64157. windows.add (w);
  64158. startTimer (10);
  64159. return isWindowActive (w);
  64160. }
  64161. void removeWindow (TopLevelWindow* const w)
  64162. {
  64163. startTimer (10);
  64164. if (currentActive == w)
  64165. currentActive = 0;
  64166. windows.removeValue (w);
  64167. if (windows.size() == 0)
  64168. deleteInstance();
  64169. }
  64170. Array <TopLevelWindow*> windows;
  64171. private:
  64172. TopLevelWindow* currentActive;
  64173. bool isWindowActive (TopLevelWindow* const tlw) const
  64174. {
  64175. return (tlw == currentActive
  64176. || tlw->isParentOf (currentActive)
  64177. || tlw->hasKeyboardFocus (true))
  64178. && tlw->isShowing();
  64179. }
  64180. TopLevelWindowManager (const TopLevelWindowManager&);
  64181. TopLevelWindowManager& operator= (const TopLevelWindowManager&);
  64182. };
  64183. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  64184. void juce_CheckCurrentlyFocusedTopLevelWindow()
  64185. {
  64186. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  64187. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  64188. }
  64189. TopLevelWindow::TopLevelWindow (const String& name,
  64190. const bool addToDesktop_)
  64191. : Component (name),
  64192. useDropShadow (true),
  64193. useNativeTitleBar (false),
  64194. windowIsActive_ (false)
  64195. {
  64196. setOpaque (true);
  64197. if (addToDesktop_)
  64198. Component::addToDesktop (getDesktopWindowStyleFlags());
  64199. else
  64200. setDropShadowEnabled (true);
  64201. setWantsKeyboardFocus (true);
  64202. setBroughtToFrontOnMouseClick (true);
  64203. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  64204. }
  64205. TopLevelWindow::~TopLevelWindow()
  64206. {
  64207. shadower = 0;
  64208. TopLevelWindowManager::getInstance()->removeWindow (this);
  64209. }
  64210. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  64211. {
  64212. if (hasKeyboardFocus (true))
  64213. TopLevelWindowManager::getInstance()->timerCallback();
  64214. else
  64215. TopLevelWindowManager::getInstance()->startTimer (10);
  64216. }
  64217. void TopLevelWindow::setWindowActive (const bool isNowActive)
  64218. {
  64219. if (windowIsActive_ != isNowActive)
  64220. {
  64221. windowIsActive_ = isNowActive;
  64222. activeWindowStatusChanged();
  64223. }
  64224. }
  64225. void TopLevelWindow::activeWindowStatusChanged()
  64226. {
  64227. }
  64228. void TopLevelWindow::parentHierarchyChanged()
  64229. {
  64230. setDropShadowEnabled (useDropShadow);
  64231. }
  64232. void TopLevelWindow::visibilityChanged()
  64233. {
  64234. if (isShowing())
  64235. toFront (true);
  64236. }
  64237. int TopLevelWindow::getDesktopWindowStyleFlags() const
  64238. {
  64239. int styleFlags = ComponentPeer::windowAppearsOnTaskbar;
  64240. if (useDropShadow)
  64241. styleFlags |= ComponentPeer::windowHasDropShadow;
  64242. if (useNativeTitleBar)
  64243. styleFlags |= ComponentPeer::windowHasTitleBar;
  64244. return styleFlags;
  64245. }
  64246. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  64247. {
  64248. useDropShadow = useShadow;
  64249. if (isOnDesktop())
  64250. {
  64251. shadower = 0;
  64252. Component::addToDesktop (getDesktopWindowStyleFlags());
  64253. }
  64254. else
  64255. {
  64256. if (useShadow && isOpaque())
  64257. {
  64258. if (shadower == 0)
  64259. {
  64260. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  64261. if (shadower != 0)
  64262. shadower->setOwner (this);
  64263. }
  64264. }
  64265. else
  64266. {
  64267. shadower = 0;
  64268. }
  64269. }
  64270. }
  64271. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  64272. {
  64273. if (useNativeTitleBar != useNativeTitleBar_)
  64274. {
  64275. useNativeTitleBar = useNativeTitleBar_;
  64276. recreateDesktopWindow();
  64277. sendLookAndFeelChange();
  64278. }
  64279. }
  64280. void TopLevelWindow::recreateDesktopWindow()
  64281. {
  64282. if (isOnDesktop())
  64283. {
  64284. Component::addToDesktop (getDesktopWindowStyleFlags());
  64285. toFront (true);
  64286. }
  64287. }
  64288. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  64289. {
  64290. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  64291. because this class needs to make sure its layout corresponds with settings like whether
  64292. it's got a native title bar or not.
  64293. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  64294. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  64295. method, then add or remove whatever flags are necessary from this value before returning it.
  64296. */
  64297. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  64298. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  64299. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  64300. if (windowStyleFlags != getDesktopWindowStyleFlags())
  64301. sendLookAndFeelChange();
  64302. }
  64303. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  64304. {
  64305. if (c == 0)
  64306. c = TopLevelWindow::getActiveTopLevelWindow();
  64307. if (c == 0)
  64308. {
  64309. centreWithSize (width, height);
  64310. }
  64311. else
  64312. {
  64313. Point<int> p (c->relativePositionToGlobal (Point<int> ((c->getWidth() - width) / 2,
  64314. (c->getHeight() - height) / 2)));
  64315. Rectangle<int> parentArea (c->getParentMonitorArea());
  64316. if (getParentComponent() != 0)
  64317. {
  64318. p = getParentComponent()->globalPositionToRelative (p);
  64319. parentArea.setBounds (0, 0, getParentWidth(), getParentHeight());
  64320. }
  64321. parentArea.reduce (12, 12);
  64322. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), p.getX()),
  64323. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), p.getY()),
  64324. width, height);
  64325. }
  64326. }
  64327. int TopLevelWindow::getNumTopLevelWindows() throw()
  64328. {
  64329. return TopLevelWindowManager::getInstance()->windows.size();
  64330. }
  64331. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  64332. {
  64333. return static_cast <TopLevelWindow*> (TopLevelWindowManager::getInstance()->windows [index]);
  64334. }
  64335. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  64336. {
  64337. TopLevelWindow* best = 0;
  64338. int bestNumTWLParents = -1;
  64339. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  64340. {
  64341. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  64342. if (tlw->isActiveWindow())
  64343. {
  64344. int numTWLParents = 0;
  64345. const Component* c = tlw->getParentComponent();
  64346. while (c != 0)
  64347. {
  64348. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  64349. ++numTWLParents;
  64350. c = c->getParentComponent();
  64351. }
  64352. if (bestNumTWLParents < numTWLParents)
  64353. {
  64354. best = tlw;
  64355. bestNumTWLParents = numTWLParents;
  64356. }
  64357. }
  64358. }
  64359. return best;
  64360. }
  64361. END_JUCE_NAMESPACE
  64362. /*** End of inlined file: juce_TopLevelWindow.cpp ***/
  64363. /*** Start of inlined file: juce_RelativeCoordinate.cpp ***/
  64364. BEGIN_JUCE_NAMESPACE
  64365. namespace RelativeCoordinateHelpers
  64366. {
  64367. static void skipComma (const juce_wchar* const s, int& i)
  64368. {
  64369. while (CharacterFunctions::isWhitespace (s[i]))
  64370. ++i;
  64371. if (s[i] == ',')
  64372. ++i;
  64373. }
  64374. }
  64375. const String RelativeCoordinate::Strings::parent ("parent");
  64376. const String RelativeCoordinate::Strings::left ("left");
  64377. const String RelativeCoordinate::Strings::right ("right");
  64378. const String RelativeCoordinate::Strings::top ("top");
  64379. const String RelativeCoordinate::Strings::bottom ("bottom");
  64380. const String RelativeCoordinate::Strings::parentLeft ("parent.left");
  64381. const String RelativeCoordinate::Strings::parentTop ("parent.top");
  64382. const String RelativeCoordinate::Strings::parentRight ("parent.right");
  64383. const String RelativeCoordinate::Strings::parentBottom ("parent.bottom");
  64384. RelativeCoordinate::RelativeCoordinate()
  64385. {
  64386. }
  64387. RelativeCoordinate::RelativeCoordinate (const Expression& term_)
  64388. : term (term_)
  64389. {
  64390. }
  64391. RelativeCoordinate::RelativeCoordinate (const RelativeCoordinate& other)
  64392. : term (other.term)
  64393. {
  64394. }
  64395. RelativeCoordinate& RelativeCoordinate::operator= (const RelativeCoordinate& other)
  64396. {
  64397. term = other.term;
  64398. return *this;
  64399. }
  64400. RelativeCoordinate::RelativeCoordinate (const double absoluteDistanceFromOrigin)
  64401. : term (absoluteDistanceFromOrigin)
  64402. {
  64403. }
  64404. RelativeCoordinate::RelativeCoordinate (const String& s)
  64405. {
  64406. try
  64407. {
  64408. term = Expression (s);
  64409. }
  64410. catch (...)
  64411. {}
  64412. }
  64413. RelativeCoordinate::~RelativeCoordinate()
  64414. {
  64415. }
  64416. bool RelativeCoordinate::operator== (const RelativeCoordinate& other) const throw()
  64417. {
  64418. return term.toString() == other.term.toString();
  64419. }
  64420. bool RelativeCoordinate::operator!= (const RelativeCoordinate& other) const throw()
  64421. {
  64422. return ! operator== (other);
  64423. }
  64424. double RelativeCoordinate::resolve (const Expression::EvaluationContext* context) const
  64425. {
  64426. try
  64427. {
  64428. if (context != 0)
  64429. return term.evaluate (*context);
  64430. else
  64431. return term.evaluate();
  64432. }
  64433. catch (...)
  64434. {}
  64435. return 0.0;
  64436. }
  64437. bool RelativeCoordinate::isRecursive (const Expression::EvaluationContext* context) const
  64438. {
  64439. try
  64440. {
  64441. if (context != 0)
  64442. term.evaluate (*context);
  64443. else
  64444. term.evaluate();
  64445. }
  64446. catch (...)
  64447. {
  64448. return true;
  64449. }
  64450. return false;
  64451. }
  64452. void RelativeCoordinate::moveToAbsolute (double newPos, const Expression::EvaluationContext* context)
  64453. {
  64454. try
  64455. {
  64456. if (context != 0)
  64457. {
  64458. term = term.adjustedToGiveNewResult (newPos, *context);
  64459. }
  64460. else
  64461. {
  64462. Expression::EvaluationContext defaultContext;
  64463. term = term.adjustedToGiveNewResult (newPos, defaultContext);
  64464. }
  64465. }
  64466. catch (...)
  64467. {}
  64468. }
  64469. bool RelativeCoordinate::references (const String& coordName, const Expression::EvaluationContext* context) const
  64470. {
  64471. try
  64472. {
  64473. return term.referencesSymbol (coordName, context);
  64474. }
  64475. catch (...)
  64476. {}
  64477. return false;
  64478. }
  64479. bool RelativeCoordinate::isDynamic() const
  64480. {
  64481. return term.usesAnySymbols();
  64482. }
  64483. const String RelativeCoordinate::toString() const
  64484. {
  64485. return term.toString();
  64486. }
  64487. void RelativeCoordinate::renameSymbolIfUsed (const String& oldName, const String& newName)
  64488. {
  64489. jassert (newName.isNotEmpty() && newName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  64490. if (term.referencesSymbol (oldName, 0))
  64491. term = term.withRenamedSymbol (oldName, newName);
  64492. }
  64493. RelativePoint::RelativePoint()
  64494. {
  64495. }
  64496. RelativePoint::RelativePoint (const Point<float>& absolutePoint)
  64497. : x (absolutePoint.getX()), y (absolutePoint.getY())
  64498. {
  64499. }
  64500. RelativePoint::RelativePoint (const float x_, const float y_)
  64501. : x (x_), y (y_)
  64502. {
  64503. }
  64504. RelativePoint::RelativePoint (const RelativeCoordinate& x_, const RelativeCoordinate& y_)
  64505. : x (x_), y (y_)
  64506. {
  64507. }
  64508. RelativePoint::RelativePoint (const String& s)
  64509. {
  64510. int i = 0;
  64511. x = RelativeCoordinate (Expression::parse (s, i));
  64512. RelativeCoordinateHelpers::skipComma (s, i);
  64513. y = RelativeCoordinate (Expression::parse (s, i));
  64514. }
  64515. bool RelativePoint::operator== (const RelativePoint& other) const throw()
  64516. {
  64517. return x == other.x && y == other.y;
  64518. }
  64519. bool RelativePoint::operator!= (const RelativePoint& other) const throw()
  64520. {
  64521. return ! operator== (other);
  64522. }
  64523. const Point<float> RelativePoint::resolve (const Expression::EvaluationContext* context) const
  64524. {
  64525. return Point<float> ((float) x.resolve (context),
  64526. (float) y.resolve (context));
  64527. }
  64528. void RelativePoint::moveToAbsolute (const Point<float>& newPos, const Expression::EvaluationContext* context)
  64529. {
  64530. x.moveToAbsolute (newPos.getX(), context);
  64531. y.moveToAbsolute (newPos.getY(), context);
  64532. }
  64533. const String RelativePoint::toString() const
  64534. {
  64535. return x.toString() + ", " + y.toString();
  64536. }
  64537. void RelativePoint::renameSymbolIfUsed (const String& oldName, const String& newName)
  64538. {
  64539. x.renameSymbolIfUsed (oldName, newName);
  64540. y.renameSymbolIfUsed (oldName, newName);
  64541. }
  64542. bool RelativePoint::isDynamic() const
  64543. {
  64544. return x.isDynamic() || y.isDynamic();
  64545. }
  64546. RelativeRectangle::RelativeRectangle()
  64547. {
  64548. }
  64549. RelativeRectangle::RelativeRectangle (const RelativeCoordinate& left_, const RelativeCoordinate& right_,
  64550. const RelativeCoordinate& top_, const RelativeCoordinate& bottom_)
  64551. : left (left_), right (right_), top (top_), bottom (bottom_)
  64552. {
  64553. }
  64554. RelativeRectangle::RelativeRectangle (const Rectangle<float>& rect, const String& componentName)
  64555. : left (rect.getX()),
  64556. right (Expression::symbol (componentName + "." + RelativeCoordinate::Strings::left) + Expression ((double) rect.getWidth())),
  64557. top (rect.getY()),
  64558. bottom (Expression::symbol (componentName + "." + RelativeCoordinate::Strings::top) + Expression ((double) rect.getHeight()))
  64559. {
  64560. }
  64561. RelativeRectangle::RelativeRectangle (const String& s)
  64562. {
  64563. int i = 0;
  64564. left = RelativeCoordinate (Expression::parse (s, i));
  64565. RelativeCoordinateHelpers::skipComma (s, i);
  64566. top = RelativeCoordinate (Expression::parse (s, i));
  64567. RelativeCoordinateHelpers::skipComma (s, i);
  64568. right = RelativeCoordinate (Expression::parse (s, i));
  64569. RelativeCoordinateHelpers::skipComma (s, i);
  64570. bottom = RelativeCoordinate (Expression::parse (s, i));
  64571. }
  64572. bool RelativeRectangle::operator== (const RelativeRectangle& other) const throw()
  64573. {
  64574. return left == other.left && top == other.top && right == other.right && bottom == other.bottom;
  64575. }
  64576. bool RelativeRectangle::operator!= (const RelativeRectangle& other) const throw()
  64577. {
  64578. return ! operator== (other);
  64579. }
  64580. const Rectangle<float> RelativeRectangle::resolve (const Expression::EvaluationContext* context) const
  64581. {
  64582. const double l = left.resolve (context);
  64583. const double r = right.resolve (context);
  64584. const double t = top.resolve (context);
  64585. const double b = bottom.resolve (context);
  64586. return Rectangle<float> ((float) l, (float) t, (float) (r - l), (float) (b - t));
  64587. }
  64588. void RelativeRectangle::moveToAbsolute (const Rectangle<float>& newPos, const Expression::EvaluationContext* context)
  64589. {
  64590. left.moveToAbsolute (newPos.getX(), context);
  64591. right.moveToAbsolute (newPos.getRight(), context);
  64592. top.moveToAbsolute (newPos.getY(), context);
  64593. bottom.moveToAbsolute (newPos.getBottom(), context);
  64594. }
  64595. const String RelativeRectangle::toString() const
  64596. {
  64597. return left.toString() + ", " + top.toString() + ", " + right.toString() + ", " + bottom.toString();
  64598. }
  64599. void RelativeRectangle::renameSymbolIfUsed (const String& oldName, const String& newName)
  64600. {
  64601. left.renameSymbolIfUsed (oldName, newName);
  64602. right.renameSymbolIfUsed (oldName, newName);
  64603. top.renameSymbolIfUsed (oldName, newName);
  64604. bottom.renameSymbolIfUsed (oldName, newName);
  64605. }
  64606. RelativePointPath::RelativePointPath()
  64607. : usesNonZeroWinding (true),
  64608. containsDynamicPoints (false)
  64609. {
  64610. }
  64611. RelativePointPath::RelativePointPath (const RelativePointPath& other)
  64612. : usesNonZeroWinding (true),
  64613. containsDynamicPoints (false)
  64614. {
  64615. ValueTree state (DrawablePath::valueTreeType);
  64616. other.writeTo (state, 0);
  64617. parse (state);
  64618. }
  64619. RelativePointPath::RelativePointPath (const ValueTree& drawable)
  64620. : usesNonZeroWinding (true),
  64621. containsDynamicPoints (false)
  64622. {
  64623. parse (drawable);
  64624. }
  64625. RelativePointPath::RelativePointPath (const Path& path)
  64626. {
  64627. usesNonZeroWinding = path.isUsingNonZeroWinding();
  64628. Path::Iterator i (path);
  64629. while (i.next())
  64630. {
  64631. switch (i.elementType)
  64632. {
  64633. case Path::Iterator::startNewSubPath: elements.add (new StartSubPath (RelativePoint (i.x1, i.y1))); break;
  64634. case Path::Iterator::lineTo: elements.add (new LineTo (RelativePoint (i.x1, i.y1))); break;
  64635. case Path::Iterator::quadraticTo: elements.add (new QuadraticTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2))); break;
  64636. case Path::Iterator::cubicTo: elements.add (new CubicTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2), RelativePoint (i.x3, i.y3))); break;
  64637. case Path::Iterator::closePath: elements.add (new CloseSubPath()); break;
  64638. default: jassertfalse; break;
  64639. }
  64640. }
  64641. }
  64642. void RelativePointPath::writeTo (ValueTree state, UndoManager* undoManager) const
  64643. {
  64644. DrawablePath::ValueTreeWrapper wrapper (state);
  64645. wrapper.setUsesNonZeroWinding (usesNonZeroWinding, undoManager);
  64646. ValueTree pathTree (wrapper.getPathState());
  64647. pathTree.removeAllChildren (undoManager);
  64648. for (int i = 0; i < elements.size(); ++i)
  64649. pathTree.addChild (elements.getUnchecked(i)->createTree(), -1, undoManager);
  64650. }
  64651. void RelativePointPath::parse (const ValueTree& state)
  64652. {
  64653. DrawablePath::ValueTreeWrapper wrapper (state);
  64654. usesNonZeroWinding = wrapper.usesNonZeroWinding();
  64655. RelativePoint points[3];
  64656. const ValueTree pathTree (wrapper.getPathState());
  64657. const int num = pathTree.getNumChildren();
  64658. for (int i = 0; i < num; ++i)
  64659. {
  64660. const DrawablePath::ValueTreeWrapper::Element e (pathTree.getChild(i));
  64661. const int numCps = e.getNumControlPoints();
  64662. for (int j = 0; j < numCps; ++j)
  64663. {
  64664. points[j] = e.getControlPoint (j);
  64665. containsDynamicPoints = containsDynamicPoints || points[j].isDynamic();
  64666. }
  64667. const Identifier type (e.getType());
  64668. if (type == DrawablePath::ValueTreeWrapper::Element::startSubPathElement)
  64669. elements.add (new StartSubPath (points[0]));
  64670. else if (type == DrawablePath::ValueTreeWrapper::Element::closeSubPathElement)
  64671. elements.add (new CloseSubPath());
  64672. else if (type == DrawablePath::ValueTreeWrapper::Element::lineToElement)
  64673. elements.add (new LineTo (points[0]));
  64674. else if (type == DrawablePath::ValueTreeWrapper::Element::quadraticToElement)
  64675. elements.add (new QuadraticTo (points[0], points[1]));
  64676. else if (type == DrawablePath::ValueTreeWrapper::Element::cubicToElement)
  64677. elements.add (new CubicTo (points[0], points[1], points[2]));
  64678. else
  64679. jassertfalse;
  64680. }
  64681. }
  64682. RelativePointPath::~RelativePointPath()
  64683. {
  64684. }
  64685. void RelativePointPath::swapWith (RelativePointPath& other) throw()
  64686. {
  64687. elements.swapWithArray (other.elements);
  64688. swapVariables (usesNonZeroWinding, other.usesNonZeroWinding);
  64689. }
  64690. void RelativePointPath::createPath (Path& path, Expression::EvaluationContext* coordFinder)
  64691. {
  64692. for (int i = 0; i < elements.size(); ++i)
  64693. elements.getUnchecked(i)->addToPath (path, coordFinder);
  64694. }
  64695. bool RelativePointPath::containsAnyDynamicPoints() const
  64696. {
  64697. return containsDynamicPoints;
  64698. }
  64699. RelativePointPath::ElementBase::ElementBase (const ElementType type_) : type (type_)
  64700. {
  64701. }
  64702. RelativePointPath::StartSubPath::StartSubPath (const RelativePoint& pos)
  64703. : ElementBase (startSubPathElement), startPos (pos)
  64704. {
  64705. }
  64706. const ValueTree RelativePointPath::StartSubPath::createTree() const
  64707. {
  64708. ValueTree v (DrawablePath::ValueTreeWrapper::Element::startSubPathElement);
  64709. v.setProperty (DrawablePath::ValueTreeWrapper::point1, startPos.toString(), 0);
  64710. return v;
  64711. }
  64712. void RelativePointPath::StartSubPath::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64713. {
  64714. path.startNewSubPath (startPos.resolve (coordFinder));
  64715. }
  64716. RelativePoint* RelativePointPath::StartSubPath::getControlPoints (int& numPoints)
  64717. {
  64718. numPoints = 1;
  64719. return &startPos;
  64720. }
  64721. RelativePointPath::CloseSubPath::CloseSubPath()
  64722. : ElementBase (closeSubPathElement)
  64723. {
  64724. }
  64725. const ValueTree RelativePointPath::CloseSubPath::createTree() const
  64726. {
  64727. return ValueTree (DrawablePath::ValueTreeWrapper::Element::closeSubPathElement);
  64728. }
  64729. void RelativePointPath::CloseSubPath::addToPath (Path& path, Expression::EvaluationContext*) const
  64730. {
  64731. path.closeSubPath();
  64732. }
  64733. RelativePoint* RelativePointPath::CloseSubPath::getControlPoints (int& numPoints)
  64734. {
  64735. numPoints = 0;
  64736. return 0;
  64737. }
  64738. RelativePointPath::LineTo::LineTo (const RelativePoint& endPoint_)
  64739. : ElementBase (lineToElement), endPoint (endPoint_)
  64740. {
  64741. }
  64742. const ValueTree RelativePointPath::LineTo::createTree() const
  64743. {
  64744. ValueTree v (DrawablePath::ValueTreeWrapper::Element::lineToElement);
  64745. v.setProperty (DrawablePath::ValueTreeWrapper::point1, endPoint.toString(), 0);
  64746. return v;
  64747. }
  64748. void RelativePointPath::LineTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64749. {
  64750. path.lineTo (endPoint.resolve (coordFinder));
  64751. }
  64752. RelativePoint* RelativePointPath::LineTo::getControlPoints (int& numPoints)
  64753. {
  64754. numPoints = 1;
  64755. return &endPoint;
  64756. }
  64757. RelativePointPath::QuadraticTo::QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint)
  64758. : ElementBase (quadraticToElement)
  64759. {
  64760. controlPoints[0] = controlPoint;
  64761. controlPoints[1] = endPoint;
  64762. }
  64763. const ValueTree RelativePointPath::QuadraticTo::createTree() const
  64764. {
  64765. ValueTree v (DrawablePath::ValueTreeWrapper::Element::quadraticToElement);
  64766. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64767. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64768. return v;
  64769. }
  64770. void RelativePointPath::QuadraticTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64771. {
  64772. path.quadraticTo (controlPoints[0].resolve (coordFinder),
  64773. controlPoints[1].resolve (coordFinder));
  64774. }
  64775. RelativePoint* RelativePointPath::QuadraticTo::getControlPoints (int& numPoints)
  64776. {
  64777. numPoints = 2;
  64778. return controlPoints;
  64779. }
  64780. RelativePointPath::CubicTo::CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint)
  64781. : ElementBase (cubicToElement)
  64782. {
  64783. controlPoints[0] = controlPoint1;
  64784. controlPoints[1] = controlPoint2;
  64785. controlPoints[2] = endPoint;
  64786. }
  64787. const ValueTree RelativePointPath::CubicTo::createTree() const
  64788. {
  64789. ValueTree v (DrawablePath::ValueTreeWrapper::Element::cubicToElement);
  64790. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64791. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64792. v.setProperty (DrawablePath::ValueTreeWrapper::point3, controlPoints[2].toString(), 0);
  64793. return v;
  64794. }
  64795. void RelativePointPath::CubicTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64796. {
  64797. path.cubicTo (controlPoints[0].resolve (coordFinder),
  64798. controlPoints[1].resolve (coordFinder),
  64799. controlPoints[2].resolve (coordFinder));
  64800. }
  64801. RelativePoint* RelativePointPath::CubicTo::getControlPoints (int& numPoints)
  64802. {
  64803. numPoints = 3;
  64804. return controlPoints;
  64805. }
  64806. RelativeParallelogram::RelativeParallelogram()
  64807. {
  64808. }
  64809. RelativeParallelogram::RelativeParallelogram (const RelativePoint& topLeft_, const RelativePoint& topRight_, const RelativePoint& bottomLeft_)
  64810. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64811. {
  64812. }
  64813. RelativeParallelogram::RelativeParallelogram (const String& topLeft_, const String& topRight_, const String& bottomLeft_)
  64814. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64815. {
  64816. }
  64817. RelativeParallelogram::~RelativeParallelogram()
  64818. {
  64819. }
  64820. void RelativeParallelogram::resolveThreePoints (Point<float>* points, Expression::EvaluationContext* const coordFinder) const
  64821. {
  64822. points[0] = topLeft.resolve (coordFinder);
  64823. points[1] = topRight.resolve (coordFinder);
  64824. points[2] = bottomLeft.resolve (coordFinder);
  64825. }
  64826. void RelativeParallelogram::resolveFourCorners (Point<float>* points, Expression::EvaluationContext* const coordFinder) const
  64827. {
  64828. resolveThreePoints (points, coordFinder);
  64829. points[3] = points[1] + (points[2] - points[0]);
  64830. }
  64831. const Rectangle<float> RelativeParallelogram::getBounds (Expression::EvaluationContext* const coordFinder) const
  64832. {
  64833. Point<float> points[4];
  64834. resolveFourCorners (points, coordFinder);
  64835. return Rectangle<float>::findAreaContainingPoints (points, 4);
  64836. }
  64837. void RelativeParallelogram::getPath (Path& path, Expression::EvaluationContext* const coordFinder) const
  64838. {
  64839. Point<float> points[4];
  64840. resolveFourCorners (points, coordFinder);
  64841. path.startNewSubPath (points[0]);
  64842. path.lineTo (points[1]);
  64843. path.lineTo (points[3]);
  64844. path.lineTo (points[2]);
  64845. path.closeSubPath();
  64846. }
  64847. const AffineTransform RelativeParallelogram::resetToPerpendicular (Expression::EvaluationContext* const coordFinder)
  64848. {
  64849. Point<float> corners[3];
  64850. resolveThreePoints (corners, coordFinder);
  64851. const Line<float> top (corners[0], corners[1]);
  64852. const Line<float> left (corners[0], corners[2]);
  64853. const Point<float> newTopRight (corners[0] + Point<float> (top.getLength(), 0.0f));
  64854. const Point<float> newBottomLeft (corners[0] + Point<float> (0.0f, left.getLength()));
  64855. topRight.moveToAbsolute (newTopRight, coordFinder);
  64856. bottomLeft.moveToAbsolute (newBottomLeft, coordFinder);
  64857. return AffineTransform::fromTargetPoints (corners[0].getX(), corners[0].getY(), corners[0].getX(), corners[0].getY(),
  64858. corners[1].getX(), corners[1].getY(), newTopRight.getX(), newTopRight.getY(),
  64859. corners[2].getX(), corners[2].getY(), newBottomLeft.getX(), newBottomLeft.getY());
  64860. }
  64861. bool RelativeParallelogram::operator== (const RelativeParallelogram& other) const throw()
  64862. {
  64863. return topLeft == other.topLeft && topRight == other.topRight && bottomLeft == other.bottomLeft;
  64864. }
  64865. bool RelativeParallelogram::operator!= (const RelativeParallelogram& other) const throw()
  64866. {
  64867. return ! operator== (other);
  64868. }
  64869. const Point<float> RelativeParallelogram::getInternalCoordForPoint (const Point<float>* const corners, Point<float> target) throw()
  64870. {
  64871. const Point<float> tr (corners[1] - corners[0]);
  64872. const Point<float> bl (corners[2] - corners[0]);
  64873. target -= corners[0];
  64874. return Point<float> (Line<float> (Point<float>(), tr).getIntersection (Line<float> (target, target - bl)).getDistanceFromOrigin(),
  64875. Line<float> (Point<float>(), bl).getIntersection (Line<float> (target, target - tr)).getDistanceFromOrigin());
  64876. }
  64877. const Point<float> RelativeParallelogram::getPointForInternalCoord (const Point<float>* const corners, const Point<float>& point) throw()
  64878. {
  64879. return corners[0]
  64880. + Line<float> (Point<float>(), corners[1] - corners[0]).getPointAlongLine (point.getX())
  64881. + Line<float> (Point<float>(), corners[2] - corners[0]).getPointAlongLine (point.getY());
  64882. }
  64883. END_JUCE_NAMESPACE
  64884. /*** End of inlined file: juce_RelativeCoordinate.cpp ***/
  64885. #endif
  64886. #if JUCE_BUILD_MISC // (put these in misc to balance the file sizes and avoid problems in iphone build)
  64887. /*** Start of inlined file: juce_Colour.cpp ***/
  64888. BEGIN_JUCE_NAMESPACE
  64889. namespace ColourHelpers
  64890. {
  64891. static uint8 floatAlphaToInt (const float alpha) throw()
  64892. {
  64893. return (uint8) jlimit (0, 0xff, roundToInt (alpha * 255.0f));
  64894. }
  64895. static void convertHSBtoRGB (float h, float s, float v,
  64896. uint8& r, uint8& g, uint8& b) throw()
  64897. {
  64898. v = jlimit (0.0f, 1.0f, v);
  64899. v *= 255.0f;
  64900. const uint8 intV = (uint8) roundToInt (v);
  64901. if (s <= 0)
  64902. {
  64903. r = intV;
  64904. g = intV;
  64905. b = intV;
  64906. }
  64907. else
  64908. {
  64909. s = jmin (1.0f, s);
  64910. h = jlimit (0.0f, 1.0f, h);
  64911. h = (h - std::floor (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  64912. const float f = h - std::floor (h);
  64913. const uint8 x = (uint8) roundToInt (v * (1.0f - s));
  64914. const float y = v * (1.0f - s * f);
  64915. const float z = v * (1.0f - (s * (1.0f - f)));
  64916. if (h < 1.0f)
  64917. {
  64918. r = intV;
  64919. g = (uint8) roundToInt (z);
  64920. b = x;
  64921. }
  64922. else if (h < 2.0f)
  64923. {
  64924. r = (uint8) roundToInt (y);
  64925. g = intV;
  64926. b = x;
  64927. }
  64928. else if (h < 3.0f)
  64929. {
  64930. r = x;
  64931. g = intV;
  64932. b = (uint8) roundToInt (z);
  64933. }
  64934. else if (h < 4.0f)
  64935. {
  64936. r = x;
  64937. g = (uint8) roundToInt (y);
  64938. b = intV;
  64939. }
  64940. else if (h < 5.0f)
  64941. {
  64942. r = (uint8) roundToInt (z);
  64943. g = x;
  64944. b = intV;
  64945. }
  64946. else if (h < 6.0f)
  64947. {
  64948. r = intV;
  64949. g = x;
  64950. b = (uint8) roundToInt (y);
  64951. }
  64952. else
  64953. {
  64954. r = 0;
  64955. g = 0;
  64956. b = 0;
  64957. }
  64958. }
  64959. }
  64960. }
  64961. Colour::Colour() throw()
  64962. : argb (0)
  64963. {
  64964. }
  64965. Colour::Colour (const Colour& other) throw()
  64966. : argb (other.argb)
  64967. {
  64968. }
  64969. Colour& Colour::operator= (const Colour& other) throw()
  64970. {
  64971. argb = other.argb;
  64972. return *this;
  64973. }
  64974. bool Colour::operator== (const Colour& other) const throw()
  64975. {
  64976. return argb.getARGB() == other.argb.getARGB();
  64977. }
  64978. bool Colour::operator!= (const Colour& other) const throw()
  64979. {
  64980. return argb.getARGB() != other.argb.getARGB();
  64981. }
  64982. Colour::Colour (const uint32 argb_) throw()
  64983. : argb (argb_)
  64984. {
  64985. }
  64986. Colour::Colour (const uint8 red,
  64987. const uint8 green,
  64988. const uint8 blue) throw()
  64989. {
  64990. argb.setARGB (0xff, red, green, blue);
  64991. }
  64992. const Colour Colour::fromRGB (const uint8 red,
  64993. const uint8 green,
  64994. const uint8 blue) throw()
  64995. {
  64996. return Colour (red, green, blue);
  64997. }
  64998. Colour::Colour (const uint8 red,
  64999. const uint8 green,
  65000. const uint8 blue,
  65001. const uint8 alpha) throw()
  65002. {
  65003. argb.setARGB (alpha, red, green, blue);
  65004. }
  65005. const Colour Colour::fromRGBA (const uint8 red,
  65006. const uint8 green,
  65007. const uint8 blue,
  65008. const uint8 alpha) throw()
  65009. {
  65010. return Colour (red, green, blue, alpha);
  65011. }
  65012. Colour::Colour (const uint8 red,
  65013. const uint8 green,
  65014. const uint8 blue,
  65015. const float alpha) throw()
  65016. {
  65017. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), red, green, blue);
  65018. }
  65019. const Colour Colour::fromRGBAFloat (const uint8 red,
  65020. const uint8 green,
  65021. const uint8 blue,
  65022. const float alpha) throw()
  65023. {
  65024. return Colour (red, green, blue, alpha);
  65025. }
  65026. Colour::Colour (const float hue,
  65027. const float saturation,
  65028. const float brightness,
  65029. const float alpha) throw()
  65030. {
  65031. uint8 r = getRed(), g = getGreen(), b = getBlue();
  65032. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  65033. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), r, g, b);
  65034. }
  65035. const Colour Colour::fromHSV (const float hue,
  65036. const float saturation,
  65037. const float brightness,
  65038. const float alpha) throw()
  65039. {
  65040. return Colour (hue, saturation, brightness, alpha);
  65041. }
  65042. Colour::Colour (const float hue,
  65043. const float saturation,
  65044. const float brightness,
  65045. const uint8 alpha) throw()
  65046. {
  65047. uint8 r = getRed(), g = getGreen(), b = getBlue();
  65048. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  65049. argb.setARGB (alpha, r, g, b);
  65050. }
  65051. Colour::~Colour() throw()
  65052. {
  65053. }
  65054. const PixelARGB Colour::getPixelARGB() const throw()
  65055. {
  65056. PixelARGB p (argb);
  65057. p.premultiply();
  65058. return p;
  65059. }
  65060. uint32 Colour::getARGB() const throw()
  65061. {
  65062. return argb.getARGB();
  65063. }
  65064. bool Colour::isTransparent() const throw()
  65065. {
  65066. return getAlpha() == 0;
  65067. }
  65068. bool Colour::isOpaque() const throw()
  65069. {
  65070. return getAlpha() == 0xff;
  65071. }
  65072. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  65073. {
  65074. PixelARGB newCol (argb);
  65075. newCol.setAlpha (newAlpha);
  65076. return Colour (newCol.getARGB());
  65077. }
  65078. const Colour Colour::withAlpha (const float newAlpha) const throw()
  65079. {
  65080. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  65081. PixelARGB newCol (argb);
  65082. newCol.setAlpha (ColourHelpers::floatAlphaToInt (newAlpha));
  65083. return Colour (newCol.getARGB());
  65084. }
  65085. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  65086. {
  65087. jassert (alphaMultiplier >= 0);
  65088. PixelARGB newCol (argb);
  65089. newCol.setAlpha ((uint8) jmin (0xff, roundToInt (alphaMultiplier * newCol.getAlpha())));
  65090. return Colour (newCol.getARGB());
  65091. }
  65092. const Colour Colour::overlaidWith (const Colour& src) const throw()
  65093. {
  65094. const int destAlpha = getAlpha();
  65095. if (destAlpha > 0)
  65096. {
  65097. const int invA = 0xff - (int) src.getAlpha();
  65098. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  65099. if (resA > 0)
  65100. {
  65101. const int da = (invA * destAlpha) / resA;
  65102. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  65103. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  65104. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  65105. (uint8) resA);
  65106. }
  65107. return *this;
  65108. }
  65109. else
  65110. {
  65111. return src;
  65112. }
  65113. }
  65114. const Colour Colour::interpolatedWith (const Colour& other, float proportionOfOther) const throw()
  65115. {
  65116. if (proportionOfOther <= 0)
  65117. return *this;
  65118. if (proportionOfOther >= 1.0f)
  65119. return other;
  65120. PixelARGB c1 (getPixelARGB());
  65121. const PixelARGB c2 (other.getPixelARGB());
  65122. c1.tween (c2, roundToInt (proportionOfOther * 255.0f));
  65123. c1.unpremultiply();
  65124. return Colour (c1.getARGB());
  65125. }
  65126. float Colour::getFloatRed() const throw()
  65127. {
  65128. return getRed() / 255.0f;
  65129. }
  65130. float Colour::getFloatGreen() const throw()
  65131. {
  65132. return getGreen() / 255.0f;
  65133. }
  65134. float Colour::getFloatBlue() const throw()
  65135. {
  65136. return getBlue() / 255.0f;
  65137. }
  65138. float Colour::getFloatAlpha() const throw()
  65139. {
  65140. return getAlpha() / 255.0f;
  65141. }
  65142. void Colour::getHSB (float& h, float& s, float& v) const throw()
  65143. {
  65144. const int r = getRed();
  65145. const int g = getGreen();
  65146. const int b = getBlue();
  65147. const int hi = jmax (r, g, b);
  65148. const int lo = jmin (r, g, b);
  65149. if (hi != 0)
  65150. {
  65151. s = (hi - lo) / (float) hi;
  65152. if (s != 0)
  65153. {
  65154. const float invDiff = 1.0f / (hi - lo);
  65155. const float red = (hi - r) * invDiff;
  65156. const float green = (hi - g) * invDiff;
  65157. const float blue = (hi - b) * invDiff;
  65158. if (r == hi)
  65159. h = blue - green;
  65160. else if (g == hi)
  65161. h = 2.0f + red - blue;
  65162. else
  65163. h = 4.0f + green - red;
  65164. h *= 1.0f / 6.0f;
  65165. if (h < 0)
  65166. ++h;
  65167. }
  65168. else
  65169. {
  65170. h = 0;
  65171. }
  65172. }
  65173. else
  65174. {
  65175. s = 0;
  65176. h = 0;
  65177. }
  65178. v = hi / 255.0f;
  65179. }
  65180. float Colour::getHue() const throw()
  65181. {
  65182. float h, s, b;
  65183. getHSB (h, s, b);
  65184. return h;
  65185. }
  65186. const Colour Colour::withHue (const float hue) const throw()
  65187. {
  65188. float h, s, b;
  65189. getHSB (h, s, b);
  65190. return Colour (hue, s, b, getAlpha());
  65191. }
  65192. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  65193. {
  65194. float h, s, b;
  65195. getHSB (h, s, b);
  65196. h += amountToRotate;
  65197. h -= std::floor (h);
  65198. return Colour (h, s, b, getAlpha());
  65199. }
  65200. float Colour::getSaturation() const throw()
  65201. {
  65202. float h, s, b;
  65203. getHSB (h, s, b);
  65204. return s;
  65205. }
  65206. const Colour Colour::withSaturation (const float saturation) const throw()
  65207. {
  65208. float h, s, b;
  65209. getHSB (h, s, b);
  65210. return Colour (h, saturation, b, getAlpha());
  65211. }
  65212. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  65213. {
  65214. float h, s, b;
  65215. getHSB (h, s, b);
  65216. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  65217. }
  65218. float Colour::getBrightness() const throw()
  65219. {
  65220. float h, s, b;
  65221. getHSB (h, s, b);
  65222. return b;
  65223. }
  65224. const Colour Colour::withBrightness (const float brightness) const throw()
  65225. {
  65226. float h, s, b;
  65227. getHSB (h, s, b);
  65228. return Colour (h, s, brightness, getAlpha());
  65229. }
  65230. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  65231. {
  65232. float h, s, b;
  65233. getHSB (h, s, b);
  65234. b *= amount;
  65235. if (b > 1.0f)
  65236. b = 1.0f;
  65237. return Colour (h, s, b, getAlpha());
  65238. }
  65239. const Colour Colour::brighter (float amount) const throw()
  65240. {
  65241. amount = 1.0f / (1.0f + amount);
  65242. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  65243. (uint8) (255 - (amount * (255 - getGreen()))),
  65244. (uint8) (255 - (amount * (255 - getBlue()))),
  65245. getAlpha());
  65246. }
  65247. const Colour Colour::darker (float amount) const throw()
  65248. {
  65249. amount = 1.0f / (1.0f + amount);
  65250. return Colour ((uint8) (amount * getRed()),
  65251. (uint8) (amount * getGreen()),
  65252. (uint8) (amount * getBlue()),
  65253. getAlpha());
  65254. }
  65255. const Colour Colour::greyLevel (const float brightness) throw()
  65256. {
  65257. const uint8 level
  65258. = (uint8) jlimit (0x00, 0xff, roundToInt (brightness * 255.0f));
  65259. return Colour (level, level, level);
  65260. }
  65261. const Colour Colour::contrasting (const float amount) const throw()
  65262. {
  65263. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  65264. ? Colours::black
  65265. : Colours::white).withAlpha (amount));
  65266. }
  65267. const Colour Colour::contrasting (const Colour& colour1,
  65268. const Colour& colour2) throw()
  65269. {
  65270. const float b1 = colour1.getBrightness();
  65271. const float b2 = colour2.getBrightness();
  65272. float best = 0.0f;
  65273. float bestDist = 0.0f;
  65274. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  65275. {
  65276. const float d1 = std::abs (i - b1);
  65277. const float d2 = std::abs (i - b2);
  65278. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  65279. if (dist > bestDist)
  65280. {
  65281. best = i;
  65282. bestDist = dist;
  65283. }
  65284. }
  65285. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  65286. .withBrightness (best);
  65287. }
  65288. const String Colour::toString() const
  65289. {
  65290. return String::toHexString ((int) argb.getARGB());
  65291. }
  65292. const Colour Colour::fromString (const String& encodedColourString)
  65293. {
  65294. return Colour ((uint32) encodedColourString.getHexValue32());
  65295. }
  65296. const String Colour::toDisplayString (const bool includeAlphaValue) const
  65297. {
  65298. return String::toHexString ((int) (argb.getARGB() & (includeAlphaValue ? 0xffffffff : 0xffffff)))
  65299. .paddedLeft ('0', includeAlphaValue ? 8 : 6)
  65300. .toUpperCase();
  65301. }
  65302. END_JUCE_NAMESPACE
  65303. /*** End of inlined file: juce_Colour.cpp ***/
  65304. /*** Start of inlined file: juce_ColourGradient.cpp ***/
  65305. BEGIN_JUCE_NAMESPACE
  65306. ColourGradient::ColourGradient() throw()
  65307. {
  65308. #if JUCE_DEBUG
  65309. point1.setX (987654.0f);
  65310. #endif
  65311. }
  65312. ColourGradient::ColourGradient (const Colour& colour1, const float x1_, const float y1_,
  65313. const Colour& colour2, const float x2_, const float y2_,
  65314. const bool isRadial_)
  65315. : point1 (x1_, y1_),
  65316. point2 (x2_, y2_),
  65317. isRadial (isRadial_)
  65318. {
  65319. colours.add (ColourPoint (0.0, colour1));
  65320. colours.add (ColourPoint (1.0, colour2));
  65321. }
  65322. ColourGradient::~ColourGradient()
  65323. {
  65324. }
  65325. bool ColourGradient::operator== (const ColourGradient& other) const throw()
  65326. {
  65327. return point1 == other.point1 && point2 == other.point2
  65328. && isRadial == other.isRadial
  65329. && colours == other.colours;
  65330. }
  65331. bool ColourGradient::operator!= (const ColourGradient& other) const throw()
  65332. {
  65333. return ! operator== (other);
  65334. }
  65335. void ColourGradient::clearColours()
  65336. {
  65337. colours.clear();
  65338. }
  65339. int ColourGradient::addColour (const double proportionAlongGradient, const Colour& colour)
  65340. {
  65341. // must be within the two end-points
  65342. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  65343. const double pos = jlimit (0.0, 1.0, proportionAlongGradient);
  65344. int i;
  65345. for (i = 0; i < colours.size(); ++i)
  65346. if (colours.getReference(i).position > pos)
  65347. break;
  65348. colours.insert (i, ColourPoint (pos, colour));
  65349. return i;
  65350. }
  65351. void ColourGradient::removeColour (int index)
  65352. {
  65353. jassert (index > 0 && index < colours.size() - 1);
  65354. colours.remove (index);
  65355. }
  65356. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  65357. {
  65358. for (int i = 0; i < colours.size(); ++i)
  65359. {
  65360. Colour& c = colours.getReference(i).colour;
  65361. c = c.withMultipliedAlpha (multiplier);
  65362. }
  65363. }
  65364. int ColourGradient::getNumColours() const throw()
  65365. {
  65366. return colours.size();
  65367. }
  65368. double ColourGradient::getColourPosition (const int index) const throw()
  65369. {
  65370. if (((unsigned int) index) < (unsigned int) colours.size())
  65371. return colours.getReference (index).position;
  65372. return 0;
  65373. }
  65374. const Colour ColourGradient::getColour (const int index) const throw()
  65375. {
  65376. if (((unsigned int) index) < (unsigned int) colours.size())
  65377. return colours.getReference (index).colour;
  65378. return Colour();
  65379. }
  65380. void ColourGradient::setColour (int index, const Colour& newColour) throw()
  65381. {
  65382. if (((unsigned int) index) < (unsigned int) colours.size())
  65383. colours.getReference (index).colour = newColour;
  65384. }
  65385. const Colour ColourGradient::getColourAtPosition (const double position) const throw()
  65386. {
  65387. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65388. if (position <= 0 || colours.size() <= 1)
  65389. return colours.getReference(0).colour;
  65390. int i = colours.size() - 1;
  65391. while (position < colours.getReference(i).position)
  65392. --i;
  65393. const ColourPoint& p1 = colours.getReference (i);
  65394. if (i >= colours.size() - 1)
  65395. return p1.colour;
  65396. const ColourPoint& p2 = colours.getReference (i + 1);
  65397. return p1.colour.interpolatedWith (p2.colour, (float) ((position - p1.position) / (p2.position - p1.position)));
  65398. }
  65399. int ColourGradient::createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& lookupTable) const
  65400. {
  65401. #if JUCE_DEBUG
  65402. // trying to use the object without setting its co-ordinates? Have a careful read of
  65403. // the comments for the constructors.
  65404. jassert (point1.getX() != 987654.0f);
  65405. #endif
  65406. const int numEntries = jlimit (1, jmax (1, (colours.size() - 1) << 8),
  65407. 3 * (int) point1.transformedBy (transform)
  65408. .getDistanceFrom (point2.transformedBy (transform)));
  65409. lookupTable.malloc (numEntries);
  65410. if (colours.size() >= 2)
  65411. {
  65412. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65413. PixelARGB pix1 (colours.getReference (0).colour.getPixelARGB());
  65414. int index = 0;
  65415. for (int j = 1; j < colours.size(); ++j)
  65416. {
  65417. const ColourPoint& p = colours.getReference (j);
  65418. const int numToDo = roundToInt (p.position * (numEntries - 1)) - index;
  65419. const PixelARGB pix2 (p.colour.getPixelARGB());
  65420. for (int i = 0; i < numToDo; ++i)
  65421. {
  65422. jassert (index >= 0 && index < numEntries);
  65423. lookupTable[index] = pix1;
  65424. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  65425. ++index;
  65426. }
  65427. pix1 = pix2;
  65428. }
  65429. while (index < numEntries)
  65430. lookupTable [index++] = pix1;
  65431. }
  65432. else
  65433. {
  65434. jassertfalse; // no colours specified!
  65435. }
  65436. return numEntries;
  65437. }
  65438. bool ColourGradient::isOpaque() const throw()
  65439. {
  65440. for (int i = 0; i < colours.size(); ++i)
  65441. if (! colours.getReference(i).colour.isOpaque())
  65442. return false;
  65443. return true;
  65444. }
  65445. bool ColourGradient::isInvisible() const throw()
  65446. {
  65447. for (int i = 0; i < colours.size(); ++i)
  65448. if (! colours.getReference(i).colour.isTransparent())
  65449. return false;
  65450. return true;
  65451. }
  65452. END_JUCE_NAMESPACE
  65453. /*** End of inlined file: juce_ColourGradient.cpp ***/
  65454. /*** Start of inlined file: juce_Colours.cpp ***/
  65455. BEGIN_JUCE_NAMESPACE
  65456. const Colour Colours::transparentBlack (0);
  65457. const Colour Colours::transparentWhite (0x00ffffff);
  65458. const Colour Colours::aliceblue (0xfff0f8ff);
  65459. const Colour Colours::antiquewhite (0xfffaebd7);
  65460. const Colour Colours::aqua (0xff00ffff);
  65461. const Colour Colours::aquamarine (0xff7fffd4);
  65462. const Colour Colours::azure (0xfff0ffff);
  65463. const Colour Colours::beige (0xfff5f5dc);
  65464. const Colour Colours::bisque (0xffffe4c4);
  65465. const Colour Colours::black (0xff000000);
  65466. const Colour Colours::blanchedalmond (0xffffebcd);
  65467. const Colour Colours::blue (0xff0000ff);
  65468. const Colour Colours::blueviolet (0xff8a2be2);
  65469. const Colour Colours::brown (0xffa52a2a);
  65470. const Colour Colours::burlywood (0xffdeb887);
  65471. const Colour Colours::cadetblue (0xff5f9ea0);
  65472. const Colour Colours::chartreuse (0xff7fff00);
  65473. const Colour Colours::chocolate (0xffd2691e);
  65474. const Colour Colours::coral (0xffff7f50);
  65475. const Colour Colours::cornflowerblue (0xff6495ed);
  65476. const Colour Colours::cornsilk (0xfffff8dc);
  65477. const Colour Colours::crimson (0xffdc143c);
  65478. const Colour Colours::cyan (0xff00ffff);
  65479. const Colour Colours::darkblue (0xff00008b);
  65480. const Colour Colours::darkcyan (0xff008b8b);
  65481. const Colour Colours::darkgoldenrod (0xffb8860b);
  65482. const Colour Colours::darkgrey (0xff555555);
  65483. const Colour Colours::darkgreen (0xff006400);
  65484. const Colour Colours::darkkhaki (0xffbdb76b);
  65485. const Colour Colours::darkmagenta (0xff8b008b);
  65486. const Colour Colours::darkolivegreen (0xff556b2f);
  65487. const Colour Colours::darkorange (0xffff8c00);
  65488. const Colour Colours::darkorchid (0xff9932cc);
  65489. const Colour Colours::darkred (0xff8b0000);
  65490. const Colour Colours::darksalmon (0xffe9967a);
  65491. const Colour Colours::darkseagreen (0xff8fbc8f);
  65492. const Colour Colours::darkslateblue (0xff483d8b);
  65493. const Colour Colours::darkslategrey (0xff2f4f4f);
  65494. const Colour Colours::darkturquoise (0xff00ced1);
  65495. const Colour Colours::darkviolet (0xff9400d3);
  65496. const Colour Colours::deeppink (0xffff1493);
  65497. const Colour Colours::deepskyblue (0xff00bfff);
  65498. const Colour Colours::dimgrey (0xff696969);
  65499. const Colour Colours::dodgerblue (0xff1e90ff);
  65500. const Colour Colours::firebrick (0xffb22222);
  65501. const Colour Colours::floralwhite (0xfffffaf0);
  65502. const Colour Colours::forestgreen (0xff228b22);
  65503. const Colour Colours::fuchsia (0xffff00ff);
  65504. const Colour Colours::gainsboro (0xffdcdcdc);
  65505. const Colour Colours::gold (0xffffd700);
  65506. const Colour Colours::goldenrod (0xffdaa520);
  65507. const Colour Colours::grey (0xff808080);
  65508. const Colour Colours::green (0xff008000);
  65509. const Colour Colours::greenyellow (0xffadff2f);
  65510. const Colour Colours::honeydew (0xfff0fff0);
  65511. const Colour Colours::hotpink (0xffff69b4);
  65512. const Colour Colours::indianred (0xffcd5c5c);
  65513. const Colour Colours::indigo (0xff4b0082);
  65514. const Colour Colours::ivory (0xfffffff0);
  65515. const Colour Colours::khaki (0xfff0e68c);
  65516. const Colour Colours::lavender (0xffe6e6fa);
  65517. const Colour Colours::lavenderblush (0xfffff0f5);
  65518. const Colour Colours::lemonchiffon (0xfffffacd);
  65519. const Colour Colours::lightblue (0xffadd8e6);
  65520. const Colour Colours::lightcoral (0xfff08080);
  65521. const Colour Colours::lightcyan (0xffe0ffff);
  65522. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  65523. const Colour Colours::lightgreen (0xff90ee90);
  65524. const Colour Colours::lightgrey (0xffd3d3d3);
  65525. const Colour Colours::lightpink (0xffffb6c1);
  65526. const Colour Colours::lightsalmon (0xffffa07a);
  65527. const Colour Colours::lightseagreen (0xff20b2aa);
  65528. const Colour Colours::lightskyblue (0xff87cefa);
  65529. const Colour Colours::lightslategrey (0xff778899);
  65530. const Colour Colours::lightsteelblue (0xffb0c4de);
  65531. const Colour Colours::lightyellow (0xffffffe0);
  65532. const Colour Colours::lime (0xff00ff00);
  65533. const Colour Colours::limegreen (0xff32cd32);
  65534. const Colour Colours::linen (0xfffaf0e6);
  65535. const Colour Colours::magenta (0xffff00ff);
  65536. const Colour Colours::maroon (0xff800000);
  65537. const Colour Colours::mediumaquamarine (0xff66cdaa);
  65538. const Colour Colours::mediumblue (0xff0000cd);
  65539. const Colour Colours::mediumorchid (0xffba55d3);
  65540. const Colour Colours::mediumpurple (0xff9370db);
  65541. const Colour Colours::mediumseagreen (0xff3cb371);
  65542. const Colour Colours::mediumslateblue (0xff7b68ee);
  65543. const Colour Colours::mediumspringgreen (0xff00fa9a);
  65544. const Colour Colours::mediumturquoise (0xff48d1cc);
  65545. const Colour Colours::mediumvioletred (0xffc71585);
  65546. const Colour Colours::midnightblue (0xff191970);
  65547. const Colour Colours::mintcream (0xfff5fffa);
  65548. const Colour Colours::mistyrose (0xffffe4e1);
  65549. const Colour Colours::navajowhite (0xffffdead);
  65550. const Colour Colours::navy (0xff000080);
  65551. const Colour Colours::oldlace (0xfffdf5e6);
  65552. const Colour Colours::olive (0xff808000);
  65553. const Colour Colours::olivedrab (0xff6b8e23);
  65554. const Colour Colours::orange (0xffffa500);
  65555. const Colour Colours::orangered (0xffff4500);
  65556. const Colour Colours::orchid (0xffda70d6);
  65557. const Colour Colours::palegoldenrod (0xffeee8aa);
  65558. const Colour Colours::palegreen (0xff98fb98);
  65559. const Colour Colours::paleturquoise (0xffafeeee);
  65560. const Colour Colours::palevioletred (0xffdb7093);
  65561. const Colour Colours::papayawhip (0xffffefd5);
  65562. const Colour Colours::peachpuff (0xffffdab9);
  65563. const Colour Colours::peru (0xffcd853f);
  65564. const Colour Colours::pink (0xffffc0cb);
  65565. const Colour Colours::plum (0xffdda0dd);
  65566. const Colour Colours::powderblue (0xffb0e0e6);
  65567. const Colour Colours::purple (0xff800080);
  65568. const Colour Colours::red (0xffff0000);
  65569. const Colour Colours::rosybrown (0xffbc8f8f);
  65570. const Colour Colours::royalblue (0xff4169e1);
  65571. const Colour Colours::saddlebrown (0xff8b4513);
  65572. const Colour Colours::salmon (0xfffa8072);
  65573. const Colour Colours::sandybrown (0xfff4a460);
  65574. const Colour Colours::seagreen (0xff2e8b57);
  65575. const Colour Colours::seashell (0xfffff5ee);
  65576. const Colour Colours::sienna (0xffa0522d);
  65577. const Colour Colours::silver (0xffc0c0c0);
  65578. const Colour Colours::skyblue (0xff87ceeb);
  65579. const Colour Colours::slateblue (0xff6a5acd);
  65580. const Colour Colours::slategrey (0xff708090);
  65581. const Colour Colours::snow (0xfffffafa);
  65582. const Colour Colours::springgreen (0xff00ff7f);
  65583. const Colour Colours::steelblue (0xff4682b4);
  65584. const Colour Colours::tan (0xffd2b48c);
  65585. const Colour Colours::teal (0xff008080);
  65586. const Colour Colours::thistle (0xffd8bfd8);
  65587. const Colour Colours::tomato (0xffff6347);
  65588. const Colour Colours::turquoise (0xff40e0d0);
  65589. const Colour Colours::violet (0xffee82ee);
  65590. const Colour Colours::wheat (0xfff5deb3);
  65591. const Colour Colours::white (0xffffffff);
  65592. const Colour Colours::whitesmoke (0xfff5f5f5);
  65593. const Colour Colours::yellow (0xffffff00);
  65594. const Colour Colours::yellowgreen (0xff9acd32);
  65595. const Colour Colours::findColourForName (const String& colourName,
  65596. const Colour& defaultColour)
  65597. {
  65598. static const int presets[] =
  65599. {
  65600. // (first value is the string's hashcode, second is ARGB)
  65601. 0x05978fff, 0xff000000, /* black */
  65602. 0x06bdcc29, 0xffffffff, /* white */
  65603. 0x002e305a, 0xff0000ff, /* blue */
  65604. 0x00308adf, 0xff808080, /* grey */
  65605. 0x05e0cf03, 0xff008000, /* green */
  65606. 0x0001b891, 0xffff0000, /* red */
  65607. 0xd43c6474, 0xffffff00, /* yellow */
  65608. 0x620886da, 0xfff0f8ff, /* aliceblue */
  65609. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  65610. 0x002dcebc, 0xff00ffff, /* aqua */
  65611. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  65612. 0x0590228f, 0xfff0ffff, /* azure */
  65613. 0x05947fe4, 0xfff5f5dc, /* beige */
  65614. 0xad388e35, 0xffffe4c4, /* bisque */
  65615. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  65616. 0x39129959, 0xff8a2be2, /* blueviolet */
  65617. 0x059a8136, 0xffa52a2a, /* brown */
  65618. 0x89cea8f9, 0xffdeb887, /* burlywood */
  65619. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  65620. 0x6b748956, 0xff7fff00, /* chartreuse */
  65621. 0x2903623c, 0xffd2691e, /* chocolate */
  65622. 0x05a74431, 0xffff7f50, /* coral */
  65623. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  65624. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  65625. 0x3d8c4edf, 0xffdc143c, /* crimson */
  65626. 0x002ed323, 0xff00ffff, /* cyan */
  65627. 0x67cc74d0, 0xff00008b, /* darkblue */
  65628. 0x67cd1799, 0xff008b8b, /* darkcyan */
  65629. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  65630. 0x67cecf55, 0xff555555, /* darkgrey */
  65631. 0x920b194d, 0xff006400, /* darkgreen */
  65632. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  65633. 0x5c293873, 0xff8b008b, /* darkmagenta */
  65634. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  65635. 0xbcfd2524, 0xffff8c00, /* darkorange */
  65636. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  65637. 0x55ee0d5b, 0xff8b0000, /* darkred */
  65638. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  65639. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  65640. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  65641. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  65642. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  65643. 0xc8769375, 0xff9400d3, /* darkviolet */
  65644. 0x25832862, 0xffff1493, /* deeppink */
  65645. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  65646. 0x634c8b67, 0xff696969, /* dimgrey */
  65647. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  65648. 0xef19e3cb, 0xffb22222, /* firebrick */
  65649. 0xb852b195, 0xfffffaf0, /* floralwhite */
  65650. 0xd086fd06, 0xff228b22, /* forestgreen */
  65651. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  65652. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  65653. 0x00308060, 0xffffd700, /* gold */
  65654. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  65655. 0xbab8a537, 0xffadff2f, /* greenyellow */
  65656. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  65657. 0x41892743, 0xffff69b4, /* hotpink */
  65658. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  65659. 0xb969fed2, 0xff4b0082, /* indigo */
  65660. 0x05fef6a9, 0xfffffff0, /* ivory */
  65661. 0x06149302, 0xfff0e68c, /* khaki */
  65662. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  65663. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  65664. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  65665. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  65666. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  65667. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  65668. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  65669. 0xf40157ad, 0xff90ee90, /* lightgreen */
  65670. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  65671. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  65672. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  65673. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  65674. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  65675. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  65676. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  65677. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  65678. 0x0032afd5, 0xff00ff00, /* lime */
  65679. 0x607bbc4e, 0xff32cd32, /* limegreen */
  65680. 0x06234efa, 0xfffaf0e6, /* linen */
  65681. 0x316858a9, 0xffff00ff, /* magenta */
  65682. 0xbf8ca470, 0xff800000, /* maroon */
  65683. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  65684. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  65685. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  65686. 0x07556b71, 0xff9370db, /* mediumpurple */
  65687. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  65688. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  65689. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  65690. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  65691. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  65692. 0x168eb32a, 0xff191970, /* midnightblue */
  65693. 0x4306b960, 0xfff5fffa, /* mintcream */
  65694. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  65695. 0xe97218a6, 0xffffdead, /* navajowhite */
  65696. 0x00337bb6, 0xff000080, /* navy */
  65697. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  65698. 0x064ee1db, 0xff808000, /* olive */
  65699. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  65700. 0xc3de262e, 0xffffa500, /* orange */
  65701. 0x58bebba3, 0xffff4500, /* orangered */
  65702. 0xc3def8a3, 0xffda70d6, /* orchid */
  65703. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  65704. 0x3d9dd619, 0xff98fb98, /* palegreen */
  65705. 0x74022737, 0xffafeeee, /* paleturquoise */
  65706. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  65707. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  65708. 0x93e1b776, 0xffffdab9, /* peachpuff */
  65709. 0x003472f8, 0xffcd853f, /* peru */
  65710. 0x00348176, 0xffffc0cb, /* pink */
  65711. 0x00348d94, 0xffdda0dd, /* plum */
  65712. 0xd036be93, 0xffb0e0e6, /* powderblue */
  65713. 0xc5c507bc, 0xff800080, /* purple */
  65714. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  65715. 0xbd9413e1, 0xff4169e1, /* royalblue */
  65716. 0xf456044f, 0xff8b4513, /* saddlebrown */
  65717. 0xc9c6f66e, 0xfffa8072, /* salmon */
  65718. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  65719. 0x34636c14, 0xff2e8b57, /* seagreen */
  65720. 0x3507fb41, 0xfffff5ee, /* seashell */
  65721. 0xca348772, 0xffa0522d, /* sienna */
  65722. 0xca37d30d, 0xffc0c0c0, /* silver */
  65723. 0x80da74fb, 0xff87ceeb, /* skyblue */
  65724. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  65725. 0x44ab37f8, 0xff708090, /* slategrey */
  65726. 0x0035f183, 0xfffffafa, /* snow */
  65727. 0xd5440d16, 0xff00ff7f, /* springgreen */
  65728. 0x3e1524a5, 0xff4682b4, /* steelblue */
  65729. 0x0001bfa1, 0xffd2b48c, /* tan */
  65730. 0x0036425c, 0xff008080, /* teal */
  65731. 0xafc8858f, 0xffd8bfd8, /* thistle */
  65732. 0xcc41600a, 0xffff6347, /* tomato */
  65733. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  65734. 0xcf57947f, 0xffee82ee, /* violet */
  65735. 0x06bdbae7, 0xfff5deb3, /* wheat */
  65736. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  65737. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  65738. };
  65739. const int hash = colourName.trim().toLowerCase().hashCode();
  65740. for (int i = 0; i < numElementsInArray (presets); i += 2)
  65741. if (presets [i] == hash)
  65742. return Colour (presets [i + 1]);
  65743. return defaultColour;
  65744. }
  65745. END_JUCE_NAMESPACE
  65746. /*** End of inlined file: juce_Colours.cpp ***/
  65747. /*** Start of inlined file: juce_EdgeTable.cpp ***/
  65748. BEGIN_JUCE_NAMESPACE
  65749. const int juce_edgeTableDefaultEdgesPerLine = 32;
  65750. EdgeTable::EdgeTable (const Rectangle<int>& bounds_,
  65751. const Path& path, const AffineTransform& transform)
  65752. : bounds (bounds_),
  65753. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65754. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65755. needToCheckEmptinesss (true)
  65756. {
  65757. table.malloc ((bounds.getHeight() + 1) * lineStrideElements);
  65758. int* t = table;
  65759. for (int i = bounds.getHeight(); --i >= 0;)
  65760. {
  65761. *t = 0;
  65762. t += lineStrideElements;
  65763. }
  65764. const int topLimit = bounds.getY() << 8;
  65765. const int heightLimit = bounds.getHeight() << 8;
  65766. const int leftLimit = bounds.getX() << 8;
  65767. const int rightLimit = bounds.getRight() << 8;
  65768. PathFlatteningIterator iter (path, transform);
  65769. while (iter.next())
  65770. {
  65771. int y1 = roundToInt (iter.y1 * 256.0f);
  65772. int y2 = roundToInt (iter.y2 * 256.0f);
  65773. if (y1 != y2)
  65774. {
  65775. y1 -= topLimit;
  65776. y2 -= topLimit;
  65777. const int startY = y1;
  65778. int direction = -1;
  65779. if (y1 > y2)
  65780. {
  65781. swapVariables (y1, y2);
  65782. direction = 1;
  65783. }
  65784. if (y1 < 0)
  65785. y1 = 0;
  65786. if (y2 > heightLimit)
  65787. y2 = heightLimit;
  65788. if (y1 < y2)
  65789. {
  65790. const double startX = 256.0f * iter.x1;
  65791. const double multiplier = (iter.x2 - iter.x1) / (iter.y2 - iter.y1);
  65792. const int stepSize = jlimit (1, 256, 256 / (1 + (int) std::abs (multiplier)));
  65793. do
  65794. {
  65795. const int step = jmin (stepSize, y2 - y1, 256 - (y1 & 255));
  65796. int x = roundToInt (startX + multiplier * ((y1 + (step >> 1)) - startY));
  65797. if (x < leftLimit)
  65798. x = leftLimit;
  65799. else if (x >= rightLimit)
  65800. x = rightLimit - 1;
  65801. addEdgePoint (x, y1 >> 8, direction * step);
  65802. y1 += step;
  65803. }
  65804. while (y1 < y2);
  65805. }
  65806. }
  65807. }
  65808. sanitiseLevels (path.isUsingNonZeroWinding());
  65809. }
  65810. EdgeTable::EdgeTable (const Rectangle<int>& rectangleToAdd)
  65811. : bounds (rectangleToAdd),
  65812. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65813. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65814. needToCheckEmptinesss (true)
  65815. {
  65816. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65817. table[0] = 0;
  65818. const int x1 = rectangleToAdd.getX() << 8;
  65819. const int x2 = rectangleToAdd.getRight() << 8;
  65820. int* t = table;
  65821. for (int i = rectangleToAdd.getHeight(); --i >= 0;)
  65822. {
  65823. t[0] = 2;
  65824. t[1] = x1;
  65825. t[2] = 255;
  65826. t[3] = x2;
  65827. t[4] = 0;
  65828. t += lineStrideElements;
  65829. }
  65830. }
  65831. EdgeTable::EdgeTable (const RectangleList& rectanglesToAdd)
  65832. : bounds (rectanglesToAdd.getBounds()),
  65833. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65834. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65835. needToCheckEmptinesss (true)
  65836. {
  65837. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65838. int* t = table;
  65839. for (int i = bounds.getHeight(); --i >= 0;)
  65840. {
  65841. *t = 0;
  65842. t += lineStrideElements;
  65843. }
  65844. for (RectangleList::Iterator iter (rectanglesToAdd); iter.next();)
  65845. {
  65846. const Rectangle<int>* const r = iter.getRectangle();
  65847. const int x1 = r->getX() << 8;
  65848. const int x2 = r->getRight() << 8;
  65849. int y = r->getY() - bounds.getY();
  65850. for (int j = r->getHeight(); --j >= 0;)
  65851. {
  65852. addEdgePoint (x1, y, 255);
  65853. addEdgePoint (x2, y, -255);
  65854. ++y;
  65855. }
  65856. }
  65857. sanitiseLevels (true);
  65858. }
  65859. EdgeTable::EdgeTable (const Rectangle<float>& rectangleToAdd)
  65860. : bounds (Rectangle<int> ((int) std::floor (rectangleToAdd.getX()),
  65861. roundToInt (rectangleToAdd.getY() * 256.0f) >> 8,
  65862. 2 + (int) rectangleToAdd.getWidth(),
  65863. 2 + (int) rectangleToAdd.getHeight())),
  65864. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65865. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65866. needToCheckEmptinesss (true)
  65867. {
  65868. jassert (! rectangleToAdd.isEmpty());
  65869. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65870. table[0] = 0;
  65871. const int x1 = roundToInt (rectangleToAdd.getX() * 256.0f);
  65872. const int x2 = roundToInt (rectangleToAdd.getRight() * 256.0f);
  65873. int y1 = roundToInt (rectangleToAdd.getY() * 256.0f) - (bounds.getY() << 8);
  65874. jassert (y1 < 256);
  65875. int y2 = roundToInt (rectangleToAdd.getBottom() * 256.0f) - (bounds.getY() << 8);
  65876. if (x2 <= x1 || y2 <= y1)
  65877. {
  65878. bounds.setHeight (0);
  65879. return;
  65880. }
  65881. int lineY = 0;
  65882. int* t = table;
  65883. if ((y1 >> 8) == (y2 >> 8))
  65884. {
  65885. t[0] = 2;
  65886. t[1] = x1;
  65887. t[2] = y2 - y1;
  65888. t[3] = x2;
  65889. t[4] = 0;
  65890. ++lineY;
  65891. t += lineStrideElements;
  65892. }
  65893. else
  65894. {
  65895. t[0] = 2;
  65896. t[1] = x1;
  65897. t[2] = 255 - (y1 & 255);
  65898. t[3] = x2;
  65899. t[4] = 0;
  65900. ++lineY;
  65901. t += lineStrideElements;
  65902. while (lineY < (y2 >> 8))
  65903. {
  65904. t[0] = 2;
  65905. t[1] = x1;
  65906. t[2] = 255;
  65907. t[3] = x2;
  65908. t[4] = 0;
  65909. ++lineY;
  65910. t += lineStrideElements;
  65911. }
  65912. jassert (lineY < bounds.getHeight());
  65913. t[0] = 2;
  65914. t[1] = x1;
  65915. t[2] = y2 & 255;
  65916. t[3] = x2;
  65917. t[4] = 0;
  65918. ++lineY;
  65919. t += lineStrideElements;
  65920. }
  65921. while (lineY < bounds.getHeight())
  65922. {
  65923. t[0] = 0;
  65924. t += lineStrideElements;
  65925. ++lineY;
  65926. }
  65927. }
  65928. EdgeTable::EdgeTable (const EdgeTable& other)
  65929. {
  65930. operator= (other);
  65931. }
  65932. EdgeTable& EdgeTable::operator= (const EdgeTable& other)
  65933. {
  65934. bounds = other.bounds;
  65935. maxEdgesPerLine = other.maxEdgesPerLine;
  65936. lineStrideElements = other.lineStrideElements;
  65937. needToCheckEmptinesss = other.needToCheckEmptinesss;
  65938. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65939. copyEdgeTableData (table, lineStrideElements, other.table, lineStrideElements, bounds.getHeight());
  65940. return *this;
  65941. }
  65942. EdgeTable::~EdgeTable()
  65943. {
  65944. }
  65945. void EdgeTable::copyEdgeTableData (int* dest, const int destLineStride, const int* src, const int srcLineStride, int numLines) throw()
  65946. {
  65947. while (--numLines >= 0)
  65948. {
  65949. memcpy (dest, src, (src[0] * 2 + 1) * sizeof (int));
  65950. src += srcLineStride;
  65951. dest += destLineStride;
  65952. }
  65953. }
  65954. void EdgeTable::sanitiseLevels (const bool useNonZeroWinding) throw()
  65955. {
  65956. // Convert the table from relative windings to absolute levels..
  65957. int* lineStart = table;
  65958. for (int i = bounds.getHeight(); --i >= 0;)
  65959. {
  65960. int* line = lineStart;
  65961. lineStart += lineStrideElements;
  65962. int num = *line;
  65963. if (num == 0)
  65964. continue;
  65965. int level = 0;
  65966. if (useNonZeroWinding)
  65967. {
  65968. while (--num > 0)
  65969. {
  65970. line += 2;
  65971. level += *line;
  65972. int corrected = abs (level);
  65973. if (corrected >> 8)
  65974. corrected = 255;
  65975. *line = corrected;
  65976. }
  65977. }
  65978. else
  65979. {
  65980. while (--num > 0)
  65981. {
  65982. line += 2;
  65983. level += *line;
  65984. int corrected = abs (level);
  65985. if (corrected >> 8)
  65986. {
  65987. corrected &= 511;
  65988. if (corrected >> 8)
  65989. corrected = 511 - corrected;
  65990. }
  65991. *line = corrected;
  65992. }
  65993. }
  65994. line[2] = 0; // force the last level to 0, just in case something went wrong in creating the table
  65995. }
  65996. }
  65997. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine) throw()
  65998. {
  65999. if (newNumEdgesPerLine != maxEdgesPerLine)
  66000. {
  66001. maxEdgesPerLine = newNumEdgesPerLine;
  66002. jassert (bounds.getHeight() > 0);
  66003. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  66004. HeapBlock <int> newTable (bounds.getHeight() * newLineStrideElements);
  66005. copyEdgeTableData (newTable, newLineStrideElements, table, lineStrideElements, bounds.getHeight());
  66006. table.swapWith (newTable);
  66007. lineStrideElements = newLineStrideElements;
  66008. }
  66009. }
  66010. void EdgeTable::optimiseTable() throw()
  66011. {
  66012. int maxLineElements = 0;
  66013. for (int i = bounds.getHeight(); --i >= 0;)
  66014. maxLineElements = jmax (maxLineElements, table [i * lineStrideElements]);
  66015. remapTableForNumEdges (maxLineElements);
  66016. }
  66017. void EdgeTable::addEdgePoint (const int x, const int y, const int winding) throw()
  66018. {
  66019. jassert (y >= 0 && y < bounds.getHeight());
  66020. int* line = table + lineStrideElements * y;
  66021. const int numPoints = line[0];
  66022. int n = numPoints << 1;
  66023. if (n > 0)
  66024. {
  66025. while (n > 0)
  66026. {
  66027. const int cx = line [n - 1];
  66028. if (cx <= x)
  66029. {
  66030. if (cx == x)
  66031. {
  66032. line [n] += winding;
  66033. return;
  66034. }
  66035. break;
  66036. }
  66037. n -= 2;
  66038. }
  66039. if (numPoints >= maxEdgesPerLine)
  66040. {
  66041. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  66042. jassert (numPoints < maxEdgesPerLine);
  66043. line = table + lineStrideElements * y;
  66044. }
  66045. memmove (line + (n + 3), line + (n + 1), sizeof (int) * ((numPoints << 1) - n));
  66046. }
  66047. line [n + 1] = x;
  66048. line [n + 2] = winding;
  66049. line[0]++;
  66050. }
  66051. void EdgeTable::translate (float dx, const int dy) throw()
  66052. {
  66053. bounds.translate ((int) std::floor (dx), dy);
  66054. int* lineStart = table;
  66055. const int intDx = (int) (dx * 256.0f);
  66056. for (int i = bounds.getHeight(); --i >= 0;)
  66057. {
  66058. int* line = lineStart;
  66059. lineStart += lineStrideElements;
  66060. int num = *line++;
  66061. while (--num >= 0)
  66062. {
  66063. *line += intDx;
  66064. line += 2;
  66065. }
  66066. }
  66067. }
  66068. void EdgeTable::intersectWithEdgeTableLine (const int y, const int* otherLine) throw()
  66069. {
  66070. jassert (y >= 0 && y < bounds.getHeight());
  66071. int* dest = table + lineStrideElements * y;
  66072. if (dest[0] == 0)
  66073. return;
  66074. int otherNumPoints = *otherLine;
  66075. if (otherNumPoints == 0)
  66076. {
  66077. *dest = 0;
  66078. return;
  66079. }
  66080. const int right = bounds.getRight() << 8;
  66081. // optimise for the common case where our line lies entirely within a
  66082. // single pair of points, as happens when clipping to a simple rect.
  66083. if (otherNumPoints == 2 && otherLine[2] >= 255)
  66084. {
  66085. clipEdgeTableLineToRange (dest, otherLine[1], jmin (right, otherLine[3]));
  66086. return;
  66087. }
  66088. ++otherLine;
  66089. const size_t lineSizeBytes = (dest[0] * 2 + 1) * sizeof (int);
  66090. int* temp = static_cast<int*> (alloca (lineSizeBytes));
  66091. memcpy (temp, dest, lineSizeBytes);
  66092. const int* src1 = temp;
  66093. int srcNum1 = *src1++;
  66094. int x1 = *src1++;
  66095. const int* src2 = otherLine;
  66096. int srcNum2 = otherNumPoints;
  66097. int x2 = *src2++;
  66098. int destIndex = 0, destTotal = 0;
  66099. int level1 = 0, level2 = 0;
  66100. int lastX = std::numeric_limits<int>::min(), lastLevel = 0;
  66101. while (srcNum1 > 0 && srcNum2 > 0)
  66102. {
  66103. int nextX;
  66104. if (x1 < x2)
  66105. {
  66106. nextX = x1;
  66107. level1 = *src1++;
  66108. x1 = *src1++;
  66109. --srcNum1;
  66110. }
  66111. else if (x1 == x2)
  66112. {
  66113. nextX = x1;
  66114. level1 = *src1++;
  66115. level2 = *src2++;
  66116. x1 = *src1++;
  66117. x2 = *src2++;
  66118. --srcNum1;
  66119. --srcNum2;
  66120. }
  66121. else
  66122. {
  66123. nextX = x2;
  66124. level2 = *src2++;
  66125. x2 = *src2++;
  66126. --srcNum2;
  66127. }
  66128. if (nextX > lastX)
  66129. {
  66130. if (nextX >= right)
  66131. break;
  66132. lastX = nextX;
  66133. const int nextLevel = (level1 * (level2 + 1)) >> 8;
  66134. jassert (((unsigned int) nextLevel) < (unsigned int) 256);
  66135. if (nextLevel != lastLevel)
  66136. {
  66137. if (destTotal >= maxEdgesPerLine)
  66138. {
  66139. dest[0] = destTotal;
  66140. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  66141. dest = table + lineStrideElements * y;
  66142. }
  66143. ++destTotal;
  66144. lastLevel = nextLevel;
  66145. dest[++destIndex] = nextX;
  66146. dest[++destIndex] = nextLevel;
  66147. }
  66148. }
  66149. }
  66150. if (lastLevel > 0)
  66151. {
  66152. if (destTotal >= maxEdgesPerLine)
  66153. {
  66154. dest[0] = destTotal;
  66155. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  66156. dest = table + lineStrideElements * y;
  66157. }
  66158. ++destTotal;
  66159. dest[++destIndex] = right;
  66160. dest[++destIndex] = 0;
  66161. }
  66162. dest[0] = destTotal;
  66163. #if JUCE_DEBUG
  66164. int last = std::numeric_limits<int>::min();
  66165. for (int i = 0; i < dest[0]; ++i)
  66166. {
  66167. jassert (dest[i * 2 + 1] > last);
  66168. last = dest[i * 2 + 1];
  66169. }
  66170. jassert (dest [dest[0] * 2] == 0);
  66171. #endif
  66172. }
  66173. void EdgeTable::clipEdgeTableLineToRange (int* dest, const int x1, const int x2) throw()
  66174. {
  66175. int* lastItem = dest + (dest[0] * 2 - 1);
  66176. if (x2 < lastItem[0])
  66177. {
  66178. if (x2 <= dest[1])
  66179. {
  66180. dest[0] = 0;
  66181. return;
  66182. }
  66183. while (x2 < lastItem[-2])
  66184. {
  66185. --(dest[0]);
  66186. lastItem -= 2;
  66187. }
  66188. lastItem[0] = x2;
  66189. lastItem[1] = 0;
  66190. }
  66191. if (x1 > dest[1])
  66192. {
  66193. while (lastItem[0] > x1)
  66194. lastItem -= 2;
  66195. const int itemsRemoved = (int) (lastItem - (dest + 1)) / 2;
  66196. if (itemsRemoved > 0)
  66197. {
  66198. dest[0] -= itemsRemoved;
  66199. memmove (dest + 1, lastItem, dest[0] * (sizeof (int) * 2));
  66200. }
  66201. dest[1] = x1;
  66202. }
  66203. }
  66204. void EdgeTable::clipToRectangle (const Rectangle<int>& r) throw()
  66205. {
  66206. const Rectangle<int> clipped (r.getIntersection (bounds));
  66207. if (clipped.isEmpty())
  66208. {
  66209. needToCheckEmptinesss = false;
  66210. bounds.setHeight (0);
  66211. }
  66212. else
  66213. {
  66214. const int top = clipped.getY() - bounds.getY();
  66215. const int bottom = clipped.getBottom() - bounds.getY();
  66216. if (bottom < bounds.getHeight())
  66217. bounds.setHeight (bottom);
  66218. if (clipped.getRight() < bounds.getRight())
  66219. bounds.setRight (clipped.getRight());
  66220. for (int i = top; --i >= 0;)
  66221. table [lineStrideElements * i] = 0;
  66222. if (clipped.getX() > bounds.getX())
  66223. {
  66224. const int x1 = clipped.getX() << 8;
  66225. const int x2 = jmin (bounds.getRight(), clipped.getRight()) << 8;
  66226. int* line = table + lineStrideElements * top;
  66227. for (int i = bottom - top; --i >= 0;)
  66228. {
  66229. if (line[0] != 0)
  66230. clipEdgeTableLineToRange (line, x1, x2);
  66231. line += lineStrideElements;
  66232. }
  66233. }
  66234. needToCheckEmptinesss = true;
  66235. }
  66236. }
  66237. void EdgeTable::excludeRectangle (const Rectangle<int>& r) throw()
  66238. {
  66239. const Rectangle<int> clipped (r.getIntersection (bounds));
  66240. if (! clipped.isEmpty())
  66241. {
  66242. const int top = clipped.getY() - bounds.getY();
  66243. const int bottom = clipped.getBottom() - bounds.getY();
  66244. //XXX optimise here by shortening the table if it fills top or bottom
  66245. const int rectLine[] = { 4, std::numeric_limits<int>::min(), 255,
  66246. clipped.getX() << 8, 0,
  66247. clipped.getRight() << 8, 255,
  66248. std::numeric_limits<int>::max(), 0 };
  66249. for (int i = top; i < bottom; ++i)
  66250. intersectWithEdgeTableLine (i, rectLine);
  66251. needToCheckEmptinesss = true;
  66252. }
  66253. }
  66254. void EdgeTable::clipToEdgeTable (const EdgeTable& other)
  66255. {
  66256. const Rectangle<int> clipped (other.bounds.getIntersection (bounds));
  66257. if (clipped.isEmpty())
  66258. {
  66259. needToCheckEmptinesss = false;
  66260. bounds.setHeight (0);
  66261. }
  66262. else
  66263. {
  66264. const int top = clipped.getY() - bounds.getY();
  66265. const int bottom = clipped.getBottom() - bounds.getY();
  66266. if (bottom < bounds.getHeight())
  66267. bounds.setHeight (bottom);
  66268. if (clipped.getRight() < bounds.getRight())
  66269. bounds.setRight (clipped.getRight());
  66270. int i = 0;
  66271. for (i = top; --i >= 0;)
  66272. table [lineStrideElements * i] = 0;
  66273. const int* otherLine = other.table + other.lineStrideElements * (clipped.getY() - other.bounds.getY());
  66274. for (i = top; i < bottom; ++i)
  66275. {
  66276. intersectWithEdgeTableLine (i, otherLine);
  66277. otherLine += other.lineStrideElements;
  66278. }
  66279. needToCheckEmptinesss = true;
  66280. }
  66281. }
  66282. void EdgeTable::clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels) throw()
  66283. {
  66284. y -= bounds.getY();
  66285. if (y < 0 || y >= bounds.getHeight())
  66286. return;
  66287. needToCheckEmptinesss = true;
  66288. if (numPixels <= 0)
  66289. {
  66290. table [lineStrideElements * y] = 0;
  66291. return;
  66292. }
  66293. int* tempLine = static_cast<int*> (alloca ((numPixels * 2 + 4) * sizeof (int)));
  66294. int destIndex = 0, lastLevel = 0;
  66295. while (--numPixels >= 0)
  66296. {
  66297. const int alpha = *mask;
  66298. mask += maskStride;
  66299. if (alpha != lastLevel)
  66300. {
  66301. tempLine[++destIndex] = (x << 8);
  66302. tempLine[++destIndex] = alpha;
  66303. lastLevel = alpha;
  66304. }
  66305. ++x;
  66306. }
  66307. if (lastLevel > 0)
  66308. {
  66309. tempLine[++destIndex] = (x << 8);
  66310. tempLine[++destIndex] = 0;
  66311. }
  66312. tempLine[0] = destIndex >> 1;
  66313. intersectWithEdgeTableLine (y, tempLine);
  66314. }
  66315. bool EdgeTable::isEmpty() throw()
  66316. {
  66317. if (needToCheckEmptinesss)
  66318. {
  66319. needToCheckEmptinesss = false;
  66320. int* t = table;
  66321. for (int i = bounds.getHeight(); --i >= 0;)
  66322. {
  66323. if (t[0] > 1)
  66324. return false;
  66325. t += lineStrideElements;
  66326. }
  66327. bounds.setHeight (0);
  66328. }
  66329. return bounds.getHeight() == 0;
  66330. }
  66331. END_JUCE_NAMESPACE
  66332. /*** End of inlined file: juce_EdgeTable.cpp ***/
  66333. /*** Start of inlined file: juce_FillType.cpp ***/
  66334. BEGIN_JUCE_NAMESPACE
  66335. FillType::FillType() throw()
  66336. : colour (0xff000000), image (0)
  66337. {
  66338. }
  66339. FillType::FillType (const Colour& colour_) throw()
  66340. : colour (colour_), image (0)
  66341. {
  66342. }
  66343. FillType::FillType (const ColourGradient& gradient_)
  66344. : colour (0xff000000), gradient (new ColourGradient (gradient_)), image (0)
  66345. {
  66346. }
  66347. FillType::FillType (const Image& image_, const AffineTransform& transform_) throw()
  66348. : colour (0xff000000), image (image_), transform (transform_)
  66349. {
  66350. }
  66351. FillType::FillType (const FillType& other)
  66352. : colour (other.colour),
  66353. gradient (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0),
  66354. image (other.image), transform (other.transform)
  66355. {
  66356. }
  66357. FillType& FillType::operator= (const FillType& other)
  66358. {
  66359. if (this != &other)
  66360. {
  66361. colour = other.colour;
  66362. gradient = (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0);
  66363. image = other.image;
  66364. transform = other.transform;
  66365. }
  66366. return *this;
  66367. }
  66368. FillType::~FillType() throw()
  66369. {
  66370. }
  66371. bool FillType::operator== (const FillType& other) const
  66372. {
  66373. return colour == other.colour && image == other.image
  66374. && transform == other.transform
  66375. && (gradient == other.gradient
  66376. || (gradient != 0 && other.gradient != 0 && *gradient == *other.gradient));
  66377. }
  66378. bool FillType::operator!= (const FillType& other) const
  66379. {
  66380. return ! operator== (other);
  66381. }
  66382. void FillType::setColour (const Colour& newColour) throw()
  66383. {
  66384. gradient = 0;
  66385. image = Image::null;
  66386. colour = newColour;
  66387. }
  66388. void FillType::setGradient (const ColourGradient& newGradient)
  66389. {
  66390. if (gradient != 0)
  66391. {
  66392. *gradient = newGradient;
  66393. }
  66394. else
  66395. {
  66396. image = Image::null;
  66397. gradient = new ColourGradient (newGradient);
  66398. colour = Colours::black;
  66399. }
  66400. }
  66401. void FillType::setTiledImage (const Image& image_, const AffineTransform& transform_) throw()
  66402. {
  66403. gradient = 0;
  66404. image = image_;
  66405. transform = transform_;
  66406. colour = Colours::black;
  66407. }
  66408. void FillType::setOpacity (const float newOpacity) throw()
  66409. {
  66410. colour = colour.withAlpha (newOpacity);
  66411. }
  66412. bool FillType::isInvisible() const throw()
  66413. {
  66414. return colour.isTransparent() || (gradient != 0 && gradient->isInvisible());
  66415. }
  66416. END_JUCE_NAMESPACE
  66417. /*** End of inlined file: juce_FillType.cpp ***/
  66418. /*** Start of inlined file: juce_Graphics.cpp ***/
  66419. BEGIN_JUCE_NAMESPACE
  66420. template <typename Type>
  66421. static bool areCoordsSensibleNumbers (Type x, Type y, Type w, Type h)
  66422. {
  66423. const int maxVal = 0x3fffffff;
  66424. return (int) x >= -maxVal && (int) x <= maxVal
  66425. && (int) y >= -maxVal && (int) y <= maxVal
  66426. && (int) w >= -maxVal && (int) w <= maxVal
  66427. && (int) h >= -maxVal && (int) h <= maxVal;
  66428. }
  66429. LowLevelGraphicsContext::LowLevelGraphicsContext()
  66430. {
  66431. }
  66432. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  66433. {
  66434. }
  66435. Graphics::Graphics (const Image& imageToDrawOnto)
  66436. : context (imageToDrawOnto.createLowLevelContext()),
  66437. contextToDelete (context),
  66438. saveStatePending (false)
  66439. {
  66440. }
  66441. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  66442. : context (internalContext),
  66443. saveStatePending (false)
  66444. {
  66445. }
  66446. Graphics::~Graphics()
  66447. {
  66448. }
  66449. void Graphics::resetToDefaultState()
  66450. {
  66451. saveStateIfPending();
  66452. context->setFill (FillType());
  66453. context->setFont (Font());
  66454. context->setInterpolationQuality (Graphics::mediumResamplingQuality);
  66455. }
  66456. bool Graphics::isVectorDevice() const
  66457. {
  66458. return context->isVectorDevice();
  66459. }
  66460. bool Graphics::reduceClipRegion (const int x, const int y, const int w, const int h)
  66461. {
  66462. saveStateIfPending();
  66463. return context->clipToRectangle (Rectangle<int> (x, y, w, h));
  66464. }
  66465. bool Graphics::reduceClipRegion (const RectangleList& clipRegion)
  66466. {
  66467. saveStateIfPending();
  66468. return context->clipToRectangleList (clipRegion);
  66469. }
  66470. bool Graphics::reduceClipRegion (const Path& path, const AffineTransform& transform)
  66471. {
  66472. saveStateIfPending();
  66473. context->clipToPath (path, transform);
  66474. return ! context->isClipEmpty();
  66475. }
  66476. bool Graphics::reduceClipRegion (const Image& image, const AffineTransform& transform)
  66477. {
  66478. saveStateIfPending();
  66479. context->clipToImageAlpha (image, transform);
  66480. return ! context->isClipEmpty();
  66481. }
  66482. void Graphics::excludeClipRegion (const Rectangle<int>& rectangleToExclude)
  66483. {
  66484. saveStateIfPending();
  66485. context->excludeClipRectangle (rectangleToExclude);
  66486. }
  66487. bool Graphics::isClipEmpty() const
  66488. {
  66489. return context->isClipEmpty();
  66490. }
  66491. const Rectangle<int> Graphics::getClipBounds() const
  66492. {
  66493. return context->getClipBounds();
  66494. }
  66495. void Graphics::saveState()
  66496. {
  66497. saveStateIfPending();
  66498. saveStatePending = true;
  66499. }
  66500. void Graphics::restoreState()
  66501. {
  66502. if (saveStatePending)
  66503. saveStatePending = false;
  66504. else
  66505. context->restoreState();
  66506. }
  66507. void Graphics::saveStateIfPending()
  66508. {
  66509. if (saveStatePending)
  66510. {
  66511. saveStatePending = false;
  66512. context->saveState();
  66513. }
  66514. }
  66515. void Graphics::setOrigin (const int newOriginX, const int newOriginY)
  66516. {
  66517. saveStateIfPending();
  66518. context->setOrigin (newOriginX, newOriginY);
  66519. }
  66520. bool Graphics::clipRegionIntersects (const Rectangle<int>& area) const
  66521. {
  66522. return context->clipRegionIntersects (area);
  66523. }
  66524. void Graphics::setColour (const Colour& newColour)
  66525. {
  66526. saveStateIfPending();
  66527. context->setFill (newColour);
  66528. }
  66529. void Graphics::setOpacity (const float newOpacity)
  66530. {
  66531. saveStateIfPending();
  66532. context->setOpacity (newOpacity);
  66533. }
  66534. void Graphics::setGradientFill (const ColourGradient& gradient)
  66535. {
  66536. setFillType (gradient);
  66537. }
  66538. void Graphics::setTiledImageFill (const Image& imageToUse, const int anchorX, const int anchorY, const float opacity)
  66539. {
  66540. saveStateIfPending();
  66541. context->setFill (FillType (imageToUse, AffineTransform::translation ((float) anchorX, (float) anchorY)));
  66542. context->setOpacity (opacity);
  66543. }
  66544. void Graphics::setFillType (const FillType& newFill)
  66545. {
  66546. saveStateIfPending();
  66547. context->setFill (newFill);
  66548. }
  66549. void Graphics::setFont (const Font& newFont)
  66550. {
  66551. saveStateIfPending();
  66552. context->setFont (newFont);
  66553. }
  66554. void Graphics::setFont (const float newFontHeight, const int newFontStyleFlags)
  66555. {
  66556. saveStateIfPending();
  66557. Font f (context->getFont());
  66558. f.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0);
  66559. context->setFont (f);
  66560. }
  66561. const Font Graphics::getCurrentFont() const
  66562. {
  66563. return context->getFont();
  66564. }
  66565. void Graphics::drawSingleLineText (const String& text, const int startX, const int baselineY) const
  66566. {
  66567. if (text.isNotEmpty()
  66568. && startX < context->getClipBounds().getRight())
  66569. {
  66570. GlyphArrangement arr;
  66571. arr.addLineOfText (context->getFont(), text, (float) startX, (float) baselineY);
  66572. arr.draw (*this);
  66573. }
  66574. }
  66575. void Graphics::drawTextAsPath (const String& text, const AffineTransform& transform) const
  66576. {
  66577. if (text.isNotEmpty())
  66578. {
  66579. GlyphArrangement arr;
  66580. arr.addLineOfText (context->getFont(), text, 0.0f, 0.0f);
  66581. arr.draw (*this, transform);
  66582. }
  66583. }
  66584. void Graphics::drawMultiLineText (const String& text, const int startX, const int baselineY, const int maximumLineWidth) const
  66585. {
  66586. if (text.isNotEmpty()
  66587. && startX < context->getClipBounds().getRight())
  66588. {
  66589. GlyphArrangement arr;
  66590. arr.addJustifiedText (context->getFont(), text,
  66591. (float) startX, (float) baselineY, (float) maximumLineWidth,
  66592. Justification::left);
  66593. arr.draw (*this);
  66594. }
  66595. }
  66596. void Graphics::drawText (const String& text,
  66597. const int x, const int y, const int width, const int height,
  66598. const Justification& justificationType,
  66599. const bool useEllipsesIfTooBig) const
  66600. {
  66601. if (text.isNotEmpty() && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66602. {
  66603. GlyphArrangement arr;
  66604. arr.addCurtailedLineOfText (context->getFont(), text,
  66605. 0.0f, 0.0f, (float) width,
  66606. useEllipsesIfTooBig);
  66607. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  66608. (float) x, (float) y, (float) width, (float) height,
  66609. justificationType);
  66610. arr.draw (*this);
  66611. }
  66612. }
  66613. void Graphics::drawFittedText (const String& text,
  66614. const int x, const int y, const int width, const int height,
  66615. const Justification& justification,
  66616. const int maximumNumberOfLines,
  66617. const float minimumHorizontalScale) const
  66618. {
  66619. if (text.isNotEmpty()
  66620. && width > 0 && height > 0
  66621. && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66622. {
  66623. GlyphArrangement arr;
  66624. arr.addFittedText (context->getFont(), text,
  66625. (float) x, (float) y, (float) width, (float) height,
  66626. justification,
  66627. maximumNumberOfLines,
  66628. minimumHorizontalScale);
  66629. arr.draw (*this);
  66630. }
  66631. }
  66632. void Graphics::fillRect (int x, int y, int width, int height) const
  66633. {
  66634. // passing in a silly number can cause maths problems in rendering!
  66635. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66636. context->fillRect (Rectangle<int> (x, y, width, height), false);
  66637. }
  66638. void Graphics::fillRect (const Rectangle<int>& r) const
  66639. {
  66640. context->fillRect (r, false);
  66641. }
  66642. void Graphics::fillRect (const float x, const float y, const float width, const float height) const
  66643. {
  66644. // passing in a silly number can cause maths problems in rendering!
  66645. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66646. Path p;
  66647. p.addRectangle (x, y, width, height);
  66648. fillPath (p);
  66649. }
  66650. void Graphics::setPixel (int x, int y) const
  66651. {
  66652. context->fillRect (Rectangle<int> (x, y, 1, 1), false);
  66653. }
  66654. void Graphics::fillAll() const
  66655. {
  66656. fillRect (context->getClipBounds());
  66657. }
  66658. void Graphics::fillAll (const Colour& colourToUse) const
  66659. {
  66660. if (! colourToUse.isTransparent())
  66661. {
  66662. const Rectangle<int> clip (context->getClipBounds());
  66663. context->saveState();
  66664. context->setFill (colourToUse);
  66665. context->fillRect (clip, false);
  66666. context->restoreState();
  66667. }
  66668. }
  66669. void Graphics::fillPath (const Path& path, const AffineTransform& transform) const
  66670. {
  66671. if ((! context->isClipEmpty()) && ! path.isEmpty())
  66672. context->fillPath (path, transform);
  66673. }
  66674. void Graphics::strokePath (const Path& path,
  66675. const PathStrokeType& strokeType,
  66676. const AffineTransform& transform) const
  66677. {
  66678. Path stroke;
  66679. strokeType.createStrokedPath (stroke, path, transform);
  66680. fillPath (stroke);
  66681. }
  66682. void Graphics::drawRect (const int x, const int y, const int width, const int height,
  66683. const int lineThickness) const
  66684. {
  66685. // passing in a silly number can cause maths problems in rendering!
  66686. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66687. context->fillRect (Rectangle<int> (x, y, width, lineThickness), false);
  66688. context->fillRect (Rectangle<int> (x, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66689. context->fillRect (Rectangle<int> (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66690. context->fillRect (Rectangle<int> (x, y + height - lineThickness, width, lineThickness), false);
  66691. }
  66692. void Graphics::drawRect (const float x, const float y, const float width, const float height, const float lineThickness) const
  66693. {
  66694. // passing in a silly number can cause maths problems in rendering!
  66695. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66696. Path p;
  66697. p.addRectangle (x, y, width, lineThickness);
  66698. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66699. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66700. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  66701. fillPath (p);
  66702. }
  66703. void Graphics::drawRect (const Rectangle<int>& r, const int lineThickness) const
  66704. {
  66705. drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight(), lineThickness);
  66706. }
  66707. void Graphics::drawBevel (const int x, const int y, const int width, const int height,
  66708. const int bevelThickness, const Colour& topLeftColour, const Colour& bottomRightColour,
  66709. const bool useGradient, const bool sharpEdgeOnOutside) const
  66710. {
  66711. // passing in a silly number can cause maths problems in rendering!
  66712. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66713. if (clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66714. {
  66715. context->saveState();
  66716. const float oldOpacity = 1.0f;//xxx state->colour.getFloatAlpha();
  66717. const float ramp = oldOpacity / bevelThickness;
  66718. for (int i = bevelThickness; --i >= 0;)
  66719. {
  66720. const float op = useGradient ? ramp * (sharpEdgeOnOutside ? bevelThickness - i : i)
  66721. : oldOpacity;
  66722. context->setFill (topLeftColour.withMultipliedAlpha (op));
  66723. context->fillRect (Rectangle<int> (x + i, y + i, width - i * 2, 1), false);
  66724. context->setFill (topLeftColour.withMultipliedAlpha (op * 0.75f));
  66725. context->fillRect (Rectangle<int> (x + i, y + i + 1, 1, height - i * 2 - 2), false);
  66726. context->setFill (bottomRightColour.withMultipliedAlpha (op));
  66727. context->fillRect (Rectangle<int> (x + i, y + height - i - 1, width - i * 2, 1), false);
  66728. context->setFill (bottomRightColour.withMultipliedAlpha (op * 0.75f));
  66729. context->fillRect (Rectangle<int> (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2), false);
  66730. }
  66731. context->restoreState();
  66732. }
  66733. }
  66734. void Graphics::fillEllipse (const float x, const float y, const float width, const float height) const
  66735. {
  66736. // passing in a silly number can cause maths problems in rendering!
  66737. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66738. Path p;
  66739. p.addEllipse (x, y, width, height);
  66740. fillPath (p);
  66741. }
  66742. void Graphics::drawEllipse (const float x, const float y, const float width, const float height,
  66743. const float lineThickness) const
  66744. {
  66745. // passing in a silly number can cause maths problems in rendering!
  66746. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66747. Path p;
  66748. p.addEllipse (x, y, width, height);
  66749. strokePath (p, PathStrokeType (lineThickness));
  66750. }
  66751. void Graphics::fillRoundedRectangle (const float x, const float y, const float width, const float height, const float cornerSize) const
  66752. {
  66753. // passing in a silly number can cause maths problems in rendering!
  66754. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66755. Path p;
  66756. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66757. fillPath (p);
  66758. }
  66759. void Graphics::fillRoundedRectangle (const Rectangle<float>& r, const float cornerSize) const
  66760. {
  66761. fillRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize);
  66762. }
  66763. void Graphics::drawRoundedRectangle (const float x, const float y, const float width, const float height,
  66764. const float cornerSize, const float lineThickness) const
  66765. {
  66766. // passing in a silly number can cause maths problems in rendering!
  66767. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66768. Path p;
  66769. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66770. strokePath (p, PathStrokeType (lineThickness));
  66771. }
  66772. void Graphics::drawRoundedRectangle (const Rectangle<float>& r, const float cornerSize, const float lineThickness) const
  66773. {
  66774. drawRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize, lineThickness);
  66775. }
  66776. void Graphics::drawArrow (const Line<float>& line, const float lineThickness, const float arrowheadWidth, const float arrowheadLength) const
  66777. {
  66778. Path p;
  66779. p.addArrow (line, lineThickness, arrowheadWidth, arrowheadLength);
  66780. fillPath (p);
  66781. }
  66782. void Graphics::fillCheckerBoard (const Rectangle<int>& area,
  66783. const int checkWidth, const int checkHeight,
  66784. const Colour& colour1, const Colour& colour2) const
  66785. {
  66786. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  66787. if (checkWidth > 0 && checkHeight > 0)
  66788. {
  66789. context->saveState();
  66790. if (colour1 == colour2)
  66791. {
  66792. context->setFill (colour1);
  66793. context->fillRect (area, false);
  66794. }
  66795. else
  66796. {
  66797. const Rectangle<int> clipped (context->getClipBounds().getIntersection (area));
  66798. if (! clipped.isEmpty())
  66799. {
  66800. context->clipToRectangle (clipped);
  66801. const int checkNumX = (clipped.getX() - area.getX()) / checkWidth;
  66802. const int checkNumY = (clipped.getY() - area.getY()) / checkHeight;
  66803. const int startX = area.getX() + checkNumX * checkWidth;
  66804. const int startY = area.getY() + checkNumY * checkHeight;
  66805. const int right = clipped.getRight();
  66806. const int bottom = clipped.getBottom();
  66807. for (int i = 0; i < 2; ++i)
  66808. {
  66809. context->setFill (i == ((checkNumX ^ checkNumY) & 1) ? colour1 : colour2);
  66810. int cy = i;
  66811. for (int y = startY; y < bottom; y += checkHeight)
  66812. for (int x = startX + (cy++ & 1) * checkWidth; x < right; x += checkWidth * 2)
  66813. context->fillRect (Rectangle<int> (x, y, checkWidth, checkHeight), false);
  66814. }
  66815. }
  66816. }
  66817. context->restoreState();
  66818. }
  66819. }
  66820. void Graphics::drawVerticalLine (const int x, float top, float bottom) const
  66821. {
  66822. context->drawVerticalLine (x, top, bottom);
  66823. }
  66824. void Graphics::drawHorizontalLine (const int y, float left, float right) const
  66825. {
  66826. context->drawHorizontalLine (y, left, right);
  66827. }
  66828. void Graphics::drawLine (float x1, float y1, float x2, float y2) const
  66829. {
  66830. context->drawLine (Line<float> (x1, y1, x2, y2));
  66831. }
  66832. void Graphics::drawLine (const float startX, const float startY,
  66833. const float endX, const float endY,
  66834. const float lineThickness) const
  66835. {
  66836. drawLine (Line<float> (startX, startY, endX, endY),lineThickness);
  66837. }
  66838. void Graphics::drawLine (const Line<float>& line) const
  66839. {
  66840. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY());
  66841. }
  66842. void Graphics::drawLine (const Line<float>& line, const float lineThickness) const
  66843. {
  66844. Path p;
  66845. p.addLineSegment (line, lineThickness);
  66846. fillPath (p);
  66847. }
  66848. void Graphics::drawDashedLine (const float startX, const float startY,
  66849. const float endX, const float endY,
  66850. const float* const dashLengths,
  66851. const int numDashLengths,
  66852. const float lineThickness) const
  66853. {
  66854. const double dx = endX - startX;
  66855. const double dy = endY - startY;
  66856. const double totalLen = juce_hypot (dx, dy);
  66857. if (totalLen >= 0.5)
  66858. {
  66859. const double onePixAlpha = 1.0 / totalLen;
  66860. double alpha = 0.0;
  66861. float x = startX;
  66862. float y = startY;
  66863. int n = 0;
  66864. while (alpha < 1.0f)
  66865. {
  66866. alpha = jmin (1.0, alpha + dashLengths[n++] * onePixAlpha);
  66867. n = n % numDashLengths;
  66868. const float oldX = x;
  66869. const float oldY = y;
  66870. x = (float) (startX + dx * alpha);
  66871. y = (float) (startY + dy * alpha);
  66872. if ((n & 1) != 0)
  66873. {
  66874. if (lineThickness != 1.0f)
  66875. drawLine (oldX, oldY, x, y, lineThickness);
  66876. else
  66877. drawLine (oldX, oldY, x, y);
  66878. }
  66879. }
  66880. }
  66881. }
  66882. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality)
  66883. {
  66884. saveStateIfPending();
  66885. context->setInterpolationQuality (newQuality);
  66886. }
  66887. void Graphics::drawImageAt (const Image& imageToDraw,
  66888. const int topLeftX, const int topLeftY,
  66889. const bool fillAlphaChannelWithCurrentBrush) const
  66890. {
  66891. const int imageW = imageToDraw.getWidth();
  66892. const int imageH = imageToDraw.getHeight();
  66893. drawImage (imageToDraw,
  66894. topLeftX, topLeftY, imageW, imageH,
  66895. 0, 0, imageW, imageH,
  66896. fillAlphaChannelWithCurrentBrush);
  66897. }
  66898. void Graphics::drawImageWithin (const Image& imageToDraw,
  66899. const int destX, const int destY,
  66900. const int destW, const int destH,
  66901. const RectanglePlacement& placementWithinTarget,
  66902. const bool fillAlphaChannelWithCurrentBrush) const
  66903. {
  66904. // passing in a silly number can cause maths problems in rendering!
  66905. jassert (areCoordsSensibleNumbers (destX, destY, destW, destH));
  66906. if (imageToDraw.isValid())
  66907. {
  66908. const int imageW = imageToDraw.getWidth();
  66909. const int imageH = imageToDraw.getHeight();
  66910. if (imageW > 0 && imageH > 0)
  66911. {
  66912. double newX = 0.0, newY = 0.0;
  66913. double newW = imageW;
  66914. double newH = imageH;
  66915. placementWithinTarget.applyTo (newX, newY, newW, newH,
  66916. destX, destY, destW, destH);
  66917. if (newW > 0 && newH > 0)
  66918. {
  66919. drawImage (imageToDraw,
  66920. roundToInt (newX), roundToInt (newY),
  66921. roundToInt (newW), roundToInt (newH),
  66922. 0, 0, imageW, imageH,
  66923. fillAlphaChannelWithCurrentBrush);
  66924. }
  66925. }
  66926. }
  66927. }
  66928. void Graphics::drawImage (const Image& imageToDraw,
  66929. int dx, int dy, int dw, int dh,
  66930. int sx, int sy, int sw, int sh,
  66931. const bool fillAlphaChannelWithCurrentBrush) const
  66932. {
  66933. // passing in a silly number can cause maths problems in rendering!
  66934. jassert (areCoordsSensibleNumbers (dx, dy, dw, dh));
  66935. jassert (areCoordsSensibleNumbers (sx, sy, sw, sh));
  66936. if (imageToDraw.isValid() && context->clipRegionIntersects (Rectangle<int> (dx, dy, dw, dh)))
  66937. {
  66938. drawImageTransformed (imageToDraw.getClippedImage (Rectangle<int> (sx, sy, sw, sh)),
  66939. AffineTransform::scale (dw / (float) sw, dh / (float) sh)
  66940. .translated ((float) dx, (float) dy),
  66941. fillAlphaChannelWithCurrentBrush);
  66942. }
  66943. }
  66944. void Graphics::drawImageTransformed (const Image& imageToDraw,
  66945. const AffineTransform& transform,
  66946. const bool fillAlphaChannelWithCurrentBrush) const
  66947. {
  66948. if (imageToDraw.isValid() && ! context->isClipEmpty())
  66949. {
  66950. if (fillAlphaChannelWithCurrentBrush)
  66951. {
  66952. context->saveState();
  66953. context->clipToImageAlpha (imageToDraw, transform);
  66954. fillAll();
  66955. context->restoreState();
  66956. }
  66957. else
  66958. {
  66959. context->drawImage (imageToDraw, transform, false);
  66960. }
  66961. }
  66962. }
  66963. END_JUCE_NAMESPACE
  66964. /*** End of inlined file: juce_Graphics.cpp ***/
  66965. /*** Start of inlined file: juce_Justification.cpp ***/
  66966. BEGIN_JUCE_NAMESPACE
  66967. Justification::Justification (const Justification& other) throw()
  66968. : flags (other.flags)
  66969. {
  66970. }
  66971. Justification& Justification::operator= (const Justification& other) throw()
  66972. {
  66973. flags = other.flags;
  66974. return *this;
  66975. }
  66976. int Justification::getOnlyVerticalFlags() const throw()
  66977. {
  66978. return flags & (top | bottom | verticallyCentred);
  66979. }
  66980. int Justification::getOnlyHorizontalFlags() const throw()
  66981. {
  66982. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  66983. }
  66984. void Justification::applyToRectangle (int& x, int& y,
  66985. const int w, const int h,
  66986. const int spaceX, const int spaceY,
  66987. const int spaceW, const int spaceH) const throw()
  66988. {
  66989. if ((flags & horizontallyCentred) != 0)
  66990. x = spaceX + ((spaceW - w) >> 1);
  66991. else if ((flags & right) != 0)
  66992. x = spaceX + spaceW - w;
  66993. else
  66994. x = spaceX;
  66995. if ((flags & verticallyCentred) != 0)
  66996. y = spaceY + ((spaceH - h) >> 1);
  66997. else if ((flags & bottom) != 0)
  66998. y = spaceY + spaceH - h;
  66999. else
  67000. y = spaceY;
  67001. }
  67002. END_JUCE_NAMESPACE
  67003. /*** End of inlined file: juce_Justification.cpp ***/
  67004. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  67005. BEGIN_JUCE_NAMESPACE
  67006. // this will throw an assertion if you try to draw something that's not
  67007. // possible in postscript
  67008. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  67009. #if JUCE_DEBUG && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  67010. #define notPossibleInPostscriptAssert jassertfalse
  67011. #else
  67012. #define notPossibleInPostscriptAssert
  67013. #endif
  67014. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  67015. const String& documentTitle,
  67016. const int totalWidth_,
  67017. const int totalHeight_)
  67018. : out (resultingPostScript),
  67019. totalWidth (totalWidth_),
  67020. totalHeight (totalHeight_),
  67021. needToClip (true)
  67022. {
  67023. stateStack.add (new SavedState());
  67024. stateStack.getLast()->clip = Rectangle<int> (totalWidth_, totalHeight_);
  67025. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  67026. out << "%!PS-Adobe-3.0 EPSF-3.0"
  67027. "\n%%BoundingBox: 0 0 600 824"
  67028. "\n%%Pages: 0"
  67029. "\n%%Creator: Raw Material Software JUCE"
  67030. "\n%%Title: " << documentTitle <<
  67031. "\n%%CreationDate: none"
  67032. "\n%%LanguageLevel: 2"
  67033. "\n%%EndComments"
  67034. "\n%%BeginProlog"
  67035. "\n%%BeginResource: JRes"
  67036. "\n/bd {bind def} bind def"
  67037. "\n/c {setrgbcolor} bd"
  67038. "\n/m {moveto} bd"
  67039. "\n/l {lineto} bd"
  67040. "\n/rl {rlineto} bd"
  67041. "\n/ct {curveto} bd"
  67042. "\n/cp {closepath} bd"
  67043. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  67044. "\n/doclip {initclip newpath} bd"
  67045. "\n/endclip {clip newpath} bd"
  67046. "\n%%EndResource"
  67047. "\n%%EndProlog"
  67048. "\n%%BeginSetup"
  67049. "\n%%EndSetup"
  67050. "\n%%Page: 1 1"
  67051. "\n%%BeginPageSetup"
  67052. "\n%%EndPageSetup\n\n"
  67053. << "40 800 translate\n"
  67054. << scale << ' ' << scale << " scale\n\n";
  67055. }
  67056. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  67057. {
  67058. }
  67059. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  67060. {
  67061. return true;
  67062. }
  67063. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  67064. {
  67065. if (x != 0 || y != 0)
  67066. {
  67067. stateStack.getLast()->xOffset += x;
  67068. stateStack.getLast()->yOffset += y;
  67069. needToClip = true;
  67070. }
  67071. }
  67072. bool LowLevelGraphicsPostScriptRenderer::clipToRectangle (const Rectangle<int>& r)
  67073. {
  67074. needToClip = true;
  67075. return stateStack.getLast()->clip.clipTo (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67076. }
  67077. bool LowLevelGraphicsPostScriptRenderer::clipToRectangleList (const RectangleList& clipRegion)
  67078. {
  67079. needToClip = true;
  67080. return stateStack.getLast()->clip.clipTo (clipRegion);
  67081. }
  67082. void LowLevelGraphicsPostScriptRenderer::excludeClipRectangle (const Rectangle<int>& r)
  67083. {
  67084. needToClip = true;
  67085. stateStack.getLast()->clip.subtract (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67086. }
  67087. void LowLevelGraphicsPostScriptRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  67088. {
  67089. writeClip();
  67090. Path p (path);
  67091. p.applyTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  67092. writePath (p);
  67093. out << "clip\n";
  67094. }
  67095. void LowLevelGraphicsPostScriptRenderer::clipToImageAlpha (const Image& /*sourceImage*/, const AffineTransform& /*transform*/)
  67096. {
  67097. needToClip = true;
  67098. jassertfalse; // xxx
  67099. }
  67100. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (const Rectangle<int>& r)
  67101. {
  67102. return stateStack.getLast()->clip.intersectsRectangle (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67103. }
  67104. const Rectangle<int> LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  67105. {
  67106. return stateStack.getLast()->clip.getBounds().translated (-stateStack.getLast()->xOffset,
  67107. -stateStack.getLast()->yOffset);
  67108. }
  67109. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  67110. {
  67111. return stateStack.getLast()->clip.isEmpty();
  67112. }
  67113. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState()
  67114. : xOffset (0),
  67115. yOffset (0)
  67116. {
  67117. }
  67118. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  67119. {
  67120. }
  67121. void LowLevelGraphicsPostScriptRenderer::saveState()
  67122. {
  67123. stateStack.add (new SavedState (*stateStack.getLast()));
  67124. }
  67125. void LowLevelGraphicsPostScriptRenderer::restoreState()
  67126. {
  67127. jassert (stateStack.size() > 0);
  67128. if (stateStack.size() > 0)
  67129. stateStack.removeLast();
  67130. }
  67131. void LowLevelGraphicsPostScriptRenderer::writeClip()
  67132. {
  67133. if (needToClip)
  67134. {
  67135. needToClip = false;
  67136. out << "doclip ";
  67137. int itemsOnLine = 0;
  67138. for (RectangleList::Iterator i (stateStack.getLast()->clip); i.next();)
  67139. {
  67140. if (++itemsOnLine == 6)
  67141. {
  67142. itemsOnLine = 0;
  67143. out << '\n';
  67144. }
  67145. const Rectangle<int>& r = *i.getRectangle();
  67146. out << r.getX() << ' ' << -r.getY() << ' '
  67147. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  67148. }
  67149. out << "endclip\n";
  67150. }
  67151. }
  67152. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  67153. {
  67154. Colour c (Colours::white.overlaidWith (colour));
  67155. if (lastColour != c)
  67156. {
  67157. lastColour = c;
  67158. out << String (c.getFloatRed(), 3) << ' '
  67159. << String (c.getFloatGreen(), 3) << ' '
  67160. << String (c.getFloatBlue(), 3) << " c\n";
  67161. }
  67162. }
  67163. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  67164. {
  67165. out << String (x, 2) << ' '
  67166. << String (-y, 2) << ' ';
  67167. }
  67168. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  67169. {
  67170. out << "newpath ";
  67171. float lastX = 0.0f;
  67172. float lastY = 0.0f;
  67173. int itemsOnLine = 0;
  67174. Path::Iterator i (path);
  67175. while (i.next())
  67176. {
  67177. if (++itemsOnLine == 4)
  67178. {
  67179. itemsOnLine = 0;
  67180. out << '\n';
  67181. }
  67182. switch (i.elementType)
  67183. {
  67184. case Path::Iterator::startNewSubPath:
  67185. writeXY (i.x1, i.y1);
  67186. lastX = i.x1;
  67187. lastY = i.y1;
  67188. out << "m ";
  67189. break;
  67190. case Path::Iterator::lineTo:
  67191. writeXY (i.x1, i.y1);
  67192. lastX = i.x1;
  67193. lastY = i.y1;
  67194. out << "l ";
  67195. break;
  67196. case Path::Iterator::quadraticTo:
  67197. {
  67198. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  67199. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  67200. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  67201. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  67202. writeXY (cp1x, cp1y);
  67203. writeXY (cp2x, cp2y);
  67204. writeXY (i.x2, i.y2);
  67205. out << "ct ";
  67206. lastX = i.x2;
  67207. lastY = i.y2;
  67208. }
  67209. break;
  67210. case Path::Iterator::cubicTo:
  67211. writeXY (i.x1, i.y1);
  67212. writeXY (i.x2, i.y2);
  67213. writeXY (i.x3, i.y3);
  67214. out << "ct ";
  67215. lastX = i.x3;
  67216. lastY = i.y3;
  67217. break;
  67218. case Path::Iterator::closePath:
  67219. out << "cp ";
  67220. break;
  67221. default:
  67222. jassertfalse;
  67223. break;
  67224. }
  67225. }
  67226. out << '\n';
  67227. }
  67228. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  67229. {
  67230. out << "[ "
  67231. << trans.mat00 << ' '
  67232. << trans.mat10 << ' '
  67233. << trans.mat01 << ' '
  67234. << trans.mat11 << ' '
  67235. << trans.mat02 << ' '
  67236. << trans.mat12 << " ] concat ";
  67237. }
  67238. void LowLevelGraphicsPostScriptRenderer::setFill (const FillType& fillType)
  67239. {
  67240. stateStack.getLast()->fillType = fillType;
  67241. }
  67242. void LowLevelGraphicsPostScriptRenderer::setOpacity (float /*opacity*/)
  67243. {
  67244. }
  67245. void LowLevelGraphicsPostScriptRenderer::setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  67246. {
  67247. }
  67248. void LowLevelGraphicsPostScriptRenderer::fillRect (const Rectangle<int>& r, const bool /*replaceExistingContents*/)
  67249. {
  67250. if (stateStack.getLast()->fillType.isColour())
  67251. {
  67252. writeClip();
  67253. writeColour (stateStack.getLast()->fillType.colour);
  67254. Rectangle<int> r2 (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67255. out << r2.getX() << ' ' << -r2.getBottom() << ' ' << r2.getWidth() << ' ' << r2.getHeight() << " rectfill\n";
  67256. }
  67257. else
  67258. {
  67259. Path p;
  67260. p.addRectangle (r);
  67261. fillPath (p, AffineTransform::identity);
  67262. }
  67263. }
  67264. void LowLevelGraphicsPostScriptRenderer::fillPath (const Path& path, const AffineTransform& t)
  67265. {
  67266. if (stateStack.getLast()->fillType.isColour())
  67267. {
  67268. writeClip();
  67269. Path p (path);
  67270. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset,
  67271. (float) stateStack.getLast()->yOffset));
  67272. writePath (p);
  67273. writeColour (stateStack.getLast()->fillType.colour);
  67274. out << "fill\n";
  67275. }
  67276. else if (stateStack.getLast()->fillType.isGradient())
  67277. {
  67278. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  67279. // postscript can't do semi-transparent ones.
  67280. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  67281. writeClip();
  67282. out << "gsave ";
  67283. {
  67284. Path p (path);
  67285. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  67286. writePath (p);
  67287. out << "clip\n";
  67288. }
  67289. const Rectangle<int> bounds (stateStack.getLast()->clip.getBounds());
  67290. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  67291. // time-being, this just fills it with the average colour..
  67292. writeColour (stateStack.getLast()->fillType.gradient->getColourAtPosition (0.5f));
  67293. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  67294. out << "grestore\n";
  67295. }
  67296. }
  67297. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  67298. const int sx, const int sy,
  67299. const int maxW, const int maxH) const
  67300. {
  67301. out << "{<\n";
  67302. const int w = jmin (maxW, im.getWidth());
  67303. const int h = jmin (maxH, im.getHeight());
  67304. int charsOnLine = 0;
  67305. const Image::BitmapData srcData (im, 0, 0, w, h);
  67306. Colour pixel;
  67307. for (int y = h; --y >= 0;)
  67308. {
  67309. for (int x = 0; x < w; ++x)
  67310. {
  67311. const uint8* pixelData = srcData.getPixelPointer (x, y);
  67312. if (x >= sx && y >= sy)
  67313. {
  67314. if (im.isARGB())
  67315. {
  67316. PixelARGB p (*(const PixelARGB*) pixelData);
  67317. p.unpremultiply();
  67318. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  67319. }
  67320. else if (im.isRGB())
  67321. {
  67322. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  67323. }
  67324. else
  67325. {
  67326. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  67327. }
  67328. }
  67329. else
  67330. {
  67331. pixel = Colours::transparentWhite;
  67332. }
  67333. const uint8 pixelValues[3] = { pixel.getRed(), pixel.getGreen(), pixel.getBlue() };
  67334. out << String::toHexString (pixelValues, 3, 0);
  67335. charsOnLine += 3;
  67336. if (charsOnLine > 100)
  67337. {
  67338. out << '\n';
  67339. charsOnLine = 0;
  67340. }
  67341. }
  67342. }
  67343. out << "\n>}\n";
  67344. }
  67345. void LowLevelGraphicsPostScriptRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool /*fillEntireClipAsTiles*/)
  67346. {
  67347. const int w = sourceImage.getWidth();
  67348. const int h = sourceImage.getHeight();
  67349. writeClip();
  67350. out << "gsave ";
  67351. writeTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset)
  67352. .scaled (1.0f, -1.0f));
  67353. RectangleList imageClip;
  67354. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  67355. out << "newpath ";
  67356. int itemsOnLine = 0;
  67357. for (RectangleList::Iterator i (imageClip); i.next();)
  67358. {
  67359. if (++itemsOnLine == 6)
  67360. {
  67361. out << '\n';
  67362. itemsOnLine = 0;
  67363. }
  67364. const Rectangle<int>& r = *i.getRectangle();
  67365. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  67366. }
  67367. out << " clip newpath\n";
  67368. out << w << ' ' << h << " scale\n";
  67369. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  67370. writeImage (sourceImage, 0, 0, w, h);
  67371. out << "false 3 colorimage grestore\n";
  67372. needToClip = true;
  67373. }
  67374. void LowLevelGraphicsPostScriptRenderer::drawLine (const Line <float>& line)
  67375. {
  67376. Path p;
  67377. p.addLineSegment (line, 1.0f);
  67378. fillPath (p, AffineTransform::identity);
  67379. }
  67380. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, float top, float bottom)
  67381. {
  67382. drawLine (Line<float> ((float) x, top, (float) x, bottom));
  67383. }
  67384. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, float left, float right)
  67385. {
  67386. drawLine (Line<float> (left, (float) y, right, (float) y));
  67387. }
  67388. void LowLevelGraphicsPostScriptRenderer::setFont (const Font& newFont)
  67389. {
  67390. stateStack.getLast()->font = newFont;
  67391. }
  67392. const Font LowLevelGraphicsPostScriptRenderer::getFont()
  67393. {
  67394. return stateStack.getLast()->font;
  67395. }
  67396. void LowLevelGraphicsPostScriptRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  67397. {
  67398. Path p;
  67399. Font& font = stateStack.getLast()->font;
  67400. font.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  67401. fillPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight()).followedBy (transform));
  67402. }
  67403. END_JUCE_NAMESPACE
  67404. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  67405. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  67406. BEGIN_JUCE_NAMESPACE
  67407. #if (JUCE_WINDOWS || JUCE_LINUX) && ! JUCE_64BIT
  67408. #define JUCE_USE_SSE_INSTRUCTIONS 1
  67409. #endif
  67410. #if JUCE_MSVC
  67411. #pragma warning (push)
  67412. #pragma warning (disable: 4127) // "expression is constant" warning
  67413. #if JUCE_DEBUG
  67414. #pragma optimize ("t", on) // optimise just this file, to avoid sluggish graphics when debugging
  67415. #pragma warning (disable: 4714) // warning about forcedinline methods not being inlined
  67416. #endif
  67417. #endif
  67418. namespace SoftwareRendererClasses
  67419. {
  67420. template <class PixelType, bool replaceExisting = false>
  67421. class SolidColourEdgeTableRenderer
  67422. {
  67423. public:
  67424. SolidColourEdgeTableRenderer (const Image::BitmapData& data_, const PixelARGB& colour)
  67425. : data (data_),
  67426. sourceColour (colour)
  67427. {
  67428. if (sizeof (PixelType) == 3)
  67429. {
  67430. areRGBComponentsEqual = sourceColour.getRed() == sourceColour.getGreen()
  67431. && sourceColour.getGreen() == sourceColour.getBlue();
  67432. filler[0].set (sourceColour);
  67433. filler[1].set (sourceColour);
  67434. filler[2].set (sourceColour);
  67435. filler[3].set (sourceColour);
  67436. }
  67437. }
  67438. forcedinline void setEdgeTableYPos (const int y) throw()
  67439. {
  67440. linePixels = (PixelType*) data.getLinePointer (y);
  67441. }
  67442. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67443. {
  67444. if (replaceExisting)
  67445. linePixels[x].set (sourceColour);
  67446. else
  67447. linePixels[x].blend (sourceColour, alphaLevel);
  67448. }
  67449. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67450. {
  67451. if (replaceExisting)
  67452. linePixels[x].set (sourceColour);
  67453. else
  67454. linePixels[x].blend (sourceColour);
  67455. }
  67456. forcedinline void handleEdgeTableLine (const int x, const int width, const int alphaLevel) const throw()
  67457. {
  67458. PixelARGB p (sourceColour);
  67459. p.multiplyAlpha (alphaLevel);
  67460. PixelType* dest = linePixels + x;
  67461. if (replaceExisting || p.getAlpha() >= 0xff)
  67462. replaceLine (dest, p, width);
  67463. else
  67464. blendLine (dest, p, width);
  67465. }
  67466. forcedinline void handleEdgeTableLineFull (const int x, const int width) const throw()
  67467. {
  67468. PixelType* dest = linePixels + x;
  67469. if (replaceExisting || sourceColour.getAlpha() >= 0xff)
  67470. replaceLine (dest, sourceColour, width);
  67471. else
  67472. blendLine (dest, sourceColour, width);
  67473. }
  67474. private:
  67475. const Image::BitmapData& data;
  67476. PixelType* linePixels;
  67477. PixelARGB sourceColour;
  67478. PixelRGB filler [4];
  67479. bool areRGBComponentsEqual;
  67480. inline void blendLine (PixelType* dest, const PixelARGB& colour, int width) const throw()
  67481. {
  67482. do
  67483. {
  67484. dest->blend (colour);
  67485. ++dest;
  67486. } while (--width > 0);
  67487. }
  67488. forcedinline void replaceLine (PixelRGB* dest, const PixelARGB& colour, int width) const throw()
  67489. {
  67490. if (areRGBComponentsEqual) // if all the component values are the same, we can cheat..
  67491. {
  67492. memset (dest, colour.getRed(), width * 3);
  67493. }
  67494. else
  67495. {
  67496. if (width >> 5)
  67497. {
  67498. const int* const intFiller = reinterpret_cast<const int*> (filler);
  67499. while (width > 8 && (((pointer_sized_int) dest) & 7) != 0)
  67500. {
  67501. dest->set (colour);
  67502. ++dest;
  67503. --width;
  67504. }
  67505. while (width > 4)
  67506. {
  67507. int* d = reinterpret_cast<int*> (dest);
  67508. *d++ = intFiller[0];
  67509. *d++ = intFiller[1];
  67510. *d++ = intFiller[2];
  67511. dest = reinterpret_cast<PixelRGB*> (d);
  67512. width -= 4;
  67513. }
  67514. }
  67515. while (--width >= 0)
  67516. {
  67517. dest->set (colour);
  67518. ++dest;
  67519. }
  67520. }
  67521. }
  67522. forcedinline void replaceLine (PixelAlpha* const dest, const PixelARGB& colour, int const width) const throw()
  67523. {
  67524. memset (dest, colour.getAlpha(), width);
  67525. }
  67526. forcedinline void replaceLine (PixelARGB* dest, const PixelARGB& colour, int width) const throw()
  67527. {
  67528. do
  67529. {
  67530. dest->set (colour);
  67531. ++dest;
  67532. } while (--width > 0);
  67533. }
  67534. SolidColourEdgeTableRenderer (const SolidColourEdgeTableRenderer&);
  67535. SolidColourEdgeTableRenderer& operator= (const SolidColourEdgeTableRenderer&);
  67536. };
  67537. class LinearGradientPixelGenerator
  67538. {
  67539. public:
  67540. LinearGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform, const PixelARGB* const lookupTable_, const int numEntries_)
  67541. : lookupTable (lookupTable_), numEntries (numEntries_)
  67542. {
  67543. jassert (numEntries_ >= 0);
  67544. Point<float> p1 (gradient.point1);
  67545. Point<float> p2 (gradient.point2);
  67546. if (! transform.isIdentity())
  67547. {
  67548. const Line<float> l (p2, p1);
  67549. Point<float> p3 = l.getPointAlongLine (0.0f, 100.0f);
  67550. p1.applyTransform (transform);
  67551. p2.applyTransform (transform);
  67552. p3.applyTransform (transform);
  67553. p2 = Line<float> (p2, p3).findNearestPointTo (p1);
  67554. }
  67555. vertical = std::abs (p1.getX() - p2.getX()) < 0.001f;
  67556. horizontal = std::abs (p1.getY() - p2.getY()) < 0.001f;
  67557. if (vertical)
  67558. {
  67559. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getY() - p1.getY()));
  67560. start = roundToInt (p1.getY() * scale);
  67561. }
  67562. else if (horizontal)
  67563. {
  67564. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getX() - p1.getX()));
  67565. start = roundToInt (p1.getX() * scale);
  67566. }
  67567. else
  67568. {
  67569. grad = (p2.getY() - p1.getY()) / (double) (p1.getX() - p2.getX());
  67570. yTerm = p1.getY() - p1.getX() / grad;
  67571. scale = roundToInt ((numEntries << (int) numScaleBits) / (yTerm * grad - (p2.getY() * grad - p2.getX())));
  67572. grad *= scale;
  67573. }
  67574. }
  67575. forcedinline void setY (const int y) throw()
  67576. {
  67577. if (vertical)
  67578. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> (int) numScaleBits)];
  67579. else if (! horizontal)
  67580. start = roundToInt ((y - yTerm) * grad);
  67581. }
  67582. inline const PixelARGB getPixel (const int x) const throw()
  67583. {
  67584. return vertical ? linePix
  67585. : lookupTable [jlimit (0, numEntries, (x * scale - start) >> (int) numScaleBits)];
  67586. }
  67587. private:
  67588. const PixelARGB* const lookupTable;
  67589. const int numEntries;
  67590. PixelARGB linePix;
  67591. int start, scale;
  67592. double grad, yTerm;
  67593. bool vertical, horizontal;
  67594. enum { numScaleBits = 12 };
  67595. LinearGradientPixelGenerator (const LinearGradientPixelGenerator&);
  67596. LinearGradientPixelGenerator& operator= (const LinearGradientPixelGenerator&);
  67597. };
  67598. class RadialGradientPixelGenerator
  67599. {
  67600. public:
  67601. RadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform&,
  67602. const PixelARGB* const lookupTable_, const int numEntries_)
  67603. : lookupTable (lookupTable_),
  67604. numEntries (numEntries_),
  67605. gx1 (gradient.point1.getX()),
  67606. gy1 (gradient.point1.getY())
  67607. {
  67608. jassert (numEntries_ >= 0);
  67609. const Point<float> diff (gradient.point1 - gradient.point2);
  67610. maxDist = diff.getX() * diff.getX() + diff.getY() * diff.getY();
  67611. invScale = numEntries / std::sqrt (maxDist);
  67612. jassert (roundToInt (std::sqrt (maxDist) * invScale) <= numEntries);
  67613. }
  67614. forcedinline void setY (const int y) throw()
  67615. {
  67616. dy = y - gy1;
  67617. dy *= dy;
  67618. }
  67619. inline const PixelARGB getPixel (const int px) const throw()
  67620. {
  67621. double x = px - gx1;
  67622. x *= x;
  67623. x += dy;
  67624. return lookupTable [x >= maxDist ? numEntries : roundToInt (std::sqrt (x) * invScale)];
  67625. }
  67626. protected:
  67627. const PixelARGB* const lookupTable;
  67628. const int numEntries;
  67629. const double gx1, gy1;
  67630. double maxDist, invScale, dy;
  67631. RadialGradientPixelGenerator (const RadialGradientPixelGenerator&);
  67632. RadialGradientPixelGenerator& operator= (const RadialGradientPixelGenerator&);
  67633. };
  67634. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  67635. {
  67636. public:
  67637. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform,
  67638. const PixelARGB* const lookupTable_, const int numEntries_)
  67639. : RadialGradientPixelGenerator (gradient, transform, lookupTable_, numEntries_),
  67640. inverseTransform (transform.inverted())
  67641. {
  67642. tM10 = inverseTransform.mat10;
  67643. tM00 = inverseTransform.mat00;
  67644. }
  67645. forcedinline void setY (const int y) throw()
  67646. {
  67647. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  67648. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  67649. }
  67650. inline const PixelARGB getPixel (const int px) const throw()
  67651. {
  67652. double x = px;
  67653. const double y = tM10 * x + lineYM11;
  67654. x = tM00 * x + lineYM01;
  67655. x *= x;
  67656. x += y * y;
  67657. if (x >= maxDist)
  67658. return lookupTable [numEntries];
  67659. else
  67660. return lookupTable [jmin (numEntries, roundToInt (std::sqrt (x) * invScale))];
  67661. }
  67662. private:
  67663. double tM10, tM00, lineYM01, lineYM11;
  67664. const AffineTransform inverseTransform;
  67665. TransformedRadialGradientPixelGenerator (const TransformedRadialGradientPixelGenerator&);
  67666. TransformedRadialGradientPixelGenerator& operator= (const TransformedRadialGradientPixelGenerator&);
  67667. };
  67668. template <class PixelType, class GradientType>
  67669. class GradientEdgeTableRenderer : public GradientType
  67670. {
  67671. public:
  67672. GradientEdgeTableRenderer (const Image::BitmapData& destData_, const ColourGradient& gradient, const AffineTransform& transform,
  67673. const PixelARGB* const lookupTable_, const int numEntries_)
  67674. : GradientType (gradient, transform, lookupTable_, numEntries_ - 1),
  67675. destData (destData_)
  67676. {
  67677. }
  67678. forcedinline void setEdgeTableYPos (const int y) throw()
  67679. {
  67680. linePixels = (PixelType*) destData.getLinePointer (y);
  67681. GradientType::setY (y);
  67682. }
  67683. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67684. {
  67685. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  67686. }
  67687. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67688. {
  67689. linePixels[x].blend (GradientType::getPixel (x));
  67690. }
  67691. void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  67692. {
  67693. PixelType* dest = linePixels + x;
  67694. if (alphaLevel < 0xff)
  67695. {
  67696. do
  67697. {
  67698. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  67699. } while (--width > 0);
  67700. }
  67701. else
  67702. {
  67703. do
  67704. {
  67705. (dest++)->blend (GradientType::getPixel (x++));
  67706. } while (--width > 0);
  67707. }
  67708. }
  67709. void handleEdgeTableLineFull (int x, int width) const throw()
  67710. {
  67711. PixelType* dest = linePixels + x;
  67712. do
  67713. {
  67714. (dest++)->blend (GradientType::getPixel (x++));
  67715. } while (--width > 0);
  67716. }
  67717. private:
  67718. const Image::BitmapData& destData;
  67719. PixelType* linePixels;
  67720. GradientEdgeTableRenderer (const GradientEdgeTableRenderer&);
  67721. GradientEdgeTableRenderer& operator= (const GradientEdgeTableRenderer&);
  67722. };
  67723. static forcedinline int safeModulo (int n, const int divisor) throw()
  67724. {
  67725. jassert (divisor > 0);
  67726. n %= divisor;
  67727. return (n < 0) ? (n + divisor) : n;
  67728. }
  67729. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67730. class ImageFillEdgeTableRenderer
  67731. {
  67732. public:
  67733. ImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67734. const Image::BitmapData& srcData_,
  67735. const int extraAlpha_,
  67736. const int x, const int y)
  67737. : destData (destData_),
  67738. srcData (srcData_),
  67739. extraAlpha (extraAlpha_ + 1),
  67740. xOffset (repeatPattern ? safeModulo (x, srcData_.width) - srcData_.width : x),
  67741. yOffset (repeatPattern ? safeModulo (y, srcData_.height) - srcData_.height : y)
  67742. {
  67743. }
  67744. forcedinline void setEdgeTableYPos (int y) throw()
  67745. {
  67746. linePixels = (DestPixelType*) destData.getLinePointer (y);
  67747. y -= yOffset;
  67748. if (repeatPattern)
  67749. {
  67750. jassert (y >= 0);
  67751. y %= srcData.height;
  67752. }
  67753. sourceLineStart = (SrcPixelType*) srcData.getLinePointer (y);
  67754. }
  67755. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  67756. {
  67757. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67758. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], alphaLevel);
  67759. }
  67760. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67761. {
  67762. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], extraAlpha);
  67763. }
  67764. void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  67765. {
  67766. DestPixelType* dest = linePixels + x;
  67767. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67768. x -= xOffset;
  67769. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67770. if (alphaLevel < 0xfe)
  67771. {
  67772. do
  67773. {
  67774. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], alphaLevel);
  67775. } while (--width > 0);
  67776. }
  67777. else
  67778. {
  67779. if (repeatPattern)
  67780. {
  67781. do
  67782. {
  67783. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67784. } while (--width > 0);
  67785. }
  67786. else
  67787. {
  67788. copyRow (dest, sourceLineStart + x, width);
  67789. }
  67790. }
  67791. }
  67792. void handleEdgeTableLineFull (int x, int width) const throw()
  67793. {
  67794. DestPixelType* dest = linePixels + x;
  67795. x -= xOffset;
  67796. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67797. if (extraAlpha < 0xfe)
  67798. {
  67799. do
  67800. {
  67801. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], extraAlpha);
  67802. } while (--width > 0);
  67803. }
  67804. else
  67805. {
  67806. if (repeatPattern)
  67807. {
  67808. do
  67809. {
  67810. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67811. } while (--width > 0);
  67812. }
  67813. else
  67814. {
  67815. copyRow (dest, sourceLineStart + x, width);
  67816. }
  67817. }
  67818. }
  67819. void clipEdgeTableLine (EdgeTable& et, int x, int y, int width)
  67820. {
  67821. jassert (x - xOffset >= 0 && x + width - xOffset <= srcData.width);
  67822. SrcPixelType* s = (SrcPixelType*) srcData.getLinePointer (y - yOffset);
  67823. uint8* mask = (uint8*) (s + x - xOffset);
  67824. if (sizeof (SrcPixelType) == sizeof (PixelARGB))
  67825. mask += PixelARGB::indexA;
  67826. et.clipLineToMask (x, y, mask, sizeof (SrcPixelType), width);
  67827. }
  67828. private:
  67829. const Image::BitmapData& destData;
  67830. const Image::BitmapData& srcData;
  67831. const int extraAlpha, xOffset, yOffset;
  67832. DestPixelType* linePixels;
  67833. SrcPixelType* sourceLineStart;
  67834. template <class PixelType1, class PixelType2>
  67835. forcedinline static void copyRow (PixelType1* dest, PixelType2* src, int width) throw()
  67836. {
  67837. do
  67838. {
  67839. dest++ ->blend (*src++);
  67840. } while (--width > 0);
  67841. }
  67842. forcedinline static void copyRow (PixelRGB* dest, PixelRGB* src, int width) throw()
  67843. {
  67844. memcpy (dest, src, width * sizeof (PixelRGB));
  67845. }
  67846. ImageFillEdgeTableRenderer (const ImageFillEdgeTableRenderer&);
  67847. ImageFillEdgeTableRenderer& operator= (const ImageFillEdgeTableRenderer&);
  67848. };
  67849. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67850. class TransformedImageFillEdgeTableRenderer
  67851. {
  67852. public:
  67853. TransformedImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67854. const Image::BitmapData& srcData_,
  67855. const AffineTransform& transform,
  67856. const int extraAlpha_,
  67857. const bool betterQuality_)
  67858. : interpolator (transform),
  67859. destData (destData_),
  67860. srcData (srcData_),
  67861. extraAlpha (extraAlpha_ + 1),
  67862. betterQuality (betterQuality_),
  67863. pixelOffset (betterQuality_ ? 0.5f : 0.0f),
  67864. pixelOffsetInt (betterQuality_ ? -128 : 0),
  67865. maxX (srcData_.width - 1),
  67866. maxY (srcData_.height - 1),
  67867. scratchSize (2048)
  67868. {
  67869. scratchBuffer.malloc (scratchSize);
  67870. }
  67871. ~TransformedImageFillEdgeTableRenderer()
  67872. {
  67873. }
  67874. forcedinline void setEdgeTableYPos (const int newY) throw()
  67875. {
  67876. y = newY;
  67877. linePixels = (DestPixelType*) destData.getLinePointer (newY);
  67878. }
  67879. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) throw()
  67880. {
  67881. alphaLevel *= extraAlpha;
  67882. alphaLevel >>= 8;
  67883. SrcPixelType p;
  67884. generate (&p, x, 1);
  67885. linePixels[x].blend (p, alphaLevel);
  67886. }
  67887. forcedinline void handleEdgeTablePixelFull (const int x) throw()
  67888. {
  67889. SrcPixelType p;
  67890. generate (&p, x, 1);
  67891. linePixels[x].blend (p, extraAlpha);
  67892. }
  67893. void handleEdgeTableLine (const int x, int width, int alphaLevel) throw()
  67894. {
  67895. if (width > scratchSize)
  67896. {
  67897. scratchSize = width;
  67898. scratchBuffer.malloc (scratchSize);
  67899. }
  67900. SrcPixelType* span = scratchBuffer;
  67901. generate (span, x, width);
  67902. DestPixelType* dest = linePixels + x;
  67903. alphaLevel *= extraAlpha;
  67904. alphaLevel >>= 8;
  67905. if (alphaLevel < 0xfe)
  67906. {
  67907. do
  67908. {
  67909. dest++ ->blend (*span++, alphaLevel);
  67910. } while (--width > 0);
  67911. }
  67912. else
  67913. {
  67914. do
  67915. {
  67916. dest++ ->blend (*span++);
  67917. } while (--width > 0);
  67918. }
  67919. }
  67920. forcedinline void handleEdgeTableLineFull (const int x, int width) throw()
  67921. {
  67922. handleEdgeTableLine (x, width, 255);
  67923. }
  67924. void clipEdgeTableLine (EdgeTable& et, int x, int y_, int width)
  67925. {
  67926. if (width > scratchSize)
  67927. {
  67928. scratchSize = width;
  67929. scratchBuffer.malloc (scratchSize);
  67930. }
  67931. y = y_;
  67932. generate (scratchBuffer, x, width);
  67933. et.clipLineToMask (x, y_,
  67934. reinterpret_cast<uint8*> (scratchBuffer.getData()) + SrcPixelType::indexA,
  67935. sizeof (SrcPixelType), width);
  67936. }
  67937. private:
  67938. void generate (PixelARGB* dest, const int x, int numPixels) throw()
  67939. {
  67940. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  67941. do
  67942. {
  67943. int hiResX, hiResY;
  67944. this->interpolator.next (hiResX, hiResY);
  67945. hiResX += pixelOffsetInt;
  67946. hiResY += pixelOffsetInt;
  67947. int loResX = hiResX >> 8;
  67948. int loResY = hiResY >> 8;
  67949. if (repeatPattern)
  67950. {
  67951. loResX = safeModulo (loResX, srcData.width);
  67952. loResY = safeModulo (loResY, srcData.height);
  67953. }
  67954. if (betterQuality
  67955. && ((unsigned int) loResX) < (unsigned int) maxX
  67956. && ((unsigned int) loResY) < (unsigned int) maxY)
  67957. {
  67958. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  67959. hiResX &= 255;
  67960. hiResY &= 255;
  67961. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  67962. uint32 weight = (256 - hiResX) * (256 - hiResY);
  67963. c[0] += weight * src[0];
  67964. c[1] += weight * src[1];
  67965. c[2] += weight * src[2];
  67966. c[3] += weight * src[3];
  67967. weight = hiResX * (256 - hiResY);
  67968. c[0] += weight * src[4];
  67969. c[1] += weight * src[5];
  67970. c[2] += weight * src[6];
  67971. c[3] += weight * src[7];
  67972. src += this->srcData.lineStride;
  67973. weight = (256 - hiResX) * hiResY;
  67974. c[0] += weight * src[0];
  67975. c[1] += weight * src[1];
  67976. c[2] += weight * src[2];
  67977. c[3] += weight * src[3];
  67978. weight = hiResX * hiResY;
  67979. c[0] += weight * src[4];
  67980. c[1] += weight * src[5];
  67981. c[2] += weight * src[6];
  67982. c[3] += weight * src[7];
  67983. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  67984. (uint8) (c[PixelARGB::indexR] >> 16),
  67985. (uint8) (c[PixelARGB::indexG] >> 16),
  67986. (uint8) (c[PixelARGB::indexB] >> 16));
  67987. }
  67988. else
  67989. {
  67990. if (! repeatPattern)
  67991. {
  67992. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  67993. if (loResX < 0) loResX = 0;
  67994. if (loResY < 0) loResY = 0;
  67995. if (loResX > maxX) loResX = maxX;
  67996. if (loResY > maxY) loResY = maxY;
  67997. }
  67998. dest->set (*(const PixelARGB*) this->srcData.getPixelPointer (loResX, loResY));
  67999. }
  68000. ++dest;
  68001. } while (--numPixels > 0);
  68002. }
  68003. void generate (PixelRGB* dest, const int x, int numPixels) throw()
  68004. {
  68005. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  68006. do
  68007. {
  68008. int hiResX, hiResY;
  68009. this->interpolator.next (hiResX, hiResY);
  68010. hiResX += pixelOffsetInt;
  68011. hiResY += pixelOffsetInt;
  68012. int loResX = hiResX >> 8;
  68013. int loResY = hiResY >> 8;
  68014. if (repeatPattern)
  68015. {
  68016. loResX = safeModulo (loResX, srcData.width);
  68017. loResY = safeModulo (loResY, srcData.height);
  68018. }
  68019. if (betterQuality
  68020. && ((unsigned int) loResX) < (unsigned int) maxX
  68021. && ((unsigned int) loResY) < (unsigned int) maxY)
  68022. {
  68023. uint32 c[3] = { 256 * 128, 256 * 128, 256 * 128 };
  68024. hiResX &= 255;
  68025. hiResY &= 255;
  68026. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  68027. unsigned int weight = (256 - hiResX) * (256 - hiResY);
  68028. c[0] += weight * src[0];
  68029. c[1] += weight * src[1];
  68030. c[2] += weight * src[2];
  68031. weight = hiResX * (256 - hiResY);
  68032. c[0] += weight * src[3];
  68033. c[1] += weight * src[4];
  68034. c[2] += weight * src[5];
  68035. src += this->srcData.lineStride;
  68036. weight = (256 - hiResX) * hiResY;
  68037. c[0] += weight * src[0];
  68038. c[1] += weight * src[1];
  68039. c[2] += weight * src[2];
  68040. weight = hiResX * hiResY;
  68041. c[0] += weight * src[3];
  68042. c[1] += weight * src[4];
  68043. c[2] += weight * src[5];
  68044. dest->setARGB ((uint8) 255,
  68045. (uint8) (c[PixelRGB::indexR] >> 16),
  68046. (uint8) (c[PixelRGB::indexG] >> 16),
  68047. (uint8) (c[PixelRGB::indexB] >> 16));
  68048. }
  68049. else
  68050. {
  68051. if (! repeatPattern)
  68052. {
  68053. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  68054. if (loResX < 0) loResX = 0;
  68055. if (loResY < 0) loResY = 0;
  68056. if (loResX > maxX) loResX = maxX;
  68057. if (loResY > maxY) loResY = maxY;
  68058. }
  68059. dest->set (*(const PixelRGB*) this->srcData.getPixelPointer (loResX, loResY));
  68060. }
  68061. ++dest;
  68062. } while (--numPixels > 0);
  68063. }
  68064. void generate (PixelAlpha* dest, const int x, int numPixels) throw()
  68065. {
  68066. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  68067. do
  68068. {
  68069. int hiResX, hiResY;
  68070. this->interpolator.next (hiResX, hiResY);
  68071. hiResX += pixelOffsetInt;
  68072. hiResY += pixelOffsetInt;
  68073. int loResX = hiResX >> 8;
  68074. int loResY = hiResY >> 8;
  68075. if (repeatPattern)
  68076. {
  68077. loResX = safeModulo (loResX, srcData.width);
  68078. loResY = safeModulo (loResY, srcData.height);
  68079. }
  68080. if (betterQuality
  68081. && ((unsigned int) loResX) < (unsigned int) maxX
  68082. && ((unsigned int) loResY) < (unsigned int) maxY)
  68083. {
  68084. hiResX &= 255;
  68085. hiResY &= 255;
  68086. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  68087. uint32 c = 256 * 128;
  68088. c += src[0] * ((256 - hiResX) * (256 - hiResY));
  68089. c += src[1] * (hiResX * (256 - hiResY));
  68090. src += this->srcData.lineStride;
  68091. c += src[0] * ((256 - hiResX) * hiResY);
  68092. c += src[1] * (hiResX * hiResY);
  68093. *((uint8*) dest) = (uint8) c;
  68094. }
  68095. else
  68096. {
  68097. if (! repeatPattern)
  68098. {
  68099. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  68100. if (loResX < 0) loResX = 0;
  68101. if (loResY < 0) loResY = 0;
  68102. if (loResX > maxX) loResX = maxX;
  68103. if (loResY > maxY) loResY = maxY;
  68104. }
  68105. *((uint8*) dest) = *(this->srcData.getPixelPointer (loResX, loResY));
  68106. }
  68107. ++dest;
  68108. } while (--numPixels > 0);
  68109. }
  68110. class TransformedImageSpanInterpolator
  68111. {
  68112. public:
  68113. TransformedImageSpanInterpolator (const AffineTransform& transform) throw()
  68114. : inverseTransform (transform.inverted())
  68115. {}
  68116. void setStartOfLine (float x, float y, const int numPixels) throw()
  68117. {
  68118. float x1 = x, y1 = y;
  68119. x += numPixels;
  68120. inverseTransform.transformPoints (x1, y1, x, y);
  68121. xBresenham.set ((int) (x1 * 256.0f), (int) (x * 256.0f), numPixels);
  68122. yBresenham.set ((int) (y1 * 256.0f), (int) (y * 256.0f), numPixels);
  68123. }
  68124. void next (int& x, int& y) throw()
  68125. {
  68126. x = xBresenham.n;
  68127. xBresenham.stepToNext();
  68128. y = yBresenham.n;
  68129. yBresenham.stepToNext();
  68130. }
  68131. private:
  68132. class BresenhamInterpolator
  68133. {
  68134. public:
  68135. BresenhamInterpolator() throw() {}
  68136. void set (const int n1, const int n2, const int numSteps_) throw()
  68137. {
  68138. numSteps = jmax (1, numSteps_);
  68139. step = (n2 - n1) / numSteps;
  68140. remainder = modulo = (n2 - n1) % numSteps;
  68141. n = n1;
  68142. if (modulo <= 0)
  68143. {
  68144. modulo += numSteps;
  68145. remainder += numSteps;
  68146. --step;
  68147. }
  68148. modulo -= numSteps;
  68149. }
  68150. forcedinline void stepToNext() throw()
  68151. {
  68152. modulo += remainder;
  68153. n += step;
  68154. if (modulo > 0)
  68155. {
  68156. modulo -= numSteps;
  68157. ++n;
  68158. }
  68159. }
  68160. int n;
  68161. private:
  68162. int numSteps, step, modulo, remainder;
  68163. };
  68164. const AffineTransform inverseTransform;
  68165. BresenhamInterpolator xBresenham, yBresenham;
  68166. TransformedImageSpanInterpolator (const TransformedImageSpanInterpolator&);
  68167. TransformedImageSpanInterpolator& operator= (const TransformedImageSpanInterpolator&);
  68168. };
  68169. TransformedImageSpanInterpolator interpolator;
  68170. const Image::BitmapData& destData;
  68171. const Image::BitmapData& srcData;
  68172. const int extraAlpha;
  68173. const bool betterQuality;
  68174. const float pixelOffset;
  68175. const int pixelOffsetInt, maxX, maxY;
  68176. int y;
  68177. DestPixelType* linePixels;
  68178. HeapBlock <SrcPixelType> scratchBuffer;
  68179. int scratchSize;
  68180. TransformedImageFillEdgeTableRenderer (const TransformedImageFillEdgeTableRenderer&);
  68181. TransformedImageFillEdgeTableRenderer& operator= (const TransformedImageFillEdgeTableRenderer&);
  68182. };
  68183. class ClipRegionBase : public ReferenceCountedObject
  68184. {
  68185. public:
  68186. ClipRegionBase() {}
  68187. virtual ~ClipRegionBase() {}
  68188. typedef ReferenceCountedObjectPtr<ClipRegionBase> Ptr;
  68189. virtual const Ptr clone() const = 0;
  68190. virtual const Ptr applyClipTo (const Ptr& target) const = 0;
  68191. virtual const Ptr clipToRectangle (const Rectangle<int>& r) = 0;
  68192. virtual const Ptr clipToRectangleList (const RectangleList& r) = 0;
  68193. virtual const Ptr excludeClipRectangle (const Rectangle<int>& r) = 0;
  68194. virtual const Ptr clipToPath (const Path& p, const AffineTransform& transform) = 0;
  68195. virtual const Ptr clipToEdgeTable (const EdgeTable& et) = 0;
  68196. virtual const Ptr clipToImageAlpha (const Image& image, const AffineTransform& t, const bool betterQuality) = 0;
  68197. virtual bool clipRegionIntersects (const Rectangle<int>& r) const = 0;
  68198. virtual const Rectangle<int> getClipBounds() const = 0;
  68199. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const = 0;
  68200. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const = 0;
  68201. virtual void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const = 0;
  68202. virtual void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const = 0;
  68203. virtual void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& t, bool betterQuality, bool tiledFill) const = 0;
  68204. virtual void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const = 0;
  68205. protected:
  68206. template <class Iterator>
  68207. static void renderImageTransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData,
  68208. const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill)
  68209. {
  68210. switch (destData.pixelFormat)
  68211. {
  68212. case Image::ARGB:
  68213. switch (srcData.pixelFormat)
  68214. {
  68215. case Image::ARGB:
  68216. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68217. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68218. break;
  68219. case Image::RGB:
  68220. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68221. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68222. break;
  68223. default:
  68224. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68225. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68226. break;
  68227. }
  68228. break;
  68229. case Image::RGB:
  68230. switch (srcData.pixelFormat)
  68231. {
  68232. case Image::ARGB:
  68233. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68234. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68235. break;
  68236. case Image::RGB:
  68237. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68238. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68239. break;
  68240. default:
  68241. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68242. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68243. break;
  68244. }
  68245. break;
  68246. default:
  68247. switch (srcData.pixelFormat)
  68248. {
  68249. case Image::ARGB:
  68250. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68251. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68252. break;
  68253. case Image::RGB:
  68254. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68255. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68256. break;
  68257. default:
  68258. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68259. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68260. break;
  68261. }
  68262. break;
  68263. }
  68264. }
  68265. template <class Iterator>
  68266. static void renderImageUntransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill)
  68267. {
  68268. switch (destData.pixelFormat)
  68269. {
  68270. case Image::ARGB:
  68271. switch (srcData.pixelFormat)
  68272. {
  68273. case Image::ARGB:
  68274. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68275. else { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68276. break;
  68277. case Image::RGB:
  68278. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68279. else { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68280. break;
  68281. default:
  68282. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68283. else { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68284. break;
  68285. }
  68286. break;
  68287. case Image::RGB:
  68288. switch (srcData.pixelFormat)
  68289. {
  68290. case Image::ARGB:
  68291. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68292. else { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68293. break;
  68294. case Image::RGB:
  68295. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68296. else { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68297. break;
  68298. default:
  68299. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68300. else { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68301. break;
  68302. }
  68303. break;
  68304. default:
  68305. switch (srcData.pixelFormat)
  68306. {
  68307. case Image::ARGB:
  68308. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68309. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68310. break;
  68311. case Image::RGB:
  68312. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68313. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68314. break;
  68315. default:
  68316. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68317. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68318. break;
  68319. }
  68320. break;
  68321. }
  68322. }
  68323. template <class Iterator, class DestPixelType>
  68324. static void renderSolidFill (Iterator& iter, const Image::BitmapData& destData, const PixelARGB& fillColour, const bool replaceContents, DestPixelType*)
  68325. {
  68326. jassert (destData.pixelStride == sizeof (DestPixelType));
  68327. if (replaceContents)
  68328. {
  68329. SolidColourEdgeTableRenderer <DestPixelType, true> r (destData, fillColour);
  68330. iter.iterate (r);
  68331. }
  68332. else
  68333. {
  68334. SolidColourEdgeTableRenderer <DestPixelType, false> r (destData, fillColour);
  68335. iter.iterate (r);
  68336. }
  68337. }
  68338. template <class Iterator, class DestPixelType>
  68339. static void renderGradient (Iterator& iter, const Image::BitmapData& destData, const ColourGradient& g, const AffineTransform& transform,
  68340. const PixelARGB* const lookupTable, const int numLookupEntries, const bool isIdentity, DestPixelType*)
  68341. {
  68342. jassert (destData.pixelStride == sizeof (DestPixelType));
  68343. if (g.isRadial)
  68344. {
  68345. if (isIdentity)
  68346. {
  68347. GradientEdgeTableRenderer <DestPixelType, RadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68348. iter.iterate (renderer);
  68349. }
  68350. else
  68351. {
  68352. GradientEdgeTableRenderer <DestPixelType, TransformedRadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68353. iter.iterate (renderer);
  68354. }
  68355. }
  68356. else
  68357. {
  68358. GradientEdgeTableRenderer <DestPixelType, LinearGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68359. iter.iterate (renderer);
  68360. }
  68361. }
  68362. };
  68363. class ClipRegion_EdgeTable : public ClipRegionBase
  68364. {
  68365. public:
  68366. ClipRegion_EdgeTable (const EdgeTable& e) : edgeTable (e) {}
  68367. ClipRegion_EdgeTable (const Rectangle<int>& r) : edgeTable (r) {}
  68368. ClipRegion_EdgeTable (const Rectangle<float>& r) : edgeTable (r) {}
  68369. ClipRegion_EdgeTable (const RectangleList& r) : edgeTable (r) {}
  68370. ClipRegion_EdgeTable (const Rectangle<int>& bounds, const Path& p, const AffineTransform& t) : edgeTable (bounds, p, t) {}
  68371. ClipRegion_EdgeTable (const ClipRegion_EdgeTable& other) : edgeTable (other.edgeTable) {}
  68372. ~ClipRegion_EdgeTable() {}
  68373. const Ptr clone() const
  68374. {
  68375. return new ClipRegion_EdgeTable (*this);
  68376. }
  68377. const Ptr applyClipTo (const Ptr& target) const
  68378. {
  68379. return target->clipToEdgeTable (edgeTable);
  68380. }
  68381. const Ptr clipToRectangle (const Rectangle<int>& r)
  68382. {
  68383. edgeTable.clipToRectangle (r);
  68384. return edgeTable.isEmpty() ? 0 : this;
  68385. }
  68386. const Ptr clipToRectangleList (const RectangleList& r)
  68387. {
  68388. RectangleList inverse (edgeTable.getMaximumBounds());
  68389. if (inverse.subtract (r))
  68390. for (RectangleList::Iterator iter (inverse); iter.next();)
  68391. edgeTable.excludeRectangle (*iter.getRectangle());
  68392. return edgeTable.isEmpty() ? 0 : this;
  68393. }
  68394. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68395. {
  68396. edgeTable.excludeRectangle (r);
  68397. return edgeTable.isEmpty() ? 0 : this;
  68398. }
  68399. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68400. {
  68401. EdgeTable et (edgeTable.getMaximumBounds(), p, transform);
  68402. edgeTable.clipToEdgeTable (et);
  68403. return edgeTable.isEmpty() ? 0 : this;
  68404. }
  68405. const Ptr clipToEdgeTable (const EdgeTable& et)
  68406. {
  68407. edgeTable.clipToEdgeTable (et);
  68408. return edgeTable.isEmpty() ? 0 : this;
  68409. }
  68410. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68411. {
  68412. const Image::BitmapData srcData (image, false);
  68413. if (transform.isOnlyTranslation())
  68414. {
  68415. // If our translation doesn't involve any distortion, just use a simple blit..
  68416. const int tx = (int) (transform.getTranslationX() * 256.0f);
  68417. const int ty = (int) (transform.getTranslationY() * 256.0f);
  68418. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  68419. {
  68420. const int imageX = ((tx + 128) >> 8);
  68421. const int imageY = ((ty + 128) >> 8);
  68422. if (image.getFormat() == Image::ARGB)
  68423. straightClipImage (srcData, imageX, imageY, (PixelARGB*) 0);
  68424. else
  68425. straightClipImage (srcData, imageX, imageY, (PixelAlpha*) 0);
  68426. return edgeTable.isEmpty() ? 0 : this;
  68427. }
  68428. }
  68429. if (transform.isSingularity())
  68430. return 0;
  68431. {
  68432. Path p;
  68433. p.addRectangle (0, 0, (float) srcData.width, (float) srcData.height);
  68434. EdgeTable et2 (edgeTable.getMaximumBounds(), p, transform);
  68435. edgeTable.clipToEdgeTable (et2);
  68436. }
  68437. if (! edgeTable.isEmpty())
  68438. {
  68439. if (image.getFormat() == Image::ARGB)
  68440. transformedClipImage (srcData, transform, betterQuality, (PixelARGB*) 0);
  68441. else
  68442. transformedClipImage (srcData, transform, betterQuality, (PixelAlpha*) 0);
  68443. }
  68444. return edgeTable.isEmpty() ? 0 : this;
  68445. }
  68446. bool clipRegionIntersects (const Rectangle<int>& r) const
  68447. {
  68448. return edgeTable.getMaximumBounds().intersects (r);
  68449. }
  68450. const Rectangle<int> getClipBounds() const
  68451. {
  68452. return edgeTable.getMaximumBounds();
  68453. }
  68454. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68455. {
  68456. const Rectangle<int> totalClip (edgeTable.getMaximumBounds());
  68457. const Rectangle<int> clipped (totalClip.getIntersection (area));
  68458. if (! clipped.isEmpty())
  68459. {
  68460. ClipRegion_EdgeTable et (clipped);
  68461. et.edgeTable.clipToEdgeTable (edgeTable);
  68462. et.fillAllWithColour (destData, colour, replaceContents);
  68463. }
  68464. }
  68465. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68466. {
  68467. const Rectangle<float> totalClip (edgeTable.getMaximumBounds().toFloat());
  68468. const Rectangle<float> clipped (totalClip.getIntersection (area));
  68469. if (! clipped.isEmpty())
  68470. {
  68471. ClipRegion_EdgeTable et (clipped);
  68472. et.edgeTable.clipToEdgeTable (edgeTable);
  68473. et.fillAllWithColour (destData, colour, false);
  68474. }
  68475. }
  68476. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68477. {
  68478. switch (destData.pixelFormat)
  68479. {
  68480. case Image::ARGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68481. case Image::RGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68482. default: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68483. }
  68484. }
  68485. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68486. {
  68487. HeapBlock <PixelARGB> lookupTable;
  68488. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68489. jassert (numLookupEntries > 0);
  68490. switch (destData.pixelFormat)
  68491. {
  68492. case Image::ARGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68493. case Image::RGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68494. default: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68495. }
  68496. }
  68497. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68498. {
  68499. renderImageTransformedInternal (edgeTable, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68500. }
  68501. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68502. {
  68503. renderImageUntransformedInternal (edgeTable, destData, srcData, alpha, x, y, tiledFill);
  68504. }
  68505. EdgeTable edgeTable;
  68506. private:
  68507. template <class SrcPixelType>
  68508. void transformedClipImage (const Image::BitmapData& srcData, const AffineTransform& transform, const bool betterQuality, const SrcPixelType*)
  68509. {
  68510. TransformedImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, transform, 255, betterQuality);
  68511. for (int y = 0; y < edgeTable.getMaximumBounds().getHeight(); ++y)
  68512. renderer.clipEdgeTableLine (edgeTable, edgeTable.getMaximumBounds().getX(), y + edgeTable.getMaximumBounds().getY(),
  68513. edgeTable.getMaximumBounds().getWidth());
  68514. }
  68515. template <class SrcPixelType>
  68516. void straightClipImage (const Image::BitmapData& srcData, int imageX, int imageY, const SrcPixelType*)
  68517. {
  68518. Rectangle<int> r (imageX, imageY, srcData.width, srcData.height);
  68519. edgeTable.clipToRectangle (r);
  68520. ImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, 255, imageX, imageY);
  68521. for (int y = 0; y < r.getHeight(); ++y)
  68522. renderer.clipEdgeTableLine (edgeTable, r.getX(), y + r.getY(), r.getWidth());
  68523. }
  68524. ClipRegion_EdgeTable& operator= (const ClipRegion_EdgeTable&);
  68525. };
  68526. class ClipRegion_RectangleList : public ClipRegionBase
  68527. {
  68528. public:
  68529. ClipRegion_RectangleList (const Rectangle<int>& r) : clip (r) {}
  68530. ClipRegion_RectangleList (const RectangleList& r) : clip (r) {}
  68531. ClipRegion_RectangleList (const ClipRegion_RectangleList& other) : clip (other.clip) {}
  68532. ~ClipRegion_RectangleList() {}
  68533. const Ptr clone() const
  68534. {
  68535. return new ClipRegion_RectangleList (*this);
  68536. }
  68537. const Ptr applyClipTo (const Ptr& target) const
  68538. {
  68539. return target->clipToRectangleList (clip);
  68540. }
  68541. const Ptr clipToRectangle (const Rectangle<int>& r)
  68542. {
  68543. clip.clipTo (r);
  68544. return clip.isEmpty() ? 0 : this;
  68545. }
  68546. const Ptr clipToRectangleList (const RectangleList& r)
  68547. {
  68548. clip.clipTo (r);
  68549. return clip.isEmpty() ? 0 : this;
  68550. }
  68551. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68552. {
  68553. clip.subtract (r);
  68554. return clip.isEmpty() ? 0 : this;
  68555. }
  68556. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68557. {
  68558. return Ptr (new ClipRegion_EdgeTable (clip))->clipToPath (p, transform);
  68559. }
  68560. const Ptr clipToEdgeTable (const EdgeTable& et)
  68561. {
  68562. return Ptr (new ClipRegion_EdgeTable (clip))->clipToEdgeTable (et);
  68563. }
  68564. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68565. {
  68566. return Ptr (new ClipRegion_EdgeTable (clip))->clipToImageAlpha (image, transform, betterQuality);
  68567. }
  68568. bool clipRegionIntersects (const Rectangle<int>& r) const
  68569. {
  68570. return clip.intersects (r);
  68571. }
  68572. const Rectangle<int> getClipBounds() const
  68573. {
  68574. return clip.getBounds();
  68575. }
  68576. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68577. {
  68578. SubRectangleIterator iter (clip, area);
  68579. switch (destData.pixelFormat)
  68580. {
  68581. case Image::ARGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68582. case Image::RGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68583. default: renderSolidFill (iter, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68584. }
  68585. }
  68586. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68587. {
  68588. SubRectangleIteratorFloat iter (clip, area);
  68589. switch (destData.pixelFormat)
  68590. {
  68591. case Image::ARGB: renderSolidFill (iter, destData, colour, false, (PixelARGB*) 0); break;
  68592. case Image::RGB: renderSolidFill (iter, destData, colour, false, (PixelRGB*) 0); break;
  68593. default: renderSolidFill (iter, destData, colour, false, (PixelAlpha*) 0); break;
  68594. }
  68595. }
  68596. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68597. {
  68598. switch (destData.pixelFormat)
  68599. {
  68600. case Image::ARGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68601. case Image::RGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68602. default: renderSolidFill (*this, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68603. }
  68604. }
  68605. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68606. {
  68607. HeapBlock <PixelARGB> lookupTable;
  68608. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68609. jassert (numLookupEntries > 0);
  68610. switch (destData.pixelFormat)
  68611. {
  68612. case Image::ARGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68613. case Image::RGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68614. default: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68615. }
  68616. }
  68617. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68618. {
  68619. renderImageTransformedInternal (*this, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68620. }
  68621. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68622. {
  68623. renderImageUntransformedInternal (*this, destData, srcData, alpha, x, y, tiledFill);
  68624. }
  68625. RectangleList clip;
  68626. template <class Renderer>
  68627. void iterate (Renderer& r) const throw()
  68628. {
  68629. RectangleList::Iterator iter (clip);
  68630. while (iter.next())
  68631. {
  68632. const Rectangle<int> rect (*iter.getRectangle());
  68633. const int x = rect.getX();
  68634. const int w = rect.getWidth();
  68635. jassert (w > 0);
  68636. const int bottom = rect.getBottom();
  68637. for (int y = rect.getY(); y < bottom; ++y)
  68638. {
  68639. r.setEdgeTableYPos (y);
  68640. r.handleEdgeTableLineFull (x, w);
  68641. }
  68642. }
  68643. }
  68644. private:
  68645. class SubRectangleIterator
  68646. {
  68647. public:
  68648. SubRectangleIterator (const RectangleList& clip_, const Rectangle<int>& area_)
  68649. : clip (clip_), area (area_)
  68650. {
  68651. }
  68652. template <class Renderer>
  68653. void iterate (Renderer& r) const throw()
  68654. {
  68655. RectangleList::Iterator iter (clip);
  68656. while (iter.next())
  68657. {
  68658. const Rectangle<int> rect (iter.getRectangle()->getIntersection (area));
  68659. if (! rect.isEmpty())
  68660. {
  68661. const int x = rect.getX();
  68662. const int w = rect.getWidth();
  68663. const int bottom = rect.getBottom();
  68664. for (int y = rect.getY(); y < bottom; ++y)
  68665. {
  68666. r.setEdgeTableYPos (y);
  68667. r.handleEdgeTableLineFull (x, w);
  68668. }
  68669. }
  68670. }
  68671. }
  68672. private:
  68673. const RectangleList& clip;
  68674. const Rectangle<int> area;
  68675. SubRectangleIterator (const SubRectangleIterator&);
  68676. SubRectangleIterator& operator= (const SubRectangleIterator&);
  68677. };
  68678. class SubRectangleIteratorFloat
  68679. {
  68680. public:
  68681. SubRectangleIteratorFloat (const RectangleList& clip_, const Rectangle<float>& area_)
  68682. : clip (clip_), area (area_)
  68683. {
  68684. }
  68685. template <class Renderer>
  68686. void iterate (Renderer& r) const throw()
  68687. {
  68688. int left = roundToInt (area.getX() * 256.0f);
  68689. int top = roundToInt (area.getY() * 256.0f);
  68690. int right = roundToInt (area.getRight() * 256.0f);
  68691. int bottom = roundToInt (area.getBottom() * 256.0f);
  68692. int totalTop, totalLeft, totalBottom, totalRight;
  68693. int topAlpha, leftAlpha, bottomAlpha, rightAlpha;
  68694. if ((top >> 8) == (bottom >> 8))
  68695. {
  68696. topAlpha = bottom - top;
  68697. bottomAlpha = 0;
  68698. totalTop = top >> 8;
  68699. totalBottom = bottom = top = totalTop + 1;
  68700. }
  68701. else
  68702. {
  68703. if ((top & 255) == 0)
  68704. {
  68705. topAlpha = 0;
  68706. top = totalTop = (top >> 8);
  68707. }
  68708. else
  68709. {
  68710. topAlpha = 255 - (top & 255);
  68711. totalTop = (top >> 8);
  68712. top = totalTop + 1;
  68713. }
  68714. bottomAlpha = bottom & 255;
  68715. bottom >>= 8;
  68716. totalBottom = bottom + (bottomAlpha != 0 ? 1 : 0);
  68717. }
  68718. if ((left >> 8) == (right >> 8))
  68719. {
  68720. leftAlpha = right - left;
  68721. rightAlpha = 0;
  68722. totalLeft = (left >> 8);
  68723. totalRight = right = left = totalLeft + 1;
  68724. }
  68725. else
  68726. {
  68727. if ((left & 255) == 0)
  68728. {
  68729. leftAlpha = 0;
  68730. left = totalLeft = (left >> 8);
  68731. }
  68732. else
  68733. {
  68734. leftAlpha = 255 - (left & 255);
  68735. totalLeft = (left >> 8);
  68736. left = totalLeft + 1;
  68737. }
  68738. rightAlpha = right & 255;
  68739. right >>= 8;
  68740. totalRight = right + (rightAlpha != 0 ? 1 : 0);
  68741. }
  68742. RectangleList::Iterator iter (clip);
  68743. while (iter.next())
  68744. {
  68745. const int clipLeft = iter.getRectangle()->getX();
  68746. const int clipRight = iter.getRectangle()->getRight();
  68747. const int clipTop = iter.getRectangle()->getY();
  68748. const int clipBottom = iter.getRectangle()->getBottom();
  68749. if (totalBottom > clipTop && totalTop < clipBottom && totalRight > clipLeft && totalLeft < clipRight)
  68750. {
  68751. if (right - left == 1 && leftAlpha + rightAlpha == 0) // special case for 1-pix vertical lines
  68752. {
  68753. if (topAlpha != 0 && totalTop >= clipTop)
  68754. {
  68755. r.setEdgeTableYPos (totalTop);
  68756. r.handleEdgeTablePixel (left, topAlpha);
  68757. }
  68758. const int endY = jmin (bottom, clipBottom);
  68759. for (int y = jmax (clipTop, top); y < endY; ++y)
  68760. {
  68761. r.setEdgeTableYPos (y);
  68762. r.handleEdgeTablePixelFull (left);
  68763. }
  68764. if (bottomAlpha != 0 && bottom < clipBottom)
  68765. {
  68766. r.setEdgeTableYPos (bottom);
  68767. r.handleEdgeTablePixel (left, bottomAlpha);
  68768. }
  68769. }
  68770. else
  68771. {
  68772. const int clippedLeft = jmax (left, clipLeft);
  68773. const int clippedWidth = jmin (right, clipRight) - clippedLeft;
  68774. const bool doLeftAlpha = leftAlpha != 0 && totalLeft >= clipLeft;
  68775. const bool doRightAlpha = rightAlpha != 0 && right < clipRight;
  68776. if (topAlpha != 0 && totalTop >= clipTop)
  68777. {
  68778. r.setEdgeTableYPos (totalTop);
  68779. if (doLeftAlpha)
  68780. r.handleEdgeTablePixel (totalLeft, (leftAlpha * topAlpha) >> 8);
  68781. if (clippedWidth > 0)
  68782. r.handleEdgeTableLine (clippedLeft, clippedWidth, topAlpha);
  68783. if (doRightAlpha)
  68784. r.handleEdgeTablePixel (right, (rightAlpha * topAlpha) >> 8);
  68785. }
  68786. const int endY = jmin (bottom, clipBottom);
  68787. for (int y = jmax (clipTop, top); y < endY; ++y)
  68788. {
  68789. r.setEdgeTableYPos (y);
  68790. if (doLeftAlpha)
  68791. r.handleEdgeTablePixel (totalLeft, leftAlpha);
  68792. if (clippedWidth > 0)
  68793. r.handleEdgeTableLineFull (clippedLeft, clippedWidth);
  68794. if (doRightAlpha)
  68795. r.handleEdgeTablePixel (right, rightAlpha);
  68796. }
  68797. if (bottomAlpha != 0 && bottom < clipBottom)
  68798. {
  68799. r.setEdgeTableYPos (bottom);
  68800. if (doLeftAlpha)
  68801. r.handleEdgeTablePixel (totalLeft, (leftAlpha * bottomAlpha) >> 8);
  68802. if (clippedWidth > 0)
  68803. r.handleEdgeTableLine (clippedLeft, clippedWidth, bottomAlpha);
  68804. if (doRightAlpha)
  68805. r.handleEdgeTablePixel (right, (rightAlpha * bottomAlpha) >> 8);
  68806. }
  68807. }
  68808. }
  68809. }
  68810. }
  68811. private:
  68812. const RectangleList& clip;
  68813. const Rectangle<float>& area;
  68814. SubRectangleIteratorFloat (const SubRectangleIteratorFloat&);
  68815. SubRectangleIteratorFloat& operator= (const SubRectangleIteratorFloat&);
  68816. };
  68817. ClipRegion_RectangleList& operator= (const ClipRegion_RectangleList&);
  68818. };
  68819. }
  68820. class LowLevelGraphicsSoftwareRenderer::SavedState
  68821. {
  68822. public:
  68823. SavedState (const Rectangle<int>& clip_, const int xOffset_, const int yOffset_)
  68824. : clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68825. xOffset (xOffset_), yOffset (yOffset_), interpolationQuality (Graphics::mediumResamplingQuality)
  68826. {
  68827. }
  68828. SavedState (const RectangleList& clip_, const int xOffset_, const int yOffset_)
  68829. : clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68830. xOffset (xOffset_), yOffset (yOffset_), interpolationQuality (Graphics::mediumResamplingQuality)
  68831. {
  68832. }
  68833. SavedState (const SavedState& other)
  68834. : clip (other.clip), xOffset (other.xOffset), yOffset (other.yOffset), font (other.font),
  68835. fillType (other.fillType), interpolationQuality (other.interpolationQuality)
  68836. {
  68837. }
  68838. ~SavedState()
  68839. {
  68840. }
  68841. void setOrigin (const int x, const int y) throw()
  68842. {
  68843. xOffset += x;
  68844. yOffset += y;
  68845. }
  68846. bool clipToRectangle (const Rectangle<int>& r)
  68847. {
  68848. if (clip != 0)
  68849. {
  68850. cloneClipIfMultiplyReferenced();
  68851. clip = clip->clipToRectangle (r.translated (xOffset, yOffset));
  68852. }
  68853. return clip != 0;
  68854. }
  68855. bool clipToRectangleList (const RectangleList& r)
  68856. {
  68857. if (clip != 0)
  68858. {
  68859. cloneClipIfMultiplyReferenced();
  68860. RectangleList offsetList (r);
  68861. offsetList.offsetAll (xOffset, yOffset);
  68862. clip = clip->clipToRectangleList (offsetList);
  68863. }
  68864. return clip != 0;
  68865. }
  68866. bool excludeClipRectangle (const Rectangle<int>& r)
  68867. {
  68868. if (clip != 0)
  68869. {
  68870. cloneClipIfMultiplyReferenced();
  68871. clip = clip->excludeClipRectangle (r.translated (xOffset, yOffset));
  68872. }
  68873. return clip != 0;
  68874. }
  68875. void clipToPath (const Path& p, const AffineTransform& transform)
  68876. {
  68877. if (clip != 0)
  68878. {
  68879. cloneClipIfMultiplyReferenced();
  68880. clip = clip->clipToPath (p, transform.translated ((float) xOffset, (float) yOffset));
  68881. }
  68882. }
  68883. void clipToImageAlpha (const Image& image, const AffineTransform& t)
  68884. {
  68885. if (clip != 0)
  68886. {
  68887. if (image.hasAlphaChannel())
  68888. {
  68889. cloneClipIfMultiplyReferenced();
  68890. clip = clip->clipToImageAlpha (image, t.translated ((float) xOffset, (float) yOffset),
  68891. interpolationQuality != Graphics::lowResamplingQuality);
  68892. }
  68893. else
  68894. {
  68895. Path p;
  68896. p.addRectangle (image.getBounds());
  68897. clipToPath (p, t);
  68898. }
  68899. }
  68900. }
  68901. bool clipRegionIntersects (const Rectangle<int>& r) const
  68902. {
  68903. return clip != 0 && clip->clipRegionIntersects (r.translated (xOffset, yOffset));
  68904. }
  68905. const Rectangle<int> getClipBounds() const
  68906. {
  68907. return clip == 0 ? Rectangle<int>() : clip->getClipBounds().translated (-xOffset, -yOffset);
  68908. }
  68909. void fillRect (Image& image, const Rectangle<int>& r, const bool replaceContents)
  68910. {
  68911. if (clip != 0)
  68912. {
  68913. if (fillType.isColour())
  68914. {
  68915. Image::BitmapData destData (image, true);
  68916. clip->fillRectWithColour (destData, r.translated (xOffset, yOffset), fillType.colour.getPixelARGB(), replaceContents);
  68917. }
  68918. else
  68919. {
  68920. const Rectangle<int> totalClip (clip->getClipBounds());
  68921. const Rectangle<int> clipped (totalClip.getIntersection (r.translated (xOffset, yOffset)));
  68922. if (! clipped.isEmpty())
  68923. fillShape (image, new SoftwareRendererClasses::ClipRegion_RectangleList (clipped), false);
  68924. }
  68925. }
  68926. }
  68927. void fillRect (Image& image, const Rectangle<float>& r)
  68928. {
  68929. if (clip != 0)
  68930. {
  68931. if (fillType.isColour())
  68932. {
  68933. Image::BitmapData destData (image, true);
  68934. clip->fillRectWithColour (destData, r.translated ((float) xOffset, (float) yOffset), fillType.colour.getPixelARGB());
  68935. }
  68936. else
  68937. {
  68938. const Rectangle<float> totalClip (clip->getClipBounds().toFloat());
  68939. const Rectangle<float> clipped (totalClip.getIntersection (r.translated ((float) xOffset, (float) yOffset)));
  68940. if (! clipped.isEmpty())
  68941. fillShape (image, new SoftwareRendererClasses::ClipRegion_EdgeTable (clipped), false);
  68942. }
  68943. }
  68944. }
  68945. void fillPath (Image& image, const Path& path, const AffineTransform& transform)
  68946. {
  68947. if (clip != 0)
  68948. fillShape (image, new SoftwareRendererClasses::ClipRegion_EdgeTable (clip->getClipBounds(), path, transform.translated ((float) xOffset, (float) yOffset)), false);
  68949. }
  68950. void fillEdgeTable (Image& image, const EdgeTable& edgeTable, const float x, const int y)
  68951. {
  68952. if (clip != 0)
  68953. {
  68954. SoftwareRendererClasses::ClipRegion_EdgeTable* edgeTableClip = new SoftwareRendererClasses::ClipRegion_EdgeTable (edgeTable);
  68955. SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill (edgeTableClip);
  68956. edgeTableClip->edgeTable.translate (x + xOffset, y + yOffset);
  68957. fillShape (image, shapeToFill, false);
  68958. }
  68959. }
  68960. void fillShape (Image& image, SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill, const bool replaceContents)
  68961. {
  68962. jassert (clip != 0);
  68963. shapeToFill = clip->applyClipTo (shapeToFill);
  68964. if (shapeToFill != 0)
  68965. {
  68966. Image::BitmapData destData (image, true);
  68967. if (fillType.isGradient())
  68968. {
  68969. jassert (! replaceContents); // that option is just for solid colours
  68970. ColourGradient g2 (*(fillType.gradient));
  68971. g2.multiplyOpacity (fillType.getOpacity());
  68972. g2.point1.addXY (-0.5f, -0.5f);
  68973. g2.point2.addXY (-0.5f, -0.5f);
  68974. AffineTransform transform (fillType.transform.translated ((float) xOffset, (float) yOffset));
  68975. const bool isIdentity = transform.isOnlyTranslation();
  68976. if (isIdentity)
  68977. {
  68978. // If our translation doesn't involve any distortion, we can speed it up..
  68979. g2.point1.applyTransform (transform);
  68980. g2.point2.applyTransform (transform);
  68981. transform = AffineTransform::identity;
  68982. }
  68983. shapeToFill->fillAllWithGradient (destData, g2, transform, isIdentity);
  68984. }
  68985. else if (fillType.isTiledImage())
  68986. {
  68987. renderImage (image, fillType.image, fillType.transform, shapeToFill);
  68988. }
  68989. else
  68990. {
  68991. shapeToFill->fillAllWithColour (destData, fillType.colour.getPixelARGB(), replaceContents);
  68992. }
  68993. }
  68994. }
  68995. void renderImage (Image& destImage, const Image& sourceImage, const AffineTransform& t, const SoftwareRendererClasses::ClipRegionBase* const tiledFillClipRegion)
  68996. {
  68997. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  68998. const Image::BitmapData destData (destImage, true);
  68999. const Image::BitmapData srcData (sourceImage, false);
  69000. const int alpha = fillType.colour.getAlpha();
  69001. const bool betterQuality = (interpolationQuality != Graphics::lowResamplingQuality);
  69002. if (transform.isOnlyTranslation())
  69003. {
  69004. // If our translation doesn't involve any distortion, just use a simple blit..
  69005. int tx = (int) (transform.getTranslationX() * 256.0f);
  69006. int ty = (int) (transform.getTranslationY() * 256.0f);
  69007. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  69008. {
  69009. tx = ((tx + 128) >> 8);
  69010. ty = ((ty + 128) >> 8);
  69011. if (tiledFillClipRegion != 0)
  69012. {
  69013. tiledFillClipRegion->renderImageUntransformed (destData, srcData, alpha, tx, ty, true);
  69014. }
  69015. else
  69016. {
  69017. SoftwareRendererClasses::ClipRegionBase::Ptr c (new SoftwareRendererClasses::ClipRegion_EdgeTable (Rectangle<int> (tx, ty, sourceImage.getWidth(), sourceImage.getHeight()).getIntersection (destImage.getBounds())));
  69018. c = clip->applyClipTo (c);
  69019. if (c != 0)
  69020. c->renderImageUntransformed (destData, srcData, alpha, tx, ty, false);
  69021. }
  69022. return;
  69023. }
  69024. }
  69025. if (transform.isSingularity())
  69026. return;
  69027. if (tiledFillClipRegion != 0)
  69028. {
  69029. tiledFillClipRegion->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, true);
  69030. }
  69031. else
  69032. {
  69033. Path p;
  69034. p.addRectangle (sourceImage.getBounds());
  69035. SoftwareRendererClasses::ClipRegionBase::Ptr c (clip->clone());
  69036. c = c->clipToPath (p, transform);
  69037. if (c != 0)
  69038. c->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, false);
  69039. }
  69040. }
  69041. SoftwareRendererClasses::ClipRegionBase::Ptr clip;
  69042. int xOffset, yOffset;
  69043. Font font;
  69044. FillType fillType;
  69045. Graphics::ResamplingQuality interpolationQuality;
  69046. private:
  69047. void cloneClipIfMultiplyReferenced()
  69048. {
  69049. if (clip->getReferenceCount() > 1)
  69050. clip = clip->clone();
  69051. }
  69052. SavedState& operator= (const SavedState&);
  69053. };
  69054. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_)
  69055. : image (image_)
  69056. {
  69057. currentState = new SavedState (image_.getBounds(), 0, 0);
  69058. }
  69059. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_, const int xOffset, const int yOffset,
  69060. const RectangleList& initialClip)
  69061. : image (image_)
  69062. {
  69063. currentState = new SavedState (initialClip, xOffset, yOffset);
  69064. }
  69065. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  69066. {
  69067. }
  69068. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  69069. {
  69070. return false;
  69071. }
  69072. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  69073. {
  69074. currentState->setOrigin (x, y);
  69075. }
  69076. bool LowLevelGraphicsSoftwareRenderer::clipToRectangle (const Rectangle<int>& r)
  69077. {
  69078. return currentState->clipToRectangle (r);
  69079. }
  69080. bool LowLevelGraphicsSoftwareRenderer::clipToRectangleList (const RectangleList& clipRegion)
  69081. {
  69082. return currentState->clipToRectangleList (clipRegion);
  69083. }
  69084. void LowLevelGraphicsSoftwareRenderer::excludeClipRectangle (const Rectangle<int>& r)
  69085. {
  69086. currentState->excludeClipRectangle (r);
  69087. }
  69088. void LowLevelGraphicsSoftwareRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  69089. {
  69090. currentState->clipToPath (path, transform);
  69091. }
  69092. void LowLevelGraphicsSoftwareRenderer::clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  69093. {
  69094. currentState->clipToImageAlpha (sourceImage, transform);
  69095. }
  69096. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (const Rectangle<int>& r)
  69097. {
  69098. return currentState->clipRegionIntersects (r);
  69099. }
  69100. const Rectangle<int> LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  69101. {
  69102. return currentState->getClipBounds();
  69103. }
  69104. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  69105. {
  69106. return currentState->clip == 0;
  69107. }
  69108. void LowLevelGraphicsSoftwareRenderer::saveState()
  69109. {
  69110. stateStack.add (new SavedState (*currentState));
  69111. }
  69112. void LowLevelGraphicsSoftwareRenderer::restoreState()
  69113. {
  69114. SavedState* const top = stateStack.getLast();
  69115. if (top != 0)
  69116. {
  69117. currentState = top;
  69118. stateStack.removeLast (1, false);
  69119. }
  69120. else
  69121. {
  69122. jassertfalse; // trying to pop with an empty stack!
  69123. }
  69124. }
  69125. void LowLevelGraphicsSoftwareRenderer::setFill (const FillType& fillType)
  69126. {
  69127. currentState->fillType = fillType;
  69128. }
  69129. void LowLevelGraphicsSoftwareRenderer::setOpacity (float newOpacity)
  69130. {
  69131. currentState->fillType.setOpacity (newOpacity);
  69132. }
  69133. void LowLevelGraphicsSoftwareRenderer::setInterpolationQuality (Graphics::ResamplingQuality quality)
  69134. {
  69135. currentState->interpolationQuality = quality;
  69136. }
  69137. void LowLevelGraphicsSoftwareRenderer::fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  69138. {
  69139. currentState->fillRect (image, r, replaceExistingContents);
  69140. }
  69141. void LowLevelGraphicsSoftwareRenderer::fillPath (const Path& path, const AffineTransform& transform)
  69142. {
  69143. currentState->fillPath (image, path, transform);
  69144. }
  69145. void LowLevelGraphicsSoftwareRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  69146. {
  69147. currentState->renderImage (image, sourceImage, transform,
  69148. fillEntireClipAsTiles ? currentState->clip : 0);
  69149. }
  69150. void LowLevelGraphicsSoftwareRenderer::drawLine (const Line <float>& line)
  69151. {
  69152. Path p;
  69153. p.addLineSegment (line, 1.0f);
  69154. fillPath (p, AffineTransform::identity);
  69155. }
  69156. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, float top, float bottom)
  69157. {
  69158. if (bottom > top)
  69159. currentState->fillRect (image, Rectangle<float> ((float) x, top, 1.0f, bottom - top));
  69160. }
  69161. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, float left, float right)
  69162. {
  69163. if (right > left)
  69164. currentState->fillRect (image, Rectangle<float> (left, (float) y, right - left, 1.0f));
  69165. }
  69166. class LowLevelGraphicsSoftwareRenderer::CachedGlyph
  69167. {
  69168. public:
  69169. CachedGlyph() : glyph (0), lastAccessCount (0) {}
  69170. ~CachedGlyph() {}
  69171. void draw (SavedState& state, Image& image, const float x, const float y) const
  69172. {
  69173. if (edgeTable != 0)
  69174. state.fillEdgeTable (image, *edgeTable, x, roundToInt (y));
  69175. }
  69176. void generate (const Font& newFont, const int glyphNumber)
  69177. {
  69178. font = newFont;
  69179. glyph = glyphNumber;
  69180. edgeTable = 0;
  69181. Path glyphPath;
  69182. font.getTypeface()->getOutlineForGlyph (glyphNumber, glyphPath);
  69183. if (! glyphPath.isEmpty())
  69184. {
  69185. const float fontHeight = font.getHeight();
  69186. const AffineTransform transform (AffineTransform::scale (fontHeight * font.getHorizontalScale(), fontHeight)
  69187. #if JUCE_MAC || JUCE_IOS
  69188. .translated (0.0f, -0.5f)
  69189. #endif
  69190. );
  69191. edgeTable = new EdgeTable (glyphPath.getBoundsTransformed (transform).getSmallestIntegerContainer().expanded (1, 0),
  69192. glyphPath, transform);
  69193. }
  69194. }
  69195. int glyph, lastAccessCount;
  69196. Font font;
  69197. juce_UseDebuggingNewOperator
  69198. private:
  69199. ScopedPointer <EdgeTable> edgeTable;
  69200. CachedGlyph (const CachedGlyph&);
  69201. CachedGlyph& operator= (const CachedGlyph&);
  69202. };
  69203. class LowLevelGraphicsSoftwareRenderer::GlyphCache : private DeletedAtShutdown
  69204. {
  69205. public:
  69206. GlyphCache()
  69207. : accessCounter (0), hits (0), misses (0)
  69208. {
  69209. for (int i = 120; --i >= 0;)
  69210. glyphs.add (new CachedGlyph());
  69211. }
  69212. ~GlyphCache()
  69213. {
  69214. clearSingletonInstance();
  69215. }
  69216. juce_DeclareSingleton_SingleThreaded_Minimal (GlyphCache);
  69217. void drawGlyph (SavedState& state, Image& image, const Font& font, const int glyphNumber, float x, float y)
  69218. {
  69219. ++accessCounter;
  69220. int oldestCounter = std::numeric_limits<int>::max();
  69221. CachedGlyph* oldest = 0;
  69222. for (int i = glyphs.size(); --i >= 0;)
  69223. {
  69224. CachedGlyph* const glyph = glyphs.getUnchecked (i);
  69225. if (glyph->glyph == glyphNumber && glyph->font == font)
  69226. {
  69227. ++hits;
  69228. glyph->lastAccessCount = accessCounter;
  69229. glyph->draw (state, image, x, y);
  69230. return;
  69231. }
  69232. if (glyph->lastAccessCount <= oldestCounter)
  69233. {
  69234. oldestCounter = glyph->lastAccessCount;
  69235. oldest = glyph;
  69236. }
  69237. }
  69238. if (hits + ++misses > (glyphs.size() << 4))
  69239. {
  69240. if (misses * 2 > hits)
  69241. {
  69242. for (int i = 32; --i >= 0;)
  69243. glyphs.add (new CachedGlyph());
  69244. }
  69245. hits = misses = 0;
  69246. oldest = glyphs.getLast();
  69247. }
  69248. jassert (oldest != 0);
  69249. oldest->lastAccessCount = accessCounter;
  69250. oldest->generate (font, glyphNumber);
  69251. oldest->draw (state, image, x, y);
  69252. }
  69253. juce_UseDebuggingNewOperator
  69254. private:
  69255. friend class OwnedArray <CachedGlyph>;
  69256. OwnedArray <CachedGlyph> glyphs;
  69257. int accessCounter, hits, misses;
  69258. GlyphCache (const GlyphCache&);
  69259. GlyphCache& operator= (const GlyphCache&);
  69260. };
  69261. juce_ImplementSingleton_SingleThreaded (LowLevelGraphicsSoftwareRenderer::GlyphCache);
  69262. void LowLevelGraphicsSoftwareRenderer::setFont (const Font& newFont)
  69263. {
  69264. currentState->font = newFont;
  69265. }
  69266. const Font LowLevelGraphicsSoftwareRenderer::getFont()
  69267. {
  69268. return currentState->font;
  69269. }
  69270. void LowLevelGraphicsSoftwareRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  69271. {
  69272. Font& f = currentState->font;
  69273. if (transform.isOnlyTranslation())
  69274. {
  69275. GlyphCache::getInstance()->drawGlyph (*currentState, image, f, glyphNumber,
  69276. transform.getTranslationX(),
  69277. transform.getTranslationY());
  69278. }
  69279. else
  69280. {
  69281. Path p;
  69282. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  69283. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight()).followedBy (transform));
  69284. }
  69285. }
  69286. #if JUCE_MSVC
  69287. #pragma warning (pop)
  69288. #if JUCE_DEBUG
  69289. #pragma optimize ("", on) // resets optimisations to the project defaults
  69290. #endif
  69291. #endif
  69292. END_JUCE_NAMESPACE
  69293. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  69294. /*** Start of inlined file: juce_RectanglePlacement.cpp ***/
  69295. BEGIN_JUCE_NAMESPACE
  69296. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  69297. : flags (other.flags)
  69298. {
  69299. }
  69300. RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  69301. {
  69302. flags = other.flags;
  69303. return *this;
  69304. }
  69305. void RectanglePlacement::applyTo (double& x, double& y,
  69306. double& w, double& h,
  69307. const double dx, const double dy,
  69308. const double dw, const double dh) const throw()
  69309. {
  69310. if (w == 0 || h == 0)
  69311. return;
  69312. if ((flags & stretchToFit) != 0)
  69313. {
  69314. x = dx;
  69315. y = dy;
  69316. w = dw;
  69317. h = dh;
  69318. }
  69319. else
  69320. {
  69321. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  69322. : jmin (dw / w, dh / h);
  69323. if ((flags & onlyReduceInSize) != 0)
  69324. scale = jmin (scale, 1.0);
  69325. if ((flags & onlyIncreaseInSize) != 0)
  69326. scale = jmax (scale, 1.0);
  69327. w *= scale;
  69328. h *= scale;
  69329. if ((flags & xLeft) != 0)
  69330. x = dx;
  69331. else if ((flags & xRight) != 0)
  69332. x = dx + dw - w;
  69333. else
  69334. x = dx + (dw - w) * 0.5;
  69335. if ((flags & yTop) != 0)
  69336. y = dy;
  69337. else if ((flags & yBottom) != 0)
  69338. y = dy + dh - h;
  69339. else
  69340. y = dy + (dh - h) * 0.5;
  69341. }
  69342. }
  69343. const AffineTransform RectanglePlacement::getTransformToFit (float x, float y,
  69344. float w, float h,
  69345. const float dx, const float dy,
  69346. const float dw, const float dh) const throw()
  69347. {
  69348. if (w == 0 || h == 0)
  69349. return AffineTransform::identity;
  69350. const float scaleX = dw / w;
  69351. const float scaleY = dh / h;
  69352. if ((flags & stretchToFit) != 0)
  69353. return AffineTransform::translation (-x, -y)
  69354. .scaled (scaleX, scaleY)
  69355. .translated (dx, dy);
  69356. float scale = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  69357. : jmin (scaleX, scaleY);
  69358. if ((flags & onlyReduceInSize) != 0)
  69359. scale = jmin (scale, 1.0f);
  69360. if ((flags & onlyIncreaseInSize) != 0)
  69361. scale = jmax (scale, 1.0f);
  69362. w *= scale;
  69363. h *= scale;
  69364. float newX = dx;
  69365. if ((flags & xRight) != 0)
  69366. newX += dw - w; // right
  69367. else if ((flags & xLeft) == 0)
  69368. newX += (dw - w) / 2.0f; // centre
  69369. float newY = dy;
  69370. if ((flags & yBottom) != 0)
  69371. newY += dh - h; // bottom
  69372. else if ((flags & yTop) == 0)
  69373. newY += (dh - h) / 2.0f; // centre
  69374. return AffineTransform::translation (-x, -y)
  69375. .scaled (scale, scale)
  69376. .translated (newX, newY);
  69377. }
  69378. END_JUCE_NAMESPACE
  69379. /*** End of inlined file: juce_RectanglePlacement.cpp ***/
  69380. /*** Start of inlined file: juce_Drawable.cpp ***/
  69381. BEGIN_JUCE_NAMESPACE
  69382. Drawable::RenderingContext::RenderingContext (Graphics& g_,
  69383. const AffineTransform& transform_,
  69384. const float opacity_) throw()
  69385. : g (g_),
  69386. transform (transform_),
  69387. opacity (opacity_)
  69388. {
  69389. }
  69390. Drawable::Drawable()
  69391. : parent (0)
  69392. {
  69393. }
  69394. Drawable::~Drawable()
  69395. {
  69396. }
  69397. void Drawable::draw (Graphics& g, const float opacity, const AffineTransform& transform) const
  69398. {
  69399. render (RenderingContext (g, transform, opacity));
  69400. }
  69401. void Drawable::drawAt (Graphics& g, const float x, const float y, const float opacity) const
  69402. {
  69403. draw (g, opacity, AffineTransform::translation (x, y));
  69404. }
  69405. void Drawable::drawWithin (Graphics& g,
  69406. const int destX,
  69407. const int destY,
  69408. const int destW,
  69409. const int destH,
  69410. const RectanglePlacement& placement,
  69411. const float opacity) const
  69412. {
  69413. if (destW > 0 && destH > 0)
  69414. {
  69415. Rectangle<float> bounds (getBounds());
  69416. draw (g, opacity,
  69417. placement.getTransformToFit (bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight(),
  69418. (float) destX, (float) destY,
  69419. (float) destW, (float) destH));
  69420. }
  69421. }
  69422. Drawable* Drawable::createFromImageData (const void* data, const size_t numBytes)
  69423. {
  69424. Drawable* result = 0;
  69425. Image image (ImageFileFormat::loadFrom (data, (int) numBytes));
  69426. if (image.isValid())
  69427. {
  69428. DrawableImage* const di = new DrawableImage();
  69429. di->setImage (image);
  69430. result = di;
  69431. }
  69432. else
  69433. {
  69434. const String asString (String::createStringFromData (data, (int) numBytes));
  69435. XmlDocument doc (asString);
  69436. ScopedPointer <XmlElement> outer (doc.getDocumentElement (true));
  69437. if (outer != 0 && outer->hasTagName ("svg"))
  69438. {
  69439. ScopedPointer <XmlElement> svg (doc.getDocumentElement());
  69440. if (svg != 0)
  69441. result = Drawable::createFromSVG (*svg);
  69442. }
  69443. }
  69444. return result;
  69445. }
  69446. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  69447. {
  69448. MemoryOutputStream mo;
  69449. mo.writeFromInputStream (dataSource, -1);
  69450. return createFromImageData (mo.getData(), mo.getDataSize());
  69451. }
  69452. Drawable* Drawable::createFromImageFile (const File& file)
  69453. {
  69454. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  69455. return fin != 0 ? createFromImageDataStream (*fin) : 0;
  69456. }
  69457. Drawable* Drawable::createFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  69458. {
  69459. return createChildFromValueTree (0, tree, imageProvider);
  69460. }
  69461. Drawable* Drawable::createChildFromValueTree (DrawableComposite* parent, const ValueTree& tree, ImageProvider* imageProvider)
  69462. {
  69463. const Identifier type (tree.getType());
  69464. Drawable* d = 0;
  69465. if (type == DrawablePath::valueTreeType)
  69466. d = new DrawablePath();
  69467. else if (type == DrawableComposite::valueTreeType)
  69468. d = new DrawableComposite();
  69469. else if (type == DrawableImage::valueTreeType)
  69470. d = new DrawableImage();
  69471. else if (type == DrawableText::valueTreeType)
  69472. d = new DrawableText();
  69473. if (d != 0)
  69474. {
  69475. d->parent = parent;
  69476. d->refreshFromValueTree (tree, imageProvider);
  69477. }
  69478. return d;
  69479. }
  69480. const Identifier Drawable::ValueTreeWrapperBase::idProperty ("id");
  69481. const Identifier Drawable::ValueTreeWrapperBase::type ("type");
  69482. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint1 ("point1");
  69483. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint2 ("point2");
  69484. const Identifier Drawable::ValueTreeWrapperBase::gradientPoint3 ("point3");
  69485. const Identifier Drawable::ValueTreeWrapperBase::colour ("colour");
  69486. const Identifier Drawable::ValueTreeWrapperBase::radial ("radial");
  69487. const Identifier Drawable::ValueTreeWrapperBase::colours ("colours");
  69488. const Identifier Drawable::ValueTreeWrapperBase::imageId ("imageId");
  69489. const Identifier Drawable::ValueTreeWrapperBase::imageOpacity ("imageOpacity");
  69490. Drawable::ValueTreeWrapperBase::ValueTreeWrapperBase (const ValueTree& state_)
  69491. : state (state_)
  69492. {
  69493. }
  69494. Drawable::ValueTreeWrapperBase::~ValueTreeWrapperBase()
  69495. {
  69496. }
  69497. const String Drawable::ValueTreeWrapperBase::getID() const
  69498. {
  69499. return state [idProperty];
  69500. }
  69501. void Drawable::ValueTreeWrapperBase::setID (const String& newID, UndoManager* const undoManager)
  69502. {
  69503. if (newID.isEmpty())
  69504. state.removeProperty (idProperty, undoManager);
  69505. else
  69506. state.setProperty (idProperty, newID, undoManager);
  69507. }
  69508. const FillType Drawable::ValueTreeWrapperBase::readFillType (const ValueTree& v, RelativePoint* const gp1, RelativePoint* const gp2, RelativePoint* const gp3,
  69509. Expression::EvaluationContext* const nameFinder, ImageProvider* imageProvider)
  69510. {
  69511. const String newType (v[type].toString());
  69512. if (newType == "solid")
  69513. {
  69514. const String colourString (v [colour].toString());
  69515. return FillType (Colour (colourString.isEmpty() ? (uint32) 0xff000000
  69516. : (uint32) colourString.getHexValue32()));
  69517. }
  69518. else if (newType == "gradient")
  69519. {
  69520. RelativePoint p1 (v [gradientPoint1]), p2 (v [gradientPoint2]), p3 (v [gradientPoint3]);
  69521. ColourGradient g;
  69522. if (gp1 != 0) *gp1 = p1;
  69523. if (gp2 != 0) *gp2 = p2;
  69524. if (gp3 != 0) *gp3 = p3;
  69525. g.point1 = p1.resolve (nameFinder);
  69526. g.point2 = p2.resolve (nameFinder);
  69527. g.isRadial = v[radial];
  69528. StringArray colourSteps;
  69529. colourSteps.addTokens (v[colours].toString(), false);
  69530. for (int i = 0; i < colourSteps.size() / 2; ++i)
  69531. g.addColour (colourSteps[i * 2].getDoubleValue(),
  69532. Colour ((uint32) colourSteps[i * 2 + 1].getHexValue32()));
  69533. FillType fillType (g);
  69534. if (g.isRadial)
  69535. {
  69536. const Point<float> point3 (p3.resolve (nameFinder));
  69537. const Point<float> point3Source (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  69538. g.point1.getY() + g.point1.getX() - g.point2.getX());
  69539. fillType.transform = AffineTransform::fromTargetPoints (g.point1.getX(), g.point1.getY(), g.point1.getX(), g.point1.getY(),
  69540. g.point2.getX(), g.point2.getY(), g.point2.getX(), g.point2.getY(),
  69541. point3Source.getX(), point3Source.getY(), point3.getX(), point3.getY());
  69542. }
  69543. return fillType;
  69544. }
  69545. else if (newType == "image")
  69546. {
  69547. Image im;
  69548. if (imageProvider != 0)
  69549. im = imageProvider->getImageForIdentifier (v[imageId]);
  69550. FillType f (im, AffineTransform::identity);
  69551. f.setOpacity ((float) v.getProperty (imageOpacity, 1.0f));
  69552. return f;
  69553. }
  69554. jassertfalse;
  69555. return FillType();
  69556. }
  69557. static const Point<float> calcThirdGradientPoint (const FillType& fillType)
  69558. {
  69559. const ColourGradient& g = *fillType.gradient;
  69560. const Point<float> point3Source (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  69561. g.point1.getY() + g.point1.getX() - g.point2.getX());
  69562. return point3Source.transformedBy (fillType.transform);
  69563. }
  69564. void Drawable::ValueTreeWrapperBase::writeFillType (ValueTree& v, const FillType& fillType,
  69565. const RelativePoint* const gp1, const RelativePoint* const gp2, const RelativePoint* gp3,
  69566. ImageProvider* imageProvider, UndoManager* const undoManager)
  69567. {
  69568. if (fillType.isColour())
  69569. {
  69570. v.setProperty (type, "solid", undoManager);
  69571. v.setProperty (colour, String::toHexString ((int) fillType.colour.getARGB()), undoManager);
  69572. }
  69573. else if (fillType.isGradient())
  69574. {
  69575. v.setProperty (type, "gradient", undoManager);
  69576. v.setProperty (gradientPoint1, gp1 != 0 ? gp1->toString() : fillType.gradient->point1.toString(), undoManager);
  69577. v.setProperty (gradientPoint2, gp2 != 0 ? gp2->toString() : fillType.gradient->point2.toString(), undoManager);
  69578. v.setProperty (gradientPoint3, gp3 != 0 ? gp3->toString() : calcThirdGradientPoint (fillType).toString(), undoManager);
  69579. v.setProperty (radial, fillType.gradient->isRadial, undoManager);
  69580. String s;
  69581. for (int i = 0; i < fillType.gradient->getNumColours(); ++i)
  69582. s << ' ' << fillType.gradient->getColourPosition (i)
  69583. << ' ' << String::toHexString ((int) fillType.gradient->getColour(i).getARGB());
  69584. v.setProperty (colours, s.trimStart(), undoManager);
  69585. }
  69586. else if (fillType.isTiledImage())
  69587. {
  69588. v.setProperty (type, "image", undoManager);
  69589. if (imageProvider != 0)
  69590. v.setProperty (imageId, imageProvider->getIdentifierForImage (fillType.image), undoManager);
  69591. if (fillType.getOpacity() < 1.0f)
  69592. v.setProperty (imageOpacity, fillType.getOpacity(), undoManager);
  69593. else
  69594. v.removeProperty (imageOpacity, undoManager);
  69595. }
  69596. else
  69597. {
  69598. jassertfalse;
  69599. }
  69600. }
  69601. END_JUCE_NAMESPACE
  69602. /*** End of inlined file: juce_Drawable.cpp ***/
  69603. /*** Start of inlined file: juce_DrawableComposite.cpp ***/
  69604. BEGIN_JUCE_NAMESPACE
  69605. DrawableComposite::DrawableComposite()
  69606. : bounds (Point<float>(), Point<float> (100.0f, 0.0f), Point<float> (0.0f, 100.0f))
  69607. {
  69608. setContentArea (RelativeRectangle (RelativeCoordinate (0.0),
  69609. RelativeCoordinate (100.0),
  69610. RelativeCoordinate (0.0),
  69611. RelativeCoordinate (100.0)));
  69612. }
  69613. DrawableComposite::DrawableComposite (const DrawableComposite& other)
  69614. {
  69615. bounds = other.bounds;
  69616. for (int i = 0; i < other.drawables.size(); ++i)
  69617. drawables.add (other.drawables.getUnchecked(i)->createCopy());
  69618. markersX.addCopiesOf (other.markersX);
  69619. markersY.addCopiesOf (other.markersY);
  69620. }
  69621. DrawableComposite::~DrawableComposite()
  69622. {
  69623. }
  69624. void DrawableComposite::insertDrawable (Drawable* drawable, const int index)
  69625. {
  69626. if (drawable != 0)
  69627. {
  69628. jassert (! drawables.contains (drawable)); // trying to add a drawable that's already in here!
  69629. jassert (drawable->parent == 0); // A drawable can only live inside one parent at a time!
  69630. drawables.insert (index, drawable);
  69631. drawable->parent = this;
  69632. }
  69633. }
  69634. void DrawableComposite::insertDrawable (const Drawable& drawable, const int index)
  69635. {
  69636. insertDrawable (drawable.createCopy(), index);
  69637. }
  69638. void DrawableComposite::removeDrawable (const int index, const bool deleteDrawable)
  69639. {
  69640. drawables.remove (index, deleteDrawable);
  69641. }
  69642. Drawable* DrawableComposite::getDrawableWithName (const String& name) const throw()
  69643. {
  69644. for (int i = drawables.size(); --i >= 0;)
  69645. if (drawables.getUnchecked(i)->getName() == name)
  69646. return drawables.getUnchecked(i);
  69647. return 0;
  69648. }
  69649. void DrawableComposite::bringToFront (const int index)
  69650. {
  69651. if (index >= 0 && index < drawables.size() - 1)
  69652. drawables.move (index, -1);
  69653. }
  69654. void DrawableComposite::setBoundingBox (const RelativeParallelogram& newBoundingBox)
  69655. {
  69656. bounds = newBoundingBox;
  69657. }
  69658. DrawableComposite::Marker::Marker (const DrawableComposite::Marker& other)
  69659. : name (other.name), position (other.position)
  69660. {
  69661. }
  69662. DrawableComposite::Marker::Marker (const String& name_, const RelativeCoordinate& position_)
  69663. : name (name_), position (position_)
  69664. {
  69665. }
  69666. bool DrawableComposite::Marker::operator!= (const DrawableComposite::Marker& other) const throw()
  69667. {
  69668. return name != other.name || position != other.position;
  69669. }
  69670. const char* const DrawableComposite::contentLeftMarkerName ("left");
  69671. const char* const DrawableComposite::contentRightMarkerName ("right");
  69672. const char* const DrawableComposite::contentTopMarkerName ("top");
  69673. const char* const DrawableComposite::contentBottomMarkerName ("bottom");
  69674. const RelativeRectangle DrawableComposite::getContentArea() const
  69675. {
  69676. jassert (markersX.size() >= 2 && getMarker (true, 0)->name == contentLeftMarkerName && getMarker (true, 1)->name == contentRightMarkerName);
  69677. jassert (markersY.size() >= 2 && getMarker (false, 0)->name == contentTopMarkerName && getMarker (false, 1)->name == contentBottomMarkerName);
  69678. return RelativeRectangle (markersX.getUnchecked(0)->position, markersX.getUnchecked(1)->position,
  69679. markersY.getUnchecked(0)->position, markersY.getUnchecked(1)->position);
  69680. }
  69681. void DrawableComposite::setContentArea (const RelativeRectangle& newArea)
  69682. {
  69683. setMarker (contentLeftMarkerName, true, newArea.left);
  69684. setMarker (contentRightMarkerName, true, newArea.right);
  69685. setMarker (contentTopMarkerName, false, newArea.top);
  69686. setMarker (contentBottomMarkerName, false, newArea.bottom);
  69687. }
  69688. void DrawableComposite::resetBoundingBoxToContentArea()
  69689. {
  69690. const RelativeRectangle content (getContentArea());
  69691. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  69692. RelativePoint (content.right, content.top),
  69693. RelativePoint (content.left, content.bottom)));
  69694. }
  69695. void DrawableComposite::resetContentAreaAndBoundingBoxToFitChildren()
  69696. {
  69697. const Rectangle<float> bounds (getUntransformedBounds (false));
  69698. setContentArea (RelativeRectangle (RelativeCoordinate (bounds.getX()),
  69699. RelativeCoordinate (bounds.getRight()),
  69700. RelativeCoordinate (bounds.getY()),
  69701. RelativeCoordinate (bounds.getBottom())));
  69702. resetBoundingBoxToContentArea();
  69703. }
  69704. int DrawableComposite::getNumMarkers (const bool xAxis) const throw()
  69705. {
  69706. return (xAxis ? markersX : markersY).size();
  69707. }
  69708. const DrawableComposite::Marker* DrawableComposite::getMarker (const bool xAxis, const int index) const throw()
  69709. {
  69710. return (xAxis ? markersX : markersY) [index];
  69711. }
  69712. void DrawableComposite::setMarker (const String& name, const bool xAxis, const RelativeCoordinate& position)
  69713. {
  69714. OwnedArray <Marker>& markers = (xAxis ? markersX : markersY);
  69715. for (int i = 0; i < markers.size(); ++i)
  69716. {
  69717. Marker* const m = markers.getUnchecked(i);
  69718. if (m->name == name)
  69719. {
  69720. if (m->position != position)
  69721. {
  69722. m->position = position;
  69723. invalidatePoints();
  69724. }
  69725. return;
  69726. }
  69727. }
  69728. (xAxis ? markersX : markersY).add (new Marker (name, position));
  69729. invalidatePoints();
  69730. }
  69731. void DrawableComposite::removeMarker (const bool xAxis, const int index)
  69732. {
  69733. jassert (index >= 2);
  69734. if (index >= 2)
  69735. (xAxis ? markersX : markersY).remove (index);
  69736. }
  69737. const AffineTransform DrawableComposite::calculateTransform() const
  69738. {
  69739. Point<float> resolved[3];
  69740. bounds.resolveThreePoints (resolved, parent);
  69741. const Rectangle<float> content (getContentArea().resolve (parent));
  69742. return AffineTransform::fromTargetPoints (content.getX(), content.getY(), resolved[0].getX(), resolved[0].getY(),
  69743. content.getRight(), content.getY(), resolved[1].getX(), resolved[1].getY(),
  69744. content.getX(), content.getBottom(), resolved[2].getX(), resolved[2].getY());
  69745. }
  69746. void DrawableComposite::render (const Drawable::RenderingContext& context) const
  69747. {
  69748. if (drawables.size() > 0 && context.opacity > 0)
  69749. {
  69750. if (context.opacity >= 1.0f || drawables.size() == 1)
  69751. {
  69752. Drawable::RenderingContext contextCopy (context);
  69753. contextCopy.transform = calculateTransform().followedBy (context.transform);
  69754. for (int i = 0; i < drawables.size(); ++i)
  69755. drawables.getUnchecked(i)->render (contextCopy);
  69756. }
  69757. else
  69758. {
  69759. // To correctly render a whole composite layer with an overall transparency,
  69760. // we need to render everything opaquely into a temp buffer, then blend that
  69761. // with the target opacity...
  69762. const Rectangle<int> clipBounds (context.g.getClipBounds());
  69763. if (! clipBounds.isEmpty())
  69764. {
  69765. Image tempImage (Image::ARGB, clipBounds.getWidth(), clipBounds.getHeight(), true);
  69766. {
  69767. Graphics tempG (tempImage);
  69768. tempG.setOrigin (-clipBounds.getX(), -clipBounds.getY());
  69769. Drawable::RenderingContext tempContext (tempG, context.transform, 1.0f);
  69770. render (tempContext);
  69771. }
  69772. context.g.setOpacity (context.opacity);
  69773. context.g.drawImageAt (tempImage, clipBounds.getX(), clipBounds.getY());
  69774. }
  69775. }
  69776. }
  69777. }
  69778. const Expression DrawableComposite::getSymbolValue (const String& symbol, const String& member) const
  69779. {
  69780. jassert (member.isEmpty()) // the only symbols available in a Drawable are markers.
  69781. int i;
  69782. for (i = 0; i < markersX.size(); ++i)
  69783. {
  69784. Marker* const m = markersX.getUnchecked(i);
  69785. if (m->name == symbol)
  69786. return m->position.getExpression();
  69787. }
  69788. for (i = 0; i < markersY.size(); ++i)
  69789. {
  69790. Marker* const m = markersY.getUnchecked(i);
  69791. if (m->name == symbol)
  69792. return m->position.getExpression();
  69793. }
  69794. throw Expression::EvaluationError (symbol, member);
  69795. }
  69796. const Rectangle<float> DrawableComposite::getUntransformedBounds (const bool includeMarkers) const
  69797. {
  69798. Rectangle<float> bounds;
  69799. int i;
  69800. for (i = 0; i < drawables.size(); ++i)
  69801. bounds = bounds.getUnion (drawables.getUnchecked(i)->getBounds());
  69802. if (includeMarkers)
  69803. {
  69804. if (markersX.size() > 0)
  69805. {
  69806. float minX = std::numeric_limits<float>::max();
  69807. float maxX = std::numeric_limits<float>::min();
  69808. for (i = markersX.size(); --i >= 0;)
  69809. {
  69810. const Marker* m = markersX.getUnchecked(i);
  69811. const float pos = (float) m->position.resolve (this);
  69812. minX = jmin (minX, pos);
  69813. maxX = jmax (maxX, pos);
  69814. }
  69815. if (minX <= maxX)
  69816. {
  69817. if (bounds.getHeight() > 0)
  69818. {
  69819. minX = jmin (minX, bounds.getX());
  69820. maxX = jmax (maxX, bounds.getRight());
  69821. }
  69822. bounds.setLeft (minX);
  69823. bounds.setWidth (maxX - minX);
  69824. }
  69825. }
  69826. if (markersY.size() > 0)
  69827. {
  69828. float minY = std::numeric_limits<float>::max();
  69829. float maxY = std::numeric_limits<float>::min();
  69830. for (i = markersY.size(); --i >= 0;)
  69831. {
  69832. const Marker* m = markersY.getUnchecked(i);
  69833. const float pos = (float) m->position.resolve (this);
  69834. minY = jmin (minY, pos);
  69835. maxY = jmax (maxY, pos);
  69836. }
  69837. if (minY <= maxY)
  69838. {
  69839. if (bounds.getHeight() > 0)
  69840. {
  69841. minY = jmin (minY, bounds.getY());
  69842. maxY = jmax (maxY, bounds.getBottom());
  69843. }
  69844. bounds.setTop (minY);
  69845. bounds.setHeight (maxY - minY);
  69846. }
  69847. }
  69848. }
  69849. return bounds;
  69850. }
  69851. const Rectangle<float> DrawableComposite::getBounds() const
  69852. {
  69853. return getUntransformedBounds (true).transformed (calculateTransform());
  69854. }
  69855. bool DrawableComposite::hitTest (float x, float y) const
  69856. {
  69857. calculateTransform().inverted().transformPoint (x, y);
  69858. for (int i = 0; i < drawables.size(); ++i)
  69859. if (drawables.getUnchecked(i)->hitTest (x, y))
  69860. return true;
  69861. return false;
  69862. }
  69863. Drawable* DrawableComposite::createCopy() const
  69864. {
  69865. return new DrawableComposite (*this);
  69866. }
  69867. void DrawableComposite::invalidatePoints()
  69868. {
  69869. for (int i = 0; i < drawables.size(); ++i)
  69870. drawables.getUnchecked(i)->invalidatePoints();
  69871. }
  69872. const Identifier DrawableComposite::valueTreeType ("Group");
  69873. const Identifier DrawableComposite::ValueTreeWrapper::topLeft ("topLeft");
  69874. const Identifier DrawableComposite::ValueTreeWrapper::topRight ("topRight");
  69875. const Identifier DrawableComposite::ValueTreeWrapper::bottomLeft ("bottomLeft");
  69876. const Identifier DrawableComposite::ValueTreeWrapper::childGroupTag ("Drawables");
  69877. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagX ("MarkersX");
  69878. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagY ("MarkersY");
  69879. const Identifier DrawableComposite::ValueTreeWrapper::markerTag ("Marker");
  69880. const Identifier DrawableComposite::ValueTreeWrapper::nameProperty ("name");
  69881. const Identifier DrawableComposite::ValueTreeWrapper::posProperty ("position");
  69882. DrawableComposite::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  69883. : ValueTreeWrapperBase (state_)
  69884. {
  69885. jassert (state.hasType (valueTreeType));
  69886. }
  69887. ValueTree DrawableComposite::ValueTreeWrapper::getChildList() const
  69888. {
  69889. return state.getChildWithName (childGroupTag);
  69890. }
  69891. ValueTree DrawableComposite::ValueTreeWrapper::getChildListCreating (UndoManager* undoManager)
  69892. {
  69893. return state.getOrCreateChildWithName (childGroupTag, undoManager);
  69894. }
  69895. int DrawableComposite::ValueTreeWrapper::getNumDrawables() const
  69896. {
  69897. return getChildList().getNumChildren();
  69898. }
  69899. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableState (int index) const
  69900. {
  69901. return getChildList().getChild (index);
  69902. }
  69903. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableWithId (const String& objectId, bool recursive) const
  69904. {
  69905. if (getID() == objectId)
  69906. return state;
  69907. if (! recursive)
  69908. {
  69909. return getChildList().getChildWithProperty (idProperty, objectId);
  69910. }
  69911. else
  69912. {
  69913. const ValueTree childList (getChildList());
  69914. for (int i = getNumDrawables(); --i >= 0;)
  69915. {
  69916. const ValueTree& child = childList.getChild (i);
  69917. if (child [Drawable::ValueTreeWrapperBase::idProperty] == objectId)
  69918. return child;
  69919. if (child.hasType (DrawableComposite::valueTreeType))
  69920. {
  69921. ValueTree v (DrawableComposite::ValueTreeWrapper (child).getDrawableWithId (objectId, true));
  69922. if (v.isValid())
  69923. return v;
  69924. }
  69925. }
  69926. return ValueTree::invalid;
  69927. }
  69928. }
  69929. int DrawableComposite::ValueTreeWrapper::indexOfDrawable (const ValueTree& item) const
  69930. {
  69931. return getChildList().indexOf (item);
  69932. }
  69933. void DrawableComposite::ValueTreeWrapper::addDrawable (const ValueTree& newDrawableState, int index, UndoManager* undoManager)
  69934. {
  69935. getChildListCreating (undoManager).addChild (newDrawableState, index, undoManager);
  69936. }
  69937. void DrawableComposite::ValueTreeWrapper::moveDrawableOrder (int currentIndex, int newIndex, UndoManager* undoManager)
  69938. {
  69939. getChildListCreating (undoManager).moveChild (currentIndex, newIndex, undoManager);
  69940. }
  69941. void DrawableComposite::ValueTreeWrapper::removeDrawable (const ValueTree& child, UndoManager* undoManager)
  69942. {
  69943. getChildList().removeChild (child, undoManager);
  69944. }
  69945. const RelativeParallelogram DrawableComposite::ValueTreeWrapper::getBoundingBox() const
  69946. {
  69947. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  69948. state.getProperty (topRight, "100, 0"),
  69949. state.getProperty (bottomLeft, "0, 100"));
  69950. }
  69951. void DrawableComposite::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  69952. {
  69953. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  69954. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  69955. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  69956. }
  69957. void DrawableComposite::ValueTreeWrapper::resetBoundingBoxToContentArea (UndoManager* undoManager)
  69958. {
  69959. const RelativeRectangle content (getContentArea());
  69960. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  69961. RelativePoint (content.right, content.top),
  69962. RelativePoint (content.left, content.bottom)), undoManager);
  69963. }
  69964. const RelativeRectangle DrawableComposite::ValueTreeWrapper::getContentArea() const
  69965. {
  69966. return RelativeRectangle (getMarker (true, getMarkerState (true, 0)).position,
  69967. getMarker (true, getMarkerState (true, 1)).position,
  69968. getMarker (false, getMarkerState (false, 0)).position,
  69969. getMarker (false, getMarkerState (false, 1)).position);
  69970. }
  69971. void DrawableComposite::ValueTreeWrapper::setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager)
  69972. {
  69973. setMarker (true, Marker (contentLeftMarkerName, newArea.left), undoManager);
  69974. setMarker (true, Marker (contentRightMarkerName, newArea.right), undoManager);
  69975. setMarker (false, Marker (contentTopMarkerName, newArea.top), undoManager);
  69976. setMarker (false, Marker (contentBottomMarkerName, newArea.bottom), undoManager);
  69977. }
  69978. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerList (bool xAxis) const
  69979. {
  69980. return state.getChildWithName (xAxis ? markerGroupTagX : markerGroupTagY);
  69981. }
  69982. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerListCreating (bool xAxis, UndoManager* undoManager)
  69983. {
  69984. return state.getOrCreateChildWithName (xAxis ? markerGroupTagX : markerGroupTagY, undoManager);
  69985. }
  69986. int DrawableComposite::ValueTreeWrapper::getNumMarkers (bool xAxis) const
  69987. {
  69988. return getMarkerList (xAxis).getNumChildren();
  69989. }
  69990. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, int index) const
  69991. {
  69992. return getMarkerList (xAxis).getChild (index);
  69993. }
  69994. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, const String& name) const
  69995. {
  69996. return getMarkerList (xAxis).getChildWithProperty (nameProperty, name);
  69997. }
  69998. bool DrawableComposite::ValueTreeWrapper::containsMarker (bool xAxis, const ValueTree& state) const
  69999. {
  70000. return state.isAChildOf (getMarkerList (xAxis));
  70001. }
  70002. const DrawableComposite::Marker DrawableComposite::ValueTreeWrapper::getMarker (bool xAxis, const ValueTree& state) const
  70003. {
  70004. (void) xAxis;
  70005. jassert (containsMarker (xAxis, state));
  70006. return Marker (state [nameProperty], RelativeCoordinate (state [posProperty].toString()));
  70007. }
  70008. void DrawableComposite::ValueTreeWrapper::setMarker (bool xAxis, const Marker& m, UndoManager* undoManager)
  70009. {
  70010. ValueTree markerList (getMarkerListCreating (xAxis, undoManager));
  70011. ValueTree marker (markerList.getChildWithProperty (nameProperty, m.name));
  70012. if (marker.isValid())
  70013. {
  70014. marker.setProperty (posProperty, m.position.toString(), undoManager);
  70015. }
  70016. else
  70017. {
  70018. marker = ValueTree (markerTag);
  70019. marker.setProperty (nameProperty, m.name, 0);
  70020. marker.setProperty (posProperty, m.position.toString(), 0);
  70021. markerList.addChild (marker, -1, undoManager);
  70022. }
  70023. }
  70024. void DrawableComposite::ValueTreeWrapper::removeMarker (bool xAxis, const ValueTree& state, UndoManager* undoManager)
  70025. {
  70026. if (state [nameProperty].toString() != contentLeftMarkerName
  70027. && state [nameProperty].toString() != contentRightMarkerName
  70028. && state [nameProperty].toString() != contentTopMarkerName
  70029. && state [nameProperty].toString() != contentBottomMarkerName)
  70030. return getMarkerList (xAxis).removeChild (state, undoManager);
  70031. }
  70032. const Rectangle<float> DrawableComposite::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70033. {
  70034. const ValueTreeWrapper wrapper (tree);
  70035. setName (wrapper.getID());
  70036. Rectangle<float> damage;
  70037. bool redrawAll = false;
  70038. const RelativeParallelogram newBounds (wrapper.getBoundingBox());
  70039. if (bounds != newBounds)
  70040. {
  70041. redrawAll = true;
  70042. damage = getBounds();
  70043. bounds = newBounds;
  70044. }
  70045. const int numMarkersX = wrapper.getNumMarkers (true);
  70046. const int numMarkersY = wrapper.getNumMarkers (false);
  70047. // Remove deleted markers...
  70048. if (markersX.size() > numMarkersX || markersY.size() > numMarkersY)
  70049. {
  70050. if (! redrawAll)
  70051. {
  70052. redrawAll = true;
  70053. damage = getBounds();
  70054. }
  70055. markersX.removeRange (jmax (2, numMarkersX), markersX.size());
  70056. markersY.removeRange (jmax (2, numMarkersY), markersY.size());
  70057. }
  70058. // Update markers and add new ones..
  70059. int i;
  70060. for (i = 0; i < numMarkersX; ++i)
  70061. {
  70062. const Marker newMarker (wrapper.getMarker (true, wrapper.getMarkerState (true, i)));
  70063. Marker* m = markersX[i];
  70064. if (m == 0 || newMarker != *m)
  70065. {
  70066. if (! redrawAll)
  70067. {
  70068. redrawAll = true;
  70069. damage = getBounds();
  70070. }
  70071. if (m == 0)
  70072. markersX.add (new Marker (newMarker));
  70073. else
  70074. *m = newMarker;
  70075. }
  70076. }
  70077. for (i = 0; i < numMarkersY; ++i)
  70078. {
  70079. const Marker newMarker (wrapper.getMarker (false, wrapper.getMarkerState (false, i)));
  70080. Marker* m = markersY[i];
  70081. if (m == 0 || newMarker != *m)
  70082. {
  70083. if (! redrawAll)
  70084. {
  70085. redrawAll = true;
  70086. damage = getBounds();
  70087. }
  70088. if (m == 0)
  70089. markersY.add (new Marker (newMarker));
  70090. else
  70091. *m = newMarker;
  70092. }
  70093. }
  70094. // Remove deleted drawables..
  70095. for (i = drawables.size(); --i >= wrapper.getNumDrawables();)
  70096. {
  70097. Drawable* const d = drawables.getUnchecked(i);
  70098. if (! redrawAll)
  70099. damage = damage.getUnion (d->getBounds());
  70100. d->parent = 0;
  70101. drawables.remove (i);
  70102. }
  70103. // Update drawables and add new ones..
  70104. for (i = 0; i < wrapper.getNumDrawables(); ++i)
  70105. {
  70106. const ValueTree newDrawable (wrapper.getDrawableState (i));
  70107. Drawable* d = drawables[i];
  70108. if (d != 0)
  70109. {
  70110. if (newDrawable.hasType (d->getValueTreeType()))
  70111. {
  70112. const Rectangle<float> area (d->refreshFromValueTree (newDrawable, imageProvider));
  70113. if (! redrawAll)
  70114. damage = damage.getUnion (area);
  70115. }
  70116. else
  70117. {
  70118. if (! redrawAll)
  70119. damage = damage.getUnion (d->getBounds());
  70120. d = createChildFromValueTree (this, newDrawable, imageProvider);
  70121. drawables.set (i, d);
  70122. if (! redrawAll)
  70123. damage = damage.getUnion (d->getBounds());
  70124. }
  70125. }
  70126. else
  70127. {
  70128. d = createChildFromValueTree (this, newDrawable, imageProvider);
  70129. drawables.set (i, d);
  70130. if (! redrawAll)
  70131. damage = damage.getUnion (d->getBounds());
  70132. }
  70133. }
  70134. if (redrawAll)
  70135. damage = damage.getUnion (getBounds());
  70136. else if (! damage.isEmpty())
  70137. damage = damage.transformed (calculateTransform());
  70138. return damage;
  70139. }
  70140. const ValueTree DrawableComposite::createValueTree (ImageProvider* imageProvider) const
  70141. {
  70142. ValueTree tree (valueTreeType);
  70143. ValueTreeWrapper v (tree);
  70144. v.setID (getName(), 0);
  70145. v.setBoundingBox (bounds, 0);
  70146. int i;
  70147. for (i = 0; i < drawables.size(); ++i)
  70148. v.addDrawable (drawables.getUnchecked(i)->createValueTree (imageProvider), -1, 0);
  70149. for (i = 0; i < markersX.size(); ++i)
  70150. v.setMarker (true, *markersX.getUnchecked(i), 0);
  70151. for (i = 0; i < markersY.size(); ++i)
  70152. v.setMarker (false, *markersY.getUnchecked(i), 0);
  70153. return tree;
  70154. }
  70155. END_JUCE_NAMESPACE
  70156. /*** End of inlined file: juce_DrawableComposite.cpp ***/
  70157. /*** Start of inlined file: juce_DrawableImage.cpp ***/
  70158. BEGIN_JUCE_NAMESPACE
  70159. DrawableImage::DrawableImage()
  70160. : image (0),
  70161. opacity (1.0f),
  70162. overlayColour (0x00000000)
  70163. {
  70164. bounds.topRight = RelativePoint (Point<float> (1.0f, 0.0f));
  70165. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, 1.0f));
  70166. }
  70167. DrawableImage::DrawableImage (const DrawableImage& other)
  70168. : image (other.image),
  70169. opacity (other.opacity),
  70170. overlayColour (other.overlayColour),
  70171. bounds (other.bounds)
  70172. {
  70173. }
  70174. DrawableImage::~DrawableImage()
  70175. {
  70176. }
  70177. void DrawableImage::setImage (const Image& imageToUse)
  70178. {
  70179. image = imageToUse;
  70180. if (image.isValid())
  70181. {
  70182. bounds.topLeft = RelativePoint (Point<float> (0.0f, 0.0f));
  70183. bounds.topRight = RelativePoint (Point<float> ((float) image.getWidth(), 0.0f));
  70184. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, (float) image.getHeight()));
  70185. }
  70186. }
  70187. void DrawableImage::setOpacity (const float newOpacity)
  70188. {
  70189. opacity = newOpacity;
  70190. }
  70191. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  70192. {
  70193. overlayColour = newOverlayColour;
  70194. }
  70195. void DrawableImage::setBoundingBox (const RelativeParallelogram& newBounds)
  70196. {
  70197. bounds = newBounds;
  70198. }
  70199. const AffineTransform DrawableImage::calculateTransform() const
  70200. {
  70201. if (image.isNull())
  70202. return AffineTransform::identity;
  70203. Point<float> resolved[3];
  70204. bounds.resolveThreePoints (resolved, parent);
  70205. const Point<float> tr (resolved[0] + (resolved[1] - resolved[0]) / (float) image.getWidth());
  70206. const Point<float> bl (resolved[0] + (resolved[2] - resolved[0]) / (float) image.getHeight());
  70207. return AffineTransform::fromTargetPoints (resolved[0].getX(), resolved[0].getY(),
  70208. tr.getX(), tr.getY(),
  70209. bl.getX(), bl.getY());
  70210. }
  70211. void DrawableImage::render (const Drawable::RenderingContext& context) const
  70212. {
  70213. if (image.isValid())
  70214. {
  70215. const AffineTransform t (calculateTransform().followedBy (context.transform));
  70216. if (opacity > 0.0f && ! overlayColour.isOpaque())
  70217. {
  70218. context.g.setOpacity (context.opacity * opacity);
  70219. context.g.drawImageTransformed (image, t, false);
  70220. }
  70221. if (! overlayColour.isTransparent())
  70222. {
  70223. context.g.setColour (overlayColour.withMultipliedAlpha (context.opacity));
  70224. context.g.drawImageTransformed (image, t, true);
  70225. }
  70226. }
  70227. }
  70228. const Rectangle<float> DrawableImage::getBounds() const
  70229. {
  70230. if (image.isNull())
  70231. return Rectangle<float>();
  70232. return bounds.getBounds (parent);
  70233. }
  70234. bool DrawableImage::hitTest (float x, float y) const
  70235. {
  70236. if (image.isNull())
  70237. return false;
  70238. calculateTransform().inverted().transformPoint (x, y);
  70239. const int ix = roundToInt (x);
  70240. const int iy = roundToInt (y);
  70241. return ix >= 0
  70242. && iy >= 0
  70243. && ix < image.getWidth()
  70244. && iy < image.getHeight()
  70245. && image.getPixelAt (ix, iy).getAlpha() >= 127;
  70246. }
  70247. Drawable* DrawableImage::createCopy() const
  70248. {
  70249. return new DrawableImage (*this);
  70250. }
  70251. void DrawableImage::invalidatePoints()
  70252. {
  70253. }
  70254. const Identifier DrawableImage::valueTreeType ("Image");
  70255. const Identifier DrawableImage::ValueTreeWrapper::opacity ("opacity");
  70256. const Identifier DrawableImage::ValueTreeWrapper::overlay ("overlay");
  70257. const Identifier DrawableImage::ValueTreeWrapper::image ("image");
  70258. const Identifier DrawableImage::ValueTreeWrapper::topLeft ("topLeft");
  70259. const Identifier DrawableImage::ValueTreeWrapper::topRight ("topRight");
  70260. const Identifier DrawableImage::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70261. DrawableImage::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70262. : ValueTreeWrapperBase (state_)
  70263. {
  70264. jassert (state.hasType (valueTreeType));
  70265. }
  70266. const var DrawableImage::ValueTreeWrapper::getImageIdentifier() const
  70267. {
  70268. return state [image];
  70269. }
  70270. Value DrawableImage::ValueTreeWrapper::getImageIdentifierValue (UndoManager* undoManager)
  70271. {
  70272. return state.getPropertyAsValue (image, undoManager);
  70273. }
  70274. void DrawableImage::ValueTreeWrapper::setImageIdentifier (const var& newIdentifier, UndoManager* undoManager)
  70275. {
  70276. state.setProperty (image, newIdentifier, undoManager);
  70277. }
  70278. float DrawableImage::ValueTreeWrapper::getOpacity() const
  70279. {
  70280. return (float) state.getProperty (opacity, 1.0);
  70281. }
  70282. Value DrawableImage::ValueTreeWrapper::getOpacityValue (UndoManager* undoManager)
  70283. {
  70284. if (! state.hasProperty (opacity))
  70285. state.setProperty (opacity, 1.0, undoManager);
  70286. return state.getPropertyAsValue (opacity, undoManager);
  70287. }
  70288. void DrawableImage::ValueTreeWrapper::setOpacity (float newOpacity, UndoManager* undoManager)
  70289. {
  70290. state.setProperty (opacity, newOpacity, undoManager);
  70291. }
  70292. const Colour DrawableImage::ValueTreeWrapper::getOverlayColour() const
  70293. {
  70294. return Colour (state [overlay].toString().getHexValue32());
  70295. }
  70296. void DrawableImage::ValueTreeWrapper::setOverlayColour (const Colour& newColour, UndoManager* undoManager)
  70297. {
  70298. if (newColour.isTransparent())
  70299. state.removeProperty (overlay, undoManager);
  70300. else
  70301. state.setProperty (overlay, String::toHexString ((int) newColour.getARGB()), undoManager);
  70302. }
  70303. Value DrawableImage::ValueTreeWrapper::getOverlayColourValue (UndoManager* undoManager)
  70304. {
  70305. return state.getPropertyAsValue (overlay, undoManager);
  70306. }
  70307. const RelativeParallelogram DrawableImage::ValueTreeWrapper::getBoundingBox() const
  70308. {
  70309. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70310. state.getProperty (topRight, "100, 0"),
  70311. state.getProperty (bottomLeft, "0, 100"));
  70312. }
  70313. void DrawableImage::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70314. {
  70315. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70316. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70317. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70318. }
  70319. const Rectangle<float> DrawableImage::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70320. {
  70321. const ValueTreeWrapper controller (tree);
  70322. setName (controller.getID());
  70323. const float newOpacity = controller.getOpacity();
  70324. const Colour newOverlayColour (controller.getOverlayColour());
  70325. Image newImage;
  70326. const var imageIdentifier (controller.getImageIdentifier());
  70327. jassert (imageProvider != 0 || imageIdentifier.isVoid()); // if you're using images, you need to provide something that can load and save them!
  70328. if (imageProvider != 0)
  70329. newImage = imageProvider->getImageForIdentifier (imageIdentifier);
  70330. const RelativeParallelogram newBounds (controller.getBoundingBox());
  70331. if (newOpacity != opacity || overlayColour != newOverlayColour || image != newImage || bounds != newBounds)
  70332. {
  70333. const Rectangle<float> damage (getBounds());
  70334. opacity = newOpacity;
  70335. overlayColour = newOverlayColour;
  70336. bounds = newBounds;
  70337. image = newImage;
  70338. return damage.getUnion (getBounds());
  70339. }
  70340. return Rectangle<float>();
  70341. }
  70342. const ValueTree DrawableImage::createValueTree (ImageProvider* imageProvider) const
  70343. {
  70344. ValueTree tree (valueTreeType);
  70345. ValueTreeWrapper v (tree);
  70346. v.setID (getName(), 0);
  70347. v.setOpacity (opacity, 0);
  70348. v.setOverlayColour (overlayColour, 0);
  70349. v.setBoundingBox (bounds, 0);
  70350. if (image.isValid())
  70351. {
  70352. jassert (imageProvider != 0); // if you're using images, you need to provide something that can load and save them!
  70353. if (imageProvider != 0)
  70354. v.setImageIdentifier (imageProvider->getIdentifierForImage (image), 0);
  70355. }
  70356. return tree;
  70357. }
  70358. END_JUCE_NAMESPACE
  70359. /*** End of inlined file: juce_DrawableImage.cpp ***/
  70360. /*** Start of inlined file: juce_DrawablePath.cpp ***/
  70361. BEGIN_JUCE_NAMESPACE
  70362. DrawablePath::DrawablePath()
  70363. : mainFill (Colours::black),
  70364. strokeFill (Colours::black),
  70365. strokeType (0.0f),
  70366. pathNeedsUpdating (true),
  70367. strokeNeedsUpdating (true)
  70368. {
  70369. }
  70370. DrawablePath::DrawablePath (const DrawablePath& other)
  70371. : mainFill (other.mainFill),
  70372. strokeFill (other.strokeFill),
  70373. strokeType (other.strokeType),
  70374. pathNeedsUpdating (true),
  70375. strokeNeedsUpdating (true)
  70376. {
  70377. if (other.relativePath != 0)
  70378. relativePath = new RelativePointPath (*other.relativePath);
  70379. else
  70380. path = other.path;
  70381. }
  70382. DrawablePath::~DrawablePath()
  70383. {
  70384. }
  70385. void DrawablePath::setPath (const Path& newPath)
  70386. {
  70387. path = newPath;
  70388. strokeNeedsUpdating = true;
  70389. }
  70390. void DrawablePath::setFill (const FillType& newFill)
  70391. {
  70392. mainFill = newFill;
  70393. }
  70394. void DrawablePath::setStrokeFill (const FillType& newFill)
  70395. {
  70396. strokeFill = newFill;
  70397. }
  70398. void DrawablePath::setStrokeType (const PathStrokeType& newStrokeType)
  70399. {
  70400. strokeType = newStrokeType;
  70401. strokeNeedsUpdating = true;
  70402. }
  70403. void DrawablePath::setStrokeThickness (const float newThickness)
  70404. {
  70405. setStrokeType (PathStrokeType (newThickness, strokeType.getJointStyle(), strokeType.getEndStyle()));
  70406. }
  70407. void DrawablePath::updatePath() const
  70408. {
  70409. if (pathNeedsUpdating)
  70410. {
  70411. pathNeedsUpdating = false;
  70412. if (relativePath != 0)
  70413. {
  70414. path.clear();
  70415. relativePath->createPath (path, parent);
  70416. strokeNeedsUpdating = true;
  70417. }
  70418. }
  70419. }
  70420. void DrawablePath::updateStroke() const
  70421. {
  70422. if (strokeNeedsUpdating)
  70423. {
  70424. strokeNeedsUpdating = false;
  70425. updatePath();
  70426. stroke.clear();
  70427. strokeType.createStrokedPath (stroke, path, AffineTransform::identity, 4.0f);
  70428. }
  70429. }
  70430. const Path& DrawablePath::getPath() const
  70431. {
  70432. updatePath();
  70433. return path;
  70434. }
  70435. const Path& DrawablePath::getStrokePath() const
  70436. {
  70437. updateStroke();
  70438. return stroke;
  70439. }
  70440. bool DrawablePath::isStrokeVisible() const throw()
  70441. {
  70442. return strokeType.getStrokeThickness() > 0.0f && ! strokeFill.isInvisible();
  70443. }
  70444. void DrawablePath::invalidatePoints()
  70445. {
  70446. pathNeedsUpdating = true;
  70447. strokeNeedsUpdating = true;
  70448. }
  70449. void DrawablePath::render (const Drawable::RenderingContext& context) const
  70450. {
  70451. {
  70452. FillType f (mainFill);
  70453. if (f.isGradient())
  70454. f.gradient->multiplyOpacity (context.opacity);
  70455. else
  70456. f.setOpacity (f.getOpacity() * context.opacity);
  70457. f.transform = f.transform.followedBy (context.transform);
  70458. context.g.setFillType (f);
  70459. context.g.fillPath (getPath(), context.transform);
  70460. }
  70461. if (isStrokeVisible())
  70462. {
  70463. FillType f (strokeFill);
  70464. if (f.isGradient())
  70465. f.gradient->multiplyOpacity (context.opacity);
  70466. else
  70467. f.setOpacity (f.getOpacity() * context.opacity);
  70468. f.transform = f.transform.followedBy (context.transform);
  70469. context.g.setFillType (f);
  70470. context.g.fillPath (getStrokePath(), context.transform);
  70471. }
  70472. }
  70473. const Rectangle<float> DrawablePath::getBounds() const
  70474. {
  70475. if (isStrokeVisible())
  70476. return getStrokePath().getBounds();
  70477. else
  70478. return getPath().getBounds();
  70479. }
  70480. bool DrawablePath::hitTest (float x, float y) const
  70481. {
  70482. return getPath().contains (x, y)
  70483. || (isStrokeVisible() && getStrokePath().contains (x, y));
  70484. }
  70485. Drawable* DrawablePath::createCopy() const
  70486. {
  70487. return new DrawablePath (*this);
  70488. }
  70489. const Identifier DrawablePath::valueTreeType ("Path");
  70490. const Identifier DrawablePath::ValueTreeWrapper::fill ("Fill");
  70491. const Identifier DrawablePath::ValueTreeWrapper::stroke ("Stroke");
  70492. const Identifier DrawablePath::ValueTreeWrapper::path ("Path");
  70493. const Identifier DrawablePath::ValueTreeWrapper::jointStyle ("jointStyle");
  70494. const Identifier DrawablePath::ValueTreeWrapper::capStyle ("capStyle");
  70495. const Identifier DrawablePath::ValueTreeWrapper::strokeWidth ("strokeWidth");
  70496. const Identifier DrawablePath::ValueTreeWrapper::nonZeroWinding ("nonZeroWinding");
  70497. const Identifier DrawablePath::ValueTreeWrapper::point1 ("p1");
  70498. const Identifier DrawablePath::ValueTreeWrapper::point2 ("p2");
  70499. const Identifier DrawablePath::ValueTreeWrapper::point3 ("p3");
  70500. DrawablePath::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70501. : ValueTreeWrapperBase (state_)
  70502. {
  70503. jassert (state.hasType (valueTreeType));
  70504. }
  70505. ValueTree DrawablePath::ValueTreeWrapper::getPathState()
  70506. {
  70507. return state.getOrCreateChildWithName (path, 0);
  70508. }
  70509. ValueTree DrawablePath::ValueTreeWrapper::getMainFillState()
  70510. {
  70511. ValueTree v (state.getChildWithName (fill));
  70512. if (v.isValid())
  70513. return v;
  70514. setMainFill (Colours::black, 0, 0, 0, 0, 0);
  70515. return getMainFillState();
  70516. }
  70517. ValueTree DrawablePath::ValueTreeWrapper::getStrokeFillState()
  70518. {
  70519. ValueTree v (state.getChildWithName (stroke));
  70520. if (v.isValid())
  70521. return v;
  70522. setStrokeFill (Colours::black, 0, 0, 0, 0, 0);
  70523. return getStrokeFillState();
  70524. }
  70525. const FillType DrawablePath::ValueTreeWrapper::getMainFill (Expression::EvaluationContext* nameFinder,
  70526. ImageProvider* imageProvider) const
  70527. {
  70528. return readFillType (state.getChildWithName (fill), 0, 0, 0, nameFinder, imageProvider);
  70529. }
  70530. void DrawablePath::ValueTreeWrapper::setMainFill (const FillType& newFill, const RelativePoint* gp1,
  70531. const RelativePoint* gp2, const RelativePoint* gp3,
  70532. ImageProvider* imageProvider, UndoManager* undoManager)
  70533. {
  70534. ValueTree v (state.getOrCreateChildWithName (fill, undoManager));
  70535. writeFillType (v, newFill, gp1, gp2, gp3, imageProvider, undoManager);
  70536. }
  70537. const FillType DrawablePath::ValueTreeWrapper::getStrokeFill (Expression::EvaluationContext* nameFinder,
  70538. ImageProvider* imageProvider) const
  70539. {
  70540. return readFillType (state.getChildWithName (stroke), 0, 0, 0, nameFinder, imageProvider);
  70541. }
  70542. void DrawablePath::ValueTreeWrapper::setStrokeFill (const FillType& newFill, const RelativePoint* gp1,
  70543. const RelativePoint* gp2, const RelativePoint* gp3,
  70544. ImageProvider* imageProvider, UndoManager* undoManager)
  70545. {
  70546. ValueTree v (state.getOrCreateChildWithName (stroke, undoManager));
  70547. writeFillType (v, newFill, gp1, gp2, gp3, imageProvider, undoManager);
  70548. }
  70549. const PathStrokeType DrawablePath::ValueTreeWrapper::getStrokeType() const
  70550. {
  70551. const String jointStyleString (state [jointStyle].toString());
  70552. const String capStyleString (state [capStyle].toString());
  70553. return PathStrokeType (state [strokeWidth],
  70554. jointStyleString == "curved" ? PathStrokeType::curved
  70555. : (jointStyleString == "bevel" ? PathStrokeType::beveled
  70556. : PathStrokeType::mitered),
  70557. capStyleString == "square" ? PathStrokeType::square
  70558. : (capStyleString == "round" ? PathStrokeType::rounded
  70559. : PathStrokeType::butt));
  70560. }
  70561. void DrawablePath::ValueTreeWrapper::setStrokeType (const PathStrokeType& newStrokeType, UndoManager* undoManager)
  70562. {
  70563. state.setProperty (strokeWidth, (double) newStrokeType.getStrokeThickness(), undoManager);
  70564. state.setProperty (jointStyle, newStrokeType.getJointStyle() == PathStrokeType::mitered
  70565. ? "miter" : (newStrokeType.getJointStyle() == PathStrokeType::curved ? "curved" : "bevel"), undoManager);
  70566. state.setProperty (capStyle, newStrokeType.getEndStyle() == PathStrokeType::butt
  70567. ? "butt" : (newStrokeType.getEndStyle() == PathStrokeType::square ? "square" : "round"), undoManager);
  70568. }
  70569. bool DrawablePath::ValueTreeWrapper::usesNonZeroWinding() const
  70570. {
  70571. return state [nonZeroWinding];
  70572. }
  70573. void DrawablePath::ValueTreeWrapper::setUsesNonZeroWinding (bool b, UndoManager* undoManager)
  70574. {
  70575. state.setProperty (nonZeroWinding, b, undoManager);
  70576. }
  70577. const Identifier DrawablePath::ValueTreeWrapper::Element::mode ("mode");
  70578. const Identifier DrawablePath::ValueTreeWrapper::Element::startSubPathElement ("Move");
  70579. const Identifier DrawablePath::ValueTreeWrapper::Element::closeSubPathElement ("Close");
  70580. const Identifier DrawablePath::ValueTreeWrapper::Element::lineToElement ("Line");
  70581. const Identifier DrawablePath::ValueTreeWrapper::Element::quadraticToElement ("Quad");
  70582. const Identifier DrawablePath::ValueTreeWrapper::Element::cubicToElement ("Cubic");
  70583. const char* DrawablePath::ValueTreeWrapper::Element::cornerMode = "corner";
  70584. const char* DrawablePath::ValueTreeWrapper::Element::roundedMode = "round";
  70585. const char* DrawablePath::ValueTreeWrapper::Element::symmetricMode = "symm";
  70586. DrawablePath::ValueTreeWrapper::Element::Element (const ValueTree& state_)
  70587. : state (state_)
  70588. {
  70589. }
  70590. DrawablePath::ValueTreeWrapper::Element::~Element()
  70591. {
  70592. }
  70593. DrawablePath::ValueTreeWrapper DrawablePath::ValueTreeWrapper::Element::getParent() const
  70594. {
  70595. return ValueTreeWrapper (state.getParent().getParent());
  70596. }
  70597. DrawablePath::ValueTreeWrapper::Element DrawablePath::ValueTreeWrapper::Element::getPreviousElement() const
  70598. {
  70599. return Element (state.getSibling (-1));
  70600. }
  70601. int DrawablePath::ValueTreeWrapper::Element::getNumControlPoints() const throw()
  70602. {
  70603. const Identifier i (state.getType());
  70604. if (i == startSubPathElement || i == lineToElement) return 1;
  70605. if (i == quadraticToElement) return 2;
  70606. if (i == cubicToElement) return 3;
  70607. return 0;
  70608. }
  70609. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getControlPoint (const int index) const
  70610. {
  70611. jassert (index >= 0 && index < getNumControlPoints());
  70612. return RelativePoint (state [index == 0 ? point1 : (index == 1 ? point2 : point3)].toString());
  70613. }
  70614. Value DrawablePath::ValueTreeWrapper::Element::getControlPointValue (int index, UndoManager* undoManager) const
  70615. {
  70616. jassert (index >= 0 && index < getNumControlPoints());
  70617. return state.getPropertyAsValue (index == 0 ? point1 : (index == 1 ? point2 : point3), undoManager);
  70618. }
  70619. void DrawablePath::ValueTreeWrapper::Element::setControlPoint (const int index, const RelativePoint& point, UndoManager* undoManager)
  70620. {
  70621. jassert (index >= 0 && index < getNumControlPoints());
  70622. return state.setProperty (index == 0 ? point1 : (index == 1 ? point2 : point3), point.toString(), undoManager);
  70623. }
  70624. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getStartPoint() const
  70625. {
  70626. const Identifier i (state.getType());
  70627. if (i == startSubPathElement)
  70628. return getControlPoint (0);
  70629. jassert (i == lineToElement || i == quadraticToElement || i == cubicToElement || i == closeSubPathElement);
  70630. return getPreviousElement().getEndPoint();
  70631. }
  70632. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getEndPoint() const
  70633. {
  70634. const Identifier i (state.getType());
  70635. if (i == startSubPathElement || i == lineToElement) return getControlPoint (0);
  70636. if (i == quadraticToElement) return getControlPoint (1);
  70637. if (i == cubicToElement) return getControlPoint (2);
  70638. jassert (i == closeSubPathElement);
  70639. return RelativePoint();
  70640. }
  70641. float DrawablePath::ValueTreeWrapper::Element::getLength (Expression::EvaluationContext* nameFinder) const
  70642. {
  70643. const Identifier i (state.getType());
  70644. if (i == lineToElement || i == closeSubPathElement)
  70645. return getEndPoint().resolve (nameFinder).getDistanceFrom (getStartPoint().resolve (nameFinder));
  70646. if (i == cubicToElement)
  70647. {
  70648. Path p;
  70649. p.startNewSubPath (getStartPoint().resolve (nameFinder));
  70650. p.cubicTo (getControlPoint (0).resolve (nameFinder), getControlPoint (1).resolve (nameFinder), getControlPoint (2).resolve (nameFinder));
  70651. return p.getLength();
  70652. }
  70653. if (i == quadraticToElement)
  70654. {
  70655. Path p;
  70656. p.startNewSubPath (getStartPoint().resolve (nameFinder));
  70657. p.quadraticTo (getControlPoint (0).resolve (nameFinder), getControlPoint (1).resolve (nameFinder));
  70658. return p.getLength();
  70659. }
  70660. jassert (i == startSubPathElement);
  70661. return 0;
  70662. }
  70663. const String DrawablePath::ValueTreeWrapper::Element::getModeOfEndPoint() const
  70664. {
  70665. return state [mode].toString();
  70666. }
  70667. void DrawablePath::ValueTreeWrapper::Element::setModeOfEndPoint (const String& newMode, UndoManager* undoManager)
  70668. {
  70669. if (state.hasType (cubicToElement))
  70670. state.setProperty (mode, newMode, undoManager);
  70671. }
  70672. void DrawablePath::ValueTreeWrapper::Element::convertToLine (UndoManager* undoManager)
  70673. {
  70674. const Identifier i (state.getType());
  70675. if (i == quadraticToElement || i == cubicToElement)
  70676. {
  70677. ValueTree newState (lineToElement);
  70678. Element e (newState);
  70679. e.setControlPoint (0, getEndPoint(), undoManager);
  70680. state = newState;
  70681. }
  70682. }
  70683. void DrawablePath::ValueTreeWrapper::Element::convertToCubic (Expression::EvaluationContext* nameFinder, UndoManager* undoManager)
  70684. {
  70685. const Identifier i (state.getType());
  70686. if (i == lineToElement || i == quadraticToElement)
  70687. {
  70688. ValueTree newState (cubicToElement);
  70689. Element e (newState);
  70690. const RelativePoint start (getStartPoint());
  70691. const RelativePoint end (getEndPoint());
  70692. const Point<float> startResolved (start.resolve (nameFinder));
  70693. const Point<float> endResolved (end.resolve (nameFinder));
  70694. e.setControlPoint (0, startResolved + (endResolved - startResolved) * 0.3f, undoManager);
  70695. e.setControlPoint (1, startResolved + (endResolved - startResolved) * 0.7f, undoManager);
  70696. e.setControlPoint (2, end, undoManager);
  70697. state = newState;
  70698. }
  70699. }
  70700. void DrawablePath::ValueTreeWrapper::Element::convertToPathBreak (UndoManager* undoManager)
  70701. {
  70702. const Identifier i (state.getType());
  70703. if (i != startSubPathElement)
  70704. {
  70705. ValueTree newState (startSubPathElement);
  70706. Element e (newState);
  70707. e.setControlPoint (0, getEndPoint(), undoManager);
  70708. state = newState;
  70709. }
  70710. }
  70711. static const Point<float> findCubicSubdivisionPoint (float proportion, const Point<float> points[4])
  70712. {
  70713. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70714. mid2 (points[1] + (points[2] - points[1]) * proportion),
  70715. mid3 (points[2] + (points[3] - points[2]) * proportion);
  70716. const Point<float> newCp1 (mid1 + (mid2 - mid1) * proportion),
  70717. newCp2 (mid2 + (mid3 - mid2) * proportion);
  70718. return newCp1 + (newCp2 - newCp1) * proportion;
  70719. }
  70720. static const Point<float> findQuadraticSubdivisionPoint (float proportion, const Point<float> points[3])
  70721. {
  70722. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70723. mid2 (points[1] + (points[2] - points[1]) * proportion);
  70724. return mid1 + (mid2 - mid1) * proportion;
  70725. }
  70726. float DrawablePath::ValueTreeWrapper::Element::findProportionAlongLine (const Point<float>& targetPoint, Expression::EvaluationContext* nameFinder) const
  70727. {
  70728. const Identifier i (state.getType());
  70729. float bestProp = 0;
  70730. if (i == cubicToElement)
  70731. {
  70732. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70733. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder), rp4.resolve (nameFinder) };
  70734. float bestDistance = std::numeric_limits<float>::max();
  70735. for (int i = 110; --i >= 0;)
  70736. {
  70737. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70738. const Point<float> centre (findCubicSubdivisionPoint (prop, points));
  70739. const float distance = centre.getDistanceFrom (targetPoint);
  70740. if (distance < bestDistance)
  70741. {
  70742. bestProp = prop;
  70743. bestDistance = distance;
  70744. }
  70745. }
  70746. }
  70747. else if (i == quadraticToElement)
  70748. {
  70749. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70750. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder) };
  70751. float bestDistance = std::numeric_limits<float>::max();
  70752. for (int i = 110; --i >= 0;)
  70753. {
  70754. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70755. const Point<float> centre (findQuadraticSubdivisionPoint ((float) prop, points));
  70756. const float distance = centre.getDistanceFrom (targetPoint);
  70757. if (distance < bestDistance)
  70758. {
  70759. bestProp = prop;
  70760. bestDistance = distance;
  70761. }
  70762. }
  70763. }
  70764. else if (i == lineToElement)
  70765. {
  70766. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70767. const Line<float> line (rp1.resolve (nameFinder), rp2.resolve (nameFinder));
  70768. bestProp = line.findNearestProportionalPositionTo (targetPoint);
  70769. }
  70770. return bestProp;
  70771. }
  70772. ValueTree DrawablePath::ValueTreeWrapper::Element::insertPoint (const Point<float>& targetPoint, Expression::EvaluationContext* nameFinder, UndoManager* undoManager)
  70773. {
  70774. ValueTree newTree;
  70775. const Identifier i (state.getType());
  70776. if (i == cubicToElement)
  70777. {
  70778. float bestProp = findProportionAlongLine (targetPoint, nameFinder);
  70779. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70780. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder), rp4.resolve (nameFinder) };
  70781. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70782. mid2 (points[1] + (points[2] - points[1]) * bestProp),
  70783. mid3 (points[2] + (points[3] - points[2]) * bestProp);
  70784. const Point<float> newCp1 (mid1 + (mid2 - mid1) * bestProp),
  70785. newCp2 (mid2 + (mid3 - mid2) * bestProp);
  70786. const Point<float> newCentre (newCp1 + (newCp2 - newCp1) * bestProp);
  70787. setControlPoint (0, mid1, undoManager);
  70788. setControlPoint (1, newCp1, undoManager);
  70789. setControlPoint (2, newCentre, undoManager);
  70790. setModeOfEndPoint (roundedMode, undoManager);
  70791. Element newElement (newTree = ValueTree (cubicToElement));
  70792. newElement.setControlPoint (0, newCp2, 0);
  70793. newElement.setControlPoint (1, mid3, 0);
  70794. newElement.setControlPoint (2, rp4, 0);
  70795. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70796. }
  70797. else if (i == quadraticToElement)
  70798. {
  70799. float bestProp = findProportionAlongLine (targetPoint, nameFinder);
  70800. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70801. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder) };
  70802. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70803. mid2 (points[1] + (points[2] - points[1]) * bestProp);
  70804. const Point<float> newCentre (mid1 + (mid2 - mid1) * bestProp);
  70805. setControlPoint (0, mid1, undoManager);
  70806. setControlPoint (1, newCentre, undoManager);
  70807. setModeOfEndPoint (roundedMode, undoManager);
  70808. Element newElement (newTree = ValueTree (quadraticToElement));
  70809. newElement.setControlPoint (0, mid2, 0);
  70810. newElement.setControlPoint (1, rp3, 0);
  70811. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70812. }
  70813. else if (i == lineToElement)
  70814. {
  70815. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70816. const Line<float> line (rp1.resolve (nameFinder), rp2.resolve (nameFinder));
  70817. const Point<float> newPoint (line.findNearestPointTo (targetPoint));
  70818. setControlPoint (0, newPoint, undoManager);
  70819. Element newElement (newTree = ValueTree (lineToElement));
  70820. newElement.setControlPoint (0, rp2, 0);
  70821. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70822. }
  70823. else if (i == closeSubPathElement)
  70824. {
  70825. }
  70826. return newTree;
  70827. }
  70828. void DrawablePath::ValueTreeWrapper::Element::removePoint (UndoManager* undoManager)
  70829. {
  70830. state.getParent().removeChild (state, undoManager);
  70831. }
  70832. const Rectangle<float> DrawablePath::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70833. {
  70834. Rectangle<float> damageRect;
  70835. ValueTreeWrapper v (tree);
  70836. setName (v.getID());
  70837. bool needsRedraw = false;
  70838. const FillType newFill (v.getMainFill (parent, imageProvider));
  70839. if (mainFill != newFill)
  70840. {
  70841. needsRedraw = true;
  70842. mainFill = newFill;
  70843. }
  70844. const FillType newStrokeFill (v.getStrokeFill (parent, imageProvider));
  70845. if (strokeFill != newStrokeFill)
  70846. {
  70847. needsRedraw = true;
  70848. strokeFill = newStrokeFill;
  70849. }
  70850. const PathStrokeType newStroke (v.getStrokeType());
  70851. ScopedPointer<RelativePointPath> newRelativePath (new RelativePointPath (tree));
  70852. Path newPath;
  70853. newRelativePath->createPath (newPath, parent);
  70854. if (! newRelativePath->containsAnyDynamicPoints())
  70855. newRelativePath = 0;
  70856. if (strokeType != newStroke || path != newPath)
  70857. {
  70858. damageRect = getBounds();
  70859. path.swapWithPath (newPath);
  70860. strokeNeedsUpdating = true;
  70861. strokeType = newStroke;
  70862. needsRedraw = true;
  70863. }
  70864. relativePath = newRelativePath;
  70865. if (needsRedraw)
  70866. damageRect = damageRect.getUnion (getBounds());
  70867. return damageRect;
  70868. }
  70869. const ValueTree DrawablePath::createValueTree (ImageProvider* imageProvider) const
  70870. {
  70871. ValueTree tree (valueTreeType);
  70872. ValueTreeWrapper v (tree);
  70873. v.setID (getName(), 0);
  70874. v.setMainFill (mainFill, 0, 0, 0, imageProvider, 0);
  70875. v.setStrokeFill (strokeFill, 0, 0, 0, imageProvider, 0);
  70876. v.setStrokeType (strokeType, 0);
  70877. if (relativePath != 0)
  70878. {
  70879. relativePath->writeTo (tree, 0);
  70880. }
  70881. else
  70882. {
  70883. RelativePointPath rp (path);
  70884. rp.writeTo (tree, 0);
  70885. }
  70886. return tree;
  70887. }
  70888. END_JUCE_NAMESPACE
  70889. /*** End of inlined file: juce_DrawablePath.cpp ***/
  70890. /*** Start of inlined file: juce_DrawableText.cpp ***/
  70891. BEGIN_JUCE_NAMESPACE
  70892. DrawableText::DrawableText()
  70893. : colour (Colours::black),
  70894. justification (Justification::centredLeft)
  70895. {
  70896. setBoundingBox (RelativeParallelogram (RelativePoint (0.0f, 0.0f),
  70897. RelativePoint (50.0f, 0.0f),
  70898. RelativePoint (0.0f, 20.0f)));
  70899. setFont (Font (15.0f), true);
  70900. }
  70901. DrawableText::DrawableText (const DrawableText& other)
  70902. : text (other.text),
  70903. font (other.font),
  70904. colour (other.colour),
  70905. justification (other.justification),
  70906. bounds (other.bounds),
  70907. fontSizeControlPoint (other.fontSizeControlPoint)
  70908. {
  70909. }
  70910. DrawableText::~DrawableText()
  70911. {
  70912. }
  70913. void DrawableText::setText (const String& newText)
  70914. {
  70915. text = newText;
  70916. }
  70917. void DrawableText::setColour (const Colour& newColour)
  70918. {
  70919. colour = newColour;
  70920. }
  70921. void DrawableText::setFont (const Font& newFont, bool applySizeAndScale)
  70922. {
  70923. font = newFont;
  70924. if (applySizeAndScale)
  70925. {
  70926. Point<float> corners[3];
  70927. bounds.resolveThreePoints (corners, parent);
  70928. setFontSizeControlPoint (RelativePoint (RelativeParallelogram::getPointForInternalCoord (corners,
  70929. Point<float> (font.getHorizontalScale() * font.getHeight(), font.getHeight()))));
  70930. }
  70931. }
  70932. void DrawableText::setJustification (const Justification& newJustification)
  70933. {
  70934. justification = newJustification;
  70935. }
  70936. void DrawableText::setBoundingBox (const RelativeParallelogram& newBounds)
  70937. {
  70938. bounds = newBounds;
  70939. }
  70940. void DrawableText::setFontSizeControlPoint (const RelativePoint& newPoint)
  70941. {
  70942. fontSizeControlPoint = newPoint;
  70943. }
  70944. void DrawableText::render (const Drawable::RenderingContext& context) const
  70945. {
  70946. Point<float> points[3];
  70947. bounds.resolveThreePoints (points, parent);
  70948. const float w = Line<float> (points[0], points[1]).getLength();
  70949. const float h = Line<float> (points[0], points[2]).getLength();
  70950. const Point<float> fontCoords (bounds.getInternalCoordForPoint (points, fontSizeControlPoint.resolve (parent)));
  70951. const float fontHeight = jlimit (1.0f, h, fontCoords.getY());
  70952. const float fontWidth = jlimit (0.01f, w, fontCoords.getX());
  70953. Font f (font);
  70954. f.setHeight (fontHeight);
  70955. f.setHorizontalScale (fontWidth / fontHeight);
  70956. context.g.setColour (colour.withMultipliedAlpha (context.opacity));
  70957. GlyphArrangement ga;
  70958. ga.addFittedText (f, text, 0, 0, w, h, justification, 0x100000);
  70959. ga.draw (context.g,
  70960. AffineTransform::fromTargetPoints (0, 0, points[0].getX(), points[0].getY(),
  70961. w, 0, points[1].getX(), points[1].getY(),
  70962. 0, h, points[2].getX(), points[2].getY())
  70963. .followedBy (context.transform));
  70964. }
  70965. const Rectangle<float> DrawableText::getBounds() const
  70966. {
  70967. return bounds.getBounds (parent);
  70968. }
  70969. bool DrawableText::hitTest (float x, float y) const
  70970. {
  70971. Path p;
  70972. bounds.getPath (p, parent);
  70973. return p.contains (x, y);
  70974. }
  70975. Drawable* DrawableText::createCopy() const
  70976. {
  70977. return new DrawableText (*this);
  70978. }
  70979. void DrawableText::invalidatePoints()
  70980. {
  70981. }
  70982. const Identifier DrawableText::valueTreeType ("Text");
  70983. const Identifier DrawableText::ValueTreeWrapper::text ("text");
  70984. const Identifier DrawableText::ValueTreeWrapper::colour ("colour");
  70985. const Identifier DrawableText::ValueTreeWrapper::font ("font");
  70986. const Identifier DrawableText::ValueTreeWrapper::justification ("justification");
  70987. const Identifier DrawableText::ValueTreeWrapper::topLeft ("topLeft");
  70988. const Identifier DrawableText::ValueTreeWrapper::topRight ("topRight");
  70989. const Identifier DrawableText::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70990. const Identifier DrawableText::ValueTreeWrapper::fontSizeAnchor ("fontSizeAnchor");
  70991. DrawableText::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70992. : ValueTreeWrapperBase (state_)
  70993. {
  70994. jassert (state.hasType (valueTreeType));
  70995. }
  70996. const String DrawableText::ValueTreeWrapper::getText() const
  70997. {
  70998. return state [text].toString();
  70999. }
  71000. void DrawableText::ValueTreeWrapper::setText (const String& newText, UndoManager* undoManager)
  71001. {
  71002. state.setProperty (text, newText, undoManager);
  71003. }
  71004. Value DrawableText::ValueTreeWrapper::getTextValue (UndoManager* undoManager)
  71005. {
  71006. return state.getPropertyAsValue (text, undoManager);
  71007. }
  71008. const Colour DrawableText::ValueTreeWrapper::getColour() const
  71009. {
  71010. return Colour::fromString (state [colour].toString());
  71011. }
  71012. void DrawableText::ValueTreeWrapper::setColour (const Colour& newColour, UndoManager* undoManager)
  71013. {
  71014. state.setProperty (colour, newColour.toString(), undoManager);
  71015. }
  71016. const Justification DrawableText::ValueTreeWrapper::getJustification() const
  71017. {
  71018. return Justification ((int) state [justification]);
  71019. }
  71020. void DrawableText::ValueTreeWrapper::setJustification (const Justification& newJustification, UndoManager* undoManager)
  71021. {
  71022. state.setProperty (justification, newJustification.getFlags(), undoManager);
  71023. }
  71024. const Font DrawableText::ValueTreeWrapper::getFont() const
  71025. {
  71026. return Font::fromString (state [font]);
  71027. }
  71028. void DrawableText::ValueTreeWrapper::setFont (const Font& newFont, UndoManager* undoManager)
  71029. {
  71030. state.setProperty (font, newFont.toString(), undoManager);
  71031. }
  71032. Value DrawableText::ValueTreeWrapper::getFontValue (UndoManager* undoManager)
  71033. {
  71034. return state.getPropertyAsValue (font, undoManager);
  71035. }
  71036. const RelativeParallelogram DrawableText::ValueTreeWrapper::getBoundingBox() const
  71037. {
  71038. return RelativeParallelogram (state [topLeft].toString(), state [topRight].toString(), state [bottomLeft].toString());
  71039. }
  71040. void DrawableText::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  71041. {
  71042. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  71043. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  71044. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  71045. }
  71046. const RelativePoint DrawableText::ValueTreeWrapper::getFontSizeControlPoint() const
  71047. {
  71048. return state [fontSizeAnchor].toString();
  71049. }
  71050. void DrawableText::ValueTreeWrapper::setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager)
  71051. {
  71052. state.setProperty (fontSizeAnchor, p.toString(), undoManager);
  71053. }
  71054. const Rectangle<float> DrawableText::refreshFromValueTree (const ValueTree& tree, ImageProvider*)
  71055. {
  71056. ValueTreeWrapper v (tree);
  71057. setName (v.getID());
  71058. const RelativeParallelogram newBounds (v.getBoundingBox());
  71059. const RelativePoint newFontPoint (v.getFontSizeControlPoint());
  71060. const Colour newColour (v.getColour());
  71061. const Justification newJustification (v.getJustification());
  71062. const String newText (v.getText());
  71063. const Font newFont (v.getFont());
  71064. if (text != newText || font != newFont || justification != newJustification
  71065. || colour != newColour || bounds != newBounds || newFontPoint != fontSizeControlPoint)
  71066. {
  71067. const Rectangle<float> damage (getBounds());
  71068. setBoundingBox (newBounds);
  71069. setFontSizeControlPoint (newFontPoint);
  71070. setColour (newColour);
  71071. setFont (newFont, false);
  71072. setJustification (newJustification);
  71073. setText (newText);
  71074. return damage.getUnion (getBounds());
  71075. }
  71076. return Rectangle<float>();
  71077. }
  71078. const ValueTree DrawableText::createValueTree (ImageProvider*) const
  71079. {
  71080. ValueTree tree (valueTreeType);
  71081. ValueTreeWrapper v (tree);
  71082. v.setID (getName(), 0);
  71083. v.setText (text, 0);
  71084. v.setFont (font, 0);
  71085. v.setJustification (justification, 0);
  71086. v.setColour (colour, 0);
  71087. v.setBoundingBox (bounds, 0);
  71088. v.setFontSizeControlPoint (fontSizeControlPoint, 0);
  71089. return tree;
  71090. }
  71091. END_JUCE_NAMESPACE
  71092. /*** End of inlined file: juce_DrawableText.cpp ***/
  71093. /*** Start of inlined file: juce_SVGParser.cpp ***/
  71094. BEGIN_JUCE_NAMESPACE
  71095. class SVGState
  71096. {
  71097. public:
  71098. SVGState (const XmlElement* const topLevel)
  71099. : topLevelXml (topLevel),
  71100. elementX (0), elementY (0),
  71101. width (512), height (512),
  71102. viewBoxW (0), viewBoxH (0)
  71103. {
  71104. }
  71105. ~SVGState()
  71106. {
  71107. }
  71108. Drawable* parseSVGElement (const XmlElement& xml)
  71109. {
  71110. if (! xml.hasTagName ("svg"))
  71111. return 0;
  71112. DrawableComposite* const drawable = new DrawableComposite();
  71113. drawable->setName (xml.getStringAttribute ("id"));
  71114. SVGState newState (*this);
  71115. if (xml.hasAttribute ("transform"))
  71116. newState.addTransform (xml);
  71117. newState.elementX = getCoordLength (xml.getStringAttribute ("x", String (newState.elementX)), viewBoxW);
  71118. newState.elementY = getCoordLength (xml.getStringAttribute ("y", String (newState.elementY)), viewBoxH);
  71119. newState.width = getCoordLength (xml.getStringAttribute ("width", String (newState.width)), viewBoxW);
  71120. newState.height = getCoordLength (xml.getStringAttribute ("height", String (newState.height)), viewBoxH);
  71121. if (xml.hasAttribute ("viewBox"))
  71122. {
  71123. const String viewParams (xml.getStringAttribute ("viewBox"));
  71124. int i = 0;
  71125. float vx, vy, vw, vh;
  71126. if (parseCoords (viewParams, vx, vy, i, true)
  71127. && parseCoords (viewParams, vw, vh, i, true)
  71128. && vw > 0
  71129. && vh > 0)
  71130. {
  71131. newState.viewBoxW = vw;
  71132. newState.viewBoxH = vh;
  71133. int placementFlags = 0;
  71134. const String aspect (xml.getStringAttribute ("preserveAspectRatio"));
  71135. if (aspect.containsIgnoreCase ("none"))
  71136. {
  71137. placementFlags = RectanglePlacement::stretchToFit;
  71138. }
  71139. else
  71140. {
  71141. if (aspect.containsIgnoreCase ("slice"))
  71142. placementFlags |= RectanglePlacement::fillDestination;
  71143. if (aspect.containsIgnoreCase ("xMin"))
  71144. placementFlags |= RectanglePlacement::xLeft;
  71145. else if (aspect.containsIgnoreCase ("xMax"))
  71146. placementFlags |= RectanglePlacement::xRight;
  71147. else
  71148. placementFlags |= RectanglePlacement::xMid;
  71149. if (aspect.containsIgnoreCase ("yMin"))
  71150. placementFlags |= RectanglePlacement::yTop;
  71151. else if (aspect.containsIgnoreCase ("yMax"))
  71152. placementFlags |= RectanglePlacement::yBottom;
  71153. else
  71154. placementFlags |= RectanglePlacement::yMid;
  71155. }
  71156. const RectanglePlacement placement (placementFlags);
  71157. newState.transform
  71158. = placement.getTransformToFit (vx, vy, vw, vh,
  71159. 0.0f, 0.0f, newState.width, newState.height)
  71160. .followedBy (newState.transform);
  71161. }
  71162. }
  71163. else
  71164. {
  71165. if (viewBoxW == 0)
  71166. newState.viewBoxW = newState.width;
  71167. if (viewBoxH == 0)
  71168. newState.viewBoxH = newState.height;
  71169. }
  71170. newState.parseSubElements (xml, drawable);
  71171. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71172. return drawable;
  71173. }
  71174. private:
  71175. const XmlElement* const topLevelXml;
  71176. float elementX, elementY, width, height, viewBoxW, viewBoxH;
  71177. AffineTransform transform;
  71178. String cssStyleText;
  71179. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  71180. {
  71181. forEachXmlChildElement (xml, e)
  71182. {
  71183. Drawable* d = 0;
  71184. if (e->hasTagName ("g")) d = parseGroupElement (*e);
  71185. else if (e->hasTagName ("svg")) d = parseSVGElement (*e);
  71186. else if (e->hasTagName ("path")) d = parsePath (*e);
  71187. else if (e->hasTagName ("rect")) d = parseRect (*e);
  71188. else if (e->hasTagName ("circle")) d = parseCircle (*e);
  71189. else if (e->hasTagName ("ellipse")) d = parseEllipse (*e);
  71190. else if (e->hasTagName ("line")) d = parseLine (*e);
  71191. else if (e->hasTagName ("polyline")) d = parsePolygon (*e, true);
  71192. else if (e->hasTagName ("polygon")) d = parsePolygon (*e, false);
  71193. else if (e->hasTagName ("text")) d = parseText (*e);
  71194. else if (e->hasTagName ("switch")) d = parseSwitch (*e);
  71195. else if (e->hasTagName ("style")) parseCSSStyle (*e);
  71196. parentDrawable->insertDrawable (d);
  71197. }
  71198. }
  71199. DrawableComposite* parseSwitch (const XmlElement& xml)
  71200. {
  71201. const XmlElement* const group = xml.getChildByName ("g");
  71202. if (group != 0)
  71203. return parseGroupElement (*group);
  71204. return 0;
  71205. }
  71206. DrawableComposite* parseGroupElement (const XmlElement& xml)
  71207. {
  71208. DrawableComposite* const drawable = new DrawableComposite();
  71209. drawable->setName (xml.getStringAttribute ("id"));
  71210. if (xml.hasAttribute ("transform"))
  71211. {
  71212. SVGState newState (*this);
  71213. newState.addTransform (xml);
  71214. newState.parseSubElements (xml, drawable);
  71215. }
  71216. else
  71217. {
  71218. parseSubElements (xml, drawable);
  71219. }
  71220. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71221. return drawable;
  71222. }
  71223. Drawable* parsePath (const XmlElement& xml) const
  71224. {
  71225. const String d (xml.getStringAttribute ("d").trimStart());
  71226. Path path;
  71227. if (getStyleAttribute (&xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  71228. path.setUsingNonZeroWinding (false);
  71229. int index = 0;
  71230. float lastX = 0, lastY = 0;
  71231. float lastX2 = 0, lastY2 = 0;
  71232. juce_wchar lastCommandChar = 0;
  71233. bool isRelative = true;
  71234. bool carryOn = true;
  71235. const String validCommandChars ("MmLlHhVvCcSsQqTtAaZz");
  71236. while (d[index] != 0)
  71237. {
  71238. float x, y, x2, y2, x3, y3;
  71239. if (validCommandChars.containsChar (d[index]))
  71240. {
  71241. lastCommandChar = d [index++];
  71242. isRelative = (lastCommandChar >= 'a' && lastCommandChar <= 'z');
  71243. }
  71244. switch (lastCommandChar)
  71245. {
  71246. case 'M':
  71247. case 'm':
  71248. case 'L':
  71249. case 'l':
  71250. if (parseCoords (d, x, y, index, false))
  71251. {
  71252. if (isRelative)
  71253. {
  71254. x += lastX;
  71255. y += lastY;
  71256. }
  71257. if (lastCommandChar == 'M' || lastCommandChar == 'm')
  71258. {
  71259. path.startNewSubPath (x, y);
  71260. lastCommandChar = 'l';
  71261. }
  71262. else
  71263. path.lineTo (x, y);
  71264. lastX2 = lastX;
  71265. lastY2 = lastY;
  71266. lastX = x;
  71267. lastY = y;
  71268. }
  71269. else
  71270. {
  71271. ++index;
  71272. }
  71273. break;
  71274. case 'H':
  71275. case 'h':
  71276. if (parseCoord (d, x, index, false, true))
  71277. {
  71278. if (isRelative)
  71279. x += lastX;
  71280. path.lineTo (x, lastY);
  71281. lastX2 = lastX;
  71282. lastX = x;
  71283. }
  71284. else
  71285. {
  71286. ++index;
  71287. }
  71288. break;
  71289. case 'V':
  71290. case 'v':
  71291. if (parseCoord (d, y, index, false, false))
  71292. {
  71293. if (isRelative)
  71294. y += lastY;
  71295. path.lineTo (lastX, y);
  71296. lastY2 = lastY;
  71297. lastY = y;
  71298. }
  71299. else
  71300. {
  71301. ++index;
  71302. }
  71303. break;
  71304. case 'C':
  71305. case 'c':
  71306. if (parseCoords (d, x, y, index, false)
  71307. && parseCoords (d, x2, y2, index, false)
  71308. && parseCoords (d, x3, y3, index, false))
  71309. {
  71310. if (isRelative)
  71311. {
  71312. x += lastX;
  71313. y += lastY;
  71314. x2 += lastX;
  71315. y2 += lastY;
  71316. x3 += lastX;
  71317. y3 += lastY;
  71318. }
  71319. path.cubicTo (x, y, x2, y2, x3, y3);
  71320. lastX2 = x2;
  71321. lastY2 = y2;
  71322. lastX = x3;
  71323. lastY = y3;
  71324. }
  71325. else
  71326. {
  71327. ++index;
  71328. }
  71329. break;
  71330. case 'S':
  71331. case 's':
  71332. if (parseCoords (d, x, y, index, false)
  71333. && parseCoords (d, x3, y3, index, false))
  71334. {
  71335. if (isRelative)
  71336. {
  71337. x += lastX;
  71338. y += lastY;
  71339. x3 += lastX;
  71340. y3 += lastY;
  71341. }
  71342. x2 = lastX + (lastX - lastX2);
  71343. y2 = lastY + (lastY - lastY2);
  71344. path.cubicTo (x2, y2, x, y, x3, y3);
  71345. lastX2 = x;
  71346. lastY2 = y;
  71347. lastX = x3;
  71348. lastY = y3;
  71349. }
  71350. else
  71351. {
  71352. ++index;
  71353. }
  71354. break;
  71355. case 'Q':
  71356. case 'q':
  71357. if (parseCoords (d, x, y, index, false)
  71358. && parseCoords (d, x2, y2, index, false))
  71359. {
  71360. if (isRelative)
  71361. {
  71362. x += lastX;
  71363. y += lastY;
  71364. x2 += lastX;
  71365. y2 += lastY;
  71366. }
  71367. path.quadraticTo (x, y, x2, y2);
  71368. lastX2 = x;
  71369. lastY2 = y;
  71370. lastX = x2;
  71371. lastY = y2;
  71372. }
  71373. else
  71374. {
  71375. ++index;
  71376. }
  71377. break;
  71378. case 'T':
  71379. case 't':
  71380. if (parseCoords (d, x, y, index, false))
  71381. {
  71382. if (isRelative)
  71383. {
  71384. x += lastX;
  71385. y += lastY;
  71386. }
  71387. x2 = lastX + (lastX - lastX2);
  71388. y2 = lastY + (lastY - lastY2);
  71389. path.quadraticTo (x2, y2, x, y);
  71390. lastX2 = x2;
  71391. lastY2 = y2;
  71392. lastX = x;
  71393. lastY = y;
  71394. }
  71395. else
  71396. {
  71397. ++index;
  71398. }
  71399. break;
  71400. case 'A':
  71401. case 'a':
  71402. if (parseCoords (d, x, y, index, false))
  71403. {
  71404. String num;
  71405. if (parseNextNumber (d, num, index, false))
  71406. {
  71407. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  71408. if (parseNextNumber (d, num, index, false))
  71409. {
  71410. const bool largeArc = num.getIntValue() != 0;
  71411. if (parseNextNumber (d, num, index, false))
  71412. {
  71413. const bool sweep = num.getIntValue() != 0;
  71414. if (parseCoords (d, x2, y2, index, false))
  71415. {
  71416. if (isRelative)
  71417. {
  71418. x2 += lastX;
  71419. y2 += lastY;
  71420. }
  71421. if (lastX != x2 || lastY != y2)
  71422. {
  71423. double centreX, centreY, startAngle, deltaAngle;
  71424. double rx = x, ry = y;
  71425. endpointToCentreParameters (lastX, lastY, x2, y2,
  71426. angle, largeArc, sweep,
  71427. rx, ry, centreX, centreY,
  71428. startAngle, deltaAngle);
  71429. path.addCentredArc ((float) centreX, (float) centreY,
  71430. (float) rx, (float) ry,
  71431. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  71432. false);
  71433. path.lineTo (x2, y2);
  71434. }
  71435. lastX2 = lastX;
  71436. lastY2 = lastY;
  71437. lastX = x2;
  71438. lastY = y2;
  71439. }
  71440. }
  71441. }
  71442. }
  71443. }
  71444. else
  71445. {
  71446. ++index;
  71447. }
  71448. break;
  71449. case 'Z':
  71450. case 'z':
  71451. path.closeSubPath();
  71452. while (CharacterFunctions::isWhitespace (d [index]))
  71453. ++index;
  71454. break;
  71455. default:
  71456. carryOn = false;
  71457. break;
  71458. }
  71459. if (! carryOn)
  71460. break;
  71461. }
  71462. return parseShape (xml, path);
  71463. }
  71464. Drawable* parseRect (const XmlElement& xml) const
  71465. {
  71466. Path rect;
  71467. const bool hasRX = xml.hasAttribute ("rx");
  71468. const bool hasRY = xml.hasAttribute ("ry");
  71469. if (hasRX || hasRY)
  71470. {
  71471. float rx = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71472. float ry = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71473. if (! hasRX)
  71474. rx = ry;
  71475. else if (! hasRY)
  71476. ry = rx;
  71477. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71478. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71479. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71480. getCoordLength (xml.getStringAttribute ("height"), viewBoxH),
  71481. rx, ry);
  71482. }
  71483. else
  71484. {
  71485. rect.addRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71486. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71487. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71488. getCoordLength (xml.getStringAttribute ("height"), viewBoxH));
  71489. }
  71490. return parseShape (xml, rect);
  71491. }
  71492. Drawable* parseCircle (const XmlElement& xml) const
  71493. {
  71494. Path circle;
  71495. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71496. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71497. const float radius = getCoordLength (xml.getStringAttribute ("r"), viewBoxW);
  71498. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  71499. return parseShape (xml, circle);
  71500. }
  71501. Drawable* parseEllipse (const XmlElement& xml) const
  71502. {
  71503. Path ellipse;
  71504. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71505. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71506. const float radiusX = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71507. const float radiusY = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71508. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  71509. return parseShape (xml, ellipse);
  71510. }
  71511. Drawable* parseLine (const XmlElement& xml) const
  71512. {
  71513. Path line;
  71514. const float x1 = getCoordLength (xml.getStringAttribute ("x1"), viewBoxW);
  71515. const float y1 = getCoordLength (xml.getStringAttribute ("y1"), viewBoxH);
  71516. const float x2 = getCoordLength (xml.getStringAttribute ("x2"), viewBoxW);
  71517. const float y2 = getCoordLength (xml.getStringAttribute ("y2"), viewBoxH);
  71518. line.startNewSubPath (x1, y1);
  71519. line.lineTo (x2, y2);
  71520. return parseShape (xml, line);
  71521. }
  71522. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  71523. {
  71524. const String points (xml.getStringAttribute ("points"));
  71525. Path path;
  71526. int index = 0;
  71527. float x, y;
  71528. if (parseCoords (points, x, y, index, true))
  71529. {
  71530. float firstX = x;
  71531. float firstY = y;
  71532. float lastX = 0, lastY = 0;
  71533. path.startNewSubPath (x, y);
  71534. while (parseCoords (points, x, y, index, true))
  71535. {
  71536. lastX = x;
  71537. lastY = y;
  71538. path.lineTo (x, y);
  71539. }
  71540. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  71541. path.closeSubPath();
  71542. }
  71543. return parseShape (xml, path);
  71544. }
  71545. Drawable* parseShape (const XmlElement& xml, Path& path,
  71546. const bool shouldParseTransform = true) const
  71547. {
  71548. if (shouldParseTransform && xml.hasAttribute ("transform"))
  71549. {
  71550. SVGState newState (*this);
  71551. newState.addTransform (xml);
  71552. return newState.parseShape (xml, path, false);
  71553. }
  71554. DrawablePath* dp = new DrawablePath();
  71555. dp->setName (xml.getStringAttribute ("id"));
  71556. dp->setFill (Colours::transparentBlack);
  71557. path.applyTransform (transform);
  71558. dp->setPath (path);
  71559. Path::Iterator iter (path);
  71560. bool containsClosedSubPath = false;
  71561. while (iter.next())
  71562. {
  71563. if (iter.elementType == Path::Iterator::closePath)
  71564. {
  71565. containsClosedSubPath = true;
  71566. break;
  71567. }
  71568. }
  71569. dp->setFill (getPathFillType (path,
  71570. getStyleAttribute (&xml, "fill"),
  71571. getStyleAttribute (&xml, "fill-opacity"),
  71572. getStyleAttribute (&xml, "opacity"),
  71573. containsClosedSubPath ? Colours::black
  71574. : Colours::transparentBlack));
  71575. const String strokeType (getStyleAttribute (&xml, "stroke"));
  71576. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  71577. {
  71578. dp->setStrokeFill (getPathFillType (path, strokeType,
  71579. getStyleAttribute (&xml, "stroke-opacity"),
  71580. getStyleAttribute (&xml, "opacity"),
  71581. Colours::transparentBlack));
  71582. dp->setStrokeType (getStrokeFor (&xml));
  71583. }
  71584. return dp;
  71585. }
  71586. const XmlElement* findLinkedElement (const XmlElement* e) const
  71587. {
  71588. const String id (e->getStringAttribute ("xlink:href"));
  71589. if (! id.startsWithChar ('#'))
  71590. return 0;
  71591. return findElementForId (topLevelXml, id.substring (1));
  71592. }
  71593. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  71594. {
  71595. if (fillXml == 0)
  71596. return;
  71597. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  71598. {
  71599. int index = 0;
  71600. Colour col (parseColour (getStyleAttribute (e, "stop-color"), index, Colours::black));
  71601. const String opacity (getStyleAttribute (e, "stop-opacity", "1"));
  71602. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  71603. double offset = e->getDoubleAttribute ("offset");
  71604. if (e->getStringAttribute ("offset").containsChar ('%'))
  71605. offset *= 0.01;
  71606. cg.addColour (jlimit (0.0, 1.0, offset), col);
  71607. }
  71608. }
  71609. const FillType getPathFillType (const Path& path,
  71610. const String& fill,
  71611. const String& fillOpacity,
  71612. const String& overallOpacity,
  71613. const Colour& defaultColour) const
  71614. {
  71615. float opacity = 1.0f;
  71616. if (overallOpacity.isNotEmpty())
  71617. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  71618. if (fillOpacity.isNotEmpty())
  71619. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  71620. if (fill.startsWithIgnoreCase ("url"))
  71621. {
  71622. const String id (fill.fromFirstOccurrenceOf ("#", false, false)
  71623. .upToLastOccurrenceOf (")", false, false).trim());
  71624. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  71625. if (fillXml != 0
  71626. && (fillXml->hasTagName ("linearGradient")
  71627. || fillXml->hasTagName ("radialGradient")))
  71628. {
  71629. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  71630. ColourGradient gradient;
  71631. addGradientStopsIn (gradient, inheritedFrom);
  71632. addGradientStopsIn (gradient, fillXml);
  71633. if (gradient.getNumColours() > 0)
  71634. {
  71635. gradient.addColour (0.0, gradient.getColour (0));
  71636. gradient.addColour (1.0, gradient.getColour (gradient.getNumColours() - 1));
  71637. }
  71638. else
  71639. {
  71640. gradient.addColour (0.0, Colours::black);
  71641. gradient.addColour (1.0, Colours::black);
  71642. }
  71643. if (overallOpacity.isNotEmpty())
  71644. gradient.multiplyOpacity (overallOpacity.getFloatValue());
  71645. jassert (gradient.getNumColours() > 0);
  71646. gradient.isRadial = fillXml->hasTagName ("radialGradient");
  71647. float gradientWidth = viewBoxW;
  71648. float gradientHeight = viewBoxH;
  71649. float dx = 0.0f;
  71650. float dy = 0.0f;
  71651. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  71652. if (! userSpace)
  71653. {
  71654. const Rectangle<float> bounds (path.getBounds());
  71655. dx = bounds.getX();
  71656. dy = bounds.getY();
  71657. gradientWidth = bounds.getWidth();
  71658. gradientHeight = bounds.getHeight();
  71659. }
  71660. if (gradient.isRadial)
  71661. {
  71662. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth),
  71663. dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight));
  71664. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  71665. gradient.point2 = gradient.point1 + Point<float> (radius, 0.0f);
  71666. //xxx (the fx, fy focal point isn't handled properly here..)
  71667. }
  71668. else
  71669. {
  71670. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth),
  71671. dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight));
  71672. gradient.point2.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth),
  71673. dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight));
  71674. if (gradient.point1 == gradient.point2)
  71675. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  71676. }
  71677. FillType type (gradient);
  71678. type.transform = parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  71679. .followedBy (transform);
  71680. return type;
  71681. }
  71682. }
  71683. if (fill.equalsIgnoreCase ("none"))
  71684. return Colours::transparentBlack;
  71685. int i = 0;
  71686. const Colour colour (parseColour (fill, i, defaultColour));
  71687. return colour.withMultipliedAlpha (opacity);
  71688. }
  71689. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  71690. {
  71691. const String strokeWidth (getStyleAttribute (xml, "stroke-width"));
  71692. const String cap (getStyleAttribute (xml, "stroke-linecap"));
  71693. const String join (getStyleAttribute (xml, "stroke-linejoin"));
  71694. //const String mitreLimit (getStyleAttribute (xml, "stroke-miterlimit"));
  71695. //const String dashArray (getStyleAttribute (xml, "stroke-dasharray"));
  71696. //const String dashOffset (getStyleAttribute (xml, "stroke-dashoffset"));
  71697. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  71698. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  71699. if (join.equalsIgnoreCase ("round"))
  71700. joinStyle = PathStrokeType::curved;
  71701. else if (join.equalsIgnoreCase ("bevel"))
  71702. joinStyle = PathStrokeType::beveled;
  71703. if (cap.equalsIgnoreCase ("round"))
  71704. capStyle = PathStrokeType::rounded;
  71705. else if (cap.equalsIgnoreCase ("square"))
  71706. capStyle = PathStrokeType::square;
  71707. float ox = 0.0f, oy = 0.0f;
  71708. float x = getCoordLength (strokeWidth, viewBoxW), y = 0.0f;
  71709. transform.transformPoints (ox, oy, x, y);
  71710. return PathStrokeType (strokeWidth.isNotEmpty() ? juce_hypotf (x - ox, y - oy) : 1.0f,
  71711. joinStyle, capStyle);
  71712. }
  71713. Drawable* parseText (const XmlElement& xml)
  71714. {
  71715. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  71716. getCoordList (xCoords, getInheritedAttribute (&xml, "x"), true, true);
  71717. getCoordList (yCoords, getInheritedAttribute (&xml, "y"), true, false);
  71718. getCoordList (dxCoords, getInheritedAttribute (&xml, "dx"), true, true);
  71719. getCoordList (dyCoords, getInheritedAttribute (&xml, "dy"), true, false);
  71720. //xxx not done text yet!
  71721. forEachXmlChildElement (xml, e)
  71722. {
  71723. if (e->isTextElement())
  71724. {
  71725. const String text (e->getText());
  71726. Path path;
  71727. Drawable* s = parseShape (*e, path);
  71728. delete s; // xxx not finished!
  71729. }
  71730. else if (e->hasTagName ("tspan"))
  71731. {
  71732. Drawable* s = parseText (*e);
  71733. delete s; // xxx not finished!
  71734. }
  71735. }
  71736. return 0;
  71737. }
  71738. void addTransform (const XmlElement& xml)
  71739. {
  71740. transform = parseTransform (xml.getStringAttribute ("transform"))
  71741. .followedBy (transform);
  71742. }
  71743. bool parseCoord (const String& s, float& value, int& index,
  71744. const bool allowUnits, const bool isX) const
  71745. {
  71746. String number;
  71747. if (! parseNextNumber (s, number, index, allowUnits))
  71748. {
  71749. value = 0;
  71750. return false;
  71751. }
  71752. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  71753. return true;
  71754. }
  71755. bool parseCoords (const String& s, float& x, float& y,
  71756. int& index, const bool allowUnits) const
  71757. {
  71758. return parseCoord (s, x, index, allowUnits, true)
  71759. && parseCoord (s, y, index, allowUnits, false);
  71760. }
  71761. float getCoordLength (const String& s, const float sizeForProportions) const
  71762. {
  71763. float n = s.getFloatValue();
  71764. const int len = s.length();
  71765. if (len > 2)
  71766. {
  71767. const float dpi = 96.0f;
  71768. const juce_wchar n1 = s [len - 2];
  71769. const juce_wchar n2 = s [len - 1];
  71770. if (n1 == 'i' && n2 == 'n')
  71771. n *= dpi;
  71772. else if (n1 == 'm' && n2 == 'm')
  71773. n *= dpi / 25.4f;
  71774. else if (n1 == 'c' && n2 == 'm')
  71775. n *= dpi / 2.54f;
  71776. else if (n1 == 'p' && n2 == 'c')
  71777. n *= 15.0f;
  71778. else if (n2 == '%')
  71779. n *= 0.01f * sizeForProportions;
  71780. }
  71781. return n;
  71782. }
  71783. void getCoordList (Array <float>& coords, const String& list,
  71784. const bool allowUnits, const bool isX) const
  71785. {
  71786. int index = 0;
  71787. float value;
  71788. while (parseCoord (list, value, index, allowUnits, isX))
  71789. coords.add (value);
  71790. }
  71791. void parseCSSStyle (const XmlElement& xml)
  71792. {
  71793. cssStyleText = xml.getAllSubText() + "\n" + cssStyleText;
  71794. }
  71795. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  71796. const String& defaultValue = String::empty) const
  71797. {
  71798. if (xml->hasAttribute (attributeName))
  71799. return xml->getStringAttribute (attributeName, defaultValue);
  71800. const String styleAtt (xml->getStringAttribute ("style"));
  71801. if (styleAtt.isNotEmpty())
  71802. {
  71803. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  71804. if (value.isNotEmpty())
  71805. return value;
  71806. }
  71807. else if (xml->hasAttribute ("class"))
  71808. {
  71809. const String className ("." + xml->getStringAttribute ("class"));
  71810. int index = cssStyleText.indexOfIgnoreCase (className + " ");
  71811. if (index < 0)
  71812. index = cssStyleText.indexOfIgnoreCase (className + "{");
  71813. if (index >= 0)
  71814. {
  71815. const int openBracket = cssStyleText.indexOfChar (index, '{');
  71816. if (openBracket > index)
  71817. {
  71818. const int closeBracket = cssStyleText.indexOfChar (openBracket, '}');
  71819. if (closeBracket > openBracket)
  71820. {
  71821. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  71822. if (value.isNotEmpty())
  71823. return value;
  71824. }
  71825. }
  71826. }
  71827. }
  71828. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  71829. if (xml != 0)
  71830. return getStyleAttribute (xml, attributeName, defaultValue);
  71831. return defaultValue;
  71832. }
  71833. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  71834. {
  71835. if (xml->hasAttribute (attributeName))
  71836. return xml->getStringAttribute (attributeName);
  71837. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  71838. if (xml != 0)
  71839. return getInheritedAttribute (xml, attributeName);
  71840. return String::empty;
  71841. }
  71842. static bool isIdentifierChar (const juce_wchar c)
  71843. {
  71844. return CharacterFunctions::isLetter (c) || c == '-';
  71845. }
  71846. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  71847. {
  71848. int i = 0;
  71849. for (;;)
  71850. {
  71851. i = list.indexOf (i, attributeName);
  71852. if (i < 0)
  71853. break;
  71854. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  71855. && ! isIdentifierChar (list [i + attributeName.length()]))
  71856. {
  71857. i = list.indexOfChar (i, ':');
  71858. if (i < 0)
  71859. break;
  71860. int end = list.indexOfChar (i, ';');
  71861. if (end < 0)
  71862. end = 0x7ffff;
  71863. return list.substring (i + 1, end).trim();
  71864. }
  71865. ++i;
  71866. }
  71867. return defaultValue;
  71868. }
  71869. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  71870. {
  71871. const juce_wchar* const s = source;
  71872. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  71873. ++index;
  71874. int start = index;
  71875. if (CharacterFunctions::isDigit (s[index]) || s[index] == '.' || s[index] == '-')
  71876. ++index;
  71877. while (CharacterFunctions::isDigit (s[index]) || s[index] == '.')
  71878. ++index;
  71879. if ((s[index] == 'e' || s[index] == 'E')
  71880. && (CharacterFunctions::isDigit (s[index + 1])
  71881. || s[index + 1] == '-'
  71882. || s[index + 1] == '+'))
  71883. {
  71884. index += 2;
  71885. while (CharacterFunctions::isDigit (s[index]))
  71886. ++index;
  71887. }
  71888. if (allowUnits)
  71889. {
  71890. while (CharacterFunctions::isLetter (s[index]))
  71891. ++index;
  71892. }
  71893. if (index == start)
  71894. return false;
  71895. value = String (s + start, index - start);
  71896. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  71897. ++index;
  71898. return true;
  71899. }
  71900. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  71901. {
  71902. if (s [index] == '#')
  71903. {
  71904. uint32 hex [6];
  71905. zeromem (hex, sizeof (hex));
  71906. int numChars = 0;
  71907. for (int i = 6; --i >= 0;)
  71908. {
  71909. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  71910. if (hexValue >= 0)
  71911. hex [numChars++] = hexValue;
  71912. else
  71913. break;
  71914. }
  71915. if (numChars <= 3)
  71916. return Colour ((uint8) (hex [0] * 0x11),
  71917. (uint8) (hex [1] * 0x11),
  71918. (uint8) (hex [2] * 0x11));
  71919. else
  71920. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  71921. (uint8) ((hex [2] << 4) + hex [3]),
  71922. (uint8) ((hex [4] << 4) + hex [5]));
  71923. }
  71924. else if (s [index] == 'r'
  71925. && s [index + 1] == 'g'
  71926. && s [index + 2] == 'b')
  71927. {
  71928. const int openBracket = s.indexOfChar (index, '(');
  71929. const int closeBracket = s.indexOfChar (openBracket, ')');
  71930. if (openBracket >= 3 && closeBracket > openBracket)
  71931. {
  71932. index = closeBracket;
  71933. StringArray tokens;
  71934. tokens.addTokens (s.substring (openBracket + 1, closeBracket), ",", "");
  71935. tokens.trim();
  71936. tokens.removeEmptyStrings();
  71937. if (tokens[0].containsChar ('%'))
  71938. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  71939. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  71940. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  71941. else
  71942. return Colour ((uint8) tokens[0].getIntValue(),
  71943. (uint8) tokens[1].getIntValue(),
  71944. (uint8) tokens[2].getIntValue());
  71945. }
  71946. }
  71947. return Colours::findColourForName (s, defaultColour);
  71948. }
  71949. static const AffineTransform parseTransform (String t)
  71950. {
  71951. AffineTransform result;
  71952. while (t.isNotEmpty())
  71953. {
  71954. StringArray tokens;
  71955. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  71956. .upToFirstOccurrenceOf (")", false, false),
  71957. ", ", String::empty);
  71958. tokens.removeEmptyStrings (true);
  71959. float numbers [6];
  71960. for (int i = 0; i < 6; ++i)
  71961. numbers[i] = tokens[i].getFloatValue();
  71962. AffineTransform trans;
  71963. if (t.startsWithIgnoreCase ("matrix"))
  71964. {
  71965. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  71966. numbers[1], numbers[3], numbers[5]);
  71967. }
  71968. else if (t.startsWithIgnoreCase ("translate"))
  71969. {
  71970. jassert (tokens.size() == 2);
  71971. trans = AffineTransform::translation (numbers[0], numbers[1]);
  71972. }
  71973. else if (t.startsWithIgnoreCase ("scale"))
  71974. {
  71975. if (tokens.size() == 1)
  71976. trans = AffineTransform::scale (numbers[0], numbers[0]);
  71977. else
  71978. trans = AffineTransform::scale (numbers[0], numbers[1]);
  71979. }
  71980. else if (t.startsWithIgnoreCase ("rotate"))
  71981. {
  71982. if (tokens.size() != 3)
  71983. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi));
  71984. else
  71985. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi),
  71986. numbers[1], numbers[2]);
  71987. }
  71988. else if (t.startsWithIgnoreCase ("skewX"))
  71989. {
  71990. trans = AffineTransform (1.0f, std::tan (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  71991. 0.0f, 1.0f, 0.0f);
  71992. }
  71993. else if (t.startsWithIgnoreCase ("skewY"))
  71994. {
  71995. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  71996. std::tan (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  71997. }
  71998. result = trans.followedBy (result);
  71999. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  72000. }
  72001. return result;
  72002. }
  72003. static void endpointToCentreParameters (const double x1, const double y1,
  72004. const double x2, const double y2,
  72005. const double angle,
  72006. const bool largeArc, const bool sweep,
  72007. double& rx, double& ry,
  72008. double& centreX, double& centreY,
  72009. double& startAngle, double& deltaAngle)
  72010. {
  72011. const double midX = (x1 - x2) * 0.5;
  72012. const double midY = (y1 - y2) * 0.5;
  72013. const double cosAngle = cos (angle);
  72014. const double sinAngle = sin (angle);
  72015. const double xp = cosAngle * midX + sinAngle * midY;
  72016. const double yp = cosAngle * midY - sinAngle * midX;
  72017. const double xp2 = xp * xp;
  72018. const double yp2 = yp * yp;
  72019. double rx2 = rx * rx;
  72020. double ry2 = ry * ry;
  72021. const double s = (xp2 / rx2) + (yp2 / ry2);
  72022. double c;
  72023. if (s <= 1.0)
  72024. {
  72025. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  72026. / (( rx2 * yp2) + (ry2 * xp2))));
  72027. if (largeArc == sweep)
  72028. c = -c;
  72029. }
  72030. else
  72031. {
  72032. const double s2 = std::sqrt (s);
  72033. rx *= s2;
  72034. ry *= s2;
  72035. rx2 = rx * rx;
  72036. ry2 = ry * ry;
  72037. c = 0;
  72038. }
  72039. const double cpx = ((rx * yp) / ry) * c;
  72040. const double cpy = ((-ry * xp) / rx) * c;
  72041. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  72042. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  72043. const double ux = (xp - cpx) / rx;
  72044. const double uy = (yp - cpy) / ry;
  72045. const double vx = (-xp - cpx) / rx;
  72046. const double vy = (-yp - cpy) / ry;
  72047. const double length = juce_hypot (ux, uy);
  72048. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  72049. if (uy < 0)
  72050. startAngle = -startAngle;
  72051. startAngle += double_Pi * 0.5;
  72052. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  72053. / (length * juce_hypot (vx, vy))));
  72054. if ((ux * vy) - (uy * vx) < 0)
  72055. deltaAngle = -deltaAngle;
  72056. if (sweep)
  72057. {
  72058. if (deltaAngle < 0)
  72059. deltaAngle += double_Pi * 2.0;
  72060. }
  72061. else
  72062. {
  72063. if (deltaAngle > 0)
  72064. deltaAngle -= double_Pi * 2.0;
  72065. }
  72066. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  72067. }
  72068. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  72069. {
  72070. forEachXmlChildElement (*parent, e)
  72071. {
  72072. if (e->compareAttribute ("id", id))
  72073. return e;
  72074. const XmlElement* const found = findElementForId (e, id);
  72075. if (found != 0)
  72076. return found;
  72077. }
  72078. return 0;
  72079. }
  72080. SVGState& operator= (const SVGState&);
  72081. };
  72082. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  72083. {
  72084. SVGState state (&svgDocument);
  72085. return state.parseSVGElement (svgDocument);
  72086. }
  72087. END_JUCE_NAMESPACE
  72088. /*** End of inlined file: juce_SVGParser.cpp ***/
  72089. /*** Start of inlined file: juce_DropShadowEffect.cpp ***/
  72090. BEGIN_JUCE_NAMESPACE
  72091. #if JUCE_MSVC && JUCE_DEBUG
  72092. #pragma optimize ("t", on)
  72093. #endif
  72094. DropShadowEffect::DropShadowEffect()
  72095. : offsetX (0),
  72096. offsetY (0),
  72097. radius (4),
  72098. opacity (0.6f)
  72099. {
  72100. }
  72101. DropShadowEffect::~DropShadowEffect()
  72102. {
  72103. }
  72104. void DropShadowEffect::setShadowProperties (const float newRadius,
  72105. const float newOpacity,
  72106. const int newShadowOffsetX,
  72107. const int newShadowOffsetY)
  72108. {
  72109. radius = jmax (1.1f, newRadius);
  72110. offsetX = newShadowOffsetX;
  72111. offsetY = newShadowOffsetY;
  72112. opacity = newOpacity;
  72113. }
  72114. void DropShadowEffect::applyEffect (Image& image, Graphics& g)
  72115. {
  72116. const int w = image.getWidth();
  72117. const int h = image.getHeight();
  72118. Image shadowImage (Image::SingleChannel, w, h, false);
  72119. const Image::BitmapData srcData (image, false);
  72120. const Image::BitmapData destData (shadowImage, true);
  72121. const int filter = roundToInt (63.0f / radius);
  72122. const int radiusMinus1 = roundToInt ((radius - 1.0f) * 63.0f);
  72123. for (int x = w; --x >= 0;)
  72124. {
  72125. int shadowAlpha = 0;
  72126. const PixelARGB* src = ((const PixelARGB*) srcData.data) + x;
  72127. uint8* shadowPix = destData.data + x;
  72128. for (int y = h; --y >= 0;)
  72129. {
  72130. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  72131. *shadowPix = (uint8) shadowAlpha;
  72132. src = (const PixelARGB*) (((const uint8*) src) + srcData.lineStride);
  72133. shadowPix += destData.lineStride;
  72134. }
  72135. }
  72136. for (int y = h; --y >= 0;)
  72137. {
  72138. int shadowAlpha = 0;
  72139. uint8* shadowPix = destData.getLinePointer (y);
  72140. for (int x = w; --x >= 0;)
  72141. {
  72142. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  72143. *shadowPix++ = (uint8) shadowAlpha;
  72144. }
  72145. }
  72146. g.setColour (Colours::black.withAlpha (opacity));
  72147. g.drawImageAt (shadowImage, offsetX, offsetY, true);
  72148. g.setOpacity (1.0f);
  72149. g.drawImageAt (image, 0, 0);
  72150. }
  72151. #if JUCE_MSVC && JUCE_DEBUG
  72152. #pragma optimize ("", on) // resets optimisations to the project defaults
  72153. #endif
  72154. END_JUCE_NAMESPACE
  72155. /*** End of inlined file: juce_DropShadowEffect.cpp ***/
  72156. /*** Start of inlined file: juce_GlowEffect.cpp ***/
  72157. BEGIN_JUCE_NAMESPACE
  72158. GlowEffect::GlowEffect()
  72159. : radius (2.0f),
  72160. colour (Colours::white)
  72161. {
  72162. }
  72163. GlowEffect::~GlowEffect()
  72164. {
  72165. }
  72166. void GlowEffect::setGlowProperties (const float newRadius,
  72167. const Colour& newColour)
  72168. {
  72169. radius = newRadius;
  72170. colour = newColour;
  72171. }
  72172. void GlowEffect::applyEffect (Image& image, Graphics& g)
  72173. {
  72174. Image temp (image.getFormat(), image.getWidth(), image.getHeight(), true);
  72175. ImageConvolutionKernel blurKernel (roundToInt (radius * 2.0f));
  72176. blurKernel.createGaussianBlur (radius);
  72177. blurKernel.rescaleAllValues (radius);
  72178. blurKernel.applyToImage (temp, image, image.getBounds());
  72179. g.setColour (colour);
  72180. g.drawImageAt (temp, 0, 0, true);
  72181. g.setOpacity (1.0f);
  72182. g.drawImageAt (image, 0, 0, false);
  72183. }
  72184. END_JUCE_NAMESPACE
  72185. /*** End of inlined file: juce_GlowEffect.cpp ***/
  72186. /*** Start of inlined file: juce_ReduceOpacityEffect.cpp ***/
  72187. BEGIN_JUCE_NAMESPACE
  72188. ReduceOpacityEffect::ReduceOpacityEffect (const float opacity_)
  72189. : opacity (opacity_)
  72190. {
  72191. }
  72192. ReduceOpacityEffect::~ReduceOpacityEffect()
  72193. {
  72194. }
  72195. void ReduceOpacityEffect::setOpacity (const float newOpacity)
  72196. {
  72197. opacity = jlimit (0.0f, 1.0f, newOpacity);
  72198. }
  72199. void ReduceOpacityEffect::applyEffect (Image& image, Graphics& g)
  72200. {
  72201. g.setOpacity (opacity);
  72202. g.drawImageAt (image, 0, 0);
  72203. }
  72204. END_JUCE_NAMESPACE
  72205. /*** End of inlined file: juce_ReduceOpacityEffect.cpp ***/
  72206. /*** Start of inlined file: juce_Font.cpp ***/
  72207. BEGIN_JUCE_NAMESPACE
  72208. namespace FontValues
  72209. {
  72210. static float limitFontHeight (const float height) throw()
  72211. {
  72212. return jlimit (0.1f, 10000.0f, height);
  72213. }
  72214. static const float defaultFontHeight = 14.0f;
  72215. static String fallbackFont;
  72216. }
  72217. Font::SharedFontInternal::SharedFontInternal (const String& typefaceName_, const float height_, const float horizontalScale_,
  72218. const float kerning_, const float ascent_, const int styleFlags_,
  72219. Typeface* const typeface_) throw()
  72220. : typefaceName (typefaceName_),
  72221. height (height_),
  72222. horizontalScale (horizontalScale_),
  72223. kerning (kerning_),
  72224. ascent (ascent_),
  72225. styleFlags (styleFlags_),
  72226. typeface (typeface_)
  72227. {
  72228. }
  72229. Font::SharedFontInternal::SharedFontInternal (const SharedFontInternal& other) throw()
  72230. : typefaceName (other.typefaceName),
  72231. height (other.height),
  72232. horizontalScale (other.horizontalScale),
  72233. kerning (other.kerning),
  72234. ascent (other.ascent),
  72235. styleFlags (other.styleFlags),
  72236. typeface (other.typeface)
  72237. {
  72238. }
  72239. Font::Font()
  72240. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::defaultFontHeight,
  72241. 1.0f, 0, 0, Font::plain, 0))
  72242. {
  72243. }
  72244. Font::Font (const float fontHeight, const int styleFlags_)
  72245. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::limitFontHeight (fontHeight),
  72246. 1.0f, 0, 0, styleFlags_, 0))
  72247. {
  72248. }
  72249. Font::Font (const String& typefaceName_,
  72250. const float fontHeight,
  72251. const int styleFlags_)
  72252. : font (new SharedFontInternal (typefaceName_, FontValues::limitFontHeight (fontHeight),
  72253. 1.0f, 0, 0, styleFlags_, 0))
  72254. {
  72255. }
  72256. Font::Font (const Font& other) throw()
  72257. : font (other.font)
  72258. {
  72259. }
  72260. Font& Font::operator= (const Font& other) throw()
  72261. {
  72262. font = other.font;
  72263. return *this;
  72264. }
  72265. Font::~Font() throw()
  72266. {
  72267. }
  72268. Font::Font (const Typeface::Ptr& typeface)
  72269. : font (new SharedFontInternal (typeface->getName(), FontValues::defaultFontHeight,
  72270. 1.0f, 0, 0, Font::plain, typeface))
  72271. {
  72272. }
  72273. bool Font::operator== (const Font& other) const throw()
  72274. {
  72275. return font == other.font
  72276. || (font->height == other.font->height
  72277. && font->styleFlags == other.font->styleFlags
  72278. && font->horizontalScale == other.font->horizontalScale
  72279. && font->kerning == other.font->kerning
  72280. && font->typefaceName == other.font->typefaceName);
  72281. }
  72282. bool Font::operator!= (const Font& other) const throw()
  72283. {
  72284. return ! operator== (other);
  72285. }
  72286. void Font::dupeInternalIfShared()
  72287. {
  72288. if (font->getReferenceCount() > 1)
  72289. font = new SharedFontInternal (*font);
  72290. }
  72291. const String Font::getDefaultSansSerifFontName()
  72292. {
  72293. static const String name ("<Sans-Serif>");
  72294. return name;
  72295. }
  72296. const String Font::getDefaultSerifFontName()
  72297. {
  72298. static const String name ("<Serif>");
  72299. return name;
  72300. }
  72301. const String Font::getDefaultMonospacedFontName()
  72302. {
  72303. static const String name ("<Monospaced>");
  72304. return name;
  72305. }
  72306. void Font::setTypefaceName (const String& faceName)
  72307. {
  72308. if (faceName != font->typefaceName)
  72309. {
  72310. dupeInternalIfShared();
  72311. font->typefaceName = faceName;
  72312. font->typeface = 0;
  72313. font->ascent = 0;
  72314. }
  72315. }
  72316. const String Font::getFallbackFontName()
  72317. {
  72318. return FontValues::fallbackFont;
  72319. }
  72320. void Font::setFallbackFontName (const String& name)
  72321. {
  72322. FontValues::fallbackFont = name;
  72323. }
  72324. void Font::setHeight (float newHeight)
  72325. {
  72326. newHeight = FontValues::limitFontHeight (newHeight);
  72327. if (font->height != newHeight)
  72328. {
  72329. dupeInternalIfShared();
  72330. font->height = newHeight;
  72331. }
  72332. }
  72333. void Font::setHeightWithoutChangingWidth (float newHeight)
  72334. {
  72335. newHeight = FontValues::limitFontHeight (newHeight);
  72336. if (font->height != newHeight)
  72337. {
  72338. dupeInternalIfShared();
  72339. font->horizontalScale *= (font->height / newHeight);
  72340. font->height = newHeight;
  72341. }
  72342. }
  72343. void Font::setStyleFlags (const int newFlags)
  72344. {
  72345. if (font->styleFlags != newFlags)
  72346. {
  72347. dupeInternalIfShared();
  72348. font->styleFlags = newFlags;
  72349. font->typeface = 0;
  72350. font->ascent = 0;
  72351. }
  72352. }
  72353. void Font::setSizeAndStyle (float newHeight,
  72354. const int newStyleFlags,
  72355. const float newHorizontalScale,
  72356. const float newKerningAmount)
  72357. {
  72358. newHeight = FontValues::limitFontHeight (newHeight);
  72359. if (font->height != newHeight
  72360. || font->horizontalScale != newHorizontalScale
  72361. || font->kerning != newKerningAmount)
  72362. {
  72363. dupeInternalIfShared();
  72364. font->height = newHeight;
  72365. font->horizontalScale = newHorizontalScale;
  72366. font->kerning = newKerningAmount;
  72367. }
  72368. setStyleFlags (newStyleFlags);
  72369. }
  72370. void Font::setHorizontalScale (const float scaleFactor)
  72371. {
  72372. dupeInternalIfShared();
  72373. font->horizontalScale = scaleFactor;
  72374. }
  72375. void Font::setExtraKerningFactor (const float extraKerning)
  72376. {
  72377. dupeInternalIfShared();
  72378. font->kerning = extraKerning;
  72379. }
  72380. void Font::setBold (const bool shouldBeBold)
  72381. {
  72382. setStyleFlags (shouldBeBold ? (font->styleFlags | bold)
  72383. : (font->styleFlags & ~bold));
  72384. }
  72385. const Font Font::boldened() const
  72386. {
  72387. Font f (*this);
  72388. f.setBold (true);
  72389. return f;
  72390. }
  72391. bool Font::isBold() const throw()
  72392. {
  72393. return (font->styleFlags & bold) != 0;
  72394. }
  72395. void Font::setItalic (const bool shouldBeItalic)
  72396. {
  72397. setStyleFlags (shouldBeItalic ? (font->styleFlags | italic)
  72398. : (font->styleFlags & ~italic));
  72399. }
  72400. const Font Font::italicised() const
  72401. {
  72402. Font f (*this);
  72403. f.setItalic (true);
  72404. return f;
  72405. }
  72406. bool Font::isItalic() const throw()
  72407. {
  72408. return (font->styleFlags & italic) != 0;
  72409. }
  72410. void Font::setUnderline (const bool shouldBeUnderlined)
  72411. {
  72412. setStyleFlags (shouldBeUnderlined ? (font->styleFlags | underlined)
  72413. : (font->styleFlags & ~underlined));
  72414. }
  72415. bool Font::isUnderlined() const throw()
  72416. {
  72417. return (font->styleFlags & underlined) != 0;
  72418. }
  72419. float Font::getAscent() const
  72420. {
  72421. if (font->ascent == 0)
  72422. font->ascent = getTypeface()->getAscent();
  72423. return font->height * font->ascent;
  72424. }
  72425. float Font::getDescent() const
  72426. {
  72427. return font->height - getAscent();
  72428. }
  72429. int Font::getStringWidth (const String& text) const
  72430. {
  72431. return roundToInt (getStringWidthFloat (text));
  72432. }
  72433. float Font::getStringWidthFloat (const String& text) const
  72434. {
  72435. float w = getTypeface()->getStringWidth (text);
  72436. if (font->kerning != 0)
  72437. w += font->kerning * text.length();
  72438. return w * font->height * font->horizontalScale;
  72439. }
  72440. void Font::getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const
  72441. {
  72442. getTypeface()->getGlyphPositions (text, glyphs, xOffsets);
  72443. const float scale = font->height * font->horizontalScale;
  72444. const int num = xOffsets.size();
  72445. if (num > 0)
  72446. {
  72447. float* const x = &(xOffsets.getReference(0));
  72448. if (font->kerning != 0)
  72449. {
  72450. for (int i = 0; i < num; ++i)
  72451. x[i] = (x[i] + i * font->kerning) * scale;
  72452. }
  72453. else
  72454. {
  72455. for (int i = 0; i < num; ++i)
  72456. x[i] *= scale;
  72457. }
  72458. }
  72459. }
  72460. void Font::findFonts (Array<Font>& destArray)
  72461. {
  72462. const StringArray names (findAllTypefaceNames());
  72463. for (int i = 0; i < names.size(); ++i)
  72464. destArray.add (Font (names[i], FontValues::defaultFontHeight, Font::plain));
  72465. }
  72466. const String Font::toString() const
  72467. {
  72468. String s (getTypefaceName());
  72469. if (s == getDefaultSansSerifFontName())
  72470. s = String::empty;
  72471. else
  72472. s += "; ";
  72473. s += String (getHeight(), 1);
  72474. if (isBold())
  72475. s += " bold";
  72476. if (isItalic())
  72477. s += " italic";
  72478. return s;
  72479. }
  72480. const Font Font::fromString (const String& fontDescription)
  72481. {
  72482. String name;
  72483. const int separator = fontDescription.indexOfChar (';');
  72484. if (separator > 0)
  72485. name = fontDescription.substring (0, separator).trim();
  72486. if (name.isEmpty())
  72487. name = getDefaultSansSerifFontName();
  72488. String sizeAndStyle (fontDescription.substring (separator + 1));
  72489. float height = sizeAndStyle.getFloatValue();
  72490. if (height <= 0)
  72491. height = 10.0f;
  72492. int flags = Font::plain;
  72493. if (sizeAndStyle.containsIgnoreCase ("bold"))
  72494. flags |= Font::bold;
  72495. if (sizeAndStyle.containsIgnoreCase ("italic"))
  72496. flags |= Font::italic;
  72497. return Font (name, height, flags);
  72498. }
  72499. class TypefaceCache : public DeletedAtShutdown
  72500. {
  72501. public:
  72502. TypefaceCache (int numToCache = 10)
  72503. : counter (1)
  72504. {
  72505. while (--numToCache >= 0)
  72506. faces.add (new CachedFace());
  72507. }
  72508. ~TypefaceCache()
  72509. {
  72510. clearSingletonInstance();
  72511. }
  72512. juce_DeclareSingleton_SingleThreaded_Minimal (TypefaceCache)
  72513. const Typeface::Ptr findTypefaceFor (const Font& font)
  72514. {
  72515. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  72516. const String faceName (font.getTypefaceName());
  72517. int i;
  72518. for (i = faces.size(); --i >= 0;)
  72519. {
  72520. CachedFace* const face = faces.getUnchecked(i);
  72521. if (face->flags == flags
  72522. && face->typefaceName == faceName)
  72523. {
  72524. face->lastUsageCount = ++counter;
  72525. return face->typeFace;
  72526. }
  72527. }
  72528. int replaceIndex = 0;
  72529. int bestLastUsageCount = std::numeric_limits<int>::max();
  72530. for (i = faces.size(); --i >= 0;)
  72531. {
  72532. const int lu = faces.getUnchecked(i)->lastUsageCount;
  72533. if (bestLastUsageCount > lu)
  72534. {
  72535. bestLastUsageCount = lu;
  72536. replaceIndex = i;
  72537. }
  72538. }
  72539. CachedFace* const face = faces.getUnchecked (replaceIndex);
  72540. face->typefaceName = faceName;
  72541. face->flags = flags;
  72542. face->lastUsageCount = ++counter;
  72543. face->typeFace = LookAndFeel::getDefaultLookAndFeel().getTypefaceForFont (font);
  72544. jassert (face->typeFace != 0); // the look and feel must return a typeface!
  72545. return face->typeFace;
  72546. }
  72547. juce_UseDebuggingNewOperator
  72548. private:
  72549. struct CachedFace
  72550. {
  72551. CachedFace() throw()
  72552. : lastUsageCount (0), flags (-1)
  72553. {
  72554. }
  72555. String typefaceName;
  72556. int lastUsageCount;
  72557. int flags;
  72558. Typeface::Ptr typeFace;
  72559. };
  72560. int counter;
  72561. OwnedArray <CachedFace> faces;
  72562. TypefaceCache (const TypefaceCache&);
  72563. TypefaceCache& operator= (const TypefaceCache&);
  72564. };
  72565. juce_ImplementSingleton_SingleThreaded (TypefaceCache)
  72566. Typeface* Font::getTypeface() const
  72567. {
  72568. if (font->typeface == 0)
  72569. font->typeface = TypefaceCache::getInstance()->findTypefaceFor (*this);
  72570. return font->typeface;
  72571. }
  72572. END_JUCE_NAMESPACE
  72573. /*** End of inlined file: juce_Font.cpp ***/
  72574. /*** Start of inlined file: juce_GlyphArrangement.cpp ***/
  72575. BEGIN_JUCE_NAMESPACE
  72576. PositionedGlyph::PositionedGlyph (const float x_, const float y_, const float w_, const Font& font_,
  72577. const juce_wchar character_, const int glyph_)
  72578. : x (x_),
  72579. y (y_),
  72580. w (w_),
  72581. font (font_),
  72582. character (character_),
  72583. glyph (glyph_)
  72584. {
  72585. }
  72586. PositionedGlyph::PositionedGlyph (const PositionedGlyph& other)
  72587. : x (other.x),
  72588. y (other.y),
  72589. w (other.w),
  72590. font (other.font),
  72591. character (other.character),
  72592. glyph (other.glyph)
  72593. {
  72594. }
  72595. void PositionedGlyph::draw (const Graphics& g) const
  72596. {
  72597. if (! isWhitespace())
  72598. {
  72599. g.getInternalContext()->setFont (font);
  72600. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y));
  72601. }
  72602. }
  72603. void PositionedGlyph::draw (const Graphics& g,
  72604. const AffineTransform& transform) const
  72605. {
  72606. if (! isWhitespace())
  72607. {
  72608. g.getInternalContext()->setFont (font);
  72609. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y)
  72610. .followedBy (transform));
  72611. }
  72612. }
  72613. void PositionedGlyph::createPath (Path& path) const
  72614. {
  72615. if (! isWhitespace())
  72616. {
  72617. Typeface* const t = font.getTypeface();
  72618. if (t != 0)
  72619. {
  72620. Path p;
  72621. t->getOutlineForGlyph (glyph, p);
  72622. path.addPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight())
  72623. .translated (x, y));
  72624. }
  72625. }
  72626. }
  72627. bool PositionedGlyph::hitTest (float px, float py) const
  72628. {
  72629. if (getBounds().contains (px, py) && ! isWhitespace())
  72630. {
  72631. Typeface* const t = font.getTypeface();
  72632. if (t != 0)
  72633. {
  72634. Path p;
  72635. t->getOutlineForGlyph (glyph, p);
  72636. AffineTransform::translation (-x, -y)
  72637. .scaled (1.0f / (font.getHeight() * font.getHorizontalScale()), 1.0f / font.getHeight())
  72638. .transformPoint (px, py);
  72639. return p.contains (px, py);
  72640. }
  72641. }
  72642. return false;
  72643. }
  72644. void PositionedGlyph::moveBy (const float deltaX,
  72645. const float deltaY)
  72646. {
  72647. x += deltaX;
  72648. y += deltaY;
  72649. }
  72650. GlyphArrangement::GlyphArrangement()
  72651. {
  72652. glyphs.ensureStorageAllocated (128);
  72653. }
  72654. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other)
  72655. {
  72656. addGlyphArrangement (other);
  72657. }
  72658. GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other)
  72659. {
  72660. if (this != &other)
  72661. {
  72662. clear();
  72663. addGlyphArrangement (other);
  72664. }
  72665. return *this;
  72666. }
  72667. GlyphArrangement::~GlyphArrangement()
  72668. {
  72669. }
  72670. void GlyphArrangement::clear()
  72671. {
  72672. glyphs.clear();
  72673. }
  72674. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const
  72675. {
  72676. jassert (((unsigned int) index) < (unsigned int) glyphs.size());
  72677. return *glyphs [index];
  72678. }
  72679. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other)
  72680. {
  72681. glyphs.ensureStorageAllocated (glyphs.size() + other.glyphs.size());
  72682. glyphs.addCopiesOf (other.glyphs);
  72683. }
  72684. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num)
  72685. {
  72686. glyphs.removeRange (startIndex, num < 0 ? glyphs.size() : num);
  72687. }
  72688. void GlyphArrangement::addLineOfText (const Font& font,
  72689. const String& text,
  72690. const float xOffset,
  72691. const float yOffset)
  72692. {
  72693. addCurtailedLineOfText (font, text,
  72694. xOffset, yOffset,
  72695. 1.0e10f, false);
  72696. }
  72697. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  72698. const String& text,
  72699. float xOffset,
  72700. const float yOffset,
  72701. const float maxWidthPixels,
  72702. const bool useEllipsis)
  72703. {
  72704. if (text.isNotEmpty())
  72705. {
  72706. Array <int> newGlyphs;
  72707. Array <float> xOffsets;
  72708. font.getGlyphPositions (text, newGlyphs, xOffsets);
  72709. const int textLen = newGlyphs.size();
  72710. const juce_wchar* const unicodeText = text;
  72711. for (int i = 0; i < textLen; ++i)
  72712. {
  72713. const float thisX = xOffsets.getUnchecked (i);
  72714. const float nextX = xOffsets.getUnchecked (i + 1);
  72715. if (nextX > maxWidthPixels + 1.0f)
  72716. {
  72717. // curtail the string if it's too wide..
  72718. if (useEllipsis && textLen > 3 && glyphs.size() >= 3)
  72719. insertEllipsis (font, xOffset + maxWidthPixels, 0, glyphs.size());
  72720. break;
  72721. }
  72722. else
  72723. {
  72724. glyphs.add (new PositionedGlyph (xOffset + thisX, yOffset, nextX - thisX,
  72725. font, unicodeText[i], newGlyphs.getUnchecked(i)));
  72726. }
  72727. }
  72728. }
  72729. }
  72730. int GlyphArrangement::insertEllipsis (const Font& font, const float maxXPos,
  72731. const int startIndex, int endIndex)
  72732. {
  72733. int numDeleted = 0;
  72734. if (glyphs.size() > 0)
  72735. {
  72736. Array<int> dotGlyphs;
  72737. Array<float> dotXs;
  72738. font.getGlyphPositions ("..", dotGlyphs, dotXs);
  72739. const float dx = dotXs[1];
  72740. float xOffset = 0.0f, yOffset = 0.0f;
  72741. while (endIndex > startIndex)
  72742. {
  72743. const PositionedGlyph* pg = glyphs.getUnchecked (--endIndex);
  72744. xOffset = pg->x;
  72745. yOffset = pg->y;
  72746. glyphs.remove (endIndex);
  72747. ++numDeleted;
  72748. if (xOffset + dx * 3 <= maxXPos)
  72749. break;
  72750. }
  72751. for (int i = 3; --i >= 0;)
  72752. {
  72753. glyphs.insert (endIndex++, new PositionedGlyph (xOffset, yOffset, dx,
  72754. font, '.', dotGlyphs.getFirst()));
  72755. --numDeleted;
  72756. xOffset += dx;
  72757. if (xOffset > maxXPos)
  72758. break;
  72759. }
  72760. }
  72761. return numDeleted;
  72762. }
  72763. void GlyphArrangement::addJustifiedText (const Font& font,
  72764. const String& text,
  72765. float x, float y,
  72766. const float maxLineWidth,
  72767. const Justification& horizontalLayout)
  72768. {
  72769. int lineStartIndex = glyphs.size();
  72770. addLineOfText (font, text, x, y);
  72771. const float originalY = y;
  72772. while (lineStartIndex < glyphs.size())
  72773. {
  72774. int i = lineStartIndex;
  72775. if (glyphs.getUnchecked(i)->getCharacter() != '\n'
  72776. && glyphs.getUnchecked(i)->getCharacter() != '\r')
  72777. ++i;
  72778. const float lineMaxX = glyphs.getUnchecked (lineStartIndex)->getLeft() + maxLineWidth;
  72779. int lastWordBreakIndex = -1;
  72780. while (i < glyphs.size())
  72781. {
  72782. const PositionedGlyph* pg = glyphs.getUnchecked (i);
  72783. const juce_wchar c = pg->getCharacter();
  72784. if (c == '\r' || c == '\n')
  72785. {
  72786. ++i;
  72787. if (c == '\r' && i < glyphs.size()
  72788. && glyphs.getUnchecked(i)->getCharacter() == '\n')
  72789. ++i;
  72790. break;
  72791. }
  72792. else if (pg->isWhitespace())
  72793. {
  72794. lastWordBreakIndex = i + 1;
  72795. }
  72796. else if (pg->getRight() - 0.0001f >= lineMaxX)
  72797. {
  72798. if (lastWordBreakIndex >= 0)
  72799. i = lastWordBreakIndex;
  72800. break;
  72801. }
  72802. ++i;
  72803. }
  72804. const float currentLineStartX = glyphs.getUnchecked (lineStartIndex)->getLeft();
  72805. float currentLineEndX = currentLineStartX;
  72806. for (int j = i; --j >= lineStartIndex;)
  72807. {
  72808. if (! glyphs.getUnchecked (j)->isWhitespace())
  72809. {
  72810. currentLineEndX = glyphs.getUnchecked (j)->getRight();
  72811. break;
  72812. }
  72813. }
  72814. float deltaX = 0.0f;
  72815. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  72816. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  72817. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  72818. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  72819. else if (horizontalLayout.testFlags (Justification::right))
  72820. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  72821. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  72822. x + deltaX - currentLineStartX, y - originalY);
  72823. lineStartIndex = i;
  72824. y += font.getHeight();
  72825. }
  72826. }
  72827. void GlyphArrangement::addFittedText (const Font& f,
  72828. const String& text,
  72829. const float x, const float y,
  72830. const float width, const float height,
  72831. const Justification& layout,
  72832. int maximumLines,
  72833. const float minimumHorizontalScale)
  72834. {
  72835. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  72836. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  72837. if (text.containsAnyOf ("\r\n"))
  72838. {
  72839. GlyphArrangement ga;
  72840. ga.addJustifiedText (f, text, x, y, width, layout);
  72841. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  72842. float dy = y - bb.getY();
  72843. if (layout.testFlags (Justification::verticallyCentred))
  72844. dy += (height - bb.getHeight()) * 0.5f;
  72845. else if (layout.testFlags (Justification::bottom))
  72846. dy += height - bb.getHeight();
  72847. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  72848. glyphs.ensureStorageAllocated (glyphs.size() + ga.glyphs.size());
  72849. for (int i = 0; i < ga.glyphs.size(); ++i)
  72850. glyphs.add (ga.glyphs.getUnchecked (i));
  72851. ga.glyphs.clear (false);
  72852. return;
  72853. }
  72854. int startIndex = glyphs.size();
  72855. addLineOfText (f, text.trim(), x, y);
  72856. if (glyphs.size() > startIndex)
  72857. {
  72858. float lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  72859. - glyphs.getUnchecked (startIndex)->getLeft();
  72860. if (lineWidth <= 0)
  72861. return;
  72862. if (lineWidth * minimumHorizontalScale < width)
  72863. {
  72864. if (lineWidth > width)
  72865. stretchRangeOfGlyphs (startIndex, glyphs.size() - startIndex,
  72866. width / lineWidth);
  72867. justifyGlyphs (startIndex, glyphs.size() - startIndex,
  72868. x, y, width, height, layout);
  72869. }
  72870. else if (maximumLines <= 1)
  72871. {
  72872. fitLineIntoSpace (startIndex, glyphs.size() - startIndex,
  72873. x, y, width, height, f, layout, minimumHorizontalScale);
  72874. }
  72875. else
  72876. {
  72877. Font font (f);
  72878. String txt (text.trim());
  72879. const int length = txt.length();
  72880. const int originalStartIndex = startIndex;
  72881. int numLines = 1;
  72882. if (length <= 12 && ! txt.containsAnyOf (" -\t\r\n"))
  72883. maximumLines = 1;
  72884. maximumLines = jmin (maximumLines, length);
  72885. while (numLines < maximumLines)
  72886. {
  72887. ++numLines;
  72888. const float newFontHeight = height / (float) numLines;
  72889. if (newFontHeight < font.getHeight())
  72890. {
  72891. font.setHeight (jmax (8.0f, newFontHeight));
  72892. removeRangeOfGlyphs (startIndex, -1);
  72893. addLineOfText (font, txt, x, y);
  72894. lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  72895. - glyphs.getUnchecked (startIndex)->getLeft();
  72896. }
  72897. if (numLines > lineWidth / width || newFontHeight < 8.0f)
  72898. break;
  72899. }
  72900. if (numLines < 1)
  72901. numLines = 1;
  72902. float lineY = y;
  72903. float widthPerLine = lineWidth / numLines;
  72904. int lastLineStartIndex = 0;
  72905. for (int line = 0; line < numLines; ++line)
  72906. {
  72907. int i = startIndex;
  72908. lastLineStartIndex = i;
  72909. float lineStartX = glyphs.getUnchecked (startIndex)->getLeft();
  72910. if (line == numLines - 1)
  72911. {
  72912. widthPerLine = width;
  72913. i = glyphs.size();
  72914. }
  72915. else
  72916. {
  72917. while (i < glyphs.size())
  72918. {
  72919. lineWidth = (glyphs.getUnchecked (i)->getRight() - lineStartX);
  72920. if (lineWidth > widthPerLine)
  72921. {
  72922. // got to a point where the line's too long, so skip forward to find a
  72923. // good place to break it..
  72924. const int searchStartIndex = i;
  72925. while (i < glyphs.size())
  72926. {
  72927. if ((glyphs.getUnchecked (i)->getRight() - lineStartX) * minimumHorizontalScale < width)
  72928. {
  72929. if (glyphs.getUnchecked (i)->isWhitespace()
  72930. || glyphs.getUnchecked (i)->getCharacter() == '-')
  72931. {
  72932. ++i;
  72933. break;
  72934. }
  72935. }
  72936. else
  72937. {
  72938. // can't find a suitable break, so try looking backwards..
  72939. i = searchStartIndex;
  72940. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  72941. {
  72942. if (glyphs.getUnchecked (i - back)->isWhitespace()
  72943. || glyphs.getUnchecked (i - back)->getCharacter() == '-')
  72944. {
  72945. i -= back - 1;
  72946. break;
  72947. }
  72948. }
  72949. break;
  72950. }
  72951. ++i;
  72952. }
  72953. break;
  72954. }
  72955. ++i;
  72956. }
  72957. int wsStart = i;
  72958. while (wsStart > 0 && glyphs.getUnchecked (wsStart - 1)->isWhitespace())
  72959. --wsStart;
  72960. int wsEnd = i;
  72961. while (wsEnd < glyphs.size() && glyphs.getUnchecked (wsEnd)->isWhitespace())
  72962. ++wsEnd;
  72963. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  72964. i = jmax (wsStart, startIndex + 1);
  72965. }
  72966. i -= fitLineIntoSpace (startIndex, i - startIndex,
  72967. x, lineY, width, font.getHeight(), font,
  72968. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  72969. minimumHorizontalScale);
  72970. startIndex = i;
  72971. lineY += font.getHeight();
  72972. if (startIndex >= glyphs.size())
  72973. break;
  72974. }
  72975. justifyGlyphs (originalStartIndex, glyphs.size() - originalStartIndex,
  72976. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  72977. }
  72978. }
  72979. }
  72980. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  72981. const float dx, const float dy)
  72982. {
  72983. jassert (startIndex >= 0);
  72984. if (dx != 0.0f || dy != 0.0f)
  72985. {
  72986. if (num < 0 || startIndex + num > glyphs.size())
  72987. num = glyphs.size() - startIndex;
  72988. while (--num >= 0)
  72989. glyphs.getUnchecked (startIndex++)->moveBy (dx, dy);
  72990. }
  72991. }
  72992. int GlyphArrangement::fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  72993. const Justification& justification, float minimumHorizontalScale)
  72994. {
  72995. int numDeleted = 0;
  72996. const float lineStartX = glyphs.getUnchecked (start)->getLeft();
  72997. float lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX;
  72998. if (lineWidth > w)
  72999. {
  73000. if (minimumHorizontalScale < 1.0f)
  73001. {
  73002. stretchRangeOfGlyphs (start, numGlyphs, jmax (minimumHorizontalScale, w / lineWidth));
  73003. lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX - 0.5f;
  73004. }
  73005. if (lineWidth > w)
  73006. {
  73007. numDeleted = insertEllipsis (font, lineStartX + w, start, start + numGlyphs);
  73008. numGlyphs -= numDeleted;
  73009. }
  73010. }
  73011. justifyGlyphs (start, numGlyphs, x, y, w, h, justification);
  73012. return numDeleted;
  73013. }
  73014. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  73015. const float horizontalScaleFactor)
  73016. {
  73017. jassert (startIndex >= 0);
  73018. if (num < 0 || startIndex + num > glyphs.size())
  73019. num = glyphs.size() - startIndex;
  73020. if (num > 0)
  73021. {
  73022. const float xAnchor = glyphs.getUnchecked (startIndex)->getLeft();
  73023. while (--num >= 0)
  73024. {
  73025. PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  73026. pg->x = xAnchor + (pg->x - xAnchor) * horizontalScaleFactor;
  73027. pg->font.setHorizontalScale (pg->font.getHorizontalScale() * horizontalScaleFactor);
  73028. pg->w *= horizontalScaleFactor;
  73029. }
  73030. }
  73031. }
  73032. const Rectangle<float> GlyphArrangement::getBoundingBox (int startIndex, int num, const bool includeWhitespace) const
  73033. {
  73034. jassert (startIndex >= 0);
  73035. if (num < 0 || startIndex + num > glyphs.size())
  73036. num = glyphs.size() - startIndex;
  73037. Rectangle<float> result;
  73038. while (--num >= 0)
  73039. {
  73040. const PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  73041. if (includeWhitespace || ! pg->isWhitespace())
  73042. result = result.getUnion (pg->getBounds());
  73043. }
  73044. return result;
  73045. }
  73046. void GlyphArrangement::justifyGlyphs (const int startIndex, const int num,
  73047. const float x, const float y, const float width, const float height,
  73048. const Justification& justification)
  73049. {
  73050. jassert (num >= 0 && startIndex >= 0);
  73051. if (glyphs.size() > 0 && num > 0)
  73052. {
  73053. const Rectangle<float> bb (getBoundingBox (startIndex, num, ! justification.testFlags (Justification::horizontallyJustified
  73054. | Justification::horizontallyCentred)));
  73055. float deltaX = 0.0f;
  73056. if (justification.testFlags (Justification::horizontallyJustified))
  73057. deltaX = x - bb.getX();
  73058. else if (justification.testFlags (Justification::horizontallyCentred))
  73059. deltaX = x + (width - bb.getWidth()) * 0.5f - bb.getX();
  73060. else if (justification.testFlags (Justification::right))
  73061. deltaX = (x + width) - bb.getRight();
  73062. else
  73063. deltaX = x - bb.getX();
  73064. float deltaY = 0.0f;
  73065. if (justification.testFlags (Justification::top))
  73066. deltaY = y - bb.getY();
  73067. else if (justification.testFlags (Justification::bottom))
  73068. deltaY = (y + height) - bb.getBottom();
  73069. else
  73070. deltaY = y + (height - bb.getHeight()) * 0.5f - bb.getY();
  73071. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  73072. if (justification.testFlags (Justification::horizontallyJustified))
  73073. {
  73074. int lineStart = 0;
  73075. float baseY = glyphs.getUnchecked (startIndex)->getBaselineY();
  73076. int i;
  73077. for (i = 0; i < num; ++i)
  73078. {
  73079. const float glyphY = glyphs.getUnchecked (startIndex + i)->getBaselineY();
  73080. if (glyphY != baseY)
  73081. {
  73082. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  73083. lineStart = i;
  73084. baseY = glyphY;
  73085. }
  73086. }
  73087. if (i > lineStart)
  73088. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  73089. }
  73090. }
  73091. }
  73092. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth)
  73093. {
  73094. if (start + num < glyphs.size()
  73095. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\r'
  73096. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\n')
  73097. {
  73098. int numSpaces = 0;
  73099. int spacesAtEnd = 0;
  73100. for (int i = 0; i < num; ++i)
  73101. {
  73102. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73103. {
  73104. ++spacesAtEnd;
  73105. ++numSpaces;
  73106. }
  73107. else
  73108. {
  73109. spacesAtEnd = 0;
  73110. }
  73111. }
  73112. numSpaces -= spacesAtEnd;
  73113. if (numSpaces > 0)
  73114. {
  73115. const float startX = glyphs.getUnchecked (start)->getLeft();
  73116. const float endX = glyphs.getUnchecked (start + num - 1 - spacesAtEnd)->getRight();
  73117. const float extraPaddingBetweenWords
  73118. = (targetWidth - (endX - startX)) / (float) numSpaces;
  73119. float deltaX = 0.0f;
  73120. for (int i = 0; i < num; ++i)
  73121. {
  73122. glyphs.getUnchecked (start + i)->moveBy (deltaX, 0.0f);
  73123. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73124. deltaX += extraPaddingBetweenWords;
  73125. }
  73126. }
  73127. }
  73128. }
  73129. void GlyphArrangement::draw (const Graphics& g) const
  73130. {
  73131. for (int i = 0; i < glyphs.size(); ++i)
  73132. {
  73133. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73134. if (pg->font.isUnderlined())
  73135. {
  73136. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73137. float nextX = pg->x + pg->w;
  73138. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73139. nextX = glyphs.getUnchecked (i + 1)->x;
  73140. g.fillRect (pg->x, pg->y + lineThickness * 2.0f,
  73141. nextX - pg->x, lineThickness);
  73142. }
  73143. pg->draw (g);
  73144. }
  73145. }
  73146. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const
  73147. {
  73148. for (int i = 0; i < glyphs.size(); ++i)
  73149. {
  73150. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73151. if (pg->font.isUnderlined())
  73152. {
  73153. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73154. float nextX = pg->x + pg->w;
  73155. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73156. nextX = glyphs.getUnchecked (i + 1)->x;
  73157. Path p;
  73158. p.addLineSegment (Line<float> (pg->x, pg->y + lineThickness * 2.0f,
  73159. nextX, pg->y + lineThickness * 2.0f),
  73160. lineThickness);
  73161. g.fillPath (p, transform);
  73162. }
  73163. pg->draw (g, transform);
  73164. }
  73165. }
  73166. void GlyphArrangement::createPath (Path& path) const
  73167. {
  73168. for (int i = 0; i < glyphs.size(); ++i)
  73169. glyphs.getUnchecked (i)->createPath (path);
  73170. }
  73171. int GlyphArrangement::findGlyphIndexAt (float x, float y) const
  73172. {
  73173. for (int i = 0; i < glyphs.size(); ++i)
  73174. if (glyphs.getUnchecked (i)->hitTest (x, y))
  73175. return i;
  73176. return -1;
  73177. }
  73178. END_JUCE_NAMESPACE
  73179. /*** End of inlined file: juce_GlyphArrangement.cpp ***/
  73180. /*** Start of inlined file: juce_TextLayout.cpp ***/
  73181. BEGIN_JUCE_NAMESPACE
  73182. class TextLayout::Token
  73183. {
  73184. public:
  73185. String text;
  73186. Font font;
  73187. int x, y, w, h;
  73188. int line, lineHeight;
  73189. bool isWhitespace, isNewLine;
  73190. Token (const String& t,
  73191. const Font& f,
  73192. const bool isWhitespace_)
  73193. : text (t),
  73194. font (f),
  73195. x(0),
  73196. y(0),
  73197. isWhitespace (isWhitespace_)
  73198. {
  73199. w = font.getStringWidth (t);
  73200. h = roundToInt (f.getHeight());
  73201. isNewLine = t.containsChar ('\n') || t.containsChar ('\r');
  73202. }
  73203. Token (const Token& other)
  73204. : text (other.text),
  73205. font (other.font),
  73206. x (other.x),
  73207. y (other.y),
  73208. w (other.w),
  73209. h (other.h),
  73210. line (other.line),
  73211. lineHeight (other.lineHeight),
  73212. isWhitespace (other.isWhitespace),
  73213. isNewLine (other.isNewLine)
  73214. {
  73215. }
  73216. ~Token()
  73217. {
  73218. }
  73219. void draw (Graphics& g,
  73220. const int xOffset,
  73221. const int yOffset)
  73222. {
  73223. if (! isWhitespace)
  73224. {
  73225. g.setFont (font);
  73226. g.drawSingleLineText (text.trimEnd(),
  73227. xOffset + x,
  73228. yOffset + y + (lineHeight - h)
  73229. + roundToInt (font.getAscent()));
  73230. }
  73231. }
  73232. juce_UseDebuggingNewOperator
  73233. };
  73234. TextLayout::TextLayout()
  73235. : totalLines (0)
  73236. {
  73237. tokens.ensureStorageAllocated (64);
  73238. }
  73239. TextLayout::TextLayout (const String& text, const Font& font)
  73240. : totalLines (0)
  73241. {
  73242. tokens.ensureStorageAllocated (64);
  73243. appendText (text, font);
  73244. }
  73245. TextLayout::TextLayout (const TextLayout& other)
  73246. : totalLines (0)
  73247. {
  73248. *this = other;
  73249. }
  73250. TextLayout& TextLayout::operator= (const TextLayout& other)
  73251. {
  73252. if (this != &other)
  73253. {
  73254. clear();
  73255. totalLines = other.totalLines;
  73256. tokens.addCopiesOf (other.tokens);
  73257. }
  73258. return *this;
  73259. }
  73260. TextLayout::~TextLayout()
  73261. {
  73262. clear();
  73263. }
  73264. void TextLayout::clear()
  73265. {
  73266. tokens.clear();
  73267. totalLines = 0;
  73268. }
  73269. bool TextLayout::isEmpty() const
  73270. {
  73271. return tokens.size() == 0;
  73272. }
  73273. void TextLayout::appendText (const String& text, const Font& font)
  73274. {
  73275. const juce_wchar* t = text;
  73276. String currentString;
  73277. int lastCharType = 0;
  73278. for (;;)
  73279. {
  73280. const juce_wchar c = *t++;
  73281. if (c == 0)
  73282. break;
  73283. int charType;
  73284. if (c == '\r' || c == '\n')
  73285. {
  73286. charType = 0;
  73287. }
  73288. else if (CharacterFunctions::isWhitespace (c))
  73289. {
  73290. charType = 2;
  73291. }
  73292. else
  73293. {
  73294. charType = 1;
  73295. }
  73296. if (charType == 0 || charType != lastCharType)
  73297. {
  73298. if (currentString.isNotEmpty())
  73299. {
  73300. tokens.add (new Token (currentString, font,
  73301. lastCharType == 2 || lastCharType == 0));
  73302. }
  73303. currentString = String::charToString (c);
  73304. if (c == '\r' && *t == '\n')
  73305. currentString += *t++;
  73306. }
  73307. else
  73308. {
  73309. currentString += c;
  73310. }
  73311. lastCharType = charType;
  73312. }
  73313. if (currentString.isNotEmpty())
  73314. tokens.add (new Token (currentString, font, lastCharType == 2));
  73315. }
  73316. void TextLayout::setText (const String& text, const Font& font)
  73317. {
  73318. clear();
  73319. appendText (text, font);
  73320. }
  73321. void TextLayout::layout (int maxWidth,
  73322. const Justification& justification,
  73323. const bool attemptToBalanceLineLengths)
  73324. {
  73325. if (attemptToBalanceLineLengths)
  73326. {
  73327. const int originalW = maxWidth;
  73328. int bestWidth = maxWidth;
  73329. float bestLineProportion = 0.0f;
  73330. while (maxWidth > originalW / 2)
  73331. {
  73332. layout (maxWidth, justification, false);
  73333. if (getNumLines() <= 1)
  73334. return;
  73335. const int lastLineW = getLineWidth (getNumLines() - 1);
  73336. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  73337. const float prop = lastLineW / (float) lastButOneLineW;
  73338. if (prop > 0.9f)
  73339. return;
  73340. if (prop > bestLineProportion)
  73341. {
  73342. bestLineProportion = prop;
  73343. bestWidth = maxWidth;
  73344. }
  73345. maxWidth -= 10;
  73346. }
  73347. layout (bestWidth, justification, false);
  73348. }
  73349. else
  73350. {
  73351. int x = 0;
  73352. int y = 0;
  73353. int h = 0;
  73354. totalLines = 0;
  73355. int i;
  73356. for (i = 0; i < tokens.size(); ++i)
  73357. {
  73358. Token* const t = tokens.getUnchecked(i);
  73359. t->x = x;
  73360. t->y = y;
  73361. t->line = totalLines;
  73362. x += t->w;
  73363. h = jmax (h, t->h);
  73364. const Token* nextTok = tokens [i + 1];
  73365. if (nextTok == 0)
  73366. break;
  73367. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  73368. {
  73369. // finished a line, so go back and update the heights of the things on it
  73370. for (int j = i; j >= 0; --j)
  73371. {
  73372. Token* const tok = tokens.getUnchecked(j);
  73373. if (tok->line == totalLines)
  73374. tok->lineHeight = h;
  73375. else
  73376. break;
  73377. }
  73378. x = 0;
  73379. y += h;
  73380. h = 0;
  73381. ++totalLines;
  73382. }
  73383. }
  73384. // finished a line, so go back and update the heights of the things on it
  73385. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  73386. {
  73387. Token* const t = tokens.getUnchecked(j);
  73388. if (t->line == totalLines)
  73389. t->lineHeight = h;
  73390. else
  73391. break;
  73392. }
  73393. ++totalLines;
  73394. if (! justification.testFlags (Justification::left))
  73395. {
  73396. int totalW = getWidth();
  73397. for (i = totalLines; --i >= 0;)
  73398. {
  73399. const int lineW = getLineWidth (i);
  73400. int dx = 0;
  73401. if (justification.testFlags (Justification::horizontallyCentred))
  73402. dx = (totalW - lineW) / 2;
  73403. else if (justification.testFlags (Justification::right))
  73404. dx = totalW - lineW;
  73405. for (int j = tokens.size(); --j >= 0;)
  73406. {
  73407. Token* const t = tokens.getUnchecked(j);
  73408. if (t->line == i)
  73409. t->x += dx;
  73410. }
  73411. }
  73412. }
  73413. }
  73414. }
  73415. int TextLayout::getLineWidth (const int lineNumber) const
  73416. {
  73417. int maxW = 0;
  73418. for (int i = tokens.size(); --i >= 0;)
  73419. {
  73420. const Token* const t = tokens.getUnchecked(i);
  73421. if (t->line == lineNumber && ! t->isWhitespace)
  73422. maxW = jmax (maxW, t->x + t->w);
  73423. }
  73424. return maxW;
  73425. }
  73426. int TextLayout::getWidth() const
  73427. {
  73428. int maxW = 0;
  73429. for (int i = tokens.size(); --i >= 0;)
  73430. {
  73431. const Token* const t = tokens.getUnchecked(i);
  73432. if (! t->isWhitespace)
  73433. maxW = jmax (maxW, t->x + t->w);
  73434. }
  73435. return maxW;
  73436. }
  73437. int TextLayout::getHeight() const
  73438. {
  73439. int maxH = 0;
  73440. for (int i = tokens.size(); --i >= 0;)
  73441. {
  73442. const Token* const t = tokens.getUnchecked(i);
  73443. if (! t->isWhitespace)
  73444. maxH = jmax (maxH, t->y + t->h);
  73445. }
  73446. return maxH;
  73447. }
  73448. void TextLayout::draw (Graphics& g,
  73449. const int xOffset,
  73450. const int yOffset) const
  73451. {
  73452. for (int i = tokens.size(); --i >= 0;)
  73453. tokens.getUnchecked(i)->draw (g, xOffset, yOffset);
  73454. }
  73455. void TextLayout::drawWithin (Graphics& g,
  73456. int x, int y, int w, int h,
  73457. const Justification& justification) const
  73458. {
  73459. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  73460. x, y, w, h);
  73461. draw (g, x, y);
  73462. }
  73463. END_JUCE_NAMESPACE
  73464. /*** End of inlined file: juce_TextLayout.cpp ***/
  73465. /*** Start of inlined file: juce_Typeface.cpp ***/
  73466. BEGIN_JUCE_NAMESPACE
  73467. Typeface::Typeface (const String& name_) throw()
  73468. : name (name_)
  73469. {
  73470. }
  73471. Typeface::~Typeface()
  73472. {
  73473. }
  73474. class CustomTypeface::GlyphInfo
  73475. {
  73476. public:
  73477. GlyphInfo (const juce_wchar character_, const Path& path_, const float width_) throw()
  73478. : character (character_), path (path_), width (width_)
  73479. {
  73480. }
  73481. ~GlyphInfo() throw()
  73482. {
  73483. }
  73484. struct KerningPair
  73485. {
  73486. juce_wchar character2;
  73487. float kerningAmount;
  73488. };
  73489. void addKerningPair (const juce_wchar subsequentCharacter,
  73490. const float extraKerningAmount) throw()
  73491. {
  73492. KerningPair kp;
  73493. kp.character2 = subsequentCharacter;
  73494. kp.kerningAmount = extraKerningAmount;
  73495. kerningPairs.add (kp);
  73496. }
  73497. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  73498. {
  73499. if (subsequentCharacter != 0)
  73500. {
  73501. for (int i = kerningPairs.size(); --i >= 0;)
  73502. if (kerningPairs.getReference(i).character2 == subsequentCharacter)
  73503. return width + kerningPairs.getReference(i).kerningAmount;
  73504. }
  73505. return width;
  73506. }
  73507. const juce_wchar character;
  73508. const Path path;
  73509. float width;
  73510. Array <KerningPair> kerningPairs;
  73511. juce_UseDebuggingNewOperator
  73512. private:
  73513. GlyphInfo (const GlyphInfo&);
  73514. GlyphInfo& operator= (const GlyphInfo&);
  73515. };
  73516. CustomTypeface::CustomTypeface()
  73517. : Typeface (String::empty)
  73518. {
  73519. clear();
  73520. }
  73521. CustomTypeface::CustomTypeface (InputStream& serialisedTypefaceStream)
  73522. : Typeface (String::empty)
  73523. {
  73524. clear();
  73525. GZIPDecompressorInputStream gzin (&serialisedTypefaceStream, false);
  73526. BufferedInputStream in (&gzin, 32768, false);
  73527. name = in.readString();
  73528. isBold = in.readBool();
  73529. isItalic = in.readBool();
  73530. ascent = in.readFloat();
  73531. defaultCharacter = (juce_wchar) in.readShort();
  73532. int i, numChars = in.readInt();
  73533. for (i = 0; i < numChars; ++i)
  73534. {
  73535. const juce_wchar c = (juce_wchar) in.readShort();
  73536. const float width = in.readFloat();
  73537. Path p;
  73538. p.loadPathFromStream (in);
  73539. addGlyph (c, p, width);
  73540. }
  73541. const int numKerningPairs = in.readInt();
  73542. for (i = 0; i < numKerningPairs; ++i)
  73543. {
  73544. const juce_wchar char1 = (juce_wchar) in.readShort();
  73545. const juce_wchar char2 = (juce_wchar) in.readShort();
  73546. addKerningPair (char1, char2, in.readFloat());
  73547. }
  73548. }
  73549. CustomTypeface::~CustomTypeface()
  73550. {
  73551. }
  73552. void CustomTypeface::clear()
  73553. {
  73554. defaultCharacter = 0;
  73555. ascent = 1.0f;
  73556. isBold = isItalic = false;
  73557. zeromem (lookupTable, sizeof (lookupTable));
  73558. glyphs.clear();
  73559. }
  73560. void CustomTypeface::setCharacteristics (const String& name_, const float ascent_, const bool isBold_,
  73561. const bool isItalic_, const juce_wchar defaultCharacter_) throw()
  73562. {
  73563. name = name_;
  73564. defaultCharacter = defaultCharacter_;
  73565. ascent = ascent_;
  73566. isBold = isBold_;
  73567. isItalic = isItalic_;
  73568. }
  73569. void CustomTypeface::addGlyph (const juce_wchar character, const Path& path, const float width) throw()
  73570. {
  73571. // Check that you're not trying to add the same character twice..
  73572. jassert (findGlyph (character, false) == 0);
  73573. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable))
  73574. lookupTable [character] = (short) glyphs.size();
  73575. glyphs.add (new GlyphInfo (character, path, width));
  73576. }
  73577. void CustomTypeface::addKerningPair (const juce_wchar char1, const juce_wchar char2, const float extraAmount) throw()
  73578. {
  73579. if (extraAmount != 0)
  73580. {
  73581. GlyphInfo* const g = findGlyph (char1, true);
  73582. jassert (g != 0); // can only add kerning pairs for characters that exist!
  73583. if (g != 0)
  73584. g->addKerningPair (char2, extraAmount);
  73585. }
  73586. }
  73587. CustomTypeface::GlyphInfo* CustomTypeface::findGlyph (const juce_wchar character, const bool loadIfNeeded) throw()
  73588. {
  73589. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable) && lookupTable [character] > 0)
  73590. return glyphs [(int) lookupTable [(int) character]];
  73591. for (int i = 0; i < glyphs.size(); ++i)
  73592. {
  73593. GlyphInfo* const g = glyphs.getUnchecked(i);
  73594. if (g->character == character)
  73595. return g;
  73596. }
  73597. if (loadIfNeeded && loadGlyphIfPossible (character))
  73598. return findGlyph (character, false);
  73599. return 0;
  73600. }
  73601. CustomTypeface::GlyphInfo* CustomTypeface::findGlyphSubstituting (const juce_wchar character) throw()
  73602. {
  73603. GlyphInfo* glyph = findGlyph (character, true);
  73604. if (glyph == 0)
  73605. {
  73606. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  73607. glyph = findGlyph (L' ', true);
  73608. if (glyph == 0)
  73609. {
  73610. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  73611. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  73612. if (fallbackTypeface != 0 && fallbackTypeface != this)
  73613. {
  73614. //xxx
  73615. }
  73616. if (glyph == 0)
  73617. glyph = findGlyph (defaultCharacter, true);
  73618. }
  73619. }
  73620. return glyph;
  73621. }
  73622. bool CustomTypeface::loadGlyphIfPossible (const juce_wchar /*characterNeeded*/)
  73623. {
  73624. return false;
  73625. }
  73626. void CustomTypeface::addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw()
  73627. {
  73628. setCharacteristics (name, typefaceToCopy.getAscent(), isBold, isItalic, defaultCharacter);
  73629. for (int i = 0; i < numCharacters; ++i)
  73630. {
  73631. const juce_wchar c = (juce_wchar) (characterStartIndex + i);
  73632. Array <int> glyphIndexes;
  73633. Array <float> offsets;
  73634. typefaceToCopy.getGlyphPositions (String::charToString (c), glyphIndexes, offsets);
  73635. const int glyphIndex = glyphIndexes.getFirst();
  73636. if (glyphIndex >= 0 && glyphIndexes.size() > 0)
  73637. {
  73638. const float glyphWidth = offsets[1];
  73639. Path p;
  73640. typefaceToCopy.getOutlineForGlyph (glyphIndex, p);
  73641. addGlyph (c, p, glyphWidth);
  73642. for (int j = glyphs.size() - 1; --j >= 0;)
  73643. {
  73644. const juce_wchar char2 = glyphs.getUnchecked (j)->character;
  73645. glyphIndexes.clearQuick();
  73646. offsets.clearQuick();
  73647. typefaceToCopy.getGlyphPositions (String::charToString (c) + String::charToString (char2), glyphIndexes, offsets);
  73648. if (offsets.size() > 1)
  73649. addKerningPair (c, char2, offsets[1] - glyphWidth);
  73650. }
  73651. }
  73652. }
  73653. }
  73654. bool CustomTypeface::writeToStream (OutputStream& outputStream)
  73655. {
  73656. GZIPCompressorOutputStream out (&outputStream);
  73657. out.writeString (name);
  73658. out.writeBool (isBold);
  73659. out.writeBool (isItalic);
  73660. out.writeFloat (ascent);
  73661. out.writeShort ((short) (unsigned short) defaultCharacter);
  73662. out.writeInt (glyphs.size());
  73663. int i, numKerningPairs = 0;
  73664. for (i = 0; i < glyphs.size(); ++i)
  73665. {
  73666. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73667. out.writeShort ((short) (unsigned short) g->character);
  73668. out.writeFloat (g->width);
  73669. g->path.writePathToStream (out);
  73670. numKerningPairs += g->kerningPairs.size();
  73671. }
  73672. out.writeInt (numKerningPairs);
  73673. for (i = 0; i < glyphs.size(); ++i)
  73674. {
  73675. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73676. for (int j = 0; j < g->kerningPairs.size(); ++j)
  73677. {
  73678. const GlyphInfo::KerningPair& p = g->kerningPairs.getReference (j);
  73679. out.writeShort ((short) (unsigned short) g->character);
  73680. out.writeShort ((short) (unsigned short) p.character2);
  73681. out.writeFloat (p.kerningAmount);
  73682. }
  73683. }
  73684. return true;
  73685. }
  73686. float CustomTypeface::getAscent() const
  73687. {
  73688. return ascent;
  73689. }
  73690. float CustomTypeface::getDescent() const
  73691. {
  73692. return 1.0f - ascent;
  73693. }
  73694. float CustomTypeface::getStringWidth (const String& text)
  73695. {
  73696. float x = 0;
  73697. const juce_wchar* t = text;
  73698. while (*t != 0)
  73699. {
  73700. const GlyphInfo* const glyph = findGlyphSubstituting (*t++);
  73701. if (glyph != 0)
  73702. x += glyph->getHorizontalSpacing (*t);
  73703. }
  73704. return x;
  73705. }
  73706. void CustomTypeface::getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array<float>& xOffsets)
  73707. {
  73708. xOffsets.add (0);
  73709. float x = 0;
  73710. const juce_wchar* t = text;
  73711. while (*t != 0)
  73712. {
  73713. const juce_wchar c = *t++;
  73714. const GlyphInfo* const glyph = findGlyphSubstituting (c);
  73715. if (glyph != 0)
  73716. {
  73717. x += glyph->getHorizontalSpacing (*t);
  73718. resultGlyphs.add ((int) glyph->character);
  73719. xOffsets.add (x);
  73720. }
  73721. }
  73722. }
  73723. bool CustomTypeface::getOutlineForGlyph (int glyphNumber, Path& path)
  73724. {
  73725. const GlyphInfo* const glyph = findGlyphSubstituting ((juce_wchar) glyphNumber);
  73726. if (glyph != 0)
  73727. {
  73728. path = glyph->path;
  73729. return true;
  73730. }
  73731. return false;
  73732. }
  73733. END_JUCE_NAMESPACE
  73734. /*** End of inlined file: juce_Typeface.cpp ***/
  73735. /*** Start of inlined file: juce_AffineTransform.cpp ***/
  73736. BEGIN_JUCE_NAMESPACE
  73737. AffineTransform::AffineTransform() throw()
  73738. : mat00 (1.0f),
  73739. mat01 (0),
  73740. mat02 (0),
  73741. mat10 (0),
  73742. mat11 (1.0f),
  73743. mat12 (0)
  73744. {
  73745. }
  73746. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  73747. : mat00 (other.mat00),
  73748. mat01 (other.mat01),
  73749. mat02 (other.mat02),
  73750. mat10 (other.mat10),
  73751. mat11 (other.mat11),
  73752. mat12 (other.mat12)
  73753. {
  73754. }
  73755. AffineTransform::AffineTransform (const float mat00_,
  73756. const float mat01_,
  73757. const float mat02_,
  73758. const float mat10_,
  73759. const float mat11_,
  73760. const float mat12_) throw()
  73761. : mat00 (mat00_),
  73762. mat01 (mat01_),
  73763. mat02 (mat02_),
  73764. mat10 (mat10_),
  73765. mat11 (mat11_),
  73766. mat12 (mat12_)
  73767. {
  73768. }
  73769. AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  73770. {
  73771. mat00 = other.mat00;
  73772. mat01 = other.mat01;
  73773. mat02 = other.mat02;
  73774. mat10 = other.mat10;
  73775. mat11 = other.mat11;
  73776. mat12 = other.mat12;
  73777. return *this;
  73778. }
  73779. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  73780. {
  73781. return mat00 == other.mat00
  73782. && mat01 == other.mat01
  73783. && mat02 == other.mat02
  73784. && mat10 == other.mat10
  73785. && mat11 == other.mat11
  73786. && mat12 == other.mat12;
  73787. }
  73788. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  73789. {
  73790. return ! operator== (other);
  73791. }
  73792. bool AffineTransform::isIdentity() const throw()
  73793. {
  73794. return (mat01 == 0)
  73795. && (mat02 == 0)
  73796. && (mat10 == 0)
  73797. && (mat12 == 0)
  73798. && (mat00 == 1.0f)
  73799. && (mat11 == 1.0f);
  73800. }
  73801. const AffineTransform AffineTransform::identity;
  73802. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  73803. {
  73804. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  73805. other.mat00 * mat01 + other.mat01 * mat11,
  73806. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  73807. other.mat10 * mat00 + other.mat11 * mat10,
  73808. other.mat10 * mat01 + other.mat11 * mat11,
  73809. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  73810. }
  73811. const AffineTransform AffineTransform::followedBy (const float omat00,
  73812. const float omat01,
  73813. const float omat02,
  73814. const float omat10,
  73815. const float omat11,
  73816. const float omat12) const throw()
  73817. {
  73818. return AffineTransform (omat00 * mat00 + omat01 * mat10,
  73819. omat00 * mat01 + omat01 * mat11,
  73820. omat00 * mat02 + omat01 * mat12 + omat02,
  73821. omat10 * mat00 + omat11 * mat10,
  73822. omat10 * mat01 + omat11 * mat11,
  73823. omat10 * mat02 + omat11 * mat12 + omat12);
  73824. }
  73825. const AffineTransform AffineTransform::translated (const float dx,
  73826. const float dy) const throw()
  73827. {
  73828. return AffineTransform (mat00, mat01, mat02 + dx,
  73829. mat10, mat11, mat12 + dy);
  73830. }
  73831. const AffineTransform AffineTransform::translation (const float dx,
  73832. const float dy) throw()
  73833. {
  73834. return AffineTransform (1.0f, 0, dx,
  73835. 0, 1.0f, dy);
  73836. }
  73837. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  73838. {
  73839. const float cosRad = std::cos (rad);
  73840. const float sinRad = std::sin (rad);
  73841. return followedBy (cosRad, -sinRad, 0,
  73842. sinRad, cosRad, 0);
  73843. }
  73844. const AffineTransform AffineTransform::rotation (const float rad) throw()
  73845. {
  73846. const float cosRad = std::cos (rad);
  73847. const float sinRad = std::sin (rad);
  73848. return AffineTransform (cosRad, -sinRad, 0,
  73849. sinRad, cosRad, 0);
  73850. }
  73851. const AffineTransform AffineTransform::rotated (const float angle,
  73852. const float pivotX,
  73853. const float pivotY) const throw()
  73854. {
  73855. return translated (-pivotX, -pivotY)
  73856. .rotated (angle)
  73857. .translated (pivotX, pivotY);
  73858. }
  73859. const AffineTransform AffineTransform::rotation (const float angle,
  73860. const float pivotX,
  73861. const float pivotY) throw()
  73862. {
  73863. return translation (-pivotX, -pivotY)
  73864. .rotated (angle)
  73865. .translated (pivotX, pivotY);
  73866. }
  73867. const AffineTransform AffineTransform::scaled (const float factorX,
  73868. const float factorY) const throw()
  73869. {
  73870. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02,
  73871. factorY * mat10, factorY * mat11, factorY * mat12);
  73872. }
  73873. const AffineTransform AffineTransform::scale (const float factorX,
  73874. const float factorY) throw()
  73875. {
  73876. return AffineTransform (factorX, 0, 0,
  73877. 0, factorY, 0);
  73878. }
  73879. const AffineTransform AffineTransform::sheared (const float shearX,
  73880. const float shearY) const throw()
  73881. {
  73882. return followedBy (1.0f, shearX, 0,
  73883. shearY, 1.0f, 0);
  73884. }
  73885. const AffineTransform AffineTransform::inverted() const throw()
  73886. {
  73887. double determinant = (mat00 * mat11 - mat10 * mat01);
  73888. if (determinant != 0.0)
  73889. {
  73890. determinant = 1.0 / determinant;
  73891. const float dst00 = (float) (mat11 * determinant);
  73892. const float dst10 = (float) (-mat10 * determinant);
  73893. const float dst01 = (float) (-mat01 * determinant);
  73894. const float dst11 = (float) (mat00 * determinant);
  73895. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  73896. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  73897. }
  73898. else
  73899. {
  73900. // singularity..
  73901. return *this;
  73902. }
  73903. }
  73904. bool AffineTransform::isSingularity() const throw()
  73905. {
  73906. return (mat00 * mat11 - mat10 * mat01) == 0.0;
  73907. }
  73908. const AffineTransform AffineTransform::fromTargetPoints (const float x00, const float y00,
  73909. const float x10, const float y10,
  73910. const float x01, const float y01) throw()
  73911. {
  73912. return AffineTransform (x10 - x00, x01 - x00, x00,
  73913. y10 - y00, y01 - y00, y00);
  73914. }
  73915. const AffineTransform AffineTransform::fromTargetPoints (const float sx1, const float sy1, const float tx1, const float ty1,
  73916. const float sx2, const float sy2, const float tx2, const float ty2,
  73917. const float sx3, const float sy3, const float tx3, const float ty3) throw()
  73918. {
  73919. return fromTargetPoints (sx1, sy1, sx2, sy2, sx3, sy3)
  73920. .inverted()
  73921. .followedBy (fromTargetPoints (tx1, ty1, tx2, ty2, tx3, ty3));
  73922. }
  73923. bool AffineTransform::isOnlyTranslation() const throw()
  73924. {
  73925. return (mat01 == 0)
  73926. && (mat10 == 0)
  73927. && (mat00 == 1.0f)
  73928. && (mat11 == 1.0f);
  73929. }
  73930. END_JUCE_NAMESPACE
  73931. /*** End of inlined file: juce_AffineTransform.cpp ***/
  73932. /*** Start of inlined file: juce_BorderSize.cpp ***/
  73933. BEGIN_JUCE_NAMESPACE
  73934. BorderSize::BorderSize() throw()
  73935. : top (0),
  73936. left (0),
  73937. bottom (0),
  73938. right (0)
  73939. {
  73940. }
  73941. BorderSize::BorderSize (const BorderSize& other) throw()
  73942. : top (other.top),
  73943. left (other.left),
  73944. bottom (other.bottom),
  73945. right (other.right)
  73946. {
  73947. }
  73948. BorderSize::BorderSize (const int topGap,
  73949. const int leftGap,
  73950. const int bottomGap,
  73951. const int rightGap) throw()
  73952. : top (topGap),
  73953. left (leftGap),
  73954. bottom (bottomGap),
  73955. right (rightGap)
  73956. {
  73957. }
  73958. BorderSize::BorderSize (const int allGaps) throw()
  73959. : top (allGaps),
  73960. left (allGaps),
  73961. bottom (allGaps),
  73962. right (allGaps)
  73963. {
  73964. }
  73965. BorderSize::~BorderSize() throw()
  73966. {
  73967. }
  73968. void BorderSize::setTop (const int newTopGap) throw()
  73969. {
  73970. top = newTopGap;
  73971. }
  73972. void BorderSize::setLeft (const int newLeftGap) throw()
  73973. {
  73974. left = newLeftGap;
  73975. }
  73976. void BorderSize::setBottom (const int newBottomGap) throw()
  73977. {
  73978. bottom = newBottomGap;
  73979. }
  73980. void BorderSize::setRight (const int newRightGap) throw()
  73981. {
  73982. right = newRightGap;
  73983. }
  73984. const Rectangle<int> BorderSize::subtractedFrom (const Rectangle<int>& r) const throw()
  73985. {
  73986. return Rectangle<int> (r.getX() + left,
  73987. r.getY() + top,
  73988. r.getWidth() - (left + right),
  73989. r.getHeight() - (top + bottom));
  73990. }
  73991. void BorderSize::subtractFrom (Rectangle<int>& r) const throw()
  73992. {
  73993. r.setBounds (r.getX() + left,
  73994. r.getY() + top,
  73995. r.getWidth() - (left + right),
  73996. r.getHeight() - (top + bottom));
  73997. }
  73998. const Rectangle<int> BorderSize::addedTo (const Rectangle<int>& r) const throw()
  73999. {
  74000. return Rectangle<int> (r.getX() - left,
  74001. r.getY() - top,
  74002. r.getWidth() + (left + right),
  74003. r.getHeight() + (top + bottom));
  74004. }
  74005. void BorderSize::addTo (Rectangle<int>& r) const throw()
  74006. {
  74007. r.setBounds (r.getX() - left,
  74008. r.getY() - top,
  74009. r.getWidth() + (left + right),
  74010. r.getHeight() + (top + bottom));
  74011. }
  74012. bool BorderSize::operator== (const BorderSize& other) const throw()
  74013. {
  74014. return top == other.top
  74015. && left == other.left
  74016. && bottom == other.bottom
  74017. && right == other.right;
  74018. }
  74019. bool BorderSize::operator!= (const BorderSize& other) const throw()
  74020. {
  74021. return ! operator== (other);
  74022. }
  74023. END_JUCE_NAMESPACE
  74024. /*** End of inlined file: juce_BorderSize.cpp ***/
  74025. /*** Start of inlined file: juce_Path.cpp ***/
  74026. BEGIN_JUCE_NAMESPACE
  74027. // tests that some co-ords aren't NaNs
  74028. #define CHECK_COORDS_ARE_VALID(x, y) \
  74029. jassert (x == x && y == y);
  74030. namespace PathHelpers
  74031. {
  74032. static const float ellipseAngularIncrement = 0.05f;
  74033. static const String nextToken (const juce_wchar*& t)
  74034. {
  74035. while (CharacterFunctions::isWhitespace (*t))
  74036. ++t;
  74037. const juce_wchar* const start = t;
  74038. while (*t != 0 && ! CharacterFunctions::isWhitespace (*t))
  74039. ++t;
  74040. return String (start, (int) (t - start));
  74041. }
  74042. }
  74043. const float Path::lineMarker = 100001.0f;
  74044. const float Path::moveMarker = 100002.0f;
  74045. const float Path::quadMarker = 100003.0f;
  74046. const float Path::cubicMarker = 100004.0f;
  74047. const float Path::closeSubPathMarker = 100005.0f;
  74048. Path::Path()
  74049. : numElements (0),
  74050. pathXMin (0),
  74051. pathXMax (0),
  74052. pathYMin (0),
  74053. pathYMax (0),
  74054. useNonZeroWinding (true)
  74055. {
  74056. }
  74057. Path::~Path()
  74058. {
  74059. }
  74060. Path::Path (const Path& other)
  74061. : numElements (other.numElements),
  74062. pathXMin (other.pathXMin),
  74063. pathXMax (other.pathXMax),
  74064. pathYMin (other.pathYMin),
  74065. pathYMax (other.pathYMax),
  74066. useNonZeroWinding (other.useNonZeroWinding)
  74067. {
  74068. if (numElements > 0)
  74069. {
  74070. data.setAllocatedSize ((int) numElements);
  74071. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  74072. }
  74073. }
  74074. Path& Path::operator= (const Path& other)
  74075. {
  74076. if (this != &other)
  74077. {
  74078. data.ensureAllocatedSize ((int) other.numElements);
  74079. numElements = other.numElements;
  74080. pathXMin = other.pathXMin;
  74081. pathXMax = other.pathXMax;
  74082. pathYMin = other.pathYMin;
  74083. pathYMax = other.pathYMax;
  74084. useNonZeroWinding = other.useNonZeroWinding;
  74085. if (numElements > 0)
  74086. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  74087. }
  74088. return *this;
  74089. }
  74090. bool Path::operator== (const Path& other) const throw()
  74091. {
  74092. return ! operator!= (other);
  74093. }
  74094. bool Path::operator!= (const Path& other) const throw()
  74095. {
  74096. if (numElements != other.numElements || useNonZeroWinding != other.useNonZeroWinding)
  74097. return true;
  74098. for (size_t i = 0; i < numElements; ++i)
  74099. if (data.elements[i] != other.data.elements[i])
  74100. return true;
  74101. return false;
  74102. }
  74103. void Path::clear() throw()
  74104. {
  74105. numElements = 0;
  74106. pathXMin = 0;
  74107. pathYMin = 0;
  74108. pathYMax = 0;
  74109. pathXMax = 0;
  74110. }
  74111. void Path::swapWithPath (Path& other) throw()
  74112. {
  74113. data.swapWith (other.data);
  74114. swapVariables <size_t> (numElements, other.numElements);
  74115. swapVariables <float> (pathXMin, other.pathXMin);
  74116. swapVariables <float> (pathXMax, other.pathXMax);
  74117. swapVariables <float> (pathYMin, other.pathYMin);
  74118. swapVariables <float> (pathYMax, other.pathYMax);
  74119. swapVariables <bool> (useNonZeroWinding, other.useNonZeroWinding);
  74120. }
  74121. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  74122. {
  74123. useNonZeroWinding = isNonZero;
  74124. }
  74125. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  74126. const bool preserveProportions) throw()
  74127. {
  74128. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  74129. }
  74130. bool Path::isEmpty() const throw()
  74131. {
  74132. size_t i = 0;
  74133. while (i < numElements)
  74134. {
  74135. const float type = data.elements [i++];
  74136. if (type == moveMarker)
  74137. {
  74138. i += 2;
  74139. }
  74140. else if (type == lineMarker
  74141. || type == quadMarker
  74142. || type == cubicMarker)
  74143. {
  74144. return false;
  74145. }
  74146. }
  74147. return true;
  74148. }
  74149. const Rectangle<float> Path::getBounds() const throw()
  74150. {
  74151. return Rectangle<float> (pathXMin, pathYMin,
  74152. pathXMax - pathXMin,
  74153. pathYMax - pathYMin);
  74154. }
  74155. const Rectangle<float> Path::getBoundsTransformed (const AffineTransform& transform) const throw()
  74156. {
  74157. return getBounds().transformed (transform);
  74158. }
  74159. void Path::startNewSubPath (const float x, const float y)
  74160. {
  74161. CHECK_COORDS_ARE_VALID (x, y);
  74162. if (numElements == 0)
  74163. {
  74164. pathXMin = pathXMax = x;
  74165. pathYMin = pathYMax = y;
  74166. }
  74167. else
  74168. {
  74169. pathXMin = jmin (pathXMin, x);
  74170. pathXMax = jmax (pathXMax, x);
  74171. pathYMin = jmin (pathYMin, y);
  74172. pathYMax = jmax (pathYMax, y);
  74173. }
  74174. data.ensureAllocatedSize ((int) numElements + 3);
  74175. data.elements [numElements++] = moveMarker;
  74176. data.elements [numElements++] = x;
  74177. data.elements [numElements++] = y;
  74178. }
  74179. void Path::startNewSubPath (const Point<float>& start)
  74180. {
  74181. startNewSubPath (start.getX(), start.getY());
  74182. }
  74183. void Path::lineTo (const float x, const float y)
  74184. {
  74185. CHECK_COORDS_ARE_VALID (x, y);
  74186. if (numElements == 0)
  74187. startNewSubPath (0, 0);
  74188. data.ensureAllocatedSize ((int) numElements + 3);
  74189. data.elements [numElements++] = lineMarker;
  74190. data.elements [numElements++] = x;
  74191. data.elements [numElements++] = y;
  74192. pathXMin = jmin (pathXMin, x);
  74193. pathXMax = jmax (pathXMax, x);
  74194. pathYMin = jmin (pathYMin, y);
  74195. pathYMax = jmax (pathYMax, y);
  74196. }
  74197. void Path::lineTo (const Point<float>& end)
  74198. {
  74199. lineTo (end.getX(), end.getY());
  74200. }
  74201. void Path::quadraticTo (const float x1, const float y1,
  74202. const float x2, const float y2)
  74203. {
  74204. CHECK_COORDS_ARE_VALID (x1, y1);
  74205. CHECK_COORDS_ARE_VALID (x2, y2);
  74206. if (numElements == 0)
  74207. startNewSubPath (0, 0);
  74208. data.ensureAllocatedSize ((int) numElements + 5);
  74209. data.elements [numElements++] = quadMarker;
  74210. data.elements [numElements++] = x1;
  74211. data.elements [numElements++] = y1;
  74212. data.elements [numElements++] = x2;
  74213. data.elements [numElements++] = y2;
  74214. pathXMin = jmin (pathXMin, x1, x2);
  74215. pathXMax = jmax (pathXMax, x1, x2);
  74216. pathYMin = jmin (pathYMin, y1, y2);
  74217. pathYMax = jmax (pathYMax, y1, y2);
  74218. }
  74219. void Path::quadraticTo (const Point<float>& controlPoint,
  74220. const Point<float>& endPoint)
  74221. {
  74222. quadraticTo (controlPoint.getX(), controlPoint.getY(),
  74223. endPoint.getX(), endPoint.getY());
  74224. }
  74225. void Path::cubicTo (const float x1, const float y1,
  74226. const float x2, const float y2,
  74227. const float x3, const float y3)
  74228. {
  74229. CHECK_COORDS_ARE_VALID (x1, y1);
  74230. CHECK_COORDS_ARE_VALID (x2, y2);
  74231. CHECK_COORDS_ARE_VALID (x3, y3);
  74232. if (numElements == 0)
  74233. startNewSubPath (0, 0);
  74234. data.ensureAllocatedSize ((int) numElements + 7);
  74235. data.elements [numElements++] = cubicMarker;
  74236. data.elements [numElements++] = x1;
  74237. data.elements [numElements++] = y1;
  74238. data.elements [numElements++] = x2;
  74239. data.elements [numElements++] = y2;
  74240. data.elements [numElements++] = x3;
  74241. data.elements [numElements++] = y3;
  74242. pathXMin = jmin (pathXMin, x1, x2, x3);
  74243. pathXMax = jmax (pathXMax, x1, x2, x3);
  74244. pathYMin = jmin (pathYMin, y1, y2, y3);
  74245. pathYMax = jmax (pathYMax, y1, y2, y3);
  74246. }
  74247. void Path::cubicTo (const Point<float>& controlPoint1,
  74248. const Point<float>& controlPoint2,
  74249. const Point<float>& endPoint)
  74250. {
  74251. cubicTo (controlPoint1.getX(), controlPoint1.getY(),
  74252. controlPoint2.getX(), controlPoint2.getY(),
  74253. endPoint.getX(), endPoint.getY());
  74254. }
  74255. void Path::closeSubPath()
  74256. {
  74257. if (numElements > 0
  74258. && data.elements [numElements - 1] != closeSubPathMarker)
  74259. {
  74260. data.ensureAllocatedSize ((int) numElements + 1);
  74261. data.elements [numElements++] = closeSubPathMarker;
  74262. }
  74263. }
  74264. const Point<float> Path::getCurrentPosition() const
  74265. {
  74266. size_t i = numElements - 1;
  74267. if (i > 0 && data.elements[i] == closeSubPathMarker)
  74268. {
  74269. while (i >= 0)
  74270. {
  74271. if (data.elements[i] == moveMarker)
  74272. {
  74273. i += 2;
  74274. break;
  74275. }
  74276. --i;
  74277. }
  74278. }
  74279. if (i > 0)
  74280. return Point<float> (data.elements [i - 1], data.elements [i]);
  74281. return Point<float>();
  74282. }
  74283. void Path::addRectangle (const float x, const float y,
  74284. const float w, const float h)
  74285. {
  74286. float x1 = x, y1 = y, x2 = x + w, y2 = y + h;
  74287. if (w < 0)
  74288. swapVariables (x1, x2);
  74289. if (h < 0)
  74290. swapVariables (y1, y2);
  74291. data.ensureAllocatedSize ((int) numElements + 13);
  74292. if (numElements == 0)
  74293. {
  74294. pathXMin = x1;
  74295. pathXMax = x2;
  74296. pathYMin = y1;
  74297. pathYMax = y2;
  74298. }
  74299. else
  74300. {
  74301. pathXMin = jmin (pathXMin, x1);
  74302. pathXMax = jmax (pathXMax, x2);
  74303. pathYMin = jmin (pathYMin, y1);
  74304. pathYMax = jmax (pathYMax, y2);
  74305. }
  74306. data.elements [numElements++] = moveMarker;
  74307. data.elements [numElements++] = x1;
  74308. data.elements [numElements++] = y2;
  74309. data.elements [numElements++] = lineMarker;
  74310. data.elements [numElements++] = x1;
  74311. data.elements [numElements++] = y1;
  74312. data.elements [numElements++] = lineMarker;
  74313. data.elements [numElements++] = x2;
  74314. data.elements [numElements++] = y1;
  74315. data.elements [numElements++] = lineMarker;
  74316. data.elements [numElements++] = x2;
  74317. data.elements [numElements++] = y2;
  74318. data.elements [numElements++] = closeSubPathMarker;
  74319. }
  74320. void Path::addRoundedRectangle (const float x, const float y,
  74321. const float w, const float h,
  74322. float csx,
  74323. float csy)
  74324. {
  74325. csx = jmin (csx, w * 0.5f);
  74326. csy = jmin (csy, h * 0.5f);
  74327. const float cs45x = csx * 0.45f;
  74328. const float cs45y = csy * 0.45f;
  74329. const float x2 = x + w;
  74330. const float y2 = y + h;
  74331. startNewSubPath (x + csx, y);
  74332. lineTo (x2 - csx, y);
  74333. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  74334. lineTo (x2, y2 - csy);
  74335. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  74336. lineTo (x + csx, y2);
  74337. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  74338. lineTo (x, y + csy);
  74339. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  74340. closeSubPath();
  74341. }
  74342. void Path::addRoundedRectangle (const float x, const float y,
  74343. const float w, const float h,
  74344. float cs)
  74345. {
  74346. addRoundedRectangle (x, y, w, h, cs, cs);
  74347. }
  74348. void Path::addTriangle (const float x1, const float y1,
  74349. const float x2, const float y2,
  74350. const float x3, const float y3)
  74351. {
  74352. startNewSubPath (x1, y1);
  74353. lineTo (x2, y2);
  74354. lineTo (x3, y3);
  74355. closeSubPath();
  74356. }
  74357. void Path::addQuadrilateral (const float x1, const float y1,
  74358. const float x2, const float y2,
  74359. const float x3, const float y3,
  74360. const float x4, const float y4)
  74361. {
  74362. startNewSubPath (x1, y1);
  74363. lineTo (x2, y2);
  74364. lineTo (x3, y3);
  74365. lineTo (x4, y4);
  74366. closeSubPath();
  74367. }
  74368. void Path::addEllipse (const float x, const float y,
  74369. const float w, const float h)
  74370. {
  74371. const float hw = w * 0.5f;
  74372. const float hw55 = hw * 0.55f;
  74373. const float hh = h * 0.5f;
  74374. const float hh45 = hh * 0.55f;
  74375. const float cx = x + hw;
  74376. const float cy = y + hh;
  74377. startNewSubPath (cx, cy - hh);
  74378. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh45, cx + hw, cy);
  74379. cubicTo (cx + hw, cy + hh45, cx + hw55, cy + hh, cx, cy + hh);
  74380. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh45, cx - hw, cy);
  74381. cubicTo (cx - hw, cy - hh45, cx - hw55, cy - hh, cx, cy - hh);
  74382. closeSubPath();
  74383. }
  74384. void Path::addArc (const float x, const float y,
  74385. const float w, const float h,
  74386. const float fromRadians,
  74387. const float toRadians,
  74388. const bool startAsNewSubPath)
  74389. {
  74390. const float radiusX = w / 2.0f;
  74391. const float radiusY = h / 2.0f;
  74392. addCentredArc (x + radiusX,
  74393. y + radiusY,
  74394. radiusX, radiusY,
  74395. 0.0f,
  74396. fromRadians, toRadians,
  74397. startAsNewSubPath);
  74398. }
  74399. void Path::addCentredArc (const float centreX, const float centreY,
  74400. const float radiusX, const float radiusY,
  74401. const float rotationOfEllipse,
  74402. const float fromRadians,
  74403. const float toRadians,
  74404. const bool startAsNewSubPath)
  74405. {
  74406. if (radiusX > 0.0f && radiusY > 0.0f)
  74407. {
  74408. const Point<float> centre (centreX, centreY);
  74409. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  74410. float angle = fromRadians;
  74411. if (startAsNewSubPath)
  74412. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74413. if (fromRadians < toRadians)
  74414. {
  74415. if (startAsNewSubPath)
  74416. angle += PathHelpers::ellipseAngularIncrement;
  74417. while (angle < toRadians)
  74418. {
  74419. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74420. angle += PathHelpers::ellipseAngularIncrement;
  74421. }
  74422. }
  74423. else
  74424. {
  74425. if (startAsNewSubPath)
  74426. angle -= PathHelpers::ellipseAngularIncrement;
  74427. while (angle > toRadians)
  74428. {
  74429. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74430. angle -= PathHelpers::ellipseAngularIncrement;
  74431. }
  74432. }
  74433. lineTo (centre.getPointOnCircumference (radiusX, radiusY, toRadians).transformedBy (rotation));
  74434. }
  74435. }
  74436. void Path::addPieSegment (const float x, const float y,
  74437. const float width, const float height,
  74438. const float fromRadians,
  74439. const float toRadians,
  74440. const float innerCircleProportionalSize)
  74441. {
  74442. float radiusX = width * 0.5f;
  74443. float radiusY = height * 0.5f;
  74444. const Point<float> centre (x + radiusX, y + radiusY);
  74445. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, fromRadians));
  74446. addArc (x, y, width, height, fromRadians, toRadians);
  74447. if (std::abs (fromRadians - toRadians) > float_Pi * 1.999f)
  74448. {
  74449. closeSubPath();
  74450. if (innerCircleProportionalSize > 0)
  74451. {
  74452. radiusX *= innerCircleProportionalSize;
  74453. radiusY *= innerCircleProportionalSize;
  74454. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, toRadians));
  74455. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74456. }
  74457. }
  74458. else
  74459. {
  74460. if (innerCircleProportionalSize > 0)
  74461. {
  74462. radiusX *= innerCircleProportionalSize;
  74463. radiusY *= innerCircleProportionalSize;
  74464. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74465. }
  74466. else
  74467. {
  74468. lineTo (centre);
  74469. }
  74470. }
  74471. closeSubPath();
  74472. }
  74473. void Path::addLineSegment (const Line<float>& line, float lineThickness)
  74474. {
  74475. const Line<float> reversed (line.reversed());
  74476. lineThickness *= 0.5f;
  74477. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74478. lineTo (line.getPointAlongLine (0, -lineThickness));
  74479. lineTo (reversed.getPointAlongLine (0, lineThickness));
  74480. lineTo (reversed.getPointAlongLine (0, -lineThickness));
  74481. closeSubPath();
  74482. }
  74483. void Path::addArrow (const Line<float>& line, float lineThickness,
  74484. float arrowheadWidth, float arrowheadLength)
  74485. {
  74486. const Line<float> reversed (line.reversed());
  74487. lineThickness *= 0.5f;
  74488. arrowheadWidth *= 0.5f;
  74489. arrowheadLength = jmin (arrowheadLength, 0.8f * line.getLength());
  74490. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74491. lineTo (line.getPointAlongLine (0, -lineThickness));
  74492. lineTo (reversed.getPointAlongLine (arrowheadLength, lineThickness));
  74493. lineTo (reversed.getPointAlongLine (arrowheadLength, arrowheadWidth));
  74494. lineTo (line.getEnd());
  74495. lineTo (reversed.getPointAlongLine (arrowheadLength, -arrowheadWidth));
  74496. lineTo (reversed.getPointAlongLine (arrowheadLength, -lineThickness));
  74497. closeSubPath();
  74498. }
  74499. void Path::addPolygon (const Point<float>& centre, const int numberOfSides,
  74500. const float radius, const float startAngle)
  74501. {
  74502. jassert (numberOfSides > 1); // this would be silly.
  74503. if (numberOfSides > 1)
  74504. {
  74505. const float angleBetweenPoints = float_Pi * 2.0f / numberOfSides;
  74506. for (int i = 0; i < numberOfSides; ++i)
  74507. {
  74508. const float angle = startAngle + i * angleBetweenPoints;
  74509. const Point<float> p (centre.getPointOnCircumference (radius, angle));
  74510. if (i == 0)
  74511. startNewSubPath (p);
  74512. else
  74513. lineTo (p);
  74514. }
  74515. closeSubPath();
  74516. }
  74517. }
  74518. void Path::addStar (const Point<float>& centre, const int numberOfPoints,
  74519. const float innerRadius, const float outerRadius, const float startAngle)
  74520. {
  74521. jassert (numberOfPoints > 1); // this would be silly.
  74522. if (numberOfPoints > 1)
  74523. {
  74524. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  74525. for (int i = 0; i < numberOfPoints; ++i)
  74526. {
  74527. const float angle = startAngle + i * angleBetweenPoints;
  74528. const Point<float> p (centre.getPointOnCircumference (outerRadius, angle));
  74529. if (i == 0)
  74530. startNewSubPath (p);
  74531. else
  74532. lineTo (p);
  74533. lineTo (centre.getPointOnCircumference (innerRadius, angle + angleBetweenPoints * 0.5f));
  74534. }
  74535. closeSubPath();
  74536. }
  74537. }
  74538. void Path::addBubble (float x, float y,
  74539. float w, float h,
  74540. float cs,
  74541. float tipX,
  74542. float tipY,
  74543. int whichSide,
  74544. float arrowPos,
  74545. float arrowWidth)
  74546. {
  74547. if (w > 1.0f && h > 1.0f)
  74548. {
  74549. cs = jmin (cs, w * 0.5f, h * 0.5f);
  74550. const float cs2 = 2.0f * cs;
  74551. startNewSubPath (x + cs, y);
  74552. if (whichSide == 0)
  74553. {
  74554. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74555. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74556. lineTo (arrowX1, y);
  74557. lineTo (tipX, tipY);
  74558. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  74559. }
  74560. lineTo (x + w - cs, y);
  74561. if (cs > 0.0f)
  74562. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  74563. if (whichSide == 3)
  74564. {
  74565. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74566. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74567. lineTo (x + w, arrowY1);
  74568. lineTo (tipX, tipY);
  74569. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  74570. }
  74571. lineTo (x + w, y + h - cs);
  74572. if (cs > 0.0f)
  74573. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  74574. if (whichSide == 2)
  74575. {
  74576. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74577. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74578. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  74579. lineTo (tipX, tipY);
  74580. lineTo (arrowX1, y + h);
  74581. }
  74582. lineTo (x + cs, y + h);
  74583. if (cs > 0.0f)
  74584. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  74585. if (whichSide == 1)
  74586. {
  74587. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74588. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74589. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  74590. lineTo (tipX, tipY);
  74591. lineTo (x, arrowY1);
  74592. }
  74593. lineTo (x, y + cs);
  74594. if (cs > 0.0f)
  74595. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - PathHelpers::ellipseAngularIncrement);
  74596. closeSubPath();
  74597. }
  74598. }
  74599. void Path::addPath (const Path& other)
  74600. {
  74601. size_t i = 0;
  74602. while (i < other.numElements)
  74603. {
  74604. const float type = other.data.elements [i++];
  74605. if (type == moveMarker)
  74606. {
  74607. startNewSubPath (other.data.elements [i],
  74608. other.data.elements [i + 1]);
  74609. i += 2;
  74610. }
  74611. else if (type == lineMarker)
  74612. {
  74613. lineTo (other.data.elements [i],
  74614. other.data.elements [i + 1]);
  74615. i += 2;
  74616. }
  74617. else if (type == quadMarker)
  74618. {
  74619. quadraticTo (other.data.elements [i],
  74620. other.data.elements [i + 1],
  74621. other.data.elements [i + 2],
  74622. other.data.elements [i + 3]);
  74623. i += 4;
  74624. }
  74625. else if (type == cubicMarker)
  74626. {
  74627. cubicTo (other.data.elements [i],
  74628. other.data.elements [i + 1],
  74629. other.data.elements [i + 2],
  74630. other.data.elements [i + 3],
  74631. other.data.elements [i + 4],
  74632. other.data.elements [i + 5]);
  74633. i += 6;
  74634. }
  74635. else if (type == closeSubPathMarker)
  74636. {
  74637. closeSubPath();
  74638. }
  74639. else
  74640. {
  74641. // something's gone wrong with the element list!
  74642. jassertfalse;
  74643. }
  74644. }
  74645. }
  74646. void Path::addPath (const Path& other,
  74647. const AffineTransform& transformToApply)
  74648. {
  74649. size_t i = 0;
  74650. while (i < other.numElements)
  74651. {
  74652. const float type = other.data.elements [i++];
  74653. if (type == closeSubPathMarker)
  74654. {
  74655. closeSubPath();
  74656. }
  74657. else
  74658. {
  74659. float x = other.data.elements [i++];
  74660. float y = other.data.elements [i++];
  74661. transformToApply.transformPoint (x, y);
  74662. if (type == moveMarker)
  74663. {
  74664. startNewSubPath (x, y);
  74665. }
  74666. else if (type == lineMarker)
  74667. {
  74668. lineTo (x, y);
  74669. }
  74670. else if (type == quadMarker)
  74671. {
  74672. float x2 = other.data.elements [i++];
  74673. float y2 = other.data.elements [i++];
  74674. transformToApply.transformPoint (x2, y2);
  74675. quadraticTo (x, y, x2, y2);
  74676. }
  74677. else if (type == cubicMarker)
  74678. {
  74679. float x2 = other.data.elements [i++];
  74680. float y2 = other.data.elements [i++];
  74681. float x3 = other.data.elements [i++];
  74682. float y3 = other.data.elements [i++];
  74683. transformToApply.transformPoints (x2, y2, x3, y3);
  74684. cubicTo (x, y, x2, y2, x3, y3);
  74685. }
  74686. else
  74687. {
  74688. // something's gone wrong with the element list!
  74689. jassertfalse;
  74690. }
  74691. }
  74692. }
  74693. }
  74694. void Path::applyTransform (const AffineTransform& transform) throw()
  74695. {
  74696. size_t i = 0;
  74697. pathYMin = pathXMin = 0;
  74698. pathYMax = pathXMax = 0;
  74699. bool setMaxMin = false;
  74700. while (i < numElements)
  74701. {
  74702. const float type = data.elements [i++];
  74703. if (type == moveMarker)
  74704. {
  74705. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74706. if (setMaxMin)
  74707. {
  74708. pathXMin = jmin (pathXMin, data.elements [i]);
  74709. pathXMax = jmax (pathXMax, data.elements [i]);
  74710. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74711. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74712. }
  74713. else
  74714. {
  74715. pathXMin = pathXMax = data.elements [i];
  74716. pathYMin = pathYMax = data.elements [i + 1];
  74717. setMaxMin = true;
  74718. }
  74719. i += 2;
  74720. }
  74721. else if (type == lineMarker)
  74722. {
  74723. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74724. pathXMin = jmin (pathXMin, data.elements [i]);
  74725. pathXMax = jmax (pathXMax, data.elements [i]);
  74726. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74727. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74728. i += 2;
  74729. }
  74730. else if (type == quadMarker)
  74731. {
  74732. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74733. data.elements [i + 2], data.elements [i + 3]);
  74734. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2]);
  74735. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2]);
  74736. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3]);
  74737. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3]);
  74738. i += 4;
  74739. }
  74740. else if (type == cubicMarker)
  74741. {
  74742. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74743. data.elements [i + 2], data.elements [i + 3],
  74744. data.elements [i + 4], data.elements [i + 5]);
  74745. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74746. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74747. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74748. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74749. i += 6;
  74750. }
  74751. }
  74752. }
  74753. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  74754. const float w, const float h,
  74755. const bool preserveProportions,
  74756. const Justification& justification) const
  74757. {
  74758. Rectangle<float> bounds (getBounds());
  74759. if (preserveProportions)
  74760. {
  74761. if (w <= 0 || h <= 0 || bounds.isEmpty())
  74762. return AffineTransform::identity;
  74763. float newW, newH;
  74764. const float srcRatio = bounds.getHeight() / bounds.getWidth();
  74765. if (srcRatio > h / w)
  74766. {
  74767. newW = h / srcRatio;
  74768. newH = h;
  74769. }
  74770. else
  74771. {
  74772. newW = w;
  74773. newH = w * srcRatio;
  74774. }
  74775. float newXCentre = x;
  74776. float newYCentre = y;
  74777. if (justification.testFlags (Justification::left))
  74778. newXCentre += newW * 0.5f;
  74779. else if (justification.testFlags (Justification::right))
  74780. newXCentre += w - newW * 0.5f;
  74781. else
  74782. newXCentre += w * 0.5f;
  74783. if (justification.testFlags (Justification::top))
  74784. newYCentre += newH * 0.5f;
  74785. else if (justification.testFlags (Justification::bottom))
  74786. newYCentre += h - newH * 0.5f;
  74787. else
  74788. newYCentre += h * 0.5f;
  74789. return AffineTransform::translation (bounds.getWidth() * -0.5f - bounds.getX(),
  74790. bounds.getHeight() * -0.5f - bounds.getY())
  74791. .scaled (newW / bounds.getWidth(), newH / bounds.getHeight())
  74792. .translated (newXCentre, newYCentre);
  74793. }
  74794. else
  74795. {
  74796. return AffineTransform::translation (-bounds.getX(), -bounds.getY())
  74797. .scaled (w / bounds.getWidth(), h / bounds.getHeight())
  74798. .translated (x, y);
  74799. }
  74800. }
  74801. bool Path::contains (const float x, const float y, const float tolerence) const
  74802. {
  74803. if (x <= pathXMin || x >= pathXMax
  74804. || y <= pathYMin || y >= pathYMax)
  74805. return false;
  74806. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  74807. int positiveCrossings = 0;
  74808. int negativeCrossings = 0;
  74809. while (i.next())
  74810. {
  74811. if ((i.y1 <= y && i.y2 > y) || (i.y2 <= y && i.y1 > y))
  74812. {
  74813. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  74814. if (intersectX <= x)
  74815. {
  74816. if (i.y1 < i.y2)
  74817. ++positiveCrossings;
  74818. else
  74819. ++negativeCrossings;
  74820. }
  74821. }
  74822. }
  74823. return useNonZeroWinding ? (negativeCrossings != positiveCrossings)
  74824. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  74825. }
  74826. bool Path::contains (const Point<float>& point, const float tolerence) const
  74827. {
  74828. return contains (point.getX(), point.getY(), tolerence);
  74829. }
  74830. bool Path::intersectsLine (const Line<float>& line, const float tolerence)
  74831. {
  74832. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  74833. Point<float> intersection;
  74834. while (i.next())
  74835. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  74836. return true;
  74837. return false;
  74838. }
  74839. const Line<float> Path::getClippedLine (const Line<float>& line, const bool keepSectionOutsidePath) const
  74840. {
  74841. Line<float> result (line);
  74842. const bool startInside = contains (line.getStart());
  74843. const bool endInside = contains (line.getEnd());
  74844. if (startInside == endInside)
  74845. {
  74846. if (keepSectionOutsidePath == startInside)
  74847. result = Line<float>();
  74848. }
  74849. else
  74850. {
  74851. PathFlatteningIterator i (*this, AffineTransform::identity);
  74852. Point<float> intersection;
  74853. while (i.next())
  74854. {
  74855. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  74856. {
  74857. if ((startInside && keepSectionOutsidePath) || (endInside && ! keepSectionOutsidePath))
  74858. result.setStart (intersection);
  74859. else
  74860. result.setEnd (intersection);
  74861. }
  74862. }
  74863. }
  74864. return result;
  74865. }
  74866. float Path::getLength (const AffineTransform& transform) const
  74867. {
  74868. float length = 0;
  74869. PathFlatteningIterator i (*this, transform);
  74870. while (i.next())
  74871. length += Line<float> (i.x1, i.y1, i.x2, i.y2).getLength();
  74872. return length;
  74873. }
  74874. const Point<float> Path::getPointAlongPath (float distanceFromStart, const AffineTransform& transform) const
  74875. {
  74876. PathFlatteningIterator i (*this, transform);
  74877. while (i.next())
  74878. {
  74879. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  74880. const float lineLength = line.getLength();
  74881. if (distanceFromStart <= lineLength)
  74882. return line.getPointAlongLine (distanceFromStart);
  74883. distanceFromStart -= lineLength;
  74884. }
  74885. return Point<float> (i.x2, i.y2);
  74886. }
  74887. float Path::getNearestPoint (const Point<float>& targetPoint, Point<float>& pointOnPath,
  74888. const AffineTransform& transform) const
  74889. {
  74890. PathFlatteningIterator i (*this, transform);
  74891. float bestPosition = 0, bestDistance = std::numeric_limits<float>::max();
  74892. float length = 0;
  74893. Point<float> pointOnLine;
  74894. while (i.next())
  74895. {
  74896. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  74897. const float distance = line.getDistanceFromPoint (targetPoint, pointOnLine);
  74898. if (distance < bestDistance)
  74899. {
  74900. bestDistance = distance;
  74901. bestPosition = length + pointOnLine.getDistanceFrom (line.getStart());
  74902. pointOnPath = pointOnLine;
  74903. }
  74904. length += line.getLength();
  74905. }
  74906. return bestPosition;
  74907. }
  74908. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const
  74909. {
  74910. if (cornerRadius <= 0.01f)
  74911. return *this;
  74912. size_t indexOfPathStart = 0, indexOfPathStartThis = 0;
  74913. size_t n = 0;
  74914. bool lastWasLine = false, firstWasLine = false;
  74915. Path p;
  74916. while (n < numElements)
  74917. {
  74918. const float type = data.elements [n++];
  74919. if (type == moveMarker)
  74920. {
  74921. indexOfPathStart = p.numElements;
  74922. indexOfPathStartThis = n - 1;
  74923. const float x = data.elements [n++];
  74924. const float y = data.elements [n++];
  74925. p.startNewSubPath (x, y);
  74926. lastWasLine = false;
  74927. firstWasLine = (data.elements [n] == lineMarker);
  74928. }
  74929. else if (type == lineMarker || type == closeSubPathMarker)
  74930. {
  74931. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  74932. if (type == lineMarker)
  74933. {
  74934. endX = data.elements [n++];
  74935. endY = data.elements [n++];
  74936. if (n > 8)
  74937. {
  74938. startX = data.elements [n - 8];
  74939. startY = data.elements [n - 7];
  74940. joinX = data.elements [n - 5];
  74941. joinY = data.elements [n - 4];
  74942. }
  74943. }
  74944. else
  74945. {
  74946. endX = data.elements [indexOfPathStartThis + 1];
  74947. endY = data.elements [indexOfPathStartThis + 2];
  74948. if (n > 6)
  74949. {
  74950. startX = data.elements [n - 6];
  74951. startY = data.elements [n - 5];
  74952. joinX = data.elements [n - 3];
  74953. joinY = data.elements [n - 2];
  74954. }
  74955. }
  74956. if (lastWasLine)
  74957. {
  74958. const double len1 = juce_hypot (startX - joinX,
  74959. startY - joinY);
  74960. if (len1 > 0)
  74961. {
  74962. const double propNeeded = jmin (0.5, cornerRadius / len1);
  74963. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  74964. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  74965. }
  74966. const double len2 = juce_hypot (endX - joinX,
  74967. endY - joinY);
  74968. if (len2 > 0)
  74969. {
  74970. const double propNeeded = jmin (0.5, cornerRadius / len2);
  74971. p.quadraticTo (joinX, joinY,
  74972. (float) (joinX + (endX - joinX) * propNeeded),
  74973. (float) (joinY + (endY - joinY) * propNeeded));
  74974. }
  74975. p.lineTo (endX, endY);
  74976. }
  74977. else if (type == lineMarker)
  74978. {
  74979. p.lineTo (endX, endY);
  74980. lastWasLine = true;
  74981. }
  74982. if (type == closeSubPathMarker)
  74983. {
  74984. if (firstWasLine)
  74985. {
  74986. startX = data.elements [n - 3];
  74987. startY = data.elements [n - 2];
  74988. joinX = endX;
  74989. joinY = endY;
  74990. endX = data.elements [indexOfPathStartThis + 4];
  74991. endY = data.elements [indexOfPathStartThis + 5];
  74992. const double len1 = juce_hypot (startX - joinX,
  74993. startY - joinY);
  74994. if (len1 > 0)
  74995. {
  74996. const double propNeeded = jmin (0.5, cornerRadius / len1);
  74997. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  74998. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  74999. }
  75000. const double len2 = juce_hypot (endX - joinX,
  75001. endY - joinY);
  75002. if (len2 > 0)
  75003. {
  75004. const double propNeeded = jmin (0.5, cornerRadius / len2);
  75005. endX = (float) (joinX + (endX - joinX) * propNeeded);
  75006. endY = (float) (joinY + (endY - joinY) * propNeeded);
  75007. p.quadraticTo (joinX, joinY, endX, endY);
  75008. p.data.elements [indexOfPathStart + 1] = endX;
  75009. p.data.elements [indexOfPathStart + 2] = endY;
  75010. }
  75011. }
  75012. p.closeSubPath();
  75013. }
  75014. }
  75015. else if (type == quadMarker)
  75016. {
  75017. lastWasLine = false;
  75018. const float x1 = data.elements [n++];
  75019. const float y1 = data.elements [n++];
  75020. const float x2 = data.elements [n++];
  75021. const float y2 = data.elements [n++];
  75022. p.quadraticTo (x1, y1, x2, y2);
  75023. }
  75024. else if (type == cubicMarker)
  75025. {
  75026. lastWasLine = false;
  75027. const float x1 = data.elements [n++];
  75028. const float y1 = data.elements [n++];
  75029. const float x2 = data.elements [n++];
  75030. const float y2 = data.elements [n++];
  75031. const float x3 = data.elements [n++];
  75032. const float y3 = data.elements [n++];
  75033. p.cubicTo (x1, y1, x2, y2, x3, y3);
  75034. }
  75035. }
  75036. return p;
  75037. }
  75038. void Path::loadPathFromStream (InputStream& source)
  75039. {
  75040. while (! source.isExhausted())
  75041. {
  75042. switch (source.readByte())
  75043. {
  75044. case 'm':
  75045. {
  75046. const float x = source.readFloat();
  75047. const float y = source.readFloat();
  75048. startNewSubPath (x, y);
  75049. break;
  75050. }
  75051. case 'l':
  75052. {
  75053. const float x = source.readFloat();
  75054. const float y = source.readFloat();
  75055. lineTo (x, y);
  75056. break;
  75057. }
  75058. case 'q':
  75059. {
  75060. const float x1 = source.readFloat();
  75061. const float y1 = source.readFloat();
  75062. const float x2 = source.readFloat();
  75063. const float y2 = source.readFloat();
  75064. quadraticTo (x1, y1, x2, y2);
  75065. break;
  75066. }
  75067. case 'b':
  75068. {
  75069. const float x1 = source.readFloat();
  75070. const float y1 = source.readFloat();
  75071. const float x2 = source.readFloat();
  75072. const float y2 = source.readFloat();
  75073. const float x3 = source.readFloat();
  75074. const float y3 = source.readFloat();
  75075. cubicTo (x1, y1, x2, y2, x3, y3);
  75076. break;
  75077. }
  75078. case 'c':
  75079. closeSubPath();
  75080. break;
  75081. case 'n':
  75082. useNonZeroWinding = true;
  75083. break;
  75084. case 'z':
  75085. useNonZeroWinding = false;
  75086. break;
  75087. case 'e':
  75088. return; // end of path marker
  75089. default:
  75090. jassertfalse; // illegal char in the stream
  75091. break;
  75092. }
  75093. }
  75094. }
  75095. void Path::loadPathFromData (const void* const pathData, const int numberOfBytes)
  75096. {
  75097. MemoryInputStream in (pathData, numberOfBytes, false);
  75098. loadPathFromStream (in);
  75099. }
  75100. void Path::writePathToStream (OutputStream& dest) const
  75101. {
  75102. dest.writeByte (useNonZeroWinding ? 'n' : 'z');
  75103. size_t i = 0;
  75104. while (i < numElements)
  75105. {
  75106. const float type = data.elements [i++];
  75107. if (type == moveMarker)
  75108. {
  75109. dest.writeByte ('m');
  75110. dest.writeFloat (data.elements [i++]);
  75111. dest.writeFloat (data.elements [i++]);
  75112. }
  75113. else if (type == lineMarker)
  75114. {
  75115. dest.writeByte ('l');
  75116. dest.writeFloat (data.elements [i++]);
  75117. dest.writeFloat (data.elements [i++]);
  75118. }
  75119. else if (type == quadMarker)
  75120. {
  75121. dest.writeByte ('q');
  75122. dest.writeFloat (data.elements [i++]);
  75123. dest.writeFloat (data.elements [i++]);
  75124. dest.writeFloat (data.elements [i++]);
  75125. dest.writeFloat (data.elements [i++]);
  75126. }
  75127. else if (type == cubicMarker)
  75128. {
  75129. dest.writeByte ('b');
  75130. dest.writeFloat (data.elements [i++]);
  75131. dest.writeFloat (data.elements [i++]);
  75132. dest.writeFloat (data.elements [i++]);
  75133. dest.writeFloat (data.elements [i++]);
  75134. dest.writeFloat (data.elements [i++]);
  75135. dest.writeFloat (data.elements [i++]);
  75136. }
  75137. else if (type == closeSubPathMarker)
  75138. {
  75139. dest.writeByte ('c');
  75140. }
  75141. }
  75142. dest.writeByte ('e'); // marks the end-of-path
  75143. }
  75144. const String Path::toString() const
  75145. {
  75146. MemoryOutputStream s (2048);
  75147. if (! useNonZeroWinding)
  75148. s << 'a';
  75149. size_t i = 0;
  75150. float lastMarker = 0.0f;
  75151. while (i < numElements)
  75152. {
  75153. const float marker = data.elements [i++];
  75154. char markerChar = 0;
  75155. int numCoords = 0;
  75156. if (marker == moveMarker)
  75157. {
  75158. markerChar = 'm';
  75159. numCoords = 2;
  75160. }
  75161. else if (marker == lineMarker)
  75162. {
  75163. markerChar = 'l';
  75164. numCoords = 2;
  75165. }
  75166. else if (marker == quadMarker)
  75167. {
  75168. markerChar = 'q';
  75169. numCoords = 4;
  75170. }
  75171. else if (marker == cubicMarker)
  75172. {
  75173. markerChar = 'c';
  75174. numCoords = 6;
  75175. }
  75176. else
  75177. {
  75178. jassert (marker == closeSubPathMarker);
  75179. markerChar = 'z';
  75180. }
  75181. if (marker != lastMarker)
  75182. {
  75183. if (s.getDataSize() != 0)
  75184. s << ' ';
  75185. s << markerChar;
  75186. lastMarker = marker;
  75187. }
  75188. while (--numCoords >= 0 && i < numElements)
  75189. {
  75190. String coord (data.elements [i++], 3);
  75191. while (coord.endsWithChar ('0') && coord != "0")
  75192. coord = coord.dropLastCharacters (1);
  75193. if (coord.endsWithChar ('.'))
  75194. coord = coord.dropLastCharacters (1);
  75195. if (s.getDataSize() != 0)
  75196. s << ' ';
  75197. s << coord;
  75198. }
  75199. }
  75200. return s.toUTF8();
  75201. }
  75202. void Path::restoreFromString (const String& stringVersion)
  75203. {
  75204. clear();
  75205. setUsingNonZeroWinding (true);
  75206. const juce_wchar* t = stringVersion;
  75207. juce_wchar marker = 'm';
  75208. int numValues = 2;
  75209. float values [6];
  75210. for (;;)
  75211. {
  75212. const String token (PathHelpers::nextToken (t));
  75213. const juce_wchar firstChar = token[0];
  75214. int startNum = 0;
  75215. if (firstChar == 0)
  75216. break;
  75217. if (firstChar == 'm' || firstChar == 'l')
  75218. {
  75219. marker = firstChar;
  75220. numValues = 2;
  75221. }
  75222. else if (firstChar == 'q')
  75223. {
  75224. marker = firstChar;
  75225. numValues = 4;
  75226. }
  75227. else if (firstChar == 'c')
  75228. {
  75229. marker = firstChar;
  75230. numValues = 6;
  75231. }
  75232. else if (firstChar == 'z')
  75233. {
  75234. marker = firstChar;
  75235. numValues = 0;
  75236. }
  75237. else if (firstChar == 'a')
  75238. {
  75239. setUsingNonZeroWinding (false);
  75240. continue;
  75241. }
  75242. else
  75243. {
  75244. ++startNum;
  75245. values [0] = token.getFloatValue();
  75246. }
  75247. for (int i = startNum; i < numValues; ++i)
  75248. values [i] = PathHelpers::nextToken (t).getFloatValue();
  75249. switch (marker)
  75250. {
  75251. case 'm': startNewSubPath (values[0], values[1]); break;
  75252. case 'l': lineTo (values[0], values[1]); break;
  75253. case 'q': quadraticTo (values[0], values[1], values[2], values[3]); break;
  75254. case 'c': cubicTo (values[0], values[1], values[2], values[3], values[4], values[5]); break;
  75255. case 'z': closeSubPath(); break;
  75256. default: jassertfalse; break; // illegal string format?
  75257. }
  75258. }
  75259. }
  75260. Path::Iterator::Iterator (const Path& path_)
  75261. : path (path_),
  75262. index (0)
  75263. {
  75264. }
  75265. Path::Iterator::~Iterator()
  75266. {
  75267. }
  75268. bool Path::Iterator::next()
  75269. {
  75270. const float* const elements = path.data.elements;
  75271. if (index < path.numElements)
  75272. {
  75273. const float type = elements [index++];
  75274. if (type == moveMarker)
  75275. {
  75276. elementType = startNewSubPath;
  75277. x1 = elements [index++];
  75278. y1 = elements [index++];
  75279. }
  75280. else if (type == lineMarker)
  75281. {
  75282. elementType = lineTo;
  75283. x1 = elements [index++];
  75284. y1 = elements [index++];
  75285. }
  75286. else if (type == quadMarker)
  75287. {
  75288. elementType = quadraticTo;
  75289. x1 = elements [index++];
  75290. y1 = elements [index++];
  75291. x2 = elements [index++];
  75292. y2 = elements [index++];
  75293. }
  75294. else if (type == cubicMarker)
  75295. {
  75296. elementType = cubicTo;
  75297. x1 = elements [index++];
  75298. y1 = elements [index++];
  75299. x2 = elements [index++];
  75300. y2 = elements [index++];
  75301. x3 = elements [index++];
  75302. y3 = elements [index++];
  75303. }
  75304. else if (type == closeSubPathMarker)
  75305. {
  75306. elementType = closePath;
  75307. }
  75308. return true;
  75309. }
  75310. return false;
  75311. }
  75312. END_JUCE_NAMESPACE
  75313. /*** End of inlined file: juce_Path.cpp ***/
  75314. /*** Start of inlined file: juce_PathIterator.cpp ***/
  75315. BEGIN_JUCE_NAMESPACE
  75316. #if JUCE_MSVC && JUCE_DEBUG
  75317. #pragma optimize ("t", on)
  75318. #endif
  75319. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  75320. const AffineTransform& transform_,
  75321. float tolerence_)
  75322. : x2 (0),
  75323. y2 (0),
  75324. closesSubPath (false),
  75325. subPathIndex (-1),
  75326. path (path_),
  75327. transform (transform_),
  75328. points (path_.data.elements),
  75329. tolerence (tolerence_ * tolerence_),
  75330. subPathCloseX (0),
  75331. subPathCloseY (0),
  75332. isIdentityTransform (transform_.isIdentity()),
  75333. stackBase (32),
  75334. index (0),
  75335. stackSize (32)
  75336. {
  75337. stackPos = stackBase;
  75338. }
  75339. PathFlatteningIterator::~PathFlatteningIterator()
  75340. {
  75341. }
  75342. bool PathFlatteningIterator::next()
  75343. {
  75344. x1 = x2;
  75345. y1 = y2;
  75346. float x3 = 0;
  75347. float y3 = 0;
  75348. float x4 = 0;
  75349. float y4 = 0;
  75350. float type;
  75351. for (;;)
  75352. {
  75353. if (stackPos == stackBase)
  75354. {
  75355. if (index >= path.numElements)
  75356. {
  75357. return false;
  75358. }
  75359. else
  75360. {
  75361. type = points [index++];
  75362. if (type != Path::closeSubPathMarker)
  75363. {
  75364. x2 = points [index++];
  75365. y2 = points [index++];
  75366. if (type == Path::quadMarker)
  75367. {
  75368. x3 = points [index++];
  75369. y3 = points [index++];
  75370. if (! isIdentityTransform)
  75371. transform.transformPoints (x2, y2, x3, y3);
  75372. }
  75373. else if (type == Path::cubicMarker)
  75374. {
  75375. x3 = points [index++];
  75376. y3 = points [index++];
  75377. x4 = points [index++];
  75378. y4 = points [index++];
  75379. if (! isIdentityTransform)
  75380. transform.transformPoints (x2, y2, x3, y3, x4, y4);
  75381. }
  75382. else
  75383. {
  75384. if (! isIdentityTransform)
  75385. transform.transformPoint (x2, y2);
  75386. }
  75387. }
  75388. }
  75389. }
  75390. else
  75391. {
  75392. type = *--stackPos;
  75393. if (type != Path::closeSubPathMarker)
  75394. {
  75395. x2 = *--stackPos;
  75396. y2 = *--stackPos;
  75397. if (type == Path::quadMarker)
  75398. {
  75399. x3 = *--stackPos;
  75400. y3 = *--stackPos;
  75401. }
  75402. else if (type == Path::cubicMarker)
  75403. {
  75404. x3 = *--stackPos;
  75405. y3 = *--stackPos;
  75406. x4 = *--stackPos;
  75407. y4 = *--stackPos;
  75408. }
  75409. }
  75410. }
  75411. if (type == Path::lineMarker)
  75412. {
  75413. ++subPathIndex;
  75414. closesSubPath = (stackPos == stackBase)
  75415. && (index < path.numElements)
  75416. && (points [index] == Path::closeSubPathMarker)
  75417. && x2 == subPathCloseX
  75418. && y2 == subPathCloseY;
  75419. return true;
  75420. }
  75421. else if (type == Path::quadMarker)
  75422. {
  75423. const size_t offset = (size_t) (stackPos - stackBase);
  75424. if (offset >= stackSize - 10)
  75425. {
  75426. stackSize <<= 1;
  75427. stackBase.realloc (stackSize);
  75428. stackPos = stackBase + offset;
  75429. }
  75430. const float dx1 = x1 - x2;
  75431. const float dy1 = y1 - y2;
  75432. const float dx2 = x2 - x3;
  75433. const float dy2 = y2 - y3;
  75434. const float m1x = (x1 + x2) * 0.5f;
  75435. const float m1y = (y1 + y2) * 0.5f;
  75436. const float m2x = (x2 + x3) * 0.5f;
  75437. const float m2y = (y2 + y3) * 0.5f;
  75438. const float m3x = (m1x + m2x) * 0.5f;
  75439. const float m3y = (m1y + m2y) * 0.5f;
  75440. if (dx1*dx1 + dy1*dy1 + dx2*dx2 + dy2*dy2 > tolerence)
  75441. {
  75442. *stackPos++ = y3;
  75443. *stackPos++ = x3;
  75444. *stackPos++ = m2y;
  75445. *stackPos++ = m2x;
  75446. *stackPos++ = Path::quadMarker;
  75447. *stackPos++ = m3y;
  75448. *stackPos++ = m3x;
  75449. *stackPos++ = m1y;
  75450. *stackPos++ = m1x;
  75451. *stackPos++ = Path::quadMarker;
  75452. }
  75453. else
  75454. {
  75455. *stackPos++ = y3;
  75456. *stackPos++ = x3;
  75457. *stackPos++ = Path::lineMarker;
  75458. *stackPos++ = m3y;
  75459. *stackPos++ = m3x;
  75460. *stackPos++ = Path::lineMarker;
  75461. }
  75462. jassert (stackPos < stackBase + stackSize);
  75463. }
  75464. else if (type == Path::cubicMarker)
  75465. {
  75466. const size_t offset = (size_t) (stackPos - stackBase);
  75467. if (offset >= stackSize - 16)
  75468. {
  75469. stackSize <<= 1;
  75470. stackBase.realloc (stackSize);
  75471. stackPos = stackBase + offset;
  75472. }
  75473. const float dx1 = x1 - x2;
  75474. const float dy1 = y1 - y2;
  75475. const float dx2 = x2 - x3;
  75476. const float dy2 = y2 - y3;
  75477. const float dx3 = x3 - x4;
  75478. const float dy3 = y3 - y4;
  75479. const float m1x = (x1 + x2) * 0.5f;
  75480. const float m1y = (y1 + y2) * 0.5f;
  75481. const float m2x = (x3 + x2) * 0.5f;
  75482. const float m2y = (y3 + y2) * 0.5f;
  75483. const float m3x = (x3 + x4) * 0.5f;
  75484. const float m3y = (y3 + y4) * 0.5f;
  75485. const float m4x = (m1x + m2x) * 0.5f;
  75486. const float m4y = (m1y + m2y) * 0.5f;
  75487. const float m5x = (m3x + m2x) * 0.5f;
  75488. const float m5y = (m3y + m2y) * 0.5f;
  75489. if (dx1*dx1 + dy1*dy1 + dx2*dx2
  75490. + dy2*dy2 + dx3*dx3 + dy3*dy3 > tolerence)
  75491. {
  75492. *stackPos++ = y4;
  75493. *stackPos++ = x4;
  75494. *stackPos++ = m3y;
  75495. *stackPos++ = m3x;
  75496. *stackPos++ = m5y;
  75497. *stackPos++ = m5x;
  75498. *stackPos++ = Path::cubicMarker;
  75499. *stackPos++ = (m4y + m5y) * 0.5f;
  75500. *stackPos++ = (m4x + m5x) * 0.5f;
  75501. *stackPos++ = m4y;
  75502. *stackPos++ = m4x;
  75503. *stackPos++ = m1y;
  75504. *stackPos++ = m1x;
  75505. *stackPos++ = Path::cubicMarker;
  75506. }
  75507. else
  75508. {
  75509. *stackPos++ = y4;
  75510. *stackPos++ = x4;
  75511. *stackPos++ = Path::lineMarker;
  75512. *stackPos++ = m5y;
  75513. *stackPos++ = m5x;
  75514. *stackPos++ = Path::lineMarker;
  75515. *stackPos++ = m4y;
  75516. *stackPos++ = m4x;
  75517. *stackPos++ = Path::lineMarker;
  75518. }
  75519. }
  75520. else if (type == Path::closeSubPathMarker)
  75521. {
  75522. if (x2 != subPathCloseX || y2 != subPathCloseY)
  75523. {
  75524. x1 = x2;
  75525. y1 = y2;
  75526. x2 = subPathCloseX;
  75527. y2 = subPathCloseY;
  75528. closesSubPath = true;
  75529. return true;
  75530. }
  75531. }
  75532. else
  75533. {
  75534. jassert (type == Path::moveMarker);
  75535. subPathIndex = -1;
  75536. subPathCloseX = x1 = x2;
  75537. subPathCloseY = y1 = y2;
  75538. }
  75539. }
  75540. }
  75541. #if JUCE_MSVC && JUCE_DEBUG
  75542. #pragma optimize ("", on) // resets optimisations to the project defaults
  75543. #endif
  75544. END_JUCE_NAMESPACE
  75545. /*** End of inlined file: juce_PathIterator.cpp ***/
  75546. /*** Start of inlined file: juce_PathStrokeType.cpp ***/
  75547. BEGIN_JUCE_NAMESPACE
  75548. PathStrokeType::PathStrokeType (const float strokeThickness,
  75549. const JointStyle jointStyle_,
  75550. const EndCapStyle endStyle_) throw()
  75551. : thickness (strokeThickness),
  75552. jointStyle (jointStyle_),
  75553. endStyle (endStyle_)
  75554. {
  75555. }
  75556. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  75557. : thickness (other.thickness),
  75558. jointStyle (other.jointStyle),
  75559. endStyle (other.endStyle)
  75560. {
  75561. }
  75562. PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  75563. {
  75564. thickness = other.thickness;
  75565. jointStyle = other.jointStyle;
  75566. endStyle = other.endStyle;
  75567. return *this;
  75568. }
  75569. PathStrokeType::~PathStrokeType() throw()
  75570. {
  75571. }
  75572. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  75573. {
  75574. return thickness == other.thickness
  75575. && jointStyle == other.jointStyle
  75576. && endStyle == other.endStyle;
  75577. }
  75578. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  75579. {
  75580. return ! operator== (other);
  75581. }
  75582. namespace PathStrokeHelpers
  75583. {
  75584. static bool lineIntersection (const float x1, const float y1,
  75585. const float x2, const float y2,
  75586. const float x3, const float y3,
  75587. const float x4, const float y4,
  75588. float& intersectionX,
  75589. float& intersectionY,
  75590. float& distanceBeyondLine1EndSquared) throw()
  75591. {
  75592. if (x2 != x3 || y2 != y3)
  75593. {
  75594. const float dx1 = x2 - x1;
  75595. const float dy1 = y2 - y1;
  75596. const float dx2 = x4 - x3;
  75597. const float dy2 = y4 - y3;
  75598. const float divisor = dx1 * dy2 - dx2 * dy1;
  75599. if (divisor == 0)
  75600. {
  75601. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  75602. {
  75603. if (dy1 == 0 && dy2 != 0)
  75604. {
  75605. const float along = (y1 - y3) / dy2;
  75606. intersectionX = x3 + along * dx2;
  75607. intersectionY = y1;
  75608. distanceBeyondLine1EndSquared = intersectionX - x2;
  75609. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75610. if ((x2 > x1) == (intersectionX < x2))
  75611. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75612. return along >= 0 && along <= 1.0f;
  75613. }
  75614. else if (dy2 == 0 && dy1 != 0)
  75615. {
  75616. const float along = (y3 - y1) / dy1;
  75617. intersectionX = x1 + along * dx1;
  75618. intersectionY = y3;
  75619. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  75620. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75621. if (along < 1.0f)
  75622. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75623. return along >= 0 && along <= 1.0f;
  75624. }
  75625. else if (dx1 == 0 && dx2 != 0)
  75626. {
  75627. const float along = (x1 - x3) / dx2;
  75628. intersectionX = x1;
  75629. intersectionY = y3 + along * dy2;
  75630. distanceBeyondLine1EndSquared = intersectionY - y2;
  75631. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75632. if ((y2 > y1) == (intersectionY < y2))
  75633. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75634. return along >= 0 && along <= 1.0f;
  75635. }
  75636. else if (dx2 == 0 && dx1 != 0)
  75637. {
  75638. const float along = (x3 - x1) / dx1;
  75639. intersectionX = x3;
  75640. intersectionY = y1 + along * dy1;
  75641. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  75642. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75643. if (along < 1.0f)
  75644. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75645. return along >= 0 && along <= 1.0f;
  75646. }
  75647. }
  75648. intersectionX = 0.5f * (x2 + x3);
  75649. intersectionY = 0.5f * (y2 + y3);
  75650. distanceBeyondLine1EndSquared = 0.0f;
  75651. return false;
  75652. }
  75653. else
  75654. {
  75655. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  75656. intersectionX = x1 + along1 * dx1;
  75657. intersectionY = y1 + along1 * dy1;
  75658. if (along1 >= 0 && along1 <= 1.0f)
  75659. {
  75660. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  75661. if (along2 >= 0 && along2 <= divisor)
  75662. {
  75663. distanceBeyondLine1EndSquared = 0.0f;
  75664. return true;
  75665. }
  75666. }
  75667. distanceBeyondLine1EndSquared = along1 - 1.0f;
  75668. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75669. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  75670. if (along1 < 1.0f)
  75671. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75672. return false;
  75673. }
  75674. }
  75675. intersectionX = x2;
  75676. intersectionY = y2;
  75677. distanceBeyondLine1EndSquared = 0.0f;
  75678. return true;
  75679. }
  75680. static void addEdgeAndJoint (Path& destPath,
  75681. const PathStrokeType::JointStyle style,
  75682. const float maxMiterExtensionSquared, const float width,
  75683. const float x1, const float y1,
  75684. const float x2, const float y2,
  75685. const float x3, const float y3,
  75686. const float x4, const float y4,
  75687. const float midX, const float midY)
  75688. {
  75689. if (style == PathStrokeType::beveled
  75690. || (x3 == x4 && y3 == y4)
  75691. || (x1 == x2 && y1 == y2))
  75692. {
  75693. destPath.lineTo (x2, y2);
  75694. destPath.lineTo (x3, y3);
  75695. }
  75696. else
  75697. {
  75698. float jx, jy, distanceBeyondLine1EndSquared;
  75699. // if they intersect, use this point..
  75700. if (lineIntersection (x1, y1, x2, y2,
  75701. x3, y3, x4, y4,
  75702. jx, jy, distanceBeyondLine1EndSquared))
  75703. {
  75704. destPath.lineTo (jx, jy);
  75705. }
  75706. else
  75707. {
  75708. if (style == PathStrokeType::mitered)
  75709. {
  75710. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  75711. && distanceBeyondLine1EndSquared > 0.0f)
  75712. {
  75713. destPath.lineTo (jx, jy);
  75714. }
  75715. else
  75716. {
  75717. // the end sticks out too far, so just use a blunt joint
  75718. destPath.lineTo (x2, y2);
  75719. destPath.lineTo (x3, y3);
  75720. }
  75721. }
  75722. else
  75723. {
  75724. // curved joints
  75725. float angle1 = std::atan2 (x2 - midX, y2 - midY);
  75726. float angle2 = std::atan2 (x3 - midX, y3 - midY);
  75727. const float angleIncrement = 0.1f;
  75728. destPath.lineTo (x2, y2);
  75729. if (std::abs (angle1 - angle2) > angleIncrement)
  75730. {
  75731. if (angle2 > angle1 + float_Pi
  75732. || (angle2 < angle1 && angle2 >= angle1 - float_Pi))
  75733. {
  75734. if (angle2 > angle1)
  75735. angle2 -= float_Pi * 2.0f;
  75736. jassert (angle1 <= angle2 + float_Pi);
  75737. angle1 -= angleIncrement;
  75738. while (angle1 > angle2)
  75739. {
  75740. destPath.lineTo (midX + width * std::sin (angle1),
  75741. midY + width * std::cos (angle1));
  75742. angle1 -= angleIncrement;
  75743. }
  75744. }
  75745. else
  75746. {
  75747. if (angle1 > angle2)
  75748. angle1 -= float_Pi * 2.0f;
  75749. jassert (angle1 >= angle2 - float_Pi);
  75750. angle1 += angleIncrement;
  75751. while (angle1 < angle2)
  75752. {
  75753. destPath.lineTo (midX + width * std::sin (angle1),
  75754. midY + width * std::cos (angle1));
  75755. angle1 += angleIncrement;
  75756. }
  75757. }
  75758. }
  75759. destPath.lineTo (x3, y3);
  75760. }
  75761. }
  75762. }
  75763. }
  75764. static void addLineEnd (Path& destPath,
  75765. const PathStrokeType::EndCapStyle style,
  75766. const float x1, const float y1,
  75767. const float x2, const float y2,
  75768. const float width)
  75769. {
  75770. if (style == PathStrokeType::butt)
  75771. {
  75772. destPath.lineTo (x2, y2);
  75773. }
  75774. else
  75775. {
  75776. float offx1, offy1, offx2, offy2;
  75777. float dx = x2 - x1;
  75778. float dy = y2 - y1;
  75779. const float len = juce_hypotf (dx, dy);
  75780. if (len == 0)
  75781. {
  75782. offx1 = offx2 = x1;
  75783. offy1 = offy2 = y1;
  75784. }
  75785. else
  75786. {
  75787. const float offset = width / len;
  75788. dx *= offset;
  75789. dy *= offset;
  75790. offx1 = x1 + dy;
  75791. offy1 = y1 - dx;
  75792. offx2 = x2 + dy;
  75793. offy2 = y2 - dx;
  75794. }
  75795. if (style == PathStrokeType::square)
  75796. {
  75797. // sqaure ends
  75798. destPath.lineTo (offx1, offy1);
  75799. destPath.lineTo (offx2, offy2);
  75800. destPath.lineTo (x2, y2);
  75801. }
  75802. else
  75803. {
  75804. // rounded ends
  75805. const float midx = (offx1 + offx2) * 0.5f;
  75806. const float midy = (offy1 + offy2) * 0.5f;
  75807. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  75808. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  75809. midx, midy);
  75810. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  75811. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  75812. x2, y2);
  75813. }
  75814. }
  75815. }
  75816. struct Arrowhead
  75817. {
  75818. float startWidth, startLength;
  75819. float endWidth, endLength;
  75820. };
  75821. static void addArrowhead (Path& destPath,
  75822. const float x1, const float y1,
  75823. const float x2, const float y2,
  75824. const float tipX, const float tipY,
  75825. const float width,
  75826. const float arrowheadWidth)
  75827. {
  75828. Line<float> line (x1, y1, x2, y2);
  75829. destPath.lineTo (line.getPointAlongLine (-(arrowheadWidth / 2.0f - width), 0));
  75830. destPath.lineTo (tipX, tipY);
  75831. destPath.lineTo (line.getPointAlongLine (arrowheadWidth - (arrowheadWidth / 2.0f - width), 0));
  75832. destPath.lineTo (x2, y2);
  75833. }
  75834. struct LineSection
  75835. {
  75836. float x1, y1, x2, y2; // original line
  75837. float lx1, ly1, lx2, ly2; // the left-hand stroke
  75838. float rx1, ry1, rx2, ry2; // the right-hand stroke
  75839. };
  75840. static void shortenSubPath (Array<LineSection>& subPath, float amountAtStart, float amountAtEnd)
  75841. {
  75842. while (amountAtEnd > 0 && subPath.size() > 0)
  75843. {
  75844. LineSection& l = subPath.getReference (subPath.size() - 1);
  75845. float dx = l.rx2 - l.rx1;
  75846. float dy = l.ry2 - l.ry1;
  75847. const float len = juce_hypotf (dx, dy);
  75848. if (len <= amountAtEnd && subPath.size() > 1)
  75849. {
  75850. LineSection& prev = subPath.getReference (subPath.size() - 2);
  75851. prev.x2 = l.x2;
  75852. prev.y2 = l.y2;
  75853. subPath.removeLast();
  75854. amountAtEnd -= len;
  75855. }
  75856. else
  75857. {
  75858. const float prop = jmin (0.9999f, amountAtEnd / len);
  75859. dx *= prop;
  75860. dy *= prop;
  75861. l.rx1 += dx;
  75862. l.ry1 += dy;
  75863. l.lx2 += dx;
  75864. l.ly2 += dy;
  75865. break;
  75866. }
  75867. }
  75868. while (amountAtStart > 0 && subPath.size() > 0)
  75869. {
  75870. LineSection& l = subPath.getReference (0);
  75871. float dx = l.rx2 - l.rx1;
  75872. float dy = l.ry2 - l.ry1;
  75873. const float len = juce_hypotf (dx, dy);
  75874. if (len <= amountAtStart && subPath.size() > 1)
  75875. {
  75876. LineSection& next = subPath.getReference (1);
  75877. next.x1 = l.x1;
  75878. next.y1 = l.y1;
  75879. subPath.remove (0);
  75880. amountAtStart -= len;
  75881. }
  75882. else
  75883. {
  75884. const float prop = jmin (0.9999f, amountAtStart / len);
  75885. dx *= prop;
  75886. dy *= prop;
  75887. l.rx2 -= dx;
  75888. l.ry2 -= dy;
  75889. l.lx1 -= dx;
  75890. l.ly1 -= dy;
  75891. break;
  75892. }
  75893. }
  75894. }
  75895. static void addSubPath (Path& destPath, Array<LineSection>& subPath,
  75896. const bool isClosed, const float width, const float maxMiterExtensionSquared,
  75897. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle,
  75898. const Arrowhead* const arrowhead)
  75899. {
  75900. jassert (subPath.size() > 0);
  75901. if (arrowhead != 0)
  75902. shortenSubPath (subPath, arrowhead->startLength, arrowhead->endLength);
  75903. const LineSection& firstLine = subPath.getReference (0);
  75904. float lastX1 = firstLine.lx1;
  75905. float lastY1 = firstLine.ly1;
  75906. float lastX2 = firstLine.lx2;
  75907. float lastY2 = firstLine.ly2;
  75908. if (isClosed)
  75909. {
  75910. destPath.startNewSubPath (lastX1, lastY1);
  75911. }
  75912. else
  75913. {
  75914. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  75915. if (arrowhead != 0)
  75916. addArrowhead (destPath, firstLine.rx2, firstLine.ry2, lastX1, lastY1, firstLine.x1, firstLine.y1,
  75917. width, arrowhead->startWidth);
  75918. else
  75919. addLineEnd (destPath, endStyle, firstLine.rx2, firstLine.ry2, lastX1, lastY1, width);
  75920. }
  75921. int i;
  75922. for (i = 1; i < subPath.size(); ++i)
  75923. {
  75924. const LineSection& l = subPath.getReference (i);
  75925. addEdgeAndJoint (destPath, jointStyle,
  75926. maxMiterExtensionSquared, width,
  75927. lastX1, lastY1, lastX2, lastY2,
  75928. l.lx1, l.ly1, l.lx2, l.ly2,
  75929. l.x1, l.y1);
  75930. lastX1 = l.lx1;
  75931. lastY1 = l.ly1;
  75932. lastX2 = l.lx2;
  75933. lastY2 = l.ly2;
  75934. }
  75935. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  75936. if (isClosed)
  75937. {
  75938. const LineSection& l = subPath.getReference (0);
  75939. addEdgeAndJoint (destPath, jointStyle,
  75940. maxMiterExtensionSquared, width,
  75941. lastX1, lastY1, lastX2, lastY2,
  75942. l.lx1, l.ly1, l.lx2, l.ly2,
  75943. l.x1, l.y1);
  75944. destPath.closeSubPath();
  75945. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  75946. }
  75947. else
  75948. {
  75949. destPath.lineTo (lastX2, lastY2);
  75950. if (arrowhead != 0)
  75951. addArrowhead (destPath, lastX2, lastY2, lastLine.rx1, lastLine.ry1, lastLine.x2, lastLine.y2,
  75952. width, arrowhead->endWidth);
  75953. else
  75954. addLineEnd (destPath, endStyle, lastX2, lastY2, lastLine.rx1, lastLine.ry1, width);
  75955. }
  75956. lastX1 = lastLine.rx1;
  75957. lastY1 = lastLine.ry1;
  75958. lastX2 = lastLine.rx2;
  75959. lastY2 = lastLine.ry2;
  75960. for (i = subPath.size() - 1; --i >= 0;)
  75961. {
  75962. const LineSection& l = subPath.getReference (i);
  75963. addEdgeAndJoint (destPath, jointStyle,
  75964. maxMiterExtensionSquared, width,
  75965. lastX1, lastY1, lastX2, lastY2,
  75966. l.rx1, l.ry1, l.rx2, l.ry2,
  75967. l.x2, l.y2);
  75968. lastX1 = l.rx1;
  75969. lastY1 = l.ry1;
  75970. lastX2 = l.rx2;
  75971. lastY2 = l.ry2;
  75972. }
  75973. if (isClosed)
  75974. {
  75975. addEdgeAndJoint (destPath, jointStyle,
  75976. maxMiterExtensionSquared, width,
  75977. lastX1, lastY1, lastX2, lastY2,
  75978. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  75979. lastLine.x2, lastLine.y2);
  75980. }
  75981. else
  75982. {
  75983. // do the last line
  75984. destPath.lineTo (lastX2, lastY2);
  75985. }
  75986. destPath.closeSubPath();
  75987. }
  75988. static void createStroke (const float thickness, const PathStrokeType::JointStyle jointStyle,
  75989. const PathStrokeType::EndCapStyle endStyle,
  75990. Path& destPath, const Path& source,
  75991. const AffineTransform& transform,
  75992. const float extraAccuracy, const Arrowhead* const arrowhead)
  75993. {
  75994. if (thickness <= 0)
  75995. {
  75996. destPath.clear();
  75997. return;
  75998. }
  75999. const Path* sourcePath = &source;
  76000. Path temp;
  76001. if (sourcePath == &destPath)
  76002. {
  76003. destPath.swapWithPath (temp);
  76004. sourcePath = &temp;
  76005. }
  76006. else
  76007. {
  76008. destPath.clear();
  76009. }
  76010. destPath.setUsingNonZeroWinding (true);
  76011. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  76012. const float width = 0.5f * thickness;
  76013. // Iterate the path, creating a list of the
  76014. // left/right-hand lines along either side of it...
  76015. PathFlatteningIterator it (*sourcePath, transform, 9.0f / extraAccuracy);
  76016. Array <LineSection> subPath;
  76017. subPath.ensureStorageAllocated (512);
  76018. LineSection l;
  76019. l.x1 = 0;
  76020. l.y1 = 0;
  76021. const float minSegmentLength = 2.0f / (extraAccuracy * extraAccuracy);
  76022. while (it.next())
  76023. {
  76024. if (it.subPathIndex == 0)
  76025. {
  76026. if (subPath.size() > 0)
  76027. {
  76028. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76029. subPath.clearQuick();
  76030. }
  76031. l.x1 = it.x1;
  76032. l.y1 = it.y1;
  76033. }
  76034. l.x2 = it.x2;
  76035. l.y2 = it.y2;
  76036. float dx = l.x2 - l.x1;
  76037. float dy = l.y2 - l.y1;
  76038. const float hypotSquared = dx*dx + dy*dy;
  76039. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  76040. {
  76041. const float len = std::sqrt (hypotSquared);
  76042. if (len == 0)
  76043. {
  76044. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  76045. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  76046. }
  76047. else
  76048. {
  76049. const float offset = width / len;
  76050. dx *= offset;
  76051. dy *= offset;
  76052. l.rx2 = l.x1 - dy;
  76053. l.ry2 = l.y1 + dx;
  76054. l.lx1 = l.x1 + dy;
  76055. l.ly1 = l.y1 - dx;
  76056. l.lx2 = l.x2 + dy;
  76057. l.ly2 = l.y2 - dx;
  76058. l.rx1 = l.x2 - dy;
  76059. l.ry1 = l.y2 + dx;
  76060. }
  76061. subPath.add (l);
  76062. if (it.closesSubPath)
  76063. {
  76064. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76065. subPath.clearQuick();
  76066. }
  76067. else
  76068. {
  76069. l.x1 = it.x2;
  76070. l.y1 = it.y2;
  76071. }
  76072. }
  76073. }
  76074. if (subPath.size() > 0)
  76075. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76076. }
  76077. }
  76078. void PathStrokeType::createStrokedPath (Path& destPath, const Path& sourcePath,
  76079. const AffineTransform& transform, const float extraAccuracy) const
  76080. {
  76081. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle, destPath, sourcePath,
  76082. transform, extraAccuracy, 0);
  76083. }
  76084. void PathStrokeType::createDashedStroke (Path& destPath,
  76085. const Path& sourcePath,
  76086. const float* dashLengths,
  76087. int numDashLengths,
  76088. const AffineTransform& transform,
  76089. const float extraAccuracy) const
  76090. {
  76091. if (thickness <= 0)
  76092. return;
  76093. // this should really be an even number..
  76094. jassert ((numDashLengths & 1) == 0);
  76095. Path newDestPath;
  76096. PathFlatteningIterator it (sourcePath, transform, 9.0f / extraAccuracy);
  76097. bool first = true;
  76098. int dashNum = 0;
  76099. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  76100. float dx = 0.0f, dy = 0.0f;
  76101. for (;;)
  76102. {
  76103. const bool isSolid = ((dashNum & 1) == 0);
  76104. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  76105. jassert (dashLen > 0); // must be a positive increment!
  76106. if (dashLen <= 0)
  76107. break;
  76108. pos += dashLen;
  76109. while (pos > lineEndPos)
  76110. {
  76111. if (! it.next())
  76112. {
  76113. if (isSolid && ! first)
  76114. newDestPath.lineTo (it.x2, it.y2);
  76115. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  76116. return;
  76117. }
  76118. if (isSolid && ! first)
  76119. newDestPath.lineTo (it.x1, it.y1);
  76120. else
  76121. newDestPath.startNewSubPath (it.x1, it.y1);
  76122. dx = it.x2 - it.x1;
  76123. dy = it.y2 - it.y1;
  76124. lineLen = juce_hypotf (dx, dy);
  76125. lineEndPos += lineLen;
  76126. first = it.closesSubPath;
  76127. }
  76128. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  76129. if (isSolid)
  76130. newDestPath.lineTo (it.x1 + dx * alpha,
  76131. it.y1 + dy * alpha);
  76132. else
  76133. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  76134. it.y1 + dy * alpha);
  76135. }
  76136. }
  76137. void PathStrokeType::createStrokeWithArrowheads (Path& destPath,
  76138. const Path& sourcePath,
  76139. const float arrowheadStartWidth, const float arrowheadStartLength,
  76140. const float arrowheadEndWidth, const float arrowheadEndLength,
  76141. const AffineTransform& transform,
  76142. const float extraAccuracy) const
  76143. {
  76144. PathStrokeHelpers::Arrowhead head;
  76145. head.startWidth = arrowheadStartWidth;
  76146. head.startLength = arrowheadStartLength;
  76147. head.endWidth = arrowheadEndWidth;
  76148. head.endLength = arrowheadEndLength;
  76149. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle,
  76150. destPath, sourcePath, transform, extraAccuracy, &head);
  76151. }
  76152. END_JUCE_NAMESPACE
  76153. /*** End of inlined file: juce_PathStrokeType.cpp ***/
  76154. /*** Start of inlined file: juce_PositionedRectangle.cpp ***/
  76155. BEGIN_JUCE_NAMESPACE
  76156. PositionedRectangle::PositionedRectangle() throw()
  76157. : x (0.0),
  76158. y (0.0),
  76159. w (0.0),
  76160. h (0.0),
  76161. xMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  76162. yMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  76163. wMode (absoluteSize),
  76164. hMode (absoluteSize)
  76165. {
  76166. }
  76167. PositionedRectangle::PositionedRectangle (const PositionedRectangle& other) throw()
  76168. : x (other.x),
  76169. y (other.y),
  76170. w (other.w),
  76171. h (other.h),
  76172. xMode (other.xMode),
  76173. yMode (other.yMode),
  76174. wMode (other.wMode),
  76175. hMode (other.hMode)
  76176. {
  76177. }
  76178. PositionedRectangle& PositionedRectangle::operator= (const PositionedRectangle& other) throw()
  76179. {
  76180. x = other.x;
  76181. y = other.y;
  76182. w = other.w;
  76183. h = other.h;
  76184. xMode = other.xMode;
  76185. yMode = other.yMode;
  76186. wMode = other.wMode;
  76187. hMode = other.hMode;
  76188. return *this;
  76189. }
  76190. PositionedRectangle::~PositionedRectangle() throw()
  76191. {
  76192. }
  76193. bool PositionedRectangle::operator== (const PositionedRectangle& other) const throw()
  76194. {
  76195. return x == other.x
  76196. && y == other.y
  76197. && w == other.w
  76198. && h == other.h
  76199. && xMode == other.xMode
  76200. && yMode == other.yMode
  76201. && wMode == other.wMode
  76202. && hMode == other.hMode;
  76203. }
  76204. bool PositionedRectangle::operator!= (const PositionedRectangle& other) const throw()
  76205. {
  76206. return ! operator== (other);
  76207. }
  76208. PositionedRectangle::PositionedRectangle (const String& stringVersion) throw()
  76209. {
  76210. StringArray tokens;
  76211. tokens.addTokens (stringVersion, false);
  76212. decodePosString (tokens [0], xMode, x);
  76213. decodePosString (tokens [1], yMode, y);
  76214. decodeSizeString (tokens [2], wMode, w);
  76215. decodeSizeString (tokens [3], hMode, h);
  76216. }
  76217. const String PositionedRectangle::toString() const throw()
  76218. {
  76219. String s;
  76220. s.preallocateStorage (12);
  76221. addPosDescription (s, xMode, x);
  76222. s << ' ';
  76223. addPosDescription (s, yMode, y);
  76224. s << ' ';
  76225. addSizeDescription (s, wMode, w);
  76226. s << ' ';
  76227. addSizeDescription (s, hMode, h);
  76228. return s;
  76229. }
  76230. const Rectangle<int> PositionedRectangle::getRectangle (const Rectangle<int>& target) const throw()
  76231. {
  76232. jassert (! target.isEmpty());
  76233. double x_, y_, w_, h_;
  76234. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  76235. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  76236. return Rectangle<int> (roundToInt (x_), roundToInt (y_),
  76237. roundToInt (w_), roundToInt (h_));
  76238. }
  76239. void PositionedRectangle::getRectangleDouble (const Rectangle<int>& target,
  76240. double& x_, double& y_,
  76241. double& w_, double& h_) const throw()
  76242. {
  76243. jassert (! target.isEmpty());
  76244. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  76245. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  76246. }
  76247. void PositionedRectangle::applyToComponent (Component& comp) const throw()
  76248. {
  76249. comp.setBounds (getRectangle (Rectangle<int> (comp.getParentWidth(), comp.getParentHeight())));
  76250. }
  76251. void PositionedRectangle::updateFrom (const Rectangle<int>& rectangle,
  76252. const Rectangle<int>& target) throw()
  76253. {
  76254. updatePosAndSize (x, w, rectangle.getX(), rectangle.getWidth(), xMode, wMode, target.getX(), target.getWidth());
  76255. updatePosAndSize (y, h, rectangle.getY(), rectangle.getHeight(), yMode, hMode, target.getY(), target.getHeight());
  76256. }
  76257. void PositionedRectangle::updateFromDouble (const double newX, const double newY,
  76258. const double newW, const double newH,
  76259. const Rectangle<int>& target) throw()
  76260. {
  76261. updatePosAndSize (x, w, newX, newW, xMode, wMode, target.getX(), target.getWidth());
  76262. updatePosAndSize (y, h, newY, newH, yMode, hMode, target.getY(), target.getHeight());
  76263. }
  76264. void PositionedRectangle::updateFromComponent (const Component& comp) throw()
  76265. {
  76266. if (comp.getParentComponent() == 0 && ! comp.isOnDesktop())
  76267. updateFrom (comp.getBounds(), Rectangle<int>());
  76268. else
  76269. updateFrom (comp.getBounds(), Rectangle<int> (comp.getParentWidth(), comp.getParentHeight()));
  76270. }
  76271. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointX() const throw()
  76272. {
  76273. return (AnchorPoint) (xMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  76274. }
  76275. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeX() const throw()
  76276. {
  76277. return (PositionMode) (xMode & (absoluteFromParentTopLeft
  76278. | absoluteFromParentBottomRight
  76279. | absoluteFromParentCentre
  76280. | proportionOfParentSize));
  76281. }
  76282. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointY() const throw()
  76283. {
  76284. return (AnchorPoint) (yMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  76285. }
  76286. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeY() const throw()
  76287. {
  76288. return (PositionMode) (yMode & (absoluteFromParentTopLeft
  76289. | absoluteFromParentBottomRight
  76290. | absoluteFromParentCentre
  76291. | proportionOfParentSize));
  76292. }
  76293. PositionedRectangle::SizeMode PositionedRectangle::getWidthMode() const throw()
  76294. {
  76295. return (SizeMode) wMode;
  76296. }
  76297. PositionedRectangle::SizeMode PositionedRectangle::getHeightMode() const throw()
  76298. {
  76299. return (SizeMode) hMode;
  76300. }
  76301. void PositionedRectangle::setModes (const AnchorPoint xAnchor,
  76302. const PositionMode xMode_,
  76303. const AnchorPoint yAnchor,
  76304. const PositionMode yMode_,
  76305. const SizeMode widthMode,
  76306. const SizeMode heightMode,
  76307. const Rectangle<int>& target) throw()
  76308. {
  76309. if (xMode != (xAnchor | xMode_) || wMode != widthMode)
  76310. {
  76311. double tx, tw;
  76312. applyPosAndSize (tx, tw, x, w, xMode, wMode, target.getX(), target.getWidth());
  76313. xMode = (uint8) (xAnchor | xMode_);
  76314. wMode = (uint8) widthMode;
  76315. updatePosAndSize (x, w, tx, tw, xMode, wMode, target.getX(), target.getWidth());
  76316. }
  76317. if (yMode != (yAnchor | yMode_) || hMode != heightMode)
  76318. {
  76319. double ty, th;
  76320. applyPosAndSize (ty, th, y, h, yMode, hMode, target.getY(), target.getHeight());
  76321. yMode = (uint8) (yAnchor | yMode_);
  76322. hMode = (uint8) heightMode;
  76323. updatePosAndSize (y, h, ty, th, yMode, hMode, target.getY(), target.getHeight());
  76324. }
  76325. }
  76326. bool PositionedRectangle::isPositionAbsolute() const throw()
  76327. {
  76328. return xMode == absoluteFromParentTopLeft
  76329. && yMode == absoluteFromParentTopLeft
  76330. && wMode == absoluteSize
  76331. && hMode == absoluteSize;
  76332. }
  76333. void PositionedRectangle::addPosDescription (String& s, const uint8 mode, const double value) const throw()
  76334. {
  76335. if ((mode & proportionOfParentSize) != 0)
  76336. {
  76337. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  76338. }
  76339. else
  76340. {
  76341. s << (roundToInt (value * 100.0) / 100.0);
  76342. if ((mode & absoluteFromParentBottomRight) != 0)
  76343. s << 'R';
  76344. else if ((mode & absoluteFromParentCentre) != 0)
  76345. s << 'C';
  76346. }
  76347. if ((mode & anchorAtRightOrBottom) != 0)
  76348. s << 'r';
  76349. else if ((mode & anchorAtCentre) != 0)
  76350. s << 'c';
  76351. }
  76352. void PositionedRectangle::addSizeDescription (String& s, const uint8 mode, const double value) const throw()
  76353. {
  76354. if (mode == proportionalSize)
  76355. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  76356. else if (mode == parentSizeMinusAbsolute)
  76357. s << (roundToInt (value * 100.0) / 100.0) << 'M';
  76358. else
  76359. s << (roundToInt (value * 100.0) / 100.0);
  76360. }
  76361. void PositionedRectangle::decodePosString (const String& s, uint8& mode, double& value) throw()
  76362. {
  76363. if (s.containsChar ('r'))
  76364. mode = anchorAtRightOrBottom;
  76365. else if (s.containsChar ('c'))
  76366. mode = anchorAtCentre;
  76367. else
  76368. mode = anchorAtLeftOrTop;
  76369. if (s.containsChar ('%'))
  76370. {
  76371. mode |= proportionOfParentSize;
  76372. value = s.removeCharacters ("%rcRC").getDoubleValue() / 100.0;
  76373. }
  76374. else
  76375. {
  76376. if (s.containsChar ('R'))
  76377. mode |= absoluteFromParentBottomRight;
  76378. else if (s.containsChar ('C'))
  76379. mode |= absoluteFromParentCentre;
  76380. else
  76381. mode |= absoluteFromParentTopLeft;
  76382. value = s.removeCharacters ("rcRC").getDoubleValue();
  76383. }
  76384. }
  76385. void PositionedRectangle::decodeSizeString (const String& s, uint8& mode, double& value) throw()
  76386. {
  76387. if (s.containsChar ('%'))
  76388. {
  76389. mode = proportionalSize;
  76390. value = s.upToFirstOccurrenceOf ("%", false, false).getDoubleValue() / 100.0;
  76391. }
  76392. else if (s.containsChar ('M'))
  76393. {
  76394. mode = parentSizeMinusAbsolute;
  76395. value = s.getDoubleValue();
  76396. }
  76397. else
  76398. {
  76399. mode = absoluteSize;
  76400. value = s.getDoubleValue();
  76401. }
  76402. }
  76403. void PositionedRectangle::applyPosAndSize (double& xOut, double& wOut,
  76404. const double x_, const double w_,
  76405. const uint8 xMode_, const uint8 wMode_,
  76406. const int parentPos,
  76407. const int parentSize) const throw()
  76408. {
  76409. if (wMode_ == proportionalSize)
  76410. wOut = roundToInt (w_ * parentSize);
  76411. else if (wMode_ == parentSizeMinusAbsolute)
  76412. wOut = jmax (0, parentSize - roundToInt (w_));
  76413. else
  76414. wOut = roundToInt (w_);
  76415. if ((xMode_ & proportionOfParentSize) != 0)
  76416. xOut = parentPos + x_ * parentSize;
  76417. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  76418. xOut = (parentPos + parentSize) - x_;
  76419. else if ((xMode_ & absoluteFromParentCentre) != 0)
  76420. xOut = x_ + (parentPos + parentSize / 2);
  76421. else
  76422. xOut = x_ + parentPos;
  76423. if ((xMode_ & anchorAtRightOrBottom) != 0)
  76424. xOut -= wOut;
  76425. else if ((xMode_ & anchorAtCentre) != 0)
  76426. xOut -= wOut / 2;
  76427. }
  76428. void PositionedRectangle::updatePosAndSize (double& xOut, double& wOut,
  76429. double x_, const double w_,
  76430. const uint8 xMode_, const uint8 wMode_,
  76431. const int parentPos,
  76432. const int parentSize) const throw()
  76433. {
  76434. if (wMode_ == proportionalSize)
  76435. {
  76436. if (parentSize > 0)
  76437. wOut = w_ / parentSize;
  76438. }
  76439. else if (wMode_ == parentSizeMinusAbsolute)
  76440. wOut = parentSize - w_;
  76441. else
  76442. wOut = w_;
  76443. if ((xMode_ & anchorAtRightOrBottom) != 0)
  76444. x_ += w_;
  76445. else if ((xMode_ & anchorAtCentre) != 0)
  76446. x_ += w_ / 2;
  76447. if ((xMode_ & proportionOfParentSize) != 0)
  76448. {
  76449. if (parentSize > 0)
  76450. xOut = (x_ - parentPos) / parentSize;
  76451. }
  76452. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  76453. xOut = (parentPos + parentSize) - x_;
  76454. else if ((xMode_ & absoluteFromParentCentre) != 0)
  76455. xOut = x_ - (parentPos + parentSize / 2);
  76456. else
  76457. xOut = x_ - parentPos;
  76458. }
  76459. END_JUCE_NAMESPACE
  76460. /*** End of inlined file: juce_PositionedRectangle.cpp ***/
  76461. /*** Start of inlined file: juce_RectangleList.cpp ***/
  76462. BEGIN_JUCE_NAMESPACE
  76463. RectangleList::RectangleList() throw()
  76464. {
  76465. }
  76466. RectangleList::RectangleList (const Rectangle<int>& rect)
  76467. {
  76468. if (! rect.isEmpty())
  76469. rects.add (rect);
  76470. }
  76471. RectangleList::RectangleList (const RectangleList& other)
  76472. : rects (other.rects)
  76473. {
  76474. }
  76475. RectangleList& RectangleList::operator= (const RectangleList& other)
  76476. {
  76477. rects = other.rects;
  76478. return *this;
  76479. }
  76480. RectangleList::~RectangleList()
  76481. {
  76482. }
  76483. void RectangleList::clear()
  76484. {
  76485. rects.clearQuick();
  76486. }
  76487. const Rectangle<int> RectangleList::getRectangle (const int index) const throw()
  76488. {
  76489. if (((unsigned int) index) < (unsigned int) rects.size())
  76490. return rects.getReference (index);
  76491. return Rectangle<int>();
  76492. }
  76493. bool RectangleList::isEmpty() const throw()
  76494. {
  76495. return rects.size() == 0;
  76496. }
  76497. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  76498. : current (0),
  76499. owner (list),
  76500. index (list.rects.size())
  76501. {
  76502. }
  76503. RectangleList::Iterator::~Iterator()
  76504. {
  76505. }
  76506. bool RectangleList::Iterator::next() throw()
  76507. {
  76508. if (--index >= 0)
  76509. {
  76510. current = & (owner.rects.getReference (index));
  76511. return true;
  76512. }
  76513. return false;
  76514. }
  76515. void RectangleList::add (const Rectangle<int>& rect)
  76516. {
  76517. if (! rect.isEmpty())
  76518. {
  76519. if (rects.size() == 0)
  76520. {
  76521. rects.add (rect);
  76522. }
  76523. else
  76524. {
  76525. bool anyOverlaps = false;
  76526. int i;
  76527. for (i = rects.size(); --i >= 0;)
  76528. {
  76529. Rectangle<int>& ourRect = rects.getReference (i);
  76530. if (rect.intersects (ourRect))
  76531. {
  76532. if (rect.contains (ourRect))
  76533. rects.remove (i);
  76534. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  76535. anyOverlaps = true;
  76536. }
  76537. }
  76538. if (anyOverlaps && rects.size() > 0)
  76539. {
  76540. RectangleList r (rect);
  76541. for (i = rects.size(); --i >= 0;)
  76542. {
  76543. const Rectangle<int>& ourRect = rects.getReference (i);
  76544. if (rect.intersects (ourRect))
  76545. {
  76546. r.subtract (ourRect);
  76547. if (r.rects.size() == 0)
  76548. return;
  76549. }
  76550. }
  76551. for (i = r.getNumRectangles(); --i >= 0;)
  76552. rects.add (r.rects.getReference (i));
  76553. }
  76554. else
  76555. {
  76556. rects.add (rect);
  76557. }
  76558. }
  76559. }
  76560. }
  76561. void RectangleList::addWithoutMerging (const Rectangle<int>& rect)
  76562. {
  76563. if (! rect.isEmpty())
  76564. rects.add (rect);
  76565. }
  76566. void RectangleList::add (const int x, const int y, const int w, const int h)
  76567. {
  76568. if (rects.size() == 0)
  76569. {
  76570. if (w > 0 && h > 0)
  76571. rects.add (Rectangle<int> (x, y, w, h));
  76572. }
  76573. else
  76574. {
  76575. add (Rectangle<int> (x, y, w, h));
  76576. }
  76577. }
  76578. void RectangleList::add (const RectangleList& other)
  76579. {
  76580. for (int i = 0; i < other.rects.size(); ++i)
  76581. add (other.rects.getReference (i));
  76582. }
  76583. void RectangleList::subtract (const Rectangle<int>& rect)
  76584. {
  76585. const int originalNumRects = rects.size();
  76586. if (originalNumRects > 0)
  76587. {
  76588. const int x1 = rect.x;
  76589. const int y1 = rect.y;
  76590. const int x2 = x1 + rect.w;
  76591. const int y2 = y1 + rect.h;
  76592. for (int i = getNumRectangles(); --i >= 0;)
  76593. {
  76594. Rectangle<int>& r = rects.getReference (i);
  76595. const int rx1 = r.x;
  76596. const int ry1 = r.y;
  76597. const int rx2 = rx1 + r.w;
  76598. const int ry2 = ry1 + r.h;
  76599. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  76600. {
  76601. if (x1 > rx1 && x1 < rx2)
  76602. {
  76603. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  76604. {
  76605. r.w = x1 - rx1;
  76606. }
  76607. else
  76608. {
  76609. r.x = x1;
  76610. r.w = rx2 - x1;
  76611. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x1 - rx1, ry2 - ry1));
  76612. i += 2;
  76613. }
  76614. }
  76615. else if (x2 > rx1 && x2 < rx2)
  76616. {
  76617. r.x = x2;
  76618. r.w = rx2 - x2;
  76619. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  76620. {
  76621. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x2 - rx1, ry2 - ry1));
  76622. i += 2;
  76623. }
  76624. }
  76625. else if (y1 > ry1 && y1 < ry2)
  76626. {
  76627. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  76628. {
  76629. r.h = y1 - ry1;
  76630. }
  76631. else
  76632. {
  76633. r.y = y1;
  76634. r.h = ry2 - y1;
  76635. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y1 - ry1));
  76636. i += 2;
  76637. }
  76638. }
  76639. else if (y2 > ry1 && y2 < ry2)
  76640. {
  76641. r.y = y2;
  76642. r.h = ry2 - y2;
  76643. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  76644. {
  76645. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y2 - ry1));
  76646. i += 2;
  76647. }
  76648. }
  76649. else
  76650. {
  76651. rects.remove (i);
  76652. }
  76653. }
  76654. }
  76655. }
  76656. }
  76657. bool RectangleList::subtract (const RectangleList& otherList)
  76658. {
  76659. for (int i = otherList.rects.size(); --i >= 0 && rects.size() > 0;)
  76660. subtract (otherList.rects.getReference (i));
  76661. return rects.size() > 0;
  76662. }
  76663. bool RectangleList::clipTo (const Rectangle<int>& rect)
  76664. {
  76665. bool notEmpty = false;
  76666. if (rect.isEmpty())
  76667. {
  76668. clear();
  76669. }
  76670. else
  76671. {
  76672. for (int i = rects.size(); --i >= 0;)
  76673. {
  76674. Rectangle<int>& r = rects.getReference (i);
  76675. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76676. rects.remove (i);
  76677. else
  76678. notEmpty = true;
  76679. }
  76680. }
  76681. return notEmpty;
  76682. }
  76683. bool RectangleList::clipTo (const RectangleList& other)
  76684. {
  76685. if (rects.size() == 0)
  76686. return false;
  76687. RectangleList result;
  76688. for (int j = 0; j < rects.size(); ++j)
  76689. {
  76690. const Rectangle<int>& rect = rects.getReference (j);
  76691. for (int i = other.rects.size(); --i >= 0;)
  76692. {
  76693. Rectangle<int> r (other.rects.getReference (i));
  76694. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76695. result.rects.add (r);
  76696. }
  76697. }
  76698. swapWith (result);
  76699. return ! isEmpty();
  76700. }
  76701. bool RectangleList::getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const
  76702. {
  76703. destRegion.clear();
  76704. if (! rect.isEmpty())
  76705. {
  76706. for (int i = rects.size(); --i >= 0;)
  76707. {
  76708. Rectangle<int> r (rects.getReference (i));
  76709. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76710. destRegion.rects.add (r);
  76711. }
  76712. }
  76713. return destRegion.rects.size() > 0;
  76714. }
  76715. void RectangleList::swapWith (RectangleList& otherList) throw()
  76716. {
  76717. rects.swapWithArray (otherList.rects);
  76718. }
  76719. void RectangleList::consolidate()
  76720. {
  76721. int i;
  76722. for (i = 0; i < getNumRectangles() - 1; ++i)
  76723. {
  76724. Rectangle<int>& r = rects.getReference (i);
  76725. const int rx1 = r.x;
  76726. const int ry1 = r.y;
  76727. const int rx2 = rx1 + r.w;
  76728. const int ry2 = ry1 + r.h;
  76729. for (int j = rects.size(); --j > i;)
  76730. {
  76731. Rectangle<int>& r2 = rects.getReference (j);
  76732. const int jrx1 = r2.x;
  76733. const int jry1 = r2.y;
  76734. const int jrx2 = jrx1 + r2.w;
  76735. const int jry2 = jry1 + r2.h;
  76736. // if the vertical edges of any blocks are touching and their horizontals don't
  76737. // line up, split them horizontally..
  76738. if (jrx1 == rx2 || jrx2 == rx1)
  76739. {
  76740. if (jry1 > ry1 && jry1 < ry2)
  76741. {
  76742. r.h = jry1 - ry1;
  76743. rects.add (Rectangle<int> (rx1, jry1, rx2 - rx1, ry2 - jry1));
  76744. i = -1;
  76745. break;
  76746. }
  76747. if (jry2 > ry1 && jry2 < ry2)
  76748. {
  76749. r.h = jry2 - ry1;
  76750. rects.add (Rectangle<int> (rx1, jry2, rx2 - rx1, ry2 - jry2));
  76751. i = -1;
  76752. break;
  76753. }
  76754. else if (ry1 > jry1 && ry1 < jry2)
  76755. {
  76756. r2.h = ry1 - jry1;
  76757. rects.add (Rectangle<int> (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  76758. i = -1;
  76759. break;
  76760. }
  76761. else if (ry2 > jry1 && ry2 < jry2)
  76762. {
  76763. r2.h = ry2 - jry1;
  76764. rects.add (Rectangle<int> (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  76765. i = -1;
  76766. break;
  76767. }
  76768. }
  76769. }
  76770. }
  76771. for (i = 0; i < rects.size() - 1; ++i)
  76772. {
  76773. Rectangle<int>& r = rects.getReference (i);
  76774. for (int j = rects.size(); --j > i;)
  76775. {
  76776. if (r.enlargeIfAdjacent (rects.getReference (j)))
  76777. {
  76778. rects.remove (j);
  76779. i = -1;
  76780. break;
  76781. }
  76782. }
  76783. }
  76784. }
  76785. bool RectangleList::containsPoint (const int x, const int y) const throw()
  76786. {
  76787. for (int i = getNumRectangles(); --i >= 0;)
  76788. if (rects.getReference (i).contains (x, y))
  76789. return true;
  76790. return false;
  76791. }
  76792. bool RectangleList::containsRectangle (const Rectangle<int>& rectangleToCheck) const
  76793. {
  76794. if (rects.size() > 1)
  76795. {
  76796. RectangleList r (rectangleToCheck);
  76797. for (int i = rects.size(); --i >= 0;)
  76798. {
  76799. r.subtract (rects.getReference (i));
  76800. if (r.rects.size() == 0)
  76801. return true;
  76802. }
  76803. }
  76804. else if (rects.size() > 0)
  76805. {
  76806. return rects.getReference (0).contains (rectangleToCheck);
  76807. }
  76808. return false;
  76809. }
  76810. bool RectangleList::intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw()
  76811. {
  76812. for (int i = rects.size(); --i >= 0;)
  76813. if (rects.getReference (i).intersects (rectangleToCheck))
  76814. return true;
  76815. return false;
  76816. }
  76817. bool RectangleList::intersects (const RectangleList& other) const throw()
  76818. {
  76819. for (int i = rects.size(); --i >= 0;)
  76820. if (other.intersectsRectangle (rects.getReference (i)))
  76821. return true;
  76822. return false;
  76823. }
  76824. const Rectangle<int> RectangleList::getBounds() const throw()
  76825. {
  76826. if (rects.size() <= 1)
  76827. {
  76828. if (rects.size() == 0)
  76829. return Rectangle<int>();
  76830. else
  76831. return rects.getReference (0);
  76832. }
  76833. else
  76834. {
  76835. const Rectangle<int>& r = rects.getReference (0);
  76836. int minX = r.x;
  76837. int minY = r.y;
  76838. int maxX = minX + r.w;
  76839. int maxY = minY + r.h;
  76840. for (int i = rects.size(); --i > 0;)
  76841. {
  76842. const Rectangle<int>& r2 = rects.getReference (i);
  76843. minX = jmin (minX, r2.x);
  76844. minY = jmin (minY, r2.y);
  76845. maxX = jmax (maxX, r2.getRight());
  76846. maxY = jmax (maxY, r2.getBottom());
  76847. }
  76848. return Rectangle<int> (minX, minY, maxX - minX, maxY - minY);
  76849. }
  76850. }
  76851. void RectangleList::offsetAll (const int dx, const int dy) throw()
  76852. {
  76853. for (int i = rects.size(); --i >= 0;)
  76854. {
  76855. Rectangle<int>& r = rects.getReference (i);
  76856. r.x += dx;
  76857. r.y += dy;
  76858. }
  76859. }
  76860. const Path RectangleList::toPath() const
  76861. {
  76862. Path p;
  76863. for (int i = rects.size(); --i >= 0;)
  76864. {
  76865. const Rectangle<int>& r = rects.getReference (i);
  76866. p.addRectangle ((float) r.x,
  76867. (float) r.y,
  76868. (float) r.w,
  76869. (float) r.h);
  76870. }
  76871. return p;
  76872. }
  76873. END_JUCE_NAMESPACE
  76874. /*** End of inlined file: juce_RectangleList.cpp ***/
  76875. /*** Start of inlined file: juce_Image.cpp ***/
  76876. BEGIN_JUCE_NAMESPACE
  76877. Image::SharedImage::SharedImage (const PixelFormat format_, const int width_, const int height_)
  76878. : format (format_), width (width_), height (height_)
  76879. {
  76880. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  76881. jassert (width > 0 && height > 0); // It's illegal to create a zero-sized image!
  76882. }
  76883. Image::SharedImage::~SharedImage()
  76884. {
  76885. }
  76886. inline uint8* Image::SharedImage::getPixelData (const int x, const int y) const throw()
  76887. {
  76888. return imageData + lineStride * y + pixelStride * x;
  76889. }
  76890. class SoftwareSharedImage : public Image::SharedImage
  76891. {
  76892. public:
  76893. SoftwareSharedImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  76894. : Image::SharedImage (format_, width_, height_)
  76895. {
  76896. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  76897. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  76898. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  76899. imageData = imageDataAllocated;
  76900. }
  76901. ~SoftwareSharedImage()
  76902. {
  76903. }
  76904. Image::ImageType getType() const
  76905. {
  76906. return Image::SoftwareImage;
  76907. }
  76908. LowLevelGraphicsContext* createLowLevelContext()
  76909. {
  76910. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  76911. }
  76912. SharedImage* clone()
  76913. {
  76914. SoftwareSharedImage* s = new SoftwareSharedImage (format, width, height, false);
  76915. memcpy (s->imageData, imageData, lineStride * height);
  76916. return s;
  76917. }
  76918. private:
  76919. HeapBlock<uint8> imageDataAllocated;
  76920. };
  76921. Image::SharedImage* Image::SharedImage::createSoftwareImage (Image::PixelFormat format, int width, int height, bool clearImage)
  76922. {
  76923. return new SoftwareSharedImage (format, width, height, clearImage);
  76924. }
  76925. class SubsectionSharedImage : public Image::SharedImage
  76926. {
  76927. public:
  76928. SubsectionSharedImage (Image::SharedImage* const image_, const Rectangle<int>& area_)
  76929. : Image::SharedImage (image_->getPixelFormat(), area_.getWidth(), area_.getHeight()),
  76930. image (image_), area (area_)
  76931. {
  76932. pixelStride = image_->getPixelStride();
  76933. lineStride = image_->getLineStride();
  76934. imageData = image_->getPixelData (area_.getX(), area_.getY());
  76935. }
  76936. ~SubsectionSharedImage() {}
  76937. Image::ImageType getType() const
  76938. {
  76939. return Image::SoftwareImage;
  76940. }
  76941. LowLevelGraphicsContext* createLowLevelContext()
  76942. {
  76943. LowLevelGraphicsContext* g = image->createLowLevelContext();
  76944. g->clipToRectangle (area);
  76945. g->setOrigin (area.getX(), area.getY());
  76946. return g;
  76947. }
  76948. SharedImage* clone()
  76949. {
  76950. return new SubsectionSharedImage (image->clone(), area);
  76951. }
  76952. private:
  76953. const ReferenceCountedObjectPtr<Image::SharedImage> image;
  76954. const Rectangle<int> area;
  76955. SubsectionSharedImage (const SubsectionSharedImage&);
  76956. SubsectionSharedImage& operator= (const SubsectionSharedImage&);
  76957. };
  76958. const Image Image::getClippedImage (const Rectangle<int>& area) const
  76959. {
  76960. if (area.contains (getBounds()))
  76961. return *this;
  76962. const Rectangle<int> validArea (area.getIntersection (getBounds()));
  76963. if (validArea.isEmpty())
  76964. return Image::null;
  76965. return Image (new SubsectionSharedImage (image, validArea));
  76966. }
  76967. Image::Image()
  76968. {
  76969. }
  76970. Image::Image (SharedImage* const instance)
  76971. : image (instance)
  76972. {
  76973. }
  76974. Image::Image (const PixelFormat format,
  76975. const int width, const int height,
  76976. const bool clearImage, const ImageType type)
  76977. : image (type == Image::NativeImage ? SharedImage::createNativeImage (format, width, height, clearImage)
  76978. : new SoftwareSharedImage (format, width, height, clearImage))
  76979. {
  76980. }
  76981. Image::Image (const Image& other)
  76982. : image (other.image)
  76983. {
  76984. }
  76985. Image& Image::operator= (const Image& other)
  76986. {
  76987. image = other.image;
  76988. return *this;
  76989. }
  76990. Image::~Image()
  76991. {
  76992. }
  76993. const Image Image::null;
  76994. LowLevelGraphicsContext* Image::createLowLevelContext() const
  76995. {
  76996. return image == 0 ? 0 : image->createLowLevelContext();
  76997. }
  76998. void Image::duplicateIfShared()
  76999. {
  77000. if (image != 0 && image->getReferenceCount() > 1)
  77001. image = image->clone();
  77002. }
  77003. const Image Image::rescaled (const int newWidth, const int newHeight, const Graphics::ResamplingQuality quality) const
  77004. {
  77005. if (image == 0 || (image->width == newWidth && image->height == newHeight))
  77006. return *this;
  77007. Image newImage (image->format, newWidth, newHeight, hasAlphaChannel(), image->getType());
  77008. Graphics g (newImage);
  77009. g.setImageResamplingQuality (quality);
  77010. g.drawImage (*this, 0, 0, newWidth, newHeight, 0, 0, image->width, image->height, false);
  77011. return newImage;
  77012. }
  77013. const Image Image::convertedToFormat (PixelFormat newFormat) const
  77014. {
  77015. if (image == 0 || newFormat == image->format)
  77016. return *this;
  77017. Image newImage (newFormat, image->width, image->height, false, image->getType());
  77018. if (newFormat == SingleChannel)
  77019. {
  77020. if (! hasAlphaChannel())
  77021. {
  77022. newImage.clear (getBounds(), Colours::black);
  77023. }
  77024. else
  77025. {
  77026. const BitmapData destData (newImage, 0, 0, image->width, image->height, true);
  77027. const BitmapData srcData (*this, 0, 0, image->width, image->height);
  77028. for (int y = 0; y < image->height; ++y)
  77029. {
  77030. const PixelARGB* src = (const PixelARGB*) srcData.getLinePointer(y);
  77031. uint8* dst = destData.getLinePointer (y);
  77032. for (int x = image->width; --x >= 0;)
  77033. {
  77034. *dst++ = src->getAlpha();
  77035. ++src;
  77036. }
  77037. }
  77038. }
  77039. }
  77040. else
  77041. {
  77042. if (hasAlphaChannel())
  77043. newImage.clear (getBounds());
  77044. Graphics g (newImage);
  77045. g.drawImageAt (*this, 0, 0);
  77046. }
  77047. return newImage;
  77048. }
  77049. const var Image::getTag() const
  77050. {
  77051. return image == 0 ? var::null : image->userTag;
  77052. }
  77053. void Image::setTag (const var& newTag)
  77054. {
  77055. if (image != 0)
  77056. image->userTag = newTag;
  77057. }
  77058. Image::BitmapData::BitmapData (Image& image, const int x, const int y, const int w, const int h, const bool /*makeWritable*/)
  77059. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  77060. pixelFormat (image.getFormat()),
  77061. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  77062. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  77063. width (w),
  77064. height (h)
  77065. {
  77066. jassert (data != 0);
  77067. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  77068. }
  77069. Image::BitmapData::BitmapData (const Image& image, const int x, const int y, const int w, const int h)
  77070. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  77071. pixelFormat (image.getFormat()),
  77072. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  77073. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  77074. width (w),
  77075. height (h)
  77076. {
  77077. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  77078. }
  77079. Image::BitmapData::BitmapData (const Image& image, bool /*needsToBeWritable*/)
  77080. : data (image.image == 0 ? 0 : image.image->imageData),
  77081. pixelFormat (image.getFormat()),
  77082. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  77083. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  77084. width (image.getWidth()),
  77085. height (image.getHeight())
  77086. {
  77087. }
  77088. Image::BitmapData::~BitmapData()
  77089. {
  77090. }
  77091. const Colour Image::BitmapData::getPixelColour (const int x, const int y) const throw()
  77092. {
  77093. jassert (((unsigned int) x) < (unsigned int) width && ((unsigned int) y) < (unsigned int) height);
  77094. const uint8* const pixel = getPixelPointer (x, y);
  77095. switch (pixelFormat)
  77096. {
  77097. case Image::ARGB:
  77098. {
  77099. PixelARGB p (*(const PixelARGB*) pixel);
  77100. p.unpremultiply();
  77101. return Colour (p.getARGB());
  77102. }
  77103. case Image::RGB:
  77104. return Colour (((const PixelRGB*) pixel)->getARGB());
  77105. case Image::SingleChannel:
  77106. return Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixel);
  77107. default:
  77108. jassertfalse;
  77109. break;
  77110. }
  77111. return Colour();
  77112. }
  77113. void Image::BitmapData::setPixelColour (const int x, const int y, const Colour& colour) const throw()
  77114. {
  77115. jassert (((unsigned int) x) < (unsigned int) width && ((unsigned int) y) < (unsigned int) height);
  77116. uint8* const pixel = getPixelPointer (x, y);
  77117. const PixelARGB col (colour.getPixelARGB());
  77118. switch (pixelFormat)
  77119. {
  77120. case Image::ARGB: ((PixelARGB*) pixel)->set (col); break;
  77121. case Image::RGB: ((PixelRGB*) pixel)->set (col); break;
  77122. case Image::SingleChannel: *pixel = col.getAlpha(); break;
  77123. default: jassertfalse; break;
  77124. }
  77125. }
  77126. void Image::setPixelData (int x, int y, int w, int h,
  77127. const uint8* const sourcePixelData, const int sourceLineStride)
  77128. {
  77129. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= getWidth() && y + h <= getHeight());
  77130. if (Rectangle<int>::intersectRectangles (x, y, w, h, 0, 0, getWidth(), getHeight()))
  77131. {
  77132. const BitmapData dest (*this, x, y, w, h, true);
  77133. for (int i = 0; i < h; ++i)
  77134. {
  77135. memcpy (dest.getLinePointer(i),
  77136. sourcePixelData + sourceLineStride * i,
  77137. w * dest.pixelStride);
  77138. }
  77139. }
  77140. }
  77141. void Image::clear (const Rectangle<int>& area, const Colour& colourToClearTo)
  77142. {
  77143. const Rectangle<int> clipped (area.getIntersection (getBounds()));
  77144. if (! clipped.isEmpty())
  77145. {
  77146. const PixelARGB col (colourToClearTo.getPixelARGB());
  77147. const BitmapData destData (*this, clipped.getX(), clipped.getY(), clipped.getWidth(), clipped.getHeight(), true);
  77148. uint8* dest = destData.data;
  77149. int dh = clipped.getHeight();
  77150. while (--dh >= 0)
  77151. {
  77152. uint8* line = dest;
  77153. dest += destData.lineStride;
  77154. if (isARGB())
  77155. {
  77156. for (int x = clipped.getWidth(); --x >= 0;)
  77157. {
  77158. ((PixelARGB*) line)->set (col);
  77159. line += destData.pixelStride;
  77160. }
  77161. }
  77162. else if (isRGB())
  77163. {
  77164. for (int x = clipped.getWidth(); --x >= 0;)
  77165. {
  77166. ((PixelRGB*) line)->set (col);
  77167. line += destData.pixelStride;
  77168. }
  77169. }
  77170. else
  77171. {
  77172. for (int x = clipped.getWidth(); --x >= 0;)
  77173. {
  77174. *line = col.getAlpha();
  77175. line += destData.pixelStride;
  77176. }
  77177. }
  77178. }
  77179. }
  77180. }
  77181. const Colour Image::getPixelAt (const int x, const int y) const
  77182. {
  77183. if (((unsigned int) x) < (unsigned int) getWidth()
  77184. && ((unsigned int) y) < (unsigned int) getHeight())
  77185. {
  77186. const BitmapData srcData (*this, x, y, 1, 1);
  77187. return srcData.getPixelColour (0, 0);
  77188. }
  77189. return Colour();
  77190. }
  77191. void Image::setPixelAt (const int x, const int y, const Colour& colour)
  77192. {
  77193. if (((unsigned int) x) < (unsigned int) getWidth()
  77194. && ((unsigned int) y) < (unsigned int) getHeight())
  77195. {
  77196. const BitmapData destData (*this, x, y, 1, 1, true);
  77197. destData.setPixelColour (0, 0, colour);
  77198. }
  77199. }
  77200. void Image::multiplyAlphaAt (const int x, const int y, const float multiplier)
  77201. {
  77202. if (((unsigned int) x) < (unsigned int) getWidth()
  77203. && ((unsigned int) y) < (unsigned int) getHeight()
  77204. && hasAlphaChannel())
  77205. {
  77206. const BitmapData destData (*this, x, y, 1, 1, true);
  77207. if (isARGB())
  77208. ((PixelARGB*) destData.data)->multiplyAlpha (multiplier);
  77209. else
  77210. *(destData.data) = (uint8) (*(destData.data) * multiplier);
  77211. }
  77212. }
  77213. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  77214. {
  77215. if (hasAlphaChannel())
  77216. {
  77217. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  77218. if (isARGB())
  77219. {
  77220. for (int y = 0; y < destData.height; ++y)
  77221. {
  77222. uint8* p = destData.getLinePointer (y);
  77223. for (int x = 0; x < destData.width; ++x)
  77224. {
  77225. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  77226. p += destData.pixelStride;
  77227. }
  77228. }
  77229. }
  77230. else
  77231. {
  77232. for (int y = 0; y < destData.height; ++y)
  77233. {
  77234. uint8* p = destData.getLinePointer (y);
  77235. for (int x = 0; x < destData.width; ++x)
  77236. {
  77237. *p = (uint8) (*p * amountToMultiplyBy);
  77238. p += destData.pixelStride;
  77239. }
  77240. }
  77241. }
  77242. }
  77243. else
  77244. {
  77245. jassertfalse; // can't do this without an alpha-channel!
  77246. }
  77247. }
  77248. void Image::desaturate()
  77249. {
  77250. if (isARGB() || isRGB())
  77251. {
  77252. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  77253. if (isARGB())
  77254. {
  77255. for (int y = 0; y < destData.height; ++y)
  77256. {
  77257. uint8* p = destData.getLinePointer (y);
  77258. for (int x = 0; x < destData.width; ++x)
  77259. {
  77260. ((PixelARGB*) p)->desaturate();
  77261. p += destData.pixelStride;
  77262. }
  77263. }
  77264. }
  77265. else
  77266. {
  77267. for (int y = 0; y < destData.height; ++y)
  77268. {
  77269. uint8* p = destData.getLinePointer (y);
  77270. for (int x = 0; x < destData.width; ++x)
  77271. {
  77272. ((PixelRGB*) p)->desaturate();
  77273. p += destData.pixelStride;
  77274. }
  77275. }
  77276. }
  77277. }
  77278. }
  77279. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  77280. {
  77281. if (hasAlphaChannel())
  77282. {
  77283. const uint8 threshold = (uint8) jlimit (0, 255, roundToInt (alphaThreshold * 255.0f));
  77284. SparseSet<int> pixelsOnRow;
  77285. const BitmapData srcData (*this, 0, 0, getWidth(), getHeight());
  77286. for (int y = 0; y < srcData.height; ++y)
  77287. {
  77288. pixelsOnRow.clear();
  77289. const uint8* lineData = srcData.getLinePointer (y);
  77290. if (isARGB())
  77291. {
  77292. for (int x = 0; x < srcData.width; ++x)
  77293. {
  77294. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  77295. pixelsOnRow.addRange (Range<int> (x, x + 1));
  77296. lineData += srcData.pixelStride;
  77297. }
  77298. }
  77299. else
  77300. {
  77301. for (int x = 0; x < srcData.width; ++x)
  77302. {
  77303. if (*lineData >= threshold)
  77304. pixelsOnRow.addRange (Range<int> (x, x + 1));
  77305. lineData += srcData.pixelStride;
  77306. }
  77307. }
  77308. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  77309. {
  77310. const Range<int> range (pixelsOnRow.getRange (i));
  77311. result.add (Rectangle<int> (range.getStart(), y, range.getLength(), 1));
  77312. }
  77313. result.consolidate();
  77314. }
  77315. }
  77316. else
  77317. {
  77318. result.add (0, 0, getWidth(), getHeight());
  77319. }
  77320. }
  77321. void Image::moveImageSection (int dx, int dy,
  77322. int sx, int sy,
  77323. int w, int h)
  77324. {
  77325. if (dx < 0)
  77326. {
  77327. w += dx;
  77328. sx -= dx;
  77329. dx = 0;
  77330. }
  77331. if (dy < 0)
  77332. {
  77333. h += dy;
  77334. sy -= dy;
  77335. dy = 0;
  77336. }
  77337. if (sx < 0)
  77338. {
  77339. w += sx;
  77340. dx -= sx;
  77341. sx = 0;
  77342. }
  77343. if (sy < 0)
  77344. {
  77345. h += sy;
  77346. dy -= sy;
  77347. sy = 0;
  77348. }
  77349. const int minX = jmin (dx, sx);
  77350. const int minY = jmin (dy, sy);
  77351. w = jmin (w, getWidth() - jmax (sx, dx));
  77352. h = jmin (h, getHeight() - jmax (sy, dy));
  77353. if (w > 0 && h > 0)
  77354. {
  77355. const int maxX = jmax (dx, sx) + w;
  77356. const int maxY = jmax (dy, sy) + h;
  77357. const BitmapData destData (*this, minX, minY, maxX - minX, maxY - minY, true);
  77358. uint8* dst = destData.getPixelPointer (dx - minX, dy - minY);
  77359. const uint8* src = destData.getPixelPointer (sx - minX, sy - minY);
  77360. const int lineSize = destData.pixelStride * w;
  77361. if (dy > sy)
  77362. {
  77363. while (--h >= 0)
  77364. {
  77365. const int offset = h * destData.lineStride;
  77366. memmove (dst + offset, src + offset, lineSize);
  77367. }
  77368. }
  77369. else if (dst != src)
  77370. {
  77371. while (--h >= 0)
  77372. {
  77373. memmove (dst, src, lineSize);
  77374. dst += destData.lineStride;
  77375. src += destData.lineStride;
  77376. }
  77377. }
  77378. }
  77379. }
  77380. END_JUCE_NAMESPACE
  77381. /*** End of inlined file: juce_Image.cpp ***/
  77382. /*** Start of inlined file: juce_ImageCache.cpp ***/
  77383. BEGIN_JUCE_NAMESPACE
  77384. class ImageCache::Pimpl : public Timer,
  77385. public DeletedAtShutdown
  77386. {
  77387. public:
  77388. Pimpl()
  77389. : cacheTimeout (5000)
  77390. {
  77391. }
  77392. ~Pimpl()
  77393. {
  77394. clearSingletonInstance();
  77395. }
  77396. const Image getFromHashCode (const int64 hashCode)
  77397. {
  77398. const ScopedLock sl (lock);
  77399. for (int i = images.size(); --i >= 0;)
  77400. {
  77401. Item* const item = images.getUnchecked(i);
  77402. if (item->hashCode == hashCode)
  77403. return item->image;
  77404. }
  77405. return Image::null;
  77406. }
  77407. void addImageToCache (const Image& image, const int64 hashCode)
  77408. {
  77409. if (image.isValid())
  77410. {
  77411. if (! isTimerRunning())
  77412. startTimer (2000);
  77413. Item* const item = new Item();
  77414. item->hashCode = hashCode;
  77415. item->image = image;
  77416. item->lastUseTime = Time::getApproximateMillisecondCounter();
  77417. const ScopedLock sl (lock);
  77418. images.add (item);
  77419. }
  77420. }
  77421. void timerCallback()
  77422. {
  77423. const uint32 now = Time::getApproximateMillisecondCounter();
  77424. const ScopedLock sl (lock);
  77425. for (int i = images.size(); --i >= 0;)
  77426. {
  77427. Item* const item = images.getUnchecked(i);
  77428. if (item->image.getReferenceCount() <= 1)
  77429. {
  77430. if (now > item->lastUseTime + cacheTimeout || now < item->lastUseTime - 1000)
  77431. images.remove (i);
  77432. }
  77433. else
  77434. {
  77435. item->lastUseTime = now; // multiply-referenced, so this image is still in use.
  77436. }
  77437. }
  77438. if (images.size() == 0)
  77439. stopTimer();
  77440. }
  77441. struct Item
  77442. {
  77443. Image image;
  77444. int64 hashCode;
  77445. uint32 lastUseTime;
  77446. };
  77447. int cacheTimeout;
  77448. juce_DeclareSingleton_SingleThreaded_Minimal (ImageCache::Pimpl);
  77449. private:
  77450. OwnedArray<Item> images;
  77451. CriticalSection lock;
  77452. Pimpl (const Pimpl&);
  77453. Pimpl& operator= (const Pimpl&);
  77454. };
  77455. juce_ImplementSingleton_SingleThreaded (ImageCache::Pimpl);
  77456. const Image ImageCache::getFromHashCode (const int64 hashCode)
  77457. {
  77458. if (Pimpl::getInstanceWithoutCreating() != 0)
  77459. return Pimpl::getInstanceWithoutCreating()->getFromHashCode (hashCode);
  77460. return Image::null;
  77461. }
  77462. void ImageCache::addImageToCache (const Image& image, const int64 hashCode)
  77463. {
  77464. Pimpl::getInstance()->addImageToCache (image, hashCode);
  77465. }
  77466. const Image ImageCache::getFromFile (const File& file)
  77467. {
  77468. const int64 hashCode = file.hashCode64();
  77469. Image image (getFromHashCode (hashCode));
  77470. if (image.isNull())
  77471. {
  77472. image = ImageFileFormat::loadFrom (file);
  77473. addImageToCache (image, hashCode);
  77474. }
  77475. return image;
  77476. }
  77477. const Image ImageCache::getFromMemory (const void* imageData, const int dataSize)
  77478. {
  77479. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  77480. Image image (getFromHashCode (hashCode));
  77481. if (image.isNull())
  77482. {
  77483. image = ImageFileFormat::loadFrom (imageData, dataSize);
  77484. addImageToCache (image, hashCode);
  77485. }
  77486. return image;
  77487. }
  77488. void ImageCache::setCacheTimeout (const int millisecs)
  77489. {
  77490. Pimpl::getInstance()->cacheTimeout = millisecs;
  77491. }
  77492. END_JUCE_NAMESPACE
  77493. /*** End of inlined file: juce_ImageCache.cpp ***/
  77494. /*** Start of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77495. BEGIN_JUCE_NAMESPACE
  77496. ImageConvolutionKernel::ImageConvolutionKernel (const int size_)
  77497. : values (size_ * size_),
  77498. size (size_)
  77499. {
  77500. clear();
  77501. }
  77502. ImageConvolutionKernel::~ImageConvolutionKernel()
  77503. {
  77504. }
  77505. float ImageConvolutionKernel::getKernelValue (const int x, const int y) const throw()
  77506. {
  77507. if (((unsigned int) x) < (unsigned int) size
  77508. && ((unsigned int) y) < (unsigned int) size)
  77509. {
  77510. return values [x + y * size];
  77511. }
  77512. else
  77513. {
  77514. jassertfalse;
  77515. return 0;
  77516. }
  77517. }
  77518. void ImageConvolutionKernel::setKernelValue (const int x, const int y, const float value) throw()
  77519. {
  77520. if (((unsigned int) x) < (unsigned int) size
  77521. && ((unsigned int) y) < (unsigned int) size)
  77522. {
  77523. values [x + y * size] = value;
  77524. }
  77525. else
  77526. {
  77527. jassertfalse;
  77528. }
  77529. }
  77530. void ImageConvolutionKernel::clear()
  77531. {
  77532. for (int i = size * size; --i >= 0;)
  77533. values[i] = 0;
  77534. }
  77535. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum)
  77536. {
  77537. double currentTotal = 0.0;
  77538. for (int i = size * size; --i >= 0;)
  77539. currentTotal += values[i];
  77540. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  77541. }
  77542. void ImageConvolutionKernel::rescaleAllValues (const float multiplier)
  77543. {
  77544. for (int i = size * size; --i >= 0;)
  77545. values[i] *= multiplier;
  77546. }
  77547. void ImageConvolutionKernel::createGaussianBlur (const float radius)
  77548. {
  77549. const double radiusFactor = -1.0 / (radius * radius * 2);
  77550. const int centre = size >> 1;
  77551. for (int y = size; --y >= 0;)
  77552. {
  77553. for (int x = size; --x >= 0;)
  77554. {
  77555. const int cx = x - centre;
  77556. const int cy = y - centre;
  77557. values [x + y * size] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  77558. }
  77559. }
  77560. setOverallSum (1.0f);
  77561. }
  77562. void ImageConvolutionKernel::applyToImage (Image& destImage,
  77563. const Image& sourceImage,
  77564. const Rectangle<int>& destinationArea) const
  77565. {
  77566. if (sourceImage == destImage)
  77567. {
  77568. destImage.duplicateIfShared();
  77569. }
  77570. else
  77571. {
  77572. if (sourceImage.getWidth() != destImage.getWidth()
  77573. || sourceImage.getHeight() != destImage.getHeight()
  77574. || sourceImage.getFormat() != destImage.getFormat())
  77575. {
  77576. jassertfalse;
  77577. return;
  77578. }
  77579. }
  77580. const Rectangle<int> area (destinationArea.getIntersection (destImage.getBounds()));
  77581. if (area.isEmpty())
  77582. return;
  77583. const int right = area.getRight();
  77584. const int bottom = area.getBottom();
  77585. const Image::BitmapData destData (destImage, area.getX(), area.getY(), area.getWidth(), area.getHeight(), true);
  77586. uint8* line = destData.data;
  77587. const Image::BitmapData srcData (sourceImage, false);
  77588. if (destData.pixelStride == 4)
  77589. {
  77590. for (int y = area.getY(); y < bottom; ++y)
  77591. {
  77592. uint8* dest = line;
  77593. line += destData.lineStride;
  77594. for (int x = area.getX(); x < right; ++x)
  77595. {
  77596. float c1 = 0;
  77597. float c2 = 0;
  77598. float c3 = 0;
  77599. float c4 = 0;
  77600. for (int yy = 0; yy < size; ++yy)
  77601. {
  77602. const int sy = y + yy - (size >> 1);
  77603. if (sy >= srcData.height)
  77604. break;
  77605. if (sy >= 0)
  77606. {
  77607. int sx = x - (size >> 1);
  77608. const uint8* src = srcData.getPixelPointer (sx, sy);
  77609. for (int xx = 0; xx < size; ++xx)
  77610. {
  77611. if (sx >= srcData.width)
  77612. break;
  77613. if (sx >= 0)
  77614. {
  77615. const float kernelMult = values [xx + yy * size];
  77616. c1 += kernelMult * *src++;
  77617. c2 += kernelMult * *src++;
  77618. c3 += kernelMult * *src++;
  77619. c4 += kernelMult * *src++;
  77620. }
  77621. else
  77622. {
  77623. src += 4;
  77624. }
  77625. ++sx;
  77626. }
  77627. }
  77628. }
  77629. *dest++ = (uint8) jmin (0xff, roundToInt (c1));
  77630. *dest++ = (uint8) jmin (0xff, roundToInt (c2));
  77631. *dest++ = (uint8) jmin (0xff, roundToInt (c3));
  77632. *dest++ = (uint8) jmin (0xff, roundToInt (c4));
  77633. }
  77634. }
  77635. }
  77636. else if (destData.pixelStride == 3)
  77637. {
  77638. for (int y = area.getY(); y < bottom; ++y)
  77639. {
  77640. uint8* dest = line;
  77641. line += destData.lineStride;
  77642. for (int x = area.getX(); x < right; ++x)
  77643. {
  77644. float c1 = 0;
  77645. float c2 = 0;
  77646. float c3 = 0;
  77647. for (int yy = 0; yy < size; ++yy)
  77648. {
  77649. const int sy = y + yy - (size >> 1);
  77650. if (sy >= srcData.height)
  77651. break;
  77652. if (sy >= 0)
  77653. {
  77654. int sx = x - (size >> 1);
  77655. const uint8* src = srcData.getPixelPointer (sx, sy);
  77656. for (int xx = 0; xx < size; ++xx)
  77657. {
  77658. if (sx >= srcData.width)
  77659. break;
  77660. if (sx >= 0)
  77661. {
  77662. const float kernelMult = values [xx + yy * size];
  77663. c1 += kernelMult * *src++;
  77664. c2 += kernelMult * *src++;
  77665. c3 += kernelMult * *src++;
  77666. }
  77667. else
  77668. {
  77669. src += 3;
  77670. }
  77671. ++sx;
  77672. }
  77673. }
  77674. }
  77675. *dest++ = (uint8) roundToInt (c1);
  77676. *dest++ = (uint8) roundToInt (c2);
  77677. *dest++ = (uint8) roundToInt (c3);
  77678. }
  77679. }
  77680. }
  77681. }
  77682. END_JUCE_NAMESPACE
  77683. /*** End of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77684. /*** Start of inlined file: juce_ImageFileFormat.cpp ***/
  77685. BEGIN_JUCE_NAMESPACE
  77686. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  77687. {
  77688. static PNGImageFormat png;
  77689. static JPEGImageFormat jpg;
  77690. static GIFImageFormat gif;
  77691. ImageFileFormat* formats[4];
  77692. int numFormats = 0;
  77693. formats [numFormats++] = &png;
  77694. formats [numFormats++] = &jpg;
  77695. formats [numFormats++] = &gif;
  77696. const int64 streamPos = input.getPosition();
  77697. for (int i = 0; i < numFormats; ++i)
  77698. {
  77699. const bool found = formats[i]->canUnderstand (input);
  77700. input.setPosition (streamPos);
  77701. if (found)
  77702. return formats[i];
  77703. }
  77704. return 0;
  77705. }
  77706. const Image ImageFileFormat::loadFrom (InputStream& input)
  77707. {
  77708. ImageFileFormat* const format = findImageFormatForStream (input);
  77709. if (format != 0)
  77710. return format->decodeImage (input);
  77711. return Image::null;
  77712. }
  77713. const Image ImageFileFormat::loadFrom (const File& file)
  77714. {
  77715. InputStream* const in = file.createInputStream();
  77716. if (in != 0)
  77717. {
  77718. BufferedInputStream b (in, 8192, true);
  77719. return loadFrom (b);
  77720. }
  77721. return Image::null;
  77722. }
  77723. const Image ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  77724. {
  77725. if (rawData != 0 && numBytes > 4)
  77726. {
  77727. MemoryInputStream stream (rawData, numBytes, false);
  77728. return loadFrom (stream);
  77729. }
  77730. return Image::null;
  77731. }
  77732. END_JUCE_NAMESPACE
  77733. /*** End of inlined file: juce_ImageFileFormat.cpp ***/
  77734. /*** Start of inlined file: juce_GIFLoader.cpp ***/
  77735. BEGIN_JUCE_NAMESPACE
  77736. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  77737. const Image juce_loadWithCoreImage (InputStream& input);
  77738. #else
  77739. class GIFLoader
  77740. {
  77741. public:
  77742. GIFLoader (InputStream& in)
  77743. : input (in),
  77744. dataBlockIsZero (false),
  77745. fresh (false),
  77746. finished (false)
  77747. {
  77748. currentBit = lastBit = lastByteIndex = 0;
  77749. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  77750. firstcode = oldcode = 0;
  77751. clearCode = end_code = 0;
  77752. int imageWidth, imageHeight;
  77753. int transparent = -1;
  77754. if (! getSizeFromHeader (imageWidth, imageHeight))
  77755. return;
  77756. if ((imageWidth <= 0) || (imageHeight <= 0))
  77757. return;
  77758. unsigned char buf [16];
  77759. if (in.read (buf, 3) != 3)
  77760. return;
  77761. int numColours = 2 << (buf[0] & 7);
  77762. if ((buf[0] & 0x80) != 0)
  77763. readPalette (numColours);
  77764. for (;;)
  77765. {
  77766. if (input.read (buf, 1) != 1 || buf[0] == ';')
  77767. break;
  77768. if (buf[0] == '!')
  77769. {
  77770. if (input.read (buf, 1) != 1)
  77771. break;
  77772. if (processExtension (buf[0], transparent) < 0)
  77773. break;
  77774. continue;
  77775. }
  77776. if (buf[0] != ',')
  77777. continue;
  77778. if (input.read (buf, 9) != 9)
  77779. break;
  77780. imageWidth = makeWord (buf[4], buf[5]);
  77781. imageHeight = makeWord (buf[6], buf[7]);
  77782. numColours = 2 << (buf[8] & 7);
  77783. if ((buf[8] & 0x80) != 0)
  77784. if (! readPalette (numColours))
  77785. break;
  77786. image = Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  77787. imageWidth, imageHeight, (transparent >= 0));
  77788. readImage ((buf[8] & 0x40) != 0, transparent);
  77789. break;
  77790. }
  77791. }
  77792. ~GIFLoader() {}
  77793. Image image;
  77794. private:
  77795. InputStream& input;
  77796. uint8 buffer [300];
  77797. uint8 palette [256][4];
  77798. bool dataBlockIsZero, fresh, finished;
  77799. int currentBit, lastBit, lastByteIndex;
  77800. int codeSize, setCodeSize;
  77801. int maxCode, maxCodeSize;
  77802. int firstcode, oldcode;
  77803. int clearCode, end_code;
  77804. enum { maxGifCode = 1 << 12 };
  77805. int table [2] [maxGifCode];
  77806. int stack [2 * maxGifCode];
  77807. int *sp;
  77808. bool getSizeFromHeader (int& w, int& h)
  77809. {
  77810. char b[8];
  77811. if (input.read (b, 6) == 6)
  77812. {
  77813. if ((strncmp ("GIF87a", b, 6) == 0)
  77814. || (strncmp ("GIF89a", b, 6) == 0))
  77815. {
  77816. if (input.read (b, 4) == 4)
  77817. {
  77818. w = makeWord (b[0], b[1]);
  77819. h = makeWord (b[2], b[3]);
  77820. return true;
  77821. }
  77822. }
  77823. }
  77824. return false;
  77825. }
  77826. bool readPalette (const int numCols)
  77827. {
  77828. unsigned char rgb[4];
  77829. for (int i = 0; i < numCols; ++i)
  77830. {
  77831. input.read (rgb, 3);
  77832. palette [i][0] = rgb[0];
  77833. palette [i][1] = rgb[1];
  77834. palette [i][2] = rgb[2];
  77835. palette [i][3] = 0xff;
  77836. }
  77837. return true;
  77838. }
  77839. int readDataBlock (unsigned char* dest)
  77840. {
  77841. unsigned char n;
  77842. if (input.read (&n, 1) == 1)
  77843. {
  77844. dataBlockIsZero = (n == 0);
  77845. if (dataBlockIsZero || (input.read (dest, n) == n))
  77846. return n;
  77847. }
  77848. return -1;
  77849. }
  77850. int processExtension (const int type, int& transparent)
  77851. {
  77852. unsigned char b [300];
  77853. int n = 0;
  77854. if (type == 0xf9)
  77855. {
  77856. n = readDataBlock (b);
  77857. if (n < 0)
  77858. return 1;
  77859. if ((b[0] & 0x1) != 0)
  77860. transparent = b[3];
  77861. }
  77862. do
  77863. {
  77864. n = readDataBlock (b);
  77865. }
  77866. while (n > 0);
  77867. return n;
  77868. }
  77869. int readLZWByte (const bool initialise, const int inputCodeSize)
  77870. {
  77871. int code, incode, i;
  77872. if (initialise)
  77873. {
  77874. setCodeSize = inputCodeSize;
  77875. codeSize = setCodeSize + 1;
  77876. clearCode = 1 << setCodeSize;
  77877. end_code = clearCode + 1;
  77878. maxCodeSize = 2 * clearCode;
  77879. maxCode = clearCode + 2;
  77880. getCode (0, true);
  77881. fresh = true;
  77882. for (i = 0; i < clearCode; ++i)
  77883. {
  77884. table[0][i] = 0;
  77885. table[1][i] = i;
  77886. }
  77887. for (; i < maxGifCode; ++i)
  77888. {
  77889. table[0][i] = 0;
  77890. table[1][i] = 0;
  77891. }
  77892. sp = stack;
  77893. return 0;
  77894. }
  77895. else if (fresh)
  77896. {
  77897. fresh = false;
  77898. do
  77899. {
  77900. firstcode = oldcode
  77901. = getCode (codeSize, false);
  77902. }
  77903. while (firstcode == clearCode);
  77904. return firstcode;
  77905. }
  77906. if (sp > stack)
  77907. return *--sp;
  77908. while ((code = getCode (codeSize, false)) >= 0)
  77909. {
  77910. if (code == clearCode)
  77911. {
  77912. for (i = 0; i < clearCode; ++i)
  77913. {
  77914. table[0][i] = 0;
  77915. table[1][i] = i;
  77916. }
  77917. for (; i < maxGifCode; ++i)
  77918. {
  77919. table[0][i] = 0;
  77920. table[1][i] = 0;
  77921. }
  77922. codeSize = setCodeSize + 1;
  77923. maxCodeSize = 2 * clearCode;
  77924. maxCode = clearCode + 2;
  77925. sp = stack;
  77926. firstcode = oldcode = getCode (codeSize, false);
  77927. return firstcode;
  77928. }
  77929. else if (code == end_code)
  77930. {
  77931. if (dataBlockIsZero)
  77932. return -2;
  77933. unsigned char buf [260];
  77934. int n;
  77935. while ((n = readDataBlock (buf)) > 0)
  77936. {}
  77937. if (n != 0)
  77938. return -2;
  77939. }
  77940. incode = code;
  77941. if (code >= maxCode)
  77942. {
  77943. *sp++ = firstcode;
  77944. code = oldcode;
  77945. }
  77946. while (code >= clearCode)
  77947. {
  77948. *sp++ = table[1][code];
  77949. if (code == table[0][code])
  77950. return -2;
  77951. code = table[0][code];
  77952. }
  77953. *sp++ = firstcode = table[1][code];
  77954. if ((code = maxCode) < maxGifCode)
  77955. {
  77956. table[0][code] = oldcode;
  77957. table[1][code] = firstcode;
  77958. ++maxCode;
  77959. if ((maxCode >= maxCodeSize)
  77960. && (maxCodeSize < maxGifCode))
  77961. {
  77962. maxCodeSize <<= 1;
  77963. ++codeSize;
  77964. }
  77965. }
  77966. oldcode = incode;
  77967. if (sp > stack)
  77968. return *--sp;
  77969. }
  77970. return code;
  77971. }
  77972. int getCode (const int codeSize_, const bool initialise)
  77973. {
  77974. if (initialise)
  77975. {
  77976. currentBit = 0;
  77977. lastBit = 0;
  77978. finished = false;
  77979. return 0;
  77980. }
  77981. if ((currentBit + codeSize_) >= lastBit)
  77982. {
  77983. if (finished)
  77984. return -1;
  77985. buffer[0] = buffer [lastByteIndex - 2];
  77986. buffer[1] = buffer [lastByteIndex - 1];
  77987. const int n = readDataBlock (&buffer[2]);
  77988. if (n == 0)
  77989. finished = true;
  77990. lastByteIndex = 2 + n;
  77991. currentBit = (currentBit - lastBit) + 16;
  77992. lastBit = (2 + n) * 8 ;
  77993. }
  77994. int result = 0;
  77995. int i = currentBit;
  77996. for (int j = 0; j < codeSize_; ++j)
  77997. {
  77998. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  77999. ++i;
  78000. }
  78001. currentBit += codeSize_;
  78002. return result;
  78003. }
  78004. bool readImage (const int interlace, const int transparent)
  78005. {
  78006. unsigned char c;
  78007. if (input.read (&c, 1) != 1
  78008. || readLZWByte (true, c) < 0)
  78009. return false;
  78010. if (transparent >= 0)
  78011. {
  78012. palette [transparent][0] = 0;
  78013. palette [transparent][1] = 0;
  78014. palette [transparent][2] = 0;
  78015. palette [transparent][3] = 0;
  78016. }
  78017. int index;
  78018. int xpos = 0, ypos = 0, pass = 0;
  78019. const Image::BitmapData destData (image, true);
  78020. uint8* p = destData.data;
  78021. const bool hasAlpha = image.hasAlphaChannel();
  78022. while ((index = readLZWByte (false, c)) >= 0)
  78023. {
  78024. const uint8* const paletteEntry = palette [index];
  78025. if (hasAlpha)
  78026. {
  78027. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  78028. paletteEntry[0],
  78029. paletteEntry[1],
  78030. paletteEntry[2]);
  78031. ((PixelARGB*) p)->premultiply();
  78032. }
  78033. else
  78034. {
  78035. ((PixelRGB*) p)->setARGB (0,
  78036. paletteEntry[0],
  78037. paletteEntry[1],
  78038. paletteEntry[2]);
  78039. }
  78040. p += destData.pixelStride;
  78041. ++xpos;
  78042. if (xpos == destData.width)
  78043. {
  78044. xpos = 0;
  78045. if (interlace)
  78046. {
  78047. switch (pass)
  78048. {
  78049. case 0:
  78050. case 1: ypos += 8; break;
  78051. case 2: ypos += 4; break;
  78052. case 3: ypos += 2; break;
  78053. }
  78054. while (ypos >= destData.height)
  78055. {
  78056. ++pass;
  78057. switch (pass)
  78058. {
  78059. case 1: ypos = 4; break;
  78060. case 2: ypos = 2; break;
  78061. case 3: ypos = 1; break;
  78062. default: return true;
  78063. }
  78064. }
  78065. }
  78066. else
  78067. {
  78068. ++ypos;
  78069. }
  78070. p = destData.getPixelPointer (xpos, ypos);
  78071. }
  78072. if (ypos >= destData.height)
  78073. break;
  78074. }
  78075. return true;
  78076. }
  78077. static inline int makeWord (const uint8 a, const uint8 b) { return (b << 8) | a; }
  78078. GIFLoader (const GIFLoader&);
  78079. GIFLoader& operator= (const GIFLoader&);
  78080. };
  78081. #endif
  78082. GIFImageFormat::GIFImageFormat() {}
  78083. GIFImageFormat::~GIFImageFormat() {}
  78084. const String GIFImageFormat::getFormatName() { return "GIF"; }
  78085. bool GIFImageFormat::canUnderstand (InputStream& in)
  78086. {
  78087. char header [4];
  78088. return (in.read (header, sizeof (header)) == sizeof (header))
  78089. && header[0] == 'G'
  78090. && header[1] == 'I'
  78091. && header[2] == 'F';
  78092. }
  78093. const Image GIFImageFormat::decodeImage (InputStream& in)
  78094. {
  78095. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  78096. return juce_loadWithCoreImage (in);
  78097. #else
  78098. const ScopedPointer <GIFLoader> loader (new GIFLoader (in));
  78099. return loader->image;
  78100. #endif
  78101. }
  78102. bool GIFImageFormat::writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  78103. {
  78104. jassertfalse; // writing isn't implemented for GIFs!
  78105. return false;
  78106. }
  78107. END_JUCE_NAMESPACE
  78108. /*** End of inlined file: juce_GIFLoader.cpp ***/
  78109. #endif
  78110. //==============================================================================
  78111. // some files include lots of library code, so leave them to the end to avoid cluttering
  78112. // up the build for the clean files.
  78113. #if JUCE_BUILD_CORE
  78114. /*** Start of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  78115. namespace zlibNamespace
  78116. {
  78117. #if JUCE_INCLUDE_ZLIB_CODE
  78118. #undef OS_CODE
  78119. #undef fdopen
  78120. /*** Start of inlined file: zlib.h ***/
  78121. #ifndef ZLIB_H
  78122. #define ZLIB_H
  78123. /*** Start of inlined file: zconf.h ***/
  78124. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  78125. #ifndef ZCONF_H
  78126. #define ZCONF_H
  78127. // *** Just a few hacks here to make it compile nicely with Juce..
  78128. #define Z_PREFIX 1
  78129. #undef __MACTYPES__
  78130. #ifdef _MSC_VER
  78131. #pragma warning (disable : 4131 4127 4244 4267)
  78132. #endif
  78133. /*
  78134. * If you *really* need a unique prefix for all types and library functions,
  78135. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  78136. */
  78137. #ifdef Z_PREFIX
  78138. # define deflateInit_ z_deflateInit_
  78139. # define deflate z_deflate
  78140. # define deflateEnd z_deflateEnd
  78141. # define inflateInit_ z_inflateInit_
  78142. # define inflate z_inflate
  78143. # define inflateEnd z_inflateEnd
  78144. # define inflatePrime z_inflatePrime
  78145. # define inflateGetHeader z_inflateGetHeader
  78146. # define adler32_combine z_adler32_combine
  78147. # define crc32_combine z_crc32_combine
  78148. # define deflateInit2_ z_deflateInit2_
  78149. # define deflateSetDictionary z_deflateSetDictionary
  78150. # define deflateCopy z_deflateCopy
  78151. # define deflateReset z_deflateReset
  78152. # define deflateParams z_deflateParams
  78153. # define deflateBound z_deflateBound
  78154. # define deflatePrime z_deflatePrime
  78155. # define inflateInit2_ z_inflateInit2_
  78156. # define inflateSetDictionary z_inflateSetDictionary
  78157. # define inflateSync z_inflateSync
  78158. # define inflateSyncPoint z_inflateSyncPoint
  78159. # define inflateCopy z_inflateCopy
  78160. # define inflateReset z_inflateReset
  78161. # define inflateBack z_inflateBack
  78162. # define inflateBackEnd z_inflateBackEnd
  78163. # define compress z_compress
  78164. # define compress2 z_compress2
  78165. # define compressBound z_compressBound
  78166. # define uncompress z_uncompress
  78167. # define adler32 z_adler32
  78168. # define crc32 z_crc32
  78169. # define get_crc_table z_get_crc_table
  78170. # define zError z_zError
  78171. # define alloc_func z_alloc_func
  78172. # define free_func z_free_func
  78173. # define in_func z_in_func
  78174. # define out_func z_out_func
  78175. # define Byte z_Byte
  78176. # define uInt z_uInt
  78177. # define uLong z_uLong
  78178. # define Bytef z_Bytef
  78179. # define charf z_charf
  78180. # define intf z_intf
  78181. # define uIntf z_uIntf
  78182. # define uLongf z_uLongf
  78183. # define voidpf z_voidpf
  78184. # define voidp z_voidp
  78185. #endif
  78186. #if defined(__MSDOS__) && !defined(MSDOS)
  78187. # define MSDOS
  78188. #endif
  78189. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  78190. # define OS2
  78191. #endif
  78192. #if defined(_WINDOWS) && !defined(WINDOWS)
  78193. # define WINDOWS
  78194. #endif
  78195. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  78196. # ifndef WIN32
  78197. # define WIN32
  78198. # endif
  78199. #endif
  78200. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  78201. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  78202. # ifndef SYS16BIT
  78203. # define SYS16BIT
  78204. # endif
  78205. # endif
  78206. #endif
  78207. /*
  78208. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  78209. * than 64k bytes at a time (needed on systems with 16-bit int).
  78210. */
  78211. #ifdef SYS16BIT
  78212. # define MAXSEG_64K
  78213. #endif
  78214. #ifdef MSDOS
  78215. # define UNALIGNED_OK
  78216. #endif
  78217. #ifdef __STDC_VERSION__
  78218. # ifndef STDC
  78219. # define STDC
  78220. # endif
  78221. # if __STDC_VERSION__ >= 199901L
  78222. # ifndef STDC99
  78223. # define STDC99
  78224. # endif
  78225. # endif
  78226. #endif
  78227. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  78228. # define STDC
  78229. #endif
  78230. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  78231. # define STDC
  78232. #endif
  78233. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  78234. # define STDC
  78235. #endif
  78236. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  78237. # define STDC
  78238. #endif
  78239. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  78240. # define STDC
  78241. #endif
  78242. #ifndef STDC
  78243. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  78244. # define const /* note: need a more gentle solution here */
  78245. # endif
  78246. #endif
  78247. /* Some Mac compilers merge all .h files incorrectly: */
  78248. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  78249. # define NO_DUMMY_DECL
  78250. #endif
  78251. /* Maximum value for memLevel in deflateInit2 */
  78252. #ifndef MAX_MEM_LEVEL
  78253. # ifdef MAXSEG_64K
  78254. # define MAX_MEM_LEVEL 8
  78255. # else
  78256. # define MAX_MEM_LEVEL 9
  78257. # endif
  78258. #endif
  78259. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  78260. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  78261. * created by gzip. (Files created by minigzip can still be extracted by
  78262. * gzip.)
  78263. */
  78264. #ifndef MAX_WBITS
  78265. # define MAX_WBITS 15 /* 32K LZ77 window */
  78266. #endif
  78267. /* The memory requirements for deflate are (in bytes):
  78268. (1 << (windowBits+2)) + (1 << (memLevel+9))
  78269. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  78270. plus a few kilobytes for small objects. For example, if you want to reduce
  78271. the default memory requirements from 256K to 128K, compile with
  78272. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  78273. Of course this will generally degrade compression (there's no free lunch).
  78274. The memory requirements for inflate are (in bytes) 1 << windowBits
  78275. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  78276. for small objects.
  78277. */
  78278. /* Type declarations */
  78279. #ifndef OF /* function prototypes */
  78280. # ifdef STDC
  78281. # define OF(args) args
  78282. # else
  78283. # define OF(args) ()
  78284. # endif
  78285. #endif
  78286. /* The following definitions for FAR are needed only for MSDOS mixed
  78287. * model programming (small or medium model with some far allocations).
  78288. * This was tested only with MSC; for other MSDOS compilers you may have
  78289. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  78290. * just define FAR to be empty.
  78291. */
  78292. #ifdef SYS16BIT
  78293. # if defined(M_I86SM) || defined(M_I86MM)
  78294. /* MSC small or medium model */
  78295. # define SMALL_MEDIUM
  78296. # ifdef _MSC_VER
  78297. # define FAR _far
  78298. # else
  78299. # define FAR far
  78300. # endif
  78301. # endif
  78302. # if (defined(__SMALL__) || defined(__MEDIUM__))
  78303. /* Turbo C small or medium model */
  78304. # define SMALL_MEDIUM
  78305. # ifdef __BORLANDC__
  78306. # define FAR _far
  78307. # else
  78308. # define FAR far
  78309. # endif
  78310. # endif
  78311. #endif
  78312. #if defined(WINDOWS) || defined(WIN32)
  78313. /* If building or using zlib as a DLL, define ZLIB_DLL.
  78314. * This is not mandatory, but it offers a little performance increase.
  78315. */
  78316. # ifdef ZLIB_DLL
  78317. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  78318. # ifdef ZLIB_INTERNAL
  78319. # define ZEXTERN extern __declspec(dllexport)
  78320. # else
  78321. # define ZEXTERN extern __declspec(dllimport)
  78322. # endif
  78323. # endif
  78324. # endif /* ZLIB_DLL */
  78325. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  78326. * define ZLIB_WINAPI.
  78327. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  78328. */
  78329. # ifdef ZLIB_WINAPI
  78330. # ifdef FAR
  78331. # undef FAR
  78332. # endif
  78333. # include <windows.h>
  78334. /* No need for _export, use ZLIB.DEF instead. */
  78335. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  78336. # define ZEXPORT WINAPI
  78337. # ifdef WIN32
  78338. # define ZEXPORTVA WINAPIV
  78339. # else
  78340. # define ZEXPORTVA FAR CDECL
  78341. # endif
  78342. # endif
  78343. #endif
  78344. #if defined (__BEOS__)
  78345. # ifdef ZLIB_DLL
  78346. # ifdef ZLIB_INTERNAL
  78347. # define ZEXPORT __declspec(dllexport)
  78348. # define ZEXPORTVA __declspec(dllexport)
  78349. # else
  78350. # define ZEXPORT __declspec(dllimport)
  78351. # define ZEXPORTVA __declspec(dllimport)
  78352. # endif
  78353. # endif
  78354. #endif
  78355. #ifndef ZEXTERN
  78356. # define ZEXTERN extern
  78357. #endif
  78358. #ifndef ZEXPORT
  78359. # define ZEXPORT
  78360. #endif
  78361. #ifndef ZEXPORTVA
  78362. # define ZEXPORTVA
  78363. #endif
  78364. #ifndef FAR
  78365. # define FAR
  78366. #endif
  78367. #if !defined(__MACTYPES__)
  78368. typedef unsigned char Byte; /* 8 bits */
  78369. #endif
  78370. typedef unsigned int uInt; /* 16 bits or more */
  78371. typedef unsigned long uLong; /* 32 bits or more */
  78372. #ifdef SMALL_MEDIUM
  78373. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  78374. # define Bytef Byte FAR
  78375. #else
  78376. typedef Byte FAR Bytef;
  78377. #endif
  78378. typedef char FAR charf;
  78379. typedef int FAR intf;
  78380. typedef uInt FAR uIntf;
  78381. typedef uLong FAR uLongf;
  78382. #ifdef STDC
  78383. typedef void const *voidpc;
  78384. typedef void FAR *voidpf;
  78385. typedef void *voidp;
  78386. #else
  78387. typedef Byte const *voidpc;
  78388. typedef Byte FAR *voidpf;
  78389. typedef Byte *voidp;
  78390. #endif
  78391. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  78392. # include <sys/types.h> /* for off_t */
  78393. # include <unistd.h> /* for SEEK_* and off_t */
  78394. # ifdef VMS
  78395. # include <unixio.h> /* for off_t */
  78396. # endif
  78397. # define z_off_t off_t
  78398. #endif
  78399. #ifndef SEEK_SET
  78400. # define SEEK_SET 0 /* Seek from beginning of file. */
  78401. # define SEEK_CUR 1 /* Seek from current position. */
  78402. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  78403. #endif
  78404. #ifndef z_off_t
  78405. # define z_off_t long
  78406. #endif
  78407. #if defined(__OS400__)
  78408. # define NO_vsnprintf
  78409. #endif
  78410. #if defined(__MVS__)
  78411. # define NO_vsnprintf
  78412. # ifdef FAR
  78413. # undef FAR
  78414. # endif
  78415. #endif
  78416. /* MVS linker does not support external names larger than 8 bytes */
  78417. #if defined(__MVS__)
  78418. # pragma map(deflateInit_,"DEIN")
  78419. # pragma map(deflateInit2_,"DEIN2")
  78420. # pragma map(deflateEnd,"DEEND")
  78421. # pragma map(deflateBound,"DEBND")
  78422. # pragma map(inflateInit_,"ININ")
  78423. # pragma map(inflateInit2_,"ININ2")
  78424. # pragma map(inflateEnd,"INEND")
  78425. # pragma map(inflateSync,"INSY")
  78426. # pragma map(inflateSetDictionary,"INSEDI")
  78427. # pragma map(compressBound,"CMBND")
  78428. # pragma map(inflate_table,"INTABL")
  78429. # pragma map(inflate_fast,"INFA")
  78430. # pragma map(inflate_copyright,"INCOPY")
  78431. #endif
  78432. #endif /* ZCONF_H */
  78433. /*** End of inlined file: zconf.h ***/
  78434. #ifdef __cplusplus
  78435. //extern "C" {
  78436. #endif
  78437. #define ZLIB_VERSION "1.2.3"
  78438. #define ZLIB_VERNUM 0x1230
  78439. /*
  78440. The 'zlib' compression library provides in-memory compression and
  78441. decompression functions, including integrity checks of the uncompressed
  78442. data. This version of the library supports only one compression method
  78443. (deflation) but other algorithms will be added later and will have the same
  78444. stream interface.
  78445. Compression can be done in a single step if the buffers are large
  78446. enough (for example if an input file is mmap'ed), or can be done by
  78447. repeated calls of the compression function. In the latter case, the
  78448. application must provide more input and/or consume the output
  78449. (providing more output space) before each call.
  78450. The compressed data format used by default by the in-memory functions is
  78451. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  78452. around a deflate stream, which is itself documented in RFC 1951.
  78453. The library also supports reading and writing files in gzip (.gz) format
  78454. with an interface similar to that of stdio using the functions that start
  78455. with "gz". The gzip format is different from the zlib format. gzip is a
  78456. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  78457. This library can optionally read and write gzip streams in memory as well.
  78458. The zlib format was designed to be compact and fast for use in memory
  78459. and on communications channels. The gzip format was designed for single-
  78460. file compression on file systems, has a larger header than zlib to maintain
  78461. directory information, and uses a different, slower check method than zlib.
  78462. The library does not install any signal handler. The decoder checks
  78463. the consistency of the compressed data, so the library should never
  78464. crash even in case of corrupted input.
  78465. */
  78466. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  78467. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  78468. struct internal_state;
  78469. typedef struct z_stream_s {
  78470. Bytef *next_in; /* next input byte */
  78471. uInt avail_in; /* number of bytes available at next_in */
  78472. uLong total_in; /* total nb of input bytes read so far */
  78473. Bytef *next_out; /* next output byte should be put there */
  78474. uInt avail_out; /* remaining free space at next_out */
  78475. uLong total_out; /* total nb of bytes output so far */
  78476. char *msg; /* last error message, NULL if no error */
  78477. struct internal_state FAR *state; /* not visible by applications */
  78478. alloc_func zalloc; /* used to allocate the internal state */
  78479. free_func zfree; /* used to free the internal state */
  78480. voidpf opaque; /* private data object passed to zalloc and zfree */
  78481. int data_type; /* best guess about the data type: binary or text */
  78482. uLong adler; /* adler32 value of the uncompressed data */
  78483. uLong reserved; /* reserved for future use */
  78484. } z_stream;
  78485. typedef z_stream FAR *z_streamp;
  78486. /*
  78487. gzip header information passed to and from zlib routines. See RFC 1952
  78488. for more details on the meanings of these fields.
  78489. */
  78490. typedef struct gz_header_s {
  78491. int text; /* true if compressed data believed to be text */
  78492. uLong time; /* modification time */
  78493. int xflags; /* extra flags (not used when writing a gzip file) */
  78494. int os; /* operating system */
  78495. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  78496. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  78497. uInt extra_max; /* space at extra (only when reading header) */
  78498. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  78499. uInt name_max; /* space at name (only when reading header) */
  78500. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  78501. uInt comm_max; /* space at comment (only when reading header) */
  78502. int hcrc; /* true if there was or will be a header crc */
  78503. int done; /* true when done reading gzip header (not used
  78504. when writing a gzip file) */
  78505. } gz_header;
  78506. typedef gz_header FAR *gz_headerp;
  78507. /*
  78508. The application must update next_in and avail_in when avail_in has
  78509. dropped to zero. It must update next_out and avail_out when avail_out
  78510. has dropped to zero. The application must initialize zalloc, zfree and
  78511. opaque before calling the init function. All other fields are set by the
  78512. compression library and must not be updated by the application.
  78513. The opaque value provided by the application will be passed as the first
  78514. parameter for calls of zalloc and zfree. This can be useful for custom
  78515. memory management. The compression library attaches no meaning to the
  78516. opaque value.
  78517. zalloc must return Z_NULL if there is not enough memory for the object.
  78518. If zlib is used in a multi-threaded application, zalloc and zfree must be
  78519. thread safe.
  78520. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  78521. exactly 65536 bytes, but will not be required to allocate more than this
  78522. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  78523. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  78524. have their offset normalized to zero. The default allocation function
  78525. provided by this library ensures this (see zutil.c). To reduce memory
  78526. requirements and avoid any allocation of 64K objects, at the expense of
  78527. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  78528. The fields total_in and total_out can be used for statistics or
  78529. progress reports. After compression, total_in holds the total size of
  78530. the uncompressed data and may be saved for use in the decompressor
  78531. (particularly if the decompressor wants to decompress everything in
  78532. a single step).
  78533. */
  78534. /* constants */
  78535. #define Z_NO_FLUSH 0
  78536. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  78537. #define Z_SYNC_FLUSH 2
  78538. #define Z_FULL_FLUSH 3
  78539. #define Z_FINISH 4
  78540. #define Z_BLOCK 5
  78541. /* Allowed flush values; see deflate() and inflate() below for details */
  78542. #define Z_OK 0
  78543. #define Z_STREAM_END 1
  78544. #define Z_NEED_DICT 2
  78545. #define Z_ERRNO (-1)
  78546. #define Z_STREAM_ERROR (-2)
  78547. #define Z_DATA_ERROR (-3)
  78548. #define Z_MEM_ERROR (-4)
  78549. #define Z_BUF_ERROR (-5)
  78550. #define Z_VERSION_ERROR (-6)
  78551. /* Return codes for the compression/decompression functions. Negative
  78552. * values are errors, positive values are used for special but normal events.
  78553. */
  78554. #define Z_NO_COMPRESSION 0
  78555. #define Z_BEST_SPEED 1
  78556. #define Z_BEST_COMPRESSION 9
  78557. #define Z_DEFAULT_COMPRESSION (-1)
  78558. /* compression levels */
  78559. #define Z_FILTERED 1
  78560. #define Z_HUFFMAN_ONLY 2
  78561. #define Z_RLE 3
  78562. #define Z_FIXED 4
  78563. #define Z_DEFAULT_STRATEGY 0
  78564. /* compression strategy; see deflateInit2() below for details */
  78565. #define Z_BINARY 0
  78566. #define Z_TEXT 1
  78567. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  78568. #define Z_UNKNOWN 2
  78569. /* Possible values of the data_type field (though see inflate()) */
  78570. #define Z_DEFLATED 8
  78571. /* The deflate compression method (the only one supported in this version) */
  78572. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  78573. #define zlib_version zlibVersion()
  78574. /* for compatibility with versions < 1.0.2 */
  78575. /* basic functions */
  78576. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  78577. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  78578. If the first character differs, the library code actually used is
  78579. not compatible with the zlib.h header file used by the application.
  78580. This check is automatically made by deflateInit and inflateInit.
  78581. */
  78582. /*
  78583. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  78584. Initializes the internal stream state for compression. The fields
  78585. zalloc, zfree and opaque must be initialized before by the caller.
  78586. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  78587. use default allocation functions.
  78588. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  78589. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  78590. all (the input data is simply copied a block at a time).
  78591. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  78592. compression (currently equivalent to level 6).
  78593. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  78594. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  78595. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  78596. with the version assumed by the caller (ZLIB_VERSION).
  78597. msg is set to null if there is no error message. deflateInit does not
  78598. perform any compression: this will be done by deflate().
  78599. */
  78600. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  78601. /*
  78602. deflate compresses as much data as possible, and stops when the input
  78603. buffer becomes empty or the output buffer becomes full. It may introduce some
  78604. output latency (reading input without producing any output) except when
  78605. forced to flush.
  78606. The detailed semantics are as follows. deflate performs one or both of the
  78607. following actions:
  78608. - Compress more input starting at next_in and update next_in and avail_in
  78609. accordingly. If not all input can be processed (because there is not
  78610. enough room in the output buffer), next_in and avail_in are updated and
  78611. processing will resume at this point for the next call of deflate().
  78612. - Provide more output starting at next_out and update next_out and avail_out
  78613. accordingly. This action is forced if the parameter flush is non zero.
  78614. Forcing flush frequently degrades the compression ratio, so this parameter
  78615. should be set only when necessary (in interactive applications).
  78616. Some output may be provided even if flush is not set.
  78617. Before the call of deflate(), the application should ensure that at least
  78618. one of the actions is possible, by providing more input and/or consuming
  78619. more output, and updating avail_in or avail_out accordingly; avail_out
  78620. should never be zero before the call. The application can consume the
  78621. compressed output when it wants, for example when the output buffer is full
  78622. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  78623. and with zero avail_out, it must be called again after making room in the
  78624. output buffer because there might be more output pending.
  78625. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  78626. decide how much data to accumualte before producing output, in order to
  78627. maximize compression.
  78628. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  78629. flushed to the output buffer and the output is aligned on a byte boundary, so
  78630. that the decompressor can get all input data available so far. (In particular
  78631. avail_in is zero after the call if enough output space has been provided
  78632. before the call.) Flushing may degrade compression for some compression
  78633. algorithms and so it should be used only when necessary.
  78634. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  78635. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  78636. restart from this point if previous compressed data has been damaged or if
  78637. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  78638. compression.
  78639. If deflate returns with avail_out == 0, this function must be called again
  78640. with the same value of the flush parameter and more output space (updated
  78641. avail_out), until the flush is complete (deflate returns with non-zero
  78642. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  78643. avail_out is greater than six to avoid repeated flush markers due to
  78644. avail_out == 0 on return.
  78645. If the parameter flush is set to Z_FINISH, pending input is processed,
  78646. pending output is flushed and deflate returns with Z_STREAM_END if there
  78647. was enough output space; if deflate returns with Z_OK, this function must be
  78648. called again with Z_FINISH and more output space (updated avail_out) but no
  78649. more input data, until it returns with Z_STREAM_END or an error. After
  78650. deflate has returned Z_STREAM_END, the only possible operations on the
  78651. stream are deflateReset or deflateEnd.
  78652. Z_FINISH can be used immediately after deflateInit if all the compression
  78653. is to be done in a single step. In this case, avail_out must be at least
  78654. the value returned by deflateBound (see below). If deflate does not return
  78655. Z_STREAM_END, then it must be called again as described above.
  78656. deflate() sets strm->adler to the adler32 checksum of all input read
  78657. so far (that is, total_in bytes).
  78658. deflate() may update strm->data_type if it can make a good guess about
  78659. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  78660. binary. This field is only for information purposes and does not affect
  78661. the compression algorithm in any manner.
  78662. deflate() returns Z_OK if some progress has been made (more input
  78663. processed or more output produced), Z_STREAM_END if all input has been
  78664. consumed and all output has been produced (only when flush is set to
  78665. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  78666. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  78667. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  78668. fatal, and deflate() can be called again with more input and more output
  78669. space to continue compressing.
  78670. */
  78671. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  78672. /*
  78673. All dynamically allocated data structures for this stream are freed.
  78674. This function discards any unprocessed input and does not flush any
  78675. pending output.
  78676. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  78677. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  78678. prematurely (some input or output was discarded). In the error case,
  78679. msg may be set but then points to a static string (which must not be
  78680. deallocated).
  78681. */
  78682. /*
  78683. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  78684. Initializes the internal stream state for decompression. The fields
  78685. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  78686. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  78687. value depends on the compression method), inflateInit determines the
  78688. compression method from the zlib header and allocates all data structures
  78689. accordingly; otherwise the allocation will be deferred to the first call of
  78690. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  78691. use default allocation functions.
  78692. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78693. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  78694. version assumed by the caller. msg is set to null if there is no error
  78695. message. inflateInit does not perform any decompression apart from reading
  78696. the zlib header if present: this will be done by inflate(). (So next_in and
  78697. avail_in may be modified, but next_out and avail_out are unchanged.)
  78698. */
  78699. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  78700. /*
  78701. inflate decompresses as much data as possible, and stops when the input
  78702. buffer becomes empty or the output buffer becomes full. It may introduce
  78703. some output latency (reading input without producing any output) except when
  78704. forced to flush.
  78705. The detailed semantics are as follows. inflate performs one or both of the
  78706. following actions:
  78707. - Decompress more input starting at next_in and update next_in and avail_in
  78708. accordingly. If not all input can be processed (because there is not
  78709. enough room in the output buffer), next_in is updated and processing
  78710. will resume at this point for the next call of inflate().
  78711. - Provide more output starting at next_out and update next_out and avail_out
  78712. accordingly. inflate() provides as much output as possible, until there
  78713. is no more input data or no more space in the output buffer (see below
  78714. about the flush parameter).
  78715. Before the call of inflate(), the application should ensure that at least
  78716. one of the actions is possible, by providing more input and/or consuming
  78717. more output, and updating the next_* and avail_* values accordingly.
  78718. The application can consume the uncompressed output when it wants, for
  78719. example when the output buffer is full (avail_out == 0), or after each
  78720. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  78721. must be called again after making room in the output buffer because there
  78722. might be more output pending.
  78723. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  78724. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  78725. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  78726. if and when it gets to the next deflate block boundary. When decoding the
  78727. zlib or gzip format, this will cause inflate() to return immediately after
  78728. the header and before the first block. When doing a raw inflate, inflate()
  78729. will go ahead and process the first block, and will return when it gets to
  78730. the end of that block, or when it runs out of data.
  78731. The Z_BLOCK option assists in appending to or combining deflate streams.
  78732. Also to assist in this, on return inflate() will set strm->data_type to the
  78733. number of unused bits in the last byte taken from strm->next_in, plus 64
  78734. if inflate() is currently decoding the last block in the deflate stream,
  78735. plus 128 if inflate() returned immediately after decoding an end-of-block
  78736. code or decoding the complete header up to just before the first byte of the
  78737. deflate stream. The end-of-block will not be indicated until all of the
  78738. uncompressed data from that block has been written to strm->next_out. The
  78739. number of unused bits may in general be greater than seven, except when
  78740. bit 7 of data_type is set, in which case the number of unused bits will be
  78741. less than eight.
  78742. inflate() should normally be called until it returns Z_STREAM_END or an
  78743. error. However if all decompression is to be performed in a single step
  78744. (a single call of inflate), the parameter flush should be set to
  78745. Z_FINISH. In this case all pending input is processed and all pending
  78746. output is flushed; avail_out must be large enough to hold all the
  78747. uncompressed data. (The size of the uncompressed data may have been saved
  78748. by the compressor for this purpose.) The next operation on this stream must
  78749. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  78750. is never required, but can be used to inform inflate that a faster approach
  78751. may be used for the single inflate() call.
  78752. In this implementation, inflate() always flushes as much output as
  78753. possible to the output buffer, and always uses the faster approach on the
  78754. first call. So the only effect of the flush parameter in this implementation
  78755. is on the return value of inflate(), as noted below, or when it returns early
  78756. because Z_BLOCK is used.
  78757. If a preset dictionary is needed after this call (see inflateSetDictionary
  78758. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  78759. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  78760. strm->adler to the adler32 checksum of all output produced so far (that is,
  78761. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  78762. below. At the end of the stream, inflate() checks that its computed adler32
  78763. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  78764. only if the checksum is correct.
  78765. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  78766. deflate data. The header type is detected automatically. Any information
  78767. contained in the gzip header is not retained, so applications that need that
  78768. information should instead use raw inflate, see inflateInit2() below, or
  78769. inflateBack() and perform their own processing of the gzip header and
  78770. trailer.
  78771. inflate() returns Z_OK if some progress has been made (more input processed
  78772. or more output produced), Z_STREAM_END if the end of the compressed data has
  78773. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  78774. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  78775. corrupted (input stream not conforming to the zlib format or incorrect check
  78776. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  78777. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  78778. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  78779. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  78780. inflate() can be called again with more input and more output space to
  78781. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  78782. call inflateSync() to look for a good compression block if a partial recovery
  78783. of the data is desired.
  78784. */
  78785. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  78786. /*
  78787. All dynamically allocated data structures for this stream are freed.
  78788. This function discards any unprocessed input and does not flush any
  78789. pending output.
  78790. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  78791. was inconsistent. In the error case, msg may be set but then points to a
  78792. static string (which must not be deallocated).
  78793. */
  78794. /* Advanced functions */
  78795. /*
  78796. The following functions are needed only in some special applications.
  78797. */
  78798. /*
  78799. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  78800. int level,
  78801. int method,
  78802. int windowBits,
  78803. int memLevel,
  78804. int strategy));
  78805. This is another version of deflateInit with more compression options. The
  78806. fields next_in, zalloc, zfree and opaque must be initialized before by
  78807. the caller.
  78808. The method parameter is the compression method. It must be Z_DEFLATED in
  78809. this version of the library.
  78810. The windowBits parameter is the base two logarithm of the window size
  78811. (the size of the history buffer). It should be in the range 8..15 for this
  78812. version of the library. Larger values of this parameter result in better
  78813. compression at the expense of memory usage. The default value is 15 if
  78814. deflateInit is used instead.
  78815. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  78816. determines the window size. deflate() will then generate raw deflate data
  78817. with no zlib header or trailer, and will not compute an adler32 check value.
  78818. windowBits can also be greater than 15 for optional gzip encoding. Add
  78819. 16 to windowBits to write a simple gzip header and trailer around the
  78820. compressed data instead of a zlib wrapper. The gzip header will have no
  78821. file name, no extra data, no comment, no modification time (set to zero),
  78822. no header crc, and the operating system will be set to 255 (unknown). If a
  78823. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  78824. The memLevel parameter specifies how much memory should be allocated
  78825. for the internal compression state. memLevel=1 uses minimum memory but
  78826. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  78827. for optimal speed. The default value is 8. See zconf.h for total memory
  78828. usage as a function of windowBits and memLevel.
  78829. The strategy parameter is used to tune the compression algorithm. Use the
  78830. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  78831. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  78832. string match), or Z_RLE to limit match distances to one (run-length
  78833. encoding). Filtered data consists mostly of small values with a somewhat
  78834. random distribution. In this case, the compression algorithm is tuned to
  78835. compress them better. The effect of Z_FILTERED is to force more Huffman
  78836. coding and less string matching; it is somewhat intermediate between
  78837. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  78838. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  78839. parameter only affects the compression ratio but not the correctness of the
  78840. compressed output even if it is not set appropriately. Z_FIXED prevents the
  78841. use of dynamic Huffman codes, allowing for a simpler decoder for special
  78842. applications.
  78843. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78844. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  78845. method). msg is set to null if there is no error message. deflateInit2 does
  78846. not perform any compression: this will be done by deflate().
  78847. */
  78848. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  78849. const Bytef *dictionary,
  78850. uInt dictLength));
  78851. /*
  78852. Initializes the compression dictionary from the given byte sequence
  78853. without producing any compressed output. This function must be called
  78854. immediately after deflateInit, deflateInit2 or deflateReset, before any
  78855. call of deflate. The compressor and decompressor must use exactly the same
  78856. dictionary (see inflateSetDictionary).
  78857. The dictionary should consist of strings (byte sequences) that are likely
  78858. to be encountered later in the data to be compressed, with the most commonly
  78859. used strings preferably put towards the end of the dictionary. Using a
  78860. dictionary is most useful when the data to be compressed is short and can be
  78861. predicted with good accuracy; the data can then be compressed better than
  78862. with the default empty dictionary.
  78863. Depending on the size of the compression data structures selected by
  78864. deflateInit or deflateInit2, a part of the dictionary may in effect be
  78865. discarded, for example if the dictionary is larger than the window size in
  78866. deflate or deflate2. Thus the strings most likely to be useful should be
  78867. put at the end of the dictionary, not at the front. In addition, the
  78868. current implementation of deflate will use at most the window size minus
  78869. 262 bytes of the provided dictionary.
  78870. Upon return of this function, strm->adler is set to the adler32 value
  78871. of the dictionary; the decompressor may later use this value to determine
  78872. which dictionary has been used by the compressor. (The adler32 value
  78873. applies to the whole dictionary even if only a subset of the dictionary is
  78874. actually used by the compressor.) If a raw deflate was requested, then the
  78875. adler32 value is not computed and strm->adler is not set.
  78876. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  78877. parameter is invalid (such as NULL dictionary) or the stream state is
  78878. inconsistent (for example if deflate has already been called for this stream
  78879. or if the compression method is bsort). deflateSetDictionary does not
  78880. perform any compression: this will be done by deflate().
  78881. */
  78882. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  78883. z_streamp source));
  78884. /*
  78885. Sets the destination stream as a complete copy of the source stream.
  78886. This function can be useful when several compression strategies will be
  78887. tried, for example when there are several ways of pre-processing the input
  78888. data with a filter. The streams that will be discarded should then be freed
  78889. by calling deflateEnd. Note that deflateCopy duplicates the internal
  78890. compression state which can be quite large, so this strategy is slow and
  78891. can consume lots of memory.
  78892. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  78893. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  78894. (such as zalloc being NULL). msg is left unchanged in both source and
  78895. destination.
  78896. */
  78897. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  78898. /*
  78899. This function is equivalent to deflateEnd followed by deflateInit,
  78900. but does not free and reallocate all the internal compression state.
  78901. The stream will keep the same compression level and any other attributes
  78902. that may have been set by deflateInit2.
  78903. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  78904. stream state was inconsistent (such as zalloc or state being NULL).
  78905. */
  78906. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  78907. int level,
  78908. int strategy));
  78909. /*
  78910. Dynamically update the compression level and compression strategy. The
  78911. interpretation of level and strategy is as in deflateInit2. This can be
  78912. used to switch between compression and straight copy of the input data, or
  78913. to switch to a different kind of input data requiring a different
  78914. strategy. If the compression level is changed, the input available so far
  78915. is compressed with the old level (and may be flushed); the new level will
  78916. take effect only at the next call of deflate().
  78917. Before the call of deflateParams, the stream state must be set as for
  78918. a call of deflate(), since the currently available input may have to
  78919. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  78920. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  78921. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  78922. if strm->avail_out was zero.
  78923. */
  78924. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  78925. int good_length,
  78926. int max_lazy,
  78927. int nice_length,
  78928. int max_chain));
  78929. /*
  78930. Fine tune deflate's internal compression parameters. This should only be
  78931. used by someone who understands the algorithm used by zlib's deflate for
  78932. searching for the best matching string, and even then only by the most
  78933. fanatic optimizer trying to squeeze out the last compressed bit for their
  78934. specific input data. Read the deflate.c source code for the meaning of the
  78935. max_lazy, good_length, nice_length, and max_chain parameters.
  78936. deflateTune() can be called after deflateInit() or deflateInit2(), and
  78937. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  78938. */
  78939. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  78940. uLong sourceLen));
  78941. /*
  78942. deflateBound() returns an upper bound on the compressed size after
  78943. deflation of sourceLen bytes. It must be called after deflateInit()
  78944. or deflateInit2(). This would be used to allocate an output buffer
  78945. for deflation in a single pass, and so would be called before deflate().
  78946. */
  78947. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  78948. int bits,
  78949. int value));
  78950. /*
  78951. deflatePrime() inserts bits in the deflate output stream. The intent
  78952. is that this function is used to start off the deflate output with the
  78953. bits leftover from a previous deflate stream when appending to it. As such,
  78954. this function can only be used for raw deflate, and must be used before the
  78955. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  78956. less than or equal to 16, and that many of the least significant bits of
  78957. value will be inserted in the output.
  78958. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  78959. stream state was inconsistent.
  78960. */
  78961. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  78962. gz_headerp head));
  78963. /*
  78964. deflateSetHeader() provides gzip header information for when a gzip
  78965. stream is requested by deflateInit2(). deflateSetHeader() may be called
  78966. after deflateInit2() or deflateReset() and before the first call of
  78967. deflate(). The text, time, os, extra field, name, and comment information
  78968. in the provided gz_header structure are written to the gzip header (xflag is
  78969. ignored -- the extra flags are set according to the compression level). The
  78970. caller must assure that, if not Z_NULL, name and comment are terminated with
  78971. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  78972. available there. If hcrc is true, a gzip header crc is included. Note that
  78973. the current versions of the command-line version of gzip (up through version
  78974. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  78975. gzip file" and give up.
  78976. If deflateSetHeader is not used, the default gzip header has text false,
  78977. the time set to zero, and os set to 255, with no extra, name, or comment
  78978. fields. The gzip header is returned to the default state by deflateReset().
  78979. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  78980. stream state was inconsistent.
  78981. */
  78982. /*
  78983. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  78984. int windowBits));
  78985. This is another version of inflateInit with an extra parameter. The
  78986. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  78987. before by the caller.
  78988. The windowBits parameter is the base two logarithm of the maximum window
  78989. size (the size of the history buffer). It should be in the range 8..15 for
  78990. this version of the library. The default value is 15 if inflateInit is used
  78991. instead. windowBits must be greater than or equal to the windowBits value
  78992. provided to deflateInit2() while compressing, or it must be equal to 15 if
  78993. deflateInit2() was not used. If a compressed stream with a larger window
  78994. size is given as input, inflate() will return with the error code
  78995. Z_DATA_ERROR instead of trying to allocate a larger window.
  78996. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  78997. determines the window size. inflate() will then process raw deflate data,
  78998. not looking for a zlib or gzip header, not generating a check value, and not
  78999. looking for any check values for comparison at the end of the stream. This
  79000. is for use with other formats that use the deflate compressed data format
  79001. such as zip. Those formats provide their own check values. If a custom
  79002. format is developed using the raw deflate format for compressed data, it is
  79003. recommended that a check value such as an adler32 or a crc32 be applied to
  79004. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  79005. most applications, the zlib format should be used as is. Note that comments
  79006. above on the use in deflateInit2() applies to the magnitude of windowBits.
  79007. windowBits can also be greater than 15 for optional gzip decoding. Add
  79008. 32 to windowBits to enable zlib and gzip decoding with automatic header
  79009. detection, or add 16 to decode only the gzip format (the zlib format will
  79010. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  79011. a crc32 instead of an adler32.
  79012. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79013. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  79014. is set to null if there is no error message. inflateInit2 does not perform
  79015. any decompression apart from reading the zlib header if present: this will
  79016. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  79017. and avail_out are unchanged.)
  79018. */
  79019. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  79020. const Bytef *dictionary,
  79021. uInt dictLength));
  79022. /*
  79023. Initializes the decompression dictionary from the given uncompressed byte
  79024. sequence. This function must be called immediately after a call of inflate,
  79025. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  79026. can be determined from the adler32 value returned by that call of inflate.
  79027. The compressor and decompressor must use exactly the same dictionary (see
  79028. deflateSetDictionary). For raw inflate, this function can be called
  79029. immediately after inflateInit2() or inflateReset() and before any call of
  79030. inflate() to set the dictionary. The application must insure that the
  79031. dictionary that was used for compression is provided.
  79032. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  79033. parameter is invalid (such as NULL dictionary) or the stream state is
  79034. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  79035. expected one (incorrect adler32 value). inflateSetDictionary does not
  79036. perform any decompression: this will be done by subsequent calls of
  79037. inflate().
  79038. */
  79039. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  79040. /*
  79041. Skips invalid compressed data until a full flush point (see above the
  79042. description of deflate with Z_FULL_FLUSH) can be found, or until all
  79043. available input is skipped. No output is provided.
  79044. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  79045. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  79046. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  79047. case, the application may save the current current value of total_in which
  79048. indicates where valid compressed data was found. In the error case, the
  79049. application may repeatedly call inflateSync, providing more input each time,
  79050. until success or end of the input data.
  79051. */
  79052. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  79053. z_streamp source));
  79054. /*
  79055. Sets the destination stream as a complete copy of the source stream.
  79056. This function can be useful when randomly accessing a large stream. The
  79057. first pass through the stream can periodically record the inflate state,
  79058. allowing restarting inflate at those points when randomly accessing the
  79059. stream.
  79060. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  79061. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  79062. (such as zalloc being NULL). msg is left unchanged in both source and
  79063. destination.
  79064. */
  79065. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  79066. /*
  79067. This function is equivalent to inflateEnd followed by inflateInit,
  79068. but does not free and reallocate all the internal decompression state.
  79069. The stream will keep attributes that may have been set by inflateInit2.
  79070. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  79071. stream state was inconsistent (such as zalloc or state being NULL).
  79072. */
  79073. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  79074. int bits,
  79075. int value));
  79076. /*
  79077. This function inserts bits in the inflate input stream. The intent is
  79078. that this function is used to start inflating at a bit position in the
  79079. middle of a byte. The provided bits will be used before any bytes are used
  79080. from next_in. This function should only be used with raw inflate, and
  79081. should be used before the first inflate() call after inflateInit2() or
  79082. inflateReset(). bits must be less than or equal to 16, and that many of the
  79083. least significant bits of value will be inserted in the input.
  79084. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  79085. stream state was inconsistent.
  79086. */
  79087. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  79088. gz_headerp head));
  79089. /*
  79090. inflateGetHeader() requests that gzip header information be stored in the
  79091. provided gz_header structure. inflateGetHeader() may be called after
  79092. inflateInit2() or inflateReset(), and before the first call of inflate().
  79093. As inflate() processes the gzip stream, head->done is zero until the header
  79094. is completed, at which time head->done is set to one. If a zlib stream is
  79095. being decoded, then head->done is set to -1 to indicate that there will be
  79096. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  79097. force inflate() to return immediately after header processing is complete
  79098. and before any actual data is decompressed.
  79099. The text, time, xflags, and os fields are filled in with the gzip header
  79100. contents. hcrc is set to true if there is a header CRC. (The header CRC
  79101. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  79102. contains the maximum number of bytes to write to extra. Once done is true,
  79103. extra_len contains the actual extra field length, and extra contains the
  79104. extra field, or that field truncated if extra_max is less than extra_len.
  79105. If name is not Z_NULL, then up to name_max characters are written there,
  79106. terminated with a zero unless the length is greater than name_max. If
  79107. comment is not Z_NULL, then up to comm_max characters are written there,
  79108. terminated with a zero unless the length is greater than comm_max. When
  79109. any of extra, name, or comment are not Z_NULL and the respective field is
  79110. not present in the header, then that field is set to Z_NULL to signal its
  79111. absence. This allows the use of deflateSetHeader() with the returned
  79112. structure to duplicate the header. However if those fields are set to
  79113. allocated memory, then the application will need to save those pointers
  79114. elsewhere so that they can be eventually freed.
  79115. If inflateGetHeader is not used, then the header information is simply
  79116. discarded. The header is always checked for validity, including the header
  79117. CRC if present. inflateReset() will reset the process to discard the header
  79118. information. The application would need to call inflateGetHeader() again to
  79119. retrieve the header from the next gzip stream.
  79120. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  79121. stream state was inconsistent.
  79122. */
  79123. /*
  79124. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  79125. unsigned char FAR *window));
  79126. Initialize the internal stream state for decompression using inflateBack()
  79127. calls. The fields zalloc, zfree and opaque in strm must be initialized
  79128. before the call. If zalloc and zfree are Z_NULL, then the default library-
  79129. derived memory allocation routines are used. windowBits is the base two
  79130. logarithm of the window size, in the range 8..15. window is a caller
  79131. supplied buffer of that size. Except for special applications where it is
  79132. assured that deflate was used with small window sizes, windowBits must be 15
  79133. and a 32K byte window must be supplied to be able to decompress general
  79134. deflate streams.
  79135. See inflateBack() for the usage of these routines.
  79136. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  79137. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  79138. be allocated, or Z_VERSION_ERROR if the version of the library does not
  79139. match the version of the header file.
  79140. */
  79141. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  79142. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  79143. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  79144. in_func in, void FAR *in_desc,
  79145. out_func out, void FAR *out_desc));
  79146. /*
  79147. inflateBack() does a raw inflate with a single call using a call-back
  79148. interface for input and output. This is more efficient than inflate() for
  79149. file i/o applications in that it avoids copying between the output and the
  79150. sliding window by simply making the window itself the output buffer. This
  79151. function trusts the application to not change the output buffer passed by
  79152. the output function, at least until inflateBack() returns.
  79153. inflateBackInit() must be called first to allocate the internal state
  79154. and to initialize the state with the user-provided window buffer.
  79155. inflateBack() may then be used multiple times to inflate a complete, raw
  79156. deflate stream with each call. inflateBackEnd() is then called to free
  79157. the allocated state.
  79158. A raw deflate stream is one with no zlib or gzip header or trailer.
  79159. This routine would normally be used in a utility that reads zip or gzip
  79160. files and writes out uncompressed files. The utility would decode the
  79161. header and process the trailer on its own, hence this routine expects
  79162. only the raw deflate stream to decompress. This is different from the
  79163. normal behavior of inflate(), which expects either a zlib or gzip header and
  79164. trailer around the deflate stream.
  79165. inflateBack() uses two subroutines supplied by the caller that are then
  79166. called by inflateBack() for input and output. inflateBack() calls those
  79167. routines until it reads a complete deflate stream and writes out all of the
  79168. uncompressed data, or until it encounters an error. The function's
  79169. parameters and return types are defined above in the in_func and out_func
  79170. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  79171. number of bytes of provided input, and a pointer to that input in buf. If
  79172. there is no input available, in() must return zero--buf is ignored in that
  79173. case--and inflateBack() will return a buffer error. inflateBack() will call
  79174. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  79175. should return zero on success, or non-zero on failure. If out() returns
  79176. non-zero, inflateBack() will return with an error. Neither in() nor out()
  79177. are permitted to change the contents of the window provided to
  79178. inflateBackInit(), which is also the buffer that out() uses to write from.
  79179. The length written by out() will be at most the window size. Any non-zero
  79180. amount of input may be provided by in().
  79181. For convenience, inflateBack() can be provided input on the first call by
  79182. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  79183. in() will be called. Therefore strm->next_in must be initialized before
  79184. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  79185. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  79186. must also be initialized, and then if strm->avail_in is not zero, input will
  79187. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  79188. The in_desc and out_desc parameters of inflateBack() is passed as the
  79189. first parameter of in() and out() respectively when they are called. These
  79190. descriptors can be optionally used to pass any information that the caller-
  79191. supplied in() and out() functions need to do their job.
  79192. On return, inflateBack() will set strm->next_in and strm->avail_in to
  79193. pass back any unused input that was provided by the last in() call. The
  79194. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  79195. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  79196. error in the deflate stream (in which case strm->msg is set to indicate the
  79197. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  79198. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  79199. distinguished using strm->next_in which will be Z_NULL only if in() returned
  79200. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  79201. out() returning non-zero. (in() will always be called before out(), so
  79202. strm->next_in is assured to be defined if out() returns non-zero.) Note
  79203. that inflateBack() cannot return Z_OK.
  79204. */
  79205. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  79206. /*
  79207. All memory allocated by inflateBackInit() is freed.
  79208. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  79209. state was inconsistent.
  79210. */
  79211. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  79212. /* Return flags indicating compile-time options.
  79213. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  79214. 1.0: size of uInt
  79215. 3.2: size of uLong
  79216. 5.4: size of voidpf (pointer)
  79217. 7.6: size of z_off_t
  79218. Compiler, assembler, and debug options:
  79219. 8: DEBUG
  79220. 9: ASMV or ASMINF -- use ASM code
  79221. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  79222. 11: 0 (reserved)
  79223. One-time table building (smaller code, but not thread-safe if true):
  79224. 12: BUILDFIXED -- build static block decoding tables when needed
  79225. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  79226. 14,15: 0 (reserved)
  79227. Library content (indicates missing functionality):
  79228. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  79229. deflate code when not needed)
  79230. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  79231. and decode gzip streams (to avoid linking crc code)
  79232. 18-19: 0 (reserved)
  79233. Operation variations (changes in library functionality):
  79234. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  79235. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  79236. 22,23: 0 (reserved)
  79237. The sprintf variant used by gzprintf (zero is best):
  79238. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  79239. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  79240. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  79241. Remainder:
  79242. 27-31: 0 (reserved)
  79243. */
  79244. /* utility functions */
  79245. /*
  79246. The following utility functions are implemented on top of the
  79247. basic stream-oriented functions. To simplify the interface, some
  79248. default options are assumed (compression level and memory usage,
  79249. standard memory allocation functions). The source code of these
  79250. utility functions can easily be modified if you need special options.
  79251. */
  79252. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  79253. const Bytef *source, uLong sourceLen));
  79254. /*
  79255. Compresses the source buffer into the destination buffer. sourceLen is
  79256. the byte length of the source buffer. Upon entry, destLen is the total
  79257. size of the destination buffer, which must be at least the value returned
  79258. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  79259. compressed buffer.
  79260. This function can be used to compress a whole file at once if the
  79261. input file is mmap'ed.
  79262. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  79263. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79264. buffer.
  79265. */
  79266. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  79267. const Bytef *source, uLong sourceLen,
  79268. int level));
  79269. /*
  79270. Compresses the source buffer into the destination buffer. The level
  79271. parameter has the same meaning as in deflateInit. sourceLen is the byte
  79272. length of the source buffer. Upon entry, destLen is the total size of the
  79273. destination buffer, which must be at least the value returned by
  79274. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  79275. compressed buffer.
  79276. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79277. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  79278. Z_STREAM_ERROR if the level parameter is invalid.
  79279. */
  79280. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  79281. /*
  79282. compressBound() returns an upper bound on the compressed size after
  79283. compress() or compress2() on sourceLen bytes. It would be used before
  79284. a compress() or compress2() call to allocate the destination buffer.
  79285. */
  79286. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  79287. const Bytef *source, uLong sourceLen));
  79288. /*
  79289. Decompresses the source buffer into the destination buffer. sourceLen is
  79290. the byte length of the source buffer. Upon entry, destLen is the total
  79291. size of the destination buffer, which must be large enough to hold the
  79292. entire uncompressed data. (The size of the uncompressed data must have
  79293. been saved previously by the compressor and transmitted to the decompressor
  79294. by some mechanism outside the scope of this compression library.)
  79295. Upon exit, destLen is the actual size of the compressed buffer.
  79296. This function can be used to decompress a whole file at once if the
  79297. input file is mmap'ed.
  79298. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  79299. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79300. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  79301. */
  79302. typedef voidp gzFile;
  79303. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  79304. /*
  79305. Opens a gzip (.gz) file for reading or writing. The mode parameter
  79306. is as in fopen ("rb" or "wb") but can also include a compression level
  79307. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  79308. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  79309. as in "wb1R". (See the description of deflateInit2 for more information
  79310. about the strategy parameter.)
  79311. gzopen can be used to read a file which is not in gzip format; in this
  79312. case gzread will directly read from the file without decompression.
  79313. gzopen returns NULL if the file could not be opened or if there was
  79314. insufficient memory to allocate the (de)compression state; errno
  79315. can be checked to distinguish the two cases (if errno is zero, the
  79316. zlib error is Z_MEM_ERROR). */
  79317. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  79318. /*
  79319. gzdopen() associates a gzFile with the file descriptor fd. File
  79320. descriptors are obtained from calls like open, dup, creat, pipe or
  79321. fileno (in the file has been previously opened with fopen).
  79322. The mode parameter is as in gzopen.
  79323. The next call of gzclose on the returned gzFile will also close the
  79324. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  79325. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  79326. gzdopen returns NULL if there was insufficient memory to allocate
  79327. the (de)compression state.
  79328. */
  79329. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  79330. /*
  79331. Dynamically update the compression level or strategy. See the description
  79332. of deflateInit2 for the meaning of these parameters.
  79333. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  79334. opened for writing.
  79335. */
  79336. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  79337. /*
  79338. Reads the given number of uncompressed bytes from the compressed file.
  79339. If the input file was not in gzip format, gzread copies the given number
  79340. of bytes into the buffer.
  79341. gzread returns the number of uncompressed bytes actually read (0 for
  79342. end of file, -1 for error). */
  79343. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  79344. voidpc buf, unsigned len));
  79345. /*
  79346. Writes the given number of uncompressed bytes into the compressed file.
  79347. gzwrite returns the number of uncompressed bytes actually written
  79348. (0 in case of error).
  79349. */
  79350. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  79351. /*
  79352. Converts, formats, and writes the args to the compressed file under
  79353. control of the format string, as in fprintf. gzprintf returns the number of
  79354. uncompressed bytes actually written (0 in case of error). The number of
  79355. uncompressed bytes written is limited to 4095. The caller should assure that
  79356. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  79357. return an error (0) with nothing written. In this case, there may also be a
  79358. buffer overflow with unpredictable consequences, which is possible only if
  79359. zlib was compiled with the insecure functions sprintf() or vsprintf()
  79360. because the secure snprintf() or vsnprintf() functions were not available.
  79361. */
  79362. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  79363. /*
  79364. Writes the given null-terminated string to the compressed file, excluding
  79365. the terminating null character.
  79366. gzputs returns the number of characters written, or -1 in case of error.
  79367. */
  79368. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  79369. /*
  79370. Reads bytes from the compressed file until len-1 characters are read, or
  79371. a newline character is read and transferred to buf, or an end-of-file
  79372. condition is encountered. The string is then terminated with a null
  79373. character.
  79374. gzgets returns buf, or Z_NULL in case of error.
  79375. */
  79376. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  79377. /*
  79378. Writes c, converted to an unsigned char, into the compressed file.
  79379. gzputc returns the value that was written, or -1 in case of error.
  79380. */
  79381. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  79382. /*
  79383. Reads one byte from the compressed file. gzgetc returns this byte
  79384. or -1 in case of end of file or error.
  79385. */
  79386. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  79387. /*
  79388. Push one character back onto the stream to be read again later.
  79389. Only one character of push-back is allowed. gzungetc() returns the
  79390. character pushed, or -1 on failure. gzungetc() will fail if a
  79391. character has been pushed but not read yet, or if c is -1. The pushed
  79392. character will be discarded if the stream is repositioned with gzseek()
  79393. or gzrewind().
  79394. */
  79395. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  79396. /*
  79397. Flushes all pending output into the compressed file. The parameter
  79398. flush is as in the deflate() function. The return value is the zlib
  79399. error number (see function gzerror below). gzflush returns Z_OK if
  79400. the flush parameter is Z_FINISH and all output could be flushed.
  79401. gzflush should be called only when strictly necessary because it can
  79402. degrade compression.
  79403. */
  79404. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  79405. z_off_t offset, int whence));
  79406. /*
  79407. Sets the starting position for the next gzread or gzwrite on the
  79408. given compressed file. The offset represents a number of bytes in the
  79409. uncompressed data stream. The whence parameter is defined as in lseek(2);
  79410. the value SEEK_END is not supported.
  79411. If the file is opened for reading, this function is emulated but can be
  79412. extremely slow. If the file is opened for writing, only forward seeks are
  79413. supported; gzseek then compresses a sequence of zeroes up to the new
  79414. starting position.
  79415. gzseek returns the resulting offset location as measured in bytes from
  79416. the beginning of the uncompressed stream, or -1 in case of error, in
  79417. particular if the file is opened for writing and the new starting position
  79418. would be before the current position.
  79419. */
  79420. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  79421. /*
  79422. Rewinds the given file. This function is supported only for reading.
  79423. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  79424. */
  79425. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  79426. /*
  79427. Returns the starting position for the next gzread or gzwrite on the
  79428. given compressed file. This position represents a number of bytes in the
  79429. uncompressed data stream.
  79430. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  79431. */
  79432. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  79433. /*
  79434. Returns 1 when EOF has previously been detected reading the given
  79435. input stream, otherwise zero.
  79436. */
  79437. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  79438. /*
  79439. Returns 1 if file is being read directly without decompression, otherwise
  79440. zero.
  79441. */
  79442. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  79443. /*
  79444. Flushes all pending output if necessary, closes the compressed file
  79445. and deallocates all the (de)compression state. The return value is the zlib
  79446. error number (see function gzerror below).
  79447. */
  79448. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  79449. /*
  79450. Returns the error message for the last error which occurred on the
  79451. given compressed file. errnum is set to zlib error number. If an
  79452. error occurred in the file system and not in the compression library,
  79453. errnum is set to Z_ERRNO and the application may consult errno
  79454. to get the exact error code.
  79455. */
  79456. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  79457. /*
  79458. Clears the error and end-of-file flags for file. This is analogous to the
  79459. clearerr() function in stdio. This is useful for continuing to read a gzip
  79460. file that is being written concurrently.
  79461. */
  79462. /* checksum functions */
  79463. /*
  79464. These functions are not related to compression but are exported
  79465. anyway because they might be useful in applications using the
  79466. compression library.
  79467. */
  79468. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  79469. /*
  79470. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  79471. return the updated checksum. If buf is NULL, this function returns
  79472. the required initial value for the checksum.
  79473. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  79474. much faster. Usage example:
  79475. uLong adler = adler32(0L, Z_NULL, 0);
  79476. while (read_buffer(buffer, length) != EOF) {
  79477. adler = adler32(adler, buffer, length);
  79478. }
  79479. if (adler != original_adler) error();
  79480. */
  79481. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  79482. z_off_t len2));
  79483. /*
  79484. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  79485. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  79486. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  79487. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  79488. */
  79489. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  79490. /*
  79491. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  79492. updated CRC-32. If buf is NULL, this function returns the required initial
  79493. value for the for the crc. Pre- and post-conditioning (one's complement) is
  79494. performed within this function so it shouldn't be done by the application.
  79495. Usage example:
  79496. uLong crc = crc32(0L, Z_NULL, 0);
  79497. while (read_buffer(buffer, length) != EOF) {
  79498. crc = crc32(crc, buffer, length);
  79499. }
  79500. if (crc != original_crc) error();
  79501. */
  79502. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  79503. /*
  79504. Combine two CRC-32 check values into one. For two sequences of bytes,
  79505. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  79506. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  79507. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  79508. len2.
  79509. */
  79510. /* various hacks, don't look :) */
  79511. /* deflateInit and inflateInit are macros to allow checking the zlib version
  79512. * and the compiler's view of z_stream:
  79513. */
  79514. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  79515. const char *version, int stream_size));
  79516. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  79517. const char *version, int stream_size));
  79518. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  79519. int windowBits, int memLevel,
  79520. int strategy, const char *version,
  79521. int stream_size));
  79522. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  79523. const char *version, int stream_size));
  79524. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  79525. unsigned char FAR *window,
  79526. const char *version,
  79527. int stream_size));
  79528. #define deflateInit(strm, level) \
  79529. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  79530. #define inflateInit(strm) \
  79531. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  79532. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  79533. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  79534. (strategy), ZLIB_VERSION, sizeof(z_stream))
  79535. #define inflateInit2(strm, windowBits) \
  79536. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  79537. #define inflateBackInit(strm, windowBits, window) \
  79538. inflateBackInit_((strm), (windowBits), (window), \
  79539. ZLIB_VERSION, sizeof(z_stream))
  79540. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  79541. struct internal_state {int dummy;}; /* hack for buggy compilers */
  79542. #endif
  79543. ZEXTERN const char * ZEXPORT zError OF((int));
  79544. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  79545. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  79546. #ifdef __cplusplus
  79547. //}
  79548. #endif
  79549. #endif /* ZLIB_H */
  79550. /*** End of inlined file: zlib.h ***/
  79551. #undef OS_CODE
  79552. #else
  79553. #include <zlib.h>
  79554. #endif
  79555. }
  79556. BEGIN_JUCE_NAMESPACE
  79557. // internal helper object that holds the zlib structures so they don't have to be
  79558. // included publicly.
  79559. class GZIPCompressorHelper
  79560. {
  79561. public:
  79562. GZIPCompressorHelper (const int compressionLevel, const bool nowrap)
  79563. : data (0),
  79564. dataSize (0),
  79565. compLevel (compressionLevel),
  79566. strategy (0),
  79567. setParams (true),
  79568. streamIsValid (false),
  79569. finished (false),
  79570. shouldFinish (false)
  79571. {
  79572. using namespace zlibNamespace;
  79573. zerostruct (stream);
  79574. streamIsValid = (deflateInit2 (&stream, compLevel, Z_DEFLATED,
  79575. nowrap ? -MAX_WBITS : MAX_WBITS,
  79576. 8, strategy) == Z_OK);
  79577. }
  79578. ~GZIPCompressorHelper()
  79579. {
  79580. using namespace zlibNamespace;
  79581. if (streamIsValid)
  79582. deflateEnd (&stream);
  79583. }
  79584. bool needsInput() const throw()
  79585. {
  79586. return dataSize <= 0;
  79587. }
  79588. void setInput (const uint8* const newData, const int size) throw()
  79589. {
  79590. data = newData;
  79591. dataSize = size;
  79592. }
  79593. int doNextBlock (uint8* const dest, const int destSize) throw()
  79594. {
  79595. using namespace zlibNamespace;
  79596. if (streamIsValid)
  79597. {
  79598. stream.next_in = const_cast <uint8*> (data);
  79599. stream.next_out = dest;
  79600. stream.avail_in = dataSize;
  79601. stream.avail_out = destSize;
  79602. const int result = setParams ? deflateParams (&stream, compLevel, strategy)
  79603. : deflate (&stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  79604. setParams = false;
  79605. switch (result)
  79606. {
  79607. case Z_STREAM_END:
  79608. finished = true;
  79609. // Deliberate fall-through..
  79610. case Z_OK:
  79611. data += dataSize - stream.avail_in;
  79612. dataSize = stream.avail_in;
  79613. return destSize - stream.avail_out;
  79614. default:
  79615. break;
  79616. }
  79617. }
  79618. return 0;
  79619. }
  79620. private:
  79621. zlibNamespace::z_stream stream;
  79622. const uint8* data;
  79623. int dataSize, compLevel, strategy;
  79624. bool setParams, streamIsValid;
  79625. public:
  79626. bool finished, shouldFinish;
  79627. };
  79628. const int gzipCompBufferSize = 32768;
  79629. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  79630. int compressionLevel,
  79631. const bool deleteDestStream,
  79632. const bool noWrap)
  79633. : destStream (destStream_),
  79634. streamToDelete (deleteDestStream ? destStream_ : 0),
  79635. buffer (gzipCompBufferSize)
  79636. {
  79637. if (compressionLevel < 1 || compressionLevel > 9)
  79638. compressionLevel = -1;
  79639. helper = new GZIPCompressorHelper (compressionLevel, noWrap);
  79640. }
  79641. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  79642. {
  79643. flush();
  79644. }
  79645. void GZIPCompressorOutputStream::flush()
  79646. {
  79647. if (! helper->finished)
  79648. {
  79649. helper->shouldFinish = true;
  79650. while (! helper->finished)
  79651. doNextBlock();
  79652. }
  79653. destStream->flush();
  79654. }
  79655. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  79656. {
  79657. if (! helper->finished)
  79658. {
  79659. helper->setInput (static_cast <const uint8*> (destBuffer), howMany);
  79660. while (! helper->needsInput())
  79661. {
  79662. if (! doNextBlock())
  79663. return false;
  79664. }
  79665. }
  79666. return true;
  79667. }
  79668. bool GZIPCompressorOutputStream::doNextBlock()
  79669. {
  79670. const int len = helper->doNextBlock (buffer, gzipCompBufferSize);
  79671. if (len > 0)
  79672. return destStream->write (buffer, len);
  79673. else
  79674. return true;
  79675. }
  79676. int64 GZIPCompressorOutputStream::getPosition()
  79677. {
  79678. return destStream->getPosition();
  79679. }
  79680. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  79681. {
  79682. jassertfalse; // can't do it!
  79683. return false;
  79684. }
  79685. END_JUCE_NAMESPACE
  79686. /*** End of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  79687. /*** Start of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  79688. #if JUCE_MSVC
  79689. #pragma warning (push)
  79690. #pragma warning (disable: 4309 4305)
  79691. #endif
  79692. namespace zlibNamespace
  79693. {
  79694. #if JUCE_INCLUDE_ZLIB_CODE
  79695. #undef OS_CODE
  79696. #undef fdopen
  79697. #define ZLIB_INTERNAL
  79698. #define NO_DUMMY_DECL
  79699. /*** Start of inlined file: adler32.c ***/
  79700. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79701. #define ZLIB_INTERNAL
  79702. #define BASE 65521UL /* largest prime smaller than 65536 */
  79703. #define NMAX 5552
  79704. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  79705. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  79706. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  79707. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  79708. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  79709. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  79710. /* use NO_DIVIDE if your processor does not do division in hardware */
  79711. #ifdef NO_DIVIDE
  79712. # define MOD(a) \
  79713. do { \
  79714. if (a >= (BASE << 16)) a -= (BASE << 16); \
  79715. if (a >= (BASE << 15)) a -= (BASE << 15); \
  79716. if (a >= (BASE << 14)) a -= (BASE << 14); \
  79717. if (a >= (BASE << 13)) a -= (BASE << 13); \
  79718. if (a >= (BASE << 12)) a -= (BASE << 12); \
  79719. if (a >= (BASE << 11)) a -= (BASE << 11); \
  79720. if (a >= (BASE << 10)) a -= (BASE << 10); \
  79721. if (a >= (BASE << 9)) a -= (BASE << 9); \
  79722. if (a >= (BASE << 8)) a -= (BASE << 8); \
  79723. if (a >= (BASE << 7)) a -= (BASE << 7); \
  79724. if (a >= (BASE << 6)) a -= (BASE << 6); \
  79725. if (a >= (BASE << 5)) a -= (BASE << 5); \
  79726. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79727. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79728. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79729. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79730. if (a >= BASE) a -= BASE; \
  79731. } while (0)
  79732. # define MOD4(a) \
  79733. do { \
  79734. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79735. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79736. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79737. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79738. if (a >= BASE) a -= BASE; \
  79739. } while (0)
  79740. #else
  79741. # define MOD(a) a %= BASE
  79742. # define MOD4(a) a %= BASE
  79743. #endif
  79744. /* ========================================================================= */
  79745. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  79746. {
  79747. unsigned long sum2;
  79748. unsigned n;
  79749. /* split Adler-32 into component sums */
  79750. sum2 = (adler >> 16) & 0xffff;
  79751. adler &= 0xffff;
  79752. /* in case user likes doing a byte at a time, keep it fast */
  79753. if (len == 1) {
  79754. adler += buf[0];
  79755. if (adler >= BASE)
  79756. adler -= BASE;
  79757. sum2 += adler;
  79758. if (sum2 >= BASE)
  79759. sum2 -= BASE;
  79760. return adler | (sum2 << 16);
  79761. }
  79762. /* initial Adler-32 value (deferred check for len == 1 speed) */
  79763. if (buf == Z_NULL)
  79764. return 1L;
  79765. /* in case short lengths are provided, keep it somewhat fast */
  79766. if (len < 16) {
  79767. while (len--) {
  79768. adler += *buf++;
  79769. sum2 += adler;
  79770. }
  79771. if (adler >= BASE)
  79772. adler -= BASE;
  79773. MOD4(sum2); /* only added so many BASE's */
  79774. return adler | (sum2 << 16);
  79775. }
  79776. /* do length NMAX blocks -- requires just one modulo operation */
  79777. while (len >= NMAX) {
  79778. len -= NMAX;
  79779. n = NMAX / 16; /* NMAX is divisible by 16 */
  79780. do {
  79781. DO16(buf); /* 16 sums unrolled */
  79782. buf += 16;
  79783. } while (--n);
  79784. MOD(adler);
  79785. MOD(sum2);
  79786. }
  79787. /* do remaining bytes (less than NMAX, still just one modulo) */
  79788. if (len) { /* avoid modulos if none remaining */
  79789. while (len >= 16) {
  79790. len -= 16;
  79791. DO16(buf);
  79792. buf += 16;
  79793. }
  79794. while (len--) {
  79795. adler += *buf++;
  79796. sum2 += adler;
  79797. }
  79798. MOD(adler);
  79799. MOD(sum2);
  79800. }
  79801. /* return recombined sums */
  79802. return adler | (sum2 << 16);
  79803. }
  79804. /* ========================================================================= */
  79805. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  79806. {
  79807. unsigned long sum1;
  79808. unsigned long sum2;
  79809. unsigned rem;
  79810. /* the derivation of this formula is left as an exercise for the reader */
  79811. rem = (unsigned)(len2 % BASE);
  79812. sum1 = adler1 & 0xffff;
  79813. sum2 = rem * sum1;
  79814. MOD(sum2);
  79815. sum1 += (adler2 & 0xffff) + BASE - 1;
  79816. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  79817. if (sum1 > BASE) sum1 -= BASE;
  79818. if (sum1 > BASE) sum1 -= BASE;
  79819. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  79820. if (sum2 > BASE) sum2 -= BASE;
  79821. return sum1 | (sum2 << 16);
  79822. }
  79823. /*** End of inlined file: adler32.c ***/
  79824. /*** Start of inlined file: compress.c ***/
  79825. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79826. #define ZLIB_INTERNAL
  79827. /* ===========================================================================
  79828. Compresses the source buffer into the destination buffer. The level
  79829. parameter has the same meaning as in deflateInit. sourceLen is the byte
  79830. length of the source buffer. Upon entry, destLen is the total size of the
  79831. destination buffer, which must be at least 0.1% larger than sourceLen plus
  79832. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  79833. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79834. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  79835. Z_STREAM_ERROR if the level parameter is invalid.
  79836. */
  79837. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  79838. uLong sourceLen, int level)
  79839. {
  79840. z_stream stream;
  79841. int err;
  79842. stream.next_in = (Bytef*)source;
  79843. stream.avail_in = (uInt)sourceLen;
  79844. #ifdef MAXSEG_64K
  79845. /* Check for source > 64K on 16-bit machine: */
  79846. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  79847. #endif
  79848. stream.next_out = dest;
  79849. stream.avail_out = (uInt)*destLen;
  79850. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  79851. stream.zalloc = (alloc_func)0;
  79852. stream.zfree = (free_func)0;
  79853. stream.opaque = (voidpf)0;
  79854. err = deflateInit(&stream, level);
  79855. if (err != Z_OK) return err;
  79856. err = deflate(&stream, Z_FINISH);
  79857. if (err != Z_STREAM_END) {
  79858. deflateEnd(&stream);
  79859. return err == Z_OK ? Z_BUF_ERROR : err;
  79860. }
  79861. *destLen = stream.total_out;
  79862. err = deflateEnd(&stream);
  79863. return err;
  79864. }
  79865. /* ===========================================================================
  79866. */
  79867. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  79868. {
  79869. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  79870. }
  79871. /* ===========================================================================
  79872. If the default memLevel or windowBits for deflateInit() is changed, then
  79873. this function needs to be updated.
  79874. */
  79875. uLong ZEXPORT compressBound (uLong sourceLen)
  79876. {
  79877. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  79878. }
  79879. /*** End of inlined file: compress.c ***/
  79880. #undef DO1
  79881. #undef DO8
  79882. /*** Start of inlined file: crc32.c ***/
  79883. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79884. /*
  79885. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  79886. protection on the static variables used to control the first-use generation
  79887. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  79888. first call get_crc_table() to initialize the tables before allowing more than
  79889. one thread to use crc32().
  79890. */
  79891. #ifdef MAKECRCH
  79892. # include <stdio.h>
  79893. # ifndef DYNAMIC_CRC_TABLE
  79894. # define DYNAMIC_CRC_TABLE
  79895. # endif /* !DYNAMIC_CRC_TABLE */
  79896. #endif /* MAKECRCH */
  79897. /*** Start of inlined file: zutil.h ***/
  79898. /* WARNING: this file should *not* be used by applications. It is
  79899. part of the implementation of the compression library and is
  79900. subject to change. Applications should only use zlib.h.
  79901. */
  79902. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79903. #ifndef ZUTIL_H
  79904. #define ZUTIL_H
  79905. #define ZLIB_INTERNAL
  79906. #ifdef STDC
  79907. # ifndef _WIN32_WCE
  79908. # include <stddef.h>
  79909. # endif
  79910. # include <string.h>
  79911. # include <stdlib.h>
  79912. #endif
  79913. #ifdef NO_ERRNO_H
  79914. # ifdef _WIN32_WCE
  79915. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  79916. * errno. We define it as a global variable to simplify porting.
  79917. * Its value is always 0 and should not be used. We rename it to
  79918. * avoid conflict with other libraries that use the same workaround.
  79919. */
  79920. # define errno z_errno
  79921. # endif
  79922. extern int errno;
  79923. #else
  79924. # ifndef _WIN32_WCE
  79925. # include <errno.h>
  79926. # endif
  79927. #endif
  79928. #ifndef local
  79929. # define local static
  79930. #endif
  79931. /* compile with -Dlocal if your debugger can't find static symbols */
  79932. typedef unsigned char uch;
  79933. typedef uch FAR uchf;
  79934. typedef unsigned short ush;
  79935. typedef ush FAR ushf;
  79936. typedef unsigned long ulg;
  79937. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  79938. /* (size given to avoid silly warnings with Visual C++) */
  79939. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  79940. #define ERR_RETURN(strm,err) \
  79941. return (strm->msg = (char*)ERR_MSG(err), (err))
  79942. /* To be used only when the state is known to be valid */
  79943. /* common constants */
  79944. #ifndef DEF_WBITS
  79945. # define DEF_WBITS MAX_WBITS
  79946. #endif
  79947. /* default windowBits for decompression. MAX_WBITS is for compression only */
  79948. #if MAX_MEM_LEVEL >= 8
  79949. # define DEF_MEM_LEVEL 8
  79950. #else
  79951. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  79952. #endif
  79953. /* default memLevel */
  79954. #define STORED_BLOCK 0
  79955. #define STATIC_TREES 1
  79956. #define DYN_TREES 2
  79957. /* The three kinds of block type */
  79958. #define MIN_MATCH 3
  79959. #define MAX_MATCH 258
  79960. /* The minimum and maximum match lengths */
  79961. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  79962. /* target dependencies */
  79963. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  79964. # define OS_CODE 0x00
  79965. # if defined(__TURBOC__) || defined(__BORLANDC__)
  79966. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  79967. /* Allow compilation with ANSI keywords only enabled */
  79968. void _Cdecl farfree( void *block );
  79969. void *_Cdecl farmalloc( unsigned long nbytes );
  79970. # else
  79971. # include <alloc.h>
  79972. # endif
  79973. # else /* MSC or DJGPP */
  79974. # include <malloc.h>
  79975. # endif
  79976. #endif
  79977. #ifdef AMIGA
  79978. # define OS_CODE 0x01
  79979. #endif
  79980. #if defined(VAXC) || defined(VMS)
  79981. # define OS_CODE 0x02
  79982. # define F_OPEN(name, mode) \
  79983. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  79984. #endif
  79985. #if defined(ATARI) || defined(atarist)
  79986. # define OS_CODE 0x05
  79987. #endif
  79988. #ifdef OS2
  79989. # define OS_CODE 0x06
  79990. # ifdef M_I86
  79991. #include <malloc.h>
  79992. # endif
  79993. #endif
  79994. #if defined(MACOS) || TARGET_OS_MAC
  79995. # define OS_CODE 0x07
  79996. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  79997. # include <unix.h> /* for fdopen */
  79998. # else
  79999. # ifndef fdopen
  80000. # define fdopen(fd,mode) NULL /* No fdopen() */
  80001. # endif
  80002. # endif
  80003. #endif
  80004. #ifdef TOPS20
  80005. # define OS_CODE 0x0a
  80006. #endif
  80007. #ifdef WIN32
  80008. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  80009. # define OS_CODE 0x0b
  80010. # endif
  80011. #endif
  80012. #ifdef __50SERIES /* Prime/PRIMOS */
  80013. # define OS_CODE 0x0f
  80014. #endif
  80015. #if defined(_BEOS_) || defined(RISCOS)
  80016. # define fdopen(fd,mode) NULL /* No fdopen() */
  80017. #endif
  80018. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  80019. # if defined(_WIN32_WCE)
  80020. # define fdopen(fd,mode) NULL /* No fdopen() */
  80021. # ifndef _PTRDIFF_T_DEFINED
  80022. typedef int ptrdiff_t;
  80023. # define _PTRDIFF_T_DEFINED
  80024. # endif
  80025. # else
  80026. # define fdopen(fd,type) _fdopen(fd,type)
  80027. # endif
  80028. #endif
  80029. /* common defaults */
  80030. #ifndef OS_CODE
  80031. # define OS_CODE 0x03 /* assume Unix */
  80032. #endif
  80033. #ifndef F_OPEN
  80034. # define F_OPEN(name, mode) fopen((name), (mode))
  80035. #endif
  80036. /* functions */
  80037. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  80038. # ifndef HAVE_VSNPRINTF
  80039. # define HAVE_VSNPRINTF
  80040. # endif
  80041. #endif
  80042. #if defined(__CYGWIN__)
  80043. # ifndef HAVE_VSNPRINTF
  80044. # define HAVE_VSNPRINTF
  80045. # endif
  80046. #endif
  80047. #ifndef HAVE_VSNPRINTF
  80048. # ifdef MSDOS
  80049. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  80050. but for now we just assume it doesn't. */
  80051. # define NO_vsnprintf
  80052. # endif
  80053. # ifdef __TURBOC__
  80054. # define NO_vsnprintf
  80055. # endif
  80056. # ifdef WIN32
  80057. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  80058. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  80059. # define vsnprintf _vsnprintf
  80060. # endif
  80061. # endif
  80062. # ifdef __SASC
  80063. # define NO_vsnprintf
  80064. # endif
  80065. #endif
  80066. #ifdef VMS
  80067. # define NO_vsnprintf
  80068. #endif
  80069. #if defined(pyr)
  80070. # define NO_MEMCPY
  80071. #endif
  80072. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  80073. /* Use our own functions for small and medium model with MSC <= 5.0.
  80074. * You may have to use the same strategy for Borland C (untested).
  80075. * The __SC__ check is for Symantec.
  80076. */
  80077. # define NO_MEMCPY
  80078. #endif
  80079. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  80080. # define HAVE_MEMCPY
  80081. #endif
  80082. #ifdef HAVE_MEMCPY
  80083. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  80084. # define zmemcpy _fmemcpy
  80085. # define zmemcmp _fmemcmp
  80086. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  80087. # else
  80088. # define zmemcpy memcpy
  80089. # define zmemcmp memcmp
  80090. # define zmemzero(dest, len) memset(dest, 0, len)
  80091. # endif
  80092. #else
  80093. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  80094. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  80095. extern void zmemzero OF((Bytef* dest, uInt len));
  80096. #endif
  80097. /* Diagnostic functions */
  80098. #ifdef DEBUG
  80099. # include <stdio.h>
  80100. extern int z_verbose;
  80101. extern void z_error OF((const char *m));
  80102. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  80103. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  80104. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  80105. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  80106. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  80107. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  80108. #else
  80109. # define Assert(cond,msg)
  80110. # define Trace(x)
  80111. # define Tracev(x)
  80112. # define Tracevv(x)
  80113. # define Tracec(c,x)
  80114. # define Tracecv(c,x)
  80115. #endif
  80116. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  80117. void zcfree OF((voidpf opaque, voidpf ptr));
  80118. #define ZALLOC(strm, items, size) \
  80119. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  80120. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  80121. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  80122. #endif /* ZUTIL_H */
  80123. /*** End of inlined file: zutil.h ***/
  80124. /* for STDC and FAR definitions */
  80125. #define local static
  80126. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  80127. #ifndef NOBYFOUR
  80128. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  80129. # include <limits.h>
  80130. # define BYFOUR
  80131. # if (UINT_MAX == 0xffffffffUL)
  80132. typedef unsigned int u4;
  80133. # else
  80134. # if (ULONG_MAX == 0xffffffffUL)
  80135. typedef unsigned long u4;
  80136. # else
  80137. # if (USHRT_MAX == 0xffffffffUL)
  80138. typedef unsigned short u4;
  80139. # else
  80140. # undef BYFOUR /* can't find a four-byte integer type! */
  80141. # endif
  80142. # endif
  80143. # endif
  80144. # endif /* STDC */
  80145. #endif /* !NOBYFOUR */
  80146. /* Definitions for doing the crc four data bytes at a time. */
  80147. #ifdef BYFOUR
  80148. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  80149. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  80150. local unsigned long crc32_little OF((unsigned long,
  80151. const unsigned char FAR *, unsigned));
  80152. local unsigned long crc32_big OF((unsigned long,
  80153. const unsigned char FAR *, unsigned));
  80154. # define TBLS 8
  80155. #else
  80156. # define TBLS 1
  80157. #endif /* BYFOUR */
  80158. /* Local functions for crc concatenation */
  80159. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  80160. unsigned long vec));
  80161. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  80162. #ifdef DYNAMIC_CRC_TABLE
  80163. local volatile int crc_table_empty = 1;
  80164. local unsigned long FAR crc_table[TBLS][256];
  80165. local void make_crc_table OF((void));
  80166. #ifdef MAKECRCH
  80167. local void write_table OF((FILE *, const unsigned long FAR *));
  80168. #endif /* MAKECRCH */
  80169. /*
  80170. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  80171. 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.
  80172. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  80173. with the lowest powers in the most significant bit. Then adding polynomials
  80174. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  80175. one. If we call the above polynomial p, and represent a byte as the
  80176. polynomial q, also with the lowest power in the most significant bit (so the
  80177. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  80178. where a mod b means the remainder after dividing a by b.
  80179. This calculation is done using the shift-register method of multiplying and
  80180. taking the remainder. The register is initialized to zero, and for each
  80181. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  80182. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  80183. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  80184. out is a one). We start with the highest power (least significant bit) of
  80185. q and repeat for all eight bits of q.
  80186. The first table is simply the CRC of all possible eight bit values. This is
  80187. all the information needed to generate CRCs on data a byte at a time for all
  80188. combinations of CRC register values and incoming bytes. The remaining tables
  80189. allow for word-at-a-time CRC calculation for both big-endian and little-
  80190. endian machines, where a word is four bytes.
  80191. */
  80192. local void make_crc_table()
  80193. {
  80194. unsigned long c;
  80195. int n, k;
  80196. unsigned long poly; /* polynomial exclusive-or pattern */
  80197. /* terms of polynomial defining this crc (except x^32): */
  80198. static volatile int first = 1; /* flag to limit concurrent making */
  80199. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  80200. /* See if another task is already doing this (not thread-safe, but better
  80201. than nothing -- significantly reduces duration of vulnerability in
  80202. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  80203. if (first) {
  80204. first = 0;
  80205. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  80206. poly = 0UL;
  80207. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  80208. poly |= 1UL << (31 - p[n]);
  80209. /* generate a crc for every 8-bit value */
  80210. for (n = 0; n < 256; n++) {
  80211. c = (unsigned long)n;
  80212. for (k = 0; k < 8; k++)
  80213. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  80214. crc_table[0][n] = c;
  80215. }
  80216. #ifdef BYFOUR
  80217. /* generate crc for each value followed by one, two, and three zeros,
  80218. and then the byte reversal of those as well as the first table */
  80219. for (n = 0; n < 256; n++) {
  80220. c = crc_table[0][n];
  80221. crc_table[4][n] = REV(c);
  80222. for (k = 1; k < 4; k++) {
  80223. c = crc_table[0][c & 0xff] ^ (c >> 8);
  80224. crc_table[k][n] = c;
  80225. crc_table[k + 4][n] = REV(c);
  80226. }
  80227. }
  80228. #endif /* BYFOUR */
  80229. crc_table_empty = 0;
  80230. }
  80231. else { /* not first */
  80232. /* wait for the other guy to finish (not efficient, but rare) */
  80233. while (crc_table_empty)
  80234. ;
  80235. }
  80236. #ifdef MAKECRCH
  80237. /* write out CRC tables to crc32.h */
  80238. {
  80239. FILE *out;
  80240. out = fopen("crc32.h", "w");
  80241. if (out == NULL) return;
  80242. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  80243. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  80244. fprintf(out, "local const unsigned long FAR ");
  80245. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  80246. write_table(out, crc_table[0]);
  80247. # ifdef BYFOUR
  80248. fprintf(out, "#ifdef BYFOUR\n");
  80249. for (k = 1; k < 8; k++) {
  80250. fprintf(out, " },\n {\n");
  80251. write_table(out, crc_table[k]);
  80252. }
  80253. fprintf(out, "#endif\n");
  80254. # endif /* BYFOUR */
  80255. fprintf(out, " }\n};\n");
  80256. fclose(out);
  80257. }
  80258. #endif /* MAKECRCH */
  80259. }
  80260. #ifdef MAKECRCH
  80261. local void write_table(out, table)
  80262. FILE *out;
  80263. const unsigned long FAR *table;
  80264. {
  80265. int n;
  80266. for (n = 0; n < 256; n++)
  80267. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  80268. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  80269. }
  80270. #endif /* MAKECRCH */
  80271. #else /* !DYNAMIC_CRC_TABLE */
  80272. /* ========================================================================
  80273. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  80274. */
  80275. /*** Start of inlined file: crc32.h ***/
  80276. local const unsigned long FAR crc_table[TBLS][256] =
  80277. {
  80278. {
  80279. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  80280. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  80281. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  80282. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  80283. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  80284. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  80285. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  80286. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  80287. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  80288. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  80289. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  80290. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  80291. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  80292. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  80293. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  80294. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  80295. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  80296. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  80297. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  80298. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  80299. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  80300. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  80301. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  80302. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  80303. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  80304. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  80305. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  80306. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  80307. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  80308. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  80309. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  80310. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  80311. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  80312. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  80313. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  80314. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  80315. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  80316. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  80317. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  80318. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  80319. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  80320. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  80321. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  80322. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  80323. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  80324. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  80325. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  80326. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  80327. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  80328. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  80329. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  80330. 0x2d02ef8dUL
  80331. #ifdef BYFOUR
  80332. },
  80333. {
  80334. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  80335. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  80336. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  80337. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  80338. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  80339. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  80340. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  80341. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  80342. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  80343. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  80344. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  80345. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  80346. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  80347. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  80348. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  80349. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  80350. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  80351. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  80352. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  80353. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  80354. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  80355. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  80356. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  80357. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  80358. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  80359. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  80360. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  80361. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  80362. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  80363. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  80364. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  80365. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  80366. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  80367. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  80368. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  80369. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  80370. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  80371. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  80372. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  80373. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  80374. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  80375. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  80376. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  80377. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  80378. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  80379. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  80380. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  80381. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  80382. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  80383. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  80384. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  80385. 0x9324fd72UL
  80386. },
  80387. {
  80388. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  80389. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  80390. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  80391. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  80392. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  80393. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  80394. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  80395. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  80396. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  80397. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  80398. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  80399. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  80400. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  80401. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  80402. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  80403. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  80404. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  80405. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  80406. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  80407. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  80408. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  80409. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  80410. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  80411. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  80412. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  80413. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  80414. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  80415. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  80416. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  80417. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  80418. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  80419. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  80420. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  80421. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  80422. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  80423. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  80424. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  80425. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  80426. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  80427. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  80428. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  80429. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  80430. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  80431. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  80432. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  80433. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  80434. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  80435. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  80436. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  80437. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  80438. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  80439. 0xbe9834edUL
  80440. },
  80441. {
  80442. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  80443. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  80444. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  80445. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  80446. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  80447. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  80448. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  80449. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  80450. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  80451. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  80452. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  80453. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  80454. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  80455. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  80456. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  80457. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  80458. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  80459. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  80460. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  80461. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  80462. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  80463. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  80464. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  80465. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  80466. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  80467. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  80468. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  80469. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  80470. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  80471. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  80472. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  80473. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  80474. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  80475. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  80476. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  80477. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  80478. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  80479. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  80480. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  80481. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  80482. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  80483. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  80484. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  80485. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  80486. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  80487. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  80488. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  80489. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  80490. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  80491. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  80492. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  80493. 0xde0506f1UL
  80494. },
  80495. {
  80496. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  80497. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  80498. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  80499. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  80500. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  80501. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  80502. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  80503. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  80504. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  80505. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  80506. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  80507. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  80508. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  80509. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  80510. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  80511. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  80512. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  80513. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  80514. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  80515. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  80516. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  80517. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  80518. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  80519. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  80520. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  80521. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  80522. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  80523. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  80524. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  80525. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  80526. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  80527. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  80528. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  80529. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  80530. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  80531. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  80532. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  80533. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  80534. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  80535. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  80536. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  80537. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  80538. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  80539. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  80540. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  80541. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  80542. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  80543. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  80544. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  80545. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  80546. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  80547. 0x8def022dUL
  80548. },
  80549. {
  80550. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  80551. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  80552. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  80553. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  80554. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  80555. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  80556. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  80557. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  80558. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  80559. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  80560. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  80561. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  80562. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  80563. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  80564. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  80565. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  80566. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  80567. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  80568. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  80569. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  80570. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  80571. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  80572. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  80573. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  80574. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  80575. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  80576. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  80577. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  80578. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  80579. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  80580. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  80581. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  80582. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  80583. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  80584. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  80585. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  80586. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  80587. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  80588. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  80589. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  80590. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  80591. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  80592. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  80593. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  80594. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  80595. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  80596. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  80597. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  80598. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  80599. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  80600. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  80601. 0x72fd2493UL
  80602. },
  80603. {
  80604. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  80605. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  80606. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  80607. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  80608. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  80609. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  80610. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  80611. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  80612. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  80613. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  80614. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  80615. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  80616. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  80617. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  80618. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  80619. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  80620. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  80621. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  80622. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  80623. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  80624. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  80625. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  80626. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  80627. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  80628. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  80629. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  80630. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  80631. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  80632. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  80633. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  80634. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  80635. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  80636. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  80637. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  80638. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  80639. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  80640. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  80641. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  80642. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  80643. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  80644. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  80645. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  80646. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  80647. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  80648. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  80649. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  80650. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  80651. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  80652. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  80653. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  80654. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  80655. 0xed3498beUL
  80656. },
  80657. {
  80658. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  80659. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  80660. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  80661. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  80662. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  80663. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  80664. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  80665. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  80666. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  80667. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  80668. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  80669. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  80670. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  80671. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  80672. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  80673. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  80674. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  80675. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  80676. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  80677. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  80678. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  80679. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  80680. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  80681. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  80682. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  80683. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  80684. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  80685. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  80686. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  80687. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  80688. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  80689. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  80690. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  80691. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  80692. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  80693. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  80694. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  80695. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  80696. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  80697. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  80698. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  80699. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  80700. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  80701. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  80702. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  80703. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  80704. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  80705. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  80706. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  80707. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  80708. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  80709. 0xf10605deUL
  80710. #endif
  80711. }
  80712. };
  80713. /*** End of inlined file: crc32.h ***/
  80714. #endif /* DYNAMIC_CRC_TABLE */
  80715. /* =========================================================================
  80716. * This function can be used by asm versions of crc32()
  80717. */
  80718. const unsigned long FAR * ZEXPORT get_crc_table()
  80719. {
  80720. #ifdef DYNAMIC_CRC_TABLE
  80721. if (crc_table_empty)
  80722. make_crc_table();
  80723. #endif /* DYNAMIC_CRC_TABLE */
  80724. return (const unsigned long FAR *)crc_table;
  80725. }
  80726. /* ========================================================================= */
  80727. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  80728. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  80729. /* ========================================================================= */
  80730. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80731. {
  80732. if (buf == Z_NULL) return 0UL;
  80733. #ifdef DYNAMIC_CRC_TABLE
  80734. if (crc_table_empty)
  80735. make_crc_table();
  80736. #endif /* DYNAMIC_CRC_TABLE */
  80737. #ifdef BYFOUR
  80738. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  80739. u4 endian;
  80740. endian = 1;
  80741. if (*((unsigned char *)(&endian)))
  80742. return crc32_little(crc, buf, len);
  80743. else
  80744. return crc32_big(crc, buf, len);
  80745. }
  80746. #endif /* BYFOUR */
  80747. crc = crc ^ 0xffffffffUL;
  80748. while (len >= 8) {
  80749. DO8;
  80750. len -= 8;
  80751. }
  80752. if (len) do {
  80753. DO1;
  80754. } while (--len);
  80755. return crc ^ 0xffffffffUL;
  80756. }
  80757. #ifdef BYFOUR
  80758. /* ========================================================================= */
  80759. #define DOLIT4 c ^= *buf4++; \
  80760. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  80761. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  80762. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  80763. /* ========================================================================= */
  80764. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80765. {
  80766. register u4 c;
  80767. register const u4 FAR *buf4;
  80768. c = (u4)crc;
  80769. c = ~c;
  80770. while (len && ((ptrdiff_t)buf & 3)) {
  80771. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80772. len--;
  80773. }
  80774. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80775. while (len >= 32) {
  80776. DOLIT32;
  80777. len -= 32;
  80778. }
  80779. while (len >= 4) {
  80780. DOLIT4;
  80781. len -= 4;
  80782. }
  80783. buf = (const unsigned char FAR *)buf4;
  80784. if (len) do {
  80785. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80786. } while (--len);
  80787. c = ~c;
  80788. return (unsigned long)c;
  80789. }
  80790. /* ========================================================================= */
  80791. #define DOBIG4 c ^= *++buf4; \
  80792. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  80793. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  80794. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  80795. /* ========================================================================= */
  80796. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80797. {
  80798. register u4 c;
  80799. register const u4 FAR *buf4;
  80800. c = REV((u4)crc);
  80801. c = ~c;
  80802. while (len && ((ptrdiff_t)buf & 3)) {
  80803. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80804. len--;
  80805. }
  80806. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80807. buf4--;
  80808. while (len >= 32) {
  80809. DOBIG32;
  80810. len -= 32;
  80811. }
  80812. while (len >= 4) {
  80813. DOBIG4;
  80814. len -= 4;
  80815. }
  80816. buf4++;
  80817. buf = (const unsigned char FAR *)buf4;
  80818. if (len) do {
  80819. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  80820. } while (--len);
  80821. c = ~c;
  80822. return (unsigned long)(REV(c));
  80823. }
  80824. #endif /* BYFOUR */
  80825. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  80826. /* ========================================================================= */
  80827. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  80828. {
  80829. unsigned long sum;
  80830. sum = 0;
  80831. while (vec) {
  80832. if (vec & 1)
  80833. sum ^= *mat;
  80834. vec >>= 1;
  80835. mat++;
  80836. }
  80837. return sum;
  80838. }
  80839. /* ========================================================================= */
  80840. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  80841. {
  80842. int n;
  80843. for (n = 0; n < GF2_DIM; n++)
  80844. square[n] = gf2_matrix_times(mat, mat[n]);
  80845. }
  80846. /* ========================================================================= */
  80847. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  80848. {
  80849. int n;
  80850. unsigned long row;
  80851. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  80852. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  80853. /* degenerate case */
  80854. if (len2 == 0)
  80855. return crc1;
  80856. /* put operator for one zero bit in odd */
  80857. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  80858. row = 1;
  80859. for (n = 1; n < GF2_DIM; n++) {
  80860. odd[n] = row;
  80861. row <<= 1;
  80862. }
  80863. /* put operator for two zero bits in even */
  80864. gf2_matrix_square(even, odd);
  80865. /* put operator for four zero bits in odd */
  80866. gf2_matrix_square(odd, even);
  80867. /* apply len2 zeros to crc1 (first square will put the operator for one
  80868. zero byte, eight zero bits, in even) */
  80869. do {
  80870. /* apply zeros operator for this bit of len2 */
  80871. gf2_matrix_square(even, odd);
  80872. if (len2 & 1)
  80873. crc1 = gf2_matrix_times(even, crc1);
  80874. len2 >>= 1;
  80875. /* if no more bits set, then done */
  80876. if (len2 == 0)
  80877. break;
  80878. /* another iteration of the loop with odd and even swapped */
  80879. gf2_matrix_square(odd, even);
  80880. if (len2 & 1)
  80881. crc1 = gf2_matrix_times(odd, crc1);
  80882. len2 >>= 1;
  80883. /* if no more bits set, then done */
  80884. } while (len2 != 0);
  80885. /* return combined crc */
  80886. crc1 ^= crc2;
  80887. return crc1;
  80888. }
  80889. /*** End of inlined file: crc32.c ***/
  80890. /*** Start of inlined file: deflate.c ***/
  80891. /*
  80892. * ALGORITHM
  80893. *
  80894. * The "deflation" process depends on being able to identify portions
  80895. * of the input text which are identical to earlier input (within a
  80896. * sliding window trailing behind the input currently being processed).
  80897. *
  80898. * The most straightforward technique turns out to be the fastest for
  80899. * most input files: try all possible matches and select the longest.
  80900. * The key feature of this algorithm is that insertions into the string
  80901. * dictionary are very simple and thus fast, and deletions are avoided
  80902. * completely. Insertions are performed at each input character, whereas
  80903. * string matches are performed only when the previous match ends. So it
  80904. * is preferable to spend more time in matches to allow very fast string
  80905. * insertions and avoid deletions. The matching algorithm for small
  80906. * strings is inspired from that of Rabin & Karp. A brute force approach
  80907. * is used to find longer strings when a small match has been found.
  80908. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  80909. * (by Leonid Broukhis).
  80910. * A previous version of this file used a more sophisticated algorithm
  80911. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  80912. * time, but has a larger average cost, uses more memory and is patented.
  80913. * However the F&G algorithm may be faster for some highly redundant
  80914. * files if the parameter max_chain_length (described below) is too large.
  80915. *
  80916. * ACKNOWLEDGEMENTS
  80917. *
  80918. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  80919. * I found it in 'freeze' written by Leonid Broukhis.
  80920. * Thanks to many people for bug reports and testing.
  80921. *
  80922. * REFERENCES
  80923. *
  80924. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  80925. * Available in http://www.ietf.org/rfc/rfc1951.txt
  80926. *
  80927. * A description of the Rabin and Karp algorithm is given in the book
  80928. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  80929. *
  80930. * Fiala,E.R., and Greene,D.H.
  80931. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  80932. *
  80933. */
  80934. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80935. /*** Start of inlined file: deflate.h ***/
  80936. /* WARNING: this file should *not* be used by applications. It is
  80937. part of the implementation of the compression library and is
  80938. subject to change. Applications should only use zlib.h.
  80939. */
  80940. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80941. #ifndef DEFLATE_H
  80942. #define DEFLATE_H
  80943. /* define NO_GZIP when compiling if you want to disable gzip header and
  80944. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  80945. the crc code when it is not needed. For shared libraries, gzip encoding
  80946. should be left enabled. */
  80947. #ifndef NO_GZIP
  80948. # define GZIP
  80949. #endif
  80950. #define NO_DUMMY_DECL
  80951. /* ===========================================================================
  80952. * Internal compression state.
  80953. */
  80954. #define LENGTH_CODES 29
  80955. /* number of length codes, not counting the special END_BLOCK code */
  80956. #define LITERALS 256
  80957. /* number of literal bytes 0..255 */
  80958. #define L_CODES (LITERALS+1+LENGTH_CODES)
  80959. /* number of Literal or Length codes, including the END_BLOCK code */
  80960. #define D_CODES 30
  80961. /* number of distance codes */
  80962. #define BL_CODES 19
  80963. /* number of codes used to transfer the bit lengths */
  80964. #define HEAP_SIZE (2*L_CODES+1)
  80965. /* maximum heap size */
  80966. #define MAX_BITS 15
  80967. /* All codes must not exceed MAX_BITS bits */
  80968. #define INIT_STATE 42
  80969. #define EXTRA_STATE 69
  80970. #define NAME_STATE 73
  80971. #define COMMENT_STATE 91
  80972. #define HCRC_STATE 103
  80973. #define BUSY_STATE 113
  80974. #define FINISH_STATE 666
  80975. /* Stream status */
  80976. /* Data structure describing a single value and its code string. */
  80977. typedef struct ct_data_s {
  80978. union {
  80979. ush freq; /* frequency count */
  80980. ush code; /* bit string */
  80981. } fc;
  80982. union {
  80983. ush dad; /* father node in Huffman tree */
  80984. ush len; /* length of bit string */
  80985. } dl;
  80986. } FAR ct_data;
  80987. #define Freq fc.freq
  80988. #define Code fc.code
  80989. #define Dad dl.dad
  80990. #define Len dl.len
  80991. typedef struct static_tree_desc_s static_tree_desc;
  80992. typedef struct tree_desc_s {
  80993. ct_data *dyn_tree; /* the dynamic tree */
  80994. int max_code; /* largest code with non zero frequency */
  80995. static_tree_desc *stat_desc; /* the corresponding static tree */
  80996. } FAR tree_desc;
  80997. typedef ush Pos;
  80998. typedef Pos FAR Posf;
  80999. typedef unsigned IPos;
  81000. /* A Pos is an index in the character window. We use short instead of int to
  81001. * save space in the various tables. IPos is used only for parameter passing.
  81002. */
  81003. typedef struct internal_state {
  81004. z_streamp strm; /* pointer back to this zlib stream */
  81005. int status; /* as the name implies */
  81006. Bytef *pending_buf; /* output still pending */
  81007. ulg pending_buf_size; /* size of pending_buf */
  81008. Bytef *pending_out; /* next pending byte to output to the stream */
  81009. uInt pending; /* nb of bytes in the pending buffer */
  81010. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  81011. gz_headerp gzhead; /* gzip header information to write */
  81012. uInt gzindex; /* where in extra, name, or comment */
  81013. Byte method; /* STORED (for zip only) or DEFLATED */
  81014. int last_flush; /* value of flush param for previous deflate call */
  81015. /* used by deflate.c: */
  81016. uInt w_size; /* LZ77 window size (32K by default) */
  81017. uInt w_bits; /* log2(w_size) (8..16) */
  81018. uInt w_mask; /* w_size - 1 */
  81019. Bytef *window;
  81020. /* Sliding window. Input bytes are read into the second half of the window,
  81021. * and move to the first half later to keep a dictionary of at least wSize
  81022. * bytes. With this organization, matches are limited to a distance of
  81023. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  81024. * performed with a length multiple of the block size. Also, it limits
  81025. * the window size to 64K, which is quite useful on MSDOS.
  81026. * To do: use the user input buffer as sliding window.
  81027. */
  81028. ulg window_size;
  81029. /* Actual size of window: 2*wSize, except when the user input buffer
  81030. * is directly used as sliding window.
  81031. */
  81032. Posf *prev;
  81033. /* Link to older string with same hash index. To limit the size of this
  81034. * array to 64K, this link is maintained only for the last 32K strings.
  81035. * An index in this array is thus a window index modulo 32K.
  81036. */
  81037. Posf *head; /* Heads of the hash chains or NIL. */
  81038. uInt ins_h; /* hash index of string to be inserted */
  81039. uInt hash_size; /* number of elements in hash table */
  81040. uInt hash_bits; /* log2(hash_size) */
  81041. uInt hash_mask; /* hash_size-1 */
  81042. uInt hash_shift;
  81043. /* Number of bits by which ins_h must be shifted at each input
  81044. * step. It must be such that after MIN_MATCH steps, the oldest
  81045. * byte no longer takes part in the hash key, that is:
  81046. * hash_shift * MIN_MATCH >= hash_bits
  81047. */
  81048. long block_start;
  81049. /* Window position at the beginning of the current output block. Gets
  81050. * negative when the window is moved backwards.
  81051. */
  81052. uInt match_length; /* length of best match */
  81053. IPos prev_match; /* previous match */
  81054. int match_available; /* set if previous match exists */
  81055. uInt strstart; /* start of string to insert */
  81056. uInt match_start; /* start of matching string */
  81057. uInt lookahead; /* number of valid bytes ahead in window */
  81058. uInt prev_length;
  81059. /* Length of the best match at previous step. Matches not greater than this
  81060. * are discarded. This is used in the lazy match evaluation.
  81061. */
  81062. uInt max_chain_length;
  81063. /* To speed up deflation, hash chains are never searched beyond this
  81064. * length. A higher limit improves compression ratio but degrades the
  81065. * speed.
  81066. */
  81067. uInt max_lazy_match;
  81068. /* Attempt to find a better match only when the current match is strictly
  81069. * smaller than this value. This mechanism is used only for compression
  81070. * levels >= 4.
  81071. */
  81072. # define max_insert_length max_lazy_match
  81073. /* Insert new strings in the hash table only if the match length is not
  81074. * greater than this length. This saves time but degrades compression.
  81075. * max_insert_length is used only for compression levels <= 3.
  81076. */
  81077. int level; /* compression level (1..9) */
  81078. int strategy; /* favor or force Huffman coding*/
  81079. uInt good_match;
  81080. /* Use a faster search when the previous match is longer than this */
  81081. int nice_match; /* Stop searching when current match exceeds this */
  81082. /* used by trees.c: */
  81083. /* Didn't use ct_data typedef below to supress compiler warning */
  81084. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  81085. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  81086. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  81087. struct tree_desc_s l_desc; /* desc. for literal tree */
  81088. struct tree_desc_s d_desc; /* desc. for distance tree */
  81089. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  81090. ush bl_count[MAX_BITS+1];
  81091. /* number of codes at each bit length for an optimal tree */
  81092. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  81093. int heap_len; /* number of elements in the heap */
  81094. int heap_max; /* element of largest frequency */
  81095. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  81096. * The same heap array is used to build all trees.
  81097. */
  81098. uch depth[2*L_CODES+1];
  81099. /* Depth of each subtree used as tie breaker for trees of equal frequency
  81100. */
  81101. uchf *l_buf; /* buffer for literals or lengths */
  81102. uInt lit_bufsize;
  81103. /* Size of match buffer for literals/lengths. There are 4 reasons for
  81104. * limiting lit_bufsize to 64K:
  81105. * - frequencies can be kept in 16 bit counters
  81106. * - if compression is not successful for the first block, all input
  81107. * data is still in the window so we can still emit a stored block even
  81108. * when input comes from standard input. (This can also be done for
  81109. * all blocks if lit_bufsize is not greater than 32K.)
  81110. * - if compression is not successful for a file smaller than 64K, we can
  81111. * even emit a stored file instead of a stored block (saving 5 bytes).
  81112. * This is applicable only for zip (not gzip or zlib).
  81113. * - creating new Huffman trees less frequently may not provide fast
  81114. * adaptation to changes in the input data statistics. (Take for
  81115. * example a binary file with poorly compressible code followed by
  81116. * a highly compressible string table.) Smaller buffer sizes give
  81117. * fast adaptation but have of course the overhead of transmitting
  81118. * trees more frequently.
  81119. * - I can't count above 4
  81120. */
  81121. uInt last_lit; /* running index in l_buf */
  81122. ushf *d_buf;
  81123. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  81124. * the same number of elements. To use different lengths, an extra flag
  81125. * array would be necessary.
  81126. */
  81127. ulg opt_len; /* bit length of current block with optimal trees */
  81128. ulg static_len; /* bit length of current block with static trees */
  81129. uInt matches; /* number of string matches in current block */
  81130. int last_eob_len; /* bit length of EOB code for last block */
  81131. #ifdef DEBUG
  81132. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  81133. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  81134. #endif
  81135. ush bi_buf;
  81136. /* Output buffer. bits are inserted starting at the bottom (least
  81137. * significant bits).
  81138. */
  81139. int bi_valid;
  81140. /* Number of valid bits in bi_buf. All bits above the last valid bit
  81141. * are always zero.
  81142. */
  81143. } FAR deflate_state;
  81144. /* Output a byte on the stream.
  81145. * IN assertion: there is enough room in pending_buf.
  81146. */
  81147. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  81148. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  81149. /* Minimum amount of lookahead, except at the end of the input file.
  81150. * See deflate.c for comments about the MIN_MATCH+1.
  81151. */
  81152. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  81153. /* In order to simplify the code, particularly on 16 bit machines, match
  81154. * distances are limited to MAX_DIST instead of WSIZE.
  81155. */
  81156. /* in trees.c */
  81157. void _tr_init OF((deflate_state *s));
  81158. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  81159. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  81160. int eof));
  81161. void _tr_align OF((deflate_state *s));
  81162. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  81163. int eof));
  81164. #define d_code(dist) \
  81165. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  81166. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  81167. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  81168. * used.
  81169. */
  81170. #ifndef DEBUG
  81171. /* Inline versions of _tr_tally for speed: */
  81172. #if defined(GEN_TREES_H) || !defined(STDC)
  81173. extern uch _length_code[];
  81174. extern uch _dist_code[];
  81175. #else
  81176. extern const uch _length_code[];
  81177. extern const uch _dist_code[];
  81178. #endif
  81179. # define _tr_tally_lit(s, c, flush) \
  81180. { uch cc = (c); \
  81181. s->d_buf[s->last_lit] = 0; \
  81182. s->l_buf[s->last_lit++] = cc; \
  81183. s->dyn_ltree[cc].Freq++; \
  81184. flush = (s->last_lit == s->lit_bufsize-1); \
  81185. }
  81186. # define _tr_tally_dist(s, distance, length, flush) \
  81187. { uch len = (length); \
  81188. ush dist = (distance); \
  81189. s->d_buf[s->last_lit] = dist; \
  81190. s->l_buf[s->last_lit++] = len; \
  81191. dist--; \
  81192. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  81193. s->dyn_dtree[d_code(dist)].Freq++; \
  81194. flush = (s->last_lit == s->lit_bufsize-1); \
  81195. }
  81196. #else
  81197. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  81198. # define _tr_tally_dist(s, distance, length, flush) \
  81199. flush = _tr_tally(s, distance, length)
  81200. #endif
  81201. #endif /* DEFLATE_H */
  81202. /*** End of inlined file: deflate.h ***/
  81203. const char deflate_copyright[] =
  81204. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  81205. /*
  81206. If you use the zlib library in a product, an acknowledgment is welcome
  81207. in the documentation of your product. If for some reason you cannot
  81208. include such an acknowledgment, I would appreciate that you keep this
  81209. copyright string in the executable of your product.
  81210. */
  81211. /* ===========================================================================
  81212. * Function prototypes.
  81213. */
  81214. typedef enum {
  81215. need_more, /* block not completed, need more input or more output */
  81216. block_done, /* block flush performed */
  81217. finish_started, /* finish started, need only more output at next deflate */
  81218. finish_done /* finish done, accept no more input or output */
  81219. } block_state;
  81220. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  81221. /* Compression function. Returns the block state after the call. */
  81222. local void fill_window OF((deflate_state *s));
  81223. local block_state deflate_stored OF((deflate_state *s, int flush));
  81224. local block_state deflate_fast OF((deflate_state *s, int flush));
  81225. #ifndef FASTEST
  81226. local block_state deflate_slow OF((deflate_state *s, int flush));
  81227. #endif
  81228. local void lm_init OF((deflate_state *s));
  81229. local void putShortMSB OF((deflate_state *s, uInt b));
  81230. local void flush_pending OF((z_streamp strm));
  81231. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  81232. #ifndef FASTEST
  81233. #ifdef ASMV
  81234. void match_init OF((void)); /* asm code initialization */
  81235. uInt longest_match OF((deflate_state *s, IPos cur_match));
  81236. #else
  81237. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  81238. #endif
  81239. #endif
  81240. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  81241. #ifdef DEBUG
  81242. local void check_match OF((deflate_state *s, IPos start, IPos match,
  81243. int length));
  81244. #endif
  81245. /* ===========================================================================
  81246. * Local data
  81247. */
  81248. #define NIL 0
  81249. /* Tail of hash chains */
  81250. #ifndef TOO_FAR
  81251. # define TOO_FAR 4096
  81252. #endif
  81253. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  81254. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  81255. /* Minimum amount of lookahead, except at the end of the input file.
  81256. * See deflate.c for comments about the MIN_MATCH+1.
  81257. */
  81258. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  81259. * the desired pack level (0..9). The values given below have been tuned to
  81260. * exclude worst case performance for pathological files. Better values may be
  81261. * found for specific files.
  81262. */
  81263. typedef struct config_s {
  81264. ush good_length; /* reduce lazy search above this match length */
  81265. ush max_lazy; /* do not perform lazy search above this match length */
  81266. ush nice_length; /* quit search above this match length */
  81267. ush max_chain;
  81268. compress_func func;
  81269. } config;
  81270. #ifdef FASTEST
  81271. local const config configuration_table[2] = {
  81272. /* good lazy nice chain */
  81273. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  81274. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  81275. #else
  81276. local const config configuration_table[10] = {
  81277. /* good lazy nice chain */
  81278. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  81279. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  81280. /* 2 */ {4, 5, 16, 8, deflate_fast},
  81281. /* 3 */ {4, 6, 32, 32, deflate_fast},
  81282. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  81283. /* 5 */ {8, 16, 32, 32, deflate_slow},
  81284. /* 6 */ {8, 16, 128, 128, deflate_slow},
  81285. /* 7 */ {8, 32, 128, 256, deflate_slow},
  81286. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  81287. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  81288. #endif
  81289. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  81290. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  81291. * meaning.
  81292. */
  81293. #define EQUAL 0
  81294. /* result of memcmp for equal strings */
  81295. #ifndef NO_DUMMY_DECL
  81296. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  81297. #endif
  81298. /* ===========================================================================
  81299. * Update a hash value with the given input byte
  81300. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  81301. * input characters, so that a running hash key can be computed from the
  81302. * previous key instead of complete recalculation each time.
  81303. */
  81304. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  81305. /* ===========================================================================
  81306. * Insert string str in the dictionary and set match_head to the previous head
  81307. * of the hash chain (the most recent string with same hash key). Return
  81308. * the previous length of the hash chain.
  81309. * If this file is compiled with -DFASTEST, the compression level is forced
  81310. * to 1, and no hash chains are maintained.
  81311. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  81312. * input characters and the first MIN_MATCH bytes of str are valid
  81313. * (except for the last MIN_MATCH-1 bytes of the input file).
  81314. */
  81315. #ifdef FASTEST
  81316. #define INSERT_STRING(s, str, match_head) \
  81317. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  81318. match_head = s->head[s->ins_h], \
  81319. s->head[s->ins_h] = (Pos)(str))
  81320. #else
  81321. #define INSERT_STRING(s, str, match_head) \
  81322. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  81323. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  81324. s->head[s->ins_h] = (Pos)(str))
  81325. #endif
  81326. /* ===========================================================================
  81327. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  81328. * prev[] will be initialized on the fly.
  81329. */
  81330. #define CLEAR_HASH(s) \
  81331. s->head[s->hash_size-1] = NIL; \
  81332. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  81333. /* ========================================================================= */
  81334. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  81335. {
  81336. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  81337. Z_DEFAULT_STRATEGY, version, stream_size);
  81338. /* To do: ignore strm->next_in if we use it as window */
  81339. }
  81340. /* ========================================================================= */
  81341. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  81342. {
  81343. deflate_state *s;
  81344. int wrap = 1;
  81345. static const char my_version[] = ZLIB_VERSION;
  81346. ushf *overlay;
  81347. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  81348. * output size for (length,distance) codes is <= 24 bits.
  81349. */
  81350. if (version == Z_NULL || version[0] != my_version[0] ||
  81351. stream_size != sizeof(z_stream)) {
  81352. return Z_VERSION_ERROR;
  81353. }
  81354. if (strm == Z_NULL) return Z_STREAM_ERROR;
  81355. strm->msg = Z_NULL;
  81356. if (strm->zalloc == (alloc_func)0) {
  81357. strm->zalloc = zcalloc;
  81358. strm->opaque = (voidpf)0;
  81359. }
  81360. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  81361. #ifdef FASTEST
  81362. if (level != 0) level = 1;
  81363. #else
  81364. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81365. #endif
  81366. if (windowBits < 0) { /* suppress zlib wrapper */
  81367. wrap = 0;
  81368. windowBits = -windowBits;
  81369. }
  81370. #ifdef GZIP
  81371. else if (windowBits > 15) {
  81372. wrap = 2; /* write gzip wrapper instead */
  81373. windowBits -= 16;
  81374. }
  81375. #endif
  81376. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  81377. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  81378. strategy < 0 || strategy > Z_FIXED) {
  81379. return Z_STREAM_ERROR;
  81380. }
  81381. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  81382. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  81383. if (s == Z_NULL) return Z_MEM_ERROR;
  81384. strm->state = (struct internal_state FAR *)s;
  81385. s->strm = strm;
  81386. s->wrap = wrap;
  81387. s->gzhead = Z_NULL;
  81388. s->w_bits = windowBits;
  81389. s->w_size = 1 << s->w_bits;
  81390. s->w_mask = s->w_size - 1;
  81391. s->hash_bits = memLevel + 7;
  81392. s->hash_size = 1 << s->hash_bits;
  81393. s->hash_mask = s->hash_size - 1;
  81394. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  81395. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  81396. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  81397. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  81398. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  81399. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  81400. s->pending_buf = (uchf *) overlay;
  81401. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  81402. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  81403. s->pending_buf == Z_NULL) {
  81404. s->status = FINISH_STATE;
  81405. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  81406. deflateEnd (strm);
  81407. return Z_MEM_ERROR;
  81408. }
  81409. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  81410. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  81411. s->level = level;
  81412. s->strategy = strategy;
  81413. s->method = (Byte)method;
  81414. return deflateReset(strm);
  81415. }
  81416. /* ========================================================================= */
  81417. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  81418. {
  81419. deflate_state *s;
  81420. uInt length = dictLength;
  81421. uInt n;
  81422. IPos hash_head = 0;
  81423. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  81424. strm->state->wrap == 2 ||
  81425. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  81426. return Z_STREAM_ERROR;
  81427. s = strm->state;
  81428. if (s->wrap)
  81429. strm->adler = adler32(strm->adler, dictionary, dictLength);
  81430. if (length < MIN_MATCH) return Z_OK;
  81431. if (length > MAX_DIST(s)) {
  81432. length = MAX_DIST(s);
  81433. dictionary += dictLength - length; /* use the tail of the dictionary */
  81434. }
  81435. zmemcpy(s->window, dictionary, length);
  81436. s->strstart = length;
  81437. s->block_start = (long)length;
  81438. /* Insert all strings in the hash table (except for the last two bytes).
  81439. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  81440. * call of fill_window.
  81441. */
  81442. s->ins_h = s->window[0];
  81443. UPDATE_HASH(s, s->ins_h, s->window[1]);
  81444. for (n = 0; n <= length - MIN_MATCH; n++) {
  81445. INSERT_STRING(s, n, hash_head);
  81446. }
  81447. if (hash_head) hash_head = 0; /* to make compiler happy */
  81448. return Z_OK;
  81449. }
  81450. /* ========================================================================= */
  81451. int ZEXPORT deflateReset (z_streamp strm)
  81452. {
  81453. deflate_state *s;
  81454. if (strm == Z_NULL || strm->state == Z_NULL ||
  81455. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  81456. return Z_STREAM_ERROR;
  81457. }
  81458. strm->total_in = strm->total_out = 0;
  81459. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  81460. strm->data_type = Z_UNKNOWN;
  81461. s = (deflate_state *)strm->state;
  81462. s->pending = 0;
  81463. s->pending_out = s->pending_buf;
  81464. if (s->wrap < 0) {
  81465. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  81466. }
  81467. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  81468. strm->adler =
  81469. #ifdef GZIP
  81470. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  81471. #endif
  81472. adler32(0L, Z_NULL, 0);
  81473. s->last_flush = Z_NO_FLUSH;
  81474. _tr_init(s);
  81475. lm_init(s);
  81476. return Z_OK;
  81477. }
  81478. /* ========================================================================= */
  81479. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  81480. {
  81481. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81482. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  81483. strm->state->gzhead = head;
  81484. return Z_OK;
  81485. }
  81486. /* ========================================================================= */
  81487. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  81488. {
  81489. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81490. strm->state->bi_valid = bits;
  81491. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  81492. return Z_OK;
  81493. }
  81494. /* ========================================================================= */
  81495. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  81496. {
  81497. deflate_state *s;
  81498. compress_func func;
  81499. int err = Z_OK;
  81500. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81501. s = strm->state;
  81502. #ifdef FASTEST
  81503. if (level != 0) level = 1;
  81504. #else
  81505. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81506. #endif
  81507. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  81508. return Z_STREAM_ERROR;
  81509. }
  81510. func = configuration_table[s->level].func;
  81511. if (func != configuration_table[level].func && strm->total_in != 0) {
  81512. /* Flush the last buffer: */
  81513. err = deflate(strm, Z_PARTIAL_FLUSH);
  81514. }
  81515. if (s->level != level) {
  81516. s->level = level;
  81517. s->max_lazy_match = configuration_table[level].max_lazy;
  81518. s->good_match = configuration_table[level].good_length;
  81519. s->nice_match = configuration_table[level].nice_length;
  81520. s->max_chain_length = configuration_table[level].max_chain;
  81521. }
  81522. s->strategy = strategy;
  81523. return err;
  81524. }
  81525. /* ========================================================================= */
  81526. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  81527. {
  81528. deflate_state *s;
  81529. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81530. s = strm->state;
  81531. s->good_match = good_length;
  81532. s->max_lazy_match = max_lazy;
  81533. s->nice_match = nice_length;
  81534. s->max_chain_length = max_chain;
  81535. return Z_OK;
  81536. }
  81537. /* =========================================================================
  81538. * For the default windowBits of 15 and memLevel of 8, this function returns
  81539. * a close to exact, as well as small, upper bound on the compressed size.
  81540. * They are coded as constants here for a reason--if the #define's are
  81541. * changed, then this function needs to be changed as well. The return
  81542. * value for 15 and 8 only works for those exact settings.
  81543. *
  81544. * For any setting other than those defaults for windowBits and memLevel,
  81545. * the value returned is a conservative worst case for the maximum expansion
  81546. * resulting from using fixed blocks instead of stored blocks, which deflate
  81547. * can emit on compressed data for some combinations of the parameters.
  81548. *
  81549. * This function could be more sophisticated to provide closer upper bounds
  81550. * for every combination of windowBits and memLevel, as well as wrap.
  81551. * But even the conservative upper bound of about 14% expansion does not
  81552. * seem onerous for output buffer allocation.
  81553. */
  81554. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  81555. {
  81556. deflate_state *s;
  81557. uLong destLen;
  81558. /* conservative upper bound */
  81559. destLen = sourceLen +
  81560. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  81561. /* if can't get parameters, return conservative bound */
  81562. if (strm == Z_NULL || strm->state == Z_NULL)
  81563. return destLen;
  81564. /* if not default parameters, return conservative bound */
  81565. s = strm->state;
  81566. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  81567. return destLen;
  81568. /* default settings: return tight bound for that case */
  81569. return compressBound(sourceLen);
  81570. }
  81571. /* =========================================================================
  81572. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  81573. * IN assertion: the stream state is correct and there is enough room in
  81574. * pending_buf.
  81575. */
  81576. local void putShortMSB (deflate_state *s, uInt b)
  81577. {
  81578. put_byte(s, (Byte)(b >> 8));
  81579. put_byte(s, (Byte)(b & 0xff));
  81580. }
  81581. /* =========================================================================
  81582. * Flush as much pending output as possible. All deflate() output goes
  81583. * through this function so some applications may wish to modify it
  81584. * to avoid allocating a large strm->next_out buffer and copying into it.
  81585. * (See also read_buf()).
  81586. */
  81587. local void flush_pending (z_streamp strm)
  81588. {
  81589. unsigned len = strm->state->pending;
  81590. if (len > strm->avail_out) len = strm->avail_out;
  81591. if (len == 0) return;
  81592. zmemcpy(strm->next_out, strm->state->pending_out, len);
  81593. strm->next_out += len;
  81594. strm->state->pending_out += len;
  81595. strm->total_out += len;
  81596. strm->avail_out -= len;
  81597. strm->state->pending -= len;
  81598. if (strm->state->pending == 0) {
  81599. strm->state->pending_out = strm->state->pending_buf;
  81600. }
  81601. }
  81602. /* ========================================================================= */
  81603. int ZEXPORT deflate (z_streamp strm, int flush)
  81604. {
  81605. int old_flush; /* value of flush param for previous deflate call */
  81606. deflate_state *s;
  81607. if (strm == Z_NULL || strm->state == Z_NULL ||
  81608. flush > Z_FINISH || flush < 0) {
  81609. return Z_STREAM_ERROR;
  81610. }
  81611. s = strm->state;
  81612. if (strm->next_out == Z_NULL ||
  81613. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  81614. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  81615. ERR_RETURN(strm, Z_STREAM_ERROR);
  81616. }
  81617. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  81618. s->strm = strm; /* just in case */
  81619. old_flush = s->last_flush;
  81620. s->last_flush = flush;
  81621. /* Write the header */
  81622. if (s->status == INIT_STATE) {
  81623. #ifdef GZIP
  81624. if (s->wrap == 2) {
  81625. strm->adler = crc32(0L, Z_NULL, 0);
  81626. put_byte(s, 31);
  81627. put_byte(s, 139);
  81628. put_byte(s, 8);
  81629. if (s->gzhead == NULL) {
  81630. put_byte(s, 0);
  81631. put_byte(s, 0);
  81632. put_byte(s, 0);
  81633. put_byte(s, 0);
  81634. put_byte(s, 0);
  81635. put_byte(s, s->level == 9 ? 2 :
  81636. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81637. 4 : 0));
  81638. put_byte(s, OS_CODE);
  81639. s->status = BUSY_STATE;
  81640. }
  81641. else {
  81642. put_byte(s, (s->gzhead->text ? 1 : 0) +
  81643. (s->gzhead->hcrc ? 2 : 0) +
  81644. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  81645. (s->gzhead->name == Z_NULL ? 0 : 8) +
  81646. (s->gzhead->comment == Z_NULL ? 0 : 16)
  81647. );
  81648. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  81649. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  81650. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  81651. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  81652. put_byte(s, s->level == 9 ? 2 :
  81653. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81654. 4 : 0));
  81655. put_byte(s, s->gzhead->os & 0xff);
  81656. if (s->gzhead->extra != NULL) {
  81657. put_byte(s, s->gzhead->extra_len & 0xff);
  81658. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  81659. }
  81660. if (s->gzhead->hcrc)
  81661. strm->adler = crc32(strm->adler, s->pending_buf,
  81662. s->pending);
  81663. s->gzindex = 0;
  81664. s->status = EXTRA_STATE;
  81665. }
  81666. }
  81667. else
  81668. #endif
  81669. {
  81670. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  81671. uInt level_flags;
  81672. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  81673. level_flags = 0;
  81674. else if (s->level < 6)
  81675. level_flags = 1;
  81676. else if (s->level == 6)
  81677. level_flags = 2;
  81678. else
  81679. level_flags = 3;
  81680. header |= (level_flags << 6);
  81681. if (s->strstart != 0) header |= PRESET_DICT;
  81682. header += 31 - (header % 31);
  81683. s->status = BUSY_STATE;
  81684. putShortMSB(s, header);
  81685. /* Save the adler32 of the preset dictionary: */
  81686. if (s->strstart != 0) {
  81687. putShortMSB(s, (uInt)(strm->adler >> 16));
  81688. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81689. }
  81690. strm->adler = adler32(0L, Z_NULL, 0);
  81691. }
  81692. }
  81693. #ifdef GZIP
  81694. if (s->status == EXTRA_STATE) {
  81695. if (s->gzhead->extra != NULL) {
  81696. uInt beg = s->pending; /* start of bytes to update crc */
  81697. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  81698. if (s->pending == s->pending_buf_size) {
  81699. if (s->gzhead->hcrc && s->pending > beg)
  81700. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81701. s->pending - beg);
  81702. flush_pending(strm);
  81703. beg = s->pending;
  81704. if (s->pending == s->pending_buf_size)
  81705. break;
  81706. }
  81707. put_byte(s, s->gzhead->extra[s->gzindex]);
  81708. s->gzindex++;
  81709. }
  81710. if (s->gzhead->hcrc && s->pending > beg)
  81711. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81712. s->pending - beg);
  81713. if (s->gzindex == s->gzhead->extra_len) {
  81714. s->gzindex = 0;
  81715. s->status = NAME_STATE;
  81716. }
  81717. }
  81718. else
  81719. s->status = NAME_STATE;
  81720. }
  81721. if (s->status == NAME_STATE) {
  81722. if (s->gzhead->name != NULL) {
  81723. uInt beg = s->pending; /* start of bytes to update crc */
  81724. int val;
  81725. do {
  81726. if (s->pending == s->pending_buf_size) {
  81727. if (s->gzhead->hcrc && s->pending > beg)
  81728. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81729. s->pending - beg);
  81730. flush_pending(strm);
  81731. beg = s->pending;
  81732. if (s->pending == s->pending_buf_size) {
  81733. val = 1;
  81734. break;
  81735. }
  81736. }
  81737. val = s->gzhead->name[s->gzindex++];
  81738. put_byte(s, val);
  81739. } while (val != 0);
  81740. if (s->gzhead->hcrc && s->pending > beg)
  81741. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81742. s->pending - beg);
  81743. if (val == 0) {
  81744. s->gzindex = 0;
  81745. s->status = COMMENT_STATE;
  81746. }
  81747. }
  81748. else
  81749. s->status = COMMENT_STATE;
  81750. }
  81751. if (s->status == COMMENT_STATE) {
  81752. if (s->gzhead->comment != NULL) {
  81753. uInt beg = s->pending; /* start of bytes to update crc */
  81754. int val;
  81755. do {
  81756. if (s->pending == s->pending_buf_size) {
  81757. if (s->gzhead->hcrc && s->pending > beg)
  81758. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81759. s->pending - beg);
  81760. flush_pending(strm);
  81761. beg = s->pending;
  81762. if (s->pending == s->pending_buf_size) {
  81763. val = 1;
  81764. break;
  81765. }
  81766. }
  81767. val = s->gzhead->comment[s->gzindex++];
  81768. put_byte(s, val);
  81769. } while (val != 0);
  81770. if (s->gzhead->hcrc && s->pending > beg)
  81771. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81772. s->pending - beg);
  81773. if (val == 0)
  81774. s->status = HCRC_STATE;
  81775. }
  81776. else
  81777. s->status = HCRC_STATE;
  81778. }
  81779. if (s->status == HCRC_STATE) {
  81780. if (s->gzhead->hcrc) {
  81781. if (s->pending + 2 > s->pending_buf_size)
  81782. flush_pending(strm);
  81783. if (s->pending + 2 <= s->pending_buf_size) {
  81784. put_byte(s, (Byte)(strm->adler & 0xff));
  81785. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81786. strm->adler = crc32(0L, Z_NULL, 0);
  81787. s->status = BUSY_STATE;
  81788. }
  81789. }
  81790. else
  81791. s->status = BUSY_STATE;
  81792. }
  81793. #endif
  81794. /* Flush as much pending output as possible */
  81795. if (s->pending != 0) {
  81796. flush_pending(strm);
  81797. if (strm->avail_out == 0) {
  81798. /* Since avail_out is 0, deflate will be called again with
  81799. * more output space, but possibly with both pending and
  81800. * avail_in equal to zero. There won't be anything to do,
  81801. * but this is not an error situation so make sure we
  81802. * return OK instead of BUF_ERROR at next call of deflate:
  81803. */
  81804. s->last_flush = -1;
  81805. return Z_OK;
  81806. }
  81807. /* Make sure there is something to do and avoid duplicate consecutive
  81808. * flushes. For repeated and useless calls with Z_FINISH, we keep
  81809. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  81810. */
  81811. } else if (strm->avail_in == 0 && flush <= old_flush &&
  81812. flush != Z_FINISH) {
  81813. ERR_RETURN(strm, Z_BUF_ERROR);
  81814. }
  81815. /* User must not provide more input after the first FINISH: */
  81816. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  81817. ERR_RETURN(strm, Z_BUF_ERROR);
  81818. }
  81819. /* Start a new block or continue the current one.
  81820. */
  81821. if (strm->avail_in != 0 || s->lookahead != 0 ||
  81822. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  81823. block_state bstate;
  81824. bstate = (*(configuration_table[s->level].func))(s, flush);
  81825. if (bstate == finish_started || bstate == finish_done) {
  81826. s->status = FINISH_STATE;
  81827. }
  81828. if (bstate == need_more || bstate == finish_started) {
  81829. if (strm->avail_out == 0) {
  81830. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  81831. }
  81832. return Z_OK;
  81833. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  81834. * of deflate should use the same flush parameter to make sure
  81835. * that the flush is complete. So we don't have to output an
  81836. * empty block here, this will be done at next call. This also
  81837. * ensures that for a very small output buffer, we emit at most
  81838. * one empty block.
  81839. */
  81840. }
  81841. if (bstate == block_done) {
  81842. if (flush == Z_PARTIAL_FLUSH) {
  81843. _tr_align(s);
  81844. } else { /* FULL_FLUSH or SYNC_FLUSH */
  81845. _tr_stored_block(s, (char*)0, 0L, 0);
  81846. /* For a full flush, this empty block will be recognized
  81847. * as a special marker by inflate_sync().
  81848. */
  81849. if (flush == Z_FULL_FLUSH) {
  81850. CLEAR_HASH(s); /* forget history */
  81851. }
  81852. }
  81853. flush_pending(strm);
  81854. if (strm->avail_out == 0) {
  81855. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  81856. return Z_OK;
  81857. }
  81858. }
  81859. }
  81860. Assert(strm->avail_out > 0, "bug2");
  81861. if (flush != Z_FINISH) return Z_OK;
  81862. if (s->wrap <= 0) return Z_STREAM_END;
  81863. /* Write the trailer */
  81864. #ifdef GZIP
  81865. if (s->wrap == 2) {
  81866. put_byte(s, (Byte)(strm->adler & 0xff));
  81867. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  81868. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  81869. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  81870. put_byte(s, (Byte)(strm->total_in & 0xff));
  81871. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  81872. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  81873. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  81874. }
  81875. else
  81876. #endif
  81877. {
  81878. putShortMSB(s, (uInt)(strm->adler >> 16));
  81879. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81880. }
  81881. flush_pending(strm);
  81882. /* If avail_out is zero, the application will call deflate again
  81883. * to flush the rest.
  81884. */
  81885. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  81886. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  81887. }
  81888. /* ========================================================================= */
  81889. int ZEXPORT deflateEnd (z_streamp strm)
  81890. {
  81891. int status;
  81892. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81893. status = strm->state->status;
  81894. if (status != INIT_STATE &&
  81895. status != EXTRA_STATE &&
  81896. status != NAME_STATE &&
  81897. status != COMMENT_STATE &&
  81898. status != HCRC_STATE &&
  81899. status != BUSY_STATE &&
  81900. status != FINISH_STATE) {
  81901. return Z_STREAM_ERROR;
  81902. }
  81903. /* Deallocate in reverse order of allocations: */
  81904. TRY_FREE(strm, strm->state->pending_buf);
  81905. TRY_FREE(strm, strm->state->head);
  81906. TRY_FREE(strm, strm->state->prev);
  81907. TRY_FREE(strm, strm->state->window);
  81908. ZFREE(strm, strm->state);
  81909. strm->state = Z_NULL;
  81910. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  81911. }
  81912. /* =========================================================================
  81913. * Copy the source state to the destination state.
  81914. * To simplify the source, this is not supported for 16-bit MSDOS (which
  81915. * doesn't have enough memory anyway to duplicate compression states).
  81916. */
  81917. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  81918. {
  81919. #ifdef MAXSEG_64K
  81920. return Z_STREAM_ERROR;
  81921. #else
  81922. deflate_state *ds;
  81923. deflate_state *ss;
  81924. ushf *overlay;
  81925. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  81926. return Z_STREAM_ERROR;
  81927. }
  81928. ss = source->state;
  81929. zmemcpy(dest, source, sizeof(z_stream));
  81930. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  81931. if (ds == Z_NULL) return Z_MEM_ERROR;
  81932. dest->state = (struct internal_state FAR *) ds;
  81933. zmemcpy(ds, ss, sizeof(deflate_state));
  81934. ds->strm = dest;
  81935. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  81936. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  81937. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  81938. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  81939. ds->pending_buf = (uchf *) overlay;
  81940. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  81941. ds->pending_buf == Z_NULL) {
  81942. deflateEnd (dest);
  81943. return Z_MEM_ERROR;
  81944. }
  81945. /* following zmemcpy do not work for 16-bit MSDOS */
  81946. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  81947. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  81948. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  81949. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  81950. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  81951. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  81952. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  81953. ds->l_desc.dyn_tree = ds->dyn_ltree;
  81954. ds->d_desc.dyn_tree = ds->dyn_dtree;
  81955. ds->bl_desc.dyn_tree = ds->bl_tree;
  81956. return Z_OK;
  81957. #endif /* MAXSEG_64K */
  81958. }
  81959. /* ===========================================================================
  81960. * Read a new buffer from the current input stream, update the adler32
  81961. * and total number of bytes read. All deflate() input goes through
  81962. * this function so some applications may wish to modify it to avoid
  81963. * allocating a large strm->next_in buffer and copying from it.
  81964. * (See also flush_pending()).
  81965. */
  81966. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  81967. {
  81968. unsigned len = strm->avail_in;
  81969. if (len > size) len = size;
  81970. if (len == 0) return 0;
  81971. strm->avail_in -= len;
  81972. if (strm->state->wrap == 1) {
  81973. strm->adler = adler32(strm->adler, strm->next_in, len);
  81974. }
  81975. #ifdef GZIP
  81976. else if (strm->state->wrap == 2) {
  81977. strm->adler = crc32(strm->adler, strm->next_in, len);
  81978. }
  81979. #endif
  81980. zmemcpy(buf, strm->next_in, len);
  81981. strm->next_in += len;
  81982. strm->total_in += len;
  81983. return (int)len;
  81984. }
  81985. /* ===========================================================================
  81986. * Initialize the "longest match" routines for a new zlib stream
  81987. */
  81988. local void lm_init (deflate_state *s)
  81989. {
  81990. s->window_size = (ulg)2L*s->w_size;
  81991. CLEAR_HASH(s);
  81992. /* Set the default configuration parameters:
  81993. */
  81994. s->max_lazy_match = configuration_table[s->level].max_lazy;
  81995. s->good_match = configuration_table[s->level].good_length;
  81996. s->nice_match = configuration_table[s->level].nice_length;
  81997. s->max_chain_length = configuration_table[s->level].max_chain;
  81998. s->strstart = 0;
  81999. s->block_start = 0L;
  82000. s->lookahead = 0;
  82001. s->match_length = s->prev_length = MIN_MATCH-1;
  82002. s->match_available = 0;
  82003. s->ins_h = 0;
  82004. #ifndef FASTEST
  82005. #ifdef ASMV
  82006. match_init(); /* initialize the asm code */
  82007. #endif
  82008. #endif
  82009. }
  82010. #ifndef FASTEST
  82011. /* ===========================================================================
  82012. * Set match_start to the longest match starting at the given string and
  82013. * return its length. Matches shorter or equal to prev_length are discarded,
  82014. * in which case the result is equal to prev_length and match_start is
  82015. * garbage.
  82016. * IN assertions: cur_match is the head of the hash chain for the current
  82017. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  82018. * OUT assertion: the match length is not greater than s->lookahead.
  82019. */
  82020. #ifndef ASMV
  82021. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  82022. * match.S. The code will be functionally equivalent.
  82023. */
  82024. local uInt longest_match(deflate_state *s, IPos cur_match)
  82025. {
  82026. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  82027. register Bytef *scan = s->window + s->strstart; /* current string */
  82028. register Bytef *match; /* matched string */
  82029. register int len; /* length of current match */
  82030. int best_len = s->prev_length; /* best match length so far */
  82031. int nice_match = s->nice_match; /* stop if match long enough */
  82032. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  82033. s->strstart - (IPos)MAX_DIST(s) : NIL;
  82034. /* Stop when cur_match becomes <= limit. To simplify the code,
  82035. * we prevent matches with the string of window index 0.
  82036. */
  82037. Posf *prev = s->prev;
  82038. uInt wmask = s->w_mask;
  82039. #ifdef UNALIGNED_OK
  82040. /* Compare two bytes at a time. Note: this is not always beneficial.
  82041. * Try with and without -DUNALIGNED_OK to check.
  82042. */
  82043. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  82044. register ush scan_start = *(ushf*)scan;
  82045. register ush scan_end = *(ushf*)(scan+best_len-1);
  82046. #else
  82047. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  82048. register Byte scan_end1 = scan[best_len-1];
  82049. register Byte scan_end = scan[best_len];
  82050. #endif
  82051. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  82052. * It is easy to get rid of this optimization if necessary.
  82053. */
  82054. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  82055. /* Do not waste too much time if we already have a good match: */
  82056. if (s->prev_length >= s->good_match) {
  82057. chain_length >>= 2;
  82058. }
  82059. /* Do not look for matches beyond the end of the input. This is necessary
  82060. * to make deflate deterministic.
  82061. */
  82062. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  82063. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  82064. do {
  82065. Assert(cur_match < s->strstart, "no future");
  82066. match = s->window + cur_match;
  82067. /* Skip to next match if the match length cannot increase
  82068. * or if the match length is less than 2. Note that the checks below
  82069. * for insufficient lookahead only occur occasionally for performance
  82070. * reasons. Therefore uninitialized memory will be accessed, and
  82071. * conditional jumps will be made that depend on those values.
  82072. * However the length of the match is limited to the lookahead, so
  82073. * the output of deflate is not affected by the uninitialized values.
  82074. */
  82075. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  82076. /* This code assumes sizeof(unsigned short) == 2. Do not use
  82077. * UNALIGNED_OK if your compiler uses a different size.
  82078. */
  82079. if (*(ushf*)(match+best_len-1) != scan_end ||
  82080. *(ushf*)match != scan_start) continue;
  82081. /* It is not necessary to compare scan[2] and match[2] since they are
  82082. * always equal when the other bytes match, given that the hash keys
  82083. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  82084. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  82085. * lookahead only every 4th comparison; the 128th check will be made
  82086. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  82087. * necessary to put more guard bytes at the end of the window, or
  82088. * to check more often for insufficient lookahead.
  82089. */
  82090. Assert(scan[2] == match[2], "scan[2]?");
  82091. scan++, match++;
  82092. do {
  82093. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82094. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82095. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82096. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82097. scan < strend);
  82098. /* The funny "do {}" generates better code on most compilers */
  82099. /* Here, scan <= window+strstart+257 */
  82100. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82101. if (*scan == *match) scan++;
  82102. len = (MAX_MATCH - 1) - (int)(strend-scan);
  82103. scan = strend - (MAX_MATCH-1);
  82104. #else /* UNALIGNED_OK */
  82105. if (match[best_len] != scan_end ||
  82106. match[best_len-1] != scan_end1 ||
  82107. *match != *scan ||
  82108. *++match != scan[1]) continue;
  82109. /* The check at best_len-1 can be removed because it will be made
  82110. * again later. (This heuristic is not always a win.)
  82111. * It is not necessary to compare scan[2] and match[2] since they
  82112. * are always equal when the other bytes match, given that
  82113. * the hash keys are equal and that HASH_BITS >= 8.
  82114. */
  82115. scan += 2, match++;
  82116. Assert(*scan == *match, "match[2]?");
  82117. /* We check for insufficient lookahead only every 8th comparison;
  82118. * the 256th check will be made at strstart+258.
  82119. */
  82120. do {
  82121. } while (*++scan == *++match && *++scan == *++match &&
  82122. *++scan == *++match && *++scan == *++match &&
  82123. *++scan == *++match && *++scan == *++match &&
  82124. *++scan == *++match && *++scan == *++match &&
  82125. scan < strend);
  82126. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82127. len = MAX_MATCH - (int)(strend - scan);
  82128. scan = strend - MAX_MATCH;
  82129. #endif /* UNALIGNED_OK */
  82130. if (len > best_len) {
  82131. s->match_start = cur_match;
  82132. best_len = len;
  82133. if (len >= nice_match) break;
  82134. #ifdef UNALIGNED_OK
  82135. scan_end = *(ushf*)(scan+best_len-1);
  82136. #else
  82137. scan_end1 = scan[best_len-1];
  82138. scan_end = scan[best_len];
  82139. #endif
  82140. }
  82141. } while ((cur_match = prev[cur_match & wmask]) > limit
  82142. && --chain_length != 0);
  82143. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  82144. return s->lookahead;
  82145. }
  82146. #endif /* ASMV */
  82147. #endif /* FASTEST */
  82148. /* ---------------------------------------------------------------------------
  82149. * Optimized version for level == 1 or strategy == Z_RLE only
  82150. */
  82151. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  82152. {
  82153. register Bytef *scan = s->window + s->strstart; /* current string */
  82154. register Bytef *match; /* matched string */
  82155. register int len; /* length of current match */
  82156. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  82157. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  82158. * It is easy to get rid of this optimization if necessary.
  82159. */
  82160. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  82161. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  82162. Assert(cur_match < s->strstart, "no future");
  82163. match = s->window + cur_match;
  82164. /* Return failure if the match length is less than 2:
  82165. */
  82166. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  82167. /* The check at best_len-1 can be removed because it will be made
  82168. * again later. (This heuristic is not always a win.)
  82169. * It is not necessary to compare scan[2] and match[2] since they
  82170. * are always equal when the other bytes match, given that
  82171. * the hash keys are equal and that HASH_BITS >= 8.
  82172. */
  82173. scan += 2, match += 2;
  82174. Assert(*scan == *match, "match[2]?");
  82175. /* We check for insufficient lookahead only every 8th comparison;
  82176. * the 256th check will be made at strstart+258.
  82177. */
  82178. do {
  82179. } while (*++scan == *++match && *++scan == *++match &&
  82180. *++scan == *++match && *++scan == *++match &&
  82181. *++scan == *++match && *++scan == *++match &&
  82182. *++scan == *++match && *++scan == *++match &&
  82183. scan < strend);
  82184. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82185. len = MAX_MATCH - (int)(strend - scan);
  82186. if (len < MIN_MATCH) return MIN_MATCH - 1;
  82187. s->match_start = cur_match;
  82188. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  82189. }
  82190. #ifdef DEBUG
  82191. /* ===========================================================================
  82192. * Check that the match at match_start is indeed a match.
  82193. */
  82194. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  82195. {
  82196. /* check that the match is indeed a match */
  82197. if (zmemcmp(s->window + match,
  82198. s->window + start, length) != EQUAL) {
  82199. fprintf(stderr, " start %u, match %u, length %d\n",
  82200. start, match, length);
  82201. do {
  82202. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  82203. } while (--length != 0);
  82204. z_error("invalid match");
  82205. }
  82206. if (z_verbose > 1) {
  82207. fprintf(stderr,"\\[%d,%d]", start-match, length);
  82208. do { putc(s->window[start++], stderr); } while (--length != 0);
  82209. }
  82210. }
  82211. #else
  82212. # define check_match(s, start, match, length)
  82213. #endif /* DEBUG */
  82214. /* ===========================================================================
  82215. * Fill the window when the lookahead becomes insufficient.
  82216. * Updates strstart and lookahead.
  82217. *
  82218. * IN assertion: lookahead < MIN_LOOKAHEAD
  82219. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  82220. * At least one byte has been read, or avail_in == 0; reads are
  82221. * performed for at least two bytes (required for the zip translate_eol
  82222. * option -- not supported here).
  82223. */
  82224. local void fill_window (deflate_state *s)
  82225. {
  82226. register unsigned n, m;
  82227. register Posf *p;
  82228. unsigned more; /* Amount of free space at the end of the window. */
  82229. uInt wsize = s->w_size;
  82230. do {
  82231. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  82232. /* Deal with !@#$% 64K limit: */
  82233. if (sizeof(int) <= 2) {
  82234. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  82235. more = wsize;
  82236. } else if (more == (unsigned)(-1)) {
  82237. /* Very unlikely, but possible on 16 bit machine if
  82238. * strstart == 0 && lookahead == 1 (input done a byte at time)
  82239. */
  82240. more--;
  82241. }
  82242. }
  82243. /* If the window is almost full and there is insufficient lookahead,
  82244. * move the upper half to the lower one to make room in the upper half.
  82245. */
  82246. if (s->strstart >= wsize+MAX_DIST(s)) {
  82247. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  82248. s->match_start -= wsize;
  82249. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  82250. s->block_start -= (long) wsize;
  82251. /* Slide the hash table (could be avoided with 32 bit values
  82252. at the expense of memory usage). We slide even when level == 0
  82253. to keep the hash table consistent if we switch back to level > 0
  82254. later. (Using level 0 permanently is not an optimal usage of
  82255. zlib, so we don't care about this pathological case.)
  82256. */
  82257. /* %%% avoid this when Z_RLE */
  82258. n = s->hash_size;
  82259. p = &s->head[n];
  82260. do {
  82261. m = *--p;
  82262. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  82263. } while (--n);
  82264. n = wsize;
  82265. #ifndef FASTEST
  82266. p = &s->prev[n];
  82267. do {
  82268. m = *--p;
  82269. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  82270. /* If n is not on any hash chain, prev[n] is garbage but
  82271. * its value will never be used.
  82272. */
  82273. } while (--n);
  82274. #endif
  82275. more += wsize;
  82276. }
  82277. if (s->strm->avail_in == 0) return;
  82278. /* If there was no sliding:
  82279. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  82280. * more == window_size - lookahead - strstart
  82281. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  82282. * => more >= window_size - 2*WSIZE + 2
  82283. * In the BIG_MEM or MMAP case (not yet supported),
  82284. * window_size == input_size + MIN_LOOKAHEAD &&
  82285. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  82286. * Otherwise, window_size == 2*WSIZE so more >= 2.
  82287. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  82288. */
  82289. Assert(more >= 2, "more < 2");
  82290. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  82291. s->lookahead += n;
  82292. /* Initialize the hash value now that we have some input: */
  82293. if (s->lookahead >= MIN_MATCH) {
  82294. s->ins_h = s->window[s->strstart];
  82295. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82296. #if MIN_MATCH != 3
  82297. Call UPDATE_HASH() MIN_MATCH-3 more times
  82298. #endif
  82299. }
  82300. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  82301. * but this is not important since only literal bytes will be emitted.
  82302. */
  82303. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  82304. }
  82305. /* ===========================================================================
  82306. * Flush the current block, with given end-of-file flag.
  82307. * IN assertion: strstart is set to the end of the current match.
  82308. */
  82309. #define FLUSH_BLOCK_ONLY(s, eof) { \
  82310. _tr_flush_block(s, (s->block_start >= 0L ? \
  82311. (charf *)&s->window[(unsigned)s->block_start] : \
  82312. (charf *)Z_NULL), \
  82313. (ulg)((long)s->strstart - s->block_start), \
  82314. (eof)); \
  82315. s->block_start = s->strstart; \
  82316. flush_pending(s->strm); \
  82317. Tracev((stderr,"[FLUSH]")); \
  82318. }
  82319. /* Same but force premature exit if necessary. */
  82320. #define FLUSH_BLOCK(s, eof) { \
  82321. FLUSH_BLOCK_ONLY(s, eof); \
  82322. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  82323. }
  82324. /* ===========================================================================
  82325. * Copy without compression as much as possible from the input stream, return
  82326. * the current block state.
  82327. * This function does not insert new strings in the dictionary since
  82328. * uncompressible data is probably not useful. This function is used
  82329. * only for the level=0 compression option.
  82330. * NOTE: this function should be optimized to avoid extra copying from
  82331. * window to pending_buf.
  82332. */
  82333. local block_state deflate_stored(deflate_state *s, int flush)
  82334. {
  82335. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  82336. * to pending_buf_size, and each stored block has a 5 byte header:
  82337. */
  82338. ulg max_block_size = 0xffff;
  82339. ulg max_start;
  82340. if (max_block_size > s->pending_buf_size - 5) {
  82341. max_block_size = s->pending_buf_size - 5;
  82342. }
  82343. /* Copy as much as possible from input to output: */
  82344. for (;;) {
  82345. /* Fill the window as much as possible: */
  82346. if (s->lookahead <= 1) {
  82347. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  82348. s->block_start >= (long)s->w_size, "slide too late");
  82349. fill_window(s);
  82350. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  82351. if (s->lookahead == 0) break; /* flush the current block */
  82352. }
  82353. Assert(s->block_start >= 0L, "block gone");
  82354. s->strstart += s->lookahead;
  82355. s->lookahead = 0;
  82356. /* Emit a stored block if pending_buf will be full: */
  82357. max_start = s->block_start + max_block_size;
  82358. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  82359. /* strstart == 0 is possible when wraparound on 16-bit machine */
  82360. s->lookahead = (uInt)(s->strstart - max_start);
  82361. s->strstart = (uInt)max_start;
  82362. FLUSH_BLOCK(s, 0);
  82363. }
  82364. /* Flush if we may have to slide, otherwise block_start may become
  82365. * negative and the data will be gone:
  82366. */
  82367. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  82368. FLUSH_BLOCK(s, 0);
  82369. }
  82370. }
  82371. FLUSH_BLOCK(s, flush == Z_FINISH);
  82372. return flush == Z_FINISH ? finish_done : block_done;
  82373. }
  82374. /* ===========================================================================
  82375. * Compress as much as possible from the input stream, return the current
  82376. * block state.
  82377. * This function does not perform lazy evaluation of matches and inserts
  82378. * new strings in the dictionary only for unmatched strings or for short
  82379. * matches. It is used only for the fast compression options.
  82380. */
  82381. local block_state deflate_fast(deflate_state *s, int flush)
  82382. {
  82383. IPos hash_head = NIL; /* head of the hash chain */
  82384. int bflush; /* set if current block must be flushed */
  82385. for (;;) {
  82386. /* Make sure that we always have enough lookahead, except
  82387. * at the end of the input file. We need MAX_MATCH bytes
  82388. * for the next match, plus MIN_MATCH bytes to insert the
  82389. * string following the next match.
  82390. */
  82391. if (s->lookahead < MIN_LOOKAHEAD) {
  82392. fill_window(s);
  82393. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82394. return need_more;
  82395. }
  82396. if (s->lookahead == 0) break; /* flush the current block */
  82397. }
  82398. /* Insert the string window[strstart .. strstart+2] in the
  82399. * dictionary, and set hash_head to the head of the hash chain:
  82400. */
  82401. if (s->lookahead >= MIN_MATCH) {
  82402. INSERT_STRING(s, s->strstart, hash_head);
  82403. }
  82404. /* Find the longest match, discarding those <= prev_length.
  82405. * At this point we have always match_length < MIN_MATCH
  82406. */
  82407. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  82408. /* To simplify the code, we prevent matches with the string
  82409. * of window index 0 (in particular we have to avoid a match
  82410. * of the string with itself at the start of the input file).
  82411. */
  82412. #ifdef FASTEST
  82413. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  82414. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  82415. s->match_length = longest_match_fast (s, hash_head);
  82416. }
  82417. #else
  82418. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82419. s->match_length = longest_match (s, hash_head);
  82420. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82421. s->match_length = longest_match_fast (s, hash_head);
  82422. }
  82423. #endif
  82424. /* longest_match() or longest_match_fast() sets match_start */
  82425. }
  82426. if (s->match_length >= MIN_MATCH) {
  82427. check_match(s, s->strstart, s->match_start, s->match_length);
  82428. _tr_tally_dist(s, s->strstart - s->match_start,
  82429. s->match_length - MIN_MATCH, bflush);
  82430. s->lookahead -= s->match_length;
  82431. /* Insert new strings in the hash table only if the match length
  82432. * is not too large. This saves time but degrades compression.
  82433. */
  82434. #ifndef FASTEST
  82435. if (s->match_length <= s->max_insert_length &&
  82436. s->lookahead >= MIN_MATCH) {
  82437. s->match_length--; /* string at strstart already in table */
  82438. do {
  82439. s->strstart++;
  82440. INSERT_STRING(s, s->strstart, hash_head);
  82441. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  82442. * always MIN_MATCH bytes ahead.
  82443. */
  82444. } while (--s->match_length != 0);
  82445. s->strstart++;
  82446. } else
  82447. #endif
  82448. {
  82449. s->strstart += s->match_length;
  82450. s->match_length = 0;
  82451. s->ins_h = s->window[s->strstart];
  82452. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82453. #if MIN_MATCH != 3
  82454. Call UPDATE_HASH() MIN_MATCH-3 more times
  82455. #endif
  82456. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  82457. * matter since it will be recomputed at next deflate call.
  82458. */
  82459. }
  82460. } else {
  82461. /* No match, output a literal byte */
  82462. Tracevv((stderr,"%c", s->window[s->strstart]));
  82463. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82464. s->lookahead--;
  82465. s->strstart++;
  82466. }
  82467. if (bflush) FLUSH_BLOCK(s, 0);
  82468. }
  82469. FLUSH_BLOCK(s, flush == Z_FINISH);
  82470. return flush == Z_FINISH ? finish_done : block_done;
  82471. }
  82472. #ifndef FASTEST
  82473. /* ===========================================================================
  82474. * Same as above, but achieves better compression. We use a lazy
  82475. * evaluation for matches: a match is finally adopted only if there is
  82476. * no better match at the next window position.
  82477. */
  82478. local block_state deflate_slow(deflate_state *s, int flush)
  82479. {
  82480. IPos hash_head = NIL; /* head of hash chain */
  82481. int bflush; /* set if current block must be flushed */
  82482. /* Process the input block. */
  82483. for (;;) {
  82484. /* Make sure that we always have enough lookahead, except
  82485. * at the end of the input file. We need MAX_MATCH bytes
  82486. * for the next match, plus MIN_MATCH bytes to insert the
  82487. * string following the next match.
  82488. */
  82489. if (s->lookahead < MIN_LOOKAHEAD) {
  82490. fill_window(s);
  82491. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82492. return need_more;
  82493. }
  82494. if (s->lookahead == 0) break; /* flush the current block */
  82495. }
  82496. /* Insert the string window[strstart .. strstart+2] in the
  82497. * dictionary, and set hash_head to the head of the hash chain:
  82498. */
  82499. if (s->lookahead >= MIN_MATCH) {
  82500. INSERT_STRING(s, s->strstart, hash_head);
  82501. }
  82502. /* Find the longest match, discarding those <= prev_length.
  82503. */
  82504. s->prev_length = s->match_length, s->prev_match = s->match_start;
  82505. s->match_length = MIN_MATCH-1;
  82506. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  82507. s->strstart - hash_head <= MAX_DIST(s)) {
  82508. /* To simplify the code, we prevent matches with the string
  82509. * of window index 0 (in particular we have to avoid a match
  82510. * of the string with itself at the start of the input file).
  82511. */
  82512. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82513. s->match_length = longest_match (s, hash_head);
  82514. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82515. s->match_length = longest_match_fast (s, hash_head);
  82516. }
  82517. /* longest_match() or longest_match_fast() sets match_start */
  82518. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  82519. #if TOO_FAR <= 32767
  82520. || (s->match_length == MIN_MATCH &&
  82521. s->strstart - s->match_start > TOO_FAR)
  82522. #endif
  82523. )) {
  82524. /* If prev_match is also MIN_MATCH, match_start is garbage
  82525. * but we will ignore the current match anyway.
  82526. */
  82527. s->match_length = MIN_MATCH-1;
  82528. }
  82529. }
  82530. /* If there was a match at the previous step and the current
  82531. * match is not better, output the previous match:
  82532. */
  82533. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  82534. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  82535. /* Do not insert strings in hash table beyond this. */
  82536. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  82537. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  82538. s->prev_length - MIN_MATCH, bflush);
  82539. /* Insert in hash table all strings up to the end of the match.
  82540. * strstart-1 and strstart are already inserted. If there is not
  82541. * enough lookahead, the last two strings are not inserted in
  82542. * the hash table.
  82543. */
  82544. s->lookahead -= s->prev_length-1;
  82545. s->prev_length -= 2;
  82546. do {
  82547. if (++s->strstart <= max_insert) {
  82548. INSERT_STRING(s, s->strstart, hash_head);
  82549. }
  82550. } while (--s->prev_length != 0);
  82551. s->match_available = 0;
  82552. s->match_length = MIN_MATCH-1;
  82553. s->strstart++;
  82554. if (bflush) FLUSH_BLOCK(s, 0);
  82555. } else if (s->match_available) {
  82556. /* If there was no match at the previous position, output a
  82557. * single literal. If there was a match but the current match
  82558. * is longer, truncate the previous match to a single literal.
  82559. */
  82560. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82561. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82562. if (bflush) {
  82563. FLUSH_BLOCK_ONLY(s, 0);
  82564. }
  82565. s->strstart++;
  82566. s->lookahead--;
  82567. if (s->strm->avail_out == 0) return need_more;
  82568. } else {
  82569. /* There is no previous match to compare with, wait for
  82570. * the next step to decide.
  82571. */
  82572. s->match_available = 1;
  82573. s->strstart++;
  82574. s->lookahead--;
  82575. }
  82576. }
  82577. Assert (flush != Z_NO_FLUSH, "no flush?");
  82578. if (s->match_available) {
  82579. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82580. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82581. s->match_available = 0;
  82582. }
  82583. FLUSH_BLOCK(s, flush == Z_FINISH);
  82584. return flush == Z_FINISH ? finish_done : block_done;
  82585. }
  82586. #endif /* FASTEST */
  82587. #if 0
  82588. /* ===========================================================================
  82589. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  82590. * one. Do not maintain a hash table. (It will be regenerated if this run of
  82591. * deflate switches away from Z_RLE.)
  82592. */
  82593. local block_state deflate_rle(s, flush)
  82594. deflate_state *s;
  82595. int flush;
  82596. {
  82597. int bflush; /* set if current block must be flushed */
  82598. uInt run; /* length of run */
  82599. uInt max; /* maximum length of run */
  82600. uInt prev; /* byte at distance one to match */
  82601. Bytef *scan; /* scan for end of run */
  82602. for (;;) {
  82603. /* Make sure that we always have enough lookahead, except
  82604. * at the end of the input file. We need MAX_MATCH bytes
  82605. * for the longest encodable run.
  82606. */
  82607. if (s->lookahead < MAX_MATCH) {
  82608. fill_window(s);
  82609. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  82610. return need_more;
  82611. }
  82612. if (s->lookahead == 0) break; /* flush the current block */
  82613. }
  82614. /* See how many times the previous byte repeats */
  82615. run = 0;
  82616. if (s->strstart > 0) { /* if there is a previous byte, that is */
  82617. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  82618. scan = s->window + s->strstart - 1;
  82619. prev = *scan++;
  82620. do {
  82621. if (*scan++ != prev)
  82622. break;
  82623. } while (++run < max);
  82624. }
  82625. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  82626. if (run >= MIN_MATCH) {
  82627. check_match(s, s->strstart, s->strstart - 1, run);
  82628. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  82629. s->lookahead -= run;
  82630. s->strstart += run;
  82631. } else {
  82632. /* No match, output a literal byte */
  82633. Tracevv((stderr,"%c", s->window[s->strstart]));
  82634. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82635. s->lookahead--;
  82636. s->strstart++;
  82637. }
  82638. if (bflush) FLUSH_BLOCK(s, 0);
  82639. }
  82640. FLUSH_BLOCK(s, flush == Z_FINISH);
  82641. return flush == Z_FINISH ? finish_done : block_done;
  82642. }
  82643. #endif
  82644. /*** End of inlined file: deflate.c ***/
  82645. /*** Start of inlined file: inffast.c ***/
  82646. /*** Start of inlined file: inftrees.h ***/
  82647. /* WARNING: this file should *not* be used by applications. It is
  82648. part of the implementation of the compression library and is
  82649. subject to change. Applications should only use zlib.h.
  82650. */
  82651. #ifndef _INFTREES_H_
  82652. #define _INFTREES_H_
  82653. /* Structure for decoding tables. Each entry provides either the
  82654. information needed to do the operation requested by the code that
  82655. indexed that table entry, or it provides a pointer to another
  82656. table that indexes more bits of the code. op indicates whether
  82657. the entry is a pointer to another table, a literal, a length or
  82658. distance, an end-of-block, or an invalid code. For a table
  82659. pointer, the low four bits of op is the number of index bits of
  82660. that table. For a length or distance, the low four bits of op
  82661. is the number of extra bits to get after the code. bits is
  82662. the number of bits in this code or part of the code to drop off
  82663. of the bit buffer. val is the actual byte to output in the case
  82664. of a literal, the base length or distance, or the offset from
  82665. the current table to the next table. Each entry is four bytes. */
  82666. typedef struct {
  82667. unsigned char op; /* operation, extra bits, table bits */
  82668. unsigned char bits; /* bits in this part of the code */
  82669. unsigned short val; /* offset in table or code value */
  82670. } code;
  82671. /* op values as set by inflate_table():
  82672. 00000000 - literal
  82673. 0000tttt - table link, tttt != 0 is the number of table index bits
  82674. 0001eeee - length or distance, eeee is the number of extra bits
  82675. 01100000 - end of block
  82676. 01000000 - invalid code
  82677. */
  82678. /* Maximum size of dynamic tree. The maximum found in a long but non-
  82679. exhaustive search was 1444 code structures (852 for length/literals
  82680. and 592 for distances, the latter actually the result of an
  82681. exhaustive search). The true maximum is not known, but the value
  82682. below is more than safe. */
  82683. #define ENOUGH 2048
  82684. #define MAXD 592
  82685. /* Type of code to build for inftable() */
  82686. typedef enum {
  82687. CODES,
  82688. LENS,
  82689. DISTS
  82690. } codetype;
  82691. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  82692. unsigned codes, code FAR * FAR *table,
  82693. unsigned FAR *bits, unsigned short FAR *work));
  82694. #endif
  82695. /*** End of inlined file: inftrees.h ***/
  82696. /*** Start of inlined file: inflate.h ***/
  82697. /* WARNING: this file should *not* be used by applications. It is
  82698. part of the implementation of the compression library and is
  82699. subject to change. Applications should only use zlib.h.
  82700. */
  82701. #ifndef _INFLATE_H_
  82702. #define _INFLATE_H_
  82703. /* define NO_GZIP when compiling if you want to disable gzip header and
  82704. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  82705. the crc code when it is not needed. For shared libraries, gzip decoding
  82706. should be left enabled. */
  82707. #ifndef NO_GZIP
  82708. # define GUNZIP
  82709. #endif
  82710. /* Possible inflate modes between inflate() calls */
  82711. typedef enum {
  82712. HEAD, /* i: waiting for magic header */
  82713. FLAGS, /* i: waiting for method and flags (gzip) */
  82714. TIME, /* i: waiting for modification time (gzip) */
  82715. OS, /* i: waiting for extra flags and operating system (gzip) */
  82716. EXLEN, /* i: waiting for extra length (gzip) */
  82717. EXTRA, /* i: waiting for extra bytes (gzip) */
  82718. NAME, /* i: waiting for end of file name (gzip) */
  82719. COMMENT, /* i: waiting for end of comment (gzip) */
  82720. HCRC, /* i: waiting for header crc (gzip) */
  82721. DICTID, /* i: waiting for dictionary check value */
  82722. DICT, /* waiting for inflateSetDictionary() call */
  82723. TYPE, /* i: waiting for type bits, including last-flag bit */
  82724. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  82725. STORED, /* i: waiting for stored size (length and complement) */
  82726. COPY, /* i/o: waiting for input or output to copy stored block */
  82727. TABLE, /* i: waiting for dynamic block table lengths */
  82728. LENLENS, /* i: waiting for code length code lengths */
  82729. CODELENS, /* i: waiting for length/lit and distance code lengths */
  82730. LEN, /* i: waiting for length/lit code */
  82731. LENEXT, /* i: waiting for length extra bits */
  82732. DIST, /* i: waiting for distance code */
  82733. DISTEXT, /* i: waiting for distance extra bits */
  82734. MATCH, /* o: waiting for output space to copy string */
  82735. LIT, /* o: waiting for output space to write literal */
  82736. CHECK, /* i: waiting for 32-bit check value */
  82737. LENGTH, /* i: waiting for 32-bit length (gzip) */
  82738. DONE, /* finished check, done -- remain here until reset */
  82739. BAD, /* got a data error -- remain here until reset */
  82740. MEM, /* got an inflate() memory error -- remain here until reset */
  82741. SYNC /* looking for synchronization bytes to restart inflate() */
  82742. } inflate_mode;
  82743. /*
  82744. State transitions between above modes -
  82745. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  82746. Process header:
  82747. HEAD -> (gzip) or (zlib)
  82748. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  82749. NAME -> COMMENT -> HCRC -> TYPE
  82750. (zlib) -> DICTID or TYPE
  82751. DICTID -> DICT -> TYPE
  82752. Read deflate blocks:
  82753. TYPE -> STORED or TABLE or LEN or CHECK
  82754. STORED -> COPY -> TYPE
  82755. TABLE -> LENLENS -> CODELENS -> LEN
  82756. Read deflate codes:
  82757. LEN -> LENEXT or LIT or TYPE
  82758. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  82759. LIT -> LEN
  82760. Process trailer:
  82761. CHECK -> LENGTH -> DONE
  82762. */
  82763. /* state maintained between inflate() calls. Approximately 7K bytes. */
  82764. struct inflate_state {
  82765. inflate_mode mode; /* current inflate mode */
  82766. int last; /* true if processing last block */
  82767. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  82768. int havedict; /* true if dictionary provided */
  82769. int flags; /* gzip header method and flags (0 if zlib) */
  82770. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  82771. unsigned long check; /* protected copy of check value */
  82772. unsigned long total; /* protected copy of output count */
  82773. gz_headerp head; /* where to save gzip header information */
  82774. /* sliding window */
  82775. unsigned wbits; /* log base 2 of requested window size */
  82776. unsigned wsize; /* window size or zero if not using window */
  82777. unsigned whave; /* valid bytes in the window */
  82778. unsigned write; /* window write index */
  82779. unsigned char FAR *window; /* allocated sliding window, if needed */
  82780. /* bit accumulator */
  82781. unsigned long hold; /* input bit accumulator */
  82782. unsigned bits; /* number of bits in "in" */
  82783. /* for string and stored block copying */
  82784. unsigned length; /* literal or length of data to copy */
  82785. unsigned offset; /* distance back to copy string from */
  82786. /* for table and code decoding */
  82787. unsigned extra; /* extra bits needed */
  82788. /* fixed and dynamic code tables */
  82789. code const FAR *lencode; /* starting table for length/literal codes */
  82790. code const FAR *distcode; /* starting table for distance codes */
  82791. unsigned lenbits; /* index bits for lencode */
  82792. unsigned distbits; /* index bits for distcode */
  82793. /* dynamic table building */
  82794. unsigned ncode; /* number of code length code lengths */
  82795. unsigned nlen; /* number of length code lengths */
  82796. unsigned ndist; /* number of distance code lengths */
  82797. unsigned have; /* number of code lengths in lens[] */
  82798. code FAR *next; /* next available space in codes[] */
  82799. unsigned short lens[320]; /* temporary storage for code lengths */
  82800. unsigned short work[288]; /* work area for code table building */
  82801. code codes[ENOUGH]; /* space for code tables */
  82802. };
  82803. #endif
  82804. /*** End of inlined file: inflate.h ***/
  82805. /*** Start of inlined file: inffast.h ***/
  82806. /* WARNING: this file should *not* be used by applications. It is
  82807. part of the implementation of the compression library and is
  82808. subject to change. Applications should only use zlib.h.
  82809. */
  82810. void inflate_fast OF((z_streamp strm, unsigned start));
  82811. /*** End of inlined file: inffast.h ***/
  82812. #ifndef ASMINF
  82813. /* Allow machine dependent optimization for post-increment or pre-increment.
  82814. Based on testing to date,
  82815. Pre-increment preferred for:
  82816. - PowerPC G3 (Adler)
  82817. - MIPS R5000 (Randers-Pehrson)
  82818. Post-increment preferred for:
  82819. - none
  82820. No measurable difference:
  82821. - Pentium III (Anderson)
  82822. - M68060 (Nikl)
  82823. */
  82824. #ifdef POSTINC
  82825. # define OFF 0
  82826. # define PUP(a) *(a)++
  82827. #else
  82828. # define OFF 1
  82829. # define PUP(a) *++(a)
  82830. #endif
  82831. /*
  82832. Decode literal, length, and distance codes and write out the resulting
  82833. literal and match bytes until either not enough input or output is
  82834. available, an end-of-block is encountered, or a data error is encountered.
  82835. When large enough input and output buffers are supplied to inflate(), for
  82836. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  82837. inflate execution time is spent in this routine.
  82838. Entry assumptions:
  82839. state->mode == LEN
  82840. strm->avail_in >= 6
  82841. strm->avail_out >= 258
  82842. start >= strm->avail_out
  82843. state->bits < 8
  82844. On return, state->mode is one of:
  82845. LEN -- ran out of enough output space or enough available input
  82846. TYPE -- reached end of block code, inflate() to interpret next block
  82847. BAD -- error in block data
  82848. Notes:
  82849. - The maximum input bits used by a length/distance pair is 15 bits for the
  82850. length code, 5 bits for the length extra, 15 bits for the distance code,
  82851. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  82852. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  82853. checking for available input while decoding.
  82854. - The maximum bytes that a single length/distance pair can output is 258
  82855. bytes, which is the maximum length that can be coded. inflate_fast()
  82856. requires strm->avail_out >= 258 for each loop to avoid checking for
  82857. output space.
  82858. */
  82859. void inflate_fast (z_streamp strm, unsigned start)
  82860. {
  82861. struct inflate_state FAR *state;
  82862. unsigned char FAR *in; /* local strm->next_in */
  82863. unsigned char FAR *last; /* while in < last, enough input available */
  82864. unsigned char FAR *out; /* local strm->next_out */
  82865. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  82866. unsigned char FAR *end; /* while out < end, enough space available */
  82867. #ifdef INFLATE_STRICT
  82868. unsigned dmax; /* maximum distance from zlib header */
  82869. #endif
  82870. unsigned wsize; /* window size or zero if not using window */
  82871. unsigned whave; /* valid bytes in the window */
  82872. unsigned write; /* window write index */
  82873. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  82874. unsigned long hold; /* local strm->hold */
  82875. unsigned bits; /* local strm->bits */
  82876. code const FAR *lcode; /* local strm->lencode */
  82877. code const FAR *dcode; /* local strm->distcode */
  82878. unsigned lmask; /* mask for first level of length codes */
  82879. unsigned dmask; /* mask for first level of distance codes */
  82880. code thisx; /* retrieved table entry */
  82881. unsigned op; /* code bits, operation, extra bits, or */
  82882. /* window position, window bytes to copy */
  82883. unsigned len; /* match length, unused bytes */
  82884. unsigned dist; /* match distance */
  82885. unsigned char FAR *from; /* where to copy match from */
  82886. /* copy state to local variables */
  82887. state = (struct inflate_state FAR *)strm->state;
  82888. in = strm->next_in - OFF;
  82889. last = in + (strm->avail_in - 5);
  82890. out = strm->next_out - OFF;
  82891. beg = out - (start - strm->avail_out);
  82892. end = out + (strm->avail_out - 257);
  82893. #ifdef INFLATE_STRICT
  82894. dmax = state->dmax;
  82895. #endif
  82896. wsize = state->wsize;
  82897. whave = state->whave;
  82898. write = state->write;
  82899. window = state->window;
  82900. hold = state->hold;
  82901. bits = state->bits;
  82902. lcode = state->lencode;
  82903. dcode = state->distcode;
  82904. lmask = (1U << state->lenbits) - 1;
  82905. dmask = (1U << state->distbits) - 1;
  82906. /* decode literals and length/distances until end-of-block or not enough
  82907. input data or output space */
  82908. do {
  82909. if (bits < 15) {
  82910. hold += (unsigned long)(PUP(in)) << bits;
  82911. bits += 8;
  82912. hold += (unsigned long)(PUP(in)) << bits;
  82913. bits += 8;
  82914. }
  82915. thisx = lcode[hold & lmask];
  82916. dolen:
  82917. op = (unsigned)(thisx.bits);
  82918. hold >>= op;
  82919. bits -= op;
  82920. op = (unsigned)(thisx.op);
  82921. if (op == 0) { /* literal */
  82922. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  82923. "inflate: literal '%c'\n" :
  82924. "inflate: literal 0x%02x\n", thisx.val));
  82925. PUP(out) = (unsigned char)(thisx.val);
  82926. }
  82927. else if (op & 16) { /* length base */
  82928. len = (unsigned)(thisx.val);
  82929. op &= 15; /* number of extra bits */
  82930. if (op) {
  82931. if (bits < op) {
  82932. hold += (unsigned long)(PUP(in)) << bits;
  82933. bits += 8;
  82934. }
  82935. len += (unsigned)hold & ((1U << op) - 1);
  82936. hold >>= op;
  82937. bits -= op;
  82938. }
  82939. Tracevv((stderr, "inflate: length %u\n", len));
  82940. if (bits < 15) {
  82941. hold += (unsigned long)(PUP(in)) << bits;
  82942. bits += 8;
  82943. hold += (unsigned long)(PUP(in)) << bits;
  82944. bits += 8;
  82945. }
  82946. thisx = dcode[hold & dmask];
  82947. dodist:
  82948. op = (unsigned)(thisx.bits);
  82949. hold >>= op;
  82950. bits -= op;
  82951. op = (unsigned)(thisx.op);
  82952. if (op & 16) { /* distance base */
  82953. dist = (unsigned)(thisx.val);
  82954. op &= 15; /* number of extra bits */
  82955. if (bits < op) {
  82956. hold += (unsigned long)(PUP(in)) << bits;
  82957. bits += 8;
  82958. if (bits < op) {
  82959. hold += (unsigned long)(PUP(in)) << bits;
  82960. bits += 8;
  82961. }
  82962. }
  82963. dist += (unsigned)hold & ((1U << op) - 1);
  82964. #ifdef INFLATE_STRICT
  82965. if (dist > dmax) {
  82966. strm->msg = (char *)"invalid distance too far back";
  82967. state->mode = BAD;
  82968. break;
  82969. }
  82970. #endif
  82971. hold >>= op;
  82972. bits -= op;
  82973. Tracevv((stderr, "inflate: distance %u\n", dist));
  82974. op = (unsigned)(out - beg); /* max distance in output */
  82975. if (dist > op) { /* see if copy from window */
  82976. op = dist - op; /* distance back in window */
  82977. if (op > whave) {
  82978. strm->msg = (char *)"invalid distance too far back";
  82979. state->mode = BAD;
  82980. break;
  82981. }
  82982. from = window - OFF;
  82983. if (write == 0) { /* very common case */
  82984. from += wsize - op;
  82985. if (op < len) { /* some from window */
  82986. len -= op;
  82987. do {
  82988. PUP(out) = PUP(from);
  82989. } while (--op);
  82990. from = out - dist; /* rest from output */
  82991. }
  82992. }
  82993. else if (write < op) { /* wrap around window */
  82994. from += wsize + write - op;
  82995. op -= write;
  82996. if (op < len) { /* some from end of window */
  82997. len -= op;
  82998. do {
  82999. PUP(out) = PUP(from);
  83000. } while (--op);
  83001. from = window - OFF;
  83002. if (write < len) { /* some from start of window */
  83003. op = write;
  83004. len -= op;
  83005. do {
  83006. PUP(out) = PUP(from);
  83007. } while (--op);
  83008. from = out - dist; /* rest from output */
  83009. }
  83010. }
  83011. }
  83012. else { /* contiguous in window */
  83013. from += write - op;
  83014. if (op < len) { /* some from window */
  83015. len -= op;
  83016. do {
  83017. PUP(out) = PUP(from);
  83018. } while (--op);
  83019. from = out - dist; /* rest from output */
  83020. }
  83021. }
  83022. while (len > 2) {
  83023. PUP(out) = PUP(from);
  83024. PUP(out) = PUP(from);
  83025. PUP(out) = PUP(from);
  83026. len -= 3;
  83027. }
  83028. if (len) {
  83029. PUP(out) = PUP(from);
  83030. if (len > 1)
  83031. PUP(out) = PUP(from);
  83032. }
  83033. }
  83034. else {
  83035. from = out - dist; /* copy direct from output */
  83036. do { /* minimum length is three */
  83037. PUP(out) = PUP(from);
  83038. PUP(out) = PUP(from);
  83039. PUP(out) = PUP(from);
  83040. len -= 3;
  83041. } while (len > 2);
  83042. if (len) {
  83043. PUP(out) = PUP(from);
  83044. if (len > 1)
  83045. PUP(out) = PUP(from);
  83046. }
  83047. }
  83048. }
  83049. else if ((op & 64) == 0) { /* 2nd level distance code */
  83050. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  83051. goto dodist;
  83052. }
  83053. else {
  83054. strm->msg = (char *)"invalid distance code";
  83055. state->mode = BAD;
  83056. break;
  83057. }
  83058. }
  83059. else if ((op & 64) == 0) { /* 2nd level length code */
  83060. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  83061. goto dolen;
  83062. }
  83063. else if (op & 32) { /* end-of-block */
  83064. Tracevv((stderr, "inflate: end of block\n"));
  83065. state->mode = TYPE;
  83066. break;
  83067. }
  83068. else {
  83069. strm->msg = (char *)"invalid literal/length code";
  83070. state->mode = BAD;
  83071. break;
  83072. }
  83073. } while (in < last && out < end);
  83074. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  83075. len = bits >> 3;
  83076. in -= len;
  83077. bits -= len << 3;
  83078. hold &= (1U << bits) - 1;
  83079. /* update state and return */
  83080. strm->next_in = in + OFF;
  83081. strm->next_out = out + OFF;
  83082. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  83083. strm->avail_out = (unsigned)(out < end ?
  83084. 257 + (end - out) : 257 - (out - end));
  83085. state->hold = hold;
  83086. state->bits = bits;
  83087. return;
  83088. }
  83089. /*
  83090. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  83091. - Using bit fields for code structure
  83092. - Different op definition to avoid & for extra bits (do & for table bits)
  83093. - Three separate decoding do-loops for direct, window, and write == 0
  83094. - Special case for distance > 1 copies to do overlapped load and store copy
  83095. - Explicit branch predictions (based on measured branch probabilities)
  83096. - Deferring match copy and interspersed it with decoding subsequent codes
  83097. - Swapping literal/length else
  83098. - Swapping window/direct else
  83099. - Larger unrolled copy loops (three is about right)
  83100. - Moving len -= 3 statement into middle of loop
  83101. */
  83102. #endif /* !ASMINF */
  83103. /*** End of inlined file: inffast.c ***/
  83104. #undef PULLBYTE
  83105. #undef LOAD
  83106. #undef RESTORE
  83107. #undef INITBITS
  83108. #undef NEEDBITS
  83109. #undef DROPBITS
  83110. #undef BYTEBITS
  83111. /*** Start of inlined file: inflate.c ***/
  83112. /*
  83113. * Change history:
  83114. *
  83115. * 1.2.beta0 24 Nov 2002
  83116. * - First version -- complete rewrite of inflate to simplify code, avoid
  83117. * creation of window when not needed, minimize use of window when it is
  83118. * needed, make inffast.c even faster, implement gzip decoding, and to
  83119. * improve code readability and style over the previous zlib inflate code
  83120. *
  83121. * 1.2.beta1 25 Nov 2002
  83122. * - Use pointers for available input and output checking in inffast.c
  83123. * - Remove input and output counters in inffast.c
  83124. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  83125. * - Remove unnecessary second byte pull from length extra in inffast.c
  83126. * - Unroll direct copy to three copies per loop in inffast.c
  83127. *
  83128. * 1.2.beta2 4 Dec 2002
  83129. * - Change external routine names to reduce potential conflicts
  83130. * - Correct filename to inffixed.h for fixed tables in inflate.c
  83131. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  83132. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  83133. * to avoid negation problem on Alphas (64 bit) in inflate.c
  83134. *
  83135. * 1.2.beta3 22 Dec 2002
  83136. * - Add comments on state->bits assertion in inffast.c
  83137. * - Add comments on op field in inftrees.h
  83138. * - Fix bug in reuse of allocated window after inflateReset()
  83139. * - Remove bit fields--back to byte structure for speed
  83140. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  83141. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  83142. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  83143. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  83144. * - Use local copies of stream next and avail values, as well as local bit
  83145. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  83146. *
  83147. * 1.2.beta4 1 Jan 2003
  83148. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  83149. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  83150. * - Add comments in inffast.c to introduce the inflate_fast() routine
  83151. * - Rearrange window copies in inflate_fast() for speed and simplification
  83152. * - Unroll last copy for window match in inflate_fast()
  83153. * - Use local copies of window variables in inflate_fast() for speed
  83154. * - Pull out common write == 0 case for speed in inflate_fast()
  83155. * - Make op and len in inflate_fast() unsigned for consistency
  83156. * - Add FAR to lcode and dcode declarations in inflate_fast()
  83157. * - Simplified bad distance check in inflate_fast()
  83158. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  83159. * source file infback.c to provide a call-back interface to inflate for
  83160. * programs like gzip and unzip -- uses window as output buffer to avoid
  83161. * window copying
  83162. *
  83163. * 1.2.beta5 1 Jan 2003
  83164. * - Improved inflateBack() interface to allow the caller to provide initial
  83165. * input in strm.
  83166. * - Fixed stored blocks bug in inflateBack()
  83167. *
  83168. * 1.2.beta6 4 Jan 2003
  83169. * - Added comments in inffast.c on effectiveness of POSTINC
  83170. * - Typecasting all around to reduce compiler warnings
  83171. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  83172. * make compilers happy
  83173. * - Changed type of window in inflateBackInit() to unsigned char *
  83174. *
  83175. * 1.2.beta7 27 Jan 2003
  83176. * - Changed many types to unsigned or unsigned short to avoid warnings
  83177. * - Added inflateCopy() function
  83178. *
  83179. * 1.2.0 9 Mar 2003
  83180. * - Changed inflateBack() interface to provide separate opaque descriptors
  83181. * for the in() and out() functions
  83182. * - Changed inflateBack() argument and in_func typedef to swap the length
  83183. * and buffer address return values for the input function
  83184. * - Check next_in and next_out for Z_NULL on entry to inflate()
  83185. *
  83186. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  83187. */
  83188. /*** Start of inlined file: inffast.h ***/
  83189. /* WARNING: this file should *not* be used by applications. It is
  83190. part of the implementation of the compression library and is
  83191. subject to change. Applications should only use zlib.h.
  83192. */
  83193. void inflate_fast OF((z_streamp strm, unsigned start));
  83194. /*** End of inlined file: inffast.h ***/
  83195. #ifdef MAKEFIXED
  83196. # ifndef BUILDFIXED
  83197. # define BUILDFIXED
  83198. # endif
  83199. #endif
  83200. /* function prototypes */
  83201. local void fixedtables OF((struct inflate_state FAR *state));
  83202. local int updatewindow OF((z_streamp strm, unsigned out));
  83203. #ifdef BUILDFIXED
  83204. void makefixed OF((void));
  83205. #endif
  83206. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  83207. unsigned len));
  83208. int ZEXPORT inflateReset (z_streamp strm)
  83209. {
  83210. struct inflate_state FAR *state;
  83211. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83212. state = (struct inflate_state FAR *)strm->state;
  83213. strm->total_in = strm->total_out = state->total = 0;
  83214. strm->msg = Z_NULL;
  83215. strm->adler = 1; /* to support ill-conceived Java test suite */
  83216. state->mode = HEAD;
  83217. state->last = 0;
  83218. state->havedict = 0;
  83219. state->dmax = 32768U;
  83220. state->head = Z_NULL;
  83221. state->wsize = 0;
  83222. state->whave = 0;
  83223. state->write = 0;
  83224. state->hold = 0;
  83225. state->bits = 0;
  83226. state->lencode = state->distcode = state->next = state->codes;
  83227. Tracev((stderr, "inflate: reset\n"));
  83228. return Z_OK;
  83229. }
  83230. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  83231. {
  83232. struct inflate_state FAR *state;
  83233. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83234. state = (struct inflate_state FAR *)strm->state;
  83235. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  83236. value &= (1L << bits) - 1;
  83237. state->hold += value << state->bits;
  83238. state->bits += bits;
  83239. return Z_OK;
  83240. }
  83241. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  83242. {
  83243. struct inflate_state FAR *state;
  83244. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  83245. stream_size != (int)(sizeof(z_stream)))
  83246. return Z_VERSION_ERROR;
  83247. if (strm == Z_NULL) return Z_STREAM_ERROR;
  83248. strm->msg = Z_NULL; /* in case we return an error */
  83249. if (strm->zalloc == (alloc_func)0) {
  83250. strm->zalloc = zcalloc;
  83251. strm->opaque = (voidpf)0;
  83252. }
  83253. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  83254. state = (struct inflate_state FAR *)
  83255. ZALLOC(strm, 1, sizeof(struct inflate_state));
  83256. if (state == Z_NULL) return Z_MEM_ERROR;
  83257. Tracev((stderr, "inflate: allocated\n"));
  83258. strm->state = (struct internal_state FAR *)state;
  83259. if (windowBits < 0) {
  83260. state->wrap = 0;
  83261. windowBits = -windowBits;
  83262. }
  83263. else {
  83264. state->wrap = (windowBits >> 4) + 1;
  83265. #ifdef GUNZIP
  83266. if (windowBits < 48) windowBits &= 15;
  83267. #endif
  83268. }
  83269. if (windowBits < 8 || windowBits > 15) {
  83270. ZFREE(strm, state);
  83271. strm->state = Z_NULL;
  83272. return Z_STREAM_ERROR;
  83273. }
  83274. state->wbits = (unsigned)windowBits;
  83275. state->window = Z_NULL;
  83276. return inflateReset(strm);
  83277. }
  83278. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  83279. {
  83280. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  83281. }
  83282. /*
  83283. Return state with length and distance decoding tables and index sizes set to
  83284. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  83285. If BUILDFIXED is defined, then instead this routine builds the tables the
  83286. first time it's called, and returns those tables the first time and
  83287. thereafter. This reduces the size of the code by about 2K bytes, in
  83288. exchange for a little execution time. However, BUILDFIXED should not be
  83289. used for threaded applications, since the rewriting of the tables and virgin
  83290. may not be thread-safe.
  83291. */
  83292. local void fixedtables (struct inflate_state FAR *state)
  83293. {
  83294. #ifdef BUILDFIXED
  83295. static int virgin = 1;
  83296. static code *lenfix, *distfix;
  83297. static code fixed[544];
  83298. /* build fixed huffman tables if first call (may not be thread safe) */
  83299. if (virgin) {
  83300. unsigned sym, bits;
  83301. static code *next;
  83302. /* literal/length table */
  83303. sym = 0;
  83304. while (sym < 144) state->lens[sym++] = 8;
  83305. while (sym < 256) state->lens[sym++] = 9;
  83306. while (sym < 280) state->lens[sym++] = 7;
  83307. while (sym < 288) state->lens[sym++] = 8;
  83308. next = fixed;
  83309. lenfix = next;
  83310. bits = 9;
  83311. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  83312. /* distance table */
  83313. sym = 0;
  83314. while (sym < 32) state->lens[sym++] = 5;
  83315. distfix = next;
  83316. bits = 5;
  83317. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  83318. /* do this just once */
  83319. virgin = 0;
  83320. }
  83321. #else /* !BUILDFIXED */
  83322. /*** Start of inlined file: inffixed.h ***/
  83323. /* WARNING: this file should *not* be used by applications. It
  83324. is part of the implementation of the compression library and
  83325. is subject to change. Applications should only use zlib.h.
  83326. */
  83327. static const code lenfix[512] = {
  83328. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  83329. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  83330. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  83331. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  83332. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  83333. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  83334. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  83335. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  83336. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  83337. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  83338. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  83339. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  83340. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  83341. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  83342. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  83343. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  83344. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  83345. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  83346. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  83347. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  83348. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  83349. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  83350. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  83351. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  83352. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  83353. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  83354. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  83355. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  83356. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  83357. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  83358. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  83359. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  83360. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  83361. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  83362. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  83363. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  83364. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  83365. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  83366. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  83367. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  83368. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  83369. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  83370. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  83371. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  83372. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  83373. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  83374. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  83375. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  83376. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  83377. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  83378. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  83379. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  83380. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  83381. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  83382. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  83383. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  83384. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  83385. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  83386. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  83387. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  83388. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  83389. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  83390. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  83391. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  83392. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  83393. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  83394. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  83395. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  83396. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  83397. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  83398. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  83399. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  83400. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  83401. {0,9,255}
  83402. };
  83403. static const code distfix[32] = {
  83404. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  83405. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  83406. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  83407. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  83408. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  83409. {22,5,193},{64,5,0}
  83410. };
  83411. /*** End of inlined file: inffixed.h ***/
  83412. #endif /* BUILDFIXED */
  83413. state->lencode = lenfix;
  83414. state->lenbits = 9;
  83415. state->distcode = distfix;
  83416. state->distbits = 5;
  83417. }
  83418. #ifdef MAKEFIXED
  83419. #include <stdio.h>
  83420. /*
  83421. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  83422. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  83423. those tables to stdout, which would be piped to inffixed.h. A small program
  83424. can simply call makefixed to do this:
  83425. void makefixed(void);
  83426. int main(void)
  83427. {
  83428. makefixed();
  83429. return 0;
  83430. }
  83431. Then that can be linked with zlib built with MAKEFIXED defined and run:
  83432. a.out > inffixed.h
  83433. */
  83434. void makefixed()
  83435. {
  83436. unsigned low, size;
  83437. struct inflate_state state;
  83438. fixedtables(&state);
  83439. puts(" /* inffixed.h -- table for decoding fixed codes");
  83440. puts(" * Generated automatically by makefixed().");
  83441. puts(" */");
  83442. puts("");
  83443. puts(" /* WARNING: this file should *not* be used by applications.");
  83444. puts(" It is part of the implementation of this library and is");
  83445. puts(" subject to change. Applications should only use zlib.h.");
  83446. puts(" */");
  83447. puts("");
  83448. size = 1U << 9;
  83449. printf(" static const code lenfix[%u] = {", size);
  83450. low = 0;
  83451. for (;;) {
  83452. if ((low % 7) == 0) printf("\n ");
  83453. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  83454. state.lencode[low].val);
  83455. if (++low == size) break;
  83456. putchar(',');
  83457. }
  83458. puts("\n };");
  83459. size = 1U << 5;
  83460. printf("\n static const code distfix[%u] = {", size);
  83461. low = 0;
  83462. for (;;) {
  83463. if ((low % 6) == 0) printf("\n ");
  83464. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  83465. state.distcode[low].val);
  83466. if (++low == size) break;
  83467. putchar(',');
  83468. }
  83469. puts("\n };");
  83470. }
  83471. #endif /* MAKEFIXED */
  83472. /*
  83473. Update the window with the last wsize (normally 32K) bytes written before
  83474. returning. If window does not exist yet, create it. This is only called
  83475. when a window is already in use, or when output has been written during this
  83476. inflate call, but the end of the deflate stream has not been reached yet.
  83477. It is also called to create a window for dictionary data when a dictionary
  83478. is loaded.
  83479. Providing output buffers larger than 32K to inflate() should provide a speed
  83480. advantage, since only the last 32K of output is copied to the sliding window
  83481. upon return from inflate(), and since all distances after the first 32K of
  83482. output will fall in the output data, making match copies simpler and faster.
  83483. The advantage may be dependent on the size of the processor's data caches.
  83484. */
  83485. local int updatewindow (z_streamp strm, unsigned out)
  83486. {
  83487. struct inflate_state FAR *state;
  83488. unsigned copy, dist;
  83489. state = (struct inflate_state FAR *)strm->state;
  83490. /* if it hasn't been done already, allocate space for the window */
  83491. if (state->window == Z_NULL) {
  83492. state->window = (unsigned char FAR *)
  83493. ZALLOC(strm, 1U << state->wbits,
  83494. sizeof(unsigned char));
  83495. if (state->window == Z_NULL) return 1;
  83496. }
  83497. /* if window not in use yet, initialize */
  83498. if (state->wsize == 0) {
  83499. state->wsize = 1U << state->wbits;
  83500. state->write = 0;
  83501. state->whave = 0;
  83502. }
  83503. /* copy state->wsize or less output bytes into the circular window */
  83504. copy = out - strm->avail_out;
  83505. if (copy >= state->wsize) {
  83506. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  83507. state->write = 0;
  83508. state->whave = state->wsize;
  83509. }
  83510. else {
  83511. dist = state->wsize - state->write;
  83512. if (dist > copy) dist = copy;
  83513. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  83514. copy -= dist;
  83515. if (copy) {
  83516. zmemcpy(state->window, strm->next_out - copy, copy);
  83517. state->write = copy;
  83518. state->whave = state->wsize;
  83519. }
  83520. else {
  83521. state->write += dist;
  83522. if (state->write == state->wsize) state->write = 0;
  83523. if (state->whave < state->wsize) state->whave += dist;
  83524. }
  83525. }
  83526. return 0;
  83527. }
  83528. /* Macros for inflate(): */
  83529. /* check function to use adler32() for zlib or crc32() for gzip */
  83530. #ifdef GUNZIP
  83531. # define UPDATE(check, buf, len) \
  83532. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  83533. #else
  83534. # define UPDATE(check, buf, len) adler32(check, buf, len)
  83535. #endif
  83536. /* check macros for header crc */
  83537. #ifdef GUNZIP
  83538. # define CRC2(check, word) \
  83539. do { \
  83540. hbuf[0] = (unsigned char)(word); \
  83541. hbuf[1] = (unsigned char)((word) >> 8); \
  83542. check = crc32(check, hbuf, 2); \
  83543. } while (0)
  83544. # define CRC4(check, word) \
  83545. do { \
  83546. hbuf[0] = (unsigned char)(word); \
  83547. hbuf[1] = (unsigned char)((word) >> 8); \
  83548. hbuf[2] = (unsigned char)((word) >> 16); \
  83549. hbuf[3] = (unsigned char)((word) >> 24); \
  83550. check = crc32(check, hbuf, 4); \
  83551. } while (0)
  83552. #endif
  83553. /* Load registers with state in inflate() for speed */
  83554. #define LOAD() \
  83555. do { \
  83556. put = strm->next_out; \
  83557. left = strm->avail_out; \
  83558. next = strm->next_in; \
  83559. have = strm->avail_in; \
  83560. hold = state->hold; \
  83561. bits = state->bits; \
  83562. } while (0)
  83563. /* Restore state from registers in inflate() */
  83564. #define RESTORE() \
  83565. do { \
  83566. strm->next_out = put; \
  83567. strm->avail_out = left; \
  83568. strm->next_in = next; \
  83569. strm->avail_in = have; \
  83570. state->hold = hold; \
  83571. state->bits = bits; \
  83572. } while (0)
  83573. /* Clear the input bit accumulator */
  83574. #define INITBITS() \
  83575. do { \
  83576. hold = 0; \
  83577. bits = 0; \
  83578. } while (0)
  83579. /* Get a byte of input into the bit accumulator, or return from inflate()
  83580. if there is no input available. */
  83581. #define PULLBYTE() \
  83582. do { \
  83583. if (have == 0) goto inf_leave; \
  83584. have--; \
  83585. hold += (unsigned long)(*next++) << bits; \
  83586. bits += 8; \
  83587. } while (0)
  83588. /* Assure that there are at least n bits in the bit accumulator. If there is
  83589. not enough available input to do that, then return from inflate(). */
  83590. #define NEEDBITS(n) \
  83591. do { \
  83592. while (bits < (unsigned)(n)) \
  83593. PULLBYTE(); \
  83594. } while (0)
  83595. /* Return the low n bits of the bit accumulator (n < 16) */
  83596. #define BITS(n) \
  83597. ((unsigned)hold & ((1U << (n)) - 1))
  83598. /* Remove n bits from the bit accumulator */
  83599. #define DROPBITS(n) \
  83600. do { \
  83601. hold >>= (n); \
  83602. bits -= (unsigned)(n); \
  83603. } while (0)
  83604. /* Remove zero to seven bits as needed to go to a byte boundary */
  83605. #define BYTEBITS() \
  83606. do { \
  83607. hold >>= bits & 7; \
  83608. bits -= bits & 7; \
  83609. } while (0)
  83610. /* Reverse the bytes in a 32-bit value */
  83611. #define REVERSE(q) \
  83612. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  83613. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  83614. /*
  83615. inflate() uses a state machine to process as much input data and generate as
  83616. much output data as possible before returning. The state machine is
  83617. structured roughly as follows:
  83618. for (;;) switch (state) {
  83619. ...
  83620. case STATEn:
  83621. if (not enough input data or output space to make progress)
  83622. return;
  83623. ... make progress ...
  83624. state = STATEm;
  83625. break;
  83626. ...
  83627. }
  83628. so when inflate() is called again, the same case is attempted again, and
  83629. if the appropriate resources are provided, the machine proceeds to the
  83630. next state. The NEEDBITS() macro is usually the way the state evaluates
  83631. whether it can proceed or should return. NEEDBITS() does the return if
  83632. the requested bits are not available. The typical use of the BITS macros
  83633. is:
  83634. NEEDBITS(n);
  83635. ... do something with BITS(n) ...
  83636. DROPBITS(n);
  83637. where NEEDBITS(n) either returns from inflate() if there isn't enough
  83638. input left to load n bits into the accumulator, or it continues. BITS(n)
  83639. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  83640. the low n bits off the accumulator. INITBITS() clears the accumulator
  83641. and sets the number of available bits to zero. BYTEBITS() discards just
  83642. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  83643. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  83644. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  83645. if there is no input available. The decoding of variable length codes uses
  83646. PULLBYTE() directly in order to pull just enough bytes to decode the next
  83647. code, and no more.
  83648. Some states loop until they get enough input, making sure that enough
  83649. state information is maintained to continue the loop where it left off
  83650. if NEEDBITS() returns in the loop. For example, want, need, and keep
  83651. would all have to actually be part of the saved state in case NEEDBITS()
  83652. returns:
  83653. case STATEw:
  83654. while (want < need) {
  83655. NEEDBITS(n);
  83656. keep[want++] = BITS(n);
  83657. DROPBITS(n);
  83658. }
  83659. state = STATEx;
  83660. case STATEx:
  83661. As shown above, if the next state is also the next case, then the break
  83662. is omitted.
  83663. A state may also return if there is not enough output space available to
  83664. complete that state. Those states are copying stored data, writing a
  83665. literal byte, and copying a matching string.
  83666. When returning, a "goto inf_leave" is used to update the total counters,
  83667. update the check value, and determine whether any progress has been made
  83668. during that inflate() call in order to return the proper return code.
  83669. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  83670. When there is a window, goto inf_leave will update the window with the last
  83671. output written. If a goto inf_leave occurs in the middle of decompression
  83672. and there is no window currently, goto inf_leave will create one and copy
  83673. output to the window for the next call of inflate().
  83674. In this implementation, the flush parameter of inflate() only affects the
  83675. return code (per zlib.h). inflate() always writes as much as possible to
  83676. strm->next_out, given the space available and the provided input--the effect
  83677. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  83678. the allocation of and copying into a sliding window until necessary, which
  83679. provides the effect documented in zlib.h for Z_FINISH when the entire input
  83680. stream available. So the only thing the flush parameter actually does is:
  83681. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  83682. will return Z_BUF_ERROR if it has not reached the end of the stream.
  83683. */
  83684. int ZEXPORT inflate (z_streamp strm, int flush)
  83685. {
  83686. struct inflate_state FAR *state;
  83687. unsigned char FAR *next; /* next input */
  83688. unsigned char FAR *put; /* next output */
  83689. unsigned have, left; /* available input and output */
  83690. unsigned long hold; /* bit buffer */
  83691. unsigned bits; /* bits in bit buffer */
  83692. unsigned in, out; /* save starting available input and output */
  83693. unsigned copy; /* number of stored or match bytes to copy */
  83694. unsigned char FAR *from; /* where to copy match bytes from */
  83695. code thisx; /* current decoding table entry */
  83696. code last; /* parent table entry */
  83697. unsigned len; /* length to copy for repeats, bits to drop */
  83698. int ret; /* return code */
  83699. #ifdef GUNZIP
  83700. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  83701. #endif
  83702. static const unsigned short order[19] = /* permutation of code lengths */
  83703. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  83704. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  83705. (strm->next_in == Z_NULL && strm->avail_in != 0))
  83706. return Z_STREAM_ERROR;
  83707. state = (struct inflate_state FAR *)strm->state;
  83708. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  83709. LOAD();
  83710. in = have;
  83711. out = left;
  83712. ret = Z_OK;
  83713. for (;;)
  83714. switch (state->mode) {
  83715. case HEAD:
  83716. if (state->wrap == 0) {
  83717. state->mode = TYPEDO;
  83718. break;
  83719. }
  83720. NEEDBITS(16);
  83721. #ifdef GUNZIP
  83722. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  83723. state->check = crc32(0L, Z_NULL, 0);
  83724. CRC2(state->check, hold);
  83725. INITBITS();
  83726. state->mode = FLAGS;
  83727. break;
  83728. }
  83729. state->flags = 0; /* expect zlib header */
  83730. if (state->head != Z_NULL)
  83731. state->head->done = -1;
  83732. if (!(state->wrap & 1) || /* check if zlib header allowed */
  83733. #else
  83734. if (
  83735. #endif
  83736. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  83737. strm->msg = (char *)"incorrect header check";
  83738. state->mode = BAD;
  83739. break;
  83740. }
  83741. if (BITS(4) != Z_DEFLATED) {
  83742. strm->msg = (char *)"unknown compression method";
  83743. state->mode = BAD;
  83744. break;
  83745. }
  83746. DROPBITS(4);
  83747. len = BITS(4) + 8;
  83748. if (len > state->wbits) {
  83749. strm->msg = (char *)"invalid window size";
  83750. state->mode = BAD;
  83751. break;
  83752. }
  83753. state->dmax = 1U << len;
  83754. Tracev((stderr, "inflate: zlib header ok\n"));
  83755. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83756. state->mode = hold & 0x200 ? DICTID : TYPE;
  83757. INITBITS();
  83758. break;
  83759. #ifdef GUNZIP
  83760. case FLAGS:
  83761. NEEDBITS(16);
  83762. state->flags = (int)(hold);
  83763. if ((state->flags & 0xff) != Z_DEFLATED) {
  83764. strm->msg = (char *)"unknown compression method";
  83765. state->mode = BAD;
  83766. break;
  83767. }
  83768. if (state->flags & 0xe000) {
  83769. strm->msg = (char *)"unknown header flags set";
  83770. state->mode = BAD;
  83771. break;
  83772. }
  83773. if (state->head != Z_NULL)
  83774. state->head->text = (int)((hold >> 8) & 1);
  83775. if (state->flags & 0x0200) CRC2(state->check, hold);
  83776. INITBITS();
  83777. state->mode = TIME;
  83778. case TIME:
  83779. NEEDBITS(32);
  83780. if (state->head != Z_NULL)
  83781. state->head->time = hold;
  83782. if (state->flags & 0x0200) CRC4(state->check, hold);
  83783. INITBITS();
  83784. state->mode = OS;
  83785. case OS:
  83786. NEEDBITS(16);
  83787. if (state->head != Z_NULL) {
  83788. state->head->xflags = (int)(hold & 0xff);
  83789. state->head->os = (int)(hold >> 8);
  83790. }
  83791. if (state->flags & 0x0200) CRC2(state->check, hold);
  83792. INITBITS();
  83793. state->mode = EXLEN;
  83794. case EXLEN:
  83795. if (state->flags & 0x0400) {
  83796. NEEDBITS(16);
  83797. state->length = (unsigned)(hold);
  83798. if (state->head != Z_NULL)
  83799. state->head->extra_len = (unsigned)hold;
  83800. if (state->flags & 0x0200) CRC2(state->check, hold);
  83801. INITBITS();
  83802. }
  83803. else if (state->head != Z_NULL)
  83804. state->head->extra = Z_NULL;
  83805. state->mode = EXTRA;
  83806. case EXTRA:
  83807. if (state->flags & 0x0400) {
  83808. copy = state->length;
  83809. if (copy > have) copy = have;
  83810. if (copy) {
  83811. if (state->head != Z_NULL &&
  83812. state->head->extra != Z_NULL) {
  83813. len = state->head->extra_len - state->length;
  83814. zmemcpy(state->head->extra + len, next,
  83815. len + copy > state->head->extra_max ?
  83816. state->head->extra_max - len : copy);
  83817. }
  83818. if (state->flags & 0x0200)
  83819. state->check = crc32(state->check, next, copy);
  83820. have -= copy;
  83821. next += copy;
  83822. state->length -= copy;
  83823. }
  83824. if (state->length) goto inf_leave;
  83825. }
  83826. state->length = 0;
  83827. state->mode = NAME;
  83828. case NAME:
  83829. if (state->flags & 0x0800) {
  83830. if (have == 0) goto inf_leave;
  83831. copy = 0;
  83832. do {
  83833. len = (unsigned)(next[copy++]);
  83834. if (state->head != Z_NULL &&
  83835. state->head->name != Z_NULL &&
  83836. state->length < state->head->name_max)
  83837. state->head->name[state->length++] = len;
  83838. } while (len && copy < have);
  83839. if (state->flags & 0x0200)
  83840. state->check = crc32(state->check, next, copy);
  83841. have -= copy;
  83842. next += copy;
  83843. if (len) goto inf_leave;
  83844. }
  83845. else if (state->head != Z_NULL)
  83846. state->head->name = Z_NULL;
  83847. state->length = 0;
  83848. state->mode = COMMENT;
  83849. case COMMENT:
  83850. if (state->flags & 0x1000) {
  83851. if (have == 0) goto inf_leave;
  83852. copy = 0;
  83853. do {
  83854. len = (unsigned)(next[copy++]);
  83855. if (state->head != Z_NULL &&
  83856. state->head->comment != Z_NULL &&
  83857. state->length < state->head->comm_max)
  83858. state->head->comment[state->length++] = len;
  83859. } while (len && copy < have);
  83860. if (state->flags & 0x0200)
  83861. state->check = crc32(state->check, next, copy);
  83862. have -= copy;
  83863. next += copy;
  83864. if (len) goto inf_leave;
  83865. }
  83866. else if (state->head != Z_NULL)
  83867. state->head->comment = Z_NULL;
  83868. state->mode = HCRC;
  83869. case HCRC:
  83870. if (state->flags & 0x0200) {
  83871. NEEDBITS(16);
  83872. if (hold != (state->check & 0xffff)) {
  83873. strm->msg = (char *)"header crc mismatch";
  83874. state->mode = BAD;
  83875. break;
  83876. }
  83877. INITBITS();
  83878. }
  83879. if (state->head != Z_NULL) {
  83880. state->head->hcrc = (int)((state->flags >> 9) & 1);
  83881. state->head->done = 1;
  83882. }
  83883. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  83884. state->mode = TYPE;
  83885. break;
  83886. #endif
  83887. case DICTID:
  83888. NEEDBITS(32);
  83889. strm->adler = state->check = REVERSE(hold);
  83890. INITBITS();
  83891. state->mode = DICT;
  83892. case DICT:
  83893. if (state->havedict == 0) {
  83894. RESTORE();
  83895. return Z_NEED_DICT;
  83896. }
  83897. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83898. state->mode = TYPE;
  83899. case TYPE:
  83900. if (flush == Z_BLOCK) goto inf_leave;
  83901. case TYPEDO:
  83902. if (state->last) {
  83903. BYTEBITS();
  83904. state->mode = CHECK;
  83905. break;
  83906. }
  83907. NEEDBITS(3);
  83908. state->last = BITS(1);
  83909. DROPBITS(1);
  83910. switch (BITS(2)) {
  83911. case 0: /* stored block */
  83912. Tracev((stderr, "inflate: stored block%s\n",
  83913. state->last ? " (last)" : ""));
  83914. state->mode = STORED;
  83915. break;
  83916. case 1: /* fixed block */
  83917. fixedtables(state);
  83918. Tracev((stderr, "inflate: fixed codes block%s\n",
  83919. state->last ? " (last)" : ""));
  83920. state->mode = LEN; /* decode codes */
  83921. break;
  83922. case 2: /* dynamic block */
  83923. Tracev((stderr, "inflate: dynamic codes block%s\n",
  83924. state->last ? " (last)" : ""));
  83925. state->mode = TABLE;
  83926. break;
  83927. case 3:
  83928. strm->msg = (char *)"invalid block type";
  83929. state->mode = BAD;
  83930. }
  83931. DROPBITS(2);
  83932. break;
  83933. case STORED:
  83934. BYTEBITS(); /* go to byte boundary */
  83935. NEEDBITS(32);
  83936. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  83937. strm->msg = (char *)"invalid stored block lengths";
  83938. state->mode = BAD;
  83939. break;
  83940. }
  83941. state->length = (unsigned)hold & 0xffff;
  83942. Tracev((stderr, "inflate: stored length %u\n",
  83943. state->length));
  83944. INITBITS();
  83945. state->mode = COPY;
  83946. case COPY:
  83947. copy = state->length;
  83948. if (copy) {
  83949. if (copy > have) copy = have;
  83950. if (copy > left) copy = left;
  83951. if (copy == 0) goto inf_leave;
  83952. zmemcpy(put, next, copy);
  83953. have -= copy;
  83954. next += copy;
  83955. left -= copy;
  83956. put += copy;
  83957. state->length -= copy;
  83958. break;
  83959. }
  83960. Tracev((stderr, "inflate: stored end\n"));
  83961. state->mode = TYPE;
  83962. break;
  83963. case TABLE:
  83964. NEEDBITS(14);
  83965. state->nlen = BITS(5) + 257;
  83966. DROPBITS(5);
  83967. state->ndist = BITS(5) + 1;
  83968. DROPBITS(5);
  83969. state->ncode = BITS(4) + 4;
  83970. DROPBITS(4);
  83971. #ifndef PKZIP_BUG_WORKAROUND
  83972. if (state->nlen > 286 || state->ndist > 30) {
  83973. strm->msg = (char *)"too many length or distance symbols";
  83974. state->mode = BAD;
  83975. break;
  83976. }
  83977. #endif
  83978. Tracev((stderr, "inflate: table sizes ok\n"));
  83979. state->have = 0;
  83980. state->mode = LENLENS;
  83981. case LENLENS:
  83982. while (state->have < state->ncode) {
  83983. NEEDBITS(3);
  83984. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  83985. DROPBITS(3);
  83986. }
  83987. while (state->have < 19)
  83988. state->lens[order[state->have++]] = 0;
  83989. state->next = state->codes;
  83990. state->lencode = (code const FAR *)(state->next);
  83991. state->lenbits = 7;
  83992. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  83993. &(state->lenbits), state->work);
  83994. if (ret) {
  83995. strm->msg = (char *)"invalid code lengths set";
  83996. state->mode = BAD;
  83997. break;
  83998. }
  83999. Tracev((stderr, "inflate: code lengths ok\n"));
  84000. state->have = 0;
  84001. state->mode = CODELENS;
  84002. case CODELENS:
  84003. while (state->have < state->nlen + state->ndist) {
  84004. for (;;) {
  84005. thisx = state->lencode[BITS(state->lenbits)];
  84006. if ((unsigned)(thisx.bits) <= bits) break;
  84007. PULLBYTE();
  84008. }
  84009. if (thisx.val < 16) {
  84010. NEEDBITS(thisx.bits);
  84011. DROPBITS(thisx.bits);
  84012. state->lens[state->have++] = thisx.val;
  84013. }
  84014. else {
  84015. if (thisx.val == 16) {
  84016. NEEDBITS(thisx.bits + 2);
  84017. DROPBITS(thisx.bits);
  84018. if (state->have == 0) {
  84019. strm->msg = (char *)"invalid bit length repeat";
  84020. state->mode = BAD;
  84021. break;
  84022. }
  84023. len = state->lens[state->have - 1];
  84024. copy = 3 + BITS(2);
  84025. DROPBITS(2);
  84026. }
  84027. else if (thisx.val == 17) {
  84028. NEEDBITS(thisx.bits + 3);
  84029. DROPBITS(thisx.bits);
  84030. len = 0;
  84031. copy = 3 + BITS(3);
  84032. DROPBITS(3);
  84033. }
  84034. else {
  84035. NEEDBITS(thisx.bits + 7);
  84036. DROPBITS(thisx.bits);
  84037. len = 0;
  84038. copy = 11 + BITS(7);
  84039. DROPBITS(7);
  84040. }
  84041. if (state->have + copy > state->nlen + state->ndist) {
  84042. strm->msg = (char *)"invalid bit length repeat";
  84043. state->mode = BAD;
  84044. break;
  84045. }
  84046. while (copy--)
  84047. state->lens[state->have++] = (unsigned short)len;
  84048. }
  84049. }
  84050. /* handle error breaks in while */
  84051. if (state->mode == BAD) break;
  84052. /* build code tables */
  84053. state->next = state->codes;
  84054. state->lencode = (code const FAR *)(state->next);
  84055. state->lenbits = 9;
  84056. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  84057. &(state->lenbits), state->work);
  84058. if (ret) {
  84059. strm->msg = (char *)"invalid literal/lengths set";
  84060. state->mode = BAD;
  84061. break;
  84062. }
  84063. state->distcode = (code const FAR *)(state->next);
  84064. state->distbits = 6;
  84065. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  84066. &(state->next), &(state->distbits), state->work);
  84067. if (ret) {
  84068. strm->msg = (char *)"invalid distances set";
  84069. state->mode = BAD;
  84070. break;
  84071. }
  84072. Tracev((stderr, "inflate: codes ok\n"));
  84073. state->mode = LEN;
  84074. case LEN:
  84075. if (have >= 6 && left >= 258) {
  84076. RESTORE();
  84077. inflate_fast(strm, out);
  84078. LOAD();
  84079. break;
  84080. }
  84081. for (;;) {
  84082. thisx = state->lencode[BITS(state->lenbits)];
  84083. if ((unsigned)(thisx.bits) <= bits) break;
  84084. PULLBYTE();
  84085. }
  84086. if (thisx.op && (thisx.op & 0xf0) == 0) {
  84087. last = thisx;
  84088. for (;;) {
  84089. thisx = state->lencode[last.val +
  84090. (BITS(last.bits + last.op) >> last.bits)];
  84091. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  84092. PULLBYTE();
  84093. }
  84094. DROPBITS(last.bits);
  84095. }
  84096. DROPBITS(thisx.bits);
  84097. state->length = (unsigned)thisx.val;
  84098. if ((int)(thisx.op) == 0) {
  84099. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  84100. "inflate: literal '%c'\n" :
  84101. "inflate: literal 0x%02x\n", thisx.val));
  84102. state->mode = LIT;
  84103. break;
  84104. }
  84105. if (thisx.op & 32) {
  84106. Tracevv((stderr, "inflate: end of block\n"));
  84107. state->mode = TYPE;
  84108. break;
  84109. }
  84110. if (thisx.op & 64) {
  84111. strm->msg = (char *)"invalid literal/length code";
  84112. state->mode = BAD;
  84113. break;
  84114. }
  84115. state->extra = (unsigned)(thisx.op) & 15;
  84116. state->mode = LENEXT;
  84117. case LENEXT:
  84118. if (state->extra) {
  84119. NEEDBITS(state->extra);
  84120. state->length += BITS(state->extra);
  84121. DROPBITS(state->extra);
  84122. }
  84123. Tracevv((stderr, "inflate: length %u\n", state->length));
  84124. state->mode = DIST;
  84125. case DIST:
  84126. for (;;) {
  84127. thisx = state->distcode[BITS(state->distbits)];
  84128. if ((unsigned)(thisx.bits) <= bits) break;
  84129. PULLBYTE();
  84130. }
  84131. if ((thisx.op & 0xf0) == 0) {
  84132. last = thisx;
  84133. for (;;) {
  84134. thisx = state->distcode[last.val +
  84135. (BITS(last.bits + last.op) >> last.bits)];
  84136. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  84137. PULLBYTE();
  84138. }
  84139. DROPBITS(last.bits);
  84140. }
  84141. DROPBITS(thisx.bits);
  84142. if (thisx.op & 64) {
  84143. strm->msg = (char *)"invalid distance code";
  84144. state->mode = BAD;
  84145. break;
  84146. }
  84147. state->offset = (unsigned)thisx.val;
  84148. state->extra = (unsigned)(thisx.op) & 15;
  84149. state->mode = DISTEXT;
  84150. case DISTEXT:
  84151. if (state->extra) {
  84152. NEEDBITS(state->extra);
  84153. state->offset += BITS(state->extra);
  84154. DROPBITS(state->extra);
  84155. }
  84156. #ifdef INFLATE_STRICT
  84157. if (state->offset > state->dmax) {
  84158. strm->msg = (char *)"invalid distance too far back";
  84159. state->mode = BAD;
  84160. break;
  84161. }
  84162. #endif
  84163. if (state->offset > state->whave + out - left) {
  84164. strm->msg = (char *)"invalid distance too far back";
  84165. state->mode = BAD;
  84166. break;
  84167. }
  84168. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  84169. state->mode = MATCH;
  84170. case MATCH:
  84171. if (left == 0) goto inf_leave;
  84172. copy = out - left;
  84173. if (state->offset > copy) { /* copy from window */
  84174. copy = state->offset - copy;
  84175. if (copy > state->write) {
  84176. copy -= state->write;
  84177. from = state->window + (state->wsize - copy);
  84178. }
  84179. else
  84180. from = state->window + (state->write - copy);
  84181. if (copy > state->length) copy = state->length;
  84182. }
  84183. else { /* copy from output */
  84184. from = put - state->offset;
  84185. copy = state->length;
  84186. }
  84187. if (copy > left) copy = left;
  84188. left -= copy;
  84189. state->length -= copy;
  84190. do {
  84191. *put++ = *from++;
  84192. } while (--copy);
  84193. if (state->length == 0) state->mode = LEN;
  84194. break;
  84195. case LIT:
  84196. if (left == 0) goto inf_leave;
  84197. *put++ = (unsigned char)(state->length);
  84198. left--;
  84199. state->mode = LEN;
  84200. break;
  84201. case CHECK:
  84202. if (state->wrap) {
  84203. NEEDBITS(32);
  84204. out -= left;
  84205. strm->total_out += out;
  84206. state->total += out;
  84207. if (out)
  84208. strm->adler = state->check =
  84209. UPDATE(state->check, put - out, out);
  84210. out = left;
  84211. if ((
  84212. #ifdef GUNZIP
  84213. state->flags ? hold :
  84214. #endif
  84215. REVERSE(hold)) != state->check) {
  84216. strm->msg = (char *)"incorrect data check";
  84217. state->mode = BAD;
  84218. break;
  84219. }
  84220. INITBITS();
  84221. Tracev((stderr, "inflate: check matches trailer\n"));
  84222. }
  84223. #ifdef GUNZIP
  84224. state->mode = LENGTH;
  84225. case LENGTH:
  84226. if (state->wrap && state->flags) {
  84227. NEEDBITS(32);
  84228. if (hold != (state->total & 0xffffffffUL)) {
  84229. strm->msg = (char *)"incorrect length check";
  84230. state->mode = BAD;
  84231. break;
  84232. }
  84233. INITBITS();
  84234. Tracev((stderr, "inflate: length matches trailer\n"));
  84235. }
  84236. #endif
  84237. state->mode = DONE;
  84238. case DONE:
  84239. ret = Z_STREAM_END;
  84240. goto inf_leave;
  84241. case BAD:
  84242. ret = Z_DATA_ERROR;
  84243. goto inf_leave;
  84244. case MEM:
  84245. return Z_MEM_ERROR;
  84246. case SYNC:
  84247. default:
  84248. return Z_STREAM_ERROR;
  84249. }
  84250. /*
  84251. Return from inflate(), updating the total counts and the check value.
  84252. If there was no progress during the inflate() call, return a buffer
  84253. error. Call updatewindow() to create and/or update the window state.
  84254. Note: a memory error from inflate() is non-recoverable.
  84255. */
  84256. inf_leave:
  84257. RESTORE();
  84258. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  84259. if (updatewindow(strm, out)) {
  84260. state->mode = MEM;
  84261. return Z_MEM_ERROR;
  84262. }
  84263. in -= strm->avail_in;
  84264. out -= strm->avail_out;
  84265. strm->total_in += in;
  84266. strm->total_out += out;
  84267. state->total += out;
  84268. if (state->wrap && out)
  84269. strm->adler = state->check =
  84270. UPDATE(state->check, strm->next_out - out, out);
  84271. strm->data_type = state->bits + (state->last ? 64 : 0) +
  84272. (state->mode == TYPE ? 128 : 0);
  84273. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  84274. ret = Z_BUF_ERROR;
  84275. return ret;
  84276. }
  84277. int ZEXPORT inflateEnd (z_streamp strm)
  84278. {
  84279. struct inflate_state FAR *state;
  84280. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  84281. return Z_STREAM_ERROR;
  84282. state = (struct inflate_state FAR *)strm->state;
  84283. if (state->window != Z_NULL) ZFREE(strm, state->window);
  84284. ZFREE(strm, strm->state);
  84285. strm->state = Z_NULL;
  84286. Tracev((stderr, "inflate: end\n"));
  84287. return Z_OK;
  84288. }
  84289. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  84290. {
  84291. struct inflate_state FAR *state;
  84292. unsigned long id_;
  84293. /* check state */
  84294. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84295. state = (struct inflate_state FAR *)strm->state;
  84296. if (state->wrap != 0 && state->mode != DICT)
  84297. return Z_STREAM_ERROR;
  84298. /* check for correct dictionary id */
  84299. if (state->mode == DICT) {
  84300. id_ = adler32(0L, Z_NULL, 0);
  84301. id_ = adler32(id_, dictionary, dictLength);
  84302. if (id_ != state->check)
  84303. return Z_DATA_ERROR;
  84304. }
  84305. /* copy dictionary to window */
  84306. if (updatewindow(strm, strm->avail_out)) {
  84307. state->mode = MEM;
  84308. return Z_MEM_ERROR;
  84309. }
  84310. if (dictLength > state->wsize) {
  84311. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  84312. state->wsize);
  84313. state->whave = state->wsize;
  84314. }
  84315. else {
  84316. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  84317. dictLength);
  84318. state->whave = dictLength;
  84319. }
  84320. state->havedict = 1;
  84321. Tracev((stderr, "inflate: dictionary set\n"));
  84322. return Z_OK;
  84323. }
  84324. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  84325. {
  84326. struct inflate_state FAR *state;
  84327. /* check state */
  84328. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84329. state = (struct inflate_state FAR *)strm->state;
  84330. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  84331. /* save header structure */
  84332. state->head = head;
  84333. head->done = 0;
  84334. return Z_OK;
  84335. }
  84336. /*
  84337. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  84338. or when out of input. When called, *have is the number of pattern bytes
  84339. found in order so far, in 0..3. On return *have is updated to the new
  84340. state. If on return *have equals four, then the pattern was found and the
  84341. return value is how many bytes were read including the last byte of the
  84342. pattern. If *have is less than four, then the pattern has not been found
  84343. yet and the return value is len. In the latter case, syncsearch() can be
  84344. called again with more data and the *have state. *have is initialized to
  84345. zero for the first call.
  84346. */
  84347. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  84348. {
  84349. unsigned got;
  84350. unsigned next;
  84351. got = *have;
  84352. next = 0;
  84353. while (next < len && got < 4) {
  84354. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  84355. got++;
  84356. else if (buf[next])
  84357. got = 0;
  84358. else
  84359. got = 4 - got;
  84360. next++;
  84361. }
  84362. *have = got;
  84363. return next;
  84364. }
  84365. int ZEXPORT inflateSync (z_streamp strm)
  84366. {
  84367. unsigned len; /* number of bytes to look at or looked at */
  84368. unsigned long in, out; /* temporary to save total_in and total_out */
  84369. unsigned char buf[4]; /* to restore bit buffer to byte string */
  84370. struct inflate_state FAR *state;
  84371. /* check parameters */
  84372. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84373. state = (struct inflate_state FAR *)strm->state;
  84374. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  84375. /* if first time, start search in bit buffer */
  84376. if (state->mode != SYNC) {
  84377. state->mode = SYNC;
  84378. state->hold <<= state->bits & 7;
  84379. state->bits -= state->bits & 7;
  84380. len = 0;
  84381. while (state->bits >= 8) {
  84382. buf[len++] = (unsigned char)(state->hold);
  84383. state->hold >>= 8;
  84384. state->bits -= 8;
  84385. }
  84386. state->have = 0;
  84387. syncsearch(&(state->have), buf, len);
  84388. }
  84389. /* search available input */
  84390. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  84391. strm->avail_in -= len;
  84392. strm->next_in += len;
  84393. strm->total_in += len;
  84394. /* return no joy or set up to restart inflate() on a new block */
  84395. if (state->have != 4) return Z_DATA_ERROR;
  84396. in = strm->total_in; out = strm->total_out;
  84397. inflateReset(strm);
  84398. strm->total_in = in; strm->total_out = out;
  84399. state->mode = TYPE;
  84400. return Z_OK;
  84401. }
  84402. /*
  84403. Returns true if inflate is currently at the end of a block generated by
  84404. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  84405. implementation to provide an additional safety check. PPP uses
  84406. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  84407. block. When decompressing, PPP checks that at the end of input packet,
  84408. inflate is waiting for these length bytes.
  84409. */
  84410. int ZEXPORT inflateSyncPoint (z_streamp strm)
  84411. {
  84412. struct inflate_state FAR *state;
  84413. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84414. state = (struct inflate_state FAR *)strm->state;
  84415. return state->mode == STORED && state->bits == 0;
  84416. }
  84417. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  84418. {
  84419. struct inflate_state FAR *state;
  84420. struct inflate_state FAR *copy;
  84421. unsigned char FAR *window;
  84422. unsigned wsize;
  84423. /* check input */
  84424. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  84425. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  84426. return Z_STREAM_ERROR;
  84427. state = (struct inflate_state FAR *)source->state;
  84428. /* allocate space */
  84429. copy = (struct inflate_state FAR *)
  84430. ZALLOC(source, 1, sizeof(struct inflate_state));
  84431. if (copy == Z_NULL) return Z_MEM_ERROR;
  84432. window = Z_NULL;
  84433. if (state->window != Z_NULL) {
  84434. window = (unsigned char FAR *)
  84435. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  84436. if (window == Z_NULL) {
  84437. ZFREE(source, copy);
  84438. return Z_MEM_ERROR;
  84439. }
  84440. }
  84441. /* copy state */
  84442. zmemcpy(dest, source, sizeof(z_stream));
  84443. zmemcpy(copy, state, sizeof(struct inflate_state));
  84444. if (state->lencode >= state->codes &&
  84445. state->lencode <= state->codes + ENOUGH - 1) {
  84446. copy->lencode = copy->codes + (state->lencode - state->codes);
  84447. copy->distcode = copy->codes + (state->distcode - state->codes);
  84448. }
  84449. copy->next = copy->codes + (state->next - state->codes);
  84450. if (window != Z_NULL) {
  84451. wsize = 1U << state->wbits;
  84452. zmemcpy(window, state->window, wsize);
  84453. }
  84454. copy->window = window;
  84455. dest->state = (struct internal_state FAR *)copy;
  84456. return Z_OK;
  84457. }
  84458. /*** End of inlined file: inflate.c ***/
  84459. /*** Start of inlined file: inftrees.c ***/
  84460. #define MAXBITS 15
  84461. const char inflate_copyright[] =
  84462. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  84463. /*
  84464. If you use the zlib library in a product, an acknowledgment is welcome
  84465. in the documentation of your product. If for some reason you cannot
  84466. include such an acknowledgment, I would appreciate that you keep this
  84467. copyright string in the executable of your product.
  84468. */
  84469. /*
  84470. Build a set of tables to decode the provided canonical Huffman code.
  84471. The code lengths are lens[0..codes-1]. The result starts at *table,
  84472. whose indices are 0..2^bits-1. work is a writable array of at least
  84473. lens shorts, which is used as a work area. type is the type of code
  84474. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  84475. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  84476. on return points to the next available entry's address. bits is the
  84477. requested root table index bits, and on return it is the actual root
  84478. table index bits. It will differ if the request is greater than the
  84479. longest code or if it is less than the shortest code.
  84480. */
  84481. int inflate_table (codetype type,
  84482. unsigned short FAR *lens,
  84483. unsigned codes,
  84484. code FAR * FAR *table,
  84485. unsigned FAR *bits,
  84486. unsigned short FAR *work)
  84487. {
  84488. unsigned len; /* a code's length in bits */
  84489. unsigned sym; /* index of code symbols */
  84490. unsigned min, max; /* minimum and maximum code lengths */
  84491. unsigned root; /* number of index bits for root table */
  84492. unsigned curr; /* number of index bits for current table */
  84493. unsigned drop; /* code bits to drop for sub-table */
  84494. int left; /* number of prefix codes available */
  84495. unsigned used; /* code entries in table used */
  84496. unsigned huff; /* Huffman code */
  84497. unsigned incr; /* for incrementing code, index */
  84498. unsigned fill; /* index for replicating entries */
  84499. unsigned low; /* low bits for current root entry */
  84500. unsigned mask; /* mask for low root bits */
  84501. code thisx; /* table entry for duplication */
  84502. code FAR *next; /* next available space in table */
  84503. const unsigned short FAR *base; /* base value table to use */
  84504. const unsigned short FAR *extra; /* extra bits table to use */
  84505. int end; /* use base and extra for symbol > end */
  84506. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  84507. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  84508. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  84509. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  84510. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  84511. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  84512. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  84513. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  84514. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  84515. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  84516. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  84517. 8193, 12289, 16385, 24577, 0, 0};
  84518. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  84519. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  84520. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  84521. 28, 28, 29, 29, 64, 64};
  84522. /*
  84523. Process a set of code lengths to create a canonical Huffman code. The
  84524. code lengths are lens[0..codes-1]. Each length corresponds to the
  84525. symbols 0..codes-1. The Huffman code is generated by first sorting the
  84526. symbols by length from short to long, and retaining the symbol order
  84527. for codes with equal lengths. Then the code starts with all zero bits
  84528. for the first code of the shortest length, and the codes are integer
  84529. increments for the same length, and zeros are appended as the length
  84530. increases. For the deflate format, these bits are stored backwards
  84531. from their more natural integer increment ordering, and so when the
  84532. decoding tables are built in the large loop below, the integer codes
  84533. are incremented backwards.
  84534. This routine assumes, but does not check, that all of the entries in
  84535. lens[] are in the range 0..MAXBITS. The caller must assure this.
  84536. 1..MAXBITS is interpreted as that code length. zero means that that
  84537. symbol does not occur in this code.
  84538. The codes are sorted by computing a count of codes for each length,
  84539. creating from that a table of starting indices for each length in the
  84540. sorted table, and then entering the symbols in order in the sorted
  84541. table. The sorted table is work[], with that space being provided by
  84542. the caller.
  84543. The length counts are used for other purposes as well, i.e. finding
  84544. the minimum and maximum length codes, determining if there are any
  84545. codes at all, checking for a valid set of lengths, and looking ahead
  84546. at length counts to determine sub-table sizes when building the
  84547. decoding tables.
  84548. */
  84549. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  84550. for (len = 0; len <= MAXBITS; len++)
  84551. count[len] = 0;
  84552. for (sym = 0; sym < codes; sym++)
  84553. count[lens[sym]]++;
  84554. /* bound code lengths, force root to be within code lengths */
  84555. root = *bits;
  84556. for (max = MAXBITS; max >= 1; max--)
  84557. if (count[max] != 0) break;
  84558. if (root > max) root = max;
  84559. if (max == 0) { /* no symbols to code at all */
  84560. thisx.op = (unsigned char)64; /* invalid code marker */
  84561. thisx.bits = (unsigned char)1;
  84562. thisx.val = (unsigned short)0;
  84563. *(*table)++ = thisx; /* make a table to force an error */
  84564. *(*table)++ = thisx;
  84565. *bits = 1;
  84566. return 0; /* no symbols, but wait for decoding to report error */
  84567. }
  84568. for (min = 1; min <= MAXBITS; min++)
  84569. if (count[min] != 0) break;
  84570. if (root < min) root = min;
  84571. /* check for an over-subscribed or incomplete set of lengths */
  84572. left = 1;
  84573. for (len = 1; len <= MAXBITS; len++) {
  84574. left <<= 1;
  84575. left -= count[len];
  84576. if (left < 0) return -1; /* over-subscribed */
  84577. }
  84578. if (left > 0 && (type == CODES || max != 1))
  84579. return -1; /* incomplete set */
  84580. /* generate offsets into symbol table for each length for sorting */
  84581. offs[1] = 0;
  84582. for (len = 1; len < MAXBITS; len++)
  84583. offs[len + 1] = offs[len] + count[len];
  84584. /* sort symbols by length, by symbol order within each length */
  84585. for (sym = 0; sym < codes; sym++)
  84586. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  84587. /*
  84588. Create and fill in decoding tables. In this loop, the table being
  84589. filled is at next and has curr index bits. The code being used is huff
  84590. with length len. That code is converted to an index by dropping drop
  84591. bits off of the bottom. For codes where len is less than drop + curr,
  84592. those top drop + curr - len bits are incremented through all values to
  84593. fill the table with replicated entries.
  84594. root is the number of index bits for the root table. When len exceeds
  84595. root, sub-tables are created pointed to by the root entry with an index
  84596. of the low root bits of huff. This is saved in low to check for when a
  84597. new sub-table should be started. drop is zero when the root table is
  84598. being filled, and drop is root when sub-tables are being filled.
  84599. When a new sub-table is needed, it is necessary to look ahead in the
  84600. code lengths to determine what size sub-table is needed. The length
  84601. counts are used for this, and so count[] is decremented as codes are
  84602. entered in the tables.
  84603. used keeps track of how many table entries have been allocated from the
  84604. provided *table space. It is checked when a LENS table is being made
  84605. against the space in *table, ENOUGH, minus the maximum space needed by
  84606. the worst case distance code, MAXD. This should never happen, but the
  84607. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  84608. This assumes that when type == LENS, bits == 9.
  84609. sym increments through all symbols, and the loop terminates when
  84610. all codes of length max, i.e. all codes, have been processed. This
  84611. routine permits incomplete codes, so another loop after this one fills
  84612. in the rest of the decoding tables with invalid code markers.
  84613. */
  84614. /* set up for code type */
  84615. switch (type) {
  84616. case CODES:
  84617. base = extra = work; /* dummy value--not used */
  84618. end = 19;
  84619. break;
  84620. case LENS:
  84621. base = lbase;
  84622. base -= 257;
  84623. extra = lext;
  84624. extra -= 257;
  84625. end = 256;
  84626. break;
  84627. default: /* DISTS */
  84628. base = dbase;
  84629. extra = dext;
  84630. end = -1;
  84631. }
  84632. /* initialize state for loop */
  84633. huff = 0; /* starting code */
  84634. sym = 0; /* starting code symbol */
  84635. len = min; /* starting code length */
  84636. next = *table; /* current table to fill in */
  84637. curr = root; /* current table index bits */
  84638. drop = 0; /* current bits to drop from code for index */
  84639. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  84640. used = 1U << root; /* use root table entries */
  84641. mask = used - 1; /* mask for comparing low */
  84642. /* check available table space */
  84643. if (type == LENS && used >= ENOUGH - MAXD)
  84644. return 1;
  84645. /* process all codes and make table entries */
  84646. for (;;) {
  84647. /* create table entry */
  84648. thisx.bits = (unsigned char)(len - drop);
  84649. if ((int)(work[sym]) < end) {
  84650. thisx.op = (unsigned char)0;
  84651. thisx.val = work[sym];
  84652. }
  84653. else if ((int)(work[sym]) > end) {
  84654. thisx.op = (unsigned char)(extra[work[sym]]);
  84655. thisx.val = base[work[sym]];
  84656. }
  84657. else {
  84658. thisx.op = (unsigned char)(32 + 64); /* end of block */
  84659. thisx.val = 0;
  84660. }
  84661. /* replicate for those indices with low len bits equal to huff */
  84662. incr = 1U << (len - drop);
  84663. fill = 1U << curr;
  84664. min = fill; /* save offset to next table */
  84665. do {
  84666. fill -= incr;
  84667. next[(huff >> drop) + fill] = thisx;
  84668. } while (fill != 0);
  84669. /* backwards increment the len-bit code huff */
  84670. incr = 1U << (len - 1);
  84671. while (huff & incr)
  84672. incr >>= 1;
  84673. if (incr != 0) {
  84674. huff &= incr - 1;
  84675. huff += incr;
  84676. }
  84677. else
  84678. huff = 0;
  84679. /* go to next symbol, update count, len */
  84680. sym++;
  84681. if (--(count[len]) == 0) {
  84682. if (len == max) break;
  84683. len = lens[work[sym]];
  84684. }
  84685. /* create new sub-table if needed */
  84686. if (len > root && (huff & mask) != low) {
  84687. /* if first time, transition to sub-tables */
  84688. if (drop == 0)
  84689. drop = root;
  84690. /* increment past last table */
  84691. next += min; /* here min is 1 << curr */
  84692. /* determine length of next table */
  84693. curr = len - drop;
  84694. left = (int)(1 << curr);
  84695. while (curr + drop < max) {
  84696. left -= count[curr + drop];
  84697. if (left <= 0) break;
  84698. curr++;
  84699. left <<= 1;
  84700. }
  84701. /* check for enough space */
  84702. used += 1U << curr;
  84703. if (type == LENS && used >= ENOUGH - MAXD)
  84704. return 1;
  84705. /* point entry in root table to sub-table */
  84706. low = huff & mask;
  84707. (*table)[low].op = (unsigned char)curr;
  84708. (*table)[low].bits = (unsigned char)root;
  84709. (*table)[low].val = (unsigned short)(next - *table);
  84710. }
  84711. }
  84712. /*
  84713. Fill in rest of table for incomplete codes. This loop is similar to the
  84714. loop above in incrementing huff for table indices. It is assumed that
  84715. len is equal to curr + drop, so there is no loop needed to increment
  84716. through high index bits. When the current sub-table is filled, the loop
  84717. drops back to the root table to fill in any remaining entries there.
  84718. */
  84719. thisx.op = (unsigned char)64; /* invalid code marker */
  84720. thisx.bits = (unsigned char)(len - drop);
  84721. thisx.val = (unsigned short)0;
  84722. while (huff != 0) {
  84723. /* when done with sub-table, drop back to root table */
  84724. if (drop != 0 && (huff & mask) != low) {
  84725. drop = 0;
  84726. len = root;
  84727. next = *table;
  84728. thisx.bits = (unsigned char)len;
  84729. }
  84730. /* put invalid code marker in table */
  84731. next[huff >> drop] = thisx;
  84732. /* backwards increment the len-bit code huff */
  84733. incr = 1U << (len - 1);
  84734. while (huff & incr)
  84735. incr >>= 1;
  84736. if (incr != 0) {
  84737. huff &= incr - 1;
  84738. huff += incr;
  84739. }
  84740. else
  84741. huff = 0;
  84742. }
  84743. /* set return parameters */
  84744. *table += used;
  84745. *bits = root;
  84746. return 0;
  84747. }
  84748. /*** End of inlined file: inftrees.c ***/
  84749. /*** Start of inlined file: trees.c ***/
  84750. /*
  84751. * ALGORITHM
  84752. *
  84753. * The "deflation" process uses several Huffman trees. The more
  84754. * common source values are represented by shorter bit sequences.
  84755. *
  84756. * Each code tree is stored in a compressed form which is itself
  84757. * a Huffman encoding of the lengths of all the code strings (in
  84758. * ascending order by source values). The actual code strings are
  84759. * reconstructed from the lengths in the inflate process, as described
  84760. * in the deflate specification.
  84761. *
  84762. * REFERENCES
  84763. *
  84764. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  84765. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  84766. *
  84767. * Storer, James A.
  84768. * Data Compression: Methods and Theory, pp. 49-50.
  84769. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  84770. *
  84771. * Sedgewick, R.
  84772. * Algorithms, p290.
  84773. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  84774. */
  84775. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  84776. /* #define GEN_TREES_H */
  84777. #ifdef DEBUG
  84778. # include <ctype.h>
  84779. #endif
  84780. /* ===========================================================================
  84781. * Constants
  84782. */
  84783. #define MAX_BL_BITS 7
  84784. /* Bit length codes must not exceed MAX_BL_BITS bits */
  84785. #define END_BLOCK 256
  84786. /* end of block literal code */
  84787. #define REP_3_6 16
  84788. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  84789. #define REPZ_3_10 17
  84790. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  84791. #define REPZ_11_138 18
  84792. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  84793. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  84794. = {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};
  84795. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  84796. = {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};
  84797. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  84798. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  84799. local const uch bl_order[BL_CODES]
  84800. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  84801. /* The lengths of the bit length codes are sent in order of decreasing
  84802. * probability, to avoid transmitting the lengths for unused bit length codes.
  84803. */
  84804. #define Buf_size (8 * 2*sizeof(char))
  84805. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  84806. * more than 16 bits on some systems.)
  84807. */
  84808. /* ===========================================================================
  84809. * Local data. These are initialized only once.
  84810. */
  84811. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  84812. #if defined(GEN_TREES_H) || !defined(STDC)
  84813. /* non ANSI compilers may not accept trees.h */
  84814. local ct_data static_ltree[L_CODES+2];
  84815. /* The static literal tree. Since the bit lengths are imposed, there is no
  84816. * need for the L_CODES extra codes used during heap construction. However
  84817. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  84818. * below).
  84819. */
  84820. local ct_data static_dtree[D_CODES];
  84821. /* The static distance tree. (Actually a trivial tree since all codes use
  84822. * 5 bits.)
  84823. */
  84824. uch _dist_code[DIST_CODE_LEN];
  84825. /* Distance codes. The first 256 values correspond to the distances
  84826. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  84827. * the 15 bit distances.
  84828. */
  84829. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  84830. /* length code for each normalized match length (0 == MIN_MATCH) */
  84831. local int base_length[LENGTH_CODES];
  84832. /* First normalized length for each code (0 = MIN_MATCH) */
  84833. local int base_dist[D_CODES];
  84834. /* First normalized distance for each code (0 = distance of 1) */
  84835. #else
  84836. /*** Start of inlined file: trees.h ***/
  84837. local const ct_data static_ltree[L_CODES+2] = {
  84838. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  84839. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  84840. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  84841. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  84842. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  84843. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  84844. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  84845. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  84846. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  84847. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  84848. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  84849. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  84850. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  84851. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  84852. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  84853. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  84854. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  84855. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  84856. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  84857. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  84858. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  84859. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  84860. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  84861. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  84862. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  84863. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  84864. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  84865. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  84866. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  84867. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  84868. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  84869. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  84870. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  84871. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  84872. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  84873. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  84874. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  84875. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  84876. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  84877. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  84878. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  84879. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  84880. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  84881. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  84882. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  84883. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  84884. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  84885. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  84886. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  84887. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  84888. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  84889. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  84890. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  84891. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  84892. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  84893. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  84894. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  84895. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  84896. };
  84897. local const ct_data static_dtree[D_CODES] = {
  84898. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  84899. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  84900. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  84901. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  84902. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  84903. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  84904. };
  84905. const uch _dist_code[DIST_CODE_LEN] = {
  84906. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  84907. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  84908. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  84909. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  84910. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  84911. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  84912. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84913. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84914. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  84915. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  84916. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84917. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  84918. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  84919. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  84920. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84921. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84922. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84923. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  84924. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84925. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84926. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84927. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  84928. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84929. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84930. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  84931. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  84932. };
  84933. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  84934. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  84935. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  84936. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  84937. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  84938. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  84939. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  84940. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84941. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  84942. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  84943. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  84944. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  84945. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  84946. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  84947. };
  84948. local const int base_length[LENGTH_CODES] = {
  84949. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  84950. 64, 80, 96, 112, 128, 160, 192, 224, 0
  84951. };
  84952. local const int base_dist[D_CODES] = {
  84953. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  84954. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  84955. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  84956. };
  84957. /*** End of inlined file: trees.h ***/
  84958. #endif /* GEN_TREES_H */
  84959. struct static_tree_desc_s {
  84960. const ct_data *static_tree; /* static tree or NULL */
  84961. const intf *extra_bits; /* extra bits for each code or NULL */
  84962. int extra_base; /* base index for extra_bits */
  84963. int elems; /* max number of elements in the tree */
  84964. int max_length; /* max bit length for the codes */
  84965. };
  84966. local static_tree_desc static_l_desc =
  84967. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  84968. local static_tree_desc static_d_desc =
  84969. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  84970. local static_tree_desc static_bl_desc =
  84971. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  84972. /* ===========================================================================
  84973. * Local (static) routines in this file.
  84974. */
  84975. local void tr_static_init OF((void));
  84976. local void init_block OF((deflate_state *s));
  84977. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  84978. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  84979. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  84980. local void build_tree OF((deflate_state *s, tree_desc *desc));
  84981. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  84982. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  84983. local int build_bl_tree OF((deflate_state *s));
  84984. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  84985. int blcodes));
  84986. local void compress_block OF((deflate_state *s, ct_data *ltree,
  84987. ct_data *dtree));
  84988. local void set_data_type OF((deflate_state *s));
  84989. local unsigned bi_reverse OF((unsigned value, int length));
  84990. local void bi_windup OF((deflate_state *s));
  84991. local void bi_flush OF((deflate_state *s));
  84992. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  84993. int header));
  84994. #ifdef GEN_TREES_H
  84995. local void gen_trees_header OF((void));
  84996. #endif
  84997. #ifndef DEBUG
  84998. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  84999. /* Send a code of the given tree. c and tree must not have side effects */
  85000. #else /* DEBUG */
  85001. # define send_code(s, c, tree) \
  85002. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  85003. send_bits(s, tree[c].Code, tree[c].Len); }
  85004. #endif
  85005. /* ===========================================================================
  85006. * Output a short LSB first on the stream.
  85007. * IN assertion: there is enough room in pendingBuf.
  85008. */
  85009. #define put_short(s, w) { \
  85010. put_byte(s, (uch)((w) & 0xff)); \
  85011. put_byte(s, (uch)((ush)(w) >> 8)); \
  85012. }
  85013. /* ===========================================================================
  85014. * Send a value on a given number of bits.
  85015. * IN assertion: length <= 16 and value fits in length bits.
  85016. */
  85017. #ifdef DEBUG
  85018. local void send_bits OF((deflate_state *s, int value, int length));
  85019. local void send_bits (deflate_state *s, int value, int length)
  85020. {
  85021. Tracevv((stderr," l %2d v %4x ", length, value));
  85022. Assert(length > 0 && length <= 15, "invalid length");
  85023. s->bits_sent += (ulg)length;
  85024. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  85025. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  85026. * unused bits in value.
  85027. */
  85028. if (s->bi_valid > (int)Buf_size - length) {
  85029. s->bi_buf |= (value << s->bi_valid);
  85030. put_short(s, s->bi_buf);
  85031. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  85032. s->bi_valid += length - Buf_size;
  85033. } else {
  85034. s->bi_buf |= value << s->bi_valid;
  85035. s->bi_valid += length;
  85036. }
  85037. }
  85038. #else /* !DEBUG */
  85039. #define send_bits(s, value, length) \
  85040. { int len = length;\
  85041. if (s->bi_valid > (int)Buf_size - len) {\
  85042. int val = value;\
  85043. s->bi_buf |= (val << s->bi_valid);\
  85044. put_short(s, s->bi_buf);\
  85045. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  85046. s->bi_valid += len - Buf_size;\
  85047. } else {\
  85048. s->bi_buf |= (value) << s->bi_valid;\
  85049. s->bi_valid += len;\
  85050. }\
  85051. }
  85052. #endif /* DEBUG */
  85053. /* the arguments must not have side effects */
  85054. /* ===========================================================================
  85055. * Initialize the various 'constant' tables.
  85056. */
  85057. local void tr_static_init()
  85058. {
  85059. #if defined(GEN_TREES_H) || !defined(STDC)
  85060. static int static_init_done = 0;
  85061. int n; /* iterates over tree elements */
  85062. int bits; /* bit counter */
  85063. int length; /* length value */
  85064. int code; /* code value */
  85065. int dist; /* distance index */
  85066. ush bl_count[MAX_BITS+1];
  85067. /* number of codes at each bit length for an optimal tree */
  85068. if (static_init_done) return;
  85069. /* For some embedded targets, global variables are not initialized: */
  85070. static_l_desc.static_tree = static_ltree;
  85071. static_l_desc.extra_bits = extra_lbits;
  85072. static_d_desc.static_tree = static_dtree;
  85073. static_d_desc.extra_bits = extra_dbits;
  85074. static_bl_desc.extra_bits = extra_blbits;
  85075. /* Initialize the mapping length (0..255) -> length code (0..28) */
  85076. length = 0;
  85077. for (code = 0; code < LENGTH_CODES-1; code++) {
  85078. base_length[code] = length;
  85079. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  85080. _length_code[length++] = (uch)code;
  85081. }
  85082. }
  85083. Assert (length == 256, "tr_static_init: length != 256");
  85084. /* Note that the length 255 (match length 258) can be represented
  85085. * in two different ways: code 284 + 5 bits or code 285, so we
  85086. * overwrite length_code[255] to use the best encoding:
  85087. */
  85088. _length_code[length-1] = (uch)code;
  85089. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  85090. dist = 0;
  85091. for (code = 0 ; code < 16; code++) {
  85092. base_dist[code] = dist;
  85093. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  85094. _dist_code[dist++] = (uch)code;
  85095. }
  85096. }
  85097. Assert (dist == 256, "tr_static_init: dist != 256");
  85098. dist >>= 7; /* from now on, all distances are divided by 128 */
  85099. for ( ; code < D_CODES; code++) {
  85100. base_dist[code] = dist << 7;
  85101. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  85102. _dist_code[256 + dist++] = (uch)code;
  85103. }
  85104. }
  85105. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  85106. /* Construct the codes of the static literal tree */
  85107. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  85108. n = 0;
  85109. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  85110. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  85111. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  85112. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  85113. /* Codes 286 and 287 do not exist, but we must include them in the
  85114. * tree construction to get a canonical Huffman tree (longest code
  85115. * all ones)
  85116. */
  85117. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  85118. /* The static distance tree is trivial: */
  85119. for (n = 0; n < D_CODES; n++) {
  85120. static_dtree[n].Len = 5;
  85121. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  85122. }
  85123. static_init_done = 1;
  85124. # ifdef GEN_TREES_H
  85125. gen_trees_header();
  85126. # endif
  85127. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  85128. }
  85129. /* ===========================================================================
  85130. * Genererate the file trees.h describing the static trees.
  85131. */
  85132. #ifdef GEN_TREES_H
  85133. # ifndef DEBUG
  85134. # include <stdio.h>
  85135. # endif
  85136. # define SEPARATOR(i, last, width) \
  85137. ((i) == (last)? "\n};\n\n" : \
  85138. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  85139. void gen_trees_header()
  85140. {
  85141. FILE *header = fopen("trees.h", "w");
  85142. int i;
  85143. Assert (header != NULL, "Can't open trees.h");
  85144. fprintf(header,
  85145. "/* header created automatically with -DGEN_TREES_H */\n\n");
  85146. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  85147. for (i = 0; i < L_CODES+2; i++) {
  85148. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  85149. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  85150. }
  85151. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  85152. for (i = 0; i < D_CODES; i++) {
  85153. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  85154. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  85155. }
  85156. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  85157. for (i = 0; i < DIST_CODE_LEN; i++) {
  85158. fprintf(header, "%2u%s", _dist_code[i],
  85159. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  85160. }
  85161. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  85162. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  85163. fprintf(header, "%2u%s", _length_code[i],
  85164. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  85165. }
  85166. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  85167. for (i = 0; i < LENGTH_CODES; i++) {
  85168. fprintf(header, "%1u%s", base_length[i],
  85169. SEPARATOR(i, LENGTH_CODES-1, 20));
  85170. }
  85171. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  85172. for (i = 0; i < D_CODES; i++) {
  85173. fprintf(header, "%5u%s", base_dist[i],
  85174. SEPARATOR(i, D_CODES-1, 10));
  85175. }
  85176. fclose(header);
  85177. }
  85178. #endif /* GEN_TREES_H */
  85179. /* ===========================================================================
  85180. * Initialize the tree data structures for a new zlib stream.
  85181. */
  85182. void _tr_init(deflate_state *s)
  85183. {
  85184. tr_static_init();
  85185. s->l_desc.dyn_tree = s->dyn_ltree;
  85186. s->l_desc.stat_desc = &static_l_desc;
  85187. s->d_desc.dyn_tree = s->dyn_dtree;
  85188. s->d_desc.stat_desc = &static_d_desc;
  85189. s->bl_desc.dyn_tree = s->bl_tree;
  85190. s->bl_desc.stat_desc = &static_bl_desc;
  85191. s->bi_buf = 0;
  85192. s->bi_valid = 0;
  85193. s->last_eob_len = 8; /* enough lookahead for inflate */
  85194. #ifdef DEBUG
  85195. s->compressed_len = 0L;
  85196. s->bits_sent = 0L;
  85197. #endif
  85198. /* Initialize the first block of the first file: */
  85199. init_block(s);
  85200. }
  85201. /* ===========================================================================
  85202. * Initialize a new block.
  85203. */
  85204. local void init_block (deflate_state *s)
  85205. {
  85206. int n; /* iterates over tree elements */
  85207. /* Initialize the trees. */
  85208. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  85209. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  85210. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  85211. s->dyn_ltree[END_BLOCK].Freq = 1;
  85212. s->opt_len = s->static_len = 0L;
  85213. s->last_lit = s->matches = 0;
  85214. }
  85215. #define SMALLEST 1
  85216. /* Index within the heap array of least frequent node in the Huffman tree */
  85217. /* ===========================================================================
  85218. * Remove the smallest element from the heap and recreate the heap with
  85219. * one less element. Updates heap and heap_len.
  85220. */
  85221. #define pqremove(s, tree, top) \
  85222. {\
  85223. top = s->heap[SMALLEST]; \
  85224. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  85225. pqdownheap(s, tree, SMALLEST); \
  85226. }
  85227. /* ===========================================================================
  85228. * Compares to subtrees, using the tree depth as tie breaker when
  85229. * the subtrees have equal frequency. This minimizes the worst case length.
  85230. */
  85231. #define smaller(tree, n, m, depth) \
  85232. (tree[n].Freq < tree[m].Freq || \
  85233. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  85234. /* ===========================================================================
  85235. * Restore the heap property by moving down the tree starting at node k,
  85236. * exchanging a node with the smallest of its two sons if necessary, stopping
  85237. * when the heap property is re-established (each father smaller than its
  85238. * two sons).
  85239. */
  85240. local void pqdownheap (deflate_state *s,
  85241. ct_data *tree, /* the tree to restore */
  85242. int k) /* node to move down */
  85243. {
  85244. int v = s->heap[k];
  85245. int j = k << 1; /* left son of k */
  85246. while (j <= s->heap_len) {
  85247. /* Set j to the smallest of the two sons: */
  85248. if (j < s->heap_len &&
  85249. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  85250. j++;
  85251. }
  85252. /* Exit if v is smaller than both sons */
  85253. if (smaller(tree, v, s->heap[j], s->depth)) break;
  85254. /* Exchange v with the smallest son */
  85255. s->heap[k] = s->heap[j]; k = j;
  85256. /* And continue down the tree, setting j to the left son of k */
  85257. j <<= 1;
  85258. }
  85259. s->heap[k] = v;
  85260. }
  85261. /* ===========================================================================
  85262. * Compute the optimal bit lengths for a tree and update the total bit length
  85263. * for the current block.
  85264. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  85265. * above are the tree nodes sorted by increasing frequency.
  85266. * OUT assertions: the field len is set to the optimal bit length, the
  85267. * array bl_count contains the frequencies for each bit length.
  85268. * The length opt_len is updated; static_len is also updated if stree is
  85269. * not null.
  85270. */
  85271. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  85272. {
  85273. ct_data *tree = desc->dyn_tree;
  85274. int max_code = desc->max_code;
  85275. const ct_data *stree = desc->stat_desc->static_tree;
  85276. const intf *extra = desc->stat_desc->extra_bits;
  85277. int base = desc->stat_desc->extra_base;
  85278. int max_length = desc->stat_desc->max_length;
  85279. int h; /* heap index */
  85280. int n, m; /* iterate over the tree elements */
  85281. int bits; /* bit length */
  85282. int xbits; /* extra bits */
  85283. ush f; /* frequency */
  85284. int overflow = 0; /* number of elements with bit length too large */
  85285. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  85286. /* In a first pass, compute the optimal bit lengths (which may
  85287. * overflow in the case of the bit length tree).
  85288. */
  85289. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  85290. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  85291. n = s->heap[h];
  85292. bits = tree[tree[n].Dad].Len + 1;
  85293. if (bits > max_length) bits = max_length, overflow++;
  85294. tree[n].Len = (ush)bits;
  85295. /* We overwrite tree[n].Dad which is no longer needed */
  85296. if (n > max_code) continue; /* not a leaf node */
  85297. s->bl_count[bits]++;
  85298. xbits = 0;
  85299. if (n >= base) xbits = extra[n-base];
  85300. f = tree[n].Freq;
  85301. s->opt_len += (ulg)f * (bits + xbits);
  85302. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  85303. }
  85304. if (overflow == 0) return;
  85305. Trace((stderr,"\nbit length overflow\n"));
  85306. /* This happens for example on obj2 and pic of the Calgary corpus */
  85307. /* Find the first bit length which could increase: */
  85308. do {
  85309. bits = max_length-1;
  85310. while (s->bl_count[bits] == 0) bits--;
  85311. s->bl_count[bits]--; /* move one leaf down the tree */
  85312. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  85313. s->bl_count[max_length]--;
  85314. /* The brother of the overflow item also moves one step up,
  85315. * but this does not affect bl_count[max_length]
  85316. */
  85317. overflow -= 2;
  85318. } while (overflow > 0);
  85319. /* Now recompute all bit lengths, scanning in increasing frequency.
  85320. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  85321. * lengths instead of fixing only the wrong ones. This idea is taken
  85322. * from 'ar' written by Haruhiko Okumura.)
  85323. */
  85324. for (bits = max_length; bits != 0; bits--) {
  85325. n = s->bl_count[bits];
  85326. while (n != 0) {
  85327. m = s->heap[--h];
  85328. if (m > max_code) continue;
  85329. if ((unsigned) tree[m].Len != (unsigned) bits) {
  85330. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  85331. s->opt_len += ((long)bits - (long)tree[m].Len)
  85332. *(long)tree[m].Freq;
  85333. tree[m].Len = (ush)bits;
  85334. }
  85335. n--;
  85336. }
  85337. }
  85338. }
  85339. /* ===========================================================================
  85340. * Generate the codes for a given tree and bit counts (which need not be
  85341. * optimal).
  85342. * IN assertion: the array bl_count contains the bit length statistics for
  85343. * the given tree and the field len is set for all tree elements.
  85344. * OUT assertion: the field code is set for all tree elements of non
  85345. * zero code length.
  85346. */
  85347. local void gen_codes (ct_data *tree, /* the tree to decorate */
  85348. int max_code, /* largest code with non zero frequency */
  85349. ushf *bl_count) /* number of codes at each bit length */
  85350. {
  85351. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  85352. ush code = 0; /* running code value */
  85353. int bits; /* bit index */
  85354. int n; /* code index */
  85355. /* The distribution counts are first used to generate the code values
  85356. * without bit reversal.
  85357. */
  85358. for (bits = 1; bits <= MAX_BITS; bits++) {
  85359. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  85360. }
  85361. /* Check that the bit counts in bl_count are consistent. The last code
  85362. * must be all ones.
  85363. */
  85364. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  85365. "inconsistent bit counts");
  85366. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  85367. for (n = 0; n <= max_code; n++) {
  85368. int len = tree[n].Len;
  85369. if (len == 0) continue;
  85370. /* Now reverse the bits */
  85371. tree[n].Code = bi_reverse(next_code[len]++, len);
  85372. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  85373. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  85374. }
  85375. }
  85376. /* ===========================================================================
  85377. * Construct one Huffman tree and assigns the code bit strings and lengths.
  85378. * Update the total bit length for the current block.
  85379. * IN assertion: the field freq is set for all tree elements.
  85380. * OUT assertions: the fields len and code are set to the optimal bit length
  85381. * and corresponding code. The length opt_len is updated; static_len is
  85382. * also updated if stree is not null. The field max_code is set.
  85383. */
  85384. local void build_tree (deflate_state *s,
  85385. tree_desc *desc) /* the tree descriptor */
  85386. {
  85387. ct_data *tree = desc->dyn_tree;
  85388. const ct_data *stree = desc->stat_desc->static_tree;
  85389. int elems = desc->stat_desc->elems;
  85390. int n, m; /* iterate over heap elements */
  85391. int max_code = -1; /* largest code with non zero frequency */
  85392. int node; /* new node being created */
  85393. /* Construct the initial heap, with least frequent element in
  85394. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  85395. * heap[0] is not used.
  85396. */
  85397. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  85398. for (n = 0; n < elems; n++) {
  85399. if (tree[n].Freq != 0) {
  85400. s->heap[++(s->heap_len)] = max_code = n;
  85401. s->depth[n] = 0;
  85402. } else {
  85403. tree[n].Len = 0;
  85404. }
  85405. }
  85406. /* The pkzip format requires that at least one distance code exists,
  85407. * and that at least one bit should be sent even if there is only one
  85408. * possible code. So to avoid special checks later on we force at least
  85409. * two codes of non zero frequency.
  85410. */
  85411. while (s->heap_len < 2) {
  85412. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  85413. tree[node].Freq = 1;
  85414. s->depth[node] = 0;
  85415. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  85416. /* node is 0 or 1 so it does not have extra bits */
  85417. }
  85418. desc->max_code = max_code;
  85419. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  85420. * establish sub-heaps of increasing lengths:
  85421. */
  85422. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  85423. /* Construct the Huffman tree by repeatedly combining the least two
  85424. * frequent nodes.
  85425. */
  85426. node = elems; /* next internal node of the tree */
  85427. do {
  85428. pqremove(s, tree, n); /* n = node of least frequency */
  85429. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  85430. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  85431. s->heap[--(s->heap_max)] = m;
  85432. /* Create a new node father of n and m */
  85433. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  85434. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  85435. s->depth[n] : s->depth[m]) + 1);
  85436. tree[n].Dad = tree[m].Dad = (ush)node;
  85437. #ifdef DUMP_BL_TREE
  85438. if (tree == s->bl_tree) {
  85439. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  85440. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  85441. }
  85442. #endif
  85443. /* and insert the new node in the heap */
  85444. s->heap[SMALLEST] = node++;
  85445. pqdownheap(s, tree, SMALLEST);
  85446. } while (s->heap_len >= 2);
  85447. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  85448. /* At this point, the fields freq and dad are set. We can now
  85449. * generate the bit lengths.
  85450. */
  85451. gen_bitlen(s, (tree_desc *)desc);
  85452. /* The field len is now set, we can generate the bit codes */
  85453. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  85454. }
  85455. /* ===========================================================================
  85456. * Scan a literal or distance tree to determine the frequencies of the codes
  85457. * in the bit length tree.
  85458. */
  85459. local void scan_tree (deflate_state *s,
  85460. ct_data *tree, /* the tree to be scanned */
  85461. int max_code) /* and its largest code of non zero frequency */
  85462. {
  85463. int n; /* iterates over all tree elements */
  85464. int prevlen = -1; /* last emitted length */
  85465. int curlen; /* length of current code */
  85466. int nextlen = tree[0].Len; /* length of next code */
  85467. int count = 0; /* repeat count of the current code */
  85468. int max_count = 7; /* max repeat count */
  85469. int min_count = 4; /* min repeat count */
  85470. if (nextlen == 0) max_count = 138, min_count = 3;
  85471. tree[max_code+1].Len = (ush)0xffff; /* guard */
  85472. for (n = 0; n <= max_code; n++) {
  85473. curlen = nextlen; nextlen = tree[n+1].Len;
  85474. if (++count < max_count && curlen == nextlen) {
  85475. continue;
  85476. } else if (count < min_count) {
  85477. s->bl_tree[curlen].Freq += count;
  85478. } else if (curlen != 0) {
  85479. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  85480. s->bl_tree[REP_3_6].Freq++;
  85481. } else if (count <= 10) {
  85482. s->bl_tree[REPZ_3_10].Freq++;
  85483. } else {
  85484. s->bl_tree[REPZ_11_138].Freq++;
  85485. }
  85486. count = 0; prevlen = curlen;
  85487. if (nextlen == 0) {
  85488. max_count = 138, min_count = 3;
  85489. } else if (curlen == nextlen) {
  85490. max_count = 6, min_count = 3;
  85491. } else {
  85492. max_count = 7, min_count = 4;
  85493. }
  85494. }
  85495. }
  85496. /* ===========================================================================
  85497. * Send a literal or distance tree in compressed form, using the codes in
  85498. * bl_tree.
  85499. */
  85500. local void send_tree (deflate_state *s,
  85501. ct_data *tree, /* the tree to be scanned */
  85502. int max_code) /* and its largest code of non zero frequency */
  85503. {
  85504. int n; /* iterates over all tree elements */
  85505. int prevlen = -1; /* last emitted length */
  85506. int curlen; /* length of current code */
  85507. int nextlen = tree[0].Len; /* length of next code */
  85508. int count = 0; /* repeat count of the current code */
  85509. int max_count = 7; /* max repeat count */
  85510. int min_count = 4; /* min repeat count */
  85511. /* tree[max_code+1].Len = -1; */ /* guard already set */
  85512. if (nextlen == 0) max_count = 138, min_count = 3;
  85513. for (n = 0; n <= max_code; n++) {
  85514. curlen = nextlen; nextlen = tree[n+1].Len;
  85515. if (++count < max_count && curlen == nextlen) {
  85516. continue;
  85517. } else if (count < min_count) {
  85518. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  85519. } else if (curlen != 0) {
  85520. if (curlen != prevlen) {
  85521. send_code(s, curlen, s->bl_tree); count--;
  85522. }
  85523. Assert(count >= 3 && count <= 6, " 3_6?");
  85524. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  85525. } else if (count <= 10) {
  85526. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  85527. } else {
  85528. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  85529. }
  85530. count = 0; prevlen = curlen;
  85531. if (nextlen == 0) {
  85532. max_count = 138, min_count = 3;
  85533. } else if (curlen == nextlen) {
  85534. max_count = 6, min_count = 3;
  85535. } else {
  85536. max_count = 7, min_count = 4;
  85537. }
  85538. }
  85539. }
  85540. /* ===========================================================================
  85541. * Construct the Huffman tree for the bit lengths and return the index in
  85542. * bl_order of the last bit length code to send.
  85543. */
  85544. local int build_bl_tree (deflate_state *s)
  85545. {
  85546. int max_blindex; /* index of last bit length code of non zero freq */
  85547. /* Determine the bit length frequencies for literal and distance trees */
  85548. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  85549. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  85550. /* Build the bit length tree: */
  85551. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  85552. /* opt_len now includes the length of the tree representations, except
  85553. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  85554. */
  85555. /* Determine the number of bit length codes to send. The pkzip format
  85556. * requires that at least 4 bit length codes be sent. (appnote.txt says
  85557. * 3 but the actual value used is 4.)
  85558. */
  85559. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  85560. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  85561. }
  85562. /* Update opt_len to include the bit length tree and counts */
  85563. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  85564. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  85565. s->opt_len, s->static_len));
  85566. return max_blindex;
  85567. }
  85568. /* ===========================================================================
  85569. * Send the header for a block using dynamic Huffman trees: the counts, the
  85570. * lengths of the bit length codes, the literal tree and the distance tree.
  85571. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  85572. */
  85573. local void send_all_trees (deflate_state *s,
  85574. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  85575. {
  85576. int rank; /* index in bl_order */
  85577. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  85578. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  85579. "too many codes");
  85580. Tracev((stderr, "\nbl counts: "));
  85581. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  85582. send_bits(s, dcodes-1, 5);
  85583. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  85584. for (rank = 0; rank < blcodes; rank++) {
  85585. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  85586. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  85587. }
  85588. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  85589. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  85590. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  85591. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  85592. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  85593. }
  85594. /* ===========================================================================
  85595. * Send a stored block
  85596. */
  85597. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  85598. {
  85599. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  85600. #ifdef DEBUG
  85601. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  85602. s->compressed_len += (stored_len + 4) << 3;
  85603. #endif
  85604. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  85605. }
  85606. /* ===========================================================================
  85607. * Send one empty static block to give enough lookahead for inflate.
  85608. * This takes 10 bits, of which 7 may remain in the bit buffer.
  85609. * The current inflate code requires 9 bits of lookahead. If the
  85610. * last two codes for the previous block (real code plus EOB) were coded
  85611. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  85612. * the last real code. In this case we send two empty static blocks instead
  85613. * of one. (There are no problems if the previous block is stored or fixed.)
  85614. * To simplify the code, we assume the worst case of last real code encoded
  85615. * on one bit only.
  85616. */
  85617. void _tr_align (deflate_state *s)
  85618. {
  85619. send_bits(s, STATIC_TREES<<1, 3);
  85620. send_code(s, END_BLOCK, static_ltree);
  85621. #ifdef DEBUG
  85622. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  85623. #endif
  85624. bi_flush(s);
  85625. /* Of the 10 bits for the empty block, we have already sent
  85626. * (10 - bi_valid) bits. The lookahead for the last real code (before
  85627. * the EOB of the previous block) was thus at least one plus the length
  85628. * of the EOB plus what we have just sent of the empty static block.
  85629. */
  85630. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  85631. send_bits(s, STATIC_TREES<<1, 3);
  85632. send_code(s, END_BLOCK, static_ltree);
  85633. #ifdef DEBUG
  85634. s->compressed_len += 10L;
  85635. #endif
  85636. bi_flush(s);
  85637. }
  85638. s->last_eob_len = 7;
  85639. }
  85640. /* ===========================================================================
  85641. * Determine the best encoding for the current block: dynamic trees, static
  85642. * trees or store, and output the encoded block to the zip file.
  85643. */
  85644. void _tr_flush_block (deflate_state *s,
  85645. charf *buf, /* input block, or NULL if too old */
  85646. ulg stored_len, /* length of input block */
  85647. int eof) /* true if this is the last block for a file */
  85648. {
  85649. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  85650. int max_blindex = 0; /* index of last bit length code of non zero freq */
  85651. /* Build the Huffman trees unless a stored block is forced */
  85652. if (s->level > 0) {
  85653. /* Check if the file is binary or text */
  85654. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  85655. set_data_type(s);
  85656. /* Construct the literal and distance trees */
  85657. build_tree(s, (tree_desc *)(&(s->l_desc)));
  85658. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  85659. s->static_len));
  85660. build_tree(s, (tree_desc *)(&(s->d_desc)));
  85661. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  85662. s->static_len));
  85663. /* At this point, opt_len and static_len are the total bit lengths of
  85664. * the compressed block data, excluding the tree representations.
  85665. */
  85666. /* Build the bit length tree for the above two trees, and get the index
  85667. * in bl_order of the last bit length code to send.
  85668. */
  85669. max_blindex = build_bl_tree(s);
  85670. /* Determine the best encoding. Compute the block lengths in bytes. */
  85671. opt_lenb = (s->opt_len+3+7)>>3;
  85672. static_lenb = (s->static_len+3+7)>>3;
  85673. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  85674. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  85675. s->last_lit));
  85676. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  85677. } else {
  85678. Assert(buf != (char*)0, "lost buf");
  85679. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  85680. }
  85681. #ifdef FORCE_STORED
  85682. if (buf != (char*)0) { /* force stored block */
  85683. #else
  85684. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  85685. /* 4: two words for the lengths */
  85686. #endif
  85687. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  85688. * Otherwise we can't have processed more than WSIZE input bytes since
  85689. * the last block flush, because compression would have been
  85690. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  85691. * transform a block into a stored block.
  85692. */
  85693. _tr_stored_block(s, buf, stored_len, eof);
  85694. #ifdef FORCE_STATIC
  85695. } else if (static_lenb >= 0) { /* force static trees */
  85696. #else
  85697. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  85698. #endif
  85699. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  85700. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  85701. #ifdef DEBUG
  85702. s->compressed_len += 3 + s->static_len;
  85703. #endif
  85704. } else {
  85705. send_bits(s, (DYN_TREES<<1)+eof, 3);
  85706. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  85707. max_blindex+1);
  85708. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  85709. #ifdef DEBUG
  85710. s->compressed_len += 3 + s->opt_len;
  85711. #endif
  85712. }
  85713. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  85714. /* The above check is made mod 2^32, for files larger than 512 MB
  85715. * and uLong implemented on 32 bits.
  85716. */
  85717. init_block(s);
  85718. if (eof) {
  85719. bi_windup(s);
  85720. #ifdef DEBUG
  85721. s->compressed_len += 7; /* align on byte boundary */
  85722. #endif
  85723. }
  85724. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  85725. s->compressed_len-7*eof));
  85726. }
  85727. /* ===========================================================================
  85728. * Save the match info and tally the frequency counts. Return true if
  85729. * the current block must be flushed.
  85730. */
  85731. int _tr_tally (deflate_state *s,
  85732. unsigned dist, /* distance of matched string */
  85733. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  85734. {
  85735. s->d_buf[s->last_lit] = (ush)dist;
  85736. s->l_buf[s->last_lit++] = (uch)lc;
  85737. if (dist == 0) {
  85738. /* lc is the unmatched char */
  85739. s->dyn_ltree[lc].Freq++;
  85740. } else {
  85741. s->matches++;
  85742. /* Here, lc is the match length - MIN_MATCH */
  85743. dist--; /* dist = match distance - 1 */
  85744. Assert((ush)dist < (ush)MAX_DIST(s) &&
  85745. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  85746. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  85747. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  85748. s->dyn_dtree[d_code(dist)].Freq++;
  85749. }
  85750. #ifdef TRUNCATE_BLOCK
  85751. /* Try to guess if it is profitable to stop the current block here */
  85752. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  85753. /* Compute an upper bound for the compressed length */
  85754. ulg out_length = (ulg)s->last_lit*8L;
  85755. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  85756. int dcode;
  85757. for (dcode = 0; dcode < D_CODES; dcode++) {
  85758. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  85759. (5L+extra_dbits[dcode]);
  85760. }
  85761. out_length >>= 3;
  85762. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  85763. s->last_lit, in_length, out_length,
  85764. 100L - out_length*100L/in_length));
  85765. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  85766. }
  85767. #endif
  85768. return (s->last_lit == s->lit_bufsize-1);
  85769. /* We avoid equality with lit_bufsize because of wraparound at 64K
  85770. * on 16 bit machines and because stored blocks are restricted to
  85771. * 64K-1 bytes.
  85772. */
  85773. }
  85774. /* ===========================================================================
  85775. * Send the block data compressed using the given Huffman trees
  85776. */
  85777. local void compress_block (deflate_state *s,
  85778. ct_data *ltree, /* literal tree */
  85779. ct_data *dtree) /* distance tree */
  85780. {
  85781. unsigned dist; /* distance of matched string */
  85782. int lc; /* match length or unmatched char (if dist == 0) */
  85783. unsigned lx = 0; /* running index in l_buf */
  85784. unsigned code; /* the code to send */
  85785. int extra; /* number of extra bits to send */
  85786. if (s->last_lit != 0) do {
  85787. dist = s->d_buf[lx];
  85788. lc = s->l_buf[lx++];
  85789. if (dist == 0) {
  85790. send_code(s, lc, ltree); /* send a literal byte */
  85791. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  85792. } else {
  85793. /* Here, lc is the match length - MIN_MATCH */
  85794. code = _length_code[lc];
  85795. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  85796. extra = extra_lbits[code];
  85797. if (extra != 0) {
  85798. lc -= base_length[code];
  85799. send_bits(s, lc, extra); /* send the extra length bits */
  85800. }
  85801. dist--; /* dist is now the match distance - 1 */
  85802. code = d_code(dist);
  85803. Assert (code < D_CODES, "bad d_code");
  85804. send_code(s, code, dtree); /* send the distance code */
  85805. extra = extra_dbits[code];
  85806. if (extra != 0) {
  85807. dist -= base_dist[code];
  85808. send_bits(s, dist, extra); /* send the extra distance bits */
  85809. }
  85810. } /* literal or match pair ? */
  85811. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  85812. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  85813. "pendingBuf overflow");
  85814. } while (lx < s->last_lit);
  85815. send_code(s, END_BLOCK, ltree);
  85816. s->last_eob_len = ltree[END_BLOCK].Len;
  85817. }
  85818. /* ===========================================================================
  85819. * Set the data type to BINARY or TEXT, using a crude approximation:
  85820. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  85821. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  85822. * IN assertion: the fields Freq of dyn_ltree are set.
  85823. */
  85824. local void set_data_type (deflate_state *s)
  85825. {
  85826. int n;
  85827. for (n = 0; n < 9; n++)
  85828. if (s->dyn_ltree[n].Freq != 0)
  85829. break;
  85830. if (n == 9)
  85831. for (n = 14; n < 32; n++)
  85832. if (s->dyn_ltree[n].Freq != 0)
  85833. break;
  85834. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  85835. }
  85836. /* ===========================================================================
  85837. * Reverse the first len bits of a code, using straightforward code (a faster
  85838. * method would use a table)
  85839. * IN assertion: 1 <= len <= 15
  85840. */
  85841. local unsigned bi_reverse (unsigned code, int len)
  85842. {
  85843. register unsigned res = 0;
  85844. do {
  85845. res |= code & 1;
  85846. code >>= 1, res <<= 1;
  85847. } while (--len > 0);
  85848. return res >> 1;
  85849. }
  85850. /* ===========================================================================
  85851. * Flush the bit buffer, keeping at most 7 bits in it.
  85852. */
  85853. local void bi_flush (deflate_state *s)
  85854. {
  85855. if (s->bi_valid == 16) {
  85856. put_short(s, s->bi_buf);
  85857. s->bi_buf = 0;
  85858. s->bi_valid = 0;
  85859. } else if (s->bi_valid >= 8) {
  85860. put_byte(s, (Byte)s->bi_buf);
  85861. s->bi_buf >>= 8;
  85862. s->bi_valid -= 8;
  85863. }
  85864. }
  85865. /* ===========================================================================
  85866. * Flush the bit buffer and align the output on a byte boundary
  85867. */
  85868. local void bi_windup (deflate_state *s)
  85869. {
  85870. if (s->bi_valid > 8) {
  85871. put_short(s, s->bi_buf);
  85872. } else if (s->bi_valid > 0) {
  85873. put_byte(s, (Byte)s->bi_buf);
  85874. }
  85875. s->bi_buf = 0;
  85876. s->bi_valid = 0;
  85877. #ifdef DEBUG
  85878. s->bits_sent = (s->bits_sent+7) & ~7;
  85879. #endif
  85880. }
  85881. /* ===========================================================================
  85882. * Copy a stored block, storing first the length and its
  85883. * one's complement if requested.
  85884. */
  85885. local void copy_block(deflate_state *s,
  85886. charf *buf, /* the input data */
  85887. unsigned len, /* its length */
  85888. int header) /* true if block header must be written */
  85889. {
  85890. bi_windup(s); /* align on byte boundary */
  85891. s->last_eob_len = 8; /* enough lookahead for inflate */
  85892. if (header) {
  85893. put_short(s, (ush)len);
  85894. put_short(s, (ush)~len);
  85895. #ifdef DEBUG
  85896. s->bits_sent += 2*16;
  85897. #endif
  85898. }
  85899. #ifdef DEBUG
  85900. s->bits_sent += (ulg)len<<3;
  85901. #endif
  85902. while (len--) {
  85903. put_byte(s, *buf++);
  85904. }
  85905. }
  85906. /*** End of inlined file: trees.c ***/
  85907. /*** Start of inlined file: zutil.c ***/
  85908. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  85909. #ifndef NO_DUMMY_DECL
  85910. struct internal_state {int dummy;}; /* for buggy compilers */
  85911. #endif
  85912. const char * const z_errmsg[10] = {
  85913. "need dictionary", /* Z_NEED_DICT 2 */
  85914. "stream end", /* Z_STREAM_END 1 */
  85915. "", /* Z_OK 0 */
  85916. "file error", /* Z_ERRNO (-1) */
  85917. "stream error", /* Z_STREAM_ERROR (-2) */
  85918. "data error", /* Z_DATA_ERROR (-3) */
  85919. "insufficient memory", /* Z_MEM_ERROR (-4) */
  85920. "buffer error", /* Z_BUF_ERROR (-5) */
  85921. "incompatible version",/* Z_VERSION_ERROR (-6) */
  85922. ""};
  85923. /*const char * ZEXPORT zlibVersion()
  85924. {
  85925. return ZLIB_VERSION;
  85926. }
  85927. uLong ZEXPORT zlibCompileFlags()
  85928. {
  85929. uLong flags;
  85930. flags = 0;
  85931. switch (sizeof(uInt)) {
  85932. case 2: break;
  85933. case 4: flags += 1; break;
  85934. case 8: flags += 2; break;
  85935. default: flags += 3;
  85936. }
  85937. switch (sizeof(uLong)) {
  85938. case 2: break;
  85939. case 4: flags += 1 << 2; break;
  85940. case 8: flags += 2 << 2; break;
  85941. default: flags += 3 << 2;
  85942. }
  85943. switch (sizeof(voidpf)) {
  85944. case 2: break;
  85945. case 4: flags += 1 << 4; break;
  85946. case 8: flags += 2 << 4; break;
  85947. default: flags += 3 << 4;
  85948. }
  85949. switch (sizeof(z_off_t)) {
  85950. case 2: break;
  85951. case 4: flags += 1 << 6; break;
  85952. case 8: flags += 2 << 6; break;
  85953. default: flags += 3 << 6;
  85954. }
  85955. #ifdef DEBUG
  85956. flags += 1 << 8;
  85957. #endif
  85958. #if defined(ASMV) || defined(ASMINF)
  85959. flags += 1 << 9;
  85960. #endif
  85961. #ifdef ZLIB_WINAPI
  85962. flags += 1 << 10;
  85963. #endif
  85964. #ifdef BUILDFIXED
  85965. flags += 1 << 12;
  85966. #endif
  85967. #ifdef DYNAMIC_CRC_TABLE
  85968. flags += 1 << 13;
  85969. #endif
  85970. #ifdef NO_GZCOMPRESS
  85971. flags += 1L << 16;
  85972. #endif
  85973. #ifdef NO_GZIP
  85974. flags += 1L << 17;
  85975. #endif
  85976. #ifdef PKZIP_BUG_WORKAROUND
  85977. flags += 1L << 20;
  85978. #endif
  85979. #ifdef FASTEST
  85980. flags += 1L << 21;
  85981. #endif
  85982. #ifdef STDC
  85983. # ifdef NO_vsnprintf
  85984. flags += 1L << 25;
  85985. # ifdef HAS_vsprintf_void
  85986. flags += 1L << 26;
  85987. # endif
  85988. # else
  85989. # ifdef HAS_vsnprintf_void
  85990. flags += 1L << 26;
  85991. # endif
  85992. # endif
  85993. #else
  85994. flags += 1L << 24;
  85995. # ifdef NO_snprintf
  85996. flags += 1L << 25;
  85997. # ifdef HAS_sprintf_void
  85998. flags += 1L << 26;
  85999. # endif
  86000. # else
  86001. # ifdef HAS_snprintf_void
  86002. flags += 1L << 26;
  86003. # endif
  86004. # endif
  86005. #endif
  86006. return flags;
  86007. }*/
  86008. #ifdef DEBUG
  86009. # ifndef verbose
  86010. # define verbose 0
  86011. # endif
  86012. int z_verbose = verbose;
  86013. void z_error (const char *m)
  86014. {
  86015. fprintf(stderr, "%s\n", m);
  86016. exit(1);
  86017. }
  86018. #endif
  86019. /* exported to allow conversion of error code to string for compress() and
  86020. * uncompress()
  86021. */
  86022. const char * ZEXPORT zError(int err)
  86023. {
  86024. return ERR_MSG(err);
  86025. }
  86026. #if defined(_WIN32_WCE)
  86027. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  86028. * errno. We define it as a global variable to simplify porting.
  86029. * Its value is always 0 and should not be used.
  86030. */
  86031. int errno = 0;
  86032. #endif
  86033. #ifndef HAVE_MEMCPY
  86034. void zmemcpy(dest, source, len)
  86035. Bytef* dest;
  86036. const Bytef* source;
  86037. uInt len;
  86038. {
  86039. if (len == 0) return;
  86040. do {
  86041. *dest++ = *source++; /* ??? to be unrolled */
  86042. } while (--len != 0);
  86043. }
  86044. int zmemcmp(s1, s2, len)
  86045. const Bytef* s1;
  86046. const Bytef* s2;
  86047. uInt len;
  86048. {
  86049. uInt j;
  86050. for (j = 0; j < len; j++) {
  86051. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  86052. }
  86053. return 0;
  86054. }
  86055. void zmemzero(dest, len)
  86056. Bytef* dest;
  86057. uInt len;
  86058. {
  86059. if (len == 0) return;
  86060. do {
  86061. *dest++ = 0; /* ??? to be unrolled */
  86062. } while (--len != 0);
  86063. }
  86064. #endif
  86065. #ifdef SYS16BIT
  86066. #ifdef __TURBOC__
  86067. /* Turbo C in 16-bit mode */
  86068. # define MY_ZCALLOC
  86069. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  86070. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  86071. * must fix the pointer. Warning: the pointer must be put back to its
  86072. * original form in order to free it, use zcfree().
  86073. */
  86074. #define MAX_PTR 10
  86075. /* 10*64K = 640K */
  86076. local int next_ptr = 0;
  86077. typedef struct ptr_table_s {
  86078. voidpf org_ptr;
  86079. voidpf new_ptr;
  86080. } ptr_table;
  86081. local ptr_table table[MAX_PTR];
  86082. /* This table is used to remember the original form of pointers
  86083. * to large buffers (64K). Such pointers are normalized with a zero offset.
  86084. * Since MSDOS is not a preemptive multitasking OS, this table is not
  86085. * protected from concurrent access. This hack doesn't work anyway on
  86086. * a protected system like OS/2. Use Microsoft C instead.
  86087. */
  86088. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86089. {
  86090. voidpf buf = opaque; /* just to make some compilers happy */
  86091. ulg bsize = (ulg)items*size;
  86092. /* If we allocate less than 65520 bytes, we assume that farmalloc
  86093. * will return a usable pointer which doesn't have to be normalized.
  86094. */
  86095. if (bsize < 65520L) {
  86096. buf = farmalloc(bsize);
  86097. if (*(ush*)&buf != 0) return buf;
  86098. } else {
  86099. buf = farmalloc(bsize + 16L);
  86100. }
  86101. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  86102. table[next_ptr].org_ptr = buf;
  86103. /* Normalize the pointer to seg:0 */
  86104. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  86105. *(ush*)&buf = 0;
  86106. table[next_ptr++].new_ptr = buf;
  86107. return buf;
  86108. }
  86109. void zcfree (voidpf opaque, voidpf ptr)
  86110. {
  86111. int n;
  86112. if (*(ush*)&ptr != 0) { /* object < 64K */
  86113. farfree(ptr);
  86114. return;
  86115. }
  86116. /* Find the original pointer */
  86117. for (n = 0; n < next_ptr; n++) {
  86118. if (ptr != table[n].new_ptr) continue;
  86119. farfree(table[n].org_ptr);
  86120. while (++n < next_ptr) {
  86121. table[n-1] = table[n];
  86122. }
  86123. next_ptr--;
  86124. return;
  86125. }
  86126. ptr = opaque; /* just to make some compilers happy */
  86127. Assert(0, "zcfree: ptr not found");
  86128. }
  86129. #endif /* __TURBOC__ */
  86130. #ifdef M_I86
  86131. /* Microsoft C in 16-bit mode */
  86132. # define MY_ZCALLOC
  86133. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  86134. # define _halloc halloc
  86135. # define _hfree hfree
  86136. #endif
  86137. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86138. {
  86139. if (opaque) opaque = 0; /* to make compiler happy */
  86140. return _halloc((long)items, size);
  86141. }
  86142. void zcfree (voidpf opaque, voidpf ptr)
  86143. {
  86144. if (opaque) opaque = 0; /* to make compiler happy */
  86145. _hfree(ptr);
  86146. }
  86147. #endif /* M_I86 */
  86148. #endif /* SYS16BIT */
  86149. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  86150. #ifndef STDC
  86151. extern voidp malloc OF((uInt size));
  86152. extern voidp calloc OF((uInt items, uInt size));
  86153. extern void free OF((voidpf ptr));
  86154. #endif
  86155. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86156. {
  86157. if (opaque) items += size - size; /* make compiler happy */
  86158. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  86159. (voidpf)calloc(items, size);
  86160. }
  86161. void zcfree (voidpf opaque, voidpf ptr)
  86162. {
  86163. free(ptr);
  86164. if (opaque) return; /* make compiler happy */
  86165. }
  86166. #endif /* MY_ZCALLOC */
  86167. /*** End of inlined file: zutil.c ***/
  86168. #undef Byte
  86169. #else
  86170. #include <zlib.h>
  86171. #endif
  86172. }
  86173. #if JUCE_MSVC
  86174. #pragma warning (pop)
  86175. #endif
  86176. BEGIN_JUCE_NAMESPACE
  86177. // internal helper object that holds the zlib structures so they don't have to be
  86178. // included publicly.
  86179. class GZIPDecompressHelper
  86180. {
  86181. public:
  86182. GZIPDecompressHelper (const bool noWrap)
  86183. : finished (true),
  86184. needsDictionary (false),
  86185. error (true),
  86186. streamIsValid (false),
  86187. data (0),
  86188. dataSize (0)
  86189. {
  86190. using namespace zlibNamespace;
  86191. zerostruct (stream);
  86192. streamIsValid = (inflateInit2 (&stream, noWrap ? -MAX_WBITS : MAX_WBITS) == Z_OK);
  86193. finished = error = ! streamIsValid;
  86194. }
  86195. ~GZIPDecompressHelper()
  86196. {
  86197. using namespace zlibNamespace;
  86198. if (streamIsValid)
  86199. inflateEnd (&stream);
  86200. }
  86201. bool needsInput() const throw() { return dataSize <= 0; }
  86202. void setInput (uint8* const data_, const int size) throw()
  86203. {
  86204. data = data_;
  86205. dataSize = size;
  86206. }
  86207. int doNextBlock (uint8* const dest, const int destSize)
  86208. {
  86209. using namespace zlibNamespace;
  86210. if (streamIsValid && data != 0 && ! finished)
  86211. {
  86212. stream.next_in = data;
  86213. stream.next_out = dest;
  86214. stream.avail_in = dataSize;
  86215. stream.avail_out = destSize;
  86216. switch (inflate (&stream, Z_PARTIAL_FLUSH))
  86217. {
  86218. case Z_STREAM_END:
  86219. finished = true;
  86220. // deliberate fall-through
  86221. case Z_OK:
  86222. data += dataSize - stream.avail_in;
  86223. dataSize = stream.avail_in;
  86224. return destSize - stream.avail_out;
  86225. case Z_NEED_DICT:
  86226. needsDictionary = true;
  86227. data += dataSize - stream.avail_in;
  86228. dataSize = stream.avail_in;
  86229. break;
  86230. case Z_DATA_ERROR:
  86231. case Z_MEM_ERROR:
  86232. error = true;
  86233. default:
  86234. break;
  86235. }
  86236. }
  86237. return 0;
  86238. }
  86239. bool finished, needsDictionary, error, streamIsValid;
  86240. private:
  86241. zlibNamespace::z_stream stream;
  86242. uint8* data;
  86243. int dataSize;
  86244. GZIPDecompressHelper (const GZIPDecompressHelper&);
  86245. GZIPDecompressHelper& operator= (const GZIPDecompressHelper&);
  86246. };
  86247. const int gzipDecompBufferSize = 32768;
  86248. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  86249. const bool deleteSourceWhenDestroyed,
  86250. const bool noWrap_,
  86251. const int64 uncompressedStreamLength_)
  86252. : sourceStream (sourceStream_),
  86253. streamToDelete (deleteSourceWhenDestroyed ? sourceStream_ : 0),
  86254. uncompressedStreamLength (uncompressedStreamLength_),
  86255. noWrap (noWrap_),
  86256. isEof (false),
  86257. activeBufferSize (0),
  86258. originalSourcePos (sourceStream_->getPosition()),
  86259. currentPos (0),
  86260. buffer (gzipDecompBufferSize),
  86261. helper (new GZIPDecompressHelper (noWrap_))
  86262. {
  86263. }
  86264. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  86265. {
  86266. }
  86267. int64 GZIPDecompressorInputStream::getTotalLength()
  86268. {
  86269. return uncompressedStreamLength;
  86270. }
  86271. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  86272. {
  86273. if ((howMany > 0) && ! isEof)
  86274. {
  86275. jassert (destBuffer != 0);
  86276. if (destBuffer != 0)
  86277. {
  86278. int numRead = 0;
  86279. uint8* d = static_cast <uint8*> (destBuffer);
  86280. while (! helper->error)
  86281. {
  86282. const int n = helper->doNextBlock (d, howMany);
  86283. currentPos += n;
  86284. if (n == 0)
  86285. {
  86286. if (helper->finished || helper->needsDictionary)
  86287. {
  86288. isEof = true;
  86289. return numRead;
  86290. }
  86291. if (helper->needsInput())
  86292. {
  86293. activeBufferSize = sourceStream->read (buffer, gzipDecompBufferSize);
  86294. if (activeBufferSize > 0)
  86295. {
  86296. helper->setInput (buffer, activeBufferSize);
  86297. }
  86298. else
  86299. {
  86300. isEof = true;
  86301. return numRead;
  86302. }
  86303. }
  86304. }
  86305. else
  86306. {
  86307. numRead += n;
  86308. howMany -= n;
  86309. d += n;
  86310. if (howMany <= 0)
  86311. return numRead;
  86312. }
  86313. }
  86314. }
  86315. }
  86316. return 0;
  86317. }
  86318. bool GZIPDecompressorInputStream::isExhausted()
  86319. {
  86320. return helper->error || isEof;
  86321. }
  86322. int64 GZIPDecompressorInputStream::getPosition()
  86323. {
  86324. return currentPos;
  86325. }
  86326. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  86327. {
  86328. if (newPos < currentPos)
  86329. {
  86330. // to go backwards, reset the stream and start again..
  86331. isEof = false;
  86332. activeBufferSize = 0;
  86333. currentPos = 0;
  86334. helper = new GZIPDecompressHelper (noWrap);
  86335. sourceStream->setPosition (originalSourcePos);
  86336. }
  86337. skipNextBytes (newPos - currentPos);
  86338. return true;
  86339. }
  86340. END_JUCE_NAMESPACE
  86341. /*** End of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  86342. #endif
  86343. #if JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  86344. /*** Start of inlined file: juce_FlacAudioFormat.cpp ***/
  86345. #if JUCE_USE_FLAC
  86346. #if JUCE_WINDOWS
  86347. #include <windows.h>
  86348. #endif
  86349. namespace FlacNamespace
  86350. {
  86351. #if JUCE_INCLUDE_FLAC_CODE
  86352. #if JUCE_MSVC
  86353. #pragma warning (disable : 4505) // (unreferenced static function removal warning)
  86354. #endif
  86355. #define FLAC__NO_DLL 1
  86356. #if ! defined (SIZE_MAX)
  86357. #define SIZE_MAX 0xffffffff
  86358. #endif
  86359. #define __STDC_LIMIT_MACROS 1
  86360. /*** Start of inlined file: all.h ***/
  86361. #ifndef FLAC__ALL_H
  86362. #define FLAC__ALL_H
  86363. /*** Start of inlined file: export.h ***/
  86364. #ifndef FLAC__EXPORT_H
  86365. #define FLAC__EXPORT_H
  86366. /** \file include/FLAC/export.h
  86367. *
  86368. * \brief
  86369. * This module contains #defines and symbols for exporting function
  86370. * calls, and providing version information and compiled-in features.
  86371. *
  86372. * See the \link flac_export export \endlink module.
  86373. */
  86374. /** \defgroup flac_export FLAC/export.h: export symbols
  86375. * \ingroup flac
  86376. *
  86377. * \brief
  86378. * This module contains #defines and symbols for exporting function
  86379. * calls, and providing version information and compiled-in features.
  86380. *
  86381. * If you are compiling with MSVC and will link to the static library
  86382. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  86383. * make sure the symbols are exported properly.
  86384. *
  86385. * \{
  86386. */
  86387. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  86388. #define FLAC_API
  86389. #else
  86390. #ifdef FLAC_API_EXPORTS
  86391. #define FLAC_API _declspec(dllexport)
  86392. #else
  86393. #define FLAC_API _declspec(dllimport)
  86394. #endif
  86395. #endif
  86396. /** These #defines will mirror the libtool-based library version number, see
  86397. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  86398. */
  86399. #define FLAC_API_VERSION_CURRENT 10
  86400. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  86401. #define FLAC_API_VERSION_AGE 2 /**< see above */
  86402. #ifdef __cplusplus
  86403. extern "C" {
  86404. #endif
  86405. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  86406. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  86407. #ifdef __cplusplus
  86408. }
  86409. #endif
  86410. /* \} */
  86411. #endif
  86412. /*** End of inlined file: export.h ***/
  86413. /*** Start of inlined file: assert.h ***/
  86414. #ifndef FLAC__ASSERT_H
  86415. #define FLAC__ASSERT_H
  86416. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  86417. #ifdef DEBUG
  86418. #include <assert.h>
  86419. #define FLAC__ASSERT(x) assert(x)
  86420. #define FLAC__ASSERT_DECLARATION(x) x
  86421. #else
  86422. #define FLAC__ASSERT(x)
  86423. #define FLAC__ASSERT_DECLARATION(x)
  86424. #endif
  86425. #endif
  86426. /*** End of inlined file: assert.h ***/
  86427. /*** Start of inlined file: callback.h ***/
  86428. #ifndef FLAC__CALLBACK_H
  86429. #define FLAC__CALLBACK_H
  86430. /*** Start of inlined file: ordinals.h ***/
  86431. #ifndef FLAC__ORDINALS_H
  86432. #define FLAC__ORDINALS_H
  86433. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  86434. #include <inttypes.h>
  86435. #endif
  86436. typedef signed char FLAC__int8;
  86437. typedef unsigned char FLAC__uint8;
  86438. #if defined(_MSC_VER) || defined(__BORLANDC__)
  86439. typedef __int16 FLAC__int16;
  86440. typedef __int32 FLAC__int32;
  86441. typedef __int64 FLAC__int64;
  86442. typedef unsigned __int16 FLAC__uint16;
  86443. typedef unsigned __int32 FLAC__uint32;
  86444. typedef unsigned __int64 FLAC__uint64;
  86445. #elif defined(__EMX__)
  86446. typedef short FLAC__int16;
  86447. typedef long FLAC__int32;
  86448. typedef long long FLAC__int64;
  86449. typedef unsigned short FLAC__uint16;
  86450. typedef unsigned long FLAC__uint32;
  86451. typedef unsigned long long FLAC__uint64;
  86452. #else
  86453. typedef int16_t FLAC__int16;
  86454. typedef int32_t FLAC__int32;
  86455. typedef int64_t FLAC__int64;
  86456. typedef uint16_t FLAC__uint16;
  86457. typedef uint32_t FLAC__uint32;
  86458. typedef uint64_t FLAC__uint64;
  86459. #endif
  86460. typedef int FLAC__bool;
  86461. typedef FLAC__uint8 FLAC__byte;
  86462. #ifdef true
  86463. #undef true
  86464. #endif
  86465. #ifdef false
  86466. #undef false
  86467. #endif
  86468. #ifndef __cplusplus
  86469. #define true 1
  86470. #define false 0
  86471. #endif
  86472. #endif
  86473. /*** End of inlined file: ordinals.h ***/
  86474. #include <stdlib.h> /* for size_t */
  86475. /** \file include/FLAC/callback.h
  86476. *
  86477. * \brief
  86478. * This module defines the structures for describing I/O callbacks
  86479. * to the other FLAC interfaces.
  86480. *
  86481. * See the detailed documentation for callbacks in the
  86482. * \link flac_callbacks callbacks \endlink module.
  86483. */
  86484. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  86485. * \ingroup flac
  86486. *
  86487. * \brief
  86488. * This module defines the structures for describing I/O callbacks
  86489. * to the other FLAC interfaces.
  86490. *
  86491. * The purpose of the I/O callback functions is to create a common way
  86492. * for the metadata interfaces to handle I/O.
  86493. *
  86494. * Originally the metadata interfaces required filenames as the way of
  86495. * specifying FLAC files to operate on. This is problematic in some
  86496. * environments so there is an additional option to specify a set of
  86497. * callbacks for doing I/O on the FLAC file, instead of the filename.
  86498. *
  86499. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  86500. * opaque structure for a data source.
  86501. *
  86502. * The callback function prototypes are similar (but not identical) to the
  86503. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  86504. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  86505. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  86506. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  86507. * is required. \warning You generally CANNOT directly use fseek or ftell
  86508. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  86509. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  86510. * large files. You will have to find an equivalent function (e.g. ftello),
  86511. * or write a wrapper. The same is true for feof() since this is usually
  86512. * implemented as a macro, not as a function whose address can be taken.
  86513. *
  86514. * \{
  86515. */
  86516. #ifdef __cplusplus
  86517. extern "C" {
  86518. #endif
  86519. /** This is the opaque handle type used by the callbacks. Typically
  86520. * this is a \c FILE* or address of a file descriptor.
  86521. */
  86522. typedef void* FLAC__IOHandle;
  86523. /** Signature for the read callback.
  86524. * The signature and semantics match POSIX fread() implementations
  86525. * and can generally be used interchangeably.
  86526. *
  86527. * \param ptr The address of the read buffer.
  86528. * \param size The size of the records to be read.
  86529. * \param nmemb The number of records to be read.
  86530. * \param handle The handle to the data source.
  86531. * \retval size_t
  86532. * The number of records read.
  86533. */
  86534. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86535. /** Signature for the write callback.
  86536. * The signature and semantics match POSIX fwrite() implementations
  86537. * and can generally be used interchangeably.
  86538. *
  86539. * \param ptr The address of the write buffer.
  86540. * \param size The size of the records to be written.
  86541. * \param nmemb The number of records to be written.
  86542. * \param handle The handle to the data source.
  86543. * \retval size_t
  86544. * The number of records written.
  86545. */
  86546. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86547. /** Signature for the seek callback.
  86548. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  86549. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  86550. * and 32-bits wide.
  86551. *
  86552. * \param handle The handle to the data source.
  86553. * \param offset The new position, relative to \a whence
  86554. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  86555. * \retval int
  86556. * \c 0 on success, \c -1 on error.
  86557. */
  86558. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  86559. /** Signature for the tell callback.
  86560. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  86561. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  86562. * and 32-bits wide.
  86563. *
  86564. * \param handle The handle to the data source.
  86565. * \retval FLAC__int64
  86566. * The current position on success, \c -1 on error.
  86567. */
  86568. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  86569. /** Signature for the EOF callback.
  86570. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  86571. * on many systems, feof() is a macro, so in this case a wrapper function
  86572. * must be provided instead.
  86573. *
  86574. * \param handle The handle to the data source.
  86575. * \retval int
  86576. * \c 0 if not at end of file, nonzero if at end of file.
  86577. */
  86578. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  86579. /** Signature for the close callback.
  86580. * The signature and semantics match POSIX fclose() implementations
  86581. * and can generally be used interchangeably.
  86582. *
  86583. * \param handle The handle to the data source.
  86584. * \retval int
  86585. * \c 0 on success, \c EOF on error.
  86586. */
  86587. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  86588. /** A structure for holding a set of callbacks.
  86589. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  86590. * describe which of the callbacks are required. The ones that are not
  86591. * required may be set to NULL.
  86592. *
  86593. * If the seek requirement for an interface is optional, you can signify that
  86594. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  86595. */
  86596. typedef struct {
  86597. FLAC__IOCallback_Read read;
  86598. FLAC__IOCallback_Write write;
  86599. FLAC__IOCallback_Seek seek;
  86600. FLAC__IOCallback_Tell tell;
  86601. FLAC__IOCallback_Eof eof;
  86602. FLAC__IOCallback_Close close;
  86603. } FLAC__IOCallbacks;
  86604. /* \} */
  86605. #ifdef __cplusplus
  86606. }
  86607. #endif
  86608. #endif
  86609. /*** End of inlined file: callback.h ***/
  86610. /*** Start of inlined file: format.h ***/
  86611. #ifndef FLAC__FORMAT_H
  86612. #define FLAC__FORMAT_H
  86613. #ifdef __cplusplus
  86614. extern "C" {
  86615. #endif
  86616. /** \file include/FLAC/format.h
  86617. *
  86618. * \brief
  86619. * This module contains structure definitions for the representation
  86620. * of FLAC format components in memory. These are the basic
  86621. * structures used by the rest of the interfaces.
  86622. *
  86623. * See the detailed documentation in the
  86624. * \link flac_format format \endlink module.
  86625. */
  86626. /** \defgroup flac_format FLAC/format.h: format components
  86627. * \ingroup flac
  86628. *
  86629. * \brief
  86630. * This module contains structure definitions for the representation
  86631. * of FLAC format components in memory. These are the basic
  86632. * structures used by the rest of the interfaces.
  86633. *
  86634. * First, you should be familiar with the
  86635. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  86636. * follow directly from the specification. As a user of libFLAC, the
  86637. * interesting parts really are the structures that describe the frame
  86638. * header and metadata blocks.
  86639. *
  86640. * The format structures here are very primitive, designed to store
  86641. * information in an efficient way. Reading information from the
  86642. * structures is easy but creating or modifying them directly is
  86643. * more complex. For the most part, as a user of a library, editing
  86644. * is not necessary; however, for metadata blocks it is, so there are
  86645. * convenience functions provided in the \link flac_metadata metadata
  86646. * module \endlink to simplify the manipulation of metadata blocks.
  86647. *
  86648. * \note
  86649. * It's not the best convention, but symbols ending in _LEN are in bits
  86650. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  86651. * global variables because they are usually used when declaring byte
  86652. * arrays and some compilers require compile-time knowledge of array
  86653. * sizes when declared on the stack.
  86654. *
  86655. * \{
  86656. */
  86657. /*
  86658. Most of the values described in this file are defined by the FLAC
  86659. format specification. There is nothing to tune here.
  86660. */
  86661. /** The largest legal metadata type code. */
  86662. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  86663. /** The minimum block size, in samples, permitted by the format. */
  86664. #define FLAC__MIN_BLOCK_SIZE (16u)
  86665. /** The maximum block size, in samples, permitted by the format. */
  86666. #define FLAC__MAX_BLOCK_SIZE (65535u)
  86667. /** The maximum block size, in samples, permitted by the FLAC subset for
  86668. * sample rates up to 48kHz. */
  86669. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  86670. /** The maximum number of channels permitted by the format. */
  86671. #define FLAC__MAX_CHANNELS (8u)
  86672. /** The minimum sample resolution permitted by the format. */
  86673. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  86674. /** The maximum sample resolution permitted by the format. */
  86675. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  86676. /** The maximum sample resolution permitted by libFLAC.
  86677. *
  86678. * \warning
  86679. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  86680. * the reference encoder/decoder is currently limited to 24 bits because
  86681. * of prevalent 32-bit math, so make sure and use this value when
  86682. * appropriate.
  86683. */
  86684. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  86685. /** The maximum sample rate permitted by the format. The value is
  86686. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  86687. * as to why.
  86688. */
  86689. #define FLAC__MAX_SAMPLE_RATE (655350u)
  86690. /** The maximum LPC order permitted by the format. */
  86691. #define FLAC__MAX_LPC_ORDER (32u)
  86692. /** The maximum LPC order permitted by the FLAC subset for sample rates
  86693. * up to 48kHz. */
  86694. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  86695. /** The minimum quantized linear predictor coefficient precision
  86696. * permitted by the format.
  86697. */
  86698. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  86699. /** The maximum quantized linear predictor coefficient precision
  86700. * permitted by the format.
  86701. */
  86702. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  86703. /** The maximum order of the fixed predictors permitted by the format. */
  86704. #define FLAC__MAX_FIXED_ORDER (4u)
  86705. /** The maximum Rice partition order permitted by the format. */
  86706. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  86707. /** The maximum Rice partition order permitted by the FLAC Subset. */
  86708. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  86709. /** The version string of the release, stamped onto the libraries and binaries.
  86710. *
  86711. * \note
  86712. * This does not correspond to the shared library version number, which
  86713. * is used to determine binary compatibility.
  86714. */
  86715. extern FLAC_API const char *FLAC__VERSION_STRING;
  86716. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  86717. * This is a NUL-terminated ASCII string; when inserted into the
  86718. * VORBIS_COMMENT the trailing null is stripped.
  86719. */
  86720. extern FLAC_API const char *FLAC__VENDOR_STRING;
  86721. /** The byte string representation of the beginning of a FLAC stream. */
  86722. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  86723. /** The 32-bit integer big-endian representation of the beginning of
  86724. * a FLAC stream.
  86725. */
  86726. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  86727. /** The length of the FLAC signature in bits. */
  86728. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  86729. /** The length of the FLAC signature in bytes. */
  86730. #define FLAC__STREAM_SYNC_LENGTH (4u)
  86731. /*****************************************************************************
  86732. *
  86733. * Subframe structures
  86734. *
  86735. *****************************************************************************/
  86736. /*****************************************************************************/
  86737. /** An enumeration of the available entropy coding methods. */
  86738. typedef enum {
  86739. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  86740. /**< Residual is coded by partitioning into contexts, each with it's own
  86741. * 4-bit Rice parameter. */
  86742. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  86743. /**< Residual is coded by partitioning into contexts, each with it's own
  86744. * 5-bit Rice parameter. */
  86745. } FLAC__EntropyCodingMethodType;
  86746. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  86747. *
  86748. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  86749. * give the string equivalent. The contents should not be modified.
  86750. */
  86751. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  86752. /** Contents of a Rice partitioned residual
  86753. */
  86754. typedef struct {
  86755. unsigned *parameters;
  86756. /**< The Rice parameters for each context. */
  86757. unsigned *raw_bits;
  86758. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  86759. * partitions and zero for unescaped partitions.
  86760. */
  86761. unsigned capacity_by_order;
  86762. /**< The capacity of the \a parameters and \a raw_bits arrays
  86763. * specified as an order, i.e. the number of array elements
  86764. * allocated is 2 ^ \a capacity_by_order.
  86765. */
  86766. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  86767. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  86768. */
  86769. typedef struct {
  86770. unsigned order;
  86771. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  86772. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  86773. /**< The context's Rice parameters and/or raw bits. */
  86774. } FLAC__EntropyCodingMethod_PartitionedRice;
  86775. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  86776. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  86777. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  86778. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  86779. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  86780. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  86781. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  86782. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  86783. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  86784. */
  86785. typedef struct {
  86786. FLAC__EntropyCodingMethodType type;
  86787. union {
  86788. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  86789. } data;
  86790. } FLAC__EntropyCodingMethod;
  86791. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  86792. /*****************************************************************************/
  86793. /** An enumeration of the available subframe types. */
  86794. typedef enum {
  86795. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  86796. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  86797. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  86798. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  86799. } FLAC__SubframeType;
  86800. /** Maps a FLAC__SubframeType to a C string.
  86801. *
  86802. * Using a FLAC__SubframeType as the index to this array will
  86803. * give the string equivalent. The contents should not be modified.
  86804. */
  86805. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  86806. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  86807. */
  86808. typedef struct {
  86809. FLAC__int32 value; /**< The constant signal value. */
  86810. } FLAC__Subframe_Constant;
  86811. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  86812. */
  86813. typedef struct {
  86814. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  86815. } FLAC__Subframe_Verbatim;
  86816. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  86817. */
  86818. typedef struct {
  86819. FLAC__EntropyCodingMethod entropy_coding_method;
  86820. /**< The residual coding method. */
  86821. unsigned order;
  86822. /**< The polynomial order. */
  86823. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  86824. /**< Warmup samples to prime the predictor, length == order. */
  86825. const FLAC__int32 *residual;
  86826. /**< The residual signal, length == (blocksize minus order) samples. */
  86827. } FLAC__Subframe_Fixed;
  86828. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  86829. */
  86830. typedef struct {
  86831. FLAC__EntropyCodingMethod entropy_coding_method;
  86832. /**< The residual coding method. */
  86833. unsigned order;
  86834. /**< The FIR order. */
  86835. unsigned qlp_coeff_precision;
  86836. /**< Quantized FIR filter coefficient precision in bits. */
  86837. int quantization_level;
  86838. /**< The qlp coeff shift needed. */
  86839. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  86840. /**< FIR filter coefficients. */
  86841. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  86842. /**< Warmup samples to prime the predictor, length == order. */
  86843. const FLAC__int32 *residual;
  86844. /**< The residual signal, length == (blocksize minus order) samples. */
  86845. } FLAC__Subframe_LPC;
  86846. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  86847. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  86848. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  86849. */
  86850. typedef struct {
  86851. FLAC__SubframeType type;
  86852. union {
  86853. FLAC__Subframe_Constant constant;
  86854. FLAC__Subframe_Fixed fixed;
  86855. FLAC__Subframe_LPC lpc;
  86856. FLAC__Subframe_Verbatim verbatim;
  86857. } data;
  86858. unsigned wasted_bits;
  86859. } FLAC__Subframe;
  86860. /** == 1 (bit)
  86861. *
  86862. * This used to be a zero-padding bit (hence the name
  86863. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  86864. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  86865. * to mean something else.
  86866. */
  86867. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  86868. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  86869. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  86870. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  86871. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  86872. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  86873. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  86874. /*****************************************************************************/
  86875. /*****************************************************************************
  86876. *
  86877. * Frame structures
  86878. *
  86879. *****************************************************************************/
  86880. /** An enumeration of the available channel assignments. */
  86881. typedef enum {
  86882. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  86883. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  86884. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  86885. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  86886. } FLAC__ChannelAssignment;
  86887. /** Maps a FLAC__ChannelAssignment to a C string.
  86888. *
  86889. * Using a FLAC__ChannelAssignment as the index to this array will
  86890. * give the string equivalent. The contents should not be modified.
  86891. */
  86892. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  86893. /** An enumeration of the possible frame numbering methods. */
  86894. typedef enum {
  86895. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  86896. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  86897. } FLAC__FrameNumberType;
  86898. /** Maps a FLAC__FrameNumberType to a C string.
  86899. *
  86900. * Using a FLAC__FrameNumberType as the index to this array will
  86901. * give the string equivalent. The contents should not be modified.
  86902. */
  86903. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  86904. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  86905. */
  86906. typedef struct {
  86907. unsigned blocksize;
  86908. /**< The number of samples per subframe. */
  86909. unsigned sample_rate;
  86910. /**< The sample rate in Hz. */
  86911. unsigned channels;
  86912. /**< The number of channels (== number of subframes). */
  86913. FLAC__ChannelAssignment channel_assignment;
  86914. /**< The channel assignment for the frame. */
  86915. unsigned bits_per_sample;
  86916. /**< The sample resolution. */
  86917. FLAC__FrameNumberType number_type;
  86918. /**< The numbering scheme used for the frame. As a convenience, the
  86919. * decoder will always convert a frame number to a sample number because
  86920. * the rules are complex. */
  86921. union {
  86922. FLAC__uint32 frame_number;
  86923. FLAC__uint64 sample_number;
  86924. } number;
  86925. /**< The frame number or sample number of first sample in frame;
  86926. * use the \a number_type value to determine which to use. */
  86927. FLAC__uint8 crc;
  86928. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  86929. * of the raw frame header bytes, meaning everything before the CRC byte
  86930. * including the sync code.
  86931. */
  86932. } FLAC__FrameHeader;
  86933. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  86934. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  86935. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  86936. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  86937. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  86938. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  86939. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  86940. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  86941. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  86942. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  86943. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  86944. */
  86945. typedef struct {
  86946. FLAC__uint16 crc;
  86947. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  86948. * 0) of the bytes before the crc, back to and including the frame header
  86949. * sync code.
  86950. */
  86951. } FLAC__FrameFooter;
  86952. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  86953. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  86954. */
  86955. typedef struct {
  86956. FLAC__FrameHeader header;
  86957. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  86958. FLAC__FrameFooter footer;
  86959. } FLAC__Frame;
  86960. /*****************************************************************************/
  86961. /*****************************************************************************
  86962. *
  86963. * Meta-data structures
  86964. *
  86965. *****************************************************************************/
  86966. /** An enumeration of the available metadata block types. */
  86967. typedef enum {
  86968. FLAC__METADATA_TYPE_STREAMINFO = 0,
  86969. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  86970. FLAC__METADATA_TYPE_PADDING = 1,
  86971. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  86972. FLAC__METADATA_TYPE_APPLICATION = 2,
  86973. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  86974. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  86975. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  86976. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  86977. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  86978. FLAC__METADATA_TYPE_CUESHEET = 5,
  86979. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  86980. FLAC__METADATA_TYPE_PICTURE = 6,
  86981. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  86982. FLAC__METADATA_TYPE_UNDEFINED = 7
  86983. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  86984. } FLAC__MetadataType;
  86985. /** Maps a FLAC__MetadataType to a C string.
  86986. *
  86987. * Using a FLAC__MetadataType as the index to this array will
  86988. * give the string equivalent. The contents should not be modified.
  86989. */
  86990. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  86991. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  86992. */
  86993. typedef struct {
  86994. unsigned min_blocksize, max_blocksize;
  86995. unsigned min_framesize, max_framesize;
  86996. unsigned sample_rate;
  86997. unsigned channels;
  86998. unsigned bits_per_sample;
  86999. FLAC__uint64 total_samples;
  87000. FLAC__byte md5sum[16];
  87001. } FLAC__StreamMetadata_StreamInfo;
  87002. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  87003. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  87004. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  87005. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  87006. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  87007. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  87008. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  87009. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  87010. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  87011. /** The total stream length of the STREAMINFO block in bytes. */
  87012. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  87013. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  87014. */
  87015. typedef struct {
  87016. int dummy;
  87017. /**< Conceptually this is an empty struct since we don't store the
  87018. * padding bytes. Empty structs are not allowed by some C compilers,
  87019. * hence the dummy.
  87020. */
  87021. } FLAC__StreamMetadata_Padding;
  87022. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  87023. */
  87024. typedef struct {
  87025. FLAC__byte id[4];
  87026. FLAC__byte *data;
  87027. } FLAC__StreamMetadata_Application;
  87028. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  87029. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  87030. */
  87031. typedef struct {
  87032. FLAC__uint64 sample_number;
  87033. /**< The sample number of the target frame. */
  87034. FLAC__uint64 stream_offset;
  87035. /**< The offset, in bytes, of the target frame with respect to
  87036. * beginning of the first frame. */
  87037. unsigned frame_samples;
  87038. /**< The number of samples in the target frame. */
  87039. } FLAC__StreamMetadata_SeekPoint;
  87040. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  87041. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  87042. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  87043. /** The total stream length of a seek point in bytes. */
  87044. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  87045. /** The value used in the \a sample_number field of
  87046. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  87047. * point (== 0xffffffffffffffff).
  87048. */
  87049. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  87050. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  87051. *
  87052. * \note From the format specification:
  87053. * - The seek points must be sorted by ascending sample number.
  87054. * - Each seek point's sample number must be the first sample of the
  87055. * target frame.
  87056. * - Each seek point's sample number must be unique within the table.
  87057. * - Existence of a SEEKTABLE block implies a correct setting of
  87058. * total_samples in the stream_info block.
  87059. * - Behavior is undefined when more than one SEEKTABLE block is
  87060. * present in a stream.
  87061. */
  87062. typedef struct {
  87063. unsigned num_points;
  87064. FLAC__StreamMetadata_SeekPoint *points;
  87065. } FLAC__StreamMetadata_SeekTable;
  87066. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  87067. *
  87068. * For convenience, the APIs maintain a trailing NUL character at the end of
  87069. * \a entry which is not counted toward \a length, i.e.
  87070. * \code strlen(entry) == length \endcode
  87071. */
  87072. typedef struct {
  87073. FLAC__uint32 length;
  87074. FLAC__byte *entry;
  87075. } FLAC__StreamMetadata_VorbisComment_Entry;
  87076. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  87077. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  87078. */
  87079. typedef struct {
  87080. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  87081. FLAC__uint32 num_comments;
  87082. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  87083. } FLAC__StreamMetadata_VorbisComment;
  87084. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  87085. /** FLAC CUESHEET track index structure. (See the
  87086. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  87087. * the full description of each field.)
  87088. */
  87089. typedef struct {
  87090. FLAC__uint64 offset;
  87091. /**< Offset in samples, relative to the track offset, of the index
  87092. * point.
  87093. */
  87094. FLAC__byte number;
  87095. /**< The index point number. */
  87096. } FLAC__StreamMetadata_CueSheet_Index;
  87097. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  87098. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  87099. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  87100. /** FLAC CUESHEET track structure. (See the
  87101. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  87102. * the full description of each field.)
  87103. */
  87104. typedef struct {
  87105. FLAC__uint64 offset;
  87106. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  87107. FLAC__byte number;
  87108. /**< The track number. */
  87109. char isrc[13];
  87110. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  87111. unsigned type:1;
  87112. /**< The track type: 0 for audio, 1 for non-audio. */
  87113. unsigned pre_emphasis:1;
  87114. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  87115. FLAC__byte num_indices;
  87116. /**< The number of track index points. */
  87117. FLAC__StreamMetadata_CueSheet_Index *indices;
  87118. /**< NULL if num_indices == 0, else pointer to array of index points. */
  87119. } FLAC__StreamMetadata_CueSheet_Track;
  87120. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  87121. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  87122. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  87123. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  87124. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  87125. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  87126. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  87127. /** FLAC CUESHEET structure. (See the
  87128. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  87129. * for the full description of each field.)
  87130. */
  87131. typedef struct {
  87132. char media_catalog_number[129];
  87133. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  87134. * general, the media catalog number may be 0 to 128 bytes long; any
  87135. * unused characters should be right-padded with NUL characters.
  87136. */
  87137. FLAC__uint64 lead_in;
  87138. /**< The number of lead-in samples. */
  87139. FLAC__bool is_cd;
  87140. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  87141. unsigned num_tracks;
  87142. /**< The number of tracks. */
  87143. FLAC__StreamMetadata_CueSheet_Track *tracks;
  87144. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  87145. } FLAC__StreamMetadata_CueSheet;
  87146. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  87147. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  87148. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  87149. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  87150. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  87151. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  87152. typedef enum {
  87153. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  87154. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  87155. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  87156. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  87157. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  87158. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  87159. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  87160. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  87161. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  87162. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  87163. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  87164. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  87165. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  87166. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  87167. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  87168. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  87169. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  87170. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  87171. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  87172. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  87173. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  87174. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  87175. } FLAC__StreamMetadata_Picture_Type;
  87176. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  87177. *
  87178. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  87179. * will give the string equivalent. The contents should not be
  87180. * modified.
  87181. */
  87182. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  87183. /** FLAC PICTURE structure. (See the
  87184. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  87185. * for the full description of each field.)
  87186. */
  87187. typedef struct {
  87188. FLAC__StreamMetadata_Picture_Type type;
  87189. /**< The kind of picture stored. */
  87190. char *mime_type;
  87191. /**< Picture data's MIME type, in ASCII printable characters
  87192. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  87193. * use picture data of MIME type \c image/jpeg or \c image/png. A
  87194. * MIME type of '-->' is also allowed, in which case the picture
  87195. * data should be a complete URL. In file storage, the MIME type is
  87196. * stored as a 32-bit length followed by the ASCII string with no NUL
  87197. * terminator, but is converted to a plain C string in this structure
  87198. * for convenience.
  87199. */
  87200. FLAC__byte *description;
  87201. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  87202. * the description is stored as a 32-bit length followed by the UTF-8
  87203. * string with no NUL terminator, but is converted to a plain C string
  87204. * in this structure for convenience.
  87205. */
  87206. FLAC__uint32 width;
  87207. /**< Picture's width in pixels. */
  87208. FLAC__uint32 height;
  87209. /**< Picture's height in pixels. */
  87210. FLAC__uint32 depth;
  87211. /**< Picture's color depth in bits-per-pixel. */
  87212. FLAC__uint32 colors;
  87213. /**< For indexed palettes (like GIF), picture's number of colors (the
  87214. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  87215. */
  87216. FLAC__uint32 data_length;
  87217. /**< Length of binary picture data in bytes. */
  87218. FLAC__byte *data;
  87219. /**< Binary picture data. */
  87220. } FLAC__StreamMetadata_Picture;
  87221. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  87222. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  87223. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  87224. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  87225. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  87226. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  87227. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  87228. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  87229. /** Structure that is used when a metadata block of unknown type is loaded.
  87230. * The contents are opaque. The structure is used only internally to
  87231. * correctly handle unknown metadata.
  87232. */
  87233. typedef struct {
  87234. FLAC__byte *data;
  87235. } FLAC__StreamMetadata_Unknown;
  87236. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  87237. */
  87238. typedef struct {
  87239. FLAC__MetadataType type;
  87240. /**< The type of the metadata block; used determine which member of the
  87241. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  87242. * then \a data.unknown must be used. */
  87243. FLAC__bool is_last;
  87244. /**< \c true if this metadata block is the last, else \a false */
  87245. unsigned length;
  87246. /**< Length, in bytes, of the block data as it appears in the stream. */
  87247. union {
  87248. FLAC__StreamMetadata_StreamInfo stream_info;
  87249. FLAC__StreamMetadata_Padding padding;
  87250. FLAC__StreamMetadata_Application application;
  87251. FLAC__StreamMetadata_SeekTable seek_table;
  87252. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  87253. FLAC__StreamMetadata_CueSheet cue_sheet;
  87254. FLAC__StreamMetadata_Picture picture;
  87255. FLAC__StreamMetadata_Unknown unknown;
  87256. } data;
  87257. /**< Polymorphic block data; use the \a type value to determine which
  87258. * to use. */
  87259. } FLAC__StreamMetadata;
  87260. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  87261. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  87262. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  87263. /** The total stream length of a metadata block header in bytes. */
  87264. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  87265. /*****************************************************************************/
  87266. /*****************************************************************************
  87267. *
  87268. * Utility functions
  87269. *
  87270. *****************************************************************************/
  87271. /** Tests that a sample rate is valid for FLAC.
  87272. *
  87273. * \param sample_rate The sample rate to test for compliance.
  87274. * \retval FLAC__bool
  87275. * \c true if the given sample rate conforms to the specification, else
  87276. * \c false.
  87277. */
  87278. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  87279. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  87280. * for valid sample rates are slightly more complex since the rate has to
  87281. * be expressible completely in the frame header.
  87282. *
  87283. * \param sample_rate The sample rate to test for compliance.
  87284. * \retval FLAC__bool
  87285. * \c true if the given sample rate conforms to the specification for the
  87286. * subset, else \c false.
  87287. */
  87288. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  87289. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  87290. * comment specification.
  87291. *
  87292. * Vorbis comment names must be composed only of characters from
  87293. * [0x20-0x3C,0x3E-0x7D].
  87294. *
  87295. * \param name A NUL-terminated string to be checked.
  87296. * \assert
  87297. * \code name != NULL \endcode
  87298. * \retval FLAC__bool
  87299. * \c false if entry name is illegal, else \c true.
  87300. */
  87301. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  87302. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  87303. * comment specification.
  87304. *
  87305. * Vorbis comment values must be valid UTF-8 sequences.
  87306. *
  87307. * \param value A string to be checked.
  87308. * \param length A the length of \a value in bytes. May be
  87309. * \c (unsigned)(-1) to indicate that \a value is a plain
  87310. * UTF-8 NUL-terminated string.
  87311. * \assert
  87312. * \code value != NULL \endcode
  87313. * \retval FLAC__bool
  87314. * \c false if entry name is illegal, else \c true.
  87315. */
  87316. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  87317. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  87318. * comment specification.
  87319. *
  87320. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  87321. * 'value' must be legal according to
  87322. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  87323. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  87324. *
  87325. * \param entry An entry to be checked.
  87326. * \param length The length of \a entry in bytes.
  87327. * \assert
  87328. * \code value != 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_is_legal(const FLAC__byte *entry, unsigned length);
  87333. /** Check a seek table to see if it conforms to the FLAC specification.
  87334. * See the format specification for limits on the contents of the
  87335. * seek table.
  87336. *
  87337. * \param seek_table A pointer to a seek table to be checked.
  87338. * \assert
  87339. * \code seek_table != NULL \endcode
  87340. * \retval FLAC__bool
  87341. * \c false if seek table is illegal, else \c true.
  87342. */
  87343. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  87344. /** Sort a seek table's seek points according to the format specification.
  87345. * This includes a "unique-ification" step to remove duplicates, i.e.
  87346. * seek points with identical \a sample_number values. Duplicate seek
  87347. * points are converted into placeholder points and sorted to the end of
  87348. * the table.
  87349. *
  87350. * \param seek_table A pointer to a seek table to be sorted.
  87351. * \assert
  87352. * \code seek_table != NULL \endcode
  87353. * \retval unsigned
  87354. * The number of duplicate seek points converted into placeholders.
  87355. */
  87356. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  87357. /** Check a cue sheet to see if it conforms to the FLAC specification.
  87358. * See the format specification for limits on the contents of the
  87359. * cue sheet.
  87360. *
  87361. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  87362. * \param check_cd_da_subset If \c true, check CUESHEET against more
  87363. * stringent requirements for a CD-DA (audio) disc.
  87364. * \param violation Address of a pointer to a string. If there is a
  87365. * violation, a pointer to a string explanation of the
  87366. * violation will be returned here. \a violation may be
  87367. * \c NULL if you don't need the returned string. Do not
  87368. * free the returned string; it will always point to static
  87369. * data.
  87370. * \assert
  87371. * \code cue_sheet != NULL \endcode
  87372. * \retval FLAC__bool
  87373. * \c false if cue sheet is illegal, else \c true.
  87374. */
  87375. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  87376. /** Check picture data to see if it conforms to the FLAC specification.
  87377. * See the format specification for limits on the contents of the
  87378. * PICTURE block.
  87379. *
  87380. * \param picture A pointer to existing picture data to be checked.
  87381. * \param violation Address of a pointer to a string. If there is a
  87382. * violation, a pointer to a string explanation of the
  87383. * violation will be returned here. \a violation may be
  87384. * \c NULL if you don't need the returned string. Do not
  87385. * free the returned string; it will always point to static
  87386. * data.
  87387. * \assert
  87388. * \code picture != NULL \endcode
  87389. * \retval FLAC__bool
  87390. * \c false if picture data is illegal, else \c true.
  87391. */
  87392. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  87393. /* \} */
  87394. #ifdef __cplusplus
  87395. }
  87396. #endif
  87397. #endif
  87398. /*** End of inlined file: format.h ***/
  87399. /*** Start of inlined file: metadata.h ***/
  87400. #ifndef FLAC__METADATA_H
  87401. #define FLAC__METADATA_H
  87402. #include <sys/types.h> /* for off_t */
  87403. /* --------------------------------------------------------------------
  87404. (For an example of how all these routines are used, see the source
  87405. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  87406. metaflac in src/metaflac/)
  87407. ------------------------------------------------------------------*/
  87408. /** \file include/FLAC/metadata.h
  87409. *
  87410. * \brief
  87411. * This module provides functions for creating and manipulating FLAC
  87412. * metadata blocks in memory, and three progressively more powerful
  87413. * interfaces for traversing and editing metadata in FLAC files.
  87414. *
  87415. * See the detailed documentation for each interface in the
  87416. * \link flac_metadata metadata \endlink module.
  87417. */
  87418. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  87419. * \ingroup flac
  87420. *
  87421. * \brief
  87422. * This module provides functions for creating and manipulating FLAC
  87423. * metadata blocks in memory, and three progressively more powerful
  87424. * interfaces for traversing and editing metadata in native FLAC files.
  87425. * Note that currently only the Chain interface (level 2) supports Ogg
  87426. * FLAC files, and it is read-only i.e. no writing back changed
  87427. * metadata to file.
  87428. *
  87429. * There are three metadata interfaces of increasing complexity:
  87430. *
  87431. * Level 0:
  87432. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  87433. * PICTURE blocks.
  87434. *
  87435. * Level 1:
  87436. * Read-write access to all metadata blocks. This level is write-
  87437. * efficient in most cases (more on this below), and uses less memory
  87438. * than level 2.
  87439. *
  87440. * Level 2:
  87441. * Read-write access to all metadata blocks. This level is write-
  87442. * efficient in all cases, but uses more memory since all metadata for
  87443. * the whole file is read into memory and manipulated before writing
  87444. * out again.
  87445. *
  87446. * What do we mean by efficient? Since FLAC metadata appears at the
  87447. * beginning of the file, when writing metadata back to a FLAC file
  87448. * it is possible to grow or shrink the metadata such that the entire
  87449. * file must be rewritten. However, if the size remains the same during
  87450. * changes or PADDING blocks are utilized, only the metadata needs to be
  87451. * overwritten, which is much faster.
  87452. *
  87453. * Efficient means the whole file is rewritten at most one time, and only
  87454. * when necessary. Level 1 is not efficient only in the case that you
  87455. * cause more than one metadata block to grow or shrink beyond what can
  87456. * be accomodated by padding. In this case you should probably use level
  87457. * 2, which allows you to edit all the metadata for a file in memory and
  87458. * write it out all at once.
  87459. *
  87460. * All levels know how to skip over and not disturb an ID3v2 tag at the
  87461. * front of the file.
  87462. *
  87463. * All levels access files via their filenames. In addition, level 2
  87464. * has additional alternative read and write functions that take an I/O
  87465. * handle and callbacks, for situations where access by filename is not
  87466. * possible.
  87467. *
  87468. * In addition to the three interfaces, this module defines functions for
  87469. * creating and manipulating various metadata objects in memory. As we see
  87470. * from the Format module, FLAC metadata blocks in memory are very primitive
  87471. * structures for storing information in an efficient way. Reading
  87472. * information from the structures is easy but creating or modifying them
  87473. * directly is more complex. The metadata object routines here facilitate
  87474. * this by taking care of the consistency and memory management drudgery.
  87475. *
  87476. * Unless you will be using the level 1 or 2 interfaces to modify existing
  87477. * metadata however, you will not probably not need these.
  87478. *
  87479. * From a dependency standpoint, none of the encoders or decoders require
  87480. * the metadata module. This is so that embedded users can strip out the
  87481. * metadata module from libFLAC to reduce the size and complexity.
  87482. */
  87483. #ifdef __cplusplus
  87484. extern "C" {
  87485. #endif
  87486. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  87487. * \ingroup flac_metadata
  87488. *
  87489. * \brief
  87490. * The level 0 interface consists of individual routines to read the
  87491. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  87492. * only a filename.
  87493. *
  87494. * They try to skip any ID3v2 tag at the head of the file.
  87495. *
  87496. * \{
  87497. */
  87498. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  87499. * will try to skip any ID3v2 tag at the head of the file.
  87500. *
  87501. * \param filename The path to the FLAC file to read.
  87502. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  87503. * FLAC__StreamMetadata is a simple structure with no
  87504. * memory allocation involved, you pass the address of
  87505. * an existing structure. It need not be initialized.
  87506. * \assert
  87507. * \code filename != NULL \endcode
  87508. * \code streaminfo != NULL \endcode
  87509. * \retval FLAC__bool
  87510. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  87511. * \c false if there was a memory allocation error, a file decoder error,
  87512. * or the file contained no STREAMINFO block. (A memory allocation error
  87513. * is possible because this function must set up a file decoder.)
  87514. */
  87515. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  87516. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  87517. * function will try to skip any ID3v2 tag at the head of the file.
  87518. *
  87519. * \param filename The path to the FLAC file to read.
  87520. * \param tags The address where the returned pointer will be
  87521. * stored. The \a tags object must be deleted by
  87522. * the caller using FLAC__metadata_object_delete().
  87523. * \assert
  87524. * \code filename != NULL \endcode
  87525. * \code tags != NULL \endcode
  87526. * \retval FLAC__bool
  87527. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  87528. * and \a *tags will be set to the address of the metadata structure.
  87529. * Returns \c false if there was a memory allocation error, a file
  87530. * decoder error, or the file contained no VORBIS_COMMENT block, and
  87531. * \a *tags will be set to \c NULL.
  87532. */
  87533. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  87534. /** Read the CUESHEET metadata block of the given FLAC file. This
  87535. * function will try to skip any ID3v2 tag at the head of the file.
  87536. *
  87537. * \param filename The path to the FLAC file to read.
  87538. * \param cuesheet The address where the returned pointer will be
  87539. * stored. The \a cuesheet object must be deleted by
  87540. * the caller using FLAC__metadata_object_delete().
  87541. * \assert
  87542. * \code filename != NULL \endcode
  87543. * \code cuesheet != NULL \endcode
  87544. * \retval FLAC__bool
  87545. * \c true if a valid CUESHEET block was read from \a filename,
  87546. * and \a *cuesheet will be set to the address of the metadata
  87547. * structure. Returns \c false if there was a memory allocation
  87548. * error, a file decoder error, or the file contained no CUESHEET
  87549. * block, and \a *cuesheet will be set to \c NULL.
  87550. */
  87551. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  87552. /** Read a PICTURE metadata block of the given FLAC file. This
  87553. * function will try to skip any ID3v2 tag at the head of the file.
  87554. * Since there can be more than one PICTURE block in a file, this
  87555. * function takes a number of parameters that act as constraints to
  87556. * the search. The PICTURE block with the largest area matching all
  87557. * the constraints will be returned, or \a *picture will be set to
  87558. * \c NULL if there was no such block.
  87559. *
  87560. * \param filename The path to the FLAC file to read.
  87561. * \param picture The address where the returned pointer will be
  87562. * stored. The \a picture object must be deleted by
  87563. * the caller using FLAC__metadata_object_delete().
  87564. * \param type The desired picture type. Use \c -1 to mean
  87565. * "any type".
  87566. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  87567. * string will be matched exactly. Use \c NULL to
  87568. * mean "any MIME type".
  87569. * \param description The desired description. The string will be
  87570. * matched exactly. Use \c NULL to mean "any
  87571. * description".
  87572. * \param max_width The maximum width in pixels desired. Use
  87573. * \c (unsigned)(-1) to mean "any width".
  87574. * \param max_height The maximum height in pixels desired. Use
  87575. * \c (unsigned)(-1) to mean "any height".
  87576. * \param max_depth The maximum color depth in bits-per-pixel desired.
  87577. * Use \c (unsigned)(-1) to mean "any depth".
  87578. * \param max_colors The maximum number of colors desired. Use
  87579. * \c (unsigned)(-1) to mean "any number of colors".
  87580. * \assert
  87581. * \code filename != NULL \endcode
  87582. * \code picture != NULL \endcode
  87583. * \retval FLAC__bool
  87584. * \c true if a valid PICTURE block was read from \a filename,
  87585. * and \a *picture will be set to the address of the metadata
  87586. * structure. Returns \c false if there was a memory allocation
  87587. * error, a file decoder error, or the file contained no PICTURE
  87588. * block, and \a *picture will be set to \c NULL.
  87589. */
  87590. 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);
  87591. /* \} */
  87592. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  87593. * \ingroup flac_metadata
  87594. *
  87595. * \brief
  87596. * The level 1 interface provides read-write access to FLAC file metadata and
  87597. * operates directly on the FLAC file.
  87598. *
  87599. * The general usage of this interface is:
  87600. *
  87601. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  87602. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  87603. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  87604. * see if the file is writable, or only read access is allowed.
  87605. * - Use FLAC__metadata_simple_iterator_next() and
  87606. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  87607. * This is does not read the actual blocks themselves.
  87608. * FLAC__metadata_simple_iterator_next() is relatively fast.
  87609. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  87610. * forward from the front of the file.
  87611. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  87612. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  87613. * the current iterator position. The returned object is yours to modify
  87614. * and free.
  87615. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  87616. * back. You must have write permission to the original file. Make sure to
  87617. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  87618. * below.
  87619. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  87620. * Use the object creation functions from
  87621. * \link flac_metadata_object here \endlink to generate new objects.
  87622. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  87623. * currently referred to by the iterator, or replace it with padding.
  87624. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  87625. * finished.
  87626. *
  87627. * \note
  87628. * The FLAC file remains open the whole time between
  87629. * FLAC__metadata_simple_iterator_init() and
  87630. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  87631. * the file during this time.
  87632. *
  87633. * \note
  87634. * Do not modify the \a is_last, \a length, or \a type fields of returned
  87635. * FLAC__StreamMetadata objects. These are managed automatically.
  87636. *
  87637. * \note
  87638. * If any of the modification functions
  87639. * (FLAC__metadata_simple_iterator_set_block(),
  87640. * FLAC__metadata_simple_iterator_delete_block(),
  87641. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  87642. * you should delete the iterator as it may no longer be valid.
  87643. *
  87644. * \{
  87645. */
  87646. struct FLAC__Metadata_SimpleIterator;
  87647. /** The opaque structure definition for the level 1 iterator type.
  87648. * See the
  87649. * \link flac_metadata_level1 metadata level 1 module \endlink
  87650. * for a detailed description.
  87651. */
  87652. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  87653. /** Status type for FLAC__Metadata_SimpleIterator.
  87654. *
  87655. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  87656. */
  87657. typedef enum {
  87658. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  87659. /**< The iterator is in the normal OK state */
  87660. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  87661. /**< The data passed into a function violated the function's usage criteria */
  87662. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  87663. /**< The iterator could not open the target file */
  87664. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  87665. /**< The iterator could not find the FLAC signature at the start of the file */
  87666. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  87667. /**< The iterator tried to write to a file that was not writable */
  87668. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  87669. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  87670. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  87671. /**< The iterator encountered an error while reading the FLAC file */
  87672. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  87673. /**< The iterator encountered an error while seeking in the FLAC file */
  87674. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  87675. /**< The iterator encountered an error while writing the FLAC file */
  87676. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  87677. /**< The iterator encountered an error renaming the FLAC file */
  87678. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  87679. /**< The iterator encountered an error removing the temporary file */
  87680. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  87681. /**< Memory allocation failed */
  87682. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  87683. /**< The caller violated an assertion or an unexpected error occurred */
  87684. } FLAC__Metadata_SimpleIteratorStatus;
  87685. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  87686. *
  87687. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  87688. * will give the string equivalent. The contents should not be modified.
  87689. */
  87690. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  87691. /** Create a new iterator instance.
  87692. *
  87693. * \retval FLAC__Metadata_SimpleIterator*
  87694. * \c NULL if there was an error allocating memory, else the new instance.
  87695. */
  87696. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  87697. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  87698. *
  87699. * \param iterator A pointer to an existing iterator.
  87700. * \assert
  87701. * \code iterator != NULL \endcode
  87702. */
  87703. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  87704. /** Get the current status of the iterator. Call this after a function
  87705. * returns \c false to get the reason for the error. Also resets the status
  87706. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  87707. *
  87708. * \param iterator A pointer to an existing iterator.
  87709. * \assert
  87710. * \code iterator != NULL \endcode
  87711. * \retval FLAC__Metadata_SimpleIteratorStatus
  87712. * The current status of the iterator.
  87713. */
  87714. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  87715. /** Initialize the iterator to point to the first metadata block in the
  87716. * given FLAC file.
  87717. *
  87718. * \param iterator A pointer to an existing iterator.
  87719. * \param filename The path to the FLAC file.
  87720. * \param read_only If \c true, the FLAC file will be opened
  87721. * in read-only mode; if \c false, the FLAC
  87722. * file will be opened for edit even if no
  87723. * edits are performed.
  87724. * \param preserve_file_stats If \c true, the owner and modification
  87725. * time will be preserved even if the FLAC
  87726. * file is written to.
  87727. * \assert
  87728. * \code iterator != NULL \endcode
  87729. * \code filename != NULL \endcode
  87730. * \retval FLAC__bool
  87731. * \c false if a memory allocation error occurs, the file can't be
  87732. * opened, or another error occurs, else \c true.
  87733. */
  87734. 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);
  87735. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  87736. * FLAC__metadata_simple_iterator_set_block() and
  87737. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  87738. *
  87739. * \param iterator A pointer to an existing iterator.
  87740. * \assert
  87741. * \code iterator != NULL \endcode
  87742. * \retval FLAC__bool
  87743. * See above.
  87744. */
  87745. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  87746. /** Moves the iterator forward one metadata block, returning \c false if
  87747. * already at the end.
  87748. *
  87749. * \param iterator A pointer to an existing initialized iterator.
  87750. * \assert
  87751. * \code iterator != NULL \endcode
  87752. * \a iterator has been successfully initialized with
  87753. * FLAC__metadata_simple_iterator_init()
  87754. * \retval FLAC__bool
  87755. * \c false if already at the last metadata block of the chain, else
  87756. * \c true.
  87757. */
  87758. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  87759. /** Moves the iterator backward one metadata block, returning \c false if
  87760. * already at the beginning.
  87761. *
  87762. * \param iterator A pointer to an existing initialized iterator.
  87763. * \assert
  87764. * \code iterator != NULL \endcode
  87765. * \a iterator has been successfully initialized with
  87766. * FLAC__metadata_simple_iterator_init()
  87767. * \retval FLAC__bool
  87768. * \c false if already at the first metadata block of the chain, else
  87769. * \c true.
  87770. */
  87771. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  87772. /** Returns a flag telling if the current metadata block is the last.
  87773. *
  87774. * \param iterator A pointer to an existing initialized iterator.
  87775. * \assert
  87776. * \code iterator != NULL \endcode
  87777. * \a iterator has been successfully initialized with
  87778. * FLAC__metadata_simple_iterator_init()
  87779. * \retval FLAC__bool
  87780. * \c true if the current metadata block is the last in the file,
  87781. * else \c false.
  87782. */
  87783. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  87784. /** Get the offset of the metadata block at the current position. This
  87785. * avoids reading the actual block data which can save time for large
  87786. * blocks.
  87787. *
  87788. * \param iterator A pointer to an existing initialized iterator.
  87789. * \assert
  87790. * \code iterator != NULL \endcode
  87791. * \a iterator has been successfully initialized with
  87792. * FLAC__metadata_simple_iterator_init()
  87793. * \retval off_t
  87794. * The offset of the metadata block at the current iterator position.
  87795. * This is the byte offset relative to the beginning of the file of
  87796. * the current metadata block's header.
  87797. */
  87798. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  87799. /** Get the type of the metadata block at the current position. This
  87800. * avoids reading the actual block data which can save time for large
  87801. * blocks.
  87802. *
  87803. * \param iterator A pointer to an existing initialized iterator.
  87804. * \assert
  87805. * \code iterator != NULL \endcode
  87806. * \a iterator has been successfully initialized with
  87807. * FLAC__metadata_simple_iterator_init()
  87808. * \retval FLAC__MetadataType
  87809. * The type of the metadata block at the current iterator position.
  87810. */
  87811. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  87812. /** Get the length of the metadata block at the current position. This
  87813. * avoids reading the actual block data which can save time for large
  87814. * blocks.
  87815. *
  87816. * \param iterator A pointer to an existing initialized iterator.
  87817. * \assert
  87818. * \code iterator != NULL \endcode
  87819. * \a iterator has been successfully initialized with
  87820. * FLAC__metadata_simple_iterator_init()
  87821. * \retval unsigned
  87822. * The length of the metadata block at the current iterator position.
  87823. * The is same length as that in the
  87824. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  87825. * i.e. the length of the metadata body that follows the header.
  87826. */
  87827. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  87828. /** Get the application ID of the \c APPLICATION block at the current
  87829. * position. This avoids reading the actual block data which can save
  87830. * time for large blocks.
  87831. *
  87832. * \param iterator A pointer to an existing initialized iterator.
  87833. * \param id A pointer to a buffer of at least \c 4 bytes where
  87834. * the ID will be stored.
  87835. * \assert
  87836. * \code iterator != NULL \endcode
  87837. * \code id != NULL \endcode
  87838. * \a iterator has been successfully initialized with
  87839. * FLAC__metadata_simple_iterator_init()
  87840. * \retval FLAC__bool
  87841. * \c true if the ID was successfully read, else \c false, in which
  87842. * case you should check FLAC__metadata_simple_iterator_status() to
  87843. * find out why. If the status is
  87844. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  87845. * current metadata block is not an \c APPLICATION block. Otherwise
  87846. * if the status is
  87847. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  87848. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  87849. * occurred and the iterator can no longer be used.
  87850. */
  87851. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  87852. /** Get the metadata block at the current position. You can modify the
  87853. * block but must use FLAC__metadata_simple_iterator_set_block() to
  87854. * write it back to the FLAC file.
  87855. *
  87856. * You must call FLAC__metadata_object_delete() on the returned object
  87857. * when you are finished with it.
  87858. *
  87859. * \param iterator A pointer to an existing initialized iterator.
  87860. * \assert
  87861. * \code iterator != NULL \endcode
  87862. * \a iterator has been successfully initialized with
  87863. * FLAC__metadata_simple_iterator_init()
  87864. * \retval FLAC__StreamMetadata*
  87865. * The current metadata block, or \c NULL if there was a memory
  87866. * allocation error.
  87867. */
  87868. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  87869. /** Write a block back to the FLAC file. This function tries to be
  87870. * as efficient as possible; how the block is actually written is
  87871. * shown by the following:
  87872. *
  87873. * Existing block is a STREAMINFO block and the new block is a
  87874. * STREAMINFO block: the new block is written in place. Make sure
  87875. * you know what you're doing when changing the values of a
  87876. * STREAMINFO block.
  87877. *
  87878. * Existing block is a STREAMINFO block and the new block is a
  87879. * not a STREAMINFO block: this is an error since the first block
  87880. * must be a STREAMINFO block. Returns \c false without altering the
  87881. * file.
  87882. *
  87883. * Existing block is not a STREAMINFO block and the new block is a
  87884. * STREAMINFO block: this is an error since there may be only one
  87885. * STREAMINFO block. Returns \c false without altering the file.
  87886. *
  87887. * Existing block and new block are the same length: the existing
  87888. * block will be replaced by the new block, written in place.
  87889. *
  87890. * Existing block is longer than new block: if use_padding is \c true,
  87891. * the existing block will be overwritten in place with the new
  87892. * block followed by a PADDING block, if possible, to make the total
  87893. * size the same as the existing block. Remember that a padding
  87894. * block requires at least four bytes so if the difference in size
  87895. * between the new block and existing block is less than that, the
  87896. * entire file will have to be rewritten, using the new block's
  87897. * exact size. If use_padding is \c false, the entire file will be
  87898. * rewritten, replacing the existing block by the new block.
  87899. *
  87900. * Existing block is shorter than new block: if use_padding is \c true,
  87901. * the function will try and expand the new block into the following
  87902. * PADDING block, if it exists and doing so won't shrink the PADDING
  87903. * block to less than 4 bytes. If there is no following PADDING
  87904. * block, or it will shrink to less than 4 bytes, or use_padding is
  87905. * \c false, the entire file is rewritten, replacing the existing block
  87906. * with the new block. Note that in this case any following PADDING
  87907. * block is preserved as is.
  87908. *
  87909. * After writing the block, the iterator will remain in the same
  87910. * place, i.e. pointing to the new block.
  87911. *
  87912. * \param iterator A pointer to an existing initialized iterator.
  87913. * \param block The block to set.
  87914. * \param use_padding See above.
  87915. * \assert
  87916. * \code iterator != NULL \endcode
  87917. * \a iterator has been successfully initialized with
  87918. * FLAC__metadata_simple_iterator_init()
  87919. * \code block != NULL \endcode
  87920. * \retval FLAC__bool
  87921. * \c true if successful, else \c false.
  87922. */
  87923. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  87924. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  87925. * except that instead of writing over an existing block, it appends
  87926. * a block after the existing block. \a use_padding is again used to
  87927. * tell the function to try an expand into following padding in an
  87928. * attempt to avoid rewriting the entire file.
  87929. *
  87930. * This function will fail and return \c false if given a STREAMINFO
  87931. * block.
  87932. *
  87933. * After writing the block, the iterator will be pointing to the
  87934. * new block.
  87935. *
  87936. * \param iterator A pointer to an existing initialized iterator.
  87937. * \param block The block to set.
  87938. * \param use_padding See above.
  87939. * \assert
  87940. * \code iterator != NULL \endcode
  87941. * \a iterator has been successfully initialized with
  87942. * FLAC__metadata_simple_iterator_init()
  87943. * \code block != NULL \endcode
  87944. * \retval FLAC__bool
  87945. * \c true if successful, else \c false.
  87946. */
  87947. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  87948. /** Deletes the block at the current position. This will cause the
  87949. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  87950. * in which case the block will be replaced by an equal-sized PADDING
  87951. * block. The iterator will be left pointing to the block before the
  87952. * one just deleted.
  87953. *
  87954. * You may not delete the STREAMINFO block.
  87955. *
  87956. * \param iterator A pointer to an existing initialized iterator.
  87957. * \param use_padding See above.
  87958. * \assert
  87959. * \code iterator != NULL \endcode
  87960. * \a iterator has been successfully initialized with
  87961. * FLAC__metadata_simple_iterator_init()
  87962. * \retval FLAC__bool
  87963. * \c true if successful, else \c false.
  87964. */
  87965. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  87966. /* \} */
  87967. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  87968. * \ingroup flac_metadata
  87969. *
  87970. * \brief
  87971. * The level 2 interface provides read-write access to FLAC file metadata;
  87972. * all metadata is read into memory, operated on in memory, and then written
  87973. * to file, which is more efficient than level 1 when editing multiple blocks.
  87974. *
  87975. * Currently Ogg FLAC is supported for read only, via
  87976. * FLAC__metadata_chain_read_ogg() but a subsequent
  87977. * FLAC__metadata_chain_write() will fail.
  87978. *
  87979. * The general usage of this interface is:
  87980. *
  87981. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  87982. * linked list of FLAC metadata blocks.
  87983. * - Read all metadata into the the chain from a FLAC file using
  87984. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  87985. * check the status.
  87986. * - Optionally, consolidate the padding using
  87987. * FLAC__metadata_chain_merge_padding() or
  87988. * FLAC__metadata_chain_sort_padding().
  87989. * - Create a new iterator using FLAC__metadata_iterator_new()
  87990. * - Initialize the iterator to point to the first element in the chain
  87991. * using FLAC__metadata_iterator_init()
  87992. * - Traverse the chain using FLAC__metadata_iterator_next and
  87993. * FLAC__metadata_iterator_prev().
  87994. * - Get a block for reading or modification using
  87995. * FLAC__metadata_iterator_get_block(). The pointer to the object
  87996. * inside the chain is returned, so the block is yours to modify.
  87997. * Changes will be reflected in the FLAC file when you write the
  87998. * chain. You can also add and delete blocks (see functions below).
  87999. * - When done, write out the chain using FLAC__metadata_chain_write().
  88000. * Make sure to read the whole comment to the function below.
  88001. * - Delete the chain using FLAC__metadata_chain_delete().
  88002. *
  88003. * \note
  88004. * Even though the FLAC file is not open while the chain is being
  88005. * manipulated, you must not alter the file externally during
  88006. * this time. The chain assumes the FLAC file will not change
  88007. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  88008. * and FLAC__metadata_chain_write().
  88009. *
  88010. * \note
  88011. * Do not modify the is_last, length, or type fields of returned
  88012. * FLAC__StreamMetadata objects. These are managed automatically.
  88013. *
  88014. * \note
  88015. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  88016. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  88017. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  88018. * become owned by the chain and they will be deleted when the chain is
  88019. * deleted.
  88020. *
  88021. * \{
  88022. */
  88023. struct FLAC__Metadata_Chain;
  88024. /** The opaque structure definition for the level 2 chain type.
  88025. */
  88026. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  88027. struct FLAC__Metadata_Iterator;
  88028. /** The opaque structure definition for the level 2 iterator type.
  88029. */
  88030. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  88031. typedef enum {
  88032. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  88033. /**< The chain is in the normal OK state */
  88034. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  88035. /**< The data passed into a function violated the function's usage criteria */
  88036. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  88037. /**< The chain could not open the target file */
  88038. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  88039. /**< The chain could not find the FLAC signature at the start of the file */
  88040. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  88041. /**< The chain tried to write to a file that was not writable */
  88042. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  88043. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  88044. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  88045. /**< The chain encountered an error while reading the FLAC file */
  88046. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  88047. /**< The chain encountered an error while seeking in the FLAC file */
  88048. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  88049. /**< The chain encountered an error while writing the FLAC file */
  88050. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  88051. /**< The chain encountered an error renaming the FLAC file */
  88052. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  88053. /**< The chain encountered an error removing the temporary file */
  88054. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  88055. /**< Memory allocation failed */
  88056. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  88057. /**< The caller violated an assertion or an unexpected error occurred */
  88058. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  88059. /**< One or more of the required callbacks was NULL */
  88060. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  88061. /**< FLAC__metadata_chain_write() was called on a chain read by
  88062. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88063. * or
  88064. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  88065. * was called on a chain read by
  88066. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88067. * Matching read/write methods must always be used. */
  88068. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  88069. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  88070. * chain write requires a tempfile; use
  88071. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  88072. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  88073. * called when the chain write does not require a tempfile; use
  88074. * FLAC__metadata_chain_write_with_callbacks() instead.
  88075. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  88076. * before writing via callbacks. */
  88077. } FLAC__Metadata_ChainStatus;
  88078. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  88079. *
  88080. * Using a FLAC__Metadata_ChainStatus as the index to this array
  88081. * will give the string equivalent. The contents should not be modified.
  88082. */
  88083. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  88084. /*********** FLAC__Metadata_Chain ***********/
  88085. /** Create a new chain instance.
  88086. *
  88087. * \retval FLAC__Metadata_Chain*
  88088. * \c NULL if there was an error allocating memory, else the new instance.
  88089. */
  88090. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  88091. /** Free a chain instance. Deletes the object pointed to by \a chain.
  88092. *
  88093. * \param chain A pointer to an existing chain.
  88094. * \assert
  88095. * \code chain != NULL \endcode
  88096. */
  88097. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  88098. /** Get the current status of the chain. Call this after a function
  88099. * returns \c false to get the reason for the error. Also resets the
  88100. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  88101. *
  88102. * \param chain A pointer to an existing chain.
  88103. * \assert
  88104. * \code chain != NULL \endcode
  88105. * \retval FLAC__Metadata_ChainStatus
  88106. * The current status of the chain.
  88107. */
  88108. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  88109. /** Read all metadata from a FLAC file into the chain.
  88110. *
  88111. * \param chain A pointer to an existing chain.
  88112. * \param filename The path to the FLAC file to read.
  88113. * \assert
  88114. * \code chain != NULL \endcode
  88115. * \code filename != NULL \endcode
  88116. * \retval FLAC__bool
  88117. * \c true if a valid list of metadata blocks was read from
  88118. * \a filename, else \c false. On failure, check the status with
  88119. * FLAC__metadata_chain_status().
  88120. */
  88121. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  88122. /** Read all metadata from an Ogg FLAC file into the chain.
  88123. *
  88124. * \note Ogg FLAC metadata data writing is not supported yet and
  88125. * FLAC__metadata_chain_write() will fail.
  88126. *
  88127. * \param chain A pointer to an existing chain.
  88128. * \param filename The path to the Ogg FLAC file to read.
  88129. * \assert
  88130. * \code chain != NULL \endcode
  88131. * \code filename != NULL \endcode
  88132. * \retval FLAC__bool
  88133. * \c true if a valid list of metadata blocks was read from
  88134. * \a filename, else \c false. On failure, check the status with
  88135. * FLAC__metadata_chain_status().
  88136. */
  88137. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  88138. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  88139. *
  88140. * The \a handle need only be open for reading, but must be seekable.
  88141. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88142. * for Windows).
  88143. *
  88144. * \param chain A pointer to an existing chain.
  88145. * \param handle The I/O handle of the FLAC stream to read. The
  88146. * handle will NOT be closed after the metadata is read;
  88147. * that is the duty of the caller.
  88148. * \param callbacks
  88149. * A set of callbacks to use for I/O. The mandatory
  88150. * callbacks are \a read, \a seek, and \a tell.
  88151. * \assert
  88152. * \code chain != NULL \endcode
  88153. * \retval FLAC__bool
  88154. * \c true if a valid list of metadata blocks was read from
  88155. * \a handle, else \c false. On failure, check the status with
  88156. * FLAC__metadata_chain_status().
  88157. */
  88158. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88159. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  88160. *
  88161. * The \a handle need only be open for reading, but must be seekable.
  88162. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88163. * for Windows).
  88164. *
  88165. * \note Ogg FLAC metadata data writing is not supported yet and
  88166. * FLAC__metadata_chain_write() will fail.
  88167. *
  88168. * \param chain A pointer to an existing chain.
  88169. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  88170. * handle will NOT be closed after the metadata is read;
  88171. * that is the duty of the caller.
  88172. * \param callbacks
  88173. * A set of callbacks to use for I/O. The mandatory
  88174. * callbacks are \a read, \a seek, and \a tell.
  88175. * \assert
  88176. * \code chain != NULL \endcode
  88177. * \retval FLAC__bool
  88178. * \c true if a valid list of metadata blocks was read from
  88179. * \a handle, else \c false. On failure, check the status with
  88180. * FLAC__metadata_chain_status().
  88181. */
  88182. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88183. /** Checks if writing the given chain would require the use of a
  88184. * temporary file, or if it could be written in place.
  88185. *
  88186. * Under certain conditions, padding can be utilized so that writing
  88187. * edited metadata back to the FLAC file does not require rewriting the
  88188. * entire file. If rewriting is required, then a temporary workfile is
  88189. * required. When writing metadata using callbacks, you must check
  88190. * this function to know whether to call
  88191. * FLAC__metadata_chain_write_with_callbacks() or
  88192. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  88193. * writing with FLAC__metadata_chain_write(), the temporary file is
  88194. * handled internally.
  88195. *
  88196. * \param chain A pointer to an existing chain.
  88197. * \param use_padding
  88198. * Whether or not padding will be allowed to be used
  88199. * during the write. The value of \a use_padding given
  88200. * here must match the value later passed to
  88201. * FLAC__metadata_chain_write_with_callbacks() or
  88202. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  88203. * \assert
  88204. * \code chain != NULL \endcode
  88205. * \retval FLAC__bool
  88206. * \c true if writing the current chain would require a tempfile, or
  88207. * \c false if metadata can be written in place.
  88208. */
  88209. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  88210. /** Write all metadata out to the FLAC file. This function tries to be as
  88211. * efficient as possible; how the metadata is actually written is shown by
  88212. * the following:
  88213. *
  88214. * If the current chain is the same size as the existing metadata, the new
  88215. * data is written in place.
  88216. *
  88217. * If the current chain is longer than the existing metadata, and
  88218. * \a use_padding is \c true, and the last block is a PADDING block of
  88219. * sufficient length, the function will truncate the final padding block
  88220. * so that the overall size of the metadata is the same as the existing
  88221. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  88222. * the above conditions are met, the entire FLAC file must be rewritten.
  88223. * If you want to use padding this way it is a good idea to call
  88224. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  88225. * amount of padding to work with, unless you need to preserve ordering
  88226. * of the PADDING blocks for some reason.
  88227. *
  88228. * If the current chain is shorter than the existing metadata, and
  88229. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  88230. * is extended to make the overall size the same as the existing data. If
  88231. * \a use_padding is \c true and the last block is not a PADDING block, a new
  88232. * PADDING block is added to the end of the new data to make it the same
  88233. * size as the existing data (if possible, see the note to
  88234. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  88235. * and the new data is written in place. If none of the above apply or
  88236. * \a use_padding is \c false, the entire FLAC file is rewritten.
  88237. *
  88238. * If \a preserve_file_stats is \c true, the owner and modification time will
  88239. * be preserved even if the FLAC file is written.
  88240. *
  88241. * For this write function to be used, the chain must have been read with
  88242. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  88243. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  88244. *
  88245. * \param chain A pointer to an existing chain.
  88246. * \param use_padding See above.
  88247. * \param preserve_file_stats See above.
  88248. * \assert
  88249. * \code chain != NULL \endcode
  88250. * \retval FLAC__bool
  88251. * \c true if the write succeeded, else \c false. On failure,
  88252. * check the status with FLAC__metadata_chain_status().
  88253. */
  88254. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  88255. /** Write all metadata out to a FLAC stream via callbacks.
  88256. *
  88257. * (See FLAC__metadata_chain_write() for the details on how padding is
  88258. * used to write metadata in place if possible.)
  88259. *
  88260. * The \a handle must be open for updating and be seekable. The
  88261. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  88262. * for Windows).
  88263. *
  88264. * For this write function to be used, the chain must have been read with
  88265. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88266. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88267. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  88268. * \c false.
  88269. *
  88270. * \param chain A pointer to an existing chain.
  88271. * \param use_padding See FLAC__metadata_chain_write()
  88272. * \param handle The I/O handle of the FLAC stream to write. The
  88273. * handle will NOT be closed after the metadata is
  88274. * written; that is the duty of the caller.
  88275. * \param callbacks A set of callbacks to use for I/O. The mandatory
  88276. * callbacks are \a write and \a seek.
  88277. * \assert
  88278. * \code chain != NULL \endcode
  88279. * \retval FLAC__bool
  88280. * \c true if the write succeeded, else \c false. On failure,
  88281. * check the status with FLAC__metadata_chain_status().
  88282. */
  88283. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88284. /** Write all metadata out to a FLAC stream via callbacks.
  88285. *
  88286. * (See FLAC__metadata_chain_write() for the details on how padding is
  88287. * used to write metadata in place if possible.)
  88288. *
  88289. * This version of the write-with-callbacks function must be used when
  88290. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  88291. * this function, you must supply an I/O handle corresponding to the
  88292. * FLAC file to edit, and a temporary handle to which the new FLAC
  88293. * file will be written. It is the caller's job to move this temporary
  88294. * FLAC file on top of the original FLAC file to complete the metadata
  88295. * edit.
  88296. *
  88297. * The \a handle must be open for reading and be seekable. The
  88298. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88299. * for Windows).
  88300. *
  88301. * The \a temp_handle must be open for writing. The
  88302. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  88303. * for Windows). It should be an empty stream, or at least positioned
  88304. * at the start-of-file (in which case it is the caller's duty to
  88305. * truncate it on return).
  88306. *
  88307. * For this write function to be used, the chain must have been read with
  88308. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88309. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88310. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  88311. * \c true.
  88312. *
  88313. * \param chain A pointer to an existing chain.
  88314. * \param use_padding See FLAC__metadata_chain_write()
  88315. * \param handle The I/O handle of the original FLAC stream to read.
  88316. * The handle will NOT be closed after the metadata is
  88317. * written; that is the duty of the caller.
  88318. * \param callbacks A set of callbacks to use for I/O on \a handle.
  88319. * The mandatory callbacks are \a read, \a seek, and
  88320. * \a eof.
  88321. * \param temp_handle The I/O handle of the FLAC stream to write. The
  88322. * handle will NOT be closed after the metadata is
  88323. * written; that is the duty of the caller.
  88324. * \param temp_callbacks
  88325. * A set of callbacks to use for I/O on temp_handle.
  88326. * The only mandatory callback is \a write.
  88327. * \assert
  88328. * \code chain != NULL \endcode
  88329. * \retval FLAC__bool
  88330. * \c true if the write succeeded, else \c false. On failure,
  88331. * check the status with FLAC__metadata_chain_status().
  88332. */
  88333. 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);
  88334. /** Merge adjacent PADDING blocks into a single block.
  88335. *
  88336. * \note This function does not write to the FLAC file, it only
  88337. * modifies the chain.
  88338. *
  88339. * \warning Any iterator on the current chain will become invalid after this
  88340. * call. You should delete the iterator and get a new one.
  88341. *
  88342. * \param chain A pointer to an existing chain.
  88343. * \assert
  88344. * \code chain != NULL \endcode
  88345. */
  88346. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  88347. /** This function will move all PADDING blocks to the end on the metadata,
  88348. * then merge them into a single block.
  88349. *
  88350. * \note This function does not write to the FLAC file, it only
  88351. * modifies the chain.
  88352. *
  88353. * \warning Any iterator on the current chain will become invalid after this
  88354. * call. You should delete the iterator and get a new one.
  88355. *
  88356. * \param chain A pointer to an existing chain.
  88357. * \assert
  88358. * \code chain != NULL \endcode
  88359. */
  88360. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  88361. /*********** FLAC__Metadata_Iterator ***********/
  88362. /** Create a new iterator instance.
  88363. *
  88364. * \retval FLAC__Metadata_Iterator*
  88365. * \c NULL if there was an error allocating memory, else the new instance.
  88366. */
  88367. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  88368. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  88369. *
  88370. * \param iterator A pointer to an existing iterator.
  88371. * \assert
  88372. * \code iterator != NULL \endcode
  88373. */
  88374. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  88375. /** Initialize the iterator to point to the first metadata block in the
  88376. * given chain.
  88377. *
  88378. * \param iterator A pointer to an existing iterator.
  88379. * \param chain A pointer to an existing and initialized (read) chain.
  88380. * \assert
  88381. * \code iterator != NULL \endcode
  88382. * \code chain != NULL \endcode
  88383. */
  88384. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  88385. /** Moves the iterator forward one metadata block, returning \c false if
  88386. * already at the end.
  88387. *
  88388. * \param iterator A pointer to an existing initialized iterator.
  88389. * \assert
  88390. * \code iterator != NULL \endcode
  88391. * \a iterator has been successfully initialized with
  88392. * FLAC__metadata_iterator_init()
  88393. * \retval FLAC__bool
  88394. * \c false if already at the last metadata block of the chain, else
  88395. * \c true.
  88396. */
  88397. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  88398. /** Moves the iterator backward one metadata block, returning \c false if
  88399. * already at the beginning.
  88400. *
  88401. * \param iterator A pointer to an existing initialized iterator.
  88402. * \assert
  88403. * \code iterator != NULL \endcode
  88404. * \a iterator has been successfully initialized with
  88405. * FLAC__metadata_iterator_init()
  88406. * \retval FLAC__bool
  88407. * \c false if already at the first metadata block of the chain, else
  88408. * \c true.
  88409. */
  88410. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  88411. /** Get the type of the metadata block at the current position.
  88412. *
  88413. * \param iterator A pointer to an existing initialized iterator.
  88414. * \assert
  88415. * \code iterator != NULL \endcode
  88416. * \a iterator has been successfully initialized with
  88417. * FLAC__metadata_iterator_init()
  88418. * \retval FLAC__MetadataType
  88419. * The type of the metadata block at the current iterator position.
  88420. */
  88421. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  88422. /** Get the metadata block at the current position. You can modify
  88423. * the block in place but must write the chain before the changes
  88424. * are reflected to the FLAC file. You do not need to call
  88425. * FLAC__metadata_iterator_set_block() to reflect the changes;
  88426. * the pointer returned by FLAC__metadata_iterator_get_block()
  88427. * points directly into the chain.
  88428. *
  88429. * \warning
  88430. * Do not call FLAC__metadata_object_delete() on the returned object;
  88431. * to delete a block use FLAC__metadata_iterator_delete_block().
  88432. *
  88433. * \param iterator A pointer to an existing initialized iterator.
  88434. * \assert
  88435. * \code iterator != NULL \endcode
  88436. * \a iterator has been successfully initialized with
  88437. * FLAC__metadata_iterator_init()
  88438. * \retval FLAC__StreamMetadata*
  88439. * The current metadata block.
  88440. */
  88441. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  88442. /** Set the metadata block at the current position, replacing the existing
  88443. * block. The new block passed in becomes owned by the chain and it will be
  88444. * deleted when the chain is deleted.
  88445. *
  88446. * \param iterator A pointer to an existing initialized iterator.
  88447. * \param block A pointer to a metadata block.
  88448. * \assert
  88449. * \code iterator != NULL \endcode
  88450. * \a iterator has been successfully initialized with
  88451. * FLAC__metadata_iterator_init()
  88452. * \code block != NULL \endcode
  88453. * \retval FLAC__bool
  88454. * \c false if the conditions in the above description are not met, or
  88455. * a memory allocation error occurs, otherwise \c true.
  88456. */
  88457. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88458. /** Removes the current block from the chain. If \a replace_with_padding is
  88459. * \c true, the block will instead be replaced with a padding block of equal
  88460. * size. You can not delete the STREAMINFO block. The iterator will be
  88461. * left pointing to the block before the one just "deleted", even if
  88462. * \a replace_with_padding is \c true.
  88463. *
  88464. * \param iterator A pointer to an existing initialized iterator.
  88465. * \param replace_with_padding See above.
  88466. * \assert
  88467. * \code iterator != NULL \endcode
  88468. * \a iterator has been successfully initialized with
  88469. * FLAC__metadata_iterator_init()
  88470. * \retval FLAC__bool
  88471. * \c false if the conditions in the above description are not met,
  88472. * otherwise \c true.
  88473. */
  88474. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  88475. /** Insert a new block before the current block. You cannot insert a block
  88476. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  88477. * as there can be only one, the one that already exists at the head when you
  88478. * read in a chain. The chain takes ownership of the new block and it will be
  88479. * deleted when the chain is deleted. The iterator will be left pointing to
  88480. * the new block.
  88481. *
  88482. * \param iterator A pointer to an existing initialized iterator.
  88483. * \param block A pointer to a metadata block to insert.
  88484. * \assert
  88485. * \code iterator != NULL \endcode
  88486. * \a iterator has been successfully initialized with
  88487. * FLAC__metadata_iterator_init()
  88488. * \retval FLAC__bool
  88489. * \c false if the conditions in the above description are not met, or
  88490. * a memory allocation error occurs, otherwise \c true.
  88491. */
  88492. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88493. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  88494. * block as there can be only one, the one that already exists at the head when
  88495. * you read in a chain. The chain takes ownership of the new block and it will
  88496. * be deleted when the chain is deleted. The iterator will be left pointing to
  88497. * the new block.
  88498. *
  88499. * \param iterator A pointer to an existing initialized iterator.
  88500. * \param block A pointer to a metadata block to insert.
  88501. * \assert
  88502. * \code iterator != NULL \endcode
  88503. * \a iterator has been successfully initialized with
  88504. * FLAC__metadata_iterator_init()
  88505. * \retval FLAC__bool
  88506. * \c false if the conditions in the above description are not met, or
  88507. * a memory allocation error occurs, otherwise \c true.
  88508. */
  88509. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88510. /* \} */
  88511. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  88512. * \ingroup flac_metadata
  88513. *
  88514. * \brief
  88515. * This module contains methods for manipulating FLAC metadata objects.
  88516. *
  88517. * Since many are variable length we have to be careful about the memory
  88518. * management. We decree that all pointers to data in the object are
  88519. * owned by the object and memory-managed by the object.
  88520. *
  88521. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  88522. * functions to create all instances. When using the
  88523. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  88524. * \a copy to \c true to have the function make it's own copy of the data, or
  88525. * to \c false to give the object ownership of your data. In the latter case
  88526. * your pointer must be freeable by free() and will be free()d when the object
  88527. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  88528. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  88529. * the length argument is 0 and the \a copy argument is \c false.
  88530. *
  88531. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  88532. * will return \c NULL in the case of a memory allocation error, otherwise a new
  88533. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  88534. * case of a memory allocation error.
  88535. *
  88536. * We don't have the convenience of C++ here, so note that the library relies
  88537. * on you to keep the types straight. In other words, if you pass, for
  88538. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  88539. * FLAC__metadata_object_application_set_data(), you will get an assertion
  88540. * failure.
  88541. *
  88542. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  88543. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  88544. * toward the length or stored in the stream, but it can make working with plain
  88545. * comments (those that don't contain embedded-NULs in the value) easier.
  88546. * Entries passed into these functions have trailing NULs added if missing, and
  88547. * returned entries are guaranteed to have a trailing NUL.
  88548. *
  88549. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  88550. * comment entry/name/value will first validate that it complies with the Vorbis
  88551. * comment specification and return false if it does not.
  88552. *
  88553. * There is no need to recalculate the length field on metadata blocks you
  88554. * have modified. They will be calculated automatically before they are
  88555. * written back to a file.
  88556. *
  88557. * \{
  88558. */
  88559. /** Create a new metadata object instance of the given type.
  88560. *
  88561. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  88562. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  88563. * the vendor string set (but zero comments).
  88564. *
  88565. * Do not pass in a value greater than or equal to
  88566. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  88567. * doing.
  88568. *
  88569. * \param type Type of object to create
  88570. * \retval FLAC__StreamMetadata*
  88571. * \c NULL if there was an error allocating memory or the type code is
  88572. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  88573. */
  88574. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  88575. /** Create a copy of an existing metadata object.
  88576. *
  88577. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  88578. * object is also copied. The caller takes ownership of the new block and
  88579. * is responsible for freeing it with FLAC__metadata_object_delete().
  88580. *
  88581. * \param object Pointer to object to copy.
  88582. * \assert
  88583. * \code object != NULL \endcode
  88584. * \retval FLAC__StreamMetadata*
  88585. * \c NULL if there was an error allocating memory, else the new instance.
  88586. */
  88587. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  88588. /** Free a metadata object. Deletes the object pointed to by \a object.
  88589. *
  88590. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  88591. * object is also deleted.
  88592. *
  88593. * \param object A pointer to an existing object.
  88594. * \assert
  88595. * \code object != NULL \endcode
  88596. */
  88597. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  88598. /** Compares two metadata objects.
  88599. *
  88600. * The compare is "deep", i.e. dynamically allocated data within the
  88601. * object is also compared.
  88602. *
  88603. * \param block1 A pointer to an existing object.
  88604. * \param block2 A pointer to an existing object.
  88605. * \assert
  88606. * \code block1 != NULL \endcode
  88607. * \code block2 != NULL \endcode
  88608. * \retval FLAC__bool
  88609. * \c true if objects are identical, else \c false.
  88610. */
  88611. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  88612. /** Sets the application data of an APPLICATION block.
  88613. *
  88614. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  88615. * takes ownership of the pointer. The existing data will be freed if this
  88616. * function is successful, otherwise the original data will remain if \a copy
  88617. * is \c true and malloc() fails.
  88618. *
  88619. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  88620. *
  88621. * \param object A pointer to an existing APPLICATION object.
  88622. * \param data A pointer to the data to set.
  88623. * \param length The length of \a data in bytes.
  88624. * \param copy See above.
  88625. * \assert
  88626. * \code object != NULL \endcode
  88627. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  88628. * \code (data != NULL && length > 0) ||
  88629. * (data == NULL && length == 0 && copy == false) \endcode
  88630. * \retval FLAC__bool
  88631. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88632. */
  88633. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  88634. /** Resize the seekpoint array.
  88635. *
  88636. * If the size shrinks, elements will truncated; if it grows, new placeholder
  88637. * points will be added to the end.
  88638. *
  88639. * \param object A pointer to an existing SEEKTABLE object.
  88640. * \param new_num_points The desired length of the array; may be \c 0.
  88641. * \assert
  88642. * \code object != NULL \endcode
  88643. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88644. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  88645. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  88646. * \retval FLAC__bool
  88647. * \c false if memory allocation error, else \c true.
  88648. */
  88649. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  88650. /** Set a seekpoint in a seektable.
  88651. *
  88652. * \param object A pointer to an existing SEEKTABLE object.
  88653. * \param point_num Index into seekpoint array to set.
  88654. * \param point The point to set.
  88655. * \assert
  88656. * \code object != NULL \endcode
  88657. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88658. * \code object->data.seek_table.num_points > point_num \endcode
  88659. */
  88660. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88661. /** Insert a seekpoint into a seektable.
  88662. *
  88663. * \param object A pointer to an existing SEEKTABLE object.
  88664. * \param point_num Index into seekpoint array to set.
  88665. * \param point The point to set.
  88666. * \assert
  88667. * \code object != NULL \endcode
  88668. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88669. * \code object->data.seek_table.num_points >= point_num \endcode
  88670. * \retval FLAC__bool
  88671. * \c false if memory allocation error, else \c true.
  88672. */
  88673. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88674. /** Delete a seekpoint from a seektable.
  88675. *
  88676. * \param object A pointer to an existing SEEKTABLE object.
  88677. * \param point_num Index into seekpoint array to set.
  88678. * \assert
  88679. * \code object != NULL \endcode
  88680. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88681. * \code object->data.seek_table.num_points > point_num \endcode
  88682. * \retval FLAC__bool
  88683. * \c false if memory allocation error, else \c true.
  88684. */
  88685. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  88686. /** Check a seektable to see if it conforms to the FLAC specification.
  88687. * See the format specification for limits on the contents of the
  88688. * seektable.
  88689. *
  88690. * \param object A pointer to an existing SEEKTABLE object.
  88691. * \assert
  88692. * \code object != NULL \endcode
  88693. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88694. * \retval FLAC__bool
  88695. * \c false if seek table is illegal, else \c true.
  88696. */
  88697. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  88698. /** Append a number of placeholder points to the end of a seek table.
  88699. *
  88700. * \note
  88701. * As with the other ..._seektable_template_... functions, you should
  88702. * call FLAC__metadata_object_seektable_template_sort() when finished
  88703. * to make the seek table legal.
  88704. *
  88705. * \param object A pointer to an existing SEEKTABLE object.
  88706. * \param num The number of placeholder points to append.
  88707. * \assert
  88708. * \code object != NULL \endcode
  88709. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88710. * \retval FLAC__bool
  88711. * \c false if memory allocation fails, else \c true.
  88712. */
  88713. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  88714. /** Append a specific seek point template to the end of a seek table.
  88715. *
  88716. * \note
  88717. * As with the other ..._seektable_template_... functions, you should
  88718. * call FLAC__metadata_object_seektable_template_sort() when finished
  88719. * to make the seek table legal.
  88720. *
  88721. * \param object A pointer to an existing SEEKTABLE object.
  88722. * \param sample_number The sample number of the seek point template.
  88723. * \assert
  88724. * \code object != NULL \endcode
  88725. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88726. * \retval FLAC__bool
  88727. * \c false if memory allocation fails, else \c true.
  88728. */
  88729. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  88730. /** Append specific seek point templates to the end of a seek table.
  88731. *
  88732. * \note
  88733. * As with the other ..._seektable_template_... functions, you should
  88734. * call FLAC__metadata_object_seektable_template_sort() when finished
  88735. * to make the seek table legal.
  88736. *
  88737. * \param object A pointer to an existing SEEKTABLE object.
  88738. * \param sample_numbers An array of sample numbers for the seek points.
  88739. * \param num The number of seek point templates to append.
  88740. * \assert
  88741. * \code object != NULL \endcode
  88742. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88743. * \retval FLAC__bool
  88744. * \c false if memory allocation fails, else \c true.
  88745. */
  88746. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  88747. /** Append a set of evenly-spaced seek point templates to the end of a
  88748. * seek table.
  88749. *
  88750. * \note
  88751. * As with the other ..._seektable_template_... functions, you should
  88752. * call FLAC__metadata_object_seektable_template_sort() when finished
  88753. * to make the seek table legal.
  88754. *
  88755. * \param object A pointer to an existing SEEKTABLE object.
  88756. * \param num The number of placeholder points to append.
  88757. * \param total_samples The total number of samples to be encoded;
  88758. * the seekpoints will be spaced approximately
  88759. * \a total_samples / \a num samples apart.
  88760. * \assert
  88761. * \code object != NULL \endcode
  88762. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88763. * \code total_samples > 0 \endcode
  88764. * \retval FLAC__bool
  88765. * \c false if memory allocation fails, else \c true.
  88766. */
  88767. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  88768. /** Append a set of evenly-spaced seek point templates to the end of a
  88769. * seek table.
  88770. *
  88771. * \note
  88772. * As with the other ..._seektable_template_... functions, you should
  88773. * call FLAC__metadata_object_seektable_template_sort() when finished
  88774. * to make the seek table legal.
  88775. *
  88776. * \param object A pointer to an existing SEEKTABLE object.
  88777. * \param samples The number of samples apart to space the placeholder
  88778. * points. The first point will be at sample \c 0, the
  88779. * second at sample \a samples, then 2*\a samples, and
  88780. * so on. As long as \a samples and \a total_samples
  88781. * are greater than \c 0, there will always be at least
  88782. * one seekpoint at sample \c 0.
  88783. * \param total_samples The total number of samples to be encoded;
  88784. * the seekpoints will be spaced
  88785. * \a samples samples apart.
  88786. * \assert
  88787. * \code object != NULL \endcode
  88788. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88789. * \code samples > 0 \endcode
  88790. * \code total_samples > 0 \endcode
  88791. * \retval FLAC__bool
  88792. * \c false if memory allocation fails, else \c true.
  88793. */
  88794. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  88795. /** Sort a seek table's seek points according to the format specification,
  88796. * removing duplicates.
  88797. *
  88798. * \param object A pointer to a seek table to be sorted.
  88799. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  88800. * If \c true, duplicates are deleted and the seek table is
  88801. * shrunk appropriately; the number of placeholder points
  88802. * present in the seek table will be the same after the call
  88803. * as before.
  88804. * \assert
  88805. * \code object != NULL \endcode
  88806. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88807. * \retval FLAC__bool
  88808. * \c false if realloc() fails, else \c true.
  88809. */
  88810. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  88811. /** Sets the vendor string in a VORBIS_COMMENT block.
  88812. *
  88813. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88814. * one already.
  88815. *
  88816. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88817. * takes ownership of the \c entry.entry pointer.
  88818. *
  88819. * \note If this function returns \c false, the caller still owns the
  88820. * pointer.
  88821. *
  88822. * \param object A pointer to an existing VORBIS_COMMENT object.
  88823. * \param entry The entry to set the vendor string to.
  88824. * \param copy See above.
  88825. * \assert
  88826. * \code object != NULL \endcode
  88827. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88828. * \code (entry.entry != NULL && entry.length > 0) ||
  88829. * (entry.entry == NULL && entry.length == 0) \endcode
  88830. * \retval FLAC__bool
  88831. * \c false if memory allocation fails or \a entry does not comply with the
  88832. * Vorbis comment specification, else \c true.
  88833. */
  88834. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88835. /** Resize the comment array.
  88836. *
  88837. * If the size shrinks, elements will truncated; if it grows, new empty
  88838. * fields will be added to the end.
  88839. *
  88840. * \param object A pointer to an existing VORBIS_COMMENT object.
  88841. * \param new_num_comments The desired length of the array; may be \c 0.
  88842. * \assert
  88843. * \code object != NULL \endcode
  88844. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88845. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  88846. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  88847. * \retval FLAC__bool
  88848. * \c false if memory allocation fails, else \c true.
  88849. */
  88850. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  88851. /** Sets a comment in a VORBIS_COMMENT block.
  88852. *
  88853. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88854. * one already.
  88855. *
  88856. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88857. * takes ownership of the \c entry.entry pointer.
  88858. *
  88859. * \note If this function returns \c false, the caller still owns the
  88860. * pointer.
  88861. *
  88862. * \param object A pointer to an existing VORBIS_COMMENT object.
  88863. * \param comment_num Index into comment array to set.
  88864. * \param entry The entry to set the comment to.
  88865. * \param copy See above.
  88866. * \assert
  88867. * \code object != NULL \endcode
  88868. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88869. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  88870. * \code (entry.entry != NULL && entry.length > 0) ||
  88871. * (entry.entry == NULL && entry.length == 0) \endcode
  88872. * \retval FLAC__bool
  88873. * \c false if memory allocation fails or \a entry does not comply with the
  88874. * Vorbis comment specification, else \c true.
  88875. */
  88876. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88877. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  88878. *
  88879. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88880. * one already.
  88881. *
  88882. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88883. * takes ownership of the \c entry.entry pointer.
  88884. *
  88885. * \note If this function returns \c false, the caller still owns the
  88886. * pointer.
  88887. *
  88888. * \param object A pointer to an existing VORBIS_COMMENT object.
  88889. * \param comment_num The index at which to insert the comment. The comments
  88890. * at and after \a comment_num move right one position.
  88891. * To append a comment to the end, set \a comment_num to
  88892. * \c object->data.vorbis_comment.num_comments .
  88893. * \param entry The comment to insert.
  88894. * \param copy See above.
  88895. * \assert
  88896. * \code object != NULL \endcode
  88897. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88898. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  88899. * \code (entry.entry != NULL && entry.length > 0) ||
  88900. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88901. * \retval FLAC__bool
  88902. * \c false if memory allocation fails or \a entry does not comply with the
  88903. * Vorbis comment specification, else \c true.
  88904. */
  88905. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88906. /** Appends a comment to a VORBIS_COMMENT block.
  88907. *
  88908. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88909. * one already.
  88910. *
  88911. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88912. * takes ownership of the \c entry.entry pointer.
  88913. *
  88914. * \note If this function returns \c false, the caller still owns the
  88915. * pointer.
  88916. *
  88917. * \param object A pointer to an existing VORBIS_COMMENT object.
  88918. * \param entry The comment to insert.
  88919. * \param copy See above.
  88920. * \assert
  88921. * \code object != NULL \endcode
  88922. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88923. * \code (entry.entry != NULL && entry.length > 0) ||
  88924. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88925. * \retval FLAC__bool
  88926. * \c false if memory allocation fails or \a entry does not comply with the
  88927. * Vorbis comment specification, else \c true.
  88928. */
  88929. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  88930. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  88931. *
  88932. * For convenience, a trailing NUL is added to the entry if it doesn't have
  88933. * one already.
  88934. *
  88935. * Depending on the the value of \a all, either all or just the first comment
  88936. * whose field name(s) match the given entry's name will be replaced by the
  88937. * given entry. If no comments match, \a entry will simply be appended.
  88938. *
  88939. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  88940. * takes ownership of the \c entry.entry pointer.
  88941. *
  88942. * \note If this function returns \c false, the caller still owns the
  88943. * pointer.
  88944. *
  88945. * \param object A pointer to an existing VORBIS_COMMENT object.
  88946. * \param entry The comment to insert.
  88947. * \param all If \c true, all comments whose field name matches
  88948. * \a entry's field name will be removed, and \a entry will
  88949. * be inserted at the position of the first matching
  88950. * comment. If \c false, only the first comment whose
  88951. * field name matches \a entry's field name will be
  88952. * replaced with \a entry.
  88953. * \param copy See above.
  88954. * \assert
  88955. * \code object != NULL \endcode
  88956. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88957. * \code (entry.entry != NULL && entry.length > 0) ||
  88958. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  88959. * \retval FLAC__bool
  88960. * \c false if memory allocation fails or \a entry does not comply with the
  88961. * Vorbis comment specification, else \c true.
  88962. */
  88963. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  88964. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  88965. *
  88966. * \param object A pointer to an existing VORBIS_COMMENT object.
  88967. * \param comment_num The index of the comment to delete.
  88968. * \assert
  88969. * \code object != NULL \endcode
  88970. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  88971. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  88972. * \retval FLAC__bool
  88973. * \c false if realloc() fails, else \c true.
  88974. */
  88975. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  88976. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  88977. *
  88978. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  88979. * memory and shall be owned by the caller. For convenience the entry will
  88980. * have a terminating NUL.
  88981. *
  88982. * \param entry A pointer to a Vorbis comment entry. The entry's
  88983. * \c entry pointer should not point to allocated
  88984. * memory as it will be overwritten.
  88985. * \param field_name The field name in ASCII, \c NUL terminated.
  88986. * \param field_value The field value in UTF-8, \c NUL terminated.
  88987. * \assert
  88988. * \code entry != NULL \endcode
  88989. * \code field_name != NULL \endcode
  88990. * \code field_value != NULL \endcode
  88991. * \retval FLAC__bool
  88992. * \c false if malloc() fails, or if \a field_name or \a field_value does
  88993. * not comply with the Vorbis comment specification, else \c true.
  88994. */
  88995. 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);
  88996. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  88997. *
  88998. * The returned pointers to name and value will be allocated by malloc()
  88999. * and shall be owned by the caller.
  89000. *
  89001. * \param entry An existing Vorbis comment entry.
  89002. * \param field_name The address of where the returned pointer to the
  89003. * field name will be stored.
  89004. * \param field_value The address of where the returned pointer to the
  89005. * field value will be stored.
  89006. * \assert
  89007. * \code (entry.entry != NULL && entry.length > 0) \endcode
  89008. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  89009. * \code field_name != NULL \endcode
  89010. * \code field_value != NULL \endcode
  89011. * \retval FLAC__bool
  89012. * \c false if memory allocation fails or \a entry does not comply with the
  89013. * Vorbis comment specification, else \c true.
  89014. */
  89015. 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);
  89016. /** Check if the given Vorbis comment entry's field name matches the given
  89017. * field name.
  89018. *
  89019. * \param entry An existing Vorbis comment entry.
  89020. * \param field_name The field name to check.
  89021. * \param field_name_length The length of \a field_name, not including the
  89022. * terminating \c NUL.
  89023. * \assert
  89024. * \code (entry.entry != NULL && entry.length > 0) \endcode
  89025. * \retval FLAC__bool
  89026. * \c true if the field names match, else \c false
  89027. */
  89028. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  89029. /** Find a Vorbis comment with the given field name.
  89030. *
  89031. * The search begins at entry number \a offset; use an offset of 0 to
  89032. * search from the beginning of the comment array.
  89033. *
  89034. * \param object A pointer to an existing VORBIS_COMMENT object.
  89035. * \param offset The offset into the comment array from where to start
  89036. * the search.
  89037. * \param field_name The field name of the comment to find.
  89038. * \assert
  89039. * \code object != NULL \endcode
  89040. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89041. * \code field_name != NULL \endcode
  89042. * \retval int
  89043. * The offset in the comment array of the first comment whose field
  89044. * name matches \a field_name, or \c -1 if no match was found.
  89045. */
  89046. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  89047. /** Remove first Vorbis comment matching the given field name.
  89048. *
  89049. * \param object A pointer to an existing VORBIS_COMMENT object.
  89050. * \param field_name The field name of comment to delete.
  89051. * \assert
  89052. * \code object != NULL \endcode
  89053. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89054. * \retval int
  89055. * \c -1 for memory allocation error, \c 0 for no matching entries,
  89056. * \c 1 for one matching entry deleted.
  89057. */
  89058. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  89059. /** Remove all Vorbis comments matching the given field name.
  89060. *
  89061. * \param object A pointer to an existing VORBIS_COMMENT object.
  89062. * \param field_name The field name of comments to delete.
  89063. * \assert
  89064. * \code object != NULL \endcode
  89065. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89066. * \retval int
  89067. * \c -1 for memory allocation error, \c 0 for no matching entries,
  89068. * else the number of matching entries deleted.
  89069. */
  89070. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  89071. /** Create a new CUESHEET track instance.
  89072. *
  89073. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  89074. *
  89075. * \retval FLAC__StreamMetadata_CueSheet_Track*
  89076. * \c NULL if there was an error allocating memory, else the new instance.
  89077. */
  89078. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  89079. /** Create a copy of an existing CUESHEET track object.
  89080. *
  89081. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  89082. * object is also copied. The caller takes ownership of the new object and
  89083. * is responsible for freeing it with
  89084. * FLAC__metadata_object_cuesheet_track_delete().
  89085. *
  89086. * \param object Pointer to object to copy.
  89087. * \assert
  89088. * \code object != NULL \endcode
  89089. * \retval FLAC__StreamMetadata_CueSheet_Track*
  89090. * \c NULL if there was an error allocating memory, else the new instance.
  89091. */
  89092. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  89093. /** Delete a CUESHEET track object
  89094. *
  89095. * \param object A pointer to an existing CUESHEET track object.
  89096. * \assert
  89097. * \code object != NULL \endcode
  89098. */
  89099. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  89100. /** Resize a track's index point array.
  89101. *
  89102. * If the size shrinks, elements will truncated; if it grows, new blank
  89103. * indices will be added to the end.
  89104. *
  89105. * \param object A pointer to an existing CUESHEET object.
  89106. * \param track_num The index of the track to modify. NOTE: this is not
  89107. * necessarily the same as the track's \a number field.
  89108. * \param new_num_indices The desired length of the array; may be \c 0.
  89109. * \assert
  89110. * \code object != NULL \endcode
  89111. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89112. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89113. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  89114. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  89115. * \retval FLAC__bool
  89116. * \c false if memory allocation error, else \c true.
  89117. */
  89118. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  89119. /** Insert an index point in a CUESHEET track at the given index.
  89120. *
  89121. * \param object A pointer to an existing CUESHEET object.
  89122. * \param track_num The index of the track to modify. NOTE: this is not
  89123. * necessarily the same as the track's \a number field.
  89124. * \param index_num The index into the track's index array at which to
  89125. * insert the index point. NOTE: this is not necessarily
  89126. * the same as the index point's \a number field. The
  89127. * indices at and after \a index_num move right one
  89128. * position. To append an index point to the end, set
  89129. * \a index_num to
  89130. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  89131. * \param index The index point to insert.
  89132. * \assert
  89133. * \code object != NULL \endcode
  89134. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89135. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89136. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  89137. * \retval FLAC__bool
  89138. * \c false if realloc() fails, else \c true.
  89139. */
  89140. 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);
  89141. /** Insert a blank index point in a CUESHEET track at the given index.
  89142. *
  89143. * A blank index point is one in which all field values are zero.
  89144. *
  89145. * \param object A pointer to an existing CUESHEET object.
  89146. * \param track_num The index of the track to modify. NOTE: this is not
  89147. * necessarily the same as the track's \a number field.
  89148. * \param index_num The index into the track's index array at which to
  89149. * insert the index point. NOTE: this is not necessarily
  89150. * the same as the index point's \a number field. The
  89151. * indices at and after \a index_num move right one
  89152. * position. To append an index point to the end, set
  89153. * \a index_num to
  89154. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  89155. * \assert
  89156. * \code object != NULL \endcode
  89157. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89158. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89159. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  89160. * \retval FLAC__bool
  89161. * \c false if realloc() fails, else \c true.
  89162. */
  89163. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  89164. /** Delete an index point in a CUESHEET track at the given index.
  89165. *
  89166. * \param object A pointer to an existing CUESHEET object.
  89167. * \param track_num The index into the track array of the track to
  89168. * modify. NOTE: this is not necessarily the same
  89169. * as the track's \a number field.
  89170. * \param index_num The index into the track's index array of the index
  89171. * to delete. NOTE: this is not necessarily the same
  89172. * as the index's \a number field.
  89173. * \assert
  89174. * \code object != NULL \endcode
  89175. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89176. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89177. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  89178. * \retval FLAC__bool
  89179. * \c false if realloc() fails, else \c true.
  89180. */
  89181. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  89182. /** Resize the track array.
  89183. *
  89184. * If the size shrinks, elements will truncated; if it grows, new blank
  89185. * tracks will be added to the end.
  89186. *
  89187. * \param object A pointer to an existing CUESHEET object.
  89188. * \param new_num_tracks The desired length of the array; may be \c 0.
  89189. * \assert
  89190. * \code object != NULL \endcode
  89191. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89192. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  89193. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  89194. * \retval FLAC__bool
  89195. * \c false if memory allocation error, else \c true.
  89196. */
  89197. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  89198. /** Sets a track in a CUESHEET block.
  89199. *
  89200. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  89201. * takes ownership of the \a track pointer.
  89202. *
  89203. * \param object A pointer to an existing CUESHEET object.
  89204. * \param track_num Index into track array to set. NOTE: this is not
  89205. * necessarily the same as the track's \a number field.
  89206. * \param track The track to set the track to. You may safely pass in
  89207. * a const pointer if \a copy is \c true.
  89208. * \param copy See above.
  89209. * \assert
  89210. * \code object != NULL \endcode
  89211. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89212. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  89213. * \code (track->indices != NULL && track->num_indices > 0) ||
  89214. * (track->indices == NULL && track->num_indices == 0)
  89215. * \retval FLAC__bool
  89216. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89217. */
  89218. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  89219. /** Insert a track in a CUESHEET block at the given index.
  89220. *
  89221. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  89222. * takes ownership of the \a track pointer.
  89223. *
  89224. * \param object A pointer to an existing CUESHEET object.
  89225. * \param track_num The index at which to insert the track. NOTE: this
  89226. * is not necessarily the same as the track's \a number
  89227. * field. The tracks at and after \a track_num move right
  89228. * one position. To append a track to the end, set
  89229. * \a track_num to \c object->data.cue_sheet.num_tracks .
  89230. * \param track The track to insert. You may safely pass in a const
  89231. * pointer if \a copy is \c true.
  89232. * \param copy See above.
  89233. * \assert
  89234. * \code object != NULL \endcode
  89235. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89236. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  89237. * \retval FLAC__bool
  89238. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89239. */
  89240. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  89241. /** Insert a blank track in a CUESHEET block at the given index.
  89242. *
  89243. * A blank track is one in which all field values are zero.
  89244. *
  89245. * \param object A pointer to an existing CUESHEET object.
  89246. * \param track_num The index at which to insert the track. NOTE: this
  89247. * is not necessarily the same as the track's \a number
  89248. * field. The tracks at and after \a track_num move right
  89249. * one position. To append a track to the end, set
  89250. * \a track_num to \c object->data.cue_sheet.num_tracks .
  89251. * \assert
  89252. * \code object != NULL \endcode
  89253. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89254. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  89255. * \retval FLAC__bool
  89256. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89257. */
  89258. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  89259. /** Delete a track in a CUESHEET block at the given index.
  89260. *
  89261. * \param object A pointer to an existing CUESHEET object.
  89262. * \param track_num The index into the track array of the track to
  89263. * delete. NOTE: this is not necessarily the same
  89264. * as the track's \a number field.
  89265. * \assert
  89266. * \code object != NULL \endcode
  89267. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89268. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89269. * \retval FLAC__bool
  89270. * \c false if realloc() fails, else \c true.
  89271. */
  89272. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  89273. /** Check a cue sheet to see if it conforms to the FLAC specification.
  89274. * See the format specification for limits on the contents of the
  89275. * cue sheet.
  89276. *
  89277. * \param object A pointer to an existing CUESHEET object.
  89278. * \param check_cd_da_subset If \c true, check CUESHEET against more
  89279. * stringent requirements for a CD-DA (audio) disc.
  89280. * \param violation Address of a pointer to a string. If there is a
  89281. * violation, a pointer to a string explanation of the
  89282. * violation will be returned here. \a violation may be
  89283. * \c NULL if you don't need the returned string. Do not
  89284. * free the returned string; it will always point to static
  89285. * data.
  89286. * \assert
  89287. * \code object != NULL \endcode
  89288. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89289. * \retval FLAC__bool
  89290. * \c false if cue sheet is illegal, else \c true.
  89291. */
  89292. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  89293. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  89294. * assumes the cue sheet corresponds to a CD; the result is undefined
  89295. * if the cuesheet's is_cd bit is not set.
  89296. *
  89297. * \param object A pointer to an existing CUESHEET object.
  89298. * \assert
  89299. * \code object != NULL \endcode
  89300. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89301. * \retval FLAC__uint32
  89302. * The unsigned integer representation of the CDDB/freedb ID
  89303. */
  89304. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  89305. /** Sets the MIME type of a PICTURE block.
  89306. *
  89307. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  89308. * takes ownership of the pointer. The existing string will be freed if this
  89309. * function is successful, otherwise the original string will remain if \a copy
  89310. * is \c true and malloc() fails.
  89311. *
  89312. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  89313. *
  89314. * \param object A pointer to an existing PICTURE object.
  89315. * \param mime_type A pointer to the MIME type string. The string must be
  89316. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  89317. * is done.
  89318. * \param copy See above.
  89319. * \assert
  89320. * \code object != NULL \endcode
  89321. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89322. * \code (mime_type != NULL) \endcode
  89323. * \retval FLAC__bool
  89324. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89325. */
  89326. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  89327. /** Sets the description of a PICTURE block.
  89328. *
  89329. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  89330. * takes ownership of the pointer. The existing string will be freed if this
  89331. * function is successful, otherwise the original string will remain if \a copy
  89332. * is \c true and malloc() fails.
  89333. *
  89334. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  89335. *
  89336. * \param object A pointer to an existing PICTURE object.
  89337. * \param description A pointer to the description string. The string must be
  89338. * valid UTF-8, NUL-terminated. No validation is done.
  89339. * \param copy See above.
  89340. * \assert
  89341. * \code object != NULL \endcode
  89342. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89343. * \code (description != NULL) \endcode
  89344. * \retval FLAC__bool
  89345. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89346. */
  89347. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  89348. /** Sets the picture data of a PICTURE block.
  89349. *
  89350. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  89351. * takes ownership of the pointer. Also sets the \a data_length field of the
  89352. * metadata object to what is passed in as the \a length parameter. The
  89353. * existing data will be freed if this function is successful, otherwise the
  89354. * original data and data_length will remain if \a copy is \c true and
  89355. * malloc() fails.
  89356. *
  89357. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  89358. *
  89359. * \param object A pointer to an existing PICTURE object.
  89360. * \param data A pointer to the data to set.
  89361. * \param length The length of \a data in bytes.
  89362. * \param copy See above.
  89363. * \assert
  89364. * \code object != NULL \endcode
  89365. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89366. * \code (data != NULL && length > 0) ||
  89367. * (data == NULL && length == 0 && copy == false) \endcode
  89368. * \retval FLAC__bool
  89369. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89370. */
  89371. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  89372. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  89373. * See the format specification for limits on the contents of the
  89374. * PICTURE block.
  89375. *
  89376. * \param object A pointer to existing PICTURE block to be checked.
  89377. * \param violation Address of a pointer to a string. If there is a
  89378. * violation, a pointer to a string explanation of the
  89379. * violation will be returned here. \a violation may be
  89380. * \c NULL if you don't need the returned string. Do not
  89381. * free the returned string; it will always point to static
  89382. * data.
  89383. * \assert
  89384. * \code object != NULL \endcode
  89385. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89386. * \retval FLAC__bool
  89387. * \c false if PICTURE block is illegal, else \c true.
  89388. */
  89389. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  89390. /* \} */
  89391. #ifdef __cplusplus
  89392. }
  89393. #endif
  89394. #endif
  89395. /*** End of inlined file: metadata.h ***/
  89396. /*** Start of inlined file: stream_decoder.h ***/
  89397. #ifndef FLAC__STREAM_DECODER_H
  89398. #define FLAC__STREAM_DECODER_H
  89399. #include <stdio.h> /* for FILE */
  89400. #ifdef __cplusplus
  89401. extern "C" {
  89402. #endif
  89403. /** \file include/FLAC/stream_decoder.h
  89404. *
  89405. * \brief
  89406. * This module contains the functions which implement the stream
  89407. * decoder.
  89408. *
  89409. * See the detailed documentation in the
  89410. * \link flac_stream_decoder stream decoder \endlink module.
  89411. */
  89412. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  89413. * \ingroup flac
  89414. *
  89415. * \brief
  89416. * This module describes the decoder layers provided by libFLAC.
  89417. *
  89418. * The stream decoder can be used to decode complete streams either from
  89419. * the client via callbacks, or directly from a file, depending on how
  89420. * it is initialized. When decoding via callbacks, the client provides
  89421. * callbacks for reading FLAC data and writing decoded samples, and
  89422. * handling metadata and errors. If the client also supplies seek-related
  89423. * callback, the decoder function for sample-accurate seeking within the
  89424. * FLAC input is also available. When decoding from a file, the client
  89425. * needs only supply a filename or open \c FILE* and write/metadata/error
  89426. * callbacks; the rest of the callbacks are supplied internally. For more
  89427. * info see the \link flac_stream_decoder stream decoder \endlink module.
  89428. */
  89429. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  89430. * \ingroup flac_decoder
  89431. *
  89432. * \brief
  89433. * This module contains the functions which implement the stream
  89434. * decoder.
  89435. *
  89436. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  89437. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  89438. *
  89439. * The basic usage of this decoder is as follows:
  89440. * - The program creates an instance of a decoder using
  89441. * FLAC__stream_decoder_new().
  89442. * - The program overrides the default settings using
  89443. * FLAC__stream_decoder_set_*() functions.
  89444. * - The program initializes the instance to validate the settings and
  89445. * prepare for decoding using
  89446. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  89447. * or FLAC__stream_decoder_init_file() for native FLAC,
  89448. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  89449. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  89450. * - The program calls the FLAC__stream_decoder_process_*() functions
  89451. * to decode data, which subsequently calls the callbacks.
  89452. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  89453. * which flushes the input and output and resets the decoder to the
  89454. * uninitialized state.
  89455. * - The instance may be used again or deleted with
  89456. * FLAC__stream_decoder_delete().
  89457. *
  89458. * In more detail, the program will create a new instance by calling
  89459. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  89460. * functions to override the default decoder options, and call
  89461. * one of the FLAC__stream_decoder_init_*() functions.
  89462. *
  89463. * There are three initialization functions for native FLAC, one for
  89464. * setting up the decoder to decode FLAC data from the client via
  89465. * callbacks, and two for decoding directly from a FLAC file.
  89466. *
  89467. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  89468. * You must also supply several callbacks for handling I/O. Some (like
  89469. * seeking) are optional, depending on the capabilities of the input.
  89470. *
  89471. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  89472. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  89473. * \c FILE* or filename and fewer callbacks; the decoder will handle
  89474. * the other callbacks internally.
  89475. *
  89476. * There are three similarly-named init functions for decoding from Ogg
  89477. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  89478. * library has been built with Ogg support.
  89479. *
  89480. * Once the decoder is initialized, your program will call one of several
  89481. * functions to start the decoding process:
  89482. *
  89483. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  89484. * most one metadata block or audio frame and return, calling either the
  89485. * metadata callback or write callback, respectively, once. If the decoder
  89486. * loses sync it will return with only the error callback being called.
  89487. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  89488. * to process the stream from the current location and stop upon reaching
  89489. * the first audio frame. The client will get one metadata, write, or error
  89490. * callback per metadata block, audio frame, or sync error, respectively.
  89491. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  89492. * to process the stream from the current location until the read callback
  89493. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  89494. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  89495. * write, or error callback per metadata block, audio frame, or sync error,
  89496. * respectively.
  89497. *
  89498. * When the decoder has finished decoding (normally or through an abort),
  89499. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  89500. * ensures the decoder is in the correct state and frees memory. Then the
  89501. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  89502. * again to decode another stream.
  89503. *
  89504. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  89505. * At any point after the stream decoder has been initialized, the client can
  89506. * call this function to seek to an exact sample within the stream.
  89507. * Subsequently, the first time the write callback is called it will be
  89508. * passed a (possibly partial) block starting at that sample.
  89509. *
  89510. * If the client cannot seek via the callback interface provided, but still
  89511. * has another way of seeking, it can flush the decoder using
  89512. * FLAC__stream_decoder_flush() and start feeding data from the new position
  89513. * through the read callback.
  89514. *
  89515. * The stream decoder also provides MD5 signature checking. If this is
  89516. * turned on before initialization, FLAC__stream_decoder_finish() will
  89517. * report when the decoded MD5 signature does not match the one stored
  89518. * in the STREAMINFO block. MD5 checking is automatically turned off
  89519. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  89520. * in the STREAMINFO block or when a seek is attempted.
  89521. *
  89522. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  89523. * attention. By default, the decoder only calls the metadata_callback for
  89524. * the STREAMINFO block. These functions allow you to tell the decoder
  89525. * explicitly which blocks to parse and return via the metadata_callback
  89526. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  89527. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  89528. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  89529. * which blocks to return. Remember that metadata blocks can potentially
  89530. * be big (for example, cover art) so filtering out the ones you don't
  89531. * use can reduce the memory requirements of the decoder. Also note the
  89532. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  89533. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  89534. * filtering APPLICATION blocks based on the application ID.
  89535. *
  89536. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  89537. * they still can legally be filtered from the metadata_callback.
  89538. *
  89539. * \note
  89540. * The "set" functions may only be called when the decoder is in the
  89541. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  89542. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  89543. * before FLAC__stream_decoder_init_*(). If this is the case they will
  89544. * return \c true, otherwise \c false.
  89545. *
  89546. * \note
  89547. * FLAC__stream_decoder_finish() resets all settings to the constructor
  89548. * defaults, including the callbacks.
  89549. *
  89550. * \{
  89551. */
  89552. /** State values for a FLAC__StreamDecoder
  89553. *
  89554. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  89555. */
  89556. typedef enum {
  89557. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  89558. /**< The decoder is ready to search for metadata. */
  89559. FLAC__STREAM_DECODER_READ_METADATA,
  89560. /**< The decoder is ready to or is in the process of reading metadata. */
  89561. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  89562. /**< The decoder is ready to or is in the process of searching for the
  89563. * frame sync code.
  89564. */
  89565. FLAC__STREAM_DECODER_READ_FRAME,
  89566. /**< The decoder is ready to or is in the process of reading a frame. */
  89567. FLAC__STREAM_DECODER_END_OF_STREAM,
  89568. /**< The decoder has reached the end of the stream. */
  89569. FLAC__STREAM_DECODER_OGG_ERROR,
  89570. /**< An error occurred in the underlying Ogg layer. */
  89571. FLAC__STREAM_DECODER_SEEK_ERROR,
  89572. /**< An error occurred while seeking. The decoder must be flushed
  89573. * with FLAC__stream_decoder_flush() or reset with
  89574. * FLAC__stream_decoder_reset() before decoding can continue.
  89575. */
  89576. FLAC__STREAM_DECODER_ABORTED,
  89577. /**< The decoder was aborted by the read callback. */
  89578. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  89579. /**< An error occurred allocating memory. The decoder is in an invalid
  89580. * state and can no longer be used.
  89581. */
  89582. FLAC__STREAM_DECODER_UNINITIALIZED
  89583. /**< The decoder is in the uninitialized state; one of the
  89584. * FLAC__stream_decoder_init_*() functions must be called before samples
  89585. * can be processed.
  89586. */
  89587. } FLAC__StreamDecoderState;
  89588. /** Maps a FLAC__StreamDecoderState to a C string.
  89589. *
  89590. * Using a FLAC__StreamDecoderState as the index to this array
  89591. * will give the string equivalent. The contents should not be modified.
  89592. */
  89593. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  89594. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  89595. */
  89596. typedef enum {
  89597. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  89598. /**< Initialization was successful. */
  89599. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  89600. /**< The library was not compiled with support for the given container
  89601. * format.
  89602. */
  89603. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  89604. /**< A required callback was not supplied. */
  89605. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  89606. /**< An error occurred allocating memory. */
  89607. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  89608. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  89609. * FLAC__stream_decoder_init_ogg_file(). */
  89610. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  89611. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  89612. * already initialized, usually because
  89613. * FLAC__stream_decoder_finish() was not called.
  89614. */
  89615. } FLAC__StreamDecoderInitStatus;
  89616. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  89617. *
  89618. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  89619. * will give the string equivalent. The contents should not be modified.
  89620. */
  89621. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  89622. /** Return values for the FLAC__StreamDecoder read callback.
  89623. */
  89624. typedef enum {
  89625. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  89626. /**< The read was OK and decoding can continue. */
  89627. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  89628. /**< The read was attempted while at the end of the stream. Note that
  89629. * the client must only return this value when the read callback was
  89630. * called when already at the end of the stream. Otherwise, if the read
  89631. * itself moves to the end of the stream, the client should still return
  89632. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  89633. * the next read callback it should return
  89634. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  89635. * of \c 0.
  89636. */
  89637. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  89638. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89639. } FLAC__StreamDecoderReadStatus;
  89640. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  89641. *
  89642. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  89643. * will give the string equivalent. The contents should not be modified.
  89644. */
  89645. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  89646. /** Return values for the FLAC__StreamDecoder seek callback.
  89647. */
  89648. typedef enum {
  89649. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  89650. /**< The seek was OK and decoding can continue. */
  89651. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  89652. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89653. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89654. /**< Client does not support seeking. */
  89655. } FLAC__StreamDecoderSeekStatus;
  89656. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  89657. *
  89658. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  89659. * will give the string equivalent. The contents should not be modified.
  89660. */
  89661. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  89662. /** Return values for the FLAC__StreamDecoder tell callback.
  89663. */
  89664. typedef enum {
  89665. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  89666. /**< The tell was OK and decoding can continue. */
  89667. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  89668. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89669. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89670. /**< Client does not support telling the position. */
  89671. } FLAC__StreamDecoderTellStatus;
  89672. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  89673. *
  89674. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  89675. * will give the string equivalent. The contents should not be modified.
  89676. */
  89677. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  89678. /** Return values for the FLAC__StreamDecoder length callback.
  89679. */
  89680. typedef enum {
  89681. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  89682. /**< The length call was OK and decoding can continue. */
  89683. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  89684. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89685. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89686. /**< Client does not support reporting the length. */
  89687. } FLAC__StreamDecoderLengthStatus;
  89688. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  89689. *
  89690. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  89691. * will give the string equivalent. The contents should not be modified.
  89692. */
  89693. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  89694. /** Return values for the FLAC__StreamDecoder write callback.
  89695. */
  89696. typedef enum {
  89697. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  89698. /**< The write was OK and decoding can continue. */
  89699. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  89700. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89701. } FLAC__StreamDecoderWriteStatus;
  89702. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  89703. *
  89704. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  89705. * will give the string equivalent. The contents should not be modified.
  89706. */
  89707. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  89708. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  89709. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  89710. * all. The rest could be caused by bad sync (false synchronization on
  89711. * data that is not the start of a frame) or corrupted data. The error
  89712. * itself is the decoder's best guess at what happened assuming a correct
  89713. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  89714. * could be caused by a correct sync on the start of a frame, but some
  89715. * data in the frame header was corrupted. Or it could be the result of
  89716. * syncing on a point the stream that looked like the starting of a frame
  89717. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89718. * could be because the decoder encountered a valid frame made by a future
  89719. * version of the encoder which it cannot parse, or because of a false
  89720. * sync making it appear as though an encountered frame was generated by
  89721. * a future encoder.
  89722. */
  89723. typedef enum {
  89724. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  89725. /**< An error in the stream caused the decoder to lose synchronization. */
  89726. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  89727. /**< The decoder encountered a corrupted frame header. */
  89728. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  89729. /**< The frame's data did not match the CRC in the footer. */
  89730. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89731. /**< The decoder encountered reserved fields in use in the stream. */
  89732. } FLAC__StreamDecoderErrorStatus;
  89733. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  89734. *
  89735. * Using a FLAC__StreamDecoderErrorStatus 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__StreamDecoderErrorStatusString[];
  89739. /***********************************************************************
  89740. *
  89741. * class FLAC__StreamDecoder
  89742. *
  89743. ***********************************************************************/
  89744. struct FLAC__StreamDecoderProtected;
  89745. struct FLAC__StreamDecoderPrivate;
  89746. /** The opaque structure definition for the stream decoder type.
  89747. * See the \link flac_stream_decoder stream decoder module \endlink
  89748. * for a detailed description.
  89749. */
  89750. typedef struct {
  89751. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  89752. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  89753. } FLAC__StreamDecoder;
  89754. /** Signature for the read callback.
  89755. *
  89756. * A function pointer matching this signature must be passed to
  89757. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89758. * called when the decoder needs more input data. The address of the
  89759. * buffer to be filled is supplied, along with the number of bytes the
  89760. * buffer can hold. The callback may choose to supply less data and
  89761. * modify the byte count but must be careful not to overflow the buffer.
  89762. * The callback then returns a status code chosen from
  89763. * FLAC__StreamDecoderReadStatus.
  89764. *
  89765. * Here is an example of a read callback for stdio streams:
  89766. * \code
  89767. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  89768. * {
  89769. * FILE *file = ((MyClientData*)client_data)->file;
  89770. * if(*bytes > 0) {
  89771. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  89772. * if(ferror(file))
  89773. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89774. * else if(*bytes == 0)
  89775. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  89776. * else
  89777. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  89778. * }
  89779. * else
  89780. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  89781. * }
  89782. * \endcode
  89783. *
  89784. * \note In general, FLAC__StreamDecoder functions which change the
  89785. * state should not be called on the \a decoder while in the callback.
  89786. *
  89787. * \param decoder The decoder instance calling the callback.
  89788. * \param buffer A pointer to a location for the callee to store
  89789. * data to be decoded.
  89790. * \param bytes A pointer to the size of the buffer. On entry
  89791. * to the callback, it contains the maximum number
  89792. * of bytes that may be stored in \a buffer. The
  89793. * callee must set it to the actual number of bytes
  89794. * stored (0 in case of error or end-of-stream) before
  89795. * returning.
  89796. * \param client_data The callee's client data set through
  89797. * FLAC__stream_decoder_init_*().
  89798. * \retval FLAC__StreamDecoderReadStatus
  89799. * The callee's return status. Note that the callback should return
  89800. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  89801. * zero bytes were read and there is no more data to be read.
  89802. */
  89803. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  89804. /** Signature for the seek callback.
  89805. *
  89806. * A function pointer matching this signature may be passed to
  89807. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89808. * called when the decoder needs to seek the input stream. The decoder
  89809. * will pass the absolute byte offset to seek to, 0 meaning the
  89810. * beginning of the stream.
  89811. *
  89812. * Here is an example of a seek callback for stdio streams:
  89813. * \code
  89814. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  89815. * {
  89816. * FILE *file = ((MyClientData*)client_data)->file;
  89817. * if(file == stdin)
  89818. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  89819. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  89820. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  89821. * else
  89822. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  89823. * }
  89824. * \endcode
  89825. *
  89826. * \note In general, FLAC__StreamDecoder functions which change the
  89827. * state should not be called on the \a decoder while in the callback.
  89828. *
  89829. * \param decoder The decoder instance calling the callback.
  89830. * \param absolute_byte_offset The offset from the beginning of the stream
  89831. * to seek to.
  89832. * \param client_data The callee's client data set through
  89833. * FLAC__stream_decoder_init_*().
  89834. * \retval FLAC__StreamDecoderSeekStatus
  89835. * The callee's return status.
  89836. */
  89837. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  89838. /** Signature for the tell callback.
  89839. *
  89840. * A function pointer matching this signature may be passed to
  89841. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89842. * called when the decoder wants to know the current position of the
  89843. * stream. The callback should return the byte offset from the
  89844. * beginning of the stream.
  89845. *
  89846. * Here is an example of a tell callback for stdio streams:
  89847. * \code
  89848. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  89849. * {
  89850. * FILE *file = ((MyClientData*)client_data)->file;
  89851. * off_t pos;
  89852. * if(file == stdin)
  89853. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  89854. * else if((pos = ftello(file)) < 0)
  89855. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  89856. * else {
  89857. * *absolute_byte_offset = (FLAC__uint64)pos;
  89858. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  89859. * }
  89860. * }
  89861. * \endcode
  89862. *
  89863. * \note In general, FLAC__StreamDecoder functions which change the
  89864. * state should not be called on the \a decoder while in the callback.
  89865. *
  89866. * \param decoder The decoder instance calling the callback.
  89867. * \param absolute_byte_offset A pointer to storage for the current offset
  89868. * from the beginning of the stream.
  89869. * \param client_data The callee's client data set through
  89870. * FLAC__stream_decoder_init_*().
  89871. * \retval FLAC__StreamDecoderTellStatus
  89872. * The callee's return status.
  89873. */
  89874. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  89875. /** Signature for the length callback.
  89876. *
  89877. * A function pointer matching this signature may be passed to
  89878. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89879. * called when the decoder wants to know the total length of the stream
  89880. * in bytes.
  89881. *
  89882. * Here is an example of a length callback for stdio streams:
  89883. * \code
  89884. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  89885. * {
  89886. * FILE *file = ((MyClientData*)client_data)->file;
  89887. * struct stat filestats;
  89888. *
  89889. * if(file == stdin)
  89890. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  89891. * else if(fstat(fileno(file), &filestats) != 0)
  89892. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  89893. * else {
  89894. * *stream_length = (FLAC__uint64)filestats.st_size;
  89895. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  89896. * }
  89897. * }
  89898. * \endcode
  89899. *
  89900. * \note In general, FLAC__StreamDecoder functions which change the
  89901. * state should not be called on the \a decoder while in the callback.
  89902. *
  89903. * \param decoder The decoder instance calling the callback.
  89904. * \param stream_length A pointer to storage for the length of the stream
  89905. * in bytes.
  89906. * \param client_data The callee's client data set through
  89907. * FLAC__stream_decoder_init_*().
  89908. * \retval FLAC__StreamDecoderLengthStatus
  89909. * The callee's return status.
  89910. */
  89911. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  89912. /** Signature for the EOF callback.
  89913. *
  89914. * A function pointer matching this signature may be passed to
  89915. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89916. * called when the decoder needs to know if the end of the stream has
  89917. * been reached.
  89918. *
  89919. * Here is an example of a EOF callback for stdio streams:
  89920. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  89921. * \code
  89922. * {
  89923. * FILE *file = ((MyClientData*)client_data)->file;
  89924. * return feof(file)? true : false;
  89925. * }
  89926. * \endcode
  89927. *
  89928. * \note In general, FLAC__StreamDecoder functions which change the
  89929. * state should not be called on the \a decoder while in the callback.
  89930. *
  89931. * \param decoder The decoder instance calling the callback.
  89932. * \param client_data The callee's client data set through
  89933. * FLAC__stream_decoder_init_*().
  89934. * \retval FLAC__bool
  89935. * \c true if the currently at the end of the stream, else \c false.
  89936. */
  89937. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  89938. /** Signature for the write callback.
  89939. *
  89940. * A function pointer matching this signature must be passed to one of
  89941. * the FLAC__stream_decoder_init_*() functions.
  89942. * The supplied function will be called when the decoder has decoded a
  89943. * single audio frame. The decoder will pass the frame metadata as well
  89944. * as an array of pointers (one for each channel) pointing to the
  89945. * decoded audio.
  89946. *
  89947. * \note In general, FLAC__StreamDecoder functions which change the
  89948. * state should not be called on the \a decoder while in the callback.
  89949. *
  89950. * \param decoder The decoder instance calling the callback.
  89951. * \param frame The description of the decoded frame. See
  89952. * FLAC__Frame.
  89953. * \param buffer An array of pointers to decoded channels of data.
  89954. * Each pointer will point to an array of signed
  89955. * samples of length \a frame->header.blocksize.
  89956. * Channels will be ordered according to the FLAC
  89957. * specification; see the documentation for the
  89958. * <A HREF="../format.html#frame_header">frame header</A>.
  89959. * \param client_data The callee's client data set through
  89960. * FLAC__stream_decoder_init_*().
  89961. * \retval FLAC__StreamDecoderWriteStatus
  89962. * The callee's return status.
  89963. */
  89964. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  89965. /** Signature for the metadata callback.
  89966. *
  89967. * A function pointer matching this signature must be passed to one of
  89968. * the FLAC__stream_decoder_init_*() functions.
  89969. * The supplied function will be called when the decoder has decoded a
  89970. * metadata block. In a valid FLAC file there will always be one
  89971. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  89972. * These will be supplied by the decoder in the same order as they
  89973. * appear in the stream and always before the first audio frame (i.e.
  89974. * write callback). The metadata block that is passed in must not be
  89975. * modified, and it doesn't live beyond the callback, so you should make
  89976. * a copy of it with FLAC__metadata_object_clone() if you will need it
  89977. * elsewhere. Since metadata blocks can potentially be large, by
  89978. * default the decoder only calls the metadata callback for the
  89979. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  89980. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  89981. *
  89982. * \note In general, FLAC__StreamDecoder functions which change the
  89983. * state should not be called on the \a decoder while in the callback.
  89984. *
  89985. * \param decoder The decoder instance calling the callback.
  89986. * \param metadata The decoded metadata block.
  89987. * \param client_data The callee's client data set through
  89988. * FLAC__stream_decoder_init_*().
  89989. */
  89990. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  89991. /** Signature for the error callback.
  89992. *
  89993. * A function pointer matching this signature must be passed to one of
  89994. * the FLAC__stream_decoder_init_*() functions.
  89995. * The supplied function will be called whenever an error occurs during
  89996. * decoding.
  89997. *
  89998. * \note In general, FLAC__StreamDecoder functions which change the
  89999. * state should not be called on the \a decoder while in the callback.
  90000. *
  90001. * \param decoder The decoder instance calling the callback.
  90002. * \param status The error encountered by the decoder.
  90003. * \param client_data The callee's client data set through
  90004. * FLAC__stream_decoder_init_*().
  90005. */
  90006. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  90007. /***********************************************************************
  90008. *
  90009. * Class constructor/destructor
  90010. *
  90011. ***********************************************************************/
  90012. /** Create a new stream decoder instance. The instance is created with
  90013. * default settings; see the individual FLAC__stream_decoder_set_*()
  90014. * functions for each setting's default.
  90015. *
  90016. * \retval FLAC__StreamDecoder*
  90017. * \c NULL if there was an error allocating memory, else the new instance.
  90018. */
  90019. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  90020. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  90021. *
  90022. * \param decoder A pointer to an existing decoder.
  90023. * \assert
  90024. * \code decoder != NULL \endcode
  90025. */
  90026. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  90027. /***********************************************************************
  90028. *
  90029. * Public class method prototypes
  90030. *
  90031. ***********************************************************************/
  90032. /** Set the serial number for the FLAC stream within the Ogg container.
  90033. * The default behavior is to use the serial number of the first Ogg
  90034. * page. Setting a serial number here will explicitly specify which
  90035. * stream is to be decoded.
  90036. *
  90037. * \note
  90038. * This does not need to be set for native FLAC decoding.
  90039. *
  90040. * \default \c use serial number of first page
  90041. * \param decoder A decoder instance to set.
  90042. * \param serial_number See above.
  90043. * \assert
  90044. * \code decoder != NULL \endcode
  90045. * \retval FLAC__bool
  90046. * \c false if the decoder is already initialized, else \c true.
  90047. */
  90048. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  90049. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  90050. * compute the MD5 signature of the unencoded audio data while decoding
  90051. * and compare it to the signature from the STREAMINFO block, if it
  90052. * exists, during FLAC__stream_decoder_finish().
  90053. *
  90054. * MD5 signature checking will be turned off (until the next
  90055. * FLAC__stream_decoder_reset()) if there is no signature in the
  90056. * STREAMINFO block or when a seek is attempted.
  90057. *
  90058. * Clients that do not use the MD5 check should leave this off to speed
  90059. * up decoding.
  90060. *
  90061. * \default \c false
  90062. * \param decoder A decoder instance to set.
  90063. * \param value Flag value (see above).
  90064. * \assert
  90065. * \code decoder != NULL \endcode
  90066. * \retval FLAC__bool
  90067. * \c false if the decoder is already initialized, else \c true.
  90068. */
  90069. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  90070. /** Direct the decoder to pass on all metadata blocks of type \a type.
  90071. *
  90072. * \default By default, only the \c STREAMINFO block is returned via the
  90073. * metadata callback.
  90074. * \param decoder A decoder instance to set.
  90075. * \param type See above.
  90076. * \assert
  90077. * \code decoder != NULL \endcode
  90078. * \a type is valid
  90079. * \retval FLAC__bool
  90080. * \c false if the decoder is already initialized, else \c true.
  90081. */
  90082. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  90083. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  90084. * given \a id.
  90085. *
  90086. * \default By default, only the \c STREAMINFO block is returned via the
  90087. * metadata callback.
  90088. * \param decoder A decoder instance to set.
  90089. * \param id See above.
  90090. * \assert
  90091. * \code decoder != NULL \endcode
  90092. * \code id != NULL \endcode
  90093. * \retval FLAC__bool
  90094. * \c false if the decoder is already initialized, else \c true.
  90095. */
  90096. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  90097. /** Direct the decoder to pass on all metadata blocks of any type.
  90098. *
  90099. * \default By default, only the \c STREAMINFO block is returned via the
  90100. * metadata callback.
  90101. * \param decoder A decoder instance to set.
  90102. * \assert
  90103. * \code decoder != NULL \endcode
  90104. * \retval FLAC__bool
  90105. * \c false if the decoder is already initialized, else \c true.
  90106. */
  90107. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  90108. /** Direct the decoder to filter out all metadata blocks of type \a type.
  90109. *
  90110. * \default By default, only the \c STREAMINFO block is returned via the
  90111. * metadata callback.
  90112. * \param decoder A decoder instance to set.
  90113. * \param type See above.
  90114. * \assert
  90115. * \code decoder != NULL \endcode
  90116. * \a type is valid
  90117. * \retval FLAC__bool
  90118. * \c false if the decoder is already initialized, else \c true.
  90119. */
  90120. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  90121. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  90122. * the given \a id.
  90123. *
  90124. * \default By default, only the \c STREAMINFO block is returned via the
  90125. * metadata callback.
  90126. * \param decoder A decoder instance to set.
  90127. * \param id See above.
  90128. * \assert
  90129. * \code decoder != NULL \endcode
  90130. * \code id != NULL \endcode
  90131. * \retval FLAC__bool
  90132. * \c false if the decoder is already initialized, else \c true.
  90133. */
  90134. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  90135. /** Direct the decoder to filter out all metadata blocks of any type.
  90136. *
  90137. * \default By default, only the \c STREAMINFO block is returned via the
  90138. * metadata callback.
  90139. * \param decoder A decoder instance to set.
  90140. * \assert
  90141. * \code decoder != NULL \endcode
  90142. * \retval FLAC__bool
  90143. * \c false if the decoder is already initialized, else \c true.
  90144. */
  90145. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  90146. /** Get the current decoder state.
  90147. *
  90148. * \param decoder A decoder instance to query.
  90149. * \assert
  90150. * \code decoder != NULL \endcode
  90151. * \retval FLAC__StreamDecoderState
  90152. * The current decoder state.
  90153. */
  90154. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  90155. /** Get the current decoder state as a C string.
  90156. *
  90157. * \param decoder A decoder instance to query.
  90158. * \assert
  90159. * \code decoder != NULL \endcode
  90160. * \retval const char *
  90161. * The decoder state as a C string. Do not modify the contents.
  90162. */
  90163. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  90164. /** Get the "MD5 signature checking" flag.
  90165. * This is the value of the setting, not whether or not the decoder is
  90166. * currently checking the MD5 (remember, it can be turned off automatically
  90167. * by a seek). When the decoder is reset the flag will be restored to the
  90168. * value returned by this function.
  90169. *
  90170. * \param decoder A decoder instance to query.
  90171. * \assert
  90172. * \code decoder != NULL \endcode
  90173. * \retval FLAC__bool
  90174. * See above.
  90175. */
  90176. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  90177. /** Get the total number of samples in the stream being decoded.
  90178. * Will only be valid after decoding has started and will contain the
  90179. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  90180. *
  90181. * \param decoder A decoder instance to query.
  90182. * \assert
  90183. * \code decoder != NULL \endcode
  90184. * \retval unsigned
  90185. * See above.
  90186. */
  90187. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  90188. /** Get the current number of channels in the stream being decoded.
  90189. * Will only be valid after decoding has started and will contain the
  90190. * value from the most recently decoded frame header.
  90191. *
  90192. * \param decoder A decoder instance to query.
  90193. * \assert
  90194. * \code decoder != NULL \endcode
  90195. * \retval unsigned
  90196. * See above.
  90197. */
  90198. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  90199. /** Get the current channel assignment in the stream being decoded.
  90200. * Will only be valid after decoding has started and will contain the
  90201. * value from the most recently decoded frame header.
  90202. *
  90203. * \param decoder A decoder instance to query.
  90204. * \assert
  90205. * \code decoder != NULL \endcode
  90206. * \retval FLAC__ChannelAssignment
  90207. * See above.
  90208. */
  90209. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  90210. /** Get the current sample resolution in the stream being decoded.
  90211. * Will only be valid after decoding has started and will contain the
  90212. * value from the most recently decoded frame header.
  90213. *
  90214. * \param decoder A decoder instance to query.
  90215. * \assert
  90216. * \code decoder != NULL \endcode
  90217. * \retval unsigned
  90218. * See above.
  90219. */
  90220. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  90221. /** Get the current sample rate in Hz of the stream being decoded.
  90222. * Will only be valid after decoding has started and will contain the
  90223. * value from the most recently decoded frame header.
  90224. *
  90225. * \param decoder A decoder instance to query.
  90226. * \assert
  90227. * \code decoder != NULL \endcode
  90228. * \retval unsigned
  90229. * See above.
  90230. */
  90231. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  90232. /** Get the current blocksize of the stream being decoded.
  90233. * Will only be valid after decoding has started and will contain the
  90234. * value from the most recently decoded frame header.
  90235. *
  90236. * \param decoder A decoder instance to query.
  90237. * \assert
  90238. * \code decoder != NULL \endcode
  90239. * \retval unsigned
  90240. * See above.
  90241. */
  90242. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  90243. /** Returns the decoder's current read position within the stream.
  90244. * The position is the byte offset from the start of the stream.
  90245. * Bytes before this position have been fully decoded. Note that
  90246. * there may still be undecoded bytes in the decoder's read FIFO.
  90247. * The returned position is correct even after a seek.
  90248. *
  90249. * \warning This function currently only works for native FLAC,
  90250. * not Ogg FLAC streams.
  90251. *
  90252. * \param decoder A decoder instance to query.
  90253. * \param position Address at which to return the desired position.
  90254. * \assert
  90255. * \code decoder != NULL \endcode
  90256. * \code position != NULL \endcode
  90257. * \retval FLAC__bool
  90258. * \c true if successful, \c false if the stream is not native FLAC,
  90259. * or there was an error from the 'tell' callback or it returned
  90260. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  90261. */
  90262. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  90263. /** Initialize the decoder instance to decode native FLAC streams.
  90264. *
  90265. * This flavor of initialization sets up the decoder to decode from a
  90266. * native FLAC stream. I/O is performed via callbacks to the client.
  90267. * For decoding from a plain file via filename or open FILE*,
  90268. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  90269. * provide a simpler interface.
  90270. *
  90271. * This function should be called after FLAC__stream_decoder_new() and
  90272. * FLAC__stream_decoder_set_*() but before any of the
  90273. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90274. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90275. * if initialization succeeded.
  90276. *
  90277. * \param decoder An uninitialized decoder instance.
  90278. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90279. * pointer must not be \c NULL.
  90280. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90281. * pointer may be \c NULL if seeking is not
  90282. * supported. If \a seek_callback is not \c NULL then a
  90283. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90284. * Alternatively, a dummy seek callback that just
  90285. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90286. * may also be supplied, all though this is slightly
  90287. * less efficient for the decoder.
  90288. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90289. * pointer may be \c NULL if not supported by the client. If
  90290. * \a seek_callback is not \c NULL then a
  90291. * \a tell_callback must also be supplied.
  90292. * Alternatively, a dummy tell callback that just
  90293. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90294. * may also be supplied, all though this is slightly
  90295. * less efficient for the decoder.
  90296. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90297. * pointer may be \c NULL if not supported by the client. If
  90298. * \a seek_callback is not \c NULL then a
  90299. * \a length_callback must also be supplied.
  90300. * Alternatively, a dummy length callback that just
  90301. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90302. * may also be supplied, all though this is slightly
  90303. * less efficient for the decoder.
  90304. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90305. * pointer may be \c NULL if not supported by the client. If
  90306. * \a seek_callback is not \c NULL then a
  90307. * \a eof_callback must also be supplied.
  90308. * Alternatively, a dummy length callback that just
  90309. * returns \c false
  90310. * may also be supplied, all though this is slightly
  90311. * less efficient for the decoder.
  90312. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90313. * pointer must not be \c NULL.
  90314. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90315. * pointer may be \c NULL if the callback is not
  90316. * desired.
  90317. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90318. * pointer must not be \c NULL.
  90319. * \param client_data This value will be supplied to callbacks in their
  90320. * \a client_data argument.
  90321. * \assert
  90322. * \code decoder != NULL \endcode
  90323. * \retval FLAC__StreamDecoderInitStatus
  90324. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90325. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90326. */
  90327. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  90328. FLAC__StreamDecoder *decoder,
  90329. FLAC__StreamDecoderReadCallback read_callback,
  90330. FLAC__StreamDecoderSeekCallback seek_callback,
  90331. FLAC__StreamDecoderTellCallback tell_callback,
  90332. FLAC__StreamDecoderLengthCallback length_callback,
  90333. FLAC__StreamDecoderEofCallback eof_callback,
  90334. FLAC__StreamDecoderWriteCallback write_callback,
  90335. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90336. FLAC__StreamDecoderErrorCallback error_callback,
  90337. void *client_data
  90338. );
  90339. /** Initialize the decoder instance to decode Ogg FLAC streams.
  90340. *
  90341. * This flavor of initialization sets up the decoder to decode from a
  90342. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  90343. * client. For decoding from a plain file via filename or open FILE*,
  90344. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  90345. * provide a simpler interface.
  90346. *
  90347. * This function should be called after FLAC__stream_decoder_new() and
  90348. * FLAC__stream_decoder_set_*() but before any of the
  90349. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90350. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90351. * if initialization succeeded.
  90352. *
  90353. * \note Support for Ogg FLAC in the library is optional. If this
  90354. * library has been built without support for Ogg FLAC, this function
  90355. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90356. *
  90357. * \param decoder An uninitialized decoder instance.
  90358. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90359. * pointer must not be \c NULL.
  90360. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90361. * pointer may be \c NULL if seeking is not
  90362. * supported. If \a seek_callback is not \c NULL then a
  90363. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90364. * Alternatively, a dummy seek callback that just
  90365. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90366. * may also be supplied, all though this is slightly
  90367. * less efficient for the decoder.
  90368. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90369. * pointer may be \c NULL if not supported by the client. If
  90370. * \a seek_callback is not \c NULL then a
  90371. * \a tell_callback must also be supplied.
  90372. * Alternatively, a dummy tell callback that just
  90373. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90374. * may also be supplied, all though this is slightly
  90375. * less efficient for the decoder.
  90376. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90377. * pointer may be \c NULL if not supported by the client. If
  90378. * \a seek_callback is not \c NULL then a
  90379. * \a length_callback must also be supplied.
  90380. * Alternatively, a dummy length callback that just
  90381. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90382. * may also be supplied, all though this is slightly
  90383. * less efficient for the decoder.
  90384. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90385. * pointer may be \c NULL if not supported by the client. If
  90386. * \a seek_callback is not \c NULL then a
  90387. * \a eof_callback must also be supplied.
  90388. * Alternatively, a dummy length callback that just
  90389. * returns \c false
  90390. * may also be supplied, all though this is slightly
  90391. * less efficient for the decoder.
  90392. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90393. * pointer must not be \c NULL.
  90394. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90395. * pointer may be \c NULL if the callback is not
  90396. * desired.
  90397. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90398. * pointer must not be \c NULL.
  90399. * \param client_data This value will be supplied to callbacks in their
  90400. * \a client_data argument.
  90401. * \assert
  90402. * \code decoder != NULL \endcode
  90403. * \retval FLAC__StreamDecoderInitStatus
  90404. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90405. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90406. */
  90407. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  90408. FLAC__StreamDecoder *decoder,
  90409. FLAC__StreamDecoderReadCallback read_callback,
  90410. FLAC__StreamDecoderSeekCallback seek_callback,
  90411. FLAC__StreamDecoderTellCallback tell_callback,
  90412. FLAC__StreamDecoderLengthCallback length_callback,
  90413. FLAC__StreamDecoderEofCallback eof_callback,
  90414. FLAC__StreamDecoderWriteCallback write_callback,
  90415. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90416. FLAC__StreamDecoderErrorCallback error_callback,
  90417. void *client_data
  90418. );
  90419. /** Initialize the decoder instance to decode native FLAC files.
  90420. *
  90421. * This flavor of initialization sets up the decoder to decode from a
  90422. * plain native FLAC file. For non-stdio streams, you must use
  90423. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  90424. *
  90425. * This function should be called after FLAC__stream_decoder_new() and
  90426. * FLAC__stream_decoder_set_*() but before any of the
  90427. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90428. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90429. * if initialization succeeded.
  90430. *
  90431. * \param decoder An uninitialized decoder instance.
  90432. * \param file An open FLAC file. The file should have been
  90433. * opened with mode \c "rb" and rewound. The file
  90434. * becomes owned by the decoder and should not be
  90435. * manipulated by the client while decoding.
  90436. * Unless \a file is \c stdin, it will be closed
  90437. * when FLAC__stream_decoder_finish() is called.
  90438. * Note however that seeking will not work when
  90439. * decoding from \c stdout since it is not seekable.
  90440. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90441. * pointer must not be \c NULL.
  90442. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90443. * pointer may be \c NULL if the callback is not
  90444. * desired.
  90445. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90446. * pointer must not be \c NULL.
  90447. * \param client_data This value will be supplied to callbacks in their
  90448. * \a client_data argument.
  90449. * \assert
  90450. * \code decoder != NULL \endcode
  90451. * \code file != NULL \endcode
  90452. * \retval FLAC__StreamDecoderInitStatus
  90453. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90454. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90455. */
  90456. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  90457. FLAC__StreamDecoder *decoder,
  90458. FILE *file,
  90459. FLAC__StreamDecoderWriteCallback write_callback,
  90460. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90461. FLAC__StreamDecoderErrorCallback error_callback,
  90462. void *client_data
  90463. );
  90464. /** Initialize the decoder instance to decode Ogg FLAC files.
  90465. *
  90466. * This flavor of initialization sets up the decoder to decode from a
  90467. * plain Ogg FLAC file. For non-stdio streams, you must use
  90468. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  90469. *
  90470. * This function should be called after FLAC__stream_decoder_new() and
  90471. * FLAC__stream_decoder_set_*() but before any of the
  90472. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90473. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90474. * if initialization succeeded.
  90475. *
  90476. * \note Support for Ogg FLAC in the library is optional. If this
  90477. * library has been built without support for Ogg FLAC, this function
  90478. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90479. *
  90480. * \param decoder An uninitialized decoder instance.
  90481. * \param file An open FLAC file. The file should have been
  90482. * opened with mode \c "rb" and rewound. The file
  90483. * becomes owned by the decoder and should not be
  90484. * manipulated by the client while decoding.
  90485. * Unless \a file is \c stdin, it will be closed
  90486. * when FLAC__stream_decoder_finish() is called.
  90487. * Note however that seeking will not work when
  90488. * decoding from \c stdout since it is not seekable.
  90489. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90490. * pointer must not be \c NULL.
  90491. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90492. * pointer may be \c NULL if the callback is not
  90493. * desired.
  90494. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90495. * pointer must not be \c NULL.
  90496. * \param client_data This value will be supplied to callbacks in their
  90497. * \a client_data argument.
  90498. * \assert
  90499. * \code decoder != NULL \endcode
  90500. * \code file != NULL \endcode
  90501. * \retval FLAC__StreamDecoderInitStatus
  90502. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90503. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90504. */
  90505. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  90506. FLAC__StreamDecoder *decoder,
  90507. FILE *file,
  90508. FLAC__StreamDecoderWriteCallback write_callback,
  90509. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90510. FLAC__StreamDecoderErrorCallback error_callback,
  90511. void *client_data
  90512. );
  90513. /** Initialize the decoder instance to decode native FLAC files.
  90514. *
  90515. * This flavor of initialization sets up the decoder to decode from a plain
  90516. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90517. * example, with Unicode filenames on Windows), you must use
  90518. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  90519. * and provide callbacks for the I/O.
  90520. *
  90521. * This function should be called after FLAC__stream_decoder_new() and
  90522. * FLAC__stream_decoder_set_*() but before any of the
  90523. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90524. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90525. * if initialization succeeded.
  90526. *
  90527. * \param decoder An uninitialized decoder instance.
  90528. * \param filename The name of the file to decode from. The file will
  90529. * be opened with fopen(). Use \c NULL to decode from
  90530. * \c stdin. Note that \c stdin is not seekable.
  90531. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90532. * pointer must not be \c NULL.
  90533. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90534. * pointer may be \c NULL if the callback is not
  90535. * desired.
  90536. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90537. * pointer must not be \c NULL.
  90538. * \param client_data This value will be supplied to callbacks in their
  90539. * \a client_data argument.
  90540. * \assert
  90541. * \code decoder != NULL \endcode
  90542. * \retval FLAC__StreamDecoderInitStatus
  90543. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90544. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90545. */
  90546. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  90547. FLAC__StreamDecoder *decoder,
  90548. const char *filename,
  90549. FLAC__StreamDecoderWriteCallback write_callback,
  90550. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90551. FLAC__StreamDecoderErrorCallback error_callback,
  90552. void *client_data
  90553. );
  90554. /** Initialize the decoder instance to decode Ogg FLAC files.
  90555. *
  90556. * This flavor of initialization sets up the decoder to decode from a plain
  90557. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90558. * example, with Unicode filenames on Windows), you must use
  90559. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  90560. * and provide callbacks for the I/O.
  90561. *
  90562. * This function should be called after FLAC__stream_decoder_new() and
  90563. * FLAC__stream_decoder_set_*() but before any of the
  90564. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90565. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90566. * if initialization succeeded.
  90567. *
  90568. * \note Support for Ogg FLAC in the library is optional. If this
  90569. * library has been built without support for Ogg FLAC, this function
  90570. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90571. *
  90572. * \param decoder An uninitialized decoder instance.
  90573. * \param filename The name of the file to decode from. The file will
  90574. * be opened with fopen(). Use \c NULL to decode from
  90575. * \c stdin. Note that \c stdin is not seekable.
  90576. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90577. * pointer must not be \c NULL.
  90578. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90579. * pointer may be \c NULL if the callback is not
  90580. * desired.
  90581. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90582. * pointer must not be \c NULL.
  90583. * \param client_data This value will be supplied to callbacks in their
  90584. * \a client_data argument.
  90585. * \assert
  90586. * \code decoder != NULL \endcode
  90587. * \retval FLAC__StreamDecoderInitStatus
  90588. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90589. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90590. */
  90591. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  90592. FLAC__StreamDecoder *decoder,
  90593. const char *filename,
  90594. FLAC__StreamDecoderWriteCallback write_callback,
  90595. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90596. FLAC__StreamDecoderErrorCallback error_callback,
  90597. void *client_data
  90598. );
  90599. /** Finish the decoding process.
  90600. * Flushes the decoding buffer, releases resources, resets the decoder
  90601. * settings to their defaults, and returns the decoder state to
  90602. * FLAC__STREAM_DECODER_UNINITIALIZED.
  90603. *
  90604. * In the event of a prematurely-terminated decode, it is not strictly
  90605. * necessary to call this immediately before FLAC__stream_decoder_delete()
  90606. * but it is good practice to match every FLAC__stream_decoder_init_*()
  90607. * with a FLAC__stream_decoder_finish().
  90608. *
  90609. * \param decoder An uninitialized decoder instance.
  90610. * \assert
  90611. * \code decoder != NULL \endcode
  90612. * \retval FLAC__bool
  90613. * \c false if MD5 checking is on AND a STREAMINFO block was available
  90614. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  90615. * signature does not match the one computed by the decoder; else
  90616. * \c true.
  90617. */
  90618. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  90619. /** Flush the stream input.
  90620. * The decoder's input buffer will be cleared and the state set to
  90621. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  90622. * off MD5 checking.
  90623. *
  90624. * \param decoder A decoder instance.
  90625. * \assert
  90626. * \code decoder != NULL \endcode
  90627. * \retval FLAC__bool
  90628. * \c true if successful, else \c false if a memory allocation
  90629. * error occurs (in which case the state will be set to
  90630. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  90631. */
  90632. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  90633. /** Reset the decoding process.
  90634. * The decoder's input buffer will be cleared and the state set to
  90635. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  90636. * FLAC__stream_decoder_finish() except that the settings are
  90637. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  90638. * before decoding again. MD5 checking will be restored to its original
  90639. * setting.
  90640. *
  90641. * If the decoder is seekable, or was initialized with
  90642. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  90643. * the decoder will also attempt to seek to the beginning of the file.
  90644. * If this rewind fails, this function will return \c false. It follows
  90645. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  90646. * \c stdin.
  90647. *
  90648. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  90649. * and is not seekable (i.e. no seek callback was provided or the seek
  90650. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  90651. * is the duty of the client to start feeding data from the beginning of
  90652. * the stream on the next FLAC__stream_decoder_process() or
  90653. * FLAC__stream_decoder_process_interleaved() call.
  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 occurs
  90660. * (in which case the state will be set to
  90661. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  90662. * occurs (the state will be unchanged).
  90663. */
  90664. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  90665. /** Decode one metadata block or audio frame.
  90666. * This version instructs the decoder to decode a either a single metadata
  90667. * block or a single frame and stop, unless the callbacks return a fatal
  90668. * error or the read callback returns
  90669. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90670. *
  90671. * As the decoder needs more input it will call the read callback.
  90672. * Depending on what was decoded, the metadata or write callback will be
  90673. * called with the decoded metadata block or audio frame.
  90674. *
  90675. * Unless there is a fatal read error or end of stream, this function
  90676. * will return once one whole frame is decoded. In other words, if the
  90677. * stream is not synchronized or points to a corrupt frame header, the
  90678. * decoder will continue to try and resync until it gets to a valid
  90679. * frame, then decode one frame, then return. If the decoder points to
  90680. * a frame whose frame CRC in the frame footer does not match the
  90681. * computed frame CRC, this function will issue a
  90682. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  90683. * error callback, and return, having decoded one complete, although
  90684. * corrupt, frame. (Such corrupted frames are sent as silence of the
  90685. * correct length to the write callback.)
  90686. *
  90687. * \param decoder An initialized decoder instance.
  90688. * \assert
  90689. * \code decoder != NULL \endcode
  90690. * \retval FLAC__bool
  90691. * \c false if any fatal read, write, or memory allocation error
  90692. * occurred (meaning decoding must stop), else \c true; for more
  90693. * information about the decoder, check the decoder state with
  90694. * FLAC__stream_decoder_get_state().
  90695. */
  90696. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  90697. /** Decode until the end of the metadata.
  90698. * This version instructs the decoder to decode from the current position
  90699. * and continue until all the metadata has been read, or until the
  90700. * callbacks return a fatal error or the read callback returns
  90701. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90702. *
  90703. * As the decoder needs more input it will call the read callback.
  90704. * As each metadata block is decoded, the metadata callback will be called
  90705. * with the decoded metadata.
  90706. *
  90707. * \param decoder An initialized decoder instance.
  90708. * \assert
  90709. * \code decoder != NULL \endcode
  90710. * \retval FLAC__bool
  90711. * \c false if any fatal read, write, or memory allocation error
  90712. * occurred (meaning decoding must stop), else \c true; for more
  90713. * information about the decoder, check the decoder state with
  90714. * FLAC__stream_decoder_get_state().
  90715. */
  90716. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  90717. /** Decode until the end of the stream.
  90718. * This version instructs the decoder to decode from the current position
  90719. * and continue until the end of stream (the read callback returns
  90720. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  90721. * callbacks return a fatal error.
  90722. *
  90723. * As the decoder needs more input it will call the read callback.
  90724. * As each metadata block and frame is decoded, the metadata or write
  90725. * callback will be called with the decoded metadata or frame.
  90726. *
  90727. * \param decoder An initialized decoder instance.
  90728. * \assert
  90729. * \code decoder != NULL \endcode
  90730. * \retval FLAC__bool
  90731. * \c false if any fatal read, write, or memory allocation error
  90732. * occurred (meaning decoding must stop), else \c true; for more
  90733. * information about the decoder, check the decoder state with
  90734. * FLAC__stream_decoder_get_state().
  90735. */
  90736. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  90737. /** Skip one audio frame.
  90738. * This version instructs the decoder to 'skip' a single frame and stop,
  90739. * unless the callbacks return a fatal error or the read callback returns
  90740. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90741. *
  90742. * The decoding flow is the same as what occurs when
  90743. * FLAC__stream_decoder_process_single() is called to process an audio
  90744. * frame, except that this function does not decode the parsed data into
  90745. * PCM or call the write callback. The integrity of the frame is still
  90746. * checked the same way as in the other process functions.
  90747. *
  90748. * This function will return once one whole frame is skipped, in the
  90749. * same way that FLAC__stream_decoder_process_single() will return once
  90750. * one whole frame is decoded.
  90751. *
  90752. * This function can be used in more quickly determining FLAC frame
  90753. * boundaries when decoding of the actual data is not needed, for
  90754. * example when an application is separating a FLAC stream into frames
  90755. * for editing or storing in a container. To do this, the application
  90756. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  90757. * to the next frame, then use
  90758. * FLAC__stream_decoder_get_decode_position() to find the new frame
  90759. * boundary.
  90760. *
  90761. * This function should only be called when the stream has advanced
  90762. * past all the metadata, otherwise it will return \c false.
  90763. *
  90764. * \param decoder An initialized decoder instance not in a metadata
  90765. * state.
  90766. * \assert
  90767. * \code decoder != NULL \endcode
  90768. * \retval FLAC__bool
  90769. * \c false if any fatal read, write, or memory allocation error
  90770. * occurred (meaning decoding must stop), or if the decoder
  90771. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  90772. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  90773. * information about the decoder, check the decoder state with
  90774. * FLAC__stream_decoder_get_state().
  90775. */
  90776. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  90777. /** Flush the input and seek to an absolute sample.
  90778. * Decoding will resume at the given sample. Note that because of
  90779. * this, the next write callback may contain a partial block. The
  90780. * client must support seeking the input or this function will fail
  90781. * and return \c false. Furthermore, if the decoder state is
  90782. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  90783. * with FLAC__stream_decoder_flush() or reset with
  90784. * FLAC__stream_decoder_reset() before decoding can continue.
  90785. *
  90786. * \param decoder A decoder instance.
  90787. * \param sample The target sample number to seek to.
  90788. * \assert
  90789. * \code decoder != NULL \endcode
  90790. * \retval FLAC__bool
  90791. * \c true if successful, else \c false.
  90792. */
  90793. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  90794. /* \} */
  90795. #ifdef __cplusplus
  90796. }
  90797. #endif
  90798. #endif
  90799. /*** End of inlined file: stream_decoder.h ***/
  90800. /*** Start of inlined file: stream_encoder.h ***/
  90801. #ifndef FLAC__STREAM_ENCODER_H
  90802. #define FLAC__STREAM_ENCODER_H
  90803. #include <stdio.h> /* for FILE */
  90804. #ifdef __cplusplus
  90805. extern "C" {
  90806. #endif
  90807. /** \file include/FLAC/stream_encoder.h
  90808. *
  90809. * \brief
  90810. * This module contains the functions which implement the stream
  90811. * encoder.
  90812. *
  90813. * See the detailed documentation in the
  90814. * \link flac_stream_encoder stream encoder \endlink module.
  90815. */
  90816. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  90817. * \ingroup flac
  90818. *
  90819. * \brief
  90820. * This module describes the encoder layers provided by libFLAC.
  90821. *
  90822. * The stream encoder can be used to encode complete streams either to the
  90823. * client via callbacks, or directly to a file, depending on how it is
  90824. * initialized. When encoding via callbacks, the client provides a write
  90825. * callback which will be called whenever FLAC data is ready to be written.
  90826. * If the client also supplies a seek callback, the encoder will also
  90827. * automatically handle the writing back of metadata discovered while
  90828. * encoding, like stream info, seek points offsets, etc. When encoding to
  90829. * a file, the client needs only supply a filename or open \c FILE* and an
  90830. * optional progress callback for periodic notification of progress; the
  90831. * write and seek callbacks are supplied internally. For more info see the
  90832. * \link flac_stream_encoder stream encoder \endlink module.
  90833. */
  90834. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  90835. * \ingroup flac_encoder
  90836. *
  90837. * \brief
  90838. * This module contains the functions which implement the stream
  90839. * encoder.
  90840. *
  90841. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  90842. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  90843. *
  90844. * The basic usage of this encoder is as follows:
  90845. * - The program creates an instance of an encoder using
  90846. * FLAC__stream_encoder_new().
  90847. * - The program overrides the default settings using
  90848. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  90849. * functions should be called:
  90850. * - FLAC__stream_encoder_set_channels()
  90851. * - FLAC__stream_encoder_set_bits_per_sample()
  90852. * - FLAC__stream_encoder_set_sample_rate()
  90853. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  90854. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  90855. * - If the application wants to control the compression level or set its own
  90856. * metadata, then the following should also be called:
  90857. * - FLAC__stream_encoder_set_compression_level()
  90858. * - FLAC__stream_encoder_set_verify()
  90859. * - FLAC__stream_encoder_set_metadata()
  90860. * - The rest of the set functions should only be called if the client needs
  90861. * exact control over how the audio is compressed; thorough understanding
  90862. * of the FLAC format is necessary to achieve good results.
  90863. * - The program initializes the instance to validate the settings and
  90864. * prepare for encoding using
  90865. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  90866. * or FLAC__stream_encoder_init_file() for native FLAC
  90867. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  90868. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  90869. * - The program calls FLAC__stream_encoder_process() or
  90870. * FLAC__stream_encoder_process_interleaved() to encode data, which
  90871. * subsequently calls the callbacks when there is encoder data ready
  90872. * to be written.
  90873. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  90874. * which causes the encoder to encode any data still in its input pipe,
  90875. * update the metadata with the final encoding statistics if output
  90876. * seeking is possible, and finally reset the encoder to the
  90877. * uninitialized state.
  90878. * - The instance may be used again or deleted with
  90879. * FLAC__stream_encoder_delete().
  90880. *
  90881. * In more detail, the stream encoder functions similarly to the
  90882. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  90883. * callbacks and more options. Typically the client will create a new
  90884. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  90885. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  90886. * calling one of the FLAC__stream_encoder_init_*() functions.
  90887. *
  90888. * Unlike the decoders, the stream encoder has many options that can
  90889. * affect the speed and compression ratio. When setting these parameters
  90890. * you should have some basic knowledge of the format (see the
  90891. * <A HREF="../documentation.html#format">user-level documentation</A>
  90892. * or the <A HREF="../format.html">formal description</A>). The
  90893. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  90894. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  90895. * functions will do this, so make sure to pay attention to the state
  90896. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  90897. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  90898. * before FLAC__stream_encoder_init_*() will take on the defaults from
  90899. * the constructor.
  90900. *
  90901. * There are three initialization functions for native FLAC, one for
  90902. * setting up the encoder to encode FLAC data to the client via
  90903. * callbacks, and two for encoding directly to a file.
  90904. *
  90905. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  90906. * You must also supply a write callback which will be called anytime
  90907. * there is raw encoded data to write. If the client can seek the output
  90908. * it is best to also supply seek and tell callbacks, as this allows the
  90909. * encoder to go back after encoding is finished to write back
  90910. * information that was collected while encoding, like seek point offsets,
  90911. * frame sizes, etc.
  90912. *
  90913. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  90914. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  90915. * filename or open \c FILE*; the encoder will handle all the callbacks
  90916. * internally. You may also supply a progress callback for periodic
  90917. * notification of the encoding progress.
  90918. *
  90919. * There are three similarly-named init functions for encoding to Ogg
  90920. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  90921. * library has been built with Ogg support.
  90922. *
  90923. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  90924. * call the write callback several times, once with the \c fLaC signature,
  90925. * and once for each encoded metadata block. Note that for Ogg FLAC
  90926. * encoding you will usually get at least twice the number of callbacks than
  90927. * with native FLAC, one for the Ogg page header and one for the page body.
  90928. *
  90929. * After initializing the instance, the client may feed audio data to the
  90930. * encoder in one of two ways:
  90931. *
  90932. * - Channel separate, through FLAC__stream_encoder_process() - The client
  90933. * will pass an array of pointers to buffers, one for each channel, to
  90934. * the encoder, each of the same length. The samples need not be
  90935. * block-aligned, but each channel should have the same number of samples.
  90936. * - Channel interleaved, through
  90937. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  90938. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  90939. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  90940. * Again, the samples need not be block-aligned but they must be
  90941. * sample-aligned, i.e. the first value should be channel0_sample0 and
  90942. * the last value channelN_sampleM.
  90943. *
  90944. * Note that for either process call, each sample in the buffers should be a
  90945. * signed integer, right-justified to the resolution set by
  90946. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  90947. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  90948. *
  90949. * When the client is finished encoding data, it calls
  90950. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  90951. * data still in its input pipe, and call the metadata callback with the
  90952. * final encoding statistics. Then the instance may be deleted with
  90953. * FLAC__stream_encoder_delete() or initialized again to encode another
  90954. * stream.
  90955. *
  90956. * For programs that write their own metadata, but that do not know the
  90957. * actual metadata until after encoding, it is advantageous to instruct
  90958. * the encoder to write a PADDING block of the correct size, so that
  90959. * instead of rewriting the whole stream after encoding, the program can
  90960. * just overwrite the PADDING block. If only the maximum size of the
  90961. * metadata is known, the program can write a slightly larger padding
  90962. * block, then split it after encoding.
  90963. *
  90964. * Make sure you understand how lengths are calculated. All FLAC metadata
  90965. * blocks have a 4 byte header which contains the type and length. This
  90966. * length does not include the 4 bytes of the header. See the format page
  90967. * for the specification of metadata blocks and their lengths.
  90968. *
  90969. * \note
  90970. * If you are writing the FLAC data to a file via callbacks, make sure it
  90971. * is open for update (e.g. mode "w+" for stdio streams). This is because
  90972. * after the first encoding pass, the encoder will try to seek back to the
  90973. * beginning of the stream, to the STREAMINFO block, to write some data
  90974. * there. (If using FLAC__stream_encoder_init*_file() or
  90975. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  90976. *
  90977. * \note
  90978. * The "set" functions may only be called when the encoder is in the
  90979. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  90980. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  90981. * before FLAC__stream_encoder_init_*(). If this is the case they will
  90982. * return \c true, otherwise \c false.
  90983. *
  90984. * \note
  90985. * FLAC__stream_encoder_finish() resets all settings to the constructor
  90986. * defaults.
  90987. *
  90988. * \{
  90989. */
  90990. /** State values for a FLAC__StreamEncoder.
  90991. *
  90992. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  90993. *
  90994. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  90995. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  90996. * must be deleted with FLAC__stream_encoder_delete().
  90997. */
  90998. typedef enum {
  90999. FLAC__STREAM_ENCODER_OK = 0,
  91000. /**< The encoder is in the normal OK state and samples can be processed. */
  91001. FLAC__STREAM_ENCODER_UNINITIALIZED,
  91002. /**< The encoder is in the uninitialized state; one of the
  91003. * FLAC__stream_encoder_init_*() functions must be called before samples
  91004. * can be processed.
  91005. */
  91006. FLAC__STREAM_ENCODER_OGG_ERROR,
  91007. /**< An error occurred in the underlying Ogg layer. */
  91008. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  91009. /**< An error occurred in the underlying verify stream decoder;
  91010. * check FLAC__stream_encoder_get_verify_decoder_state().
  91011. */
  91012. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  91013. /**< The verify decoder detected a mismatch between the original
  91014. * audio signal and the decoded audio signal.
  91015. */
  91016. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  91017. /**< One of the callbacks returned a fatal error. */
  91018. FLAC__STREAM_ENCODER_IO_ERROR,
  91019. /**< An I/O error occurred while opening/reading/writing a file.
  91020. * Check \c errno.
  91021. */
  91022. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  91023. /**< An error occurred while writing the stream; usually, the
  91024. * write_callback returned an error.
  91025. */
  91026. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  91027. /**< Memory allocation failed. */
  91028. } FLAC__StreamEncoderState;
  91029. /** Maps a FLAC__StreamEncoderState to a C string.
  91030. *
  91031. * Using a FLAC__StreamEncoderState as the index to this array
  91032. * will give the string equivalent. The contents should not be modified.
  91033. */
  91034. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  91035. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  91036. */
  91037. typedef enum {
  91038. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  91039. /**< Initialization was successful. */
  91040. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  91041. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  91042. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  91043. /**< The library was not compiled with support for the given container
  91044. * format.
  91045. */
  91046. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  91047. /**< A required callback was not supplied. */
  91048. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  91049. /**< The encoder has an invalid setting for number of channels. */
  91050. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  91051. /**< The encoder has an invalid setting for bits-per-sample.
  91052. * FLAC supports 4-32 bps but the reference encoder currently supports
  91053. * only up to 24 bps.
  91054. */
  91055. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  91056. /**< The encoder has an invalid setting for the input sample rate. */
  91057. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  91058. /**< The encoder has an invalid setting for the block size. */
  91059. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  91060. /**< The encoder has an invalid setting for the maximum LPC order. */
  91061. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  91062. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  91063. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  91064. /**< The specified block size is less than the maximum LPC order. */
  91065. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  91066. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  91067. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  91068. /**< The metadata input to the encoder is invalid, in one of the following ways:
  91069. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  91070. * - One of the metadata blocks contains an undefined type
  91071. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  91072. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  91073. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  91074. */
  91075. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  91076. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  91077. * already initialized, usually because
  91078. * FLAC__stream_encoder_finish() was not called.
  91079. */
  91080. } FLAC__StreamEncoderInitStatus;
  91081. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  91082. *
  91083. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  91084. * will give the string equivalent. The contents should not be modified.
  91085. */
  91086. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  91087. /** Return values for the FLAC__StreamEncoder read callback.
  91088. */
  91089. typedef enum {
  91090. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  91091. /**< The read was OK and decoding can continue. */
  91092. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  91093. /**< The read was attempted at the end of the stream. */
  91094. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  91095. /**< An unrecoverable error occurred. */
  91096. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  91097. /**< Client does not support reading back from the output. */
  91098. } FLAC__StreamEncoderReadStatus;
  91099. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  91100. *
  91101. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  91102. * will give the string equivalent. The contents should not be modified.
  91103. */
  91104. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  91105. /** Return values for the FLAC__StreamEncoder write callback.
  91106. */
  91107. typedef enum {
  91108. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  91109. /**< The write was OK and encoding can continue. */
  91110. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  91111. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  91112. } FLAC__StreamEncoderWriteStatus;
  91113. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  91114. *
  91115. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  91116. * will give the string equivalent. The contents should not be modified.
  91117. */
  91118. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  91119. /** Return values for the FLAC__StreamEncoder seek callback.
  91120. */
  91121. typedef enum {
  91122. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  91123. /**< The seek was OK and encoding can continue. */
  91124. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  91125. /**< An unrecoverable error occurred. */
  91126. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91127. /**< Client does not support seeking. */
  91128. } FLAC__StreamEncoderSeekStatus;
  91129. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  91130. *
  91131. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  91132. * will give the string equivalent. The contents should not be modified.
  91133. */
  91134. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  91135. /** Return values for the FLAC__StreamEncoder tell callback.
  91136. */
  91137. typedef enum {
  91138. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  91139. /**< The tell was OK and encoding can continue. */
  91140. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  91141. /**< An unrecoverable error occurred. */
  91142. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91143. /**< Client does not support seeking. */
  91144. } FLAC__StreamEncoderTellStatus;
  91145. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  91146. *
  91147. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  91148. * will give the string equivalent. The contents should not be modified.
  91149. */
  91150. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  91151. /***********************************************************************
  91152. *
  91153. * class FLAC__StreamEncoder
  91154. *
  91155. ***********************************************************************/
  91156. struct FLAC__StreamEncoderProtected;
  91157. struct FLAC__StreamEncoderPrivate;
  91158. /** The opaque structure definition for the stream encoder type.
  91159. * See the \link flac_stream_encoder stream encoder module \endlink
  91160. * for a detailed description.
  91161. */
  91162. typedef struct {
  91163. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  91164. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  91165. } FLAC__StreamEncoder;
  91166. /** Signature for the read callback.
  91167. *
  91168. * A function pointer matching this signature must be passed to
  91169. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  91170. * The supplied function will be called when the encoder needs to read back
  91171. * encoded data. This happens during the metadata callback, when the encoder
  91172. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  91173. * while encoding. The address of the buffer to be filled is supplied, along
  91174. * with the number of bytes the buffer can hold. The callback may choose to
  91175. * supply less data and modify the byte count but must be careful not to
  91176. * overflow the buffer. The callback then returns a status code chosen from
  91177. * FLAC__StreamEncoderReadStatus.
  91178. *
  91179. * Here is an example of a read callback for stdio streams:
  91180. * \code
  91181. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  91182. * {
  91183. * FILE *file = ((MyClientData*)client_data)->file;
  91184. * if(*bytes > 0) {
  91185. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  91186. * if(ferror(file))
  91187. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  91188. * else if(*bytes == 0)
  91189. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  91190. * else
  91191. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  91192. * }
  91193. * else
  91194. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  91195. * }
  91196. * \endcode
  91197. *
  91198. * \note In general, FLAC__StreamEncoder functions which change the
  91199. * state should not be called on the \a encoder while in the callback.
  91200. *
  91201. * \param encoder The encoder instance calling the callback.
  91202. * \param buffer A pointer to a location for the callee to store
  91203. * data to be encoded.
  91204. * \param bytes A pointer to the size of the buffer. On entry
  91205. * to the callback, it contains the maximum number
  91206. * of bytes that may be stored in \a buffer. The
  91207. * callee must set it to the actual number of bytes
  91208. * stored (0 in case of error or end-of-stream) before
  91209. * returning.
  91210. * \param client_data The callee's client data set through
  91211. * FLAC__stream_encoder_set_client_data().
  91212. * \retval FLAC__StreamEncoderReadStatus
  91213. * The callee's return status.
  91214. */
  91215. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  91216. /** Signature for the write callback.
  91217. *
  91218. * A function pointer matching this signature must be passed to
  91219. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91220. * by the encoder anytime there is raw encoded data ready to write. It may
  91221. * include metadata mixed with encoded audio frames and the data is not
  91222. * guaranteed to be aligned on frame or metadata block boundaries.
  91223. *
  91224. * The only duty of the callback is to write out the \a bytes worth of data
  91225. * in \a buffer to the current position in the output stream. The arguments
  91226. * \a samples and \a current_frame are purely informational. If \a samples
  91227. * is greater than \c 0, then \a current_frame will hold the current frame
  91228. * number that is being written; otherwise it indicates that the write
  91229. * callback is being called to write metadata.
  91230. *
  91231. * \note
  91232. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  91233. * write callback will be called twice when writing each audio
  91234. * frame; once for the page header, and once for the page body.
  91235. * When writing the page header, the \a samples argument to the
  91236. * write callback will be \c 0.
  91237. *
  91238. * \note In general, FLAC__StreamEncoder functions which change the
  91239. * state should not be called on the \a encoder while in the callback.
  91240. *
  91241. * \param encoder The encoder instance calling the callback.
  91242. * \param buffer An array of encoded data of length \a bytes.
  91243. * \param bytes The byte length of \a buffer.
  91244. * \param samples The number of samples encoded by \a buffer.
  91245. * \c 0 has a special meaning; see above.
  91246. * \param current_frame The number of the current frame being encoded.
  91247. * \param client_data The callee's client data set through
  91248. * FLAC__stream_encoder_init_*().
  91249. * \retval FLAC__StreamEncoderWriteStatus
  91250. * The callee's return status.
  91251. */
  91252. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  91253. /** Signature for the seek callback.
  91254. *
  91255. * A function pointer matching this signature may be passed to
  91256. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91257. * when the encoder needs to seek the output stream. The encoder will pass
  91258. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  91259. *
  91260. * Here is an example of a seek callback for stdio streams:
  91261. * \code
  91262. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  91263. * {
  91264. * FILE *file = ((MyClientData*)client_data)->file;
  91265. * if(file == stdin)
  91266. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  91267. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  91268. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  91269. * else
  91270. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  91271. * }
  91272. * \endcode
  91273. *
  91274. * \note In general, FLAC__StreamEncoder functions which change the
  91275. * state should not be called on the \a encoder while in the callback.
  91276. *
  91277. * \param encoder The encoder instance calling the callback.
  91278. * \param absolute_byte_offset The offset from the beginning of the stream
  91279. * to seek to.
  91280. * \param client_data The callee's client data set through
  91281. * FLAC__stream_encoder_init_*().
  91282. * \retval FLAC__StreamEncoderSeekStatus
  91283. * The callee's return status.
  91284. */
  91285. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  91286. /** Signature for the tell callback.
  91287. *
  91288. * A function pointer matching this signature may be passed to
  91289. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91290. * when the encoder needs to know the current position of the output stream.
  91291. *
  91292. * \warning
  91293. * The callback must return the true current byte offset of the output to
  91294. * which the encoder is writing. If you are buffering the output, make
  91295. * sure and take this into account. If you are writing directly to a
  91296. * FILE* from your write callback, ftell() is sufficient. If you are
  91297. * writing directly to a file descriptor from your write callback, you
  91298. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  91299. * these points to rewrite metadata after encoding.
  91300. *
  91301. * Here is an example of a tell callback for stdio streams:
  91302. * \code
  91303. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  91304. * {
  91305. * FILE *file = ((MyClientData*)client_data)->file;
  91306. * off_t pos;
  91307. * if(file == stdin)
  91308. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  91309. * else if((pos = ftello(file)) < 0)
  91310. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  91311. * else {
  91312. * *absolute_byte_offset = (FLAC__uint64)pos;
  91313. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  91314. * }
  91315. * }
  91316. * \endcode
  91317. *
  91318. * \note In general, FLAC__StreamEncoder functions which change the
  91319. * state should not be called on the \a encoder while in the callback.
  91320. *
  91321. * \param encoder The encoder instance calling the callback.
  91322. * \param absolute_byte_offset The address at which to store the current
  91323. * position of the output.
  91324. * \param client_data The callee's client data set through
  91325. * FLAC__stream_encoder_init_*().
  91326. * \retval FLAC__StreamEncoderTellStatus
  91327. * The callee's return status.
  91328. */
  91329. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  91330. /** Signature for the metadata callback.
  91331. *
  91332. * A function pointer matching this signature may be passed to
  91333. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91334. * once at the end of encoding with the populated STREAMINFO structure. This
  91335. * is so the client can seek back to the beginning of the file and write the
  91336. * STREAMINFO block with the correct statistics after encoding (like
  91337. * minimum/maximum frame size and total samples).
  91338. *
  91339. * \note In general, FLAC__StreamEncoder functions which change the
  91340. * state should not be called on the \a encoder while in the callback.
  91341. *
  91342. * \param encoder The encoder instance calling the callback.
  91343. * \param metadata The final populated STREAMINFO block.
  91344. * \param client_data The callee's client data set through
  91345. * FLAC__stream_encoder_init_*().
  91346. */
  91347. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  91348. /** Signature for the progress callback.
  91349. *
  91350. * A function pointer matching this signature may be passed to
  91351. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  91352. * The supplied function will be called when the encoder has finished
  91353. * writing a frame. The \c total_frames_estimate argument to the
  91354. * callback will be based on the value from
  91355. * FLAC__stream_encoder_set_total_samples_estimate().
  91356. *
  91357. * \note In general, FLAC__StreamEncoder functions which change the
  91358. * state should not be called on the \a encoder while in the callback.
  91359. *
  91360. * \param encoder The encoder instance calling the callback.
  91361. * \param bytes_written Bytes written so far.
  91362. * \param samples_written Samples written so far.
  91363. * \param frames_written Frames written so far.
  91364. * \param total_frames_estimate The estimate of the total number of
  91365. * frames to be written.
  91366. * \param client_data The callee's client data set through
  91367. * FLAC__stream_encoder_init_*().
  91368. */
  91369. 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);
  91370. /***********************************************************************
  91371. *
  91372. * Class constructor/destructor
  91373. *
  91374. ***********************************************************************/
  91375. /** Create a new stream encoder instance. The instance is created with
  91376. * default settings; see the individual FLAC__stream_encoder_set_*()
  91377. * functions for each setting's default.
  91378. *
  91379. * \retval FLAC__StreamEncoder*
  91380. * \c NULL if there was an error allocating memory, else the new instance.
  91381. */
  91382. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  91383. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  91384. *
  91385. * \param encoder A pointer to an existing encoder.
  91386. * \assert
  91387. * \code encoder != NULL \endcode
  91388. */
  91389. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  91390. /***********************************************************************
  91391. *
  91392. * Public class method prototypes
  91393. *
  91394. ***********************************************************************/
  91395. /** Set the serial number for the FLAC stream to use in the Ogg container.
  91396. *
  91397. * \note
  91398. * This does not need to be set for native FLAC encoding.
  91399. *
  91400. * \note
  91401. * It is recommended to set a serial number explicitly as the default of '0'
  91402. * may collide with other streams.
  91403. *
  91404. * \default \c 0
  91405. * \param encoder An encoder instance to set.
  91406. * \param serial_number See above.
  91407. * \assert
  91408. * \code encoder != NULL \endcode
  91409. * \retval FLAC__bool
  91410. * \c false if the encoder is already initialized, else \c true.
  91411. */
  91412. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  91413. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  91414. * encoded output by feeding it through an internal decoder and comparing
  91415. * the original signal against the decoded signal. If a mismatch occurs,
  91416. * the process call will return \c false. Note that this will slow the
  91417. * encoding process by the extra time required for decoding and comparison.
  91418. *
  91419. * \default \c false
  91420. * \param encoder An encoder instance to set.
  91421. * \param value Flag value (see above).
  91422. * \assert
  91423. * \code encoder != NULL \endcode
  91424. * \retval FLAC__bool
  91425. * \c false if the encoder is already initialized, else \c true.
  91426. */
  91427. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91428. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  91429. * the encoder will comply with the Subset and will check the
  91430. * settings during FLAC__stream_encoder_init_*() to see if all settings
  91431. * comply. If \c false, the settings may take advantage of the full
  91432. * range that the format allows.
  91433. *
  91434. * Make sure you know what it entails before setting this to \c false.
  91435. *
  91436. * \default \c true
  91437. * \param encoder An encoder instance to set.
  91438. * \param value Flag value (see above).
  91439. * \assert
  91440. * \code encoder != NULL \endcode
  91441. * \retval FLAC__bool
  91442. * \c false if the encoder is already initialized, else \c true.
  91443. */
  91444. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91445. /** Set the number of channels to be encoded.
  91446. *
  91447. * \default \c 2
  91448. * \param encoder An encoder instance to set.
  91449. * \param value See above.
  91450. * \assert
  91451. * \code encoder != NULL \endcode
  91452. * \retval FLAC__bool
  91453. * \c false if the encoder is already initialized, else \c true.
  91454. */
  91455. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  91456. /** Set the sample resolution of the input to be encoded.
  91457. *
  91458. * \warning
  91459. * Do not feed the encoder data that is wider than the value you
  91460. * set here or you will generate an invalid stream.
  91461. *
  91462. * \default \c 16
  91463. * \param encoder An encoder instance to set.
  91464. * \param value See above.
  91465. * \assert
  91466. * \code encoder != NULL \endcode
  91467. * \retval FLAC__bool
  91468. * \c false if the encoder is already initialized, else \c true.
  91469. */
  91470. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  91471. /** Set the sample rate (in Hz) of the input to be encoded.
  91472. *
  91473. * \default \c 44100
  91474. * \param encoder An encoder instance to set.
  91475. * \param value See above.
  91476. * \assert
  91477. * \code encoder != NULL \endcode
  91478. * \retval FLAC__bool
  91479. * \c false if the encoder is already initialized, else \c true.
  91480. */
  91481. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  91482. /** Set the compression level
  91483. *
  91484. * The compression level is roughly proportional to the amount of effort
  91485. * the encoder expends to compress the file. A higher level usually
  91486. * means more computation but higher compression. The default level is
  91487. * suitable for most applications.
  91488. *
  91489. * Currently the levels range from \c 0 (fastest, least compression) to
  91490. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  91491. * treated as \c 8.
  91492. *
  91493. * This function automatically calls the following other \c _set_
  91494. * functions with appropriate values, so the client does not need to
  91495. * unless it specifically wants to override them:
  91496. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  91497. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  91498. * - FLAC__stream_encoder_set_apodization()
  91499. * - FLAC__stream_encoder_set_max_lpc_order()
  91500. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  91501. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  91502. * - FLAC__stream_encoder_set_do_escape_coding()
  91503. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  91504. * - FLAC__stream_encoder_set_min_residual_partition_order()
  91505. * - FLAC__stream_encoder_set_max_residual_partition_order()
  91506. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  91507. *
  91508. * The actual values set for each level are:
  91509. * <table>
  91510. * <tr>
  91511. * <td><b>level</b><td>
  91512. * <td>do mid-side stereo<td>
  91513. * <td>loose mid-side stereo<td>
  91514. * <td>apodization<td>
  91515. * <td>max lpc order<td>
  91516. * <td>qlp coeff precision<td>
  91517. * <td>qlp coeff prec search<td>
  91518. * <td>escape coding<td>
  91519. * <td>exhaustive model search<td>
  91520. * <td>min residual partition order<td>
  91521. * <td>max residual partition order<td>
  91522. * <td>rice parameter search dist<td>
  91523. * </tr>
  91524. * <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>
  91525. * <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>
  91526. * <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>
  91527. * <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>
  91528. * <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>
  91529. * <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>
  91530. * <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>
  91531. * <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>
  91532. * <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>
  91533. * </table>
  91534. *
  91535. * \default \c 5
  91536. * \param encoder An encoder instance to set.
  91537. * \param value See above.
  91538. * \assert
  91539. * \code encoder != NULL \endcode
  91540. * \retval FLAC__bool
  91541. * \c false if the encoder is already initialized, else \c true.
  91542. */
  91543. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  91544. /** Set the blocksize to use while encoding.
  91545. *
  91546. * The number of samples to use per frame. Use \c 0 to let the encoder
  91547. * estimate a blocksize; this is usually best.
  91548. *
  91549. * \default \c 0
  91550. * \param encoder An encoder instance to set.
  91551. * \param value See above.
  91552. * \assert
  91553. * \code encoder != NULL \endcode
  91554. * \retval FLAC__bool
  91555. * \c false if the encoder is already initialized, else \c true.
  91556. */
  91557. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  91558. /** Set to \c true to enable mid-side encoding on stereo input. The
  91559. * number of channels must be 2 for this to have any effect. Set to
  91560. * \c false to use only independent channel coding.
  91561. *
  91562. * \default \c false
  91563. * \param encoder An encoder instance to set.
  91564. * \param value Flag value (see above).
  91565. * \assert
  91566. * \code encoder != NULL \endcode
  91567. * \retval FLAC__bool
  91568. * \c false if the encoder is already initialized, else \c true.
  91569. */
  91570. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91571. /** Set to \c true to enable adaptive switching between mid-side and
  91572. * left-right encoding on stereo input. Set to \c false to use
  91573. * exhaustive searching. Setting this to \c true requires
  91574. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  91575. * \c true in order to have any effect.
  91576. *
  91577. * \default \c false
  91578. * \param encoder An encoder instance to set.
  91579. * \param value Flag value (see above).
  91580. * \assert
  91581. * \code encoder != NULL \endcode
  91582. * \retval FLAC__bool
  91583. * \c false if the encoder is already initialized, else \c true.
  91584. */
  91585. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91586. /** Sets the apodization function(s) the encoder will use when windowing
  91587. * audio data for LPC analysis.
  91588. *
  91589. * The \a specification is a plain ASCII string which specifies exactly
  91590. * which functions to use. There may be more than one (up to 32),
  91591. * separated by \c ';' characters. Some functions take one or more
  91592. * comma-separated arguments in parentheses.
  91593. *
  91594. * The available functions are \c bartlett, \c bartlett_hann,
  91595. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  91596. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  91597. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  91598. *
  91599. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  91600. * (0<STDDEV<=0.5).
  91601. *
  91602. * For \c tukey(P), P specifies the fraction of the window that is
  91603. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  91604. * corresponds to \c hann.
  91605. *
  91606. * Example specifications are \c "blackman" or
  91607. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  91608. *
  91609. * Any function that is specified erroneously is silently dropped. Up
  91610. * to 32 functions are kept, the rest are dropped. If the specification
  91611. * is empty the encoder defaults to \c "tukey(0.5)".
  91612. *
  91613. * When more than one function is specified, then for every subframe the
  91614. * encoder will try each of them separately and choose the window that
  91615. * results in the smallest compressed subframe.
  91616. *
  91617. * Note that each function specified causes the encoder to occupy a
  91618. * floating point array in which to store the window.
  91619. *
  91620. * \default \c "tukey(0.5)"
  91621. * \param encoder An encoder instance to set.
  91622. * \param specification See above.
  91623. * \assert
  91624. * \code encoder != NULL \endcode
  91625. * \code specification != NULL \endcode
  91626. * \retval FLAC__bool
  91627. * \c false if the encoder is already initialized, else \c true.
  91628. */
  91629. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  91630. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  91631. *
  91632. * \default \c 0
  91633. * \param encoder An encoder instance to set.
  91634. * \param value See above.
  91635. * \assert
  91636. * \code encoder != NULL \endcode
  91637. * \retval FLAC__bool
  91638. * \c false if the encoder is already initialized, else \c true.
  91639. */
  91640. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  91641. /** Set the precision, in bits, of the quantized linear predictor
  91642. * coefficients, or \c 0 to let the encoder select it based on the
  91643. * blocksize.
  91644. *
  91645. * \note
  91646. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  91647. * be less than 32.
  91648. *
  91649. * \default \c 0
  91650. * \param encoder An encoder instance to set.
  91651. * \param value See above.
  91652. * \assert
  91653. * \code encoder != NULL \endcode
  91654. * \retval FLAC__bool
  91655. * \c false if the encoder is already initialized, else \c true.
  91656. */
  91657. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  91658. /** Set to \c false to use only the specified quantized linear predictor
  91659. * coefficient precision, or \c true to search neighboring precision
  91660. * values and use the best one.
  91661. *
  91662. * \default \c false
  91663. * \param encoder An encoder instance to set.
  91664. * \param value See above.
  91665. * \assert
  91666. * \code encoder != NULL \endcode
  91667. * \retval FLAC__bool
  91668. * \c false if the encoder is already initialized, else \c true.
  91669. */
  91670. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91671. /** Deprecated. Setting this value has no effect.
  91672. *
  91673. * \default \c false
  91674. * \param encoder An encoder instance to set.
  91675. * \param value See above.
  91676. * \assert
  91677. * \code encoder != NULL \endcode
  91678. * \retval FLAC__bool
  91679. * \c false if the encoder is already initialized, else \c true.
  91680. */
  91681. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91682. /** Set to \c false to let the encoder estimate the best model order
  91683. * based on the residual signal energy, or \c true to force the
  91684. * encoder to evaluate all order models and select the best.
  91685. *
  91686. * \default \c false
  91687. * \param encoder An encoder instance to set.
  91688. * \param value See above.
  91689. * \assert
  91690. * \code encoder != NULL \endcode
  91691. * \retval FLAC__bool
  91692. * \c false if the encoder is already initialized, else \c true.
  91693. */
  91694. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91695. /** Set the minimum partition order to search when coding the residual.
  91696. * This is used in tandem with
  91697. * FLAC__stream_encoder_set_max_residual_partition_order().
  91698. *
  91699. * The partition order determines the context size in the residual.
  91700. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91701. *
  91702. * Set both min and max values to \c 0 to force a single context,
  91703. * whose Rice parameter is based on the residual signal variance.
  91704. * Otherwise, set a min and max order, and the encoder will search
  91705. * all orders, using the mean of each context for its Rice parameter,
  91706. * and use the best.
  91707. *
  91708. * \default \c 0
  91709. * \param encoder An encoder instance to set.
  91710. * \param value See above.
  91711. * \assert
  91712. * \code encoder != NULL \endcode
  91713. * \retval FLAC__bool
  91714. * \c false if the encoder is already initialized, else \c true.
  91715. */
  91716. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91717. /** Set the maximum partition order to search when coding the residual.
  91718. * This is used in tandem with
  91719. * FLAC__stream_encoder_set_min_residual_partition_order().
  91720. *
  91721. * The partition order determines the context size in the residual.
  91722. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91723. *
  91724. * Set both min and max values to \c 0 to force a single context,
  91725. * whose Rice parameter is based on the residual signal variance.
  91726. * Otherwise, set a min and max order, and the encoder will search
  91727. * all orders, using the mean of each context for its Rice parameter,
  91728. * and use the best.
  91729. *
  91730. * \default \c 0
  91731. * \param encoder An encoder instance to set.
  91732. * \param value See above.
  91733. * \assert
  91734. * \code encoder != NULL \endcode
  91735. * \retval FLAC__bool
  91736. * \c false if the encoder is already initialized, else \c true.
  91737. */
  91738. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91739. /** Deprecated. Setting this value has no effect.
  91740. *
  91741. * \default \c 0
  91742. * \param encoder An encoder instance to set.
  91743. * \param value See above.
  91744. * \assert
  91745. * \code encoder != NULL \endcode
  91746. * \retval FLAC__bool
  91747. * \c false if the encoder is already initialized, else \c true.
  91748. */
  91749. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  91750. /** Set an estimate of the total samples that will be encoded.
  91751. * This is merely an estimate and may be set to \c 0 if unknown.
  91752. * This value will be written to the STREAMINFO block before encoding,
  91753. * and can remove the need for the caller to rewrite the value later
  91754. * if the value is known before encoding.
  91755. *
  91756. * \default \c 0
  91757. * \param encoder An encoder instance to set.
  91758. * \param value See above.
  91759. * \assert
  91760. * \code encoder != NULL \endcode
  91761. * \retval FLAC__bool
  91762. * \c false if the encoder is already initialized, else \c true.
  91763. */
  91764. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  91765. /** Set the metadata blocks to be emitted to the stream before encoding.
  91766. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  91767. * array of pointers to metadata blocks. The array is non-const since
  91768. * the encoder may need to change the \a is_last flag inside them, and
  91769. * in some cases update seek point offsets. Otherwise, the encoder will
  91770. * not modify or free the blocks. It is up to the caller to free the
  91771. * metadata blocks after encoding finishes.
  91772. *
  91773. * \note
  91774. * The encoder stores only copies of the pointers in the \a metadata array;
  91775. * the metadata blocks themselves must survive at least until after
  91776. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  91777. *
  91778. * \note
  91779. * The STREAMINFO block is always written and no STREAMINFO block may
  91780. * occur in the supplied array.
  91781. *
  91782. * \note
  91783. * By default the encoder does not create a SEEKTABLE. If one is supplied
  91784. * in the \a metadata array, but the client has specified that it does not
  91785. * support seeking, then the SEEKTABLE will be written verbatim. However
  91786. * by itself this is not very useful as the client will not know the stream
  91787. * offsets for the seekpoints ahead of time. In order to get a proper
  91788. * seektable the client must support seeking. See next note.
  91789. *
  91790. * \note
  91791. * SEEKTABLE blocks are handled specially. Since you will not know
  91792. * the values for the seek point stream offsets, you should pass in
  91793. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  91794. * required sample numbers (or placeholder points), with \c 0 for the
  91795. * \a frame_samples and \a stream_offset fields for each point. If the
  91796. * client has specified that it supports seeking by providing a seek
  91797. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  91798. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  91799. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  91800. * then while it is encoding the encoder will fill the stream offsets in
  91801. * for you and when encoding is finished, it will seek back and write the
  91802. * real values into the SEEKTABLE block in the stream. There are helper
  91803. * routines for manipulating seektable template blocks; see metadata.h:
  91804. * FLAC__metadata_object_seektable_template_*(). If the client does
  91805. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  91806. * will slow down or remove the ability to seek in the FLAC stream.
  91807. *
  91808. * \note
  91809. * The encoder instance \b will modify the first \c SEEKTABLE block
  91810. * as it transforms the template to a valid seektable while encoding,
  91811. * but it is still up to the caller to free all metadata blocks after
  91812. * encoding.
  91813. *
  91814. * \note
  91815. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  91816. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  91817. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  91818. * will simply write it's own into the stream. If no VORBIS_COMMENT
  91819. * block is present in the \a metadata array, libFLAC will write an
  91820. * empty one, containing only the vendor string.
  91821. *
  91822. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  91823. * the second metadata block of the stream. The encoder already supplies
  91824. * the STREAMINFO block automatically. If \a metadata does not contain a
  91825. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  91826. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  91827. * first, the init function will reorder \a metadata by moving the
  91828. * VORBIS_COMMENT block to the front; the relative ordering of the other
  91829. * blocks will remain as they were.
  91830. *
  91831. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  91832. * stream to \c 65535. If \a num_blocks exceeds this the function will
  91833. * return \c false.
  91834. *
  91835. * \default \c NULL, 0
  91836. * \param encoder An encoder instance to set.
  91837. * \param metadata See above.
  91838. * \param num_blocks See above.
  91839. * \assert
  91840. * \code encoder != NULL \endcode
  91841. * \retval FLAC__bool
  91842. * \c false if the encoder is already initialized, else \c true.
  91843. * \c false if the encoder is already initialized, or if
  91844. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  91845. */
  91846. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  91847. /** Get the current encoder state.
  91848. *
  91849. * \param encoder An encoder instance to query.
  91850. * \assert
  91851. * \code encoder != NULL \endcode
  91852. * \retval FLAC__StreamEncoderState
  91853. * The current encoder state.
  91854. */
  91855. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  91856. /** Get the state of the verify stream decoder.
  91857. * Useful when the stream encoder state is
  91858. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  91859. *
  91860. * \param encoder An encoder instance to query.
  91861. * \assert
  91862. * \code encoder != NULL \endcode
  91863. * \retval FLAC__StreamDecoderState
  91864. * The verify stream decoder state.
  91865. */
  91866. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  91867. /** Get the current encoder state as a C string.
  91868. * This version automatically resolves
  91869. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  91870. * verify decoder's state.
  91871. *
  91872. * \param encoder A encoder instance to query.
  91873. * \assert
  91874. * \code encoder != NULL \endcode
  91875. * \retval const char *
  91876. * The encoder state as a C string. Do not modify the contents.
  91877. */
  91878. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  91879. /** Get relevant values about the nature of a verify decoder error.
  91880. * Useful when the stream encoder state is
  91881. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  91882. * be addresses in which the stats will be returned, or NULL if value
  91883. * is not desired.
  91884. *
  91885. * \param encoder An encoder instance to query.
  91886. * \param absolute_sample The absolute sample number of the mismatch.
  91887. * \param frame_number The number of the frame in which the mismatch occurred.
  91888. * \param channel The channel in which the mismatch occurred.
  91889. * \param sample The number of the sample (relative to the frame) in
  91890. * which the mismatch occurred.
  91891. * \param expected The expected value for the sample in question.
  91892. * \param got The actual value returned by the decoder.
  91893. * \assert
  91894. * \code encoder != NULL \endcode
  91895. */
  91896. 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);
  91897. /** Get the "verify" flag.
  91898. *
  91899. * \param encoder An encoder instance to query.
  91900. * \assert
  91901. * \code encoder != NULL \endcode
  91902. * \retval FLAC__bool
  91903. * See FLAC__stream_encoder_set_verify().
  91904. */
  91905. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  91906. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  91907. *
  91908. * \param encoder An encoder instance to query.
  91909. * \assert
  91910. * \code encoder != NULL \endcode
  91911. * \retval FLAC__bool
  91912. * See FLAC__stream_encoder_set_streamable_subset().
  91913. */
  91914. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  91915. /** Get the number of input channels being processed.
  91916. *
  91917. * \param encoder An encoder instance to query.
  91918. * \assert
  91919. * \code encoder != NULL \endcode
  91920. * \retval unsigned
  91921. * See FLAC__stream_encoder_set_channels().
  91922. */
  91923. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  91924. /** Get the input sample resolution setting.
  91925. *
  91926. * \param encoder An encoder instance to query.
  91927. * \assert
  91928. * \code encoder != NULL \endcode
  91929. * \retval unsigned
  91930. * See FLAC__stream_encoder_set_bits_per_sample().
  91931. */
  91932. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  91933. /** Get the input sample rate setting.
  91934. *
  91935. * \param encoder An encoder instance to query.
  91936. * \assert
  91937. * \code encoder != NULL \endcode
  91938. * \retval unsigned
  91939. * See FLAC__stream_encoder_set_sample_rate().
  91940. */
  91941. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  91942. /** Get the blocksize setting.
  91943. *
  91944. * \param encoder An encoder instance to query.
  91945. * \assert
  91946. * \code encoder != NULL \endcode
  91947. * \retval unsigned
  91948. * See FLAC__stream_encoder_set_blocksize().
  91949. */
  91950. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  91951. /** Get the "mid/side stereo coding" flag.
  91952. *
  91953. * \param encoder An encoder instance to query.
  91954. * \assert
  91955. * \code encoder != NULL \endcode
  91956. * \retval FLAC__bool
  91957. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  91958. */
  91959. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  91960. /** Get the "adaptive mid/side switching" flag.
  91961. *
  91962. * \param encoder An encoder instance to query.
  91963. * \assert
  91964. * \code encoder != NULL \endcode
  91965. * \retval FLAC__bool
  91966. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  91967. */
  91968. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  91969. /** Get the maximum LPC order setting.
  91970. *
  91971. * \param encoder An encoder instance to query.
  91972. * \assert
  91973. * \code encoder != NULL \endcode
  91974. * \retval unsigned
  91975. * See FLAC__stream_encoder_set_max_lpc_order().
  91976. */
  91977. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  91978. /** Get the quantized linear predictor coefficient precision setting.
  91979. *
  91980. * \param encoder An encoder instance to query.
  91981. * \assert
  91982. * \code encoder != NULL \endcode
  91983. * \retval unsigned
  91984. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  91985. */
  91986. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  91987. /** Get the qlp coefficient precision search flag.
  91988. *
  91989. * \param encoder An encoder instance to query.
  91990. * \assert
  91991. * \code encoder != NULL \endcode
  91992. * \retval FLAC__bool
  91993. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  91994. */
  91995. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  91996. /** Get the "escape coding" flag.
  91997. *
  91998. * \param encoder An encoder instance to query.
  91999. * \assert
  92000. * \code encoder != NULL \endcode
  92001. * \retval FLAC__bool
  92002. * See FLAC__stream_encoder_set_do_escape_coding().
  92003. */
  92004. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  92005. /** Get the exhaustive model search flag.
  92006. *
  92007. * \param encoder An encoder instance to query.
  92008. * \assert
  92009. * \code encoder != NULL \endcode
  92010. * \retval FLAC__bool
  92011. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  92012. */
  92013. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  92014. /** Get the minimum residual partition order setting.
  92015. *
  92016. * \param encoder An encoder instance to query.
  92017. * \assert
  92018. * \code encoder != NULL \endcode
  92019. * \retval unsigned
  92020. * See FLAC__stream_encoder_set_min_residual_partition_order().
  92021. */
  92022. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  92023. /** Get maximum residual partition order setting.
  92024. *
  92025. * \param encoder An encoder instance to query.
  92026. * \assert
  92027. * \code encoder != NULL \endcode
  92028. * \retval unsigned
  92029. * See FLAC__stream_encoder_set_max_residual_partition_order().
  92030. */
  92031. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  92032. /** Get the Rice parameter search distance setting.
  92033. *
  92034. * \param encoder An encoder instance to query.
  92035. * \assert
  92036. * \code encoder != NULL \endcode
  92037. * \retval unsigned
  92038. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  92039. */
  92040. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  92041. /** Get the previously set estimate of the total samples to be encoded.
  92042. * The encoder merely mimics back the value given to
  92043. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  92044. * other way of knowing how many samples the client will encode.
  92045. *
  92046. * \param encoder An encoder instance to set.
  92047. * \assert
  92048. * \code encoder != NULL \endcode
  92049. * \retval FLAC__uint64
  92050. * See FLAC__stream_encoder_get_total_samples_estimate().
  92051. */
  92052. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  92053. /** Initialize the encoder instance to encode native FLAC streams.
  92054. *
  92055. * This flavor of initialization sets up the encoder to encode to a
  92056. * native FLAC stream. I/O is performed via callbacks to the client.
  92057. * For encoding to a plain file via filename or open \c FILE*,
  92058. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  92059. * provide a simpler interface.
  92060. *
  92061. * This function should be called after FLAC__stream_encoder_new() and
  92062. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92063. * or FLAC__stream_encoder_process_interleaved().
  92064. * initialization succeeded.
  92065. *
  92066. * The call to FLAC__stream_encoder_init_stream() currently will also
  92067. * immediately call the write callback several times, once with the \c fLaC
  92068. * signature, and once for each encoded metadata block.
  92069. *
  92070. * \param encoder An uninitialized encoder instance.
  92071. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  92072. * pointer must not be \c NULL.
  92073. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  92074. * pointer may be \c NULL if seeking is not
  92075. * supported. The encoder uses seeking to go back
  92076. * and write some some stream statistics to the
  92077. * STREAMINFO block; this is recommended but not
  92078. * necessary to create a valid FLAC stream. If
  92079. * \a seek_callback is not \c NULL then a
  92080. * \a tell_callback must also be supplied.
  92081. * Alternatively, a dummy seek callback that just
  92082. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  92083. * may also be supplied, all though this is slightly
  92084. * less efficient for the encoder.
  92085. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  92086. * pointer may be \c NULL if seeking is not
  92087. * supported. If \a seek_callback is \c NULL then
  92088. * this argument will be ignored. If
  92089. * \a seek_callback is not \c NULL then a
  92090. * \a tell_callback must also be supplied.
  92091. * Alternatively, a dummy tell callback that just
  92092. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  92093. * may also be supplied, all though this is slightly
  92094. * less efficient for the encoder.
  92095. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  92096. * pointer may be \c NULL if the callback is not
  92097. * desired. If the client provides a seek callback,
  92098. * this function is not necessary as the encoder
  92099. * will automatically seek back and update the
  92100. * STREAMINFO block. It may also be \c NULL if the
  92101. * client does not support seeking, since it will
  92102. * have no way of going back to update the
  92103. * STREAMINFO. However the client can still supply
  92104. * a callback if it would like to know the details
  92105. * from the STREAMINFO.
  92106. * \param client_data This value will be supplied to callbacks in their
  92107. * \a client_data argument.
  92108. * \assert
  92109. * \code encoder != NULL \endcode
  92110. * \retval FLAC__StreamEncoderInitStatus
  92111. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92112. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92113. */
  92114. 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);
  92115. /** Initialize the encoder instance to encode Ogg FLAC streams.
  92116. *
  92117. * This flavor of initialization sets up the encoder to encode to a FLAC
  92118. * stream in an Ogg container. I/O is performed via callbacks to the
  92119. * client. For encoding to a plain file via filename or open \c FILE*,
  92120. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  92121. * provide a simpler interface.
  92122. *
  92123. * This function should be called after FLAC__stream_encoder_new() and
  92124. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92125. * or FLAC__stream_encoder_process_interleaved().
  92126. * initialization succeeded.
  92127. *
  92128. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  92129. * immediately call the write callback several times to write the metadata
  92130. * packets.
  92131. *
  92132. * \param encoder An uninitialized encoder instance.
  92133. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  92134. * pointer must not be \c NULL if \a seek_callback
  92135. * is non-NULL since they are both needed to be
  92136. * able to write data back to the Ogg FLAC stream
  92137. * in the post-encode phase.
  92138. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  92139. * pointer must not be \c NULL.
  92140. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  92141. * pointer may be \c NULL if seeking is not
  92142. * supported. The encoder uses seeking to go back
  92143. * and write some some stream statistics to the
  92144. * STREAMINFO block; this is recommended but not
  92145. * necessary to create a valid FLAC stream. If
  92146. * \a seek_callback is not \c NULL then a
  92147. * \a tell_callback must also be supplied.
  92148. * Alternatively, a dummy seek callback that just
  92149. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  92150. * may also be supplied, all though this is slightly
  92151. * less efficient for the encoder.
  92152. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  92153. * pointer may be \c NULL if seeking is not
  92154. * supported. If \a seek_callback is \c NULL then
  92155. * this argument will be ignored. If
  92156. * \a seek_callback is not \c NULL then a
  92157. * \a tell_callback must also be supplied.
  92158. * Alternatively, a dummy tell callback that just
  92159. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  92160. * may also be supplied, all though this is slightly
  92161. * less efficient for the encoder.
  92162. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  92163. * pointer may be \c NULL if the callback is not
  92164. * desired. If the client provides a seek callback,
  92165. * this function is not necessary as the encoder
  92166. * will automatically seek back and update the
  92167. * STREAMINFO block. It may also be \c NULL if the
  92168. * client does not support seeking, since it will
  92169. * have no way of going back to update the
  92170. * STREAMINFO. However the client can still supply
  92171. * a callback if it would like to know the details
  92172. * from the STREAMINFO.
  92173. * \param client_data This value will be supplied to callbacks in their
  92174. * \a client_data argument.
  92175. * \assert
  92176. * \code encoder != NULL \endcode
  92177. * \retval FLAC__StreamEncoderInitStatus
  92178. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92179. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92180. */
  92181. 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);
  92182. /** Initialize the encoder instance to encode native FLAC files.
  92183. *
  92184. * This flavor of initialization sets up the encoder to encode to a
  92185. * plain native FLAC file. For non-stdio streams, you must use
  92186. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  92187. *
  92188. * This function should be called after FLAC__stream_encoder_new() and
  92189. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92190. * or FLAC__stream_encoder_process_interleaved().
  92191. * initialization succeeded.
  92192. *
  92193. * \param encoder An uninitialized encoder instance.
  92194. * \param file An open file. The file should have been opened
  92195. * with mode \c "w+b" and rewound. The file
  92196. * becomes owned by the encoder and should not be
  92197. * manipulated by the client while encoding.
  92198. * Unless \a file is \c stdout, it will be closed
  92199. * when FLAC__stream_encoder_finish() is called.
  92200. * Note however that a proper SEEKTABLE cannot be
  92201. * created when encoding to \c stdout since it is
  92202. * not seekable.
  92203. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92204. * pointer may be \c NULL if the callback is not
  92205. * desired.
  92206. * \param client_data This value will be supplied to callbacks in their
  92207. * \a client_data argument.
  92208. * \assert
  92209. * \code encoder != NULL \endcode
  92210. * \code file != NULL \endcode
  92211. * \retval FLAC__StreamEncoderInitStatus
  92212. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92213. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92214. */
  92215. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92216. /** Initialize the encoder instance to encode Ogg FLAC files.
  92217. *
  92218. * This flavor of initialization sets up the encoder to encode to a
  92219. * plain Ogg FLAC file. For non-stdio streams, you must use
  92220. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  92221. *
  92222. * This function should be called after FLAC__stream_encoder_new() and
  92223. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92224. * or FLAC__stream_encoder_process_interleaved().
  92225. * initialization succeeded.
  92226. *
  92227. * \param encoder An uninitialized encoder instance.
  92228. * \param file An open file. The file should have been opened
  92229. * with mode \c "w+b" and rewound. The file
  92230. * becomes owned by the encoder and should not be
  92231. * manipulated by the client while encoding.
  92232. * Unless \a file is \c stdout, it will be closed
  92233. * when FLAC__stream_encoder_finish() is called.
  92234. * Note however that a proper SEEKTABLE cannot be
  92235. * created when encoding to \c stdout since it is
  92236. * not seekable.
  92237. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92238. * pointer may be \c NULL if the callback is not
  92239. * desired.
  92240. * \param client_data This value will be supplied to callbacks in their
  92241. * \a client_data argument.
  92242. * \assert
  92243. * \code encoder != NULL \endcode
  92244. * \code file != NULL \endcode
  92245. * \retval FLAC__StreamEncoderInitStatus
  92246. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92247. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92248. */
  92249. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92250. /** Initialize the encoder instance to encode native FLAC files.
  92251. *
  92252. * This flavor of initialization sets up the encoder to encode to a plain
  92253. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  92254. * with Unicode filenames on Windows), you must use
  92255. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  92256. * and provide callbacks for the I/O.
  92257. *
  92258. * This function should be called after FLAC__stream_encoder_new() and
  92259. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92260. * or FLAC__stream_encoder_process_interleaved().
  92261. * initialization succeeded.
  92262. *
  92263. * \param encoder An uninitialized encoder instance.
  92264. * \param filename The name of the file to encode to. The file will
  92265. * be opened with fopen(). Use \c NULL to encode to
  92266. * \c stdout. Note however that a proper SEEKTABLE
  92267. * cannot be created when encoding to \c stdout since
  92268. * it is not seekable.
  92269. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92270. * pointer may be \c NULL if the callback is not
  92271. * desired.
  92272. * \param client_data This value will be supplied to callbacks in their
  92273. * \a client_data argument.
  92274. * \assert
  92275. * \code encoder != 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_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92281. /** Initialize the encoder instance to encode Ogg FLAC files.
  92282. *
  92283. * This flavor of initialization sets up the encoder to encode to a plain
  92284. * Ogg 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_ogg_FILE(), or FLAC__stream_encoder_init_ogg_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_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92312. /** Finish the encoding process.
  92313. * Flushes the encoding buffer, releases resources, resets the encoder
  92314. * settings to their defaults, and returns the encoder state to
  92315. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  92316. * one or more write callbacks before returning, and will generate
  92317. * a metadata callback.
  92318. *
  92319. * Note that in the course of processing the last frame, errors can
  92320. * occur, so the caller should be sure to check the return value to
  92321. * ensure the file was encoded properly.
  92322. *
  92323. * In the event of a prematurely-terminated encode, it is not strictly
  92324. * necessary to call this immediately before FLAC__stream_encoder_delete()
  92325. * but it is good practice to match every FLAC__stream_encoder_init_*()
  92326. * with a FLAC__stream_encoder_finish().
  92327. *
  92328. * \param encoder An uninitialized encoder instance.
  92329. * \assert
  92330. * \code encoder != NULL \endcode
  92331. * \retval FLAC__bool
  92332. * \c false if an error occurred processing the last frame; or if verify
  92333. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  92334. * verify mismatch; else \c true. If \c false, caller should check the
  92335. * state with FLAC__stream_encoder_get_state() for more information
  92336. * about the error.
  92337. */
  92338. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  92339. /** Submit data for encoding.
  92340. * This version allows you to supply the input data via an array of
  92341. * pointers, each pointer pointing to an array of \a samples samples
  92342. * representing one channel. The samples need not be block-aligned,
  92343. * but each channel should have the same number of samples. Each sample
  92344. * should be a signed integer, right-justified to the resolution set by
  92345. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92346. * resolution is 16 bits per sample, the samples should all be in the
  92347. * range [-32768,32767].
  92348. *
  92349. * For applications where channel order is important, channels must
  92350. * follow the order as described in the
  92351. * <A HREF="../format.html#frame_header">frame header</A>.
  92352. *
  92353. * \param encoder An initialized encoder instance in the OK state.
  92354. * \param buffer An array of pointers to each channel's signal.
  92355. * \param samples The number of samples in one channel.
  92356. * \assert
  92357. * \code encoder != NULL \endcode
  92358. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92359. * \retval FLAC__bool
  92360. * \c true if successful, else \c false; in this case, check the
  92361. * encoder state with FLAC__stream_encoder_get_state() to see what
  92362. * went wrong.
  92363. */
  92364. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  92365. /** Submit data for encoding.
  92366. * This version allows you to supply the input data where the channels
  92367. * are interleaved into a single array (i.e. channel0_sample0,
  92368. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  92369. * The samples need not be block-aligned but they must be
  92370. * sample-aligned, i.e. the first value should be channel0_sample0
  92371. * and the last value channelN_sampleM. Each sample should be a signed
  92372. * integer, right-justified to the resolution set by
  92373. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92374. * resolution is 16 bits per sample, the samples should all be in the
  92375. * range [-32768,32767].
  92376. *
  92377. * For applications where channel order is important, channels must
  92378. * follow the order as described in the
  92379. * <A HREF="../format.html#frame_header">frame header</A>.
  92380. *
  92381. * \param encoder An initialized encoder instance in the OK state.
  92382. * \param buffer An array of channel-interleaved data (see above).
  92383. * \param samples The number of samples in one channel, the same as for
  92384. * FLAC__stream_encoder_process(). For example, if
  92385. * encoding two channels, \c 1000 \a samples corresponds
  92386. * to a \a buffer of 2000 values.
  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_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  92396. /* \} */
  92397. #ifdef __cplusplus
  92398. }
  92399. #endif
  92400. #endif
  92401. /*** End of inlined file: stream_encoder.h ***/
  92402. #ifdef _MSC_VER
  92403. /* OPT: an MSVC built-in would be better */
  92404. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  92405. {
  92406. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  92407. return (x>>16) | (x<<16);
  92408. }
  92409. #endif
  92410. #if defined(_MSC_VER) && defined(_X86_)
  92411. /* OPT: an MSVC built-in would be better */
  92412. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  92413. {
  92414. __asm {
  92415. mov edx, start
  92416. mov ecx, len
  92417. test ecx, ecx
  92418. loop1:
  92419. jz done1
  92420. mov eax, [edx]
  92421. bswap eax
  92422. mov [edx], eax
  92423. add edx, 4
  92424. dec ecx
  92425. jmp short loop1
  92426. done1:
  92427. }
  92428. }
  92429. #endif
  92430. /** \mainpage
  92431. *
  92432. * \section intro Introduction
  92433. *
  92434. * This is the documentation for the FLAC C and C++ APIs. It is
  92435. * highly interconnected; this introduction should give you a top
  92436. * level idea of the structure and how to find the information you
  92437. * need. As a prerequisite you should have at least a basic
  92438. * knowledge of the FLAC format, documented
  92439. * <A HREF="../format.html">here</A>.
  92440. *
  92441. * \section c_api FLAC C API
  92442. *
  92443. * The FLAC C API is the interface to libFLAC, a set of structures
  92444. * describing the components of FLAC streams, and functions for
  92445. * encoding and decoding streams, as well as manipulating FLAC
  92446. * metadata in files. The public include files will be installed
  92447. * in your include area (for example /usr/include/FLAC/...).
  92448. *
  92449. * By writing a little code and linking against libFLAC, it is
  92450. * relatively easy to add FLAC support to another program. The
  92451. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  92452. * Complete source code of libFLAC as well as the command-line
  92453. * encoder and plugins is available and is a useful source of
  92454. * examples.
  92455. *
  92456. * Aside from encoders and decoders, libFLAC provides a powerful
  92457. * metadata interface for manipulating metadata in FLAC files. It
  92458. * allows the user to add, delete, and modify FLAC metadata blocks
  92459. * and it can automatically take advantage of PADDING blocks to avoid
  92460. * rewriting the entire FLAC file when changing the size of the
  92461. * metadata.
  92462. *
  92463. * libFLAC usually only requires the standard C library and C math
  92464. * library. In particular, threading is not used so there is no
  92465. * dependency on a thread library. However, libFLAC does not use
  92466. * global variables and should be thread-safe.
  92467. *
  92468. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  92469. * However the metadata editing interfaces currently have limited
  92470. * read-only support for Ogg FLAC files.
  92471. *
  92472. * \section cpp_api FLAC C++ API
  92473. *
  92474. * The FLAC C++ API is a set of classes that encapsulate the
  92475. * structures and functions in libFLAC. They provide slightly more
  92476. * functionality with respect to metadata but are otherwise
  92477. * equivalent. For the most part, they share the same usage as
  92478. * their counterparts in libFLAC, and the FLAC C API documentation
  92479. * can be used as a supplement. The public include files
  92480. * for the C++ API will be installed in your include area (for
  92481. * example /usr/include/FLAC++/...).
  92482. *
  92483. * libFLAC++ is also licensed under
  92484. * <A HREF="../license.html">Xiph's BSD license</A>.
  92485. *
  92486. * \section getting_started Getting Started
  92487. *
  92488. * A good starting point for learning the API is to browse through
  92489. * the <A HREF="modules.html">modules</A>. Modules are logical
  92490. * groupings of related functions or classes, which correspond roughly
  92491. * to header files or sections of header files. Each module includes a
  92492. * detailed description of the general usage of its functions or
  92493. * classes.
  92494. *
  92495. * From there you can go on to look at the documentation of
  92496. * individual functions. You can see different views of the individual
  92497. * functions through the links in top bar across this page.
  92498. *
  92499. * If you prefer a more hands-on approach, you can jump right to some
  92500. * <A HREF="../documentation_example_code.html">example code</A>.
  92501. *
  92502. * \section porting_guide Porting Guide
  92503. *
  92504. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  92505. * has been introduced which gives detailed instructions on how to
  92506. * port your code to newer versions of FLAC.
  92507. *
  92508. * \section embedded_developers Embedded Developers
  92509. *
  92510. * libFLAC has grown larger over time as more functionality has been
  92511. * included, but much of it may be unnecessary for a particular embedded
  92512. * implementation. Unused parts may be pruned by some simple editing of
  92513. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  92514. * metadata interface are all independent from each other.
  92515. *
  92516. * It is easiest to just describe the dependencies:
  92517. *
  92518. * - All modules depend on the \link flac_format Format \endlink module.
  92519. * - The decoders and encoders depend on the bitbuffer.
  92520. * - The decoder is independent of the encoder. The encoder uses the
  92521. * decoder because of the verify feature, but this can be removed if
  92522. * not needed.
  92523. * - Parts of the metadata interface require the stream decoder (but not
  92524. * the encoder).
  92525. * - Ogg support is selectable through the compile time macro
  92526. * \c FLAC__HAS_OGG.
  92527. *
  92528. * For example, if your application only requires the stream decoder, no
  92529. * encoder, and no metadata interface, you can remove the stream encoder
  92530. * and the metadata interface, which will greatly reduce the size of the
  92531. * library.
  92532. *
  92533. * Also, there are several places in the libFLAC code with comments marked
  92534. * with "OPT:" where a #define can be changed to enable code that might be
  92535. * faster on a specific platform. Experimenting with these can yield faster
  92536. * binaries.
  92537. */
  92538. /** \defgroup porting Porting Guide for New Versions
  92539. *
  92540. * This module describes differences in the library interfaces from
  92541. * version to version. It assists in the porting of code that uses
  92542. * the libraries to newer versions of FLAC.
  92543. *
  92544. * One simple facility for making porting easier that has been added
  92545. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  92546. * library's includes (e.g. \c include/FLAC/export.h). The
  92547. * \c #defines mirror the libraries'
  92548. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  92549. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  92550. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  92551. * These can be used to support multiple versions of an API during the
  92552. * transition phase, e.g.
  92553. *
  92554. * \code
  92555. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  92556. * legacy code
  92557. * #else
  92558. * new code
  92559. * #endif
  92560. * \endcode
  92561. *
  92562. * The the source will work for multiple versions and the legacy code can
  92563. * easily be removed when the transition is complete.
  92564. *
  92565. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  92566. * include/FLAC/export.h), which can be used to determine whether or not
  92567. * the library has been compiled with support for Ogg FLAC. This is
  92568. * simpler than trying to call an Ogg init function and catching the
  92569. * error.
  92570. */
  92571. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  92572. * \ingroup porting
  92573. *
  92574. * \brief
  92575. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  92576. *
  92577. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  92578. * been simplified. First, libOggFLAC has been merged into libFLAC and
  92579. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  92580. * decoding layers and three encoding layers have been merged into a
  92581. * single stream decoder and stream encoder. That is, the functionality
  92582. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  92583. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  92584. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  92585. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  92586. * is there is now a single API that can be used to encode or decode
  92587. * streams to/from native FLAC or Ogg FLAC and the single API can work
  92588. * on both seekable and non-seekable streams.
  92589. *
  92590. * Instead of creating an encoder or decoder of a certain layer, now the
  92591. * client will always create a FLAC__StreamEncoder or
  92592. * FLAC__StreamDecoder. The old layers are now differentiated by the
  92593. * initialization function. For example, for the decoder,
  92594. * FLAC__stream_decoder_init() has been replaced by
  92595. * FLAC__stream_decoder_init_stream(). This init function takes
  92596. * callbacks for the I/O, and the seeking callbacks are optional. This
  92597. * allows the client to use the same object for seekable and
  92598. * non-seekable streams. For decoding a FLAC file directly, the client
  92599. * can use FLAC__stream_decoder_init_file() and pass just a filename
  92600. * and fewer callbacks; most of the other callbacks are supplied
  92601. * internally. For situations where fopen()ing by filename is not
  92602. * possible (e.g. Unicode filenames on Windows) the client can instead
  92603. * open the file itself and supply the FILE* to
  92604. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  92605. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  92606. * Since the callbacks and client data are now passed to the init
  92607. * function, the FLAC__stream_decoder_set_*_callback() functions and
  92608. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  92609. * rest of the calls to the decoder are the same as before.
  92610. *
  92611. * There are counterpart init functions for Ogg FLAC, e.g.
  92612. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  92613. * and callbacks are the same as for native FLAC.
  92614. *
  92615. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  92616. * been set up like so:
  92617. *
  92618. * \code
  92619. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  92620. * if(decoder == NULL) do_something;
  92621. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  92622. * [... other settings ...]
  92623. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  92624. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  92625. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  92626. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  92627. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  92628. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  92629. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  92630. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  92631. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  92632. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  92633. * \endcode
  92634. *
  92635. * In FLAC 1.1.3 it is like this:
  92636. *
  92637. * \code
  92638. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  92639. * if(decoder == NULL) do_something;
  92640. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  92641. * [... other settings ...]
  92642. * if(FLAC__stream_decoder_init_stream(
  92643. * decoder,
  92644. * my_read_callback,
  92645. * my_seek_callback, // or NULL
  92646. * my_tell_callback, // or NULL
  92647. * my_length_callback, // or NULL
  92648. * my_eof_callback, // or NULL
  92649. * my_write_callback,
  92650. * my_metadata_callback, // or NULL
  92651. * my_error_callback,
  92652. * my_client_data
  92653. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92654. * \endcode
  92655. *
  92656. * or you could do;
  92657. *
  92658. * \code
  92659. * [...]
  92660. * FILE *file = fopen("somefile.flac","rb");
  92661. * if(file == NULL) do_somthing;
  92662. * if(FLAC__stream_decoder_init_FILE(
  92663. * decoder,
  92664. * file,
  92665. * my_write_callback,
  92666. * my_metadata_callback, // or NULL
  92667. * my_error_callback,
  92668. * my_client_data
  92669. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92670. * \endcode
  92671. *
  92672. * or just:
  92673. *
  92674. * \code
  92675. * [...]
  92676. * if(FLAC__stream_decoder_init_file(
  92677. * decoder,
  92678. * "somefile.flac",
  92679. * my_write_callback,
  92680. * my_metadata_callback, // or NULL
  92681. * my_error_callback,
  92682. * my_client_data
  92683. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92684. * \endcode
  92685. *
  92686. * Another small change to the decoder is in how it handles unparseable
  92687. * streams. Before, when the decoder found an unparseable stream
  92688. * (reserved for when the decoder encounters a stream from a future
  92689. * encoder that it can't parse), it changed the state to
  92690. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  92691. * drops sync and calls the error callback with a new error code
  92692. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  92693. * more robust. If your error callback does not discriminate on the the
  92694. * error state, your code does not need to be changed.
  92695. *
  92696. * The encoder now has a new setting:
  92697. * FLAC__stream_encoder_set_apodization(). This is for setting the
  92698. * method used to window the data before LPC analysis. You only need to
  92699. * add a call to this function if the default is not suitable. There
  92700. * are also two new convenience functions that may be useful:
  92701. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  92702. * FLAC__metadata_get_cuesheet().
  92703. *
  92704. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  92705. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  92706. * is now \c size_t instead of \c unsigned.
  92707. */
  92708. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  92709. * \ingroup porting
  92710. *
  92711. * \brief
  92712. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  92713. *
  92714. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  92715. * There was a slight change in the implementation of
  92716. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  92717. * of the \a metadata array of pointers so the client no longer needs
  92718. * to maintain it after the call. The objects themselves that are
  92719. * pointed to by the array are still not copied though and must be
  92720. * maintained until the call to FLAC__stream_encoder_finish().
  92721. */
  92722. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  92723. * \ingroup porting
  92724. *
  92725. * \brief
  92726. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  92727. *
  92728. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  92729. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  92730. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  92731. *
  92732. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  92733. * has changed to reflect the conversion of one of the reserved bits
  92734. * into active use. It used to be \c 2 and now is \c 1. However the
  92735. * FLAC frame header length has not changed, so to skip the proper
  92736. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  92737. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  92738. */
  92739. /** \defgroup flac FLAC C API
  92740. *
  92741. * The FLAC C API is the interface to libFLAC, a set of structures
  92742. * describing the components of FLAC streams, and functions for
  92743. * encoding and decoding streams, as well as manipulating FLAC
  92744. * metadata in files.
  92745. *
  92746. * You should start with the format components as all other modules
  92747. * are dependent on it.
  92748. */
  92749. #endif
  92750. /*** End of inlined file: all.h ***/
  92751. /*** Start of inlined file: bitmath.c ***/
  92752. /*** Start of inlined file: juce_FlacHeader.h ***/
  92753. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92754. // tasks..
  92755. #define VERSION "1.2.1"
  92756. #define FLAC__NO_DLL 1
  92757. #if JUCE_MSVC
  92758. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92759. #endif
  92760. #if JUCE_MAC
  92761. #define FLAC__SYS_DARWIN 1
  92762. #endif
  92763. /*** End of inlined file: juce_FlacHeader.h ***/
  92764. #if JUCE_USE_FLAC
  92765. #if HAVE_CONFIG_H
  92766. # include <config.h>
  92767. #endif
  92768. /*** Start of inlined file: bitmath.h ***/
  92769. #ifndef FLAC__PRIVATE__BITMATH_H
  92770. #define FLAC__PRIVATE__BITMATH_H
  92771. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  92772. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  92773. unsigned FLAC__bitmath_silog2(int v);
  92774. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  92775. #endif
  92776. /*** End of inlined file: bitmath.h ***/
  92777. /* An example of what FLAC__bitmath_ilog2() computes:
  92778. *
  92779. * ilog2( 0) = assertion failure
  92780. * ilog2( 1) = 0
  92781. * ilog2( 2) = 1
  92782. * ilog2( 3) = 1
  92783. * ilog2( 4) = 2
  92784. * ilog2( 5) = 2
  92785. * ilog2( 6) = 2
  92786. * ilog2( 7) = 2
  92787. * ilog2( 8) = 3
  92788. * ilog2( 9) = 3
  92789. * ilog2(10) = 3
  92790. * ilog2(11) = 3
  92791. * ilog2(12) = 3
  92792. * ilog2(13) = 3
  92793. * ilog2(14) = 3
  92794. * ilog2(15) = 3
  92795. * ilog2(16) = 4
  92796. * ilog2(17) = 4
  92797. * ilog2(18) = 4
  92798. */
  92799. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  92800. {
  92801. unsigned l = 0;
  92802. FLAC__ASSERT(v > 0);
  92803. while(v >>= 1)
  92804. l++;
  92805. return l;
  92806. }
  92807. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  92808. {
  92809. unsigned l = 0;
  92810. FLAC__ASSERT(v > 0);
  92811. while(v >>= 1)
  92812. l++;
  92813. return l;
  92814. }
  92815. /* An example of what FLAC__bitmath_silog2() computes:
  92816. *
  92817. * silog2(-10) = 5
  92818. * silog2(- 9) = 5
  92819. * silog2(- 8) = 4
  92820. * silog2(- 7) = 4
  92821. * silog2(- 6) = 4
  92822. * silog2(- 5) = 4
  92823. * silog2(- 4) = 3
  92824. * silog2(- 3) = 3
  92825. * silog2(- 2) = 2
  92826. * silog2(- 1) = 2
  92827. * silog2( 0) = 0
  92828. * silog2( 1) = 2
  92829. * silog2( 2) = 3
  92830. * silog2( 3) = 3
  92831. * silog2( 4) = 4
  92832. * silog2( 5) = 4
  92833. * silog2( 6) = 4
  92834. * silog2( 7) = 4
  92835. * silog2( 8) = 5
  92836. * silog2( 9) = 5
  92837. * silog2( 10) = 5
  92838. */
  92839. unsigned FLAC__bitmath_silog2(int v)
  92840. {
  92841. while(1) {
  92842. if(v == 0) {
  92843. return 0;
  92844. }
  92845. else if(v > 0) {
  92846. unsigned l = 0;
  92847. while(v) {
  92848. l++;
  92849. v >>= 1;
  92850. }
  92851. return l+1;
  92852. }
  92853. else if(v == -1) {
  92854. return 2;
  92855. }
  92856. else {
  92857. v++;
  92858. v = -v;
  92859. }
  92860. }
  92861. }
  92862. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  92863. {
  92864. while(1) {
  92865. if(v == 0) {
  92866. return 0;
  92867. }
  92868. else if(v > 0) {
  92869. unsigned l = 0;
  92870. while(v) {
  92871. l++;
  92872. v >>= 1;
  92873. }
  92874. return l+1;
  92875. }
  92876. else if(v == -1) {
  92877. return 2;
  92878. }
  92879. else {
  92880. v++;
  92881. v = -v;
  92882. }
  92883. }
  92884. }
  92885. #endif
  92886. /*** End of inlined file: bitmath.c ***/
  92887. /*** Start of inlined file: bitreader.c ***/
  92888. /*** Start of inlined file: juce_FlacHeader.h ***/
  92889. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92890. // tasks..
  92891. #define VERSION "1.2.1"
  92892. #define FLAC__NO_DLL 1
  92893. #if JUCE_MSVC
  92894. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92895. #endif
  92896. #if JUCE_MAC
  92897. #define FLAC__SYS_DARWIN 1
  92898. #endif
  92899. /*** End of inlined file: juce_FlacHeader.h ***/
  92900. #if JUCE_USE_FLAC
  92901. #if HAVE_CONFIG_H
  92902. # include <config.h>
  92903. #endif
  92904. #include <stdlib.h> /* for malloc() */
  92905. #include <string.h> /* for memcpy(), memset() */
  92906. #ifdef _MSC_VER
  92907. #include <winsock.h> /* for ntohl() */
  92908. #elif defined FLAC__SYS_DARWIN
  92909. #include <machine/endian.h> /* for ntohl() */
  92910. #elif defined __MINGW32__
  92911. #include <winsock.h> /* for ntohl() */
  92912. #else
  92913. #include <netinet/in.h> /* for ntohl() */
  92914. #endif
  92915. /*** Start of inlined file: bitreader.h ***/
  92916. #ifndef FLAC__PRIVATE__BITREADER_H
  92917. #define FLAC__PRIVATE__BITREADER_H
  92918. #include <stdio.h> /* for FILE */
  92919. /*** Start of inlined file: cpu.h ***/
  92920. #ifndef FLAC__PRIVATE__CPU_H
  92921. #define FLAC__PRIVATE__CPU_H
  92922. #ifdef HAVE_CONFIG_H
  92923. #include <config.h>
  92924. #endif
  92925. typedef enum {
  92926. FLAC__CPUINFO_TYPE_IA32,
  92927. FLAC__CPUINFO_TYPE_PPC,
  92928. FLAC__CPUINFO_TYPE_UNKNOWN
  92929. } FLAC__CPUInfo_Type;
  92930. typedef struct {
  92931. FLAC__bool cpuid;
  92932. FLAC__bool bswap;
  92933. FLAC__bool cmov;
  92934. FLAC__bool mmx;
  92935. FLAC__bool fxsr;
  92936. FLAC__bool sse;
  92937. FLAC__bool sse2;
  92938. FLAC__bool sse3;
  92939. FLAC__bool ssse3;
  92940. FLAC__bool _3dnow;
  92941. FLAC__bool ext3dnow;
  92942. FLAC__bool extmmx;
  92943. } FLAC__CPUInfo_IA32;
  92944. typedef struct {
  92945. FLAC__bool altivec;
  92946. FLAC__bool ppc64;
  92947. } FLAC__CPUInfo_PPC;
  92948. typedef struct {
  92949. FLAC__bool use_asm;
  92950. FLAC__CPUInfo_Type type;
  92951. union {
  92952. FLAC__CPUInfo_IA32 ia32;
  92953. FLAC__CPUInfo_PPC ppc;
  92954. } data;
  92955. } FLAC__CPUInfo;
  92956. void FLAC__cpu_info(FLAC__CPUInfo *info);
  92957. #ifndef FLAC__NO_ASM
  92958. #ifdef FLAC__CPU_IA32
  92959. #ifdef FLAC__HAS_NASM
  92960. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  92961. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  92962. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  92963. #endif
  92964. #endif
  92965. #endif
  92966. #endif
  92967. /*** End of inlined file: cpu.h ***/
  92968. /*
  92969. * opaque structure definition
  92970. */
  92971. struct FLAC__BitReader;
  92972. typedef struct FLAC__BitReader FLAC__BitReader;
  92973. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  92974. /*
  92975. * construction, deletion, initialization, etc functions
  92976. */
  92977. FLAC__BitReader *FLAC__bitreader_new(void);
  92978. void FLAC__bitreader_delete(FLAC__BitReader *br);
  92979. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  92980. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  92981. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  92982. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  92983. /*
  92984. * CRC functions
  92985. */
  92986. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  92987. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  92988. /*
  92989. * info functions
  92990. */
  92991. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  92992. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  92993. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  92994. /*
  92995. * read functions
  92996. */
  92997. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  92998. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  92999. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  93000. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  93001. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  93002. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  93003. 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! */
  93004. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  93005. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  93006. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  93007. #ifndef FLAC__NO_ASM
  93008. # ifdef FLAC__CPU_IA32
  93009. # ifdef FLAC__HAS_NASM
  93010. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  93011. # endif
  93012. # endif
  93013. #endif
  93014. #if 0 /* UNUSED */
  93015. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  93016. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  93017. #endif
  93018. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  93019. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  93020. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  93021. #endif
  93022. /*** End of inlined file: bitreader.h ***/
  93023. /*** Start of inlined file: crc.h ***/
  93024. #ifndef FLAC__PRIVATE__CRC_H
  93025. #define FLAC__PRIVATE__CRC_H
  93026. /* 8 bit CRC generator, MSB shifted first
  93027. ** polynomial = x^8 + x^2 + x^1 + x^0
  93028. ** init = 0
  93029. */
  93030. extern FLAC__byte const FLAC__crc8_table[256];
  93031. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  93032. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  93033. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  93034. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  93035. /* 16 bit CRC generator, MSB shifted first
  93036. ** polynomial = x^16 + x^15 + x^2 + x^0
  93037. ** init = 0
  93038. */
  93039. extern unsigned FLAC__crc16_table[256];
  93040. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  93041. /* this alternate may be faster on some systems/compilers */
  93042. #if 0
  93043. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  93044. #endif
  93045. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  93046. #endif
  93047. /*** End of inlined file: crc.h ***/
  93048. /* Things should be fastest when this matches the machine word size */
  93049. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  93050. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  93051. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  93052. typedef FLAC__uint32 brword;
  93053. #define FLAC__BYTES_PER_WORD 4
  93054. #define FLAC__BITS_PER_WORD 32
  93055. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  93056. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  93057. #if WORDS_BIGENDIAN
  93058. #define SWAP_BE_WORD_TO_HOST(x) (x)
  93059. #else
  93060. #if defined (_MSC_VER) && defined (_X86_)
  93061. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  93062. #else
  93063. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  93064. #endif
  93065. #endif
  93066. /* counts the # of zero MSBs in a word */
  93067. #define COUNT_ZERO_MSBS(word) ( \
  93068. (word) <= 0xffff ? \
  93069. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  93070. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  93071. )
  93072. /* this alternate might be slightly faster on some systems/compilers: */
  93073. #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])) )
  93074. /*
  93075. * This should be at least twice as large as the largest number of words
  93076. * required to represent any 'number' (in any encoding) you are going to
  93077. * read. With FLAC this is on the order of maybe a few hundred bits.
  93078. * If the buffer is smaller than that, the decoder won't be able to read
  93079. * in a whole number that is in a variable length encoding (e.g. Rice).
  93080. * But to be practical it should be at least 1K bytes.
  93081. *
  93082. * Increase this number to decrease the number of read callbacks, at the
  93083. * expense of using more memory. Or decrease for the reverse effect,
  93084. * keeping in mind the limit from the first paragraph. The optimal size
  93085. * also depends on the CPU cache size and other factors; some twiddling
  93086. * may be necessary to squeeze out the best performance.
  93087. */
  93088. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  93089. static const unsigned char byte_to_unary_table[] = {
  93090. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  93091. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  93092. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  93093. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  93094. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93095. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93096. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93097. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  93106. };
  93107. #ifdef min
  93108. #undef min
  93109. #endif
  93110. #define min(x,y) ((x)<(y)?(x):(y))
  93111. #ifdef max
  93112. #undef max
  93113. #endif
  93114. #define max(x,y) ((x)>(y)?(x):(y))
  93115. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  93116. #ifdef _MSC_VER
  93117. #define FLAC__U64L(x) x
  93118. #else
  93119. #define FLAC__U64L(x) x##LLU
  93120. #endif
  93121. #ifndef FLaC__INLINE
  93122. #define FLaC__INLINE
  93123. #endif
  93124. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  93125. struct FLAC__BitReader {
  93126. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  93127. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  93128. brword *buffer;
  93129. unsigned capacity; /* in words */
  93130. unsigned words; /* # of completed words in buffer */
  93131. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  93132. unsigned consumed_words; /* #words ... */
  93133. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  93134. unsigned read_crc16; /* the running frame CRC */
  93135. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  93136. FLAC__BitReaderReadCallback read_callback;
  93137. void *client_data;
  93138. FLAC__CPUInfo cpu_info;
  93139. };
  93140. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  93141. {
  93142. register unsigned crc = br->read_crc16;
  93143. #if FLAC__BYTES_PER_WORD == 4
  93144. switch(br->crc16_align) {
  93145. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  93146. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  93147. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  93148. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  93149. }
  93150. #elif FLAC__BYTES_PER_WORD == 8
  93151. switch(br->crc16_align) {
  93152. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  93153. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  93154. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  93155. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  93156. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  93157. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  93158. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  93159. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  93160. }
  93161. #else
  93162. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  93163. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  93164. br->read_crc16 = crc;
  93165. #endif
  93166. br->crc16_align = 0;
  93167. }
  93168. /* would be static except it needs to be called by asm routines */
  93169. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  93170. {
  93171. unsigned start, end;
  93172. size_t bytes;
  93173. FLAC__byte *target;
  93174. /* first shift the unconsumed buffer data toward the front as much as possible */
  93175. if(br->consumed_words > 0) {
  93176. start = br->consumed_words;
  93177. end = br->words + (br->bytes? 1:0);
  93178. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  93179. br->words -= start;
  93180. br->consumed_words = 0;
  93181. }
  93182. /*
  93183. * set the target for reading, taking into account word alignment and endianness
  93184. */
  93185. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  93186. if(bytes == 0)
  93187. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  93188. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  93189. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  93190. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  93191. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  93192. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  93193. * ^^-------target, bytes=3
  93194. * on LE machines, have to byteswap the odd tail word so nothing is
  93195. * overwritten:
  93196. */
  93197. #if WORDS_BIGENDIAN
  93198. #else
  93199. if(br->bytes)
  93200. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  93201. #endif
  93202. /* now it looks like:
  93203. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  93204. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  93205. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  93206. * ^^-------target, bytes=3
  93207. */
  93208. /* read in the data; note that the callback may return a smaller number of bytes */
  93209. if(!br->read_callback(target, &bytes, br->client_data))
  93210. return false;
  93211. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  93212. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  93213. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  93214. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  93215. * now have to byteswap on LE machines:
  93216. */
  93217. #if WORDS_BIGENDIAN
  93218. #else
  93219. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  93220. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  93221. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  93222. start = br->words;
  93223. local_swap32_block_(br->buffer + start, end - start);
  93224. }
  93225. else
  93226. # endif
  93227. for(start = br->words; start < end; start++)
  93228. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  93229. #endif
  93230. /* now it looks like:
  93231. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  93232. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  93233. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  93234. * finally we'll update the reader values:
  93235. */
  93236. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  93237. br->words = end / FLAC__BYTES_PER_WORD;
  93238. br->bytes = end % FLAC__BYTES_PER_WORD;
  93239. return true;
  93240. }
  93241. /***********************************************************************
  93242. *
  93243. * Class constructor/destructor
  93244. *
  93245. ***********************************************************************/
  93246. FLAC__BitReader *FLAC__bitreader_new(void)
  93247. {
  93248. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  93249. /* calloc() implies:
  93250. memset(br, 0, sizeof(FLAC__BitReader));
  93251. br->buffer = 0;
  93252. br->capacity = 0;
  93253. br->words = br->bytes = 0;
  93254. br->consumed_words = br->consumed_bits = 0;
  93255. br->read_callback = 0;
  93256. br->client_data = 0;
  93257. */
  93258. return br;
  93259. }
  93260. void FLAC__bitreader_delete(FLAC__BitReader *br)
  93261. {
  93262. FLAC__ASSERT(0 != br);
  93263. FLAC__bitreader_free(br);
  93264. free(br);
  93265. }
  93266. /***********************************************************************
  93267. *
  93268. * Public class methods
  93269. *
  93270. ***********************************************************************/
  93271. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  93272. {
  93273. FLAC__ASSERT(0 != br);
  93274. br->words = br->bytes = 0;
  93275. br->consumed_words = br->consumed_bits = 0;
  93276. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  93277. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  93278. if(br->buffer == 0)
  93279. return false;
  93280. br->read_callback = rcb;
  93281. br->client_data = cd;
  93282. br->cpu_info = cpu;
  93283. return true;
  93284. }
  93285. void FLAC__bitreader_free(FLAC__BitReader *br)
  93286. {
  93287. FLAC__ASSERT(0 != br);
  93288. if(0 != br->buffer)
  93289. free(br->buffer);
  93290. br->buffer = 0;
  93291. br->capacity = 0;
  93292. br->words = br->bytes = 0;
  93293. br->consumed_words = br->consumed_bits = 0;
  93294. br->read_callback = 0;
  93295. br->client_data = 0;
  93296. }
  93297. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  93298. {
  93299. br->words = br->bytes = 0;
  93300. br->consumed_words = br->consumed_bits = 0;
  93301. return true;
  93302. }
  93303. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  93304. {
  93305. unsigned i, j;
  93306. if(br == 0) {
  93307. fprintf(out, "bitreader is NULL\n");
  93308. }
  93309. else {
  93310. 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);
  93311. for(i = 0; i < br->words; i++) {
  93312. fprintf(out, "%08X: ", i);
  93313. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  93314. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93315. fprintf(out, ".");
  93316. else
  93317. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  93318. fprintf(out, "\n");
  93319. }
  93320. if(br->bytes > 0) {
  93321. fprintf(out, "%08X: ", i);
  93322. for(j = 0; j < br->bytes*8; j++)
  93323. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93324. fprintf(out, ".");
  93325. else
  93326. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  93327. fprintf(out, "\n");
  93328. }
  93329. }
  93330. }
  93331. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  93332. {
  93333. FLAC__ASSERT(0 != br);
  93334. FLAC__ASSERT(0 != br->buffer);
  93335. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93336. br->read_crc16 = (unsigned)seed;
  93337. br->crc16_align = br->consumed_bits;
  93338. }
  93339. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  93340. {
  93341. FLAC__ASSERT(0 != br);
  93342. FLAC__ASSERT(0 != br->buffer);
  93343. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93344. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  93345. /* CRC any tail bytes in a partially-consumed word */
  93346. if(br->consumed_bits) {
  93347. const brword tail = br->buffer[br->consumed_words];
  93348. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  93349. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  93350. }
  93351. return br->read_crc16;
  93352. }
  93353. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  93354. {
  93355. return ((br->consumed_bits & 7) == 0);
  93356. }
  93357. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  93358. {
  93359. return 8 - (br->consumed_bits & 7);
  93360. }
  93361. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  93362. {
  93363. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  93364. }
  93365. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  93366. {
  93367. FLAC__ASSERT(0 != br);
  93368. FLAC__ASSERT(0 != br->buffer);
  93369. FLAC__ASSERT(bits <= 32);
  93370. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  93371. FLAC__ASSERT(br->consumed_words <= br->words);
  93372. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93373. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93374. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  93375. *val = 0;
  93376. return true;
  93377. }
  93378. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  93379. if(!bitreader_read_from_client_(br))
  93380. return false;
  93381. }
  93382. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93383. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93384. if(br->consumed_bits) {
  93385. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93386. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  93387. const brword word = br->buffer[br->consumed_words];
  93388. if(bits < n) {
  93389. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  93390. br->consumed_bits += bits;
  93391. return true;
  93392. }
  93393. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  93394. bits -= n;
  93395. crc16_update_word_(br, word);
  93396. br->consumed_words++;
  93397. br->consumed_bits = 0;
  93398. 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 */
  93399. *val <<= bits;
  93400. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  93401. br->consumed_bits = bits;
  93402. }
  93403. return true;
  93404. }
  93405. else {
  93406. const brword word = br->buffer[br->consumed_words];
  93407. if(bits < FLAC__BITS_PER_WORD) {
  93408. *val = word >> (FLAC__BITS_PER_WORD-bits);
  93409. br->consumed_bits = bits;
  93410. return true;
  93411. }
  93412. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  93413. *val = word;
  93414. crc16_update_word_(br, word);
  93415. br->consumed_words++;
  93416. return true;
  93417. }
  93418. }
  93419. else {
  93420. /* in this case we're starting our read at a partial tail word;
  93421. * the reader has guaranteed that we have at least 'bits' bits
  93422. * available to read, which makes this case simpler.
  93423. */
  93424. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93425. if(br->consumed_bits) {
  93426. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93427. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  93428. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  93429. br->consumed_bits += bits;
  93430. return true;
  93431. }
  93432. else {
  93433. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  93434. br->consumed_bits += bits;
  93435. return true;
  93436. }
  93437. }
  93438. }
  93439. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  93440. {
  93441. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  93442. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  93443. return false;
  93444. /* sign-extend: */
  93445. *val <<= (32-bits);
  93446. *val >>= (32-bits);
  93447. return true;
  93448. }
  93449. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  93450. {
  93451. FLAC__uint32 hi, lo;
  93452. if(bits > 32) {
  93453. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  93454. return false;
  93455. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  93456. return false;
  93457. *val = hi;
  93458. *val <<= 32;
  93459. *val |= lo;
  93460. }
  93461. else {
  93462. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  93463. return false;
  93464. *val = lo;
  93465. }
  93466. return true;
  93467. }
  93468. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  93469. {
  93470. FLAC__uint32 x8, x32 = 0;
  93471. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  93472. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  93473. return false;
  93474. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93475. return false;
  93476. x32 |= (x8 << 8);
  93477. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93478. return false;
  93479. x32 |= (x8 << 16);
  93480. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93481. return false;
  93482. x32 |= (x8 << 24);
  93483. *val = x32;
  93484. return true;
  93485. }
  93486. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  93487. {
  93488. /*
  93489. * OPT: a faster implementation is possible but probably not that useful
  93490. * since this is only called a couple of times in the metadata readers.
  93491. */
  93492. FLAC__ASSERT(0 != br);
  93493. FLAC__ASSERT(0 != br->buffer);
  93494. if(bits > 0) {
  93495. const unsigned n = br->consumed_bits & 7;
  93496. unsigned m;
  93497. FLAC__uint32 x;
  93498. if(n != 0) {
  93499. m = min(8-n, bits);
  93500. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  93501. return false;
  93502. bits -= m;
  93503. }
  93504. m = bits / 8;
  93505. if(m > 0) {
  93506. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  93507. return false;
  93508. bits %= 8;
  93509. }
  93510. if(bits > 0) {
  93511. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  93512. return false;
  93513. }
  93514. }
  93515. return true;
  93516. }
  93517. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  93518. {
  93519. FLAC__uint32 x;
  93520. FLAC__ASSERT(0 != br);
  93521. FLAC__ASSERT(0 != br->buffer);
  93522. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93523. /* step 1: skip over partial head word to get word aligned */
  93524. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93525. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93526. return false;
  93527. nvals--;
  93528. }
  93529. if(0 == nvals)
  93530. return true;
  93531. /* step 2: skip whole words in chunks */
  93532. while(nvals >= FLAC__BYTES_PER_WORD) {
  93533. if(br->consumed_words < br->words) {
  93534. br->consumed_words++;
  93535. nvals -= FLAC__BYTES_PER_WORD;
  93536. }
  93537. else if(!bitreader_read_from_client_(br))
  93538. return false;
  93539. }
  93540. /* step 3: skip any remainder from partial tail bytes */
  93541. while(nvals) {
  93542. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93543. return false;
  93544. nvals--;
  93545. }
  93546. return true;
  93547. }
  93548. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, 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: read from 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. *val++ = (FLAC__byte)x;
  93559. nvals--;
  93560. }
  93561. if(0 == nvals)
  93562. return true;
  93563. /* step 2: read whole words in chunks */
  93564. while(nvals >= FLAC__BYTES_PER_WORD) {
  93565. if(br->consumed_words < br->words) {
  93566. const brword word = br->buffer[br->consumed_words++];
  93567. #if FLAC__BYTES_PER_WORD == 4
  93568. val[0] = (FLAC__byte)(word >> 24);
  93569. val[1] = (FLAC__byte)(word >> 16);
  93570. val[2] = (FLAC__byte)(word >> 8);
  93571. val[3] = (FLAC__byte)word;
  93572. #elif FLAC__BYTES_PER_WORD == 8
  93573. val[0] = (FLAC__byte)(word >> 56);
  93574. val[1] = (FLAC__byte)(word >> 48);
  93575. val[2] = (FLAC__byte)(word >> 40);
  93576. val[3] = (FLAC__byte)(word >> 32);
  93577. val[4] = (FLAC__byte)(word >> 24);
  93578. val[5] = (FLAC__byte)(word >> 16);
  93579. val[6] = (FLAC__byte)(word >> 8);
  93580. val[7] = (FLAC__byte)word;
  93581. #else
  93582. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  93583. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  93584. #endif
  93585. val += FLAC__BYTES_PER_WORD;
  93586. nvals -= FLAC__BYTES_PER_WORD;
  93587. }
  93588. else if(!bitreader_read_from_client_(br))
  93589. return false;
  93590. }
  93591. /* step 3: read any remainder from partial tail bytes */
  93592. while(nvals) {
  93593. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93594. return false;
  93595. *val++ = (FLAC__byte)x;
  93596. nvals--;
  93597. }
  93598. return true;
  93599. }
  93600. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  93601. #if 0 /* slow but readable version */
  93602. {
  93603. unsigned bit;
  93604. FLAC__ASSERT(0 != br);
  93605. FLAC__ASSERT(0 != br->buffer);
  93606. *val = 0;
  93607. while(1) {
  93608. if(!FLAC__bitreader_read_bit(br, &bit))
  93609. return false;
  93610. if(bit)
  93611. break;
  93612. else
  93613. *val++;
  93614. }
  93615. return true;
  93616. }
  93617. #else
  93618. {
  93619. unsigned i;
  93620. FLAC__ASSERT(0 != br);
  93621. FLAC__ASSERT(0 != br->buffer);
  93622. *val = 0;
  93623. while(1) {
  93624. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93625. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  93626. if(b) {
  93627. i = COUNT_ZERO_MSBS(b);
  93628. *val += i;
  93629. i++;
  93630. br->consumed_bits += i;
  93631. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  93632. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93633. br->consumed_words++;
  93634. br->consumed_bits = 0;
  93635. }
  93636. return true;
  93637. }
  93638. else {
  93639. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  93640. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93641. br->consumed_words++;
  93642. br->consumed_bits = 0;
  93643. /* didn't find stop bit yet, have to keep going... */
  93644. }
  93645. }
  93646. /* at this point we've eaten up all the whole words; have to try
  93647. * reading through any tail bytes before calling the read callback.
  93648. * this is a repeat of the above logic adjusted for the fact we
  93649. * don't have a whole word. note though if the client is feeding
  93650. * us data a byte at a time (unlikely), br->consumed_bits may not
  93651. * be zero.
  93652. */
  93653. if(br->bytes) {
  93654. const unsigned end = br->bytes * 8;
  93655. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  93656. if(b) {
  93657. i = COUNT_ZERO_MSBS(b);
  93658. *val += i;
  93659. i++;
  93660. br->consumed_bits += i;
  93661. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93662. return true;
  93663. }
  93664. else {
  93665. *val += end - br->consumed_bits;
  93666. br->consumed_bits += end;
  93667. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93668. /* didn't find stop bit yet, have to keep going... */
  93669. }
  93670. }
  93671. if(!bitreader_read_from_client_(br))
  93672. return false;
  93673. }
  93674. }
  93675. #endif
  93676. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  93677. {
  93678. FLAC__uint32 lsbs = 0, msbs = 0;
  93679. unsigned uval;
  93680. FLAC__ASSERT(0 != br);
  93681. FLAC__ASSERT(0 != br->buffer);
  93682. FLAC__ASSERT(parameter <= 31);
  93683. /* read the unary MSBs and end bit */
  93684. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  93685. return false;
  93686. /* read the binary LSBs */
  93687. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  93688. return false;
  93689. /* compose the value */
  93690. uval = (msbs << parameter) | lsbs;
  93691. if(uval & 1)
  93692. *val = -((int)(uval >> 1)) - 1;
  93693. else
  93694. *val = (int)(uval >> 1);
  93695. return true;
  93696. }
  93697. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  93698. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  93699. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  93700. /* OPT: possibly faster version for use with MSVC */
  93701. #ifdef _MSC_VER
  93702. {
  93703. unsigned i;
  93704. unsigned uval = 0;
  93705. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  93706. /* try and get br->consumed_words and br->consumed_bits into register;
  93707. * must remember to flush them back to *br before calling other
  93708. * bitwriter functions that use them, and before returning */
  93709. register unsigned cwords;
  93710. register unsigned cbits;
  93711. FLAC__ASSERT(0 != br);
  93712. FLAC__ASSERT(0 != br->buffer);
  93713. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93714. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93715. FLAC__ASSERT(parameter < 32);
  93716. /* 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 */
  93717. if(nvals == 0)
  93718. return true;
  93719. cbits = br->consumed_bits;
  93720. cwords = br->consumed_words;
  93721. while(1) {
  93722. /* read unary part */
  93723. while(1) {
  93724. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93725. brword b = br->buffer[cwords] << cbits;
  93726. if(b) {
  93727. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  93728. __asm {
  93729. bsr eax, b
  93730. not eax
  93731. and eax, 31
  93732. mov i, eax
  93733. }
  93734. #else
  93735. i = COUNT_ZERO_MSBS(b);
  93736. #endif
  93737. uval += i;
  93738. bits = parameter;
  93739. i++;
  93740. cbits += i;
  93741. if(cbits == FLAC__BITS_PER_WORD) {
  93742. crc16_update_word_(br, br->buffer[cwords]);
  93743. cwords++;
  93744. cbits = 0;
  93745. }
  93746. goto break1;
  93747. }
  93748. else {
  93749. uval += FLAC__BITS_PER_WORD - cbits;
  93750. crc16_update_word_(br, br->buffer[cwords]);
  93751. cwords++;
  93752. cbits = 0;
  93753. /* didn't find stop bit yet, have to keep going... */
  93754. }
  93755. }
  93756. /* at this point we've eaten up all the whole words; have to try
  93757. * reading through any tail bytes before calling the read callback.
  93758. * this is a repeat of the above logic adjusted for the fact we
  93759. * don't have a whole word. note though if the client is feeding
  93760. * us data a byte at a time (unlikely), br->consumed_bits may not
  93761. * be zero.
  93762. */
  93763. if(br->bytes) {
  93764. const unsigned end = br->bytes * 8;
  93765. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  93766. if(b) {
  93767. i = COUNT_ZERO_MSBS(b);
  93768. uval += i;
  93769. bits = parameter;
  93770. i++;
  93771. cbits += i;
  93772. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93773. goto break1;
  93774. }
  93775. else {
  93776. uval += end - cbits;
  93777. cbits += end;
  93778. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93779. /* didn't find stop bit yet, have to keep going... */
  93780. }
  93781. }
  93782. /* flush registers and read; bitreader_read_from_client_() does
  93783. * not touch br->consumed_bits at all but we still need to set
  93784. * it in case it fails and we have to return false.
  93785. */
  93786. br->consumed_bits = cbits;
  93787. br->consumed_words = cwords;
  93788. if(!bitreader_read_from_client_(br))
  93789. return false;
  93790. cwords = br->consumed_words;
  93791. }
  93792. break1:
  93793. /* read binary part */
  93794. FLAC__ASSERT(cwords <= br->words);
  93795. if(bits) {
  93796. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  93797. /* flush registers and read; bitreader_read_from_client_() does
  93798. * not touch br->consumed_bits at all but we still need to set
  93799. * it in case it fails and we have to return false.
  93800. */
  93801. br->consumed_bits = cbits;
  93802. br->consumed_words = cwords;
  93803. if(!bitreader_read_from_client_(br))
  93804. return false;
  93805. cwords = br->consumed_words;
  93806. }
  93807. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93808. if(cbits) {
  93809. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93810. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  93811. const brword word = br->buffer[cwords];
  93812. if(bits < n) {
  93813. uval <<= bits;
  93814. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  93815. cbits += bits;
  93816. goto break2;
  93817. }
  93818. uval <<= n;
  93819. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  93820. bits -= n;
  93821. crc16_update_word_(br, word);
  93822. cwords++;
  93823. cbits = 0;
  93824. 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 */
  93825. uval <<= bits;
  93826. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  93827. cbits = bits;
  93828. }
  93829. goto break2;
  93830. }
  93831. else {
  93832. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  93833. uval <<= bits;
  93834. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  93835. cbits = bits;
  93836. goto break2;
  93837. }
  93838. }
  93839. else {
  93840. /* in this case we're starting our read at a partial tail word;
  93841. * the reader has guaranteed that we have at least 'bits' bits
  93842. * available to read, which makes this case simpler.
  93843. */
  93844. uval <<= bits;
  93845. if(cbits) {
  93846. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93847. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  93848. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  93849. cbits += bits;
  93850. goto break2;
  93851. }
  93852. else {
  93853. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  93854. cbits += bits;
  93855. goto break2;
  93856. }
  93857. }
  93858. }
  93859. break2:
  93860. /* compose the value */
  93861. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  93862. /* are we done? */
  93863. --nvals;
  93864. if(nvals == 0) {
  93865. br->consumed_bits = cbits;
  93866. br->consumed_words = cwords;
  93867. return true;
  93868. }
  93869. uval = 0;
  93870. ++vals;
  93871. }
  93872. }
  93873. #else
  93874. {
  93875. unsigned i;
  93876. unsigned uval = 0;
  93877. /* try and get br->consumed_words and br->consumed_bits into register;
  93878. * must remember to flush them back to *br before calling other
  93879. * bitwriter functions that use them, and before returning */
  93880. register unsigned cwords;
  93881. register unsigned cbits;
  93882. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  93883. FLAC__ASSERT(0 != br);
  93884. FLAC__ASSERT(0 != br->buffer);
  93885. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93886. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93887. FLAC__ASSERT(parameter < 32);
  93888. /* 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 */
  93889. if(nvals == 0)
  93890. return true;
  93891. cbits = br->consumed_bits;
  93892. cwords = br->consumed_words;
  93893. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  93894. while(1) {
  93895. /* read unary part */
  93896. while(1) {
  93897. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93898. brword b = br->buffer[cwords] << cbits;
  93899. if(b) {
  93900. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  93901. asm volatile (
  93902. "bsrl %1, %0;"
  93903. "notl %0;"
  93904. "andl $31, %0;"
  93905. : "=r"(i)
  93906. : "r"(b)
  93907. );
  93908. #else
  93909. i = COUNT_ZERO_MSBS(b);
  93910. #endif
  93911. uval += i;
  93912. cbits += i;
  93913. cbits++; /* skip over stop bit */
  93914. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  93915. crc16_update_word_(br, br->buffer[cwords]);
  93916. cwords++;
  93917. cbits = 0;
  93918. }
  93919. goto break1;
  93920. }
  93921. else {
  93922. uval += FLAC__BITS_PER_WORD - cbits;
  93923. crc16_update_word_(br, br->buffer[cwords]);
  93924. cwords++;
  93925. cbits = 0;
  93926. /* didn't find stop bit yet, have to keep going... */
  93927. }
  93928. }
  93929. /* at this point we've eaten up all the whole words; have to try
  93930. * reading through any tail bytes before calling the read callback.
  93931. * this is a repeat of the above logic adjusted for the fact we
  93932. * don't have a whole word. note though if the client is feeding
  93933. * us data a byte at a time (unlikely), br->consumed_bits may not
  93934. * be zero.
  93935. */
  93936. if(br->bytes) {
  93937. const unsigned end = br->bytes * 8;
  93938. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  93939. if(b) {
  93940. i = COUNT_ZERO_MSBS(b);
  93941. uval += i;
  93942. cbits += i;
  93943. cbits++; /* skip over stop bit */
  93944. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93945. goto break1;
  93946. }
  93947. else {
  93948. uval += end - cbits;
  93949. cbits += end;
  93950. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  93951. /* didn't find stop bit yet, have to keep going... */
  93952. }
  93953. }
  93954. /* flush registers and read; bitreader_read_from_client_() does
  93955. * not touch br->consumed_bits at all but we still need to set
  93956. * it in case it fails and we have to return false.
  93957. */
  93958. br->consumed_bits = cbits;
  93959. br->consumed_words = cwords;
  93960. if(!bitreader_read_from_client_(br))
  93961. return false;
  93962. cwords = br->consumed_words;
  93963. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  93964. /* + uval to offset our count by the # of unary bits already
  93965. * consumed before the read, because we will add these back
  93966. * in all at once at break1
  93967. */
  93968. }
  93969. break1:
  93970. ucbits -= uval;
  93971. ucbits--; /* account for stop bit */
  93972. /* read binary part */
  93973. FLAC__ASSERT(cwords <= br->words);
  93974. if(parameter) {
  93975. while(ucbits < parameter) {
  93976. /* flush registers and read; bitreader_read_from_client_() does
  93977. * not touch br->consumed_bits at all but we still need to set
  93978. * it in case it fails and we have to return false.
  93979. */
  93980. br->consumed_bits = cbits;
  93981. br->consumed_words = cwords;
  93982. if(!bitreader_read_from_client_(br))
  93983. return false;
  93984. cwords = br->consumed_words;
  93985. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  93986. }
  93987. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93988. if(cbits) {
  93989. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  93990. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  93991. const brword word = br->buffer[cwords];
  93992. if(parameter < n) {
  93993. uval <<= parameter;
  93994. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  93995. cbits += parameter;
  93996. }
  93997. else {
  93998. uval <<= n;
  93999. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  94000. crc16_update_word_(br, word);
  94001. cwords++;
  94002. cbits = parameter - n;
  94003. 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 */
  94004. uval <<= cbits;
  94005. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  94006. }
  94007. }
  94008. }
  94009. else {
  94010. cbits = parameter;
  94011. uval <<= parameter;
  94012. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  94013. }
  94014. }
  94015. else {
  94016. /* in this case we're starting our read at a partial tail word;
  94017. * the reader has guaranteed that we have at least 'parameter'
  94018. * bits available to read, which makes this case simpler.
  94019. */
  94020. uval <<= parameter;
  94021. if(cbits) {
  94022. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  94023. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  94024. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  94025. cbits += parameter;
  94026. }
  94027. else {
  94028. cbits = parameter;
  94029. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  94030. }
  94031. }
  94032. }
  94033. ucbits -= parameter;
  94034. /* compose the value */
  94035. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  94036. /* are we done? */
  94037. --nvals;
  94038. if(nvals == 0) {
  94039. br->consumed_bits = cbits;
  94040. br->consumed_words = cwords;
  94041. return true;
  94042. }
  94043. uval = 0;
  94044. ++vals;
  94045. }
  94046. }
  94047. #endif
  94048. #if 0 /* UNUSED */
  94049. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  94050. {
  94051. FLAC__uint32 lsbs = 0, msbs = 0;
  94052. unsigned bit, uval, k;
  94053. FLAC__ASSERT(0 != br);
  94054. FLAC__ASSERT(0 != br->buffer);
  94055. k = FLAC__bitmath_ilog2(parameter);
  94056. /* read the unary MSBs and end bit */
  94057. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  94058. return false;
  94059. /* read the binary LSBs */
  94060. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  94061. return false;
  94062. if(parameter == 1u<<k) {
  94063. /* compose the value */
  94064. uval = (msbs << k) | lsbs;
  94065. }
  94066. else {
  94067. unsigned d = (1 << (k+1)) - parameter;
  94068. if(lsbs >= d) {
  94069. if(!FLAC__bitreader_read_bit(br, &bit))
  94070. return false;
  94071. lsbs <<= 1;
  94072. lsbs |= bit;
  94073. lsbs -= d;
  94074. }
  94075. /* compose the value */
  94076. uval = msbs * parameter + lsbs;
  94077. }
  94078. /* unfold unsigned to signed */
  94079. if(uval & 1)
  94080. *val = -((int)(uval >> 1)) - 1;
  94081. else
  94082. *val = (int)(uval >> 1);
  94083. return true;
  94084. }
  94085. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  94086. {
  94087. FLAC__uint32 lsbs, msbs = 0;
  94088. unsigned bit, k;
  94089. FLAC__ASSERT(0 != br);
  94090. FLAC__ASSERT(0 != br->buffer);
  94091. k = FLAC__bitmath_ilog2(parameter);
  94092. /* read the unary MSBs and end bit */
  94093. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  94094. return false;
  94095. /* read the binary LSBs */
  94096. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  94097. return false;
  94098. if(parameter == 1u<<k) {
  94099. /* compose the value */
  94100. *val = (msbs << k) | lsbs;
  94101. }
  94102. else {
  94103. unsigned d = (1 << (k+1)) - parameter;
  94104. if(lsbs >= d) {
  94105. if(!FLAC__bitreader_read_bit(br, &bit))
  94106. return false;
  94107. lsbs <<= 1;
  94108. lsbs |= bit;
  94109. lsbs -= d;
  94110. }
  94111. /* compose the value */
  94112. *val = msbs * parameter + lsbs;
  94113. }
  94114. return true;
  94115. }
  94116. #endif /* UNUSED */
  94117. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  94118. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  94119. {
  94120. FLAC__uint32 v = 0;
  94121. FLAC__uint32 x;
  94122. unsigned i;
  94123. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94124. return false;
  94125. if(raw)
  94126. raw[(*rawlen)++] = (FLAC__byte)x;
  94127. if(!(x & 0x80)) { /* 0xxxxxxx */
  94128. v = x;
  94129. i = 0;
  94130. }
  94131. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  94132. v = x & 0x1F;
  94133. i = 1;
  94134. }
  94135. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  94136. v = x & 0x0F;
  94137. i = 2;
  94138. }
  94139. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  94140. v = x & 0x07;
  94141. i = 3;
  94142. }
  94143. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  94144. v = x & 0x03;
  94145. i = 4;
  94146. }
  94147. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  94148. v = x & 0x01;
  94149. i = 5;
  94150. }
  94151. else {
  94152. *val = 0xffffffff;
  94153. return true;
  94154. }
  94155. for( ; i; i--) {
  94156. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94157. return false;
  94158. if(raw)
  94159. raw[(*rawlen)++] = (FLAC__byte)x;
  94160. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  94161. *val = 0xffffffff;
  94162. return true;
  94163. }
  94164. v <<= 6;
  94165. v |= (x & 0x3F);
  94166. }
  94167. *val = v;
  94168. return true;
  94169. }
  94170. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  94171. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  94172. {
  94173. FLAC__uint64 v = 0;
  94174. FLAC__uint32 x;
  94175. unsigned i;
  94176. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94177. return false;
  94178. if(raw)
  94179. raw[(*rawlen)++] = (FLAC__byte)x;
  94180. if(!(x & 0x80)) { /* 0xxxxxxx */
  94181. v = x;
  94182. i = 0;
  94183. }
  94184. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  94185. v = x & 0x1F;
  94186. i = 1;
  94187. }
  94188. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  94189. v = x & 0x0F;
  94190. i = 2;
  94191. }
  94192. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  94193. v = x & 0x07;
  94194. i = 3;
  94195. }
  94196. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  94197. v = x & 0x03;
  94198. i = 4;
  94199. }
  94200. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  94201. v = x & 0x01;
  94202. i = 5;
  94203. }
  94204. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  94205. v = 0;
  94206. i = 6;
  94207. }
  94208. else {
  94209. *val = FLAC__U64L(0xffffffffffffffff);
  94210. return true;
  94211. }
  94212. for( ; i; i--) {
  94213. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94214. return false;
  94215. if(raw)
  94216. raw[(*rawlen)++] = (FLAC__byte)x;
  94217. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  94218. *val = FLAC__U64L(0xffffffffffffffff);
  94219. return true;
  94220. }
  94221. v <<= 6;
  94222. v |= (x & 0x3F);
  94223. }
  94224. *val = v;
  94225. return true;
  94226. }
  94227. #endif
  94228. /*** End of inlined file: bitreader.c ***/
  94229. /*** Start of inlined file: bitwriter.c ***/
  94230. /*** Start of inlined file: juce_FlacHeader.h ***/
  94231. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94232. // tasks..
  94233. #define VERSION "1.2.1"
  94234. #define FLAC__NO_DLL 1
  94235. #if JUCE_MSVC
  94236. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94237. #endif
  94238. #if JUCE_MAC
  94239. #define FLAC__SYS_DARWIN 1
  94240. #endif
  94241. /*** End of inlined file: juce_FlacHeader.h ***/
  94242. #if JUCE_USE_FLAC
  94243. #if HAVE_CONFIG_H
  94244. # include <config.h>
  94245. #endif
  94246. #include <stdlib.h> /* for malloc() */
  94247. #include <string.h> /* for memcpy(), memset() */
  94248. #ifdef _MSC_VER
  94249. #include <winsock.h> /* for ntohl() */
  94250. #elif defined FLAC__SYS_DARWIN
  94251. #include <machine/endian.h> /* for ntohl() */
  94252. #elif defined __MINGW32__
  94253. #include <winsock.h> /* for ntohl() */
  94254. #else
  94255. #include <netinet/in.h> /* for ntohl() */
  94256. #endif
  94257. #if 0 /* UNUSED */
  94258. #endif
  94259. /*** Start of inlined file: bitwriter.h ***/
  94260. #ifndef FLAC__PRIVATE__BITWRITER_H
  94261. #define FLAC__PRIVATE__BITWRITER_H
  94262. #include <stdio.h> /* for FILE */
  94263. /*
  94264. * opaque structure definition
  94265. */
  94266. struct FLAC__BitWriter;
  94267. typedef struct FLAC__BitWriter FLAC__BitWriter;
  94268. /*
  94269. * construction, deletion, initialization, etc functions
  94270. */
  94271. FLAC__BitWriter *FLAC__bitwriter_new(void);
  94272. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  94273. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  94274. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  94275. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  94276. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  94277. /*
  94278. * CRC functions
  94279. *
  94280. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  94281. */
  94282. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  94283. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  94284. /*
  94285. * info functions
  94286. */
  94287. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  94288. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  94289. /*
  94290. * direct buffer access
  94291. *
  94292. * there may be no calls on the bitwriter between get and release.
  94293. * the bitwriter continues to own the returned buffer.
  94294. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  94295. */
  94296. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  94297. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  94298. /*
  94299. * write functions
  94300. */
  94301. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  94302. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  94303. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  94304. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  94305. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  94306. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  94307. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  94308. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  94309. #if 0 /* UNUSED */
  94310. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  94311. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  94312. #endif
  94313. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  94314. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  94315. #if 0 /* UNUSED */
  94316. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  94317. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  94318. #endif
  94319. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  94320. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  94321. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  94322. #endif
  94323. /*** End of inlined file: bitwriter.h ***/
  94324. /*** Start of inlined file: alloc.h ***/
  94325. #ifndef FLAC__SHARE__ALLOC_H
  94326. #define FLAC__SHARE__ALLOC_H
  94327. #if HAVE_CONFIG_H
  94328. # include <config.h>
  94329. #endif
  94330. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  94331. * before #including this file, otherwise SIZE_MAX might not be defined
  94332. */
  94333. #include <limits.h> /* for SIZE_MAX */
  94334. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  94335. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  94336. #endif
  94337. #include <stdlib.h> /* for size_t, malloc(), etc */
  94338. #ifndef SIZE_MAX
  94339. # ifndef SIZE_T_MAX
  94340. # ifdef _MSC_VER
  94341. # define SIZE_T_MAX UINT_MAX
  94342. # else
  94343. # error
  94344. # endif
  94345. # endif
  94346. # define SIZE_MAX SIZE_T_MAX
  94347. #endif
  94348. #ifndef FLaC__INLINE
  94349. #define FLaC__INLINE
  94350. #endif
  94351. /* avoid malloc()ing 0 bytes, see:
  94352. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  94353. */
  94354. static FLaC__INLINE void *safe_malloc_(size_t size)
  94355. {
  94356. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94357. if(!size)
  94358. size++;
  94359. return malloc(size);
  94360. }
  94361. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  94362. {
  94363. if(!nmemb || !size)
  94364. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94365. return calloc(nmemb, size);
  94366. }
  94367. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  94368. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  94369. {
  94370. size2 += size1;
  94371. if(size2 < size1)
  94372. return 0;
  94373. return safe_malloc_(size2);
  94374. }
  94375. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  94376. {
  94377. size2 += size1;
  94378. if(size2 < size1)
  94379. return 0;
  94380. size3 += size2;
  94381. if(size3 < size2)
  94382. return 0;
  94383. return safe_malloc_(size3);
  94384. }
  94385. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  94386. {
  94387. size2 += size1;
  94388. if(size2 < size1)
  94389. return 0;
  94390. size3 += size2;
  94391. if(size3 < size2)
  94392. return 0;
  94393. size4 += size3;
  94394. if(size4 < size3)
  94395. return 0;
  94396. return safe_malloc_(size4);
  94397. }
  94398. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  94399. #if 0
  94400. needs support for cases where sizeof(size_t) != 4
  94401. {
  94402. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  94403. if(sizeof(size_t) == 4) {
  94404. if ((double)size1 * (double)size2 < 4294967296.0)
  94405. return malloc(size1*size2);
  94406. }
  94407. return 0;
  94408. }
  94409. #else
  94410. /* better? */
  94411. {
  94412. if(!size1 || !size2)
  94413. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94414. if(size1 > SIZE_MAX / size2)
  94415. return 0;
  94416. return malloc(size1*size2);
  94417. }
  94418. #endif
  94419. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  94420. {
  94421. if(!size1 || !size2 || !size3)
  94422. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94423. if(size1 > SIZE_MAX / size2)
  94424. return 0;
  94425. size1 *= size2;
  94426. if(size1 > SIZE_MAX / size3)
  94427. return 0;
  94428. return malloc(size1*size3);
  94429. }
  94430. /* size1*size2 + size3 */
  94431. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  94432. {
  94433. if(!size1 || !size2)
  94434. return safe_malloc_(size3);
  94435. if(size1 > SIZE_MAX / size2)
  94436. return 0;
  94437. return safe_malloc_add_2op_(size1*size2, size3);
  94438. }
  94439. /* size1 * (size2 + size3) */
  94440. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  94441. {
  94442. if(!size1 || (!size2 && !size3))
  94443. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94444. size2 += size3;
  94445. if(size2 < size3)
  94446. return 0;
  94447. return safe_malloc_mul_2op_(size1, size2);
  94448. }
  94449. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  94450. {
  94451. size2 += size1;
  94452. if(size2 < size1)
  94453. return 0;
  94454. return realloc(ptr, size2);
  94455. }
  94456. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  94457. {
  94458. size2 += size1;
  94459. if(size2 < size1)
  94460. return 0;
  94461. size3 += size2;
  94462. if(size3 < size2)
  94463. return 0;
  94464. return realloc(ptr, size3);
  94465. }
  94466. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  94467. {
  94468. size2 += size1;
  94469. if(size2 < size1)
  94470. return 0;
  94471. size3 += size2;
  94472. if(size3 < size2)
  94473. return 0;
  94474. size4 += size3;
  94475. if(size4 < size3)
  94476. return 0;
  94477. return realloc(ptr, size4);
  94478. }
  94479. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  94480. {
  94481. if(!size1 || !size2)
  94482. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94483. if(size1 > SIZE_MAX / size2)
  94484. return 0;
  94485. return realloc(ptr, size1*size2);
  94486. }
  94487. /* size1 * (size2 + size3) */
  94488. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  94489. {
  94490. if(!size1 || (!size2 && !size3))
  94491. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94492. size2 += size3;
  94493. if(size2 < size3)
  94494. return 0;
  94495. return safe_realloc_mul_2op_(ptr, size1, size2);
  94496. }
  94497. #endif
  94498. /*** End of inlined file: alloc.h ***/
  94499. /* Things should be fastest when this matches the machine word size */
  94500. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  94501. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  94502. typedef FLAC__uint32 bwword;
  94503. #define FLAC__BYTES_PER_WORD 4
  94504. #define FLAC__BITS_PER_WORD 32
  94505. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  94506. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  94507. #if WORDS_BIGENDIAN
  94508. #define SWAP_BE_WORD_TO_HOST(x) (x)
  94509. #else
  94510. #ifdef _MSC_VER
  94511. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  94512. #else
  94513. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  94514. #endif
  94515. #endif
  94516. /*
  94517. * The default capacity here doesn't matter too much. The buffer always grows
  94518. * to hold whatever is written to it. Usually the encoder will stop adding at
  94519. * a frame or metadata block, then write that out and clear the buffer for the
  94520. * next one.
  94521. */
  94522. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  94523. /* When growing, increment 4K at a time */
  94524. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  94525. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  94526. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  94527. #ifdef min
  94528. #undef min
  94529. #endif
  94530. #define min(x,y) ((x)<(y)?(x):(y))
  94531. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  94532. #ifdef _MSC_VER
  94533. #define FLAC__U64L(x) x
  94534. #else
  94535. #define FLAC__U64L(x) x##LLU
  94536. #endif
  94537. #ifndef FLaC__INLINE
  94538. #define FLaC__INLINE
  94539. #endif
  94540. struct FLAC__BitWriter {
  94541. bwword *buffer;
  94542. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  94543. unsigned capacity; /* capacity of buffer in words */
  94544. unsigned words; /* # of complete words in buffer */
  94545. unsigned bits; /* # of used bits in accum */
  94546. };
  94547. /* * WATCHOUT: The current implementation only grows the buffer. */
  94548. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  94549. {
  94550. unsigned new_capacity;
  94551. bwword *new_buffer;
  94552. FLAC__ASSERT(0 != bw);
  94553. FLAC__ASSERT(0 != bw->buffer);
  94554. /* calculate total words needed to store 'bits_to_add' additional bits */
  94555. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  94556. /* it's possible (due to pessimism in the growth estimation that
  94557. * leads to this call) that we don't actually need to grow
  94558. */
  94559. if(bw->capacity >= new_capacity)
  94560. return true;
  94561. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  94562. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  94563. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94564. /* make sure we got everything right */
  94565. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94566. FLAC__ASSERT(new_capacity > bw->capacity);
  94567. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  94568. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  94569. if(new_buffer == 0)
  94570. return false;
  94571. bw->buffer = new_buffer;
  94572. bw->capacity = new_capacity;
  94573. return true;
  94574. }
  94575. /***********************************************************************
  94576. *
  94577. * Class constructor/destructor
  94578. *
  94579. ***********************************************************************/
  94580. FLAC__BitWriter *FLAC__bitwriter_new(void)
  94581. {
  94582. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  94583. /* note that calloc() sets all members to 0 for us */
  94584. return bw;
  94585. }
  94586. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  94587. {
  94588. FLAC__ASSERT(0 != bw);
  94589. FLAC__bitwriter_free(bw);
  94590. free(bw);
  94591. }
  94592. /***********************************************************************
  94593. *
  94594. * Public class methods
  94595. *
  94596. ***********************************************************************/
  94597. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  94598. {
  94599. FLAC__ASSERT(0 != bw);
  94600. bw->words = bw->bits = 0;
  94601. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  94602. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  94603. if(bw->buffer == 0)
  94604. return false;
  94605. return true;
  94606. }
  94607. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  94608. {
  94609. FLAC__ASSERT(0 != bw);
  94610. if(0 != bw->buffer)
  94611. free(bw->buffer);
  94612. bw->buffer = 0;
  94613. bw->capacity = 0;
  94614. bw->words = bw->bits = 0;
  94615. }
  94616. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  94617. {
  94618. bw->words = bw->bits = 0;
  94619. }
  94620. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  94621. {
  94622. unsigned i, j;
  94623. if(bw == 0) {
  94624. fprintf(out, "bitwriter is NULL\n");
  94625. }
  94626. else {
  94627. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  94628. for(i = 0; i < bw->words; i++) {
  94629. fprintf(out, "%08X: ", i);
  94630. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  94631. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  94632. fprintf(out, "\n");
  94633. }
  94634. if(bw->bits > 0) {
  94635. fprintf(out, "%08X: ", i);
  94636. for(j = 0; j < bw->bits; j++)
  94637. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  94638. fprintf(out, "\n");
  94639. }
  94640. }
  94641. }
  94642. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  94643. {
  94644. const FLAC__byte *buffer;
  94645. size_t bytes;
  94646. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94647. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94648. return false;
  94649. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  94650. FLAC__bitwriter_release_buffer(bw);
  94651. return true;
  94652. }
  94653. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  94654. {
  94655. const FLAC__byte *buffer;
  94656. size_t bytes;
  94657. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94658. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94659. return false;
  94660. *crc = FLAC__crc8(buffer, bytes);
  94661. FLAC__bitwriter_release_buffer(bw);
  94662. return true;
  94663. }
  94664. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  94665. {
  94666. return ((bw->bits & 7) == 0);
  94667. }
  94668. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  94669. {
  94670. return FLAC__TOTAL_BITS(bw);
  94671. }
  94672. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  94673. {
  94674. FLAC__ASSERT((bw->bits & 7) == 0);
  94675. /* double protection */
  94676. if(bw->bits & 7)
  94677. return false;
  94678. /* if we have bits in the accumulator we have to flush those to the buffer first */
  94679. if(bw->bits) {
  94680. FLAC__ASSERT(bw->words <= bw->capacity);
  94681. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  94682. return false;
  94683. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  94684. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  94685. }
  94686. /* now we can just return what we have */
  94687. *buffer = (FLAC__byte*)bw->buffer;
  94688. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  94689. return true;
  94690. }
  94691. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  94692. {
  94693. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  94694. * get-mode' flag could be added everywhere and then cleared here
  94695. */
  94696. (void)bw;
  94697. }
  94698. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  94699. {
  94700. unsigned n;
  94701. FLAC__ASSERT(0 != bw);
  94702. FLAC__ASSERT(0 != bw->buffer);
  94703. if(bits == 0)
  94704. return true;
  94705. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94706. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94707. return false;
  94708. /* first part gets to word alignment */
  94709. if(bw->bits) {
  94710. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  94711. bw->accum <<= n;
  94712. bits -= n;
  94713. bw->bits += n;
  94714. if(bw->bits == FLAC__BITS_PER_WORD) {
  94715. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94716. bw->bits = 0;
  94717. }
  94718. else
  94719. return true;
  94720. }
  94721. /* do whole words */
  94722. while(bits >= FLAC__BITS_PER_WORD) {
  94723. bw->buffer[bw->words++] = 0;
  94724. bits -= FLAC__BITS_PER_WORD;
  94725. }
  94726. /* do any leftovers */
  94727. if(bits > 0) {
  94728. bw->accum = 0;
  94729. bw->bits = bits;
  94730. }
  94731. return true;
  94732. }
  94733. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  94734. {
  94735. register unsigned left;
  94736. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94737. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94738. FLAC__ASSERT(0 != bw);
  94739. FLAC__ASSERT(0 != bw->buffer);
  94740. FLAC__ASSERT(bits <= 32);
  94741. if(bits == 0)
  94742. return true;
  94743. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94744. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94745. return false;
  94746. left = FLAC__BITS_PER_WORD - bw->bits;
  94747. if(bits < left) {
  94748. bw->accum <<= bits;
  94749. bw->accum |= val;
  94750. bw->bits += bits;
  94751. }
  94752. 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 */
  94753. bw->accum <<= left;
  94754. bw->accum |= val >> (bw->bits = bits - left);
  94755. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94756. bw->accum = val;
  94757. }
  94758. else {
  94759. bw->accum = val;
  94760. bw->bits = 0;
  94761. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  94762. }
  94763. return true;
  94764. }
  94765. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  94766. {
  94767. /* zero-out unused bits */
  94768. if(bits < 32)
  94769. val &= (~(0xffffffff << bits));
  94770. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94771. }
  94772. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  94773. {
  94774. /* this could be a little faster but it's not used for much */
  94775. if(bits > 32) {
  94776. return
  94777. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  94778. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  94779. }
  94780. else
  94781. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94782. }
  94783. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  94784. {
  94785. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  94786. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  94787. return false;
  94788. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  94789. return false;
  94790. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  94791. return false;
  94792. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  94793. return false;
  94794. return true;
  94795. }
  94796. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  94797. {
  94798. unsigned i;
  94799. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  94800. for(i = 0; i < nvals; i++) {
  94801. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  94802. return false;
  94803. }
  94804. return true;
  94805. }
  94806. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  94807. {
  94808. if(val < 32)
  94809. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  94810. else
  94811. return
  94812. FLAC__bitwriter_write_zeroes(bw, val) &&
  94813. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  94814. }
  94815. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  94816. {
  94817. FLAC__uint32 uval;
  94818. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  94819. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94820. uval = (val<<1) ^ (val>>31);
  94821. return 1 + parameter + (uval >> parameter);
  94822. }
  94823. #if 0 /* UNUSED */
  94824. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  94825. {
  94826. unsigned bits, msbs, uval;
  94827. unsigned k;
  94828. FLAC__ASSERT(parameter > 0);
  94829. /* fold signed to unsigned */
  94830. if(val < 0)
  94831. uval = (unsigned)(((-(++val)) << 1) + 1);
  94832. else
  94833. uval = (unsigned)(val << 1);
  94834. k = FLAC__bitmath_ilog2(parameter);
  94835. if(parameter == 1u<<k) {
  94836. FLAC__ASSERT(k <= 30);
  94837. msbs = uval >> k;
  94838. bits = 1 + k + msbs;
  94839. }
  94840. else {
  94841. unsigned q, r, d;
  94842. d = (1 << (k+1)) - parameter;
  94843. q = uval / parameter;
  94844. r = uval - (q * parameter);
  94845. bits = 1 + q + k;
  94846. if(r >= d)
  94847. bits++;
  94848. }
  94849. return bits;
  94850. }
  94851. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  94852. {
  94853. unsigned bits, msbs;
  94854. unsigned k;
  94855. FLAC__ASSERT(parameter > 0);
  94856. k = FLAC__bitmath_ilog2(parameter);
  94857. if(parameter == 1u<<k) {
  94858. FLAC__ASSERT(k <= 30);
  94859. msbs = uval >> k;
  94860. bits = 1 + k + msbs;
  94861. }
  94862. else {
  94863. unsigned q, r, d;
  94864. d = (1 << (k+1)) - parameter;
  94865. q = uval / parameter;
  94866. r = uval - (q * parameter);
  94867. bits = 1 + q + k;
  94868. if(r >= d)
  94869. bits++;
  94870. }
  94871. return bits;
  94872. }
  94873. #endif /* UNUSED */
  94874. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  94875. {
  94876. unsigned total_bits, interesting_bits, msbs;
  94877. FLAC__uint32 uval, pattern;
  94878. FLAC__ASSERT(0 != bw);
  94879. FLAC__ASSERT(0 != bw->buffer);
  94880. FLAC__ASSERT(parameter < 8*sizeof(uval));
  94881. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94882. uval = (val<<1) ^ (val>>31);
  94883. msbs = uval >> parameter;
  94884. interesting_bits = 1 + parameter;
  94885. total_bits = interesting_bits + msbs;
  94886. pattern = 1 << parameter; /* the unary end bit */
  94887. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  94888. if(total_bits <= 32)
  94889. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  94890. else
  94891. return
  94892. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  94893. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  94894. }
  94895. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  94896. {
  94897. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  94898. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  94899. FLAC__uint32 uval;
  94900. unsigned left;
  94901. const unsigned lsbits = 1 + parameter;
  94902. unsigned msbits;
  94903. FLAC__ASSERT(0 != bw);
  94904. FLAC__ASSERT(0 != bw->buffer);
  94905. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  94906. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94907. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94908. while(nvals) {
  94909. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  94910. uval = (*vals<<1) ^ (*vals>>31);
  94911. msbits = uval >> parameter;
  94912. #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) */
  94913. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94914. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94915. bw->bits = bw->bits + msbits + lsbits;
  94916. uval |= mask1; /* set stop bit */
  94917. uval &= mask2; /* mask off unused top bits */
  94918. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  94919. bw->accum <<= msbits;
  94920. bw->accum <<= lsbits;
  94921. bw->accum |= uval;
  94922. if(bw->bits == FLAC__BITS_PER_WORD) {
  94923. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94924. bw->bits = 0;
  94925. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  94926. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  94927. FLAC__ASSERT(bw->capacity == bw->words);
  94928. return false;
  94929. }
  94930. }
  94931. }
  94932. else {
  94933. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  94934. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  94935. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  94936. bw->bits = bw->bits + msbits + lsbits;
  94937. uval |= mask1; /* set stop bit */
  94938. uval &= mask2; /* mask off unused top bits */
  94939. bw->accum <<= msbits + lsbits;
  94940. bw->accum |= uval;
  94941. }
  94942. else {
  94943. #endif
  94944. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94945. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  94946. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  94947. return false;
  94948. if(msbits) {
  94949. /* first part gets to word alignment */
  94950. if(bw->bits) {
  94951. left = FLAC__BITS_PER_WORD - bw->bits;
  94952. if(msbits < left) {
  94953. bw->accum <<= msbits;
  94954. bw->bits += msbits;
  94955. goto break1;
  94956. }
  94957. else {
  94958. bw->accum <<= left;
  94959. msbits -= left;
  94960. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94961. bw->bits = 0;
  94962. }
  94963. }
  94964. /* do whole words */
  94965. while(msbits >= FLAC__BITS_PER_WORD) {
  94966. bw->buffer[bw->words++] = 0;
  94967. msbits -= FLAC__BITS_PER_WORD;
  94968. }
  94969. /* do any leftovers */
  94970. if(msbits > 0) {
  94971. bw->accum = 0;
  94972. bw->bits = msbits;
  94973. }
  94974. }
  94975. break1:
  94976. uval |= mask1; /* set stop bit */
  94977. uval &= mask2; /* mask off unused top bits */
  94978. left = FLAC__BITS_PER_WORD - bw->bits;
  94979. if(lsbits < left) {
  94980. bw->accum <<= lsbits;
  94981. bw->accum |= uval;
  94982. bw->bits += lsbits;
  94983. }
  94984. else {
  94985. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  94986. * be > lsbits (because of previous assertions) so it would have
  94987. * triggered the (lsbits<left) case above.
  94988. */
  94989. FLAC__ASSERT(bw->bits);
  94990. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  94991. bw->accum <<= left;
  94992. bw->accum |= uval >> (bw->bits = lsbits - left);
  94993. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94994. bw->accum = uval;
  94995. }
  94996. #if 1
  94997. }
  94998. #endif
  94999. vals++;
  95000. nvals--;
  95001. }
  95002. return true;
  95003. }
  95004. #if 0 /* UNUSED */
  95005. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  95006. {
  95007. unsigned total_bits, msbs, uval;
  95008. unsigned k;
  95009. FLAC__ASSERT(0 != bw);
  95010. FLAC__ASSERT(0 != bw->buffer);
  95011. FLAC__ASSERT(parameter > 0);
  95012. /* fold signed to unsigned */
  95013. if(val < 0)
  95014. uval = (unsigned)(((-(++val)) << 1) + 1);
  95015. else
  95016. uval = (unsigned)(val << 1);
  95017. k = FLAC__bitmath_ilog2(parameter);
  95018. if(parameter == 1u<<k) {
  95019. unsigned pattern;
  95020. FLAC__ASSERT(k <= 30);
  95021. msbs = uval >> k;
  95022. total_bits = 1 + k + msbs;
  95023. pattern = 1 << k; /* the unary end bit */
  95024. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  95025. if(total_bits <= 32) {
  95026. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  95027. return false;
  95028. }
  95029. else {
  95030. /* write the unary MSBs */
  95031. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  95032. return false;
  95033. /* write the unary end bit and binary LSBs */
  95034. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  95035. return false;
  95036. }
  95037. }
  95038. else {
  95039. unsigned q, r, d;
  95040. d = (1 << (k+1)) - parameter;
  95041. q = uval / parameter;
  95042. r = uval - (q * parameter);
  95043. /* write the unary MSBs */
  95044. if(!FLAC__bitwriter_write_zeroes(bw, q))
  95045. return false;
  95046. /* write the unary end bit */
  95047. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  95048. return false;
  95049. /* write the binary LSBs */
  95050. if(r >= d) {
  95051. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  95052. return false;
  95053. }
  95054. else {
  95055. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  95056. return false;
  95057. }
  95058. }
  95059. return true;
  95060. }
  95061. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  95062. {
  95063. unsigned total_bits, msbs;
  95064. unsigned k;
  95065. FLAC__ASSERT(0 != bw);
  95066. FLAC__ASSERT(0 != bw->buffer);
  95067. FLAC__ASSERT(parameter > 0);
  95068. k = FLAC__bitmath_ilog2(parameter);
  95069. if(parameter == 1u<<k) {
  95070. unsigned pattern;
  95071. FLAC__ASSERT(k <= 30);
  95072. msbs = uval >> k;
  95073. total_bits = 1 + k + msbs;
  95074. pattern = 1 << k; /* the unary end bit */
  95075. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  95076. if(total_bits <= 32) {
  95077. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  95078. return false;
  95079. }
  95080. else {
  95081. /* write the unary MSBs */
  95082. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  95083. return false;
  95084. /* write the unary end bit and binary LSBs */
  95085. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  95086. return false;
  95087. }
  95088. }
  95089. else {
  95090. unsigned q, r, d;
  95091. d = (1 << (k+1)) - parameter;
  95092. q = uval / parameter;
  95093. r = uval - (q * parameter);
  95094. /* write the unary MSBs */
  95095. if(!FLAC__bitwriter_write_zeroes(bw, q))
  95096. return false;
  95097. /* write the unary end bit */
  95098. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  95099. return false;
  95100. /* write the binary LSBs */
  95101. if(r >= d) {
  95102. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  95103. return false;
  95104. }
  95105. else {
  95106. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  95107. return false;
  95108. }
  95109. }
  95110. return true;
  95111. }
  95112. #endif /* UNUSED */
  95113. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  95114. {
  95115. FLAC__bool ok = 1;
  95116. FLAC__ASSERT(0 != bw);
  95117. FLAC__ASSERT(0 != bw->buffer);
  95118. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  95119. if(val < 0x80) {
  95120. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  95121. }
  95122. else if(val < 0x800) {
  95123. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  95124. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95125. }
  95126. else if(val < 0x10000) {
  95127. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  95128. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95129. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95130. }
  95131. else if(val < 0x200000) {
  95132. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  95133. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95134. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95135. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95136. }
  95137. else if(val < 0x4000000) {
  95138. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  95139. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  95140. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95141. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95142. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95143. }
  95144. else {
  95145. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  95146. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  95147. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  95148. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95149. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95150. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95151. }
  95152. return ok;
  95153. }
  95154. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  95155. {
  95156. FLAC__bool ok = 1;
  95157. FLAC__ASSERT(0 != bw);
  95158. FLAC__ASSERT(0 != bw->buffer);
  95159. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  95160. if(val < 0x80) {
  95161. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  95162. }
  95163. else if(val < 0x800) {
  95164. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  95165. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95166. }
  95167. else if(val < 0x10000) {
  95168. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  95169. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95170. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95171. }
  95172. else if(val < 0x200000) {
  95173. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  95174. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95175. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95176. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95177. }
  95178. else if(val < 0x4000000) {
  95179. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  95180. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95181. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95182. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95183. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95184. }
  95185. else if(val < 0x80000000) {
  95186. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  95187. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  95188. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95189. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95190. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95191. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95192. }
  95193. else {
  95194. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  95195. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  95196. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  95197. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95198. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95199. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95200. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95201. }
  95202. return ok;
  95203. }
  95204. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  95205. {
  95206. /* 0-pad to byte boundary */
  95207. if(bw->bits & 7u)
  95208. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  95209. else
  95210. return true;
  95211. }
  95212. #endif
  95213. /*** End of inlined file: bitwriter.c ***/
  95214. /*** Start of inlined file: cpu.c ***/
  95215. /*** Start of inlined file: juce_FlacHeader.h ***/
  95216. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95217. // tasks..
  95218. #define VERSION "1.2.1"
  95219. #define FLAC__NO_DLL 1
  95220. #if JUCE_MSVC
  95221. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95222. #endif
  95223. #if JUCE_MAC
  95224. #define FLAC__SYS_DARWIN 1
  95225. #endif
  95226. /*** End of inlined file: juce_FlacHeader.h ***/
  95227. #if JUCE_USE_FLAC
  95228. #if HAVE_CONFIG_H
  95229. # include <config.h>
  95230. #endif
  95231. #include <stdlib.h>
  95232. #include <stdio.h>
  95233. #if defined FLAC__CPU_IA32
  95234. # include <signal.h>
  95235. #elif defined FLAC__CPU_PPC
  95236. # if !defined FLAC__NO_ASM
  95237. # if defined FLAC__SYS_DARWIN
  95238. # include <sys/sysctl.h>
  95239. # include <mach/mach.h>
  95240. # include <mach/mach_host.h>
  95241. # include <mach/host_info.h>
  95242. # include <mach/machine.h>
  95243. # ifndef CPU_SUBTYPE_POWERPC_970
  95244. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  95245. # endif
  95246. # else /* FLAC__SYS_DARWIN */
  95247. # include <signal.h>
  95248. # include <setjmp.h>
  95249. static sigjmp_buf jmpbuf;
  95250. static volatile sig_atomic_t canjump = 0;
  95251. static void sigill_handler (int sig)
  95252. {
  95253. if (!canjump) {
  95254. signal (sig, SIG_DFL);
  95255. raise (sig);
  95256. }
  95257. canjump = 0;
  95258. siglongjmp (jmpbuf, 1);
  95259. }
  95260. # endif /* FLAC__SYS_DARWIN */
  95261. # endif /* FLAC__NO_ASM */
  95262. #endif /* FLAC__CPU_PPC */
  95263. #if defined (__NetBSD__) || defined(__OpenBSD__)
  95264. #include <sys/param.h>
  95265. #include <sys/sysctl.h>
  95266. #include <machine/cpu.h>
  95267. #endif
  95268. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  95269. #include <sys/types.h>
  95270. #include <sys/sysctl.h>
  95271. #endif
  95272. #if defined(__APPLE__)
  95273. /* how to get sysctlbyname()? */
  95274. #endif
  95275. /* these are flags in EDX of CPUID AX=00000001 */
  95276. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  95277. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  95278. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  95279. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  95280. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  95281. /* these are flags in ECX of CPUID AX=00000001 */
  95282. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  95283. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  95284. /* these are flags in EDX of CPUID AX=80000001 */
  95285. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  95286. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  95287. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  95288. /*
  95289. * Extra stuff needed for detection of OS support for SSE on IA-32
  95290. */
  95291. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  95292. # if defined(__linux__)
  95293. /*
  95294. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  95295. * modify the return address to jump over the offending SSE instruction
  95296. * and also the operation following it that indicates the instruction
  95297. * executed successfully. In this way we use no global variables and
  95298. * stay thread-safe.
  95299. *
  95300. * 3 + 3 + 6:
  95301. * 3 bytes for "xorps xmm0,xmm0"
  95302. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  95303. * 6 bytes extra in case our estimate is wrong
  95304. * 12 bytes puts us in the NOP "landing zone"
  95305. */
  95306. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  95307. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95308. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  95309. {
  95310. (void)signal;
  95311. sc.eip += 3 + 3 + 6;
  95312. }
  95313. # else
  95314. # include <sys/ucontext.h>
  95315. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  95316. {
  95317. (void)signal, (void)si;
  95318. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  95319. }
  95320. # endif
  95321. # elif defined(_MSC_VER)
  95322. # include <windows.h>
  95323. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  95324. # ifdef USE_TRY_CATCH_FLAVOR
  95325. # else
  95326. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  95327. {
  95328. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  95329. ep->ContextRecord->Eip += 3 + 3 + 6;
  95330. return EXCEPTION_CONTINUE_EXECUTION;
  95331. }
  95332. return EXCEPTION_CONTINUE_SEARCH;
  95333. }
  95334. # endif
  95335. # endif
  95336. #endif
  95337. void FLAC__cpu_info(FLAC__CPUInfo *info)
  95338. {
  95339. /*
  95340. * IA32-specific
  95341. */
  95342. #ifdef FLAC__CPU_IA32
  95343. info->type = FLAC__CPUINFO_TYPE_IA32;
  95344. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  95345. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  95346. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  95347. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  95348. info->data.ia32.cmov = false;
  95349. info->data.ia32.mmx = false;
  95350. info->data.ia32.fxsr = false;
  95351. info->data.ia32.sse = false;
  95352. info->data.ia32.sse2 = false;
  95353. info->data.ia32.sse3 = false;
  95354. info->data.ia32.ssse3 = false;
  95355. info->data.ia32._3dnow = false;
  95356. info->data.ia32.ext3dnow = false;
  95357. info->data.ia32.extmmx = false;
  95358. if(info->data.ia32.cpuid) {
  95359. /* http://www.sandpile.org/ia32/cpuid.htm */
  95360. FLAC__uint32 flags_edx, flags_ecx;
  95361. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  95362. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  95363. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  95364. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  95365. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  95366. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  95367. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  95368. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  95369. #ifdef FLAC__USE_3DNOW
  95370. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  95371. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  95372. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  95373. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  95374. #else
  95375. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  95376. #endif
  95377. #ifdef DEBUG
  95378. fprintf(stderr, "CPU info (IA-32):\n");
  95379. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  95380. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  95381. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  95382. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  95383. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  95384. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95385. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  95386. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  95387. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  95388. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  95389. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  95390. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  95391. #endif
  95392. /*
  95393. * now have to check for OS support of SSE/SSE2
  95394. */
  95395. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  95396. #if defined FLAC__NO_SSE_OS
  95397. /* assume user knows better than us; turn it off */
  95398. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95399. #elif defined FLAC__SSE_OS
  95400. /* assume user knows better than us; leave as detected above */
  95401. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  95402. int sse = 0;
  95403. size_t len;
  95404. /* at least one of these must work: */
  95405. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  95406. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  95407. if(!sse)
  95408. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95409. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  95410. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  95411. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  95412. size_t len = sizeof(val);
  95413. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95414. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95415. else { /* double-check SSE2 */
  95416. mib[1] = CPU_SSE2;
  95417. len = sizeof(val);
  95418. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95419. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95420. }
  95421. # else
  95422. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95423. # endif
  95424. #elif defined(__linux__)
  95425. int sse = 0;
  95426. struct sigaction sigill_save;
  95427. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95428. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  95429. #else
  95430. struct sigaction sigill_sse;
  95431. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  95432. __sigemptyset(&sigill_sse.sa_mask);
  95433. 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 */
  95434. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  95435. #endif
  95436. {
  95437. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  95438. /* see sigill_handler_sse_os() for an explanation of the following: */
  95439. asm volatile (
  95440. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  95441. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  95442. "incl %0\n\t" /* SIGILL handler will jump over this */
  95443. /* landing zone */
  95444. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  95445. "nop\n\t"
  95446. "nop\n\t"
  95447. "nop\n\t"
  95448. "nop\n\t"
  95449. "nop\n\t"
  95450. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  95451. "nop\n\t"
  95452. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  95453. : "=r"(sse)
  95454. : "r"(sse)
  95455. );
  95456. sigaction(SIGILL, &sigill_save, NULL);
  95457. }
  95458. if(!sse)
  95459. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95460. #elif defined(_MSC_VER)
  95461. # ifdef USE_TRY_CATCH_FLAVOR
  95462. _try {
  95463. __asm {
  95464. # if _MSC_VER <= 1200
  95465. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95466. _emit 0x0F
  95467. _emit 0x57
  95468. _emit 0xC0
  95469. # else
  95470. xorps xmm0,xmm0
  95471. # endif
  95472. }
  95473. }
  95474. _except(EXCEPTION_EXECUTE_HANDLER) {
  95475. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  95476. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95477. }
  95478. # else
  95479. int sse = 0;
  95480. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  95481. /* see GCC version above for explanation */
  95482. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  95483. /* http://www.codeproject.com/cpp/gccasm.asp */
  95484. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  95485. __asm {
  95486. # if _MSC_VER <= 1200
  95487. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95488. _emit 0x0F
  95489. _emit 0x57
  95490. _emit 0xC0
  95491. # else
  95492. xorps xmm0,xmm0
  95493. # endif
  95494. inc sse
  95495. nop
  95496. nop
  95497. nop
  95498. nop
  95499. nop
  95500. nop
  95501. nop
  95502. nop
  95503. nop
  95504. }
  95505. SetUnhandledExceptionFilter(save);
  95506. if(!sse)
  95507. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95508. # endif
  95509. #else
  95510. /* no way to test, disable to be safe */
  95511. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95512. #endif
  95513. #ifdef DEBUG
  95514. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95515. #endif
  95516. }
  95517. }
  95518. #else
  95519. info->use_asm = false;
  95520. #endif
  95521. /*
  95522. * PPC-specific
  95523. */
  95524. #elif defined FLAC__CPU_PPC
  95525. info->type = FLAC__CPUINFO_TYPE_PPC;
  95526. # if !defined FLAC__NO_ASM
  95527. info->use_asm = true;
  95528. # ifdef FLAC__USE_ALTIVEC
  95529. # if defined FLAC__SYS_DARWIN
  95530. {
  95531. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  95532. size_t len = sizeof(val);
  95533. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  95534. }
  95535. {
  95536. host_basic_info_data_t hostInfo;
  95537. mach_msg_type_number_t infoCount;
  95538. infoCount = HOST_BASIC_INFO_COUNT;
  95539. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  95540. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  95541. }
  95542. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  95543. {
  95544. /* no Darwin, do it the brute-force way */
  95545. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  95546. info->data.ppc.altivec = 0;
  95547. info->data.ppc.ppc64 = 0;
  95548. signal (SIGILL, sigill_handler);
  95549. canjump = 0;
  95550. if (!sigsetjmp (jmpbuf, 1)) {
  95551. canjump = 1;
  95552. asm volatile (
  95553. "mtspr 256, %0\n\t"
  95554. "vand %%v0, %%v0, %%v0"
  95555. :
  95556. : "r" (-1)
  95557. );
  95558. info->data.ppc.altivec = 1;
  95559. }
  95560. canjump = 0;
  95561. if (!sigsetjmp (jmpbuf, 1)) {
  95562. int x = 0;
  95563. canjump = 1;
  95564. /* PPC64 hardware implements the cntlzd instruction */
  95565. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  95566. info->data.ppc.ppc64 = 1;
  95567. }
  95568. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  95569. }
  95570. # endif
  95571. # else /* !FLAC__USE_ALTIVEC */
  95572. info->data.ppc.altivec = 0;
  95573. info->data.ppc.ppc64 = 0;
  95574. # endif
  95575. # else
  95576. info->use_asm = false;
  95577. # endif
  95578. /*
  95579. * unknown CPI
  95580. */
  95581. #else
  95582. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  95583. info->use_asm = false;
  95584. #endif
  95585. }
  95586. #endif
  95587. /*** End of inlined file: cpu.c ***/
  95588. /*** Start of inlined file: crc.c ***/
  95589. /*** Start of inlined file: juce_FlacHeader.h ***/
  95590. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95591. // tasks..
  95592. #define VERSION "1.2.1"
  95593. #define FLAC__NO_DLL 1
  95594. #if JUCE_MSVC
  95595. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95596. #endif
  95597. #if JUCE_MAC
  95598. #define FLAC__SYS_DARWIN 1
  95599. #endif
  95600. /*** End of inlined file: juce_FlacHeader.h ***/
  95601. #if JUCE_USE_FLAC
  95602. #if HAVE_CONFIG_H
  95603. # include <config.h>
  95604. #endif
  95605. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  95606. FLAC__byte const FLAC__crc8_table[256] = {
  95607. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  95608. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  95609. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  95610. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  95611. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  95612. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  95613. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  95614. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  95615. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  95616. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  95617. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  95618. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  95619. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  95620. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  95621. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  95622. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  95623. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  95624. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  95625. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  95626. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  95627. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  95628. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  95629. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  95630. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  95631. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  95632. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  95633. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  95634. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  95635. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  95636. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  95637. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  95638. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  95639. };
  95640. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  95641. unsigned FLAC__crc16_table[256] = {
  95642. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  95643. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  95644. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  95645. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  95646. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  95647. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  95648. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  95649. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  95650. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  95651. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  95652. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  95653. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  95654. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  95655. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  95656. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  95657. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  95658. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  95659. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  95660. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  95661. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  95662. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  95663. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  95664. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  95665. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  95666. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  95667. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  95668. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  95669. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  95670. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  95671. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  95672. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  95673. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  95674. };
  95675. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  95676. {
  95677. *crc = FLAC__crc8_table[*crc ^ data];
  95678. }
  95679. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  95680. {
  95681. while(len--)
  95682. *crc = FLAC__crc8_table[*crc ^ *data++];
  95683. }
  95684. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  95685. {
  95686. FLAC__uint8 crc = 0;
  95687. while(len--)
  95688. crc = FLAC__crc8_table[crc ^ *data++];
  95689. return crc;
  95690. }
  95691. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  95692. {
  95693. unsigned crc = 0;
  95694. while(len--)
  95695. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  95696. return crc;
  95697. }
  95698. #endif
  95699. /*** End of inlined file: crc.c ***/
  95700. /*** Start of inlined file: fixed.c ***/
  95701. /*** Start of inlined file: juce_FlacHeader.h ***/
  95702. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95703. // tasks..
  95704. #define VERSION "1.2.1"
  95705. #define FLAC__NO_DLL 1
  95706. #if JUCE_MSVC
  95707. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95708. #endif
  95709. #if JUCE_MAC
  95710. #define FLAC__SYS_DARWIN 1
  95711. #endif
  95712. /*** End of inlined file: juce_FlacHeader.h ***/
  95713. #if JUCE_USE_FLAC
  95714. #if HAVE_CONFIG_H
  95715. # include <config.h>
  95716. #endif
  95717. #include <math.h>
  95718. #include <string.h>
  95719. /*** Start of inlined file: fixed.h ***/
  95720. #ifndef FLAC__PRIVATE__FIXED_H
  95721. #define FLAC__PRIVATE__FIXED_H
  95722. #ifdef HAVE_CONFIG_H
  95723. #include <config.h>
  95724. #endif
  95725. /*** Start of inlined file: float.h ***/
  95726. #ifndef FLAC__PRIVATE__FLOAT_H
  95727. #define FLAC__PRIVATE__FLOAT_H
  95728. #ifdef HAVE_CONFIG_H
  95729. #include <config.h>
  95730. #endif
  95731. /*
  95732. * These typedefs make it easier to ensure that integer versions of
  95733. * the library really only contain integer operations. All the code
  95734. * in libFLAC should use FLAC__float and FLAC__double in place of
  95735. * float and double, and be protected by checks of the macro
  95736. * FLAC__INTEGER_ONLY_LIBRARY.
  95737. *
  95738. * FLAC__real is the basic floating point type used in LPC analysis.
  95739. */
  95740. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95741. typedef double FLAC__double;
  95742. typedef float FLAC__float;
  95743. /*
  95744. * WATCHOUT: changing FLAC__real will change the signatures of many
  95745. * functions that have assembly language equivalents and break them.
  95746. */
  95747. typedef float FLAC__real;
  95748. #else
  95749. /*
  95750. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  95751. * for the integer part and lower 16 bits for the fractional part.
  95752. */
  95753. typedef FLAC__int32 FLAC__fixedpoint;
  95754. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  95755. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  95756. extern const FLAC__fixedpoint FLAC__FP_ONE;
  95757. extern const FLAC__fixedpoint FLAC__FP_LN2;
  95758. extern const FLAC__fixedpoint FLAC__FP_E;
  95759. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  95760. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  95761. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  95762. /*
  95763. * FLAC__fixedpoint_log2()
  95764. * --------------------------------------------------------------------
  95765. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  95766. * algorithm by Knuth for x >= 1.0
  95767. *
  95768. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  95769. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  95770. *
  95771. * 'precision' roughly limits the number of iterations that are done;
  95772. * use (unsigned)(-1) for maximum precision.
  95773. *
  95774. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  95775. * function will punt and return 0.
  95776. *
  95777. * The return value will also have 'fracbits' fractional bits.
  95778. */
  95779. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  95780. #endif
  95781. #endif
  95782. /*** End of inlined file: float.h ***/
  95783. /*** Start of inlined file: format.h ***/
  95784. #ifndef FLAC__PRIVATE__FORMAT_H
  95785. #define FLAC__PRIVATE__FORMAT_H
  95786. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  95787. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  95788. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  95789. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95790. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  95791. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  95792. #endif
  95793. /*** End of inlined file: format.h ***/
  95794. /*
  95795. * FLAC__fixed_compute_best_predictor()
  95796. * --------------------------------------------------------------------
  95797. * Compute the best fixed predictor and the expected bits-per-sample
  95798. * of the residual signal for each order. The _wide() version uses
  95799. * 64-bit integers which is statistically necessary when bits-per-
  95800. * sample + log2(blocksize) > 30
  95801. *
  95802. * IN data[0,data_len-1]
  95803. * IN data_len
  95804. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  95805. */
  95806. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95807. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95808. # ifndef FLAC__NO_ASM
  95809. # ifdef FLAC__CPU_IA32
  95810. # ifdef FLAC__HAS_NASM
  95811. 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]);
  95812. # endif
  95813. # endif
  95814. # endif
  95815. 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]);
  95816. #else
  95817. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95818. 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]);
  95819. #endif
  95820. /*
  95821. * FLAC__fixed_compute_residual()
  95822. * --------------------------------------------------------------------
  95823. * Compute the residual signal obtained from sutracting the predicted
  95824. * signal from the original.
  95825. *
  95826. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  95827. * IN data_len length of original signal
  95828. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  95829. * OUT residual[0,data_len-1] residual signal
  95830. */
  95831. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  95832. /*
  95833. * FLAC__fixed_restore_signal()
  95834. * --------------------------------------------------------------------
  95835. * Restore the original signal by summing the residual and the
  95836. * predictor.
  95837. *
  95838. * IN residual[0,data_len-1] residual signal
  95839. * IN data_len length of original signal
  95840. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  95841. * *** IMPORTANT: the caller must pass in the historical samples:
  95842. * IN data[-order,-1] previously-reconstructed historical samples
  95843. * OUT data[0,data_len-1] original signal
  95844. */
  95845. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  95846. #endif
  95847. /*** End of inlined file: fixed.h ***/
  95848. #ifndef M_LN2
  95849. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  95850. #define M_LN2 0.69314718055994530942
  95851. #endif
  95852. #ifdef min
  95853. #undef min
  95854. #endif
  95855. #define min(x,y) ((x) < (y)? (x) : (y))
  95856. #ifdef local_abs
  95857. #undef local_abs
  95858. #endif
  95859. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  95860. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  95861. /* rbps stands for residual bits per sample
  95862. *
  95863. * (ln(2) * err)
  95864. * rbps = log (-----------)
  95865. * 2 ( n )
  95866. */
  95867. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  95868. {
  95869. FLAC__uint32 rbps;
  95870. unsigned bits; /* the number of bits required to represent a number */
  95871. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  95872. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  95873. FLAC__ASSERT(err > 0);
  95874. FLAC__ASSERT(n > 0);
  95875. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  95876. if(err <= n)
  95877. return 0;
  95878. /*
  95879. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  95880. * These allow us later to know we won't lose too much precision in the
  95881. * fixed-point division (err<<fracbits)/n.
  95882. */
  95883. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  95884. err <<= fracbits;
  95885. err /= n;
  95886. /* err now holds err/n with fracbits fractional bits */
  95887. /*
  95888. * Whittle err down to 16 bits max. 16 significant bits is enough for
  95889. * our purposes.
  95890. */
  95891. FLAC__ASSERT(err > 0);
  95892. bits = FLAC__bitmath_ilog2(err)+1;
  95893. if(bits > 16) {
  95894. err >>= (bits-16);
  95895. fracbits -= (bits-16);
  95896. }
  95897. rbps = (FLAC__uint32)err;
  95898. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  95899. rbps *= FLAC__FP_LN2;
  95900. fracbits += 16;
  95901. FLAC__ASSERT(fracbits >= 0);
  95902. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  95903. {
  95904. const int f = fracbits & 3;
  95905. if(f) {
  95906. rbps >>= f;
  95907. fracbits -= f;
  95908. }
  95909. }
  95910. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  95911. if(rbps == 0)
  95912. return 0;
  95913. /*
  95914. * The return value must have 16 fractional bits. Since the whole part
  95915. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  95916. * must be >= -3, these assertion allows us to be able to shift rbps
  95917. * left if necessary to get 16 fracbits without losing any bits of the
  95918. * whole part of rbps.
  95919. *
  95920. * There is a slight chance due to accumulated error that the whole part
  95921. * will require 6 bits, so we use 6 in the assertion. Really though as
  95922. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  95923. */
  95924. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  95925. FLAC__ASSERT(fracbits >= -3);
  95926. /* now shift the decimal point into place */
  95927. if(fracbits < 16)
  95928. return rbps << (16-fracbits);
  95929. else if(fracbits > 16)
  95930. return rbps >> (fracbits-16);
  95931. else
  95932. return rbps;
  95933. }
  95934. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  95935. {
  95936. FLAC__uint32 rbps;
  95937. unsigned bits; /* the number of bits required to represent a number */
  95938. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  95939. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  95940. FLAC__ASSERT(err > 0);
  95941. FLAC__ASSERT(n > 0);
  95942. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  95943. if(err <= n)
  95944. return 0;
  95945. /*
  95946. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  95947. * These allow us later to know we won't lose too much precision in the
  95948. * fixed-point division (err<<fracbits)/n.
  95949. */
  95950. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  95951. err <<= fracbits;
  95952. err /= n;
  95953. /* err now holds err/n with fracbits fractional bits */
  95954. /*
  95955. * Whittle err down to 16 bits max. 16 significant bits is enough for
  95956. * our purposes.
  95957. */
  95958. FLAC__ASSERT(err > 0);
  95959. bits = FLAC__bitmath_ilog2_wide(err)+1;
  95960. if(bits > 16) {
  95961. err >>= (bits-16);
  95962. fracbits -= (bits-16);
  95963. }
  95964. rbps = (FLAC__uint32)err;
  95965. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  95966. rbps *= FLAC__FP_LN2;
  95967. fracbits += 16;
  95968. FLAC__ASSERT(fracbits >= 0);
  95969. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  95970. {
  95971. const int f = fracbits & 3;
  95972. if(f) {
  95973. rbps >>= f;
  95974. fracbits -= f;
  95975. }
  95976. }
  95977. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  95978. if(rbps == 0)
  95979. return 0;
  95980. /*
  95981. * The return value must have 16 fractional bits. Since the whole part
  95982. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  95983. * must be >= -3, these assertion allows us to be able to shift rbps
  95984. * left if necessary to get 16 fracbits without losing any bits of the
  95985. * whole part of rbps.
  95986. *
  95987. * There is a slight chance due to accumulated error that the whole part
  95988. * will require 6 bits, so we use 6 in the assertion. Really though as
  95989. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  95990. */
  95991. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  95992. FLAC__ASSERT(fracbits >= -3);
  95993. /* now shift the decimal point into place */
  95994. if(fracbits < 16)
  95995. return rbps << (16-fracbits);
  95996. else if(fracbits > 16)
  95997. return rbps >> (fracbits-16);
  95998. else
  95999. return rbps;
  96000. }
  96001. #endif
  96002. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96003. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  96004. #else
  96005. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  96006. #endif
  96007. {
  96008. FLAC__int32 last_error_0 = data[-1];
  96009. FLAC__int32 last_error_1 = data[-1] - data[-2];
  96010. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  96011. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  96012. FLAC__int32 error, save;
  96013. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  96014. unsigned i, order;
  96015. for(i = 0; i < data_len; i++) {
  96016. error = data[i] ; total_error_0 += local_abs(error); save = error;
  96017. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  96018. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  96019. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  96020. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  96021. }
  96022. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  96023. order = 0;
  96024. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  96025. order = 1;
  96026. else if(total_error_2 < min(total_error_3, total_error_4))
  96027. order = 2;
  96028. else if(total_error_3 < total_error_4)
  96029. order = 3;
  96030. else
  96031. order = 4;
  96032. /* Estimate the expected number of bits per residual signal sample. */
  96033. /* 'total_error*' is linearly related to the variance of the residual */
  96034. /* signal, so we use it directly to compute E(|x|) */
  96035. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  96036. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  96037. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  96038. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  96039. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  96040. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96041. 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);
  96042. 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);
  96043. 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);
  96044. 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);
  96045. 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);
  96046. #else
  96047. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  96048. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  96049. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  96050. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  96051. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  96052. #endif
  96053. return order;
  96054. }
  96055. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96056. 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])
  96057. #else
  96058. 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])
  96059. #endif
  96060. {
  96061. FLAC__int32 last_error_0 = data[-1];
  96062. FLAC__int32 last_error_1 = data[-1] - data[-2];
  96063. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  96064. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  96065. FLAC__int32 error, save;
  96066. /* total_error_* are 64-bits to avoid overflow when encoding
  96067. * erratic signals when the bits-per-sample and blocksize are
  96068. * large.
  96069. */
  96070. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  96071. unsigned i, order;
  96072. for(i = 0; i < data_len; i++) {
  96073. error = data[i] ; total_error_0 += local_abs(error); save = error;
  96074. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  96075. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  96076. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  96077. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  96078. }
  96079. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  96080. order = 0;
  96081. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  96082. order = 1;
  96083. else if(total_error_2 < min(total_error_3, total_error_4))
  96084. order = 2;
  96085. else if(total_error_3 < total_error_4)
  96086. order = 3;
  96087. else
  96088. order = 4;
  96089. /* Estimate the expected number of bits per residual signal sample. */
  96090. /* 'total_error*' is linearly related to the variance of the residual */
  96091. /* signal, so we use it directly to compute E(|x|) */
  96092. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  96093. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  96094. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  96095. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  96096. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  96097. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96098. #if defined _MSC_VER || defined __MINGW32__
  96099. /* with MSVC you have to spoon feed it the casting */
  96100. 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);
  96101. 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);
  96102. 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);
  96103. 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);
  96104. 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);
  96105. #else
  96106. 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);
  96107. 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);
  96108. 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);
  96109. 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);
  96110. 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);
  96111. #endif
  96112. #else
  96113. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  96114. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  96115. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  96116. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  96117. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  96118. #endif
  96119. return order;
  96120. }
  96121. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  96122. {
  96123. const int idata_len = (int)data_len;
  96124. int i;
  96125. switch(order) {
  96126. case 0:
  96127. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  96128. memcpy(residual, data, sizeof(residual[0])*data_len);
  96129. break;
  96130. case 1:
  96131. for(i = 0; i < idata_len; i++)
  96132. residual[i] = data[i] - data[i-1];
  96133. break;
  96134. case 2:
  96135. for(i = 0; i < idata_len; i++)
  96136. #if 1 /* OPT: may be faster with some compilers on some systems */
  96137. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  96138. #else
  96139. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  96140. #endif
  96141. break;
  96142. case 3:
  96143. for(i = 0; i < idata_len; i++)
  96144. #if 1 /* OPT: may be faster with some compilers on some systems */
  96145. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  96146. #else
  96147. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  96148. #endif
  96149. break;
  96150. case 4:
  96151. for(i = 0; i < idata_len; i++)
  96152. #if 1 /* OPT: may be faster with some compilers on some systems */
  96153. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  96154. #else
  96155. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  96156. #endif
  96157. break;
  96158. default:
  96159. FLAC__ASSERT(0);
  96160. }
  96161. }
  96162. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  96163. {
  96164. int i, idata_len = (int)data_len;
  96165. switch(order) {
  96166. case 0:
  96167. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  96168. memcpy(data, residual, sizeof(residual[0])*data_len);
  96169. break;
  96170. case 1:
  96171. for(i = 0; i < idata_len; i++)
  96172. data[i] = residual[i] + data[i-1];
  96173. break;
  96174. case 2:
  96175. for(i = 0; i < idata_len; i++)
  96176. #if 1 /* OPT: may be faster with some compilers on some systems */
  96177. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  96178. #else
  96179. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  96180. #endif
  96181. break;
  96182. case 3:
  96183. for(i = 0; i < idata_len; i++)
  96184. #if 1 /* OPT: may be faster with some compilers on some systems */
  96185. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  96186. #else
  96187. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  96188. #endif
  96189. break;
  96190. case 4:
  96191. for(i = 0; i < idata_len; i++)
  96192. #if 1 /* OPT: may be faster with some compilers on some systems */
  96193. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  96194. #else
  96195. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  96196. #endif
  96197. break;
  96198. default:
  96199. FLAC__ASSERT(0);
  96200. }
  96201. }
  96202. #endif
  96203. /*** End of inlined file: fixed.c ***/
  96204. /*** Start of inlined file: float.c ***/
  96205. /*** Start of inlined file: juce_FlacHeader.h ***/
  96206. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96207. // tasks..
  96208. #define VERSION "1.2.1"
  96209. #define FLAC__NO_DLL 1
  96210. #if JUCE_MSVC
  96211. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96212. #endif
  96213. #if JUCE_MAC
  96214. #define FLAC__SYS_DARWIN 1
  96215. #endif
  96216. /*** End of inlined file: juce_FlacHeader.h ***/
  96217. #if JUCE_USE_FLAC
  96218. #if HAVE_CONFIG_H
  96219. # include <config.h>
  96220. #endif
  96221. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  96222. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96223. #ifdef _MSC_VER
  96224. #define FLAC__U64L(x) x
  96225. #else
  96226. #define FLAC__U64L(x) x##LLU
  96227. #endif
  96228. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  96229. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  96230. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  96231. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  96232. const FLAC__fixedpoint FLAC__FP_E = 178145;
  96233. /* Lookup tables for Knuth's logarithm algorithm */
  96234. #define LOG2_LOOKUP_PRECISION 16
  96235. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  96236. {
  96237. /*
  96238. * 0 fraction bits
  96239. */
  96240. /* undefined */ 0x00000000,
  96241. /* lg(2/1) = */ 0x00000001,
  96242. /* lg(4/3) = */ 0x00000000,
  96243. /* lg(8/7) = */ 0x00000000,
  96244. /* lg(16/15) = */ 0x00000000,
  96245. /* lg(32/31) = */ 0x00000000,
  96246. /* lg(64/63) = */ 0x00000000,
  96247. /* lg(128/127) = */ 0x00000000,
  96248. /* lg(256/255) = */ 0x00000000,
  96249. /* lg(512/511) = */ 0x00000000,
  96250. /* lg(1024/1023) = */ 0x00000000,
  96251. /* lg(2048/2047) = */ 0x00000000,
  96252. /* lg(4096/4095) = */ 0x00000000,
  96253. /* lg(8192/8191) = */ 0x00000000,
  96254. /* lg(16384/16383) = */ 0x00000000,
  96255. /* lg(32768/32767) = */ 0x00000000
  96256. },
  96257. {
  96258. /*
  96259. * 4 fraction bits
  96260. */
  96261. /* undefined */ 0x00000000,
  96262. /* lg(2/1) = */ 0x00000010,
  96263. /* lg(4/3) = */ 0x00000007,
  96264. /* lg(8/7) = */ 0x00000003,
  96265. /* lg(16/15) = */ 0x00000001,
  96266. /* lg(32/31) = */ 0x00000001,
  96267. /* lg(64/63) = */ 0x00000000,
  96268. /* lg(128/127) = */ 0x00000000,
  96269. /* lg(256/255) = */ 0x00000000,
  96270. /* lg(512/511) = */ 0x00000000,
  96271. /* lg(1024/1023) = */ 0x00000000,
  96272. /* lg(2048/2047) = */ 0x00000000,
  96273. /* lg(4096/4095) = */ 0x00000000,
  96274. /* lg(8192/8191) = */ 0x00000000,
  96275. /* lg(16384/16383) = */ 0x00000000,
  96276. /* lg(32768/32767) = */ 0x00000000
  96277. },
  96278. {
  96279. /*
  96280. * 8 fraction bits
  96281. */
  96282. /* undefined */ 0x00000000,
  96283. /* lg(2/1) = */ 0x00000100,
  96284. /* lg(4/3) = */ 0x0000006a,
  96285. /* lg(8/7) = */ 0x00000031,
  96286. /* lg(16/15) = */ 0x00000018,
  96287. /* lg(32/31) = */ 0x0000000c,
  96288. /* lg(64/63) = */ 0x00000006,
  96289. /* lg(128/127) = */ 0x00000003,
  96290. /* lg(256/255) = */ 0x00000001,
  96291. /* lg(512/511) = */ 0x00000001,
  96292. /* lg(1024/1023) = */ 0x00000000,
  96293. /* lg(2048/2047) = */ 0x00000000,
  96294. /* lg(4096/4095) = */ 0x00000000,
  96295. /* lg(8192/8191) = */ 0x00000000,
  96296. /* lg(16384/16383) = */ 0x00000000,
  96297. /* lg(32768/32767) = */ 0x00000000
  96298. },
  96299. {
  96300. /*
  96301. * 12 fraction bits
  96302. */
  96303. /* undefined */ 0x00000000,
  96304. /* lg(2/1) = */ 0x00001000,
  96305. /* lg(4/3) = */ 0x000006a4,
  96306. /* lg(8/7) = */ 0x00000315,
  96307. /* lg(16/15) = */ 0x0000017d,
  96308. /* lg(32/31) = */ 0x000000bc,
  96309. /* lg(64/63) = */ 0x0000005d,
  96310. /* lg(128/127) = */ 0x0000002e,
  96311. /* lg(256/255) = */ 0x00000017,
  96312. /* lg(512/511) = */ 0x0000000c,
  96313. /* lg(1024/1023) = */ 0x00000006,
  96314. /* lg(2048/2047) = */ 0x00000003,
  96315. /* lg(4096/4095) = */ 0x00000001,
  96316. /* lg(8192/8191) = */ 0x00000001,
  96317. /* lg(16384/16383) = */ 0x00000000,
  96318. /* lg(32768/32767) = */ 0x00000000
  96319. },
  96320. {
  96321. /*
  96322. * 16 fraction bits
  96323. */
  96324. /* undefined */ 0x00000000,
  96325. /* lg(2/1) = */ 0x00010000,
  96326. /* lg(4/3) = */ 0x00006a40,
  96327. /* lg(8/7) = */ 0x00003151,
  96328. /* lg(16/15) = */ 0x000017d6,
  96329. /* lg(32/31) = */ 0x00000bba,
  96330. /* lg(64/63) = */ 0x000005d1,
  96331. /* lg(128/127) = */ 0x000002e6,
  96332. /* lg(256/255) = */ 0x00000172,
  96333. /* lg(512/511) = */ 0x000000b9,
  96334. /* lg(1024/1023) = */ 0x0000005c,
  96335. /* lg(2048/2047) = */ 0x0000002e,
  96336. /* lg(4096/4095) = */ 0x00000017,
  96337. /* lg(8192/8191) = */ 0x0000000c,
  96338. /* lg(16384/16383) = */ 0x00000006,
  96339. /* lg(32768/32767) = */ 0x00000003
  96340. },
  96341. {
  96342. /*
  96343. * 20 fraction bits
  96344. */
  96345. /* undefined */ 0x00000000,
  96346. /* lg(2/1) = */ 0x00100000,
  96347. /* lg(4/3) = */ 0x0006a3fe,
  96348. /* lg(8/7) = */ 0x00031513,
  96349. /* lg(16/15) = */ 0x00017d60,
  96350. /* lg(32/31) = */ 0x0000bb9d,
  96351. /* lg(64/63) = */ 0x00005d10,
  96352. /* lg(128/127) = */ 0x00002e59,
  96353. /* lg(256/255) = */ 0x00001721,
  96354. /* lg(512/511) = */ 0x00000b8e,
  96355. /* lg(1024/1023) = */ 0x000005c6,
  96356. /* lg(2048/2047) = */ 0x000002e3,
  96357. /* lg(4096/4095) = */ 0x00000171,
  96358. /* lg(8192/8191) = */ 0x000000b9,
  96359. /* lg(16384/16383) = */ 0x0000005c,
  96360. /* lg(32768/32767) = */ 0x0000002e
  96361. },
  96362. {
  96363. /*
  96364. * 24 fraction bits
  96365. */
  96366. /* undefined */ 0x00000000,
  96367. /* lg(2/1) = */ 0x01000000,
  96368. /* lg(4/3) = */ 0x006a3fe6,
  96369. /* lg(8/7) = */ 0x00315130,
  96370. /* lg(16/15) = */ 0x0017d605,
  96371. /* lg(32/31) = */ 0x000bb9ca,
  96372. /* lg(64/63) = */ 0x0005d0fc,
  96373. /* lg(128/127) = */ 0x0002e58f,
  96374. /* lg(256/255) = */ 0x0001720e,
  96375. /* lg(512/511) = */ 0x0000b8d8,
  96376. /* lg(1024/1023) = */ 0x00005c61,
  96377. /* lg(2048/2047) = */ 0x00002e2d,
  96378. /* lg(4096/4095) = */ 0x00001716,
  96379. /* lg(8192/8191) = */ 0x00000b8b,
  96380. /* lg(16384/16383) = */ 0x000005c5,
  96381. /* lg(32768/32767) = */ 0x000002e3
  96382. },
  96383. {
  96384. /*
  96385. * 28 fraction bits
  96386. */
  96387. /* undefined */ 0x00000000,
  96388. /* lg(2/1) = */ 0x10000000,
  96389. /* lg(4/3) = */ 0x06a3fe5c,
  96390. /* lg(8/7) = */ 0x03151301,
  96391. /* lg(16/15) = */ 0x017d6049,
  96392. /* lg(32/31) = */ 0x00bb9ca6,
  96393. /* lg(64/63) = */ 0x005d0fba,
  96394. /* lg(128/127) = */ 0x002e58f7,
  96395. /* lg(256/255) = */ 0x001720da,
  96396. /* lg(512/511) = */ 0x000b8d87,
  96397. /* lg(1024/1023) = */ 0x0005c60b,
  96398. /* lg(2048/2047) = */ 0x0002e2d7,
  96399. /* lg(4096/4095) = */ 0x00017160,
  96400. /* lg(8192/8191) = */ 0x0000b8ad,
  96401. /* lg(16384/16383) = */ 0x00005c56,
  96402. /* lg(32768/32767) = */ 0x00002e2b
  96403. }
  96404. };
  96405. #if 0
  96406. static const FLAC__uint64 log2_lookup_wide[] = {
  96407. {
  96408. /*
  96409. * 32 fraction bits
  96410. */
  96411. /* undefined */ 0x00000000,
  96412. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  96413. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  96414. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  96415. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  96416. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  96417. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  96418. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  96419. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  96420. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  96421. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  96422. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  96423. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  96424. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  96425. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  96426. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  96427. },
  96428. {
  96429. /*
  96430. * 48 fraction bits
  96431. */
  96432. /* undefined */ 0x00000000,
  96433. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  96434. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  96435. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  96436. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  96437. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  96438. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  96439. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  96440. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  96441. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  96442. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  96443. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  96444. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  96445. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  96446. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  96447. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  96448. }
  96449. };
  96450. #endif
  96451. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  96452. {
  96453. const FLAC__uint32 ONE = (1u << fracbits);
  96454. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  96455. FLAC__ASSERT(fracbits < 32);
  96456. FLAC__ASSERT((fracbits & 0x3) == 0);
  96457. if(x < ONE)
  96458. return 0;
  96459. if(precision > LOG2_LOOKUP_PRECISION)
  96460. precision = LOG2_LOOKUP_PRECISION;
  96461. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  96462. {
  96463. FLAC__uint32 y = 0;
  96464. FLAC__uint32 z = x >> 1, k = 1;
  96465. while (x > ONE && k < precision) {
  96466. if (x - z >= ONE) {
  96467. x -= z;
  96468. z = x >> k;
  96469. y += table[k];
  96470. }
  96471. else {
  96472. z >>= 1;
  96473. k++;
  96474. }
  96475. }
  96476. return y;
  96477. }
  96478. }
  96479. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  96480. #endif
  96481. /*** End of inlined file: float.c ***/
  96482. /*** Start of inlined file: format.c ***/
  96483. /*** Start of inlined file: juce_FlacHeader.h ***/
  96484. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96485. // tasks..
  96486. #define VERSION "1.2.1"
  96487. #define FLAC__NO_DLL 1
  96488. #if JUCE_MSVC
  96489. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96490. #endif
  96491. #if JUCE_MAC
  96492. #define FLAC__SYS_DARWIN 1
  96493. #endif
  96494. /*** End of inlined file: juce_FlacHeader.h ***/
  96495. #if JUCE_USE_FLAC
  96496. #if HAVE_CONFIG_H
  96497. # include <config.h>
  96498. #endif
  96499. #include <stdio.h>
  96500. #include <stdlib.h> /* for qsort() */
  96501. #include <string.h> /* for memset() */
  96502. #ifndef FLaC__INLINE
  96503. #define FLaC__INLINE
  96504. #endif
  96505. #ifdef min
  96506. #undef min
  96507. #endif
  96508. #define min(a,b) ((a)<(b)?(a):(b))
  96509. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96510. #ifdef _MSC_VER
  96511. #define FLAC__U64L(x) x
  96512. #else
  96513. #define FLAC__U64L(x) x##LLU
  96514. #endif
  96515. /* VERSION should come from configure */
  96516. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  96517. ;
  96518. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  96519. /* yet one more hack because of MSVC6: */
  96520. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  96521. #else
  96522. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  96523. #endif
  96524. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  96525. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  96526. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  96527. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  96528. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  96529. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  96530. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  96531. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  96532. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  96533. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  96534. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  96535. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  96536. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  96537. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  96538. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  96539. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  96540. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  96541. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  96542. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  96543. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  96544. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  96545. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  96546. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  96547. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  96548. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  96549. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  96550. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  96551. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  96552. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  96553. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  96554. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  96555. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  96556. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  96557. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  96558. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  96559. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  96560. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  96561. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  96562. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  96563. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  96564. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  96565. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  96566. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  96567. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  96568. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  96569. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  96570. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  96571. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  96572. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  96573. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  96574. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  96575. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  96576. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  96577. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  96578. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  96579. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  96580. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  96581. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  96582. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  96583. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  96584. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  96585. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  96586. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  96587. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  96588. "PARTITIONED_RICE",
  96589. "PARTITIONED_RICE2"
  96590. };
  96591. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  96592. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  96593. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  96594. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  96595. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  96596. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  96597. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  96598. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  96599. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  96600. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  96601. "CONSTANT",
  96602. "VERBATIM",
  96603. "FIXED",
  96604. "LPC"
  96605. };
  96606. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  96607. "INDEPENDENT",
  96608. "LEFT_SIDE",
  96609. "RIGHT_SIDE",
  96610. "MID_SIDE"
  96611. };
  96612. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  96613. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  96614. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  96615. };
  96616. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  96617. "STREAMINFO",
  96618. "PADDING",
  96619. "APPLICATION",
  96620. "SEEKTABLE",
  96621. "VORBIS_COMMENT",
  96622. "CUESHEET",
  96623. "PICTURE"
  96624. };
  96625. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  96626. "Other",
  96627. "32x32 pixels 'file icon' (PNG only)",
  96628. "Other file icon",
  96629. "Cover (front)",
  96630. "Cover (back)",
  96631. "Leaflet page",
  96632. "Media (e.g. label side of CD)",
  96633. "Lead artist/lead performer/soloist",
  96634. "Artist/performer",
  96635. "Conductor",
  96636. "Band/Orchestra",
  96637. "Composer",
  96638. "Lyricist/text writer",
  96639. "Recording Location",
  96640. "During recording",
  96641. "During performance",
  96642. "Movie/video screen capture",
  96643. "A bright coloured fish",
  96644. "Illustration",
  96645. "Band/artist logotype",
  96646. "Publisher/Studio logotype"
  96647. };
  96648. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  96649. {
  96650. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  96651. return false;
  96652. }
  96653. else
  96654. return true;
  96655. }
  96656. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  96657. {
  96658. if(
  96659. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  96660. (
  96661. sample_rate >= (1u << 16) &&
  96662. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  96663. )
  96664. ) {
  96665. return false;
  96666. }
  96667. else
  96668. return true;
  96669. }
  96670. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96671. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  96672. {
  96673. unsigned i;
  96674. FLAC__uint64 prev_sample_number = 0;
  96675. FLAC__bool got_prev = false;
  96676. FLAC__ASSERT(0 != seek_table);
  96677. for(i = 0; i < seek_table->num_points; i++) {
  96678. if(got_prev) {
  96679. if(
  96680. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  96681. seek_table->points[i].sample_number <= prev_sample_number
  96682. )
  96683. return false;
  96684. }
  96685. prev_sample_number = seek_table->points[i].sample_number;
  96686. got_prev = true;
  96687. }
  96688. return true;
  96689. }
  96690. /* used as the sort predicate for qsort() */
  96691. static int seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  96692. {
  96693. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  96694. if(l->sample_number == r->sample_number)
  96695. return 0;
  96696. else if(l->sample_number < r->sample_number)
  96697. return -1;
  96698. else
  96699. return 1;
  96700. }
  96701. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96702. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  96703. {
  96704. unsigned i, j;
  96705. FLAC__bool first;
  96706. FLAC__ASSERT(0 != seek_table);
  96707. /* sort the seekpoints */
  96708. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare_);
  96709. /* uniquify the seekpoints */
  96710. first = true;
  96711. for(i = j = 0; i < seek_table->num_points; i++) {
  96712. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  96713. if(!first) {
  96714. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  96715. continue;
  96716. }
  96717. }
  96718. first = false;
  96719. seek_table->points[j++] = seek_table->points[i];
  96720. }
  96721. for(i = j; i < seek_table->num_points; i++) {
  96722. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  96723. seek_table->points[i].stream_offset = 0;
  96724. seek_table->points[i].frame_samples = 0;
  96725. }
  96726. return j;
  96727. }
  96728. /*
  96729. * also disallows non-shortest-form encodings, c.f.
  96730. * http://www.unicode.org/versions/corrigendum1.html
  96731. * and a more clear explanation at the end of this section:
  96732. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  96733. */
  96734. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  96735. {
  96736. FLAC__ASSERT(0 != utf8);
  96737. if ((utf8[0] & 0x80) == 0) {
  96738. return 1;
  96739. }
  96740. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  96741. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  96742. return 0;
  96743. return 2;
  96744. }
  96745. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  96746. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  96747. return 0;
  96748. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  96749. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  96750. return 0;
  96751. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  96752. return 0;
  96753. return 3;
  96754. }
  96755. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  96756. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  96757. return 0;
  96758. return 4;
  96759. }
  96760. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  96761. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  96762. return 0;
  96763. return 5;
  96764. }
  96765. 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) {
  96766. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  96767. return 0;
  96768. return 6;
  96769. }
  96770. else {
  96771. return 0;
  96772. }
  96773. }
  96774. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  96775. {
  96776. char c;
  96777. for(c = *name; c; c = *(++name))
  96778. if(c < 0x20 || c == 0x3d || c > 0x7d)
  96779. return false;
  96780. return true;
  96781. }
  96782. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  96783. {
  96784. if(length == (unsigned)(-1)) {
  96785. while(*value) {
  96786. unsigned n = utf8len_(value);
  96787. if(n == 0)
  96788. return false;
  96789. value += n;
  96790. }
  96791. }
  96792. else {
  96793. const FLAC__byte *end = value + length;
  96794. while(value < end) {
  96795. unsigned n = utf8len_(value);
  96796. if(n == 0)
  96797. return false;
  96798. value += n;
  96799. }
  96800. if(value != end)
  96801. return false;
  96802. }
  96803. return true;
  96804. }
  96805. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  96806. {
  96807. const FLAC__byte *s, *end;
  96808. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  96809. if(*s < 0x20 || *s > 0x7D)
  96810. return false;
  96811. }
  96812. if(s == end)
  96813. return false;
  96814. s++; /* skip '=' */
  96815. while(s < end) {
  96816. unsigned n = utf8len_(s);
  96817. if(n == 0)
  96818. return false;
  96819. s += n;
  96820. }
  96821. if(s != end)
  96822. return false;
  96823. return true;
  96824. }
  96825. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96826. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  96827. {
  96828. unsigned i, j;
  96829. if(check_cd_da_subset) {
  96830. if(cue_sheet->lead_in < 2 * 44100) {
  96831. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  96832. return false;
  96833. }
  96834. if(cue_sheet->lead_in % 588 != 0) {
  96835. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  96836. return false;
  96837. }
  96838. }
  96839. if(cue_sheet->num_tracks == 0) {
  96840. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  96841. return false;
  96842. }
  96843. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  96844. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  96845. return false;
  96846. }
  96847. for(i = 0; i < cue_sheet->num_tracks; i++) {
  96848. if(cue_sheet->tracks[i].number == 0) {
  96849. if(violation) *violation = "cue sheet may not have a track number 0";
  96850. return false;
  96851. }
  96852. if(check_cd_da_subset) {
  96853. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  96854. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  96855. return false;
  96856. }
  96857. }
  96858. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  96859. if(violation) {
  96860. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  96861. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  96862. else
  96863. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  96864. }
  96865. return false;
  96866. }
  96867. if(i < cue_sheet->num_tracks - 1) {
  96868. if(cue_sheet->tracks[i].num_indices == 0) {
  96869. if(violation) *violation = "cue sheet track must have at least one index point";
  96870. return false;
  96871. }
  96872. if(cue_sheet->tracks[i].indices[0].number > 1) {
  96873. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  96874. return false;
  96875. }
  96876. }
  96877. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  96878. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  96879. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  96880. return false;
  96881. }
  96882. if(j > 0) {
  96883. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  96884. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  96885. return false;
  96886. }
  96887. }
  96888. }
  96889. }
  96890. return true;
  96891. }
  96892. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96893. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  96894. {
  96895. char *p;
  96896. FLAC__byte *b;
  96897. for(p = picture->mime_type; *p; p++) {
  96898. if(*p < 0x20 || *p > 0x7e) {
  96899. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  96900. return false;
  96901. }
  96902. }
  96903. for(b = picture->description; *b; ) {
  96904. unsigned n = utf8len_(b);
  96905. if(n == 0) {
  96906. if(violation) *violation = "description string must be valid UTF-8";
  96907. return false;
  96908. }
  96909. b += n;
  96910. }
  96911. return true;
  96912. }
  96913. /*
  96914. * These routines are private to libFLAC
  96915. */
  96916. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  96917. {
  96918. return
  96919. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  96920. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  96921. blocksize,
  96922. predictor_order
  96923. );
  96924. }
  96925. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  96926. {
  96927. unsigned max_rice_partition_order = 0;
  96928. while(!(blocksize & 1)) {
  96929. max_rice_partition_order++;
  96930. blocksize >>= 1;
  96931. }
  96932. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  96933. }
  96934. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  96935. {
  96936. unsigned max_rice_partition_order = limit;
  96937. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  96938. max_rice_partition_order--;
  96939. FLAC__ASSERT(
  96940. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  96941. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  96942. );
  96943. return max_rice_partition_order;
  96944. }
  96945. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  96946. {
  96947. FLAC__ASSERT(0 != object);
  96948. object->parameters = 0;
  96949. object->raw_bits = 0;
  96950. object->capacity_by_order = 0;
  96951. }
  96952. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  96953. {
  96954. FLAC__ASSERT(0 != object);
  96955. if(0 != object->parameters)
  96956. free(object->parameters);
  96957. if(0 != object->raw_bits)
  96958. free(object->raw_bits);
  96959. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  96960. }
  96961. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  96962. {
  96963. FLAC__ASSERT(0 != object);
  96964. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  96965. if(object->capacity_by_order < max_partition_order) {
  96966. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  96967. return false;
  96968. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  96969. return false;
  96970. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  96971. object->capacity_by_order = max_partition_order;
  96972. }
  96973. return true;
  96974. }
  96975. #endif
  96976. /*** End of inlined file: format.c ***/
  96977. /*** Start of inlined file: lpc_flac.c ***/
  96978. /*** Start of inlined file: juce_FlacHeader.h ***/
  96979. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96980. // tasks..
  96981. #define VERSION "1.2.1"
  96982. #define FLAC__NO_DLL 1
  96983. #if JUCE_MSVC
  96984. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96985. #endif
  96986. #if JUCE_MAC
  96987. #define FLAC__SYS_DARWIN 1
  96988. #endif
  96989. /*** End of inlined file: juce_FlacHeader.h ***/
  96990. #if JUCE_USE_FLAC
  96991. #if HAVE_CONFIG_H
  96992. # include <config.h>
  96993. #endif
  96994. #include <math.h>
  96995. /*** Start of inlined file: lpc.h ***/
  96996. #ifndef FLAC__PRIVATE__LPC_H
  96997. #define FLAC__PRIVATE__LPC_H
  96998. #ifdef HAVE_CONFIG_H
  96999. #include <config.h>
  97000. #endif
  97001. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97002. /*
  97003. * FLAC__lpc_window_data()
  97004. * --------------------------------------------------------------------
  97005. * Applies the given window to the data.
  97006. * OPT: asm implementation
  97007. *
  97008. * IN in[0,data_len-1]
  97009. * IN window[0,data_len-1]
  97010. * OUT out[0,lag-1]
  97011. * IN data_len
  97012. */
  97013. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  97014. /*
  97015. * FLAC__lpc_compute_autocorrelation()
  97016. * --------------------------------------------------------------------
  97017. * Compute the autocorrelation for lags between 0 and lag-1.
  97018. * Assumes data[] outside of [0,data_len-1] == 0.
  97019. * Asserts that lag > 0.
  97020. *
  97021. * IN data[0,data_len-1]
  97022. * IN data_len
  97023. * IN 0 < lag <= data_len
  97024. * OUT autoc[0,lag-1]
  97025. */
  97026. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97027. #ifndef FLAC__NO_ASM
  97028. # ifdef FLAC__CPU_IA32
  97029. # ifdef FLAC__HAS_NASM
  97030. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97031. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97032. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97033. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97034. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97035. # endif
  97036. # endif
  97037. #endif
  97038. /*
  97039. * FLAC__lpc_compute_lp_coefficients()
  97040. * --------------------------------------------------------------------
  97041. * Computes LP coefficients for orders 1..max_order.
  97042. * Do not call if autoc[0] == 0.0. This means the signal is zero
  97043. * and there is no point in calculating a predictor.
  97044. *
  97045. * IN autoc[0,max_order] autocorrelation values
  97046. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  97047. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  97048. * *** IMPORTANT:
  97049. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  97050. * OUT error[0,max_order-1] error for each order (more
  97051. * specifically, the variance of
  97052. * the error signal times # of
  97053. * samples in the signal)
  97054. *
  97055. * Example: if max_order is 9, the LP coefficients for order 9 will be
  97056. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  97057. * in lp_coeff[7][0,7], etc.
  97058. */
  97059. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  97060. /*
  97061. * FLAC__lpc_quantize_coefficients()
  97062. * --------------------------------------------------------------------
  97063. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  97064. * must be less than 32 (sizeof(FLAC__int32)*8).
  97065. *
  97066. * IN lp_coeff[0,order-1] LP coefficients
  97067. * IN order LP order
  97068. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  97069. * desired precision (in bits, including sign
  97070. * bit) of largest coefficient
  97071. * OUT qlp_coeff[0,order-1] quantized coefficients
  97072. * OUT shift # of bits to shift right to get approximated
  97073. * LP coefficients. NOTE: could be negative.
  97074. * RETURN 0 => quantization OK
  97075. * 1 => coefficients require too much shifting for *shift to
  97076. * fit in the LPC subframe header. 'shift' is unset.
  97077. * 2 => coefficients are all zero, which is bad. 'shift' is
  97078. * unset.
  97079. */
  97080. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  97081. /*
  97082. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  97083. * --------------------------------------------------------------------
  97084. * Compute the residual signal obtained from sutracting the predicted
  97085. * signal from the original.
  97086. *
  97087. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  97088. * IN data_len length of original signal
  97089. * IN qlp_coeff[0,order-1] quantized LP coefficients
  97090. * IN order > 0 LP order
  97091. * IN lp_quantization quantization of LP coefficients in bits
  97092. * OUT residual[0,data_len-1] residual signal
  97093. */
  97094. 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[]);
  97095. 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[]);
  97096. #ifndef FLAC__NO_ASM
  97097. # ifdef FLAC__CPU_IA32
  97098. # ifdef FLAC__HAS_NASM
  97099. 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[]);
  97100. 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[]);
  97101. # endif
  97102. # endif
  97103. #endif
  97104. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97105. /*
  97106. * FLAC__lpc_restore_signal()
  97107. * --------------------------------------------------------------------
  97108. * Restore the original signal by summing the residual and the
  97109. * predictor.
  97110. *
  97111. * IN residual[0,data_len-1] residual signal
  97112. * IN data_len length of original signal
  97113. * IN qlp_coeff[0,order-1] quantized LP coefficients
  97114. * IN order > 0 LP order
  97115. * IN lp_quantization quantization of LP coefficients in bits
  97116. * *** IMPORTANT: the caller must pass in the historical samples:
  97117. * IN data[-order,-1] previously-reconstructed historical samples
  97118. * OUT data[0,data_len-1] original signal
  97119. */
  97120. 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[]);
  97121. 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[]);
  97122. #ifndef FLAC__NO_ASM
  97123. # ifdef FLAC__CPU_IA32
  97124. # ifdef FLAC__HAS_NASM
  97125. 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[]);
  97126. 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[]);
  97127. # endif /* FLAC__HAS_NASM */
  97128. # elif defined FLAC__CPU_PPC
  97129. 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[]);
  97130. 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[]);
  97131. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  97132. #endif /* FLAC__NO_ASM */
  97133. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97134. /*
  97135. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  97136. * --------------------------------------------------------------------
  97137. * Compute the expected number of bits per residual signal sample
  97138. * based on the LP error (which is related to the residual variance).
  97139. *
  97140. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  97141. * IN total_samples > 0 # of samples in residual signal
  97142. * RETURN expected bits per sample
  97143. */
  97144. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  97145. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  97146. /*
  97147. * FLAC__lpc_compute_best_order()
  97148. * --------------------------------------------------------------------
  97149. * Compute the best order from the array of signal errors returned
  97150. * during coefficient computation.
  97151. *
  97152. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  97153. * IN max_order > 0 max LP order
  97154. * IN total_samples > 0 # of samples in residual signal
  97155. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  97156. * (includes warmup sample size and quantized LP coefficient)
  97157. * RETURN [1,max_order] best order
  97158. */
  97159. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  97160. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97161. #endif
  97162. /*** End of inlined file: lpc.h ***/
  97163. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  97164. #include <stdio.h>
  97165. #endif
  97166. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97167. #ifndef M_LN2
  97168. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  97169. #define M_LN2 0.69314718055994530942
  97170. #endif
  97171. /* OPT: #undef'ing this may improve the speed on some architectures */
  97172. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  97173. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  97174. {
  97175. unsigned i;
  97176. for(i = 0; i < data_len; i++)
  97177. out[i] = in[i] * window[i];
  97178. }
  97179. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  97180. {
  97181. /* a readable, but slower, version */
  97182. #if 0
  97183. FLAC__real d;
  97184. unsigned i;
  97185. FLAC__ASSERT(lag > 0);
  97186. FLAC__ASSERT(lag <= data_len);
  97187. /*
  97188. * Technically we should subtract the mean first like so:
  97189. * for(i = 0; i < data_len; i++)
  97190. * data[i] -= mean;
  97191. * but it appears not to make enough of a difference to matter, and
  97192. * most signals are already closely centered around zero
  97193. */
  97194. while(lag--) {
  97195. for(i = lag, d = 0.0; i < data_len; i++)
  97196. d += data[i] * data[i - lag];
  97197. autoc[lag] = d;
  97198. }
  97199. #endif
  97200. /*
  97201. * this version tends to run faster because of better data locality
  97202. * ('data_len' is usually much larger than 'lag')
  97203. */
  97204. FLAC__real d;
  97205. unsigned sample, coeff;
  97206. const unsigned limit = data_len - lag;
  97207. FLAC__ASSERT(lag > 0);
  97208. FLAC__ASSERT(lag <= data_len);
  97209. for(coeff = 0; coeff < lag; coeff++)
  97210. autoc[coeff] = 0.0;
  97211. for(sample = 0; sample <= limit; sample++) {
  97212. d = data[sample];
  97213. for(coeff = 0; coeff < lag; coeff++)
  97214. autoc[coeff] += d * data[sample+coeff];
  97215. }
  97216. for(; sample < data_len; sample++) {
  97217. d = data[sample];
  97218. for(coeff = 0; coeff < data_len - sample; coeff++)
  97219. autoc[coeff] += d * data[sample+coeff];
  97220. }
  97221. }
  97222. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  97223. {
  97224. unsigned i, j;
  97225. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  97226. FLAC__ASSERT(0 != max_order);
  97227. FLAC__ASSERT(0 < *max_order);
  97228. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  97229. FLAC__ASSERT(autoc[0] != 0.0);
  97230. err = autoc[0];
  97231. for(i = 0; i < *max_order; i++) {
  97232. /* Sum up this iteration's reflection coefficient. */
  97233. r = -autoc[i+1];
  97234. for(j = 0; j < i; j++)
  97235. r -= lpc[j] * autoc[i-j];
  97236. ref[i] = (r/=err);
  97237. /* Update LPC coefficients and total error. */
  97238. lpc[i]=r;
  97239. for(j = 0; j < (i>>1); j++) {
  97240. FLAC__double tmp = lpc[j];
  97241. lpc[j] += r * lpc[i-1-j];
  97242. lpc[i-1-j] += r * tmp;
  97243. }
  97244. if(i & 1)
  97245. lpc[j] += lpc[j] * r;
  97246. err *= (1.0 - r * r);
  97247. /* save this order */
  97248. for(j = 0; j <= i; j++)
  97249. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  97250. error[i] = err;
  97251. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  97252. if(err == 0.0) {
  97253. *max_order = i+1;
  97254. return;
  97255. }
  97256. }
  97257. }
  97258. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  97259. {
  97260. unsigned i;
  97261. FLAC__double cmax;
  97262. FLAC__int32 qmax, qmin;
  97263. FLAC__ASSERT(precision > 0);
  97264. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  97265. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  97266. precision--;
  97267. qmax = 1 << precision;
  97268. qmin = -qmax;
  97269. qmax--;
  97270. /* calc cmax = max( |lp_coeff[i]| ) */
  97271. cmax = 0.0;
  97272. for(i = 0; i < order; i++) {
  97273. const FLAC__double d = fabs(lp_coeff[i]);
  97274. if(d > cmax)
  97275. cmax = d;
  97276. }
  97277. if(cmax <= 0.0) {
  97278. /* => coefficients are all 0, which means our constant-detect didn't work */
  97279. return 2;
  97280. }
  97281. else {
  97282. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  97283. const int min_shiftlimit = -max_shiftlimit - 1;
  97284. int log2cmax;
  97285. (void)frexp(cmax, &log2cmax);
  97286. log2cmax--;
  97287. *shift = (int)precision - log2cmax - 1;
  97288. if(*shift > max_shiftlimit)
  97289. *shift = max_shiftlimit;
  97290. else if(*shift < min_shiftlimit)
  97291. return 1;
  97292. }
  97293. if(*shift >= 0) {
  97294. FLAC__double error = 0.0;
  97295. FLAC__int32 q;
  97296. for(i = 0; i < order; i++) {
  97297. error += lp_coeff[i] * (1 << *shift);
  97298. #if 1 /* unfortunately lround() is C99 */
  97299. if(error >= 0.0)
  97300. q = (FLAC__int32)(error + 0.5);
  97301. else
  97302. q = (FLAC__int32)(error - 0.5);
  97303. #else
  97304. q = lround(error);
  97305. #endif
  97306. #ifdef FLAC__OVERFLOW_DETECT
  97307. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97308. 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]);
  97309. else if(q < qmin)
  97310. 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]);
  97311. #endif
  97312. if(q > qmax)
  97313. q = qmax;
  97314. else if(q < qmin)
  97315. q = qmin;
  97316. error -= q;
  97317. qlp_coeff[i] = q;
  97318. }
  97319. }
  97320. /* negative shift is very rare but due to design flaw, negative shift is
  97321. * a NOP in the decoder, so it must be handled specially by scaling down
  97322. * coeffs
  97323. */
  97324. else {
  97325. const int nshift = -(*shift);
  97326. FLAC__double error = 0.0;
  97327. FLAC__int32 q;
  97328. #ifdef DEBUG
  97329. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  97330. #endif
  97331. for(i = 0; i < order; i++) {
  97332. error += lp_coeff[i] / (1 << nshift);
  97333. #if 1 /* unfortunately lround() is C99 */
  97334. if(error >= 0.0)
  97335. q = (FLAC__int32)(error + 0.5);
  97336. else
  97337. q = (FLAC__int32)(error - 0.5);
  97338. #else
  97339. q = lround(error);
  97340. #endif
  97341. #ifdef FLAC__OVERFLOW_DETECT
  97342. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97343. 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]);
  97344. else if(q < qmin)
  97345. 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]);
  97346. #endif
  97347. if(q > qmax)
  97348. q = qmax;
  97349. else if(q < qmin)
  97350. q = qmin;
  97351. error -= q;
  97352. qlp_coeff[i] = q;
  97353. }
  97354. *shift = 0;
  97355. }
  97356. return 0;
  97357. }
  97358. 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[])
  97359. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97360. {
  97361. FLAC__int64 sumo;
  97362. unsigned i, j;
  97363. FLAC__int32 sum;
  97364. const FLAC__int32 *history;
  97365. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97366. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97367. for(i=0;i<order;i++)
  97368. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97369. fprintf(stderr,"\n");
  97370. #endif
  97371. FLAC__ASSERT(order > 0);
  97372. for(i = 0; i < data_len; i++) {
  97373. sumo = 0;
  97374. sum = 0;
  97375. history = data;
  97376. for(j = 0; j < order; j++) {
  97377. sum += qlp_coeff[j] * (*(--history));
  97378. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97379. #if defined _MSC_VER
  97380. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97381. 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);
  97382. #else
  97383. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97384. 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);
  97385. #endif
  97386. }
  97387. *(residual++) = *(data++) - (sum >> lp_quantization);
  97388. }
  97389. /* Here's a slower but clearer version:
  97390. for(i = 0; i < data_len; i++) {
  97391. sum = 0;
  97392. for(j = 0; j < order; j++)
  97393. sum += qlp_coeff[j] * data[i-j-1];
  97394. residual[i] = data[i] - (sum >> lp_quantization);
  97395. }
  97396. */
  97397. }
  97398. #else /* fully unrolled version for normal use */
  97399. {
  97400. int i;
  97401. FLAC__int32 sum;
  97402. FLAC__ASSERT(order > 0);
  97403. FLAC__ASSERT(order <= 32);
  97404. /*
  97405. * We do unique versions up to 12th order since that's the subset limit.
  97406. * Also they are roughly ordered to match frequency of occurrence to
  97407. * minimize branching.
  97408. */
  97409. if(order <= 12) {
  97410. if(order > 8) {
  97411. if(order > 10) {
  97412. if(order == 12) {
  97413. for(i = 0; i < (int)data_len; i++) {
  97414. sum = 0;
  97415. sum += qlp_coeff[11] * data[i-12];
  97416. sum += qlp_coeff[10] * data[i-11];
  97417. sum += qlp_coeff[9] * data[i-10];
  97418. sum += qlp_coeff[8] * data[i-9];
  97419. sum += qlp_coeff[7] * data[i-8];
  97420. sum += qlp_coeff[6] * data[i-7];
  97421. sum += qlp_coeff[5] * data[i-6];
  97422. sum += qlp_coeff[4] * data[i-5];
  97423. sum += qlp_coeff[3] * data[i-4];
  97424. sum += qlp_coeff[2] * data[i-3];
  97425. sum += qlp_coeff[1] * data[i-2];
  97426. sum += qlp_coeff[0] * data[i-1];
  97427. residual[i] = data[i] - (sum >> lp_quantization);
  97428. }
  97429. }
  97430. else { /* order == 11 */
  97431. for(i = 0; i < (int)data_len; i++) {
  97432. sum = 0;
  97433. sum += qlp_coeff[10] * data[i-11];
  97434. sum += qlp_coeff[9] * data[i-10];
  97435. sum += qlp_coeff[8] * data[i-9];
  97436. sum += qlp_coeff[7] * data[i-8];
  97437. sum += qlp_coeff[6] * data[i-7];
  97438. sum += qlp_coeff[5] * data[i-6];
  97439. sum += qlp_coeff[4] * data[i-5];
  97440. sum += qlp_coeff[3] * data[i-4];
  97441. sum += qlp_coeff[2] * data[i-3];
  97442. sum += qlp_coeff[1] * data[i-2];
  97443. sum += qlp_coeff[0] * data[i-1];
  97444. residual[i] = data[i] - (sum >> lp_quantization);
  97445. }
  97446. }
  97447. }
  97448. else {
  97449. if(order == 10) {
  97450. for(i = 0; i < (int)data_len; i++) {
  97451. sum = 0;
  97452. sum += qlp_coeff[9] * data[i-10];
  97453. sum += qlp_coeff[8] * data[i-9];
  97454. sum += qlp_coeff[7] * data[i-8];
  97455. sum += qlp_coeff[6] * data[i-7];
  97456. sum += qlp_coeff[5] * data[i-6];
  97457. sum += qlp_coeff[4] * data[i-5];
  97458. sum += qlp_coeff[3] * data[i-4];
  97459. sum += qlp_coeff[2] * data[i-3];
  97460. sum += qlp_coeff[1] * data[i-2];
  97461. sum += qlp_coeff[0] * data[i-1];
  97462. residual[i] = data[i] - (sum >> lp_quantization);
  97463. }
  97464. }
  97465. else { /* order == 9 */
  97466. for(i = 0; i < (int)data_len; i++) {
  97467. sum = 0;
  97468. sum += qlp_coeff[8] * data[i-9];
  97469. sum += qlp_coeff[7] * data[i-8];
  97470. sum += qlp_coeff[6] * data[i-7];
  97471. sum += qlp_coeff[5] * data[i-6];
  97472. sum += qlp_coeff[4] * data[i-5];
  97473. sum += qlp_coeff[3] * data[i-4];
  97474. sum += qlp_coeff[2] * data[i-3];
  97475. sum += qlp_coeff[1] * data[i-2];
  97476. sum += qlp_coeff[0] * data[i-1];
  97477. residual[i] = data[i] - (sum >> lp_quantization);
  97478. }
  97479. }
  97480. }
  97481. }
  97482. else if(order > 4) {
  97483. if(order > 6) {
  97484. if(order == 8) {
  97485. for(i = 0; i < (int)data_len; i++) {
  97486. sum = 0;
  97487. sum += qlp_coeff[7] * data[i-8];
  97488. sum += qlp_coeff[6] * data[i-7];
  97489. sum += qlp_coeff[5] * data[i-6];
  97490. sum += qlp_coeff[4] * data[i-5];
  97491. sum += qlp_coeff[3] * data[i-4];
  97492. sum += qlp_coeff[2] * data[i-3];
  97493. sum += qlp_coeff[1] * data[i-2];
  97494. sum += qlp_coeff[0] * data[i-1];
  97495. residual[i] = data[i] - (sum >> lp_quantization);
  97496. }
  97497. }
  97498. else { /* order == 7 */
  97499. for(i = 0; i < (int)data_len; i++) {
  97500. sum = 0;
  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. else {
  97513. if(order == 6) {
  97514. for(i = 0; i < (int)data_len; i++) {
  97515. sum = 0;
  97516. sum += qlp_coeff[5] * data[i-6];
  97517. sum += qlp_coeff[4] * data[i-5];
  97518. sum += qlp_coeff[3] * data[i-4];
  97519. sum += qlp_coeff[2] * data[i-3];
  97520. sum += qlp_coeff[1] * data[i-2];
  97521. sum += qlp_coeff[0] * data[i-1];
  97522. residual[i] = data[i] - (sum >> lp_quantization);
  97523. }
  97524. }
  97525. else { /* order == 5 */
  97526. for(i = 0; i < (int)data_len; i++) {
  97527. sum = 0;
  97528. sum += qlp_coeff[4] * data[i-5];
  97529. sum += qlp_coeff[3] * data[i-4];
  97530. sum += qlp_coeff[2] * data[i-3];
  97531. sum += qlp_coeff[1] * data[i-2];
  97532. sum += qlp_coeff[0] * data[i-1];
  97533. residual[i] = data[i] - (sum >> lp_quantization);
  97534. }
  97535. }
  97536. }
  97537. }
  97538. else {
  97539. if(order > 2) {
  97540. if(order == 4) {
  97541. for(i = 0; i < (int)data_len; i++) {
  97542. sum = 0;
  97543. sum += qlp_coeff[3] * data[i-4];
  97544. sum += qlp_coeff[2] * data[i-3];
  97545. sum += qlp_coeff[1] * data[i-2];
  97546. sum += qlp_coeff[0] * data[i-1];
  97547. residual[i] = data[i] - (sum >> lp_quantization);
  97548. }
  97549. }
  97550. else { /* order == 3 */
  97551. for(i = 0; i < (int)data_len; i++) {
  97552. sum = 0;
  97553. sum += qlp_coeff[2] * data[i-3];
  97554. sum += qlp_coeff[1] * data[i-2];
  97555. sum += qlp_coeff[0] * data[i-1];
  97556. residual[i] = data[i] - (sum >> lp_quantization);
  97557. }
  97558. }
  97559. }
  97560. else {
  97561. if(order == 2) {
  97562. for(i = 0; i < (int)data_len; i++) {
  97563. sum = 0;
  97564. sum += qlp_coeff[1] * data[i-2];
  97565. sum += qlp_coeff[0] * data[i-1];
  97566. residual[i] = data[i] - (sum >> lp_quantization);
  97567. }
  97568. }
  97569. else { /* order == 1 */
  97570. for(i = 0; i < (int)data_len; i++)
  97571. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  97572. }
  97573. }
  97574. }
  97575. }
  97576. else { /* order > 12 */
  97577. for(i = 0; i < (int)data_len; i++) {
  97578. sum = 0;
  97579. switch(order) {
  97580. case 32: sum += qlp_coeff[31] * data[i-32];
  97581. case 31: sum += qlp_coeff[30] * data[i-31];
  97582. case 30: sum += qlp_coeff[29] * data[i-30];
  97583. case 29: sum += qlp_coeff[28] * data[i-29];
  97584. case 28: sum += qlp_coeff[27] * data[i-28];
  97585. case 27: sum += qlp_coeff[26] * data[i-27];
  97586. case 26: sum += qlp_coeff[25] * data[i-26];
  97587. case 25: sum += qlp_coeff[24] * data[i-25];
  97588. case 24: sum += qlp_coeff[23] * data[i-24];
  97589. case 23: sum += qlp_coeff[22] * data[i-23];
  97590. case 22: sum += qlp_coeff[21] * data[i-22];
  97591. case 21: sum += qlp_coeff[20] * data[i-21];
  97592. case 20: sum += qlp_coeff[19] * data[i-20];
  97593. case 19: sum += qlp_coeff[18] * data[i-19];
  97594. case 18: sum += qlp_coeff[17] * data[i-18];
  97595. case 17: sum += qlp_coeff[16] * data[i-17];
  97596. case 16: sum += qlp_coeff[15] * data[i-16];
  97597. case 15: sum += qlp_coeff[14] * data[i-15];
  97598. case 14: sum += qlp_coeff[13] * data[i-14];
  97599. case 13: sum += qlp_coeff[12] * data[i-13];
  97600. sum += qlp_coeff[11] * data[i-12];
  97601. sum += qlp_coeff[10] * data[i-11];
  97602. sum += qlp_coeff[ 9] * data[i-10];
  97603. sum += qlp_coeff[ 8] * data[i- 9];
  97604. sum += qlp_coeff[ 7] * data[i- 8];
  97605. sum += qlp_coeff[ 6] * data[i- 7];
  97606. sum += qlp_coeff[ 5] * data[i- 6];
  97607. sum += qlp_coeff[ 4] * data[i- 5];
  97608. sum += qlp_coeff[ 3] * data[i- 4];
  97609. sum += qlp_coeff[ 2] * data[i- 3];
  97610. sum += qlp_coeff[ 1] * data[i- 2];
  97611. sum += qlp_coeff[ 0] * data[i- 1];
  97612. }
  97613. residual[i] = data[i] - (sum >> lp_quantization);
  97614. }
  97615. }
  97616. }
  97617. #endif
  97618. 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[])
  97619. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97620. {
  97621. unsigned i, j;
  97622. FLAC__int64 sum;
  97623. const FLAC__int32 *history;
  97624. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97625. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97626. for(i=0;i<order;i++)
  97627. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97628. fprintf(stderr,"\n");
  97629. #endif
  97630. FLAC__ASSERT(order > 0);
  97631. for(i = 0; i < data_len; i++) {
  97632. sum = 0;
  97633. history = data;
  97634. for(j = 0; j < order; j++)
  97635. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  97636. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  97637. #if defined _MSC_VER
  97638. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  97639. #else
  97640. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  97641. #endif
  97642. break;
  97643. }
  97644. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  97645. #if defined _MSC_VER
  97646. 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));
  97647. #else
  97648. 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)));
  97649. #endif
  97650. break;
  97651. }
  97652. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  97653. }
  97654. }
  97655. #else /* fully unrolled version for normal use */
  97656. {
  97657. int i;
  97658. FLAC__int64 sum;
  97659. FLAC__ASSERT(order > 0);
  97660. FLAC__ASSERT(order <= 32);
  97661. /*
  97662. * We do unique versions up to 12th order since that's the subset limit.
  97663. * Also they are roughly ordered to match frequency of occurrence to
  97664. * minimize branching.
  97665. */
  97666. if(order <= 12) {
  97667. if(order > 8) {
  97668. if(order > 10) {
  97669. if(order == 12) {
  97670. for(i = 0; i < (int)data_len; i++) {
  97671. sum = 0;
  97672. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97673. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97674. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97675. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97676. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97677. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97678. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97679. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97680. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97681. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97682. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97683. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97684. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97685. }
  97686. }
  97687. else { /* order == 11 */
  97688. for(i = 0; i < (int)data_len; i++) {
  97689. sum = 0;
  97690. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97691. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97692. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97693. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97694. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97695. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97696. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97697. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97698. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97699. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97700. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97701. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97702. }
  97703. }
  97704. }
  97705. else {
  97706. if(order == 10) {
  97707. for(i = 0; i < (int)data_len; i++) {
  97708. sum = 0;
  97709. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97710. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97711. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97712. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97713. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97714. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97715. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97716. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97717. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97718. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97719. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97720. }
  97721. }
  97722. else { /* order == 9 */
  97723. for(i = 0; i < (int)data_len; i++) {
  97724. sum = 0;
  97725. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97726. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97727. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97728. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97729. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97730. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97731. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97732. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97733. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97734. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97735. }
  97736. }
  97737. }
  97738. }
  97739. else if(order > 4) {
  97740. if(order > 6) {
  97741. if(order == 8) {
  97742. for(i = 0; i < (int)data_len; i++) {
  97743. sum = 0;
  97744. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97745. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97746. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97747. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97748. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97749. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97750. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97751. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97752. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97753. }
  97754. }
  97755. else { /* order == 7 */
  97756. for(i = 0; i < (int)data_len; i++) {
  97757. sum = 0;
  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. else {
  97770. if(order == 6) {
  97771. for(i = 0; i < (int)data_len; i++) {
  97772. sum = 0;
  97773. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97774. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97775. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97776. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97777. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97778. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97779. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97780. }
  97781. }
  97782. else { /* order == 5 */
  97783. for(i = 0; i < (int)data_len; i++) {
  97784. sum = 0;
  97785. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97786. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97787. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97788. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97789. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97790. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97791. }
  97792. }
  97793. }
  97794. }
  97795. else {
  97796. if(order > 2) {
  97797. if(order == 4) {
  97798. for(i = 0; i < (int)data_len; i++) {
  97799. sum = 0;
  97800. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97801. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97802. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97803. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97804. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97805. }
  97806. }
  97807. else { /* order == 3 */
  97808. for(i = 0; i < (int)data_len; i++) {
  97809. sum = 0;
  97810. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97811. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97812. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97813. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97814. }
  97815. }
  97816. }
  97817. else {
  97818. if(order == 2) {
  97819. for(i = 0; i < (int)data_len; i++) {
  97820. sum = 0;
  97821. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97822. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97823. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97824. }
  97825. }
  97826. else { /* order == 1 */
  97827. for(i = 0; i < (int)data_len; i++)
  97828. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  97829. }
  97830. }
  97831. }
  97832. }
  97833. else { /* order > 12 */
  97834. for(i = 0; i < (int)data_len; i++) {
  97835. sum = 0;
  97836. switch(order) {
  97837. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  97838. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  97839. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  97840. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  97841. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  97842. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  97843. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  97844. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  97845. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  97846. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  97847. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  97848. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  97849. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  97850. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  97851. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  97852. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  97853. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  97854. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  97855. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  97856. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  97857. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97858. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97859. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  97860. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  97861. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  97862. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  97863. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  97864. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  97865. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  97866. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  97867. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  97868. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  97869. }
  97870. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97871. }
  97872. }
  97873. }
  97874. #endif
  97875. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97876. 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[])
  97877. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97878. {
  97879. FLAC__int64 sumo;
  97880. unsigned i, j;
  97881. FLAC__int32 sum;
  97882. const FLAC__int32 *r = residual, *history;
  97883. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97884. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97885. for(i=0;i<order;i++)
  97886. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97887. fprintf(stderr,"\n");
  97888. #endif
  97889. FLAC__ASSERT(order > 0);
  97890. for(i = 0; i < data_len; i++) {
  97891. sumo = 0;
  97892. sum = 0;
  97893. history = data;
  97894. for(j = 0; j < order; j++) {
  97895. sum += qlp_coeff[j] * (*(--history));
  97896. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97897. #if defined _MSC_VER
  97898. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97899. 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);
  97900. #else
  97901. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97902. 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);
  97903. #endif
  97904. }
  97905. *(data++) = *(r++) + (sum >> lp_quantization);
  97906. }
  97907. /* Here's a slower but clearer version:
  97908. for(i = 0; i < data_len; i++) {
  97909. sum = 0;
  97910. for(j = 0; j < order; j++)
  97911. sum += qlp_coeff[j] * data[i-j-1];
  97912. data[i] = residual[i] + (sum >> lp_quantization);
  97913. }
  97914. */
  97915. }
  97916. #else /* fully unrolled version for normal use */
  97917. {
  97918. int i;
  97919. FLAC__int32 sum;
  97920. FLAC__ASSERT(order > 0);
  97921. FLAC__ASSERT(order <= 32);
  97922. /*
  97923. * We do unique versions up to 12th order since that's the subset limit.
  97924. * Also they are roughly ordered to match frequency of occurrence to
  97925. * minimize branching.
  97926. */
  97927. if(order <= 12) {
  97928. if(order > 8) {
  97929. if(order > 10) {
  97930. if(order == 12) {
  97931. for(i = 0; i < (int)data_len; i++) {
  97932. sum = 0;
  97933. sum += qlp_coeff[11] * data[i-12];
  97934. sum += qlp_coeff[10] * data[i-11];
  97935. sum += qlp_coeff[9] * data[i-10];
  97936. sum += qlp_coeff[8] * data[i-9];
  97937. sum += qlp_coeff[7] * data[i-8];
  97938. sum += qlp_coeff[6] * data[i-7];
  97939. sum += qlp_coeff[5] * data[i-6];
  97940. sum += qlp_coeff[4] * data[i-5];
  97941. sum += qlp_coeff[3] * data[i-4];
  97942. sum += qlp_coeff[2] * data[i-3];
  97943. sum += qlp_coeff[1] * data[i-2];
  97944. sum += qlp_coeff[0] * data[i-1];
  97945. data[i] = residual[i] + (sum >> lp_quantization);
  97946. }
  97947. }
  97948. else { /* order == 11 */
  97949. for(i = 0; i < (int)data_len; i++) {
  97950. sum = 0;
  97951. sum += qlp_coeff[10] * data[i-11];
  97952. sum += qlp_coeff[9] * data[i-10];
  97953. sum += qlp_coeff[8] * data[i-9];
  97954. sum += qlp_coeff[7] * data[i-8];
  97955. sum += qlp_coeff[6] * data[i-7];
  97956. sum += qlp_coeff[5] * data[i-6];
  97957. sum += qlp_coeff[4] * data[i-5];
  97958. sum += qlp_coeff[3] * data[i-4];
  97959. sum += qlp_coeff[2] * data[i-3];
  97960. sum += qlp_coeff[1] * data[i-2];
  97961. sum += qlp_coeff[0] * data[i-1];
  97962. data[i] = residual[i] + (sum >> lp_quantization);
  97963. }
  97964. }
  97965. }
  97966. else {
  97967. if(order == 10) {
  97968. for(i = 0; i < (int)data_len; i++) {
  97969. sum = 0;
  97970. sum += qlp_coeff[9] * data[i-10];
  97971. sum += qlp_coeff[8] * data[i-9];
  97972. sum += qlp_coeff[7] * data[i-8];
  97973. sum += qlp_coeff[6] * data[i-7];
  97974. sum += qlp_coeff[5] * data[i-6];
  97975. sum += qlp_coeff[4] * data[i-5];
  97976. sum += qlp_coeff[3] * data[i-4];
  97977. sum += qlp_coeff[2] * data[i-3];
  97978. sum += qlp_coeff[1] * data[i-2];
  97979. sum += qlp_coeff[0] * data[i-1];
  97980. data[i] = residual[i] + (sum >> lp_quantization);
  97981. }
  97982. }
  97983. else { /* order == 9 */
  97984. for(i = 0; i < (int)data_len; i++) {
  97985. sum = 0;
  97986. sum += qlp_coeff[8] * data[i-9];
  97987. sum += qlp_coeff[7] * data[i-8];
  97988. sum += qlp_coeff[6] * data[i-7];
  97989. sum += qlp_coeff[5] * data[i-6];
  97990. sum += qlp_coeff[4] * data[i-5];
  97991. sum += qlp_coeff[3] * data[i-4];
  97992. sum += qlp_coeff[2] * data[i-3];
  97993. sum += qlp_coeff[1] * data[i-2];
  97994. sum += qlp_coeff[0] * data[i-1];
  97995. data[i] = residual[i] + (sum >> lp_quantization);
  97996. }
  97997. }
  97998. }
  97999. }
  98000. else if(order > 4) {
  98001. if(order > 6) {
  98002. if(order == 8) {
  98003. for(i = 0; i < (int)data_len; i++) {
  98004. sum = 0;
  98005. sum += qlp_coeff[7] * data[i-8];
  98006. sum += qlp_coeff[6] * data[i-7];
  98007. sum += qlp_coeff[5] * data[i-6];
  98008. sum += qlp_coeff[4] * data[i-5];
  98009. sum += qlp_coeff[3] * data[i-4];
  98010. sum += qlp_coeff[2] * data[i-3];
  98011. sum += qlp_coeff[1] * data[i-2];
  98012. sum += qlp_coeff[0] * data[i-1];
  98013. data[i] = residual[i] + (sum >> lp_quantization);
  98014. }
  98015. }
  98016. else { /* order == 7 */
  98017. for(i = 0; i < (int)data_len; i++) {
  98018. sum = 0;
  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. else {
  98031. if(order == 6) {
  98032. for(i = 0; i < (int)data_len; i++) {
  98033. sum = 0;
  98034. sum += qlp_coeff[5] * data[i-6];
  98035. sum += qlp_coeff[4] * data[i-5];
  98036. sum += qlp_coeff[3] * data[i-4];
  98037. sum += qlp_coeff[2] * data[i-3];
  98038. sum += qlp_coeff[1] * data[i-2];
  98039. sum += qlp_coeff[0] * data[i-1];
  98040. data[i] = residual[i] + (sum >> lp_quantization);
  98041. }
  98042. }
  98043. else { /* order == 5 */
  98044. for(i = 0; i < (int)data_len; i++) {
  98045. sum = 0;
  98046. sum += qlp_coeff[4] * data[i-5];
  98047. sum += qlp_coeff[3] * data[i-4];
  98048. sum += qlp_coeff[2] * data[i-3];
  98049. sum += qlp_coeff[1] * data[i-2];
  98050. sum += qlp_coeff[0] * data[i-1];
  98051. data[i] = residual[i] + (sum >> lp_quantization);
  98052. }
  98053. }
  98054. }
  98055. }
  98056. else {
  98057. if(order > 2) {
  98058. if(order == 4) {
  98059. for(i = 0; i < (int)data_len; i++) {
  98060. sum = 0;
  98061. sum += qlp_coeff[3] * data[i-4];
  98062. sum += qlp_coeff[2] * data[i-3];
  98063. sum += qlp_coeff[1] * data[i-2];
  98064. sum += qlp_coeff[0] * data[i-1];
  98065. data[i] = residual[i] + (sum >> lp_quantization);
  98066. }
  98067. }
  98068. else { /* order == 3 */
  98069. for(i = 0; i < (int)data_len; i++) {
  98070. sum = 0;
  98071. sum += qlp_coeff[2] * data[i-3];
  98072. sum += qlp_coeff[1] * data[i-2];
  98073. sum += qlp_coeff[0] * data[i-1];
  98074. data[i] = residual[i] + (sum >> lp_quantization);
  98075. }
  98076. }
  98077. }
  98078. else {
  98079. if(order == 2) {
  98080. for(i = 0; i < (int)data_len; i++) {
  98081. sum = 0;
  98082. sum += qlp_coeff[1] * data[i-2];
  98083. sum += qlp_coeff[0] * data[i-1];
  98084. data[i] = residual[i] + (sum >> lp_quantization);
  98085. }
  98086. }
  98087. else { /* order == 1 */
  98088. for(i = 0; i < (int)data_len; i++)
  98089. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  98090. }
  98091. }
  98092. }
  98093. }
  98094. else { /* order > 12 */
  98095. for(i = 0; i < (int)data_len; i++) {
  98096. sum = 0;
  98097. switch(order) {
  98098. case 32: sum += qlp_coeff[31] * data[i-32];
  98099. case 31: sum += qlp_coeff[30] * data[i-31];
  98100. case 30: sum += qlp_coeff[29] * data[i-30];
  98101. case 29: sum += qlp_coeff[28] * data[i-29];
  98102. case 28: sum += qlp_coeff[27] * data[i-28];
  98103. case 27: sum += qlp_coeff[26] * data[i-27];
  98104. case 26: sum += qlp_coeff[25] * data[i-26];
  98105. case 25: sum += qlp_coeff[24] * data[i-25];
  98106. case 24: sum += qlp_coeff[23] * data[i-24];
  98107. case 23: sum += qlp_coeff[22] * data[i-23];
  98108. case 22: sum += qlp_coeff[21] * data[i-22];
  98109. case 21: sum += qlp_coeff[20] * data[i-21];
  98110. case 20: sum += qlp_coeff[19] * data[i-20];
  98111. case 19: sum += qlp_coeff[18] * data[i-19];
  98112. case 18: sum += qlp_coeff[17] * data[i-18];
  98113. case 17: sum += qlp_coeff[16] * data[i-17];
  98114. case 16: sum += qlp_coeff[15] * data[i-16];
  98115. case 15: sum += qlp_coeff[14] * data[i-15];
  98116. case 14: sum += qlp_coeff[13] * data[i-14];
  98117. case 13: sum += qlp_coeff[12] * data[i-13];
  98118. sum += qlp_coeff[11] * data[i-12];
  98119. sum += qlp_coeff[10] * data[i-11];
  98120. sum += qlp_coeff[ 9] * data[i-10];
  98121. sum += qlp_coeff[ 8] * data[i- 9];
  98122. sum += qlp_coeff[ 7] * data[i- 8];
  98123. sum += qlp_coeff[ 6] * data[i- 7];
  98124. sum += qlp_coeff[ 5] * data[i- 6];
  98125. sum += qlp_coeff[ 4] * data[i- 5];
  98126. sum += qlp_coeff[ 3] * data[i- 4];
  98127. sum += qlp_coeff[ 2] * data[i- 3];
  98128. sum += qlp_coeff[ 1] * data[i- 2];
  98129. sum += qlp_coeff[ 0] * data[i- 1];
  98130. }
  98131. data[i] = residual[i] + (sum >> lp_quantization);
  98132. }
  98133. }
  98134. }
  98135. #endif
  98136. 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[])
  98137. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  98138. {
  98139. unsigned i, j;
  98140. FLAC__int64 sum;
  98141. const FLAC__int32 *r = residual, *history;
  98142. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  98143. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  98144. for(i=0;i<order;i++)
  98145. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  98146. fprintf(stderr,"\n");
  98147. #endif
  98148. FLAC__ASSERT(order > 0);
  98149. for(i = 0; i < data_len; i++) {
  98150. sum = 0;
  98151. history = data;
  98152. for(j = 0; j < order; j++)
  98153. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  98154. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  98155. #ifdef _MSC_VER
  98156. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  98157. #else
  98158. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  98159. #endif
  98160. break;
  98161. }
  98162. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  98163. #ifdef _MSC_VER
  98164. 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));
  98165. #else
  98166. 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)));
  98167. #endif
  98168. break;
  98169. }
  98170. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  98171. }
  98172. }
  98173. #else /* fully unrolled version for normal use */
  98174. {
  98175. int i;
  98176. FLAC__int64 sum;
  98177. FLAC__ASSERT(order > 0);
  98178. FLAC__ASSERT(order <= 32);
  98179. /*
  98180. * We do unique versions up to 12th order since that's the subset limit.
  98181. * Also they are roughly ordered to match frequency of occurrence to
  98182. * minimize branching.
  98183. */
  98184. if(order <= 12) {
  98185. if(order > 8) {
  98186. if(order > 10) {
  98187. if(order == 12) {
  98188. for(i = 0; i < (int)data_len; i++) {
  98189. sum = 0;
  98190. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98191. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98192. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98193. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98194. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98195. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98196. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98197. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98198. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98199. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98200. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98201. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98202. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98203. }
  98204. }
  98205. else { /* order == 11 */
  98206. for(i = 0; i < (int)data_len; i++) {
  98207. sum = 0;
  98208. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98209. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98210. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98211. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98212. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98213. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98214. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98215. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98216. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98217. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98218. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98219. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98220. }
  98221. }
  98222. }
  98223. else {
  98224. if(order == 10) {
  98225. for(i = 0; i < (int)data_len; i++) {
  98226. sum = 0;
  98227. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98228. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98229. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98230. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98231. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98232. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98233. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98234. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98235. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98236. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98237. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98238. }
  98239. }
  98240. else { /* order == 9 */
  98241. for(i = 0; i < (int)data_len; i++) {
  98242. sum = 0;
  98243. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98244. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98245. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98246. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98247. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98248. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98249. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98250. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98251. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98252. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98253. }
  98254. }
  98255. }
  98256. }
  98257. else if(order > 4) {
  98258. if(order > 6) {
  98259. if(order == 8) {
  98260. for(i = 0; i < (int)data_len; i++) {
  98261. sum = 0;
  98262. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98263. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98264. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98265. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98266. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98267. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98268. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98269. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98270. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98271. }
  98272. }
  98273. else { /* order == 7 */
  98274. for(i = 0; i < (int)data_len; i++) {
  98275. sum = 0;
  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. else {
  98288. if(order == 6) {
  98289. for(i = 0; i < (int)data_len; i++) {
  98290. sum = 0;
  98291. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98292. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98293. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98294. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98295. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98296. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98297. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98298. }
  98299. }
  98300. else { /* order == 5 */
  98301. for(i = 0; i < (int)data_len; i++) {
  98302. sum = 0;
  98303. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98304. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98305. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98306. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98307. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98308. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98309. }
  98310. }
  98311. }
  98312. }
  98313. else {
  98314. if(order > 2) {
  98315. if(order == 4) {
  98316. for(i = 0; i < (int)data_len; i++) {
  98317. sum = 0;
  98318. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98319. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98320. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98321. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98322. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98323. }
  98324. }
  98325. else { /* order == 3 */
  98326. for(i = 0; i < (int)data_len; i++) {
  98327. sum = 0;
  98328. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98329. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98330. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98331. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98332. }
  98333. }
  98334. }
  98335. else {
  98336. if(order == 2) {
  98337. for(i = 0; i < (int)data_len; i++) {
  98338. sum = 0;
  98339. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98340. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98341. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98342. }
  98343. }
  98344. else { /* order == 1 */
  98345. for(i = 0; i < (int)data_len; i++)
  98346. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  98347. }
  98348. }
  98349. }
  98350. }
  98351. else { /* order > 12 */
  98352. for(i = 0; i < (int)data_len; i++) {
  98353. sum = 0;
  98354. switch(order) {
  98355. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  98356. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  98357. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  98358. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  98359. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  98360. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  98361. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  98362. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  98363. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  98364. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  98365. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  98366. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  98367. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  98368. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  98369. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  98370. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  98371. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  98372. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  98373. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  98374. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  98375. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98376. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98377. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  98378. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  98379. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  98380. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  98381. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  98382. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  98383. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  98384. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  98385. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  98386. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  98387. }
  98388. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98389. }
  98390. }
  98391. }
  98392. #endif
  98393. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98394. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  98395. {
  98396. FLAC__double error_scale;
  98397. FLAC__ASSERT(total_samples > 0);
  98398. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98399. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  98400. }
  98401. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  98402. {
  98403. if(lpc_error > 0.0) {
  98404. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  98405. if(bps >= 0.0)
  98406. return bps;
  98407. else
  98408. return 0.0;
  98409. }
  98410. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  98411. return 1e32;
  98412. }
  98413. else {
  98414. return 0.0;
  98415. }
  98416. }
  98417. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  98418. {
  98419. 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 */
  98420. FLAC__double bits, best_bits, error_scale;
  98421. FLAC__ASSERT(max_order > 0);
  98422. FLAC__ASSERT(total_samples > 0);
  98423. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98424. best_index = 0;
  98425. best_bits = (unsigned)(-1);
  98426. for(index = 0, order = 1; index < max_order; index++, order++) {
  98427. 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);
  98428. if(bits < best_bits) {
  98429. best_index = index;
  98430. best_bits = bits;
  98431. }
  98432. }
  98433. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  98434. }
  98435. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  98436. #endif
  98437. /*** End of inlined file: lpc_flac.c ***/
  98438. /*** Start of inlined file: md5.c ***/
  98439. /*** Start of inlined file: juce_FlacHeader.h ***/
  98440. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98441. // tasks..
  98442. #define VERSION "1.2.1"
  98443. #define FLAC__NO_DLL 1
  98444. #if JUCE_MSVC
  98445. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98446. #endif
  98447. #if JUCE_MAC
  98448. #define FLAC__SYS_DARWIN 1
  98449. #endif
  98450. /*** End of inlined file: juce_FlacHeader.h ***/
  98451. #if JUCE_USE_FLAC
  98452. #if HAVE_CONFIG_H
  98453. # include <config.h>
  98454. #endif
  98455. #include <stdlib.h> /* for malloc() */
  98456. #include <string.h> /* for memcpy() */
  98457. /*** Start of inlined file: md5.h ***/
  98458. #ifndef FLAC__PRIVATE__MD5_H
  98459. #define FLAC__PRIVATE__MD5_H
  98460. /*
  98461. * This is the header file for the MD5 message-digest algorithm.
  98462. * The algorithm is due to Ron Rivest. This code was
  98463. * written by Colin Plumb in 1993, no copyright is claimed.
  98464. * This code is in the public domain; do with it what you wish.
  98465. *
  98466. * Equivalent code is available from RSA Data Security, Inc.
  98467. * This code has been tested against that, and is equivalent,
  98468. * except that you don't need to include two pages of legalese
  98469. * with every copy.
  98470. *
  98471. * To compute the message digest of a chunk of bytes, declare an
  98472. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98473. * needed on buffers full of bytes, and then call MD5Final, which
  98474. * will fill a supplied 16-byte array with the digest.
  98475. *
  98476. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  98477. * header definitions; now uses stuff from dpkg's config.h
  98478. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98479. * Still in the public domain.
  98480. *
  98481. * Josh Coalson: made some changes to integrate with libFLAC.
  98482. * Still in the public domain, with no warranty.
  98483. */
  98484. typedef struct {
  98485. FLAC__uint32 in[16];
  98486. FLAC__uint32 buf[4];
  98487. FLAC__uint32 bytes[2];
  98488. FLAC__byte *internal_buf;
  98489. size_t capacity;
  98490. } FLAC__MD5Context;
  98491. void FLAC__MD5Init(FLAC__MD5Context *context);
  98492. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  98493. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  98494. #endif
  98495. /*** End of inlined file: md5.h ***/
  98496. #ifndef FLaC__INLINE
  98497. #define FLaC__INLINE
  98498. #endif
  98499. /*
  98500. * This code implements the MD5 message-digest algorithm.
  98501. * The algorithm is due to Ron Rivest. This code was
  98502. * written by Colin Plumb in 1993, no copyright is claimed.
  98503. * This code is in the public domain; do with it what you wish.
  98504. *
  98505. * Equivalent code is available from RSA Data Security, Inc.
  98506. * This code has been tested against that, and is equivalent,
  98507. * except that you don't need to include two pages of legalese
  98508. * with every copy.
  98509. *
  98510. * To compute the message digest of a chunk of bytes, declare an
  98511. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98512. * needed on buffers full of bytes, and then call MD5Final, which
  98513. * will fill a supplied 16-byte array with the digest.
  98514. *
  98515. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  98516. * definitions; now uses stuff from dpkg's config.h.
  98517. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98518. * Still in the public domain.
  98519. *
  98520. * Josh Coalson: made some changes to integrate with libFLAC.
  98521. * Still in the public domain.
  98522. */
  98523. /* The four core functions - F1 is optimized somewhat */
  98524. /* #define F1(x, y, z) (x & y | ~x & z) */
  98525. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  98526. #define F2(x, y, z) F1(z, x, y)
  98527. #define F3(x, y, z) (x ^ y ^ z)
  98528. #define F4(x, y, z) (y ^ (x | ~z))
  98529. /* This is the central step in the MD5 algorithm. */
  98530. #define MD5STEP(f,w,x,y,z,in,s) \
  98531. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  98532. /*
  98533. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  98534. * reflect the addition of 16 longwords of new data. MD5Update blocks
  98535. * the data and converts bytes into longwords for this routine.
  98536. */
  98537. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  98538. {
  98539. register FLAC__uint32 a, b, c, d;
  98540. a = buf[0];
  98541. b = buf[1];
  98542. c = buf[2];
  98543. d = buf[3];
  98544. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  98545. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  98546. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  98547. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  98548. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  98549. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  98550. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  98551. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  98552. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  98553. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  98554. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  98555. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  98556. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  98557. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  98558. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  98559. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  98560. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  98561. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  98562. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  98563. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  98564. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  98565. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  98566. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  98567. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  98568. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  98569. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  98570. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  98571. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  98572. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  98573. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  98574. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  98575. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  98576. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  98577. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  98578. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  98579. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  98580. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  98581. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  98582. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  98583. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  98584. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  98585. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  98586. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  98587. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  98588. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  98589. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  98590. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  98591. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  98592. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  98593. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  98594. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  98595. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  98596. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  98597. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  98598. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  98599. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  98600. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  98601. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  98602. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  98603. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  98604. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  98605. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  98606. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  98607. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  98608. buf[0] += a;
  98609. buf[1] += b;
  98610. buf[2] += c;
  98611. buf[3] += d;
  98612. }
  98613. #if WORDS_BIGENDIAN
  98614. //@@@@@@ OPT: use bswap/intrinsics
  98615. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  98616. {
  98617. register FLAC__uint32 x;
  98618. do {
  98619. x = *buf;
  98620. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  98621. *buf++ = (x >> 16) | (x << 16);
  98622. } while (--words);
  98623. }
  98624. static void byteSwapX16(FLAC__uint32 *buf)
  98625. {
  98626. register FLAC__uint32 x;
  98627. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98628. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98629. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98630. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98631. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98632. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98633. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98634. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98635. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98636. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98637. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98638. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98639. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98640. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98641. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98642. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  98643. }
  98644. #else
  98645. #define byteSwap(buf, words)
  98646. #define byteSwapX16(buf)
  98647. #endif
  98648. /*
  98649. * Update context to reflect the concatenation of another buffer full
  98650. * of bytes.
  98651. */
  98652. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  98653. {
  98654. FLAC__uint32 t;
  98655. /* Update byte count */
  98656. t = ctx->bytes[0];
  98657. if ((ctx->bytes[0] = t + len) < t)
  98658. ctx->bytes[1]++; /* Carry from low to high */
  98659. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  98660. if (t > len) {
  98661. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  98662. return;
  98663. }
  98664. /* First chunk is an odd size */
  98665. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  98666. byteSwapX16(ctx->in);
  98667. FLAC__MD5Transform(ctx->buf, ctx->in);
  98668. buf += t;
  98669. len -= t;
  98670. /* Process data in 64-byte chunks */
  98671. while (len >= 64) {
  98672. memcpy(ctx->in, buf, 64);
  98673. byteSwapX16(ctx->in);
  98674. FLAC__MD5Transform(ctx->buf, ctx->in);
  98675. buf += 64;
  98676. len -= 64;
  98677. }
  98678. /* Handle any remaining bytes of data. */
  98679. memcpy(ctx->in, buf, len);
  98680. }
  98681. /*
  98682. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  98683. * initialization constants.
  98684. */
  98685. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  98686. {
  98687. ctx->buf[0] = 0x67452301;
  98688. ctx->buf[1] = 0xefcdab89;
  98689. ctx->buf[2] = 0x98badcfe;
  98690. ctx->buf[3] = 0x10325476;
  98691. ctx->bytes[0] = 0;
  98692. ctx->bytes[1] = 0;
  98693. ctx->internal_buf = 0;
  98694. ctx->capacity = 0;
  98695. }
  98696. /*
  98697. * Final wrapup - pad to 64-byte boundary with the bit pattern
  98698. * 1 0* (64-bit count of bits processed, MSB-first)
  98699. */
  98700. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  98701. {
  98702. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  98703. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  98704. /* Set the first char of padding to 0x80. There is always room. */
  98705. *p++ = 0x80;
  98706. /* Bytes of padding needed to make 56 bytes (-8..55) */
  98707. count = 56 - 1 - count;
  98708. if (count < 0) { /* Padding forces an extra block */
  98709. memset(p, 0, count + 8);
  98710. byteSwapX16(ctx->in);
  98711. FLAC__MD5Transform(ctx->buf, ctx->in);
  98712. p = (FLAC__byte *)ctx->in;
  98713. count = 56;
  98714. }
  98715. memset(p, 0, count);
  98716. byteSwap(ctx->in, 14);
  98717. /* Append length in bits and transform */
  98718. ctx->in[14] = ctx->bytes[0] << 3;
  98719. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  98720. FLAC__MD5Transform(ctx->buf, ctx->in);
  98721. byteSwap(ctx->buf, 4);
  98722. memcpy(digest, ctx->buf, 16);
  98723. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  98724. if(0 != ctx->internal_buf) {
  98725. free(ctx->internal_buf);
  98726. ctx->internal_buf = 0;
  98727. ctx->capacity = 0;
  98728. }
  98729. }
  98730. /*
  98731. * Convert the incoming audio signal to a byte stream
  98732. */
  98733. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98734. {
  98735. unsigned channel, sample;
  98736. register FLAC__int32 a_word;
  98737. register FLAC__byte *buf_ = buf;
  98738. #if WORDS_BIGENDIAN
  98739. #else
  98740. if(channels == 2 && bytes_per_sample == 2) {
  98741. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  98742. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  98743. for(sample = 0; sample < samples; sample++, buf1_+=2)
  98744. *buf1_ = (FLAC__int16)signal[1][sample];
  98745. }
  98746. else if(channels == 1 && bytes_per_sample == 2) {
  98747. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  98748. for(sample = 0; sample < samples; sample++)
  98749. *buf1_++ = (FLAC__int16)signal[0][sample];
  98750. }
  98751. else
  98752. #endif
  98753. if(bytes_per_sample == 2) {
  98754. if(channels == 2) {
  98755. for(sample = 0; sample < samples; sample++) {
  98756. a_word = signal[0][sample];
  98757. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98758. *buf_++ = (FLAC__byte)a_word;
  98759. a_word = signal[1][sample];
  98760. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98761. *buf_++ = (FLAC__byte)a_word;
  98762. }
  98763. }
  98764. else if(channels == 1) {
  98765. for(sample = 0; sample < samples; sample++) {
  98766. a_word = signal[0][sample];
  98767. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98768. *buf_++ = (FLAC__byte)a_word;
  98769. }
  98770. }
  98771. else {
  98772. for(sample = 0; sample < samples; sample++) {
  98773. for(channel = 0; channel < channels; channel++) {
  98774. a_word = signal[channel][sample];
  98775. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98776. *buf_++ = (FLAC__byte)a_word;
  98777. }
  98778. }
  98779. }
  98780. }
  98781. else if(bytes_per_sample == 3) {
  98782. if(channels == 2) {
  98783. for(sample = 0; sample < samples; sample++) {
  98784. a_word = signal[0][sample];
  98785. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98786. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98787. *buf_++ = (FLAC__byte)a_word;
  98788. a_word = signal[1][sample];
  98789. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98790. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98791. *buf_++ = (FLAC__byte)a_word;
  98792. }
  98793. }
  98794. else if(channels == 1) {
  98795. for(sample = 0; sample < samples; sample++) {
  98796. a_word = signal[0][sample];
  98797. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  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; a_word >>= 8;
  98808. *buf_++ = (FLAC__byte)a_word;
  98809. }
  98810. }
  98811. }
  98812. }
  98813. else if(bytes_per_sample == 1) {
  98814. if(channels == 2) {
  98815. for(sample = 0; sample < samples; sample++) {
  98816. a_word = signal[0][sample];
  98817. *buf_++ = (FLAC__byte)a_word;
  98818. a_word = signal[1][sample];
  98819. *buf_++ = (FLAC__byte)a_word;
  98820. }
  98821. }
  98822. else if(channels == 1) {
  98823. for(sample = 0; sample < samples; sample++) {
  98824. a_word = signal[0][sample];
  98825. *buf_++ = (FLAC__byte)a_word;
  98826. }
  98827. }
  98828. else {
  98829. for(sample = 0; sample < samples; sample++) {
  98830. for(channel = 0; channel < channels; channel++) {
  98831. a_word = signal[channel][sample];
  98832. *buf_++ = (FLAC__byte)a_word;
  98833. }
  98834. }
  98835. }
  98836. }
  98837. else { /* bytes_per_sample == 4, maybe optimize more later */
  98838. for(sample = 0; sample < samples; sample++) {
  98839. for(channel = 0; channel < channels; channel++) {
  98840. a_word = signal[channel][sample];
  98841. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98842. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98843. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98844. *buf_++ = (FLAC__byte)a_word;
  98845. }
  98846. }
  98847. }
  98848. }
  98849. /*
  98850. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  98851. */
  98852. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98853. {
  98854. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  98855. /* overflow check */
  98856. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  98857. return false;
  98858. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  98859. return false;
  98860. if(ctx->capacity < bytes_needed) {
  98861. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  98862. if(0 == tmp) {
  98863. free(ctx->internal_buf);
  98864. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  98865. return false;
  98866. }
  98867. ctx->internal_buf = tmp;
  98868. ctx->capacity = bytes_needed;
  98869. }
  98870. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  98871. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  98872. return true;
  98873. }
  98874. #endif
  98875. /*** End of inlined file: md5.c ***/
  98876. /*** Start of inlined file: memory.c ***/
  98877. /*** Start of inlined file: juce_FlacHeader.h ***/
  98878. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98879. // tasks..
  98880. #define VERSION "1.2.1"
  98881. #define FLAC__NO_DLL 1
  98882. #if JUCE_MSVC
  98883. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98884. #endif
  98885. #if JUCE_MAC
  98886. #define FLAC__SYS_DARWIN 1
  98887. #endif
  98888. /*** End of inlined file: juce_FlacHeader.h ***/
  98889. #if JUCE_USE_FLAC
  98890. #if HAVE_CONFIG_H
  98891. # include <config.h>
  98892. #endif
  98893. /*** Start of inlined file: memory.h ***/
  98894. #ifndef FLAC__PRIVATE__MEMORY_H
  98895. #define FLAC__PRIVATE__MEMORY_H
  98896. #ifdef HAVE_CONFIG_H
  98897. #include <config.h>
  98898. #endif
  98899. #include <stdlib.h> /* for size_t */
  98900. /* Returns the unaligned address returned by malloc.
  98901. * Use free() on this address to deallocate.
  98902. */
  98903. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  98904. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  98905. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  98906. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  98907. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  98908. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98909. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  98910. #endif
  98911. #endif
  98912. /*** End of inlined file: memory.h ***/
  98913. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  98914. {
  98915. void *x;
  98916. FLAC__ASSERT(0 != aligned_address);
  98917. #ifdef FLAC__ALIGN_MALLOC_DATA
  98918. /* align on 32-byte (256-bit) boundary */
  98919. x = safe_malloc_add_2op_(bytes, /*+*/31);
  98920. #ifdef SIZEOF_VOIDP
  98921. #if SIZEOF_VOIDP == 4
  98922. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  98923. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  98924. #elif SIZEOF_VOIDP == 8
  98925. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  98926. #else
  98927. # error Unsupported sizeof(void*)
  98928. #endif
  98929. #else
  98930. /* there's got to be a better way to do this right for all archs */
  98931. if(sizeof(void*) == sizeof(unsigned))
  98932. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  98933. else if(sizeof(void*) == sizeof(FLAC__uint64))
  98934. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  98935. else
  98936. return 0;
  98937. #endif
  98938. #else
  98939. x = safe_malloc_(bytes);
  98940. *aligned_address = x;
  98941. #endif
  98942. return x;
  98943. }
  98944. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  98945. {
  98946. FLAC__int32 *pu; /* unaligned pointer */
  98947. union { /* union needed to comply with C99 pointer aliasing rules */
  98948. FLAC__int32 *pa; /* aligned pointer */
  98949. void *pv; /* aligned pointer alias */
  98950. } u;
  98951. FLAC__ASSERT(elements > 0);
  98952. FLAC__ASSERT(0 != unaligned_pointer);
  98953. FLAC__ASSERT(0 != aligned_pointer);
  98954. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98955. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  98956. if(0 == pu) {
  98957. return false;
  98958. }
  98959. else {
  98960. if(*unaligned_pointer != 0)
  98961. free(*unaligned_pointer);
  98962. *unaligned_pointer = pu;
  98963. *aligned_pointer = u.pa;
  98964. return true;
  98965. }
  98966. }
  98967. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  98968. {
  98969. FLAC__uint32 *pu; /* unaligned pointer */
  98970. union { /* union needed to comply with C99 pointer aliasing rules */
  98971. FLAC__uint32 *pa; /* aligned pointer */
  98972. void *pv; /* aligned pointer alias */
  98973. } u;
  98974. FLAC__ASSERT(elements > 0);
  98975. FLAC__ASSERT(0 != unaligned_pointer);
  98976. FLAC__ASSERT(0 != aligned_pointer);
  98977. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  98978. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  98979. if(0 == pu) {
  98980. return false;
  98981. }
  98982. else {
  98983. if(*unaligned_pointer != 0)
  98984. free(*unaligned_pointer);
  98985. *unaligned_pointer = pu;
  98986. *aligned_pointer = u.pa;
  98987. return true;
  98988. }
  98989. }
  98990. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  98991. {
  98992. FLAC__uint64 *pu; /* unaligned pointer */
  98993. union { /* union needed to comply with C99 pointer aliasing rules */
  98994. FLAC__uint64 *pa; /* aligned pointer */
  98995. void *pv; /* aligned pointer alias */
  98996. } u;
  98997. FLAC__ASSERT(elements > 0);
  98998. FLAC__ASSERT(0 != unaligned_pointer);
  98999. FLAC__ASSERT(0 != aligned_pointer);
  99000. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99001. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99002. if(0 == pu) {
  99003. return false;
  99004. }
  99005. else {
  99006. if(*unaligned_pointer != 0)
  99007. free(*unaligned_pointer);
  99008. *unaligned_pointer = pu;
  99009. *aligned_pointer = u.pa;
  99010. return true;
  99011. }
  99012. }
  99013. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  99014. {
  99015. unsigned *pu; /* unaligned pointer */
  99016. union { /* union needed to comply with C99 pointer aliasing rules */
  99017. unsigned *pa; /* aligned pointer */
  99018. void *pv; /* aligned pointer alias */
  99019. } u;
  99020. FLAC__ASSERT(elements > 0);
  99021. FLAC__ASSERT(0 != unaligned_pointer);
  99022. FLAC__ASSERT(0 != aligned_pointer);
  99023. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99024. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99025. if(0 == pu) {
  99026. return false;
  99027. }
  99028. else {
  99029. if(*unaligned_pointer != 0)
  99030. free(*unaligned_pointer);
  99031. *unaligned_pointer = pu;
  99032. *aligned_pointer = u.pa;
  99033. return true;
  99034. }
  99035. }
  99036. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99037. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  99038. {
  99039. FLAC__real *pu; /* unaligned pointer */
  99040. union { /* union needed to comply with C99 pointer aliasing rules */
  99041. FLAC__real *pa; /* aligned pointer */
  99042. void *pv; /* aligned pointer alias */
  99043. } u;
  99044. FLAC__ASSERT(elements > 0);
  99045. FLAC__ASSERT(0 != unaligned_pointer);
  99046. FLAC__ASSERT(0 != aligned_pointer);
  99047. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99048. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99049. if(0 == pu) {
  99050. return false;
  99051. }
  99052. else {
  99053. if(*unaligned_pointer != 0)
  99054. free(*unaligned_pointer);
  99055. *unaligned_pointer = pu;
  99056. *aligned_pointer = u.pa;
  99057. return true;
  99058. }
  99059. }
  99060. #endif
  99061. #endif
  99062. /*** End of inlined file: memory.c ***/
  99063. /*** Start of inlined file: stream_decoder.c ***/
  99064. /*** Start of inlined file: juce_FlacHeader.h ***/
  99065. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  99066. // tasks..
  99067. #define VERSION "1.2.1"
  99068. #define FLAC__NO_DLL 1
  99069. #if JUCE_MSVC
  99070. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  99071. #endif
  99072. #if JUCE_MAC
  99073. #define FLAC__SYS_DARWIN 1
  99074. #endif
  99075. /*** End of inlined file: juce_FlacHeader.h ***/
  99076. #if JUCE_USE_FLAC
  99077. #if HAVE_CONFIG_H
  99078. # include <config.h>
  99079. #endif
  99080. #if defined _MSC_VER || defined __MINGW32__
  99081. #include <io.h> /* for _setmode() */
  99082. #include <fcntl.h> /* for _O_BINARY */
  99083. #endif
  99084. #if defined __CYGWIN__ || defined __EMX__
  99085. #include <io.h> /* for setmode(), O_BINARY */
  99086. #include <fcntl.h> /* for _O_BINARY */
  99087. #endif
  99088. #include <stdio.h>
  99089. #include <stdlib.h> /* for malloc() */
  99090. #include <string.h> /* for memset/memcpy() */
  99091. #include <sys/stat.h> /* for stat() */
  99092. #include <sys/types.h> /* for off_t */
  99093. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  99094. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  99095. #define fseeko fseek
  99096. #define ftello ftell
  99097. #endif
  99098. #endif
  99099. /*** Start of inlined file: stream_decoder.h ***/
  99100. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  99101. #define FLAC__PROTECTED__STREAM_DECODER_H
  99102. #if FLAC__HAS_OGG
  99103. #include "include/private/ogg_decoder_aspect.h"
  99104. #endif
  99105. typedef struct FLAC__StreamDecoderProtected {
  99106. FLAC__StreamDecoderState state;
  99107. unsigned channels;
  99108. FLAC__ChannelAssignment channel_assignment;
  99109. unsigned bits_per_sample;
  99110. unsigned sample_rate; /* in Hz */
  99111. unsigned blocksize; /* in samples (per channel) */
  99112. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  99113. #if FLAC__HAS_OGG
  99114. FLAC__OggDecoderAspect ogg_decoder_aspect;
  99115. #endif
  99116. } FLAC__StreamDecoderProtected;
  99117. /*
  99118. * return the number of input bytes consumed
  99119. */
  99120. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  99121. #endif
  99122. /*** End of inlined file: stream_decoder.h ***/
  99123. #ifdef max
  99124. #undef max
  99125. #endif
  99126. #define max(a,b) ((a)>(b)?(a):(b))
  99127. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  99128. #ifdef _MSC_VER
  99129. #define FLAC__U64L(x) x
  99130. #else
  99131. #define FLAC__U64L(x) x##LLU
  99132. #endif
  99133. /* technically this should be in an "export.c" but this is convenient enough */
  99134. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  99135. #if FLAC__HAS_OGG
  99136. 1
  99137. #else
  99138. 0
  99139. #endif
  99140. ;
  99141. /***********************************************************************
  99142. *
  99143. * Private static data
  99144. *
  99145. ***********************************************************************/
  99146. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  99147. /***********************************************************************
  99148. *
  99149. * Private class method prototypes
  99150. *
  99151. ***********************************************************************/
  99152. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  99153. static FILE *get_binary_stdin_(void);
  99154. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  99155. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  99156. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  99157. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  99158. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  99159. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  99160. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  99161. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  99162. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  99163. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  99164. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  99165. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  99166. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  99167. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99168. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99169. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  99170. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  99171. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99172. 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);
  99173. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  99174. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  99175. #if FLAC__HAS_OGG
  99176. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  99177. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  99178. #endif
  99179. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  99180. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  99181. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  99182. #if FLAC__HAS_OGG
  99183. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  99184. #endif
  99185. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  99186. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  99187. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  99188. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  99189. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  99190. /***********************************************************************
  99191. *
  99192. * Private class data
  99193. *
  99194. ***********************************************************************/
  99195. typedef struct FLAC__StreamDecoderPrivate {
  99196. #if FLAC__HAS_OGG
  99197. FLAC__bool is_ogg;
  99198. #endif
  99199. FLAC__StreamDecoderReadCallback read_callback;
  99200. FLAC__StreamDecoderSeekCallback seek_callback;
  99201. FLAC__StreamDecoderTellCallback tell_callback;
  99202. FLAC__StreamDecoderLengthCallback length_callback;
  99203. FLAC__StreamDecoderEofCallback eof_callback;
  99204. FLAC__StreamDecoderWriteCallback write_callback;
  99205. FLAC__StreamDecoderMetadataCallback metadata_callback;
  99206. FLAC__StreamDecoderErrorCallback error_callback;
  99207. /* generic 32-bit datapath: */
  99208. 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[]);
  99209. /* generic 64-bit datapath: */
  99210. 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[]);
  99211. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  99212. 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[]);
  99213. /* 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: */
  99214. 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[]);
  99215. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  99216. void *client_data;
  99217. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  99218. FLAC__BitReader *input;
  99219. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  99220. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  99221. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  99222. unsigned output_capacity, output_channels;
  99223. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  99224. FLAC__uint64 samples_decoded;
  99225. FLAC__bool has_stream_info, has_seek_table;
  99226. FLAC__StreamMetadata stream_info;
  99227. FLAC__StreamMetadata seek_table;
  99228. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  99229. FLAC__byte *metadata_filter_ids;
  99230. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  99231. FLAC__Frame frame;
  99232. FLAC__bool cached; /* true if there is a byte in lookahead */
  99233. FLAC__CPUInfo cpuinfo;
  99234. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  99235. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  99236. /* unaligned (original) pointers to allocated data */
  99237. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  99238. 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 */
  99239. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  99240. FLAC__bool is_seeking;
  99241. FLAC__MD5Context md5context;
  99242. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  99243. /* (the rest of these are only used for seeking) */
  99244. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  99245. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  99246. FLAC__uint64 target_sample;
  99247. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  99248. #if FLAC__HAS_OGG
  99249. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  99250. #endif
  99251. } FLAC__StreamDecoderPrivate;
  99252. /***********************************************************************
  99253. *
  99254. * Public static class data
  99255. *
  99256. ***********************************************************************/
  99257. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  99258. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  99259. "FLAC__STREAM_DECODER_READ_METADATA",
  99260. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  99261. "FLAC__STREAM_DECODER_READ_FRAME",
  99262. "FLAC__STREAM_DECODER_END_OF_STREAM",
  99263. "FLAC__STREAM_DECODER_OGG_ERROR",
  99264. "FLAC__STREAM_DECODER_SEEK_ERROR",
  99265. "FLAC__STREAM_DECODER_ABORTED",
  99266. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  99267. "FLAC__STREAM_DECODER_UNINITIALIZED"
  99268. };
  99269. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  99270. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  99271. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  99272. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  99273. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  99274. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  99275. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  99276. };
  99277. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  99278. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  99279. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  99280. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  99281. };
  99282. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  99283. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  99284. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  99285. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  99286. };
  99287. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  99288. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  99289. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  99290. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  99291. };
  99292. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  99293. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  99294. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  99295. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  99296. };
  99297. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  99298. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  99299. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  99300. };
  99301. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  99302. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  99303. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  99304. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  99305. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  99306. };
  99307. /***********************************************************************
  99308. *
  99309. * Class constructor/destructor
  99310. *
  99311. ***********************************************************************/
  99312. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  99313. {
  99314. FLAC__StreamDecoder *decoder;
  99315. unsigned i;
  99316. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  99317. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  99318. if(decoder == 0) {
  99319. return 0;
  99320. }
  99321. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  99322. if(decoder->protected_ == 0) {
  99323. free(decoder);
  99324. return 0;
  99325. }
  99326. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  99327. if(decoder->private_ == 0) {
  99328. free(decoder->protected_);
  99329. free(decoder);
  99330. return 0;
  99331. }
  99332. decoder->private_->input = FLAC__bitreader_new();
  99333. if(decoder->private_->input == 0) {
  99334. free(decoder->private_);
  99335. free(decoder->protected_);
  99336. free(decoder);
  99337. return 0;
  99338. }
  99339. decoder->private_->metadata_filter_ids_capacity = 16;
  99340. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  99341. FLAC__bitreader_delete(decoder->private_->input);
  99342. free(decoder->private_);
  99343. free(decoder->protected_);
  99344. free(decoder);
  99345. return 0;
  99346. }
  99347. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99348. decoder->private_->output[i] = 0;
  99349. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99350. }
  99351. decoder->private_->output_capacity = 0;
  99352. decoder->private_->output_channels = 0;
  99353. decoder->private_->has_seek_table = false;
  99354. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99355. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  99356. decoder->private_->file = 0;
  99357. set_defaults_dec(decoder);
  99358. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99359. return decoder;
  99360. }
  99361. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  99362. {
  99363. unsigned i;
  99364. FLAC__ASSERT(0 != decoder);
  99365. FLAC__ASSERT(0 != decoder->protected_);
  99366. FLAC__ASSERT(0 != decoder->private_);
  99367. FLAC__ASSERT(0 != decoder->private_->input);
  99368. (void)FLAC__stream_decoder_finish(decoder);
  99369. if(0 != decoder->private_->metadata_filter_ids)
  99370. free(decoder->private_->metadata_filter_ids);
  99371. FLAC__bitreader_delete(decoder->private_->input);
  99372. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99373. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  99374. free(decoder->private_);
  99375. free(decoder->protected_);
  99376. free(decoder);
  99377. }
  99378. /***********************************************************************
  99379. *
  99380. * Public class methods
  99381. *
  99382. ***********************************************************************/
  99383. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  99384. FLAC__StreamDecoder *decoder,
  99385. FLAC__StreamDecoderReadCallback read_callback,
  99386. FLAC__StreamDecoderSeekCallback seek_callback,
  99387. FLAC__StreamDecoderTellCallback tell_callback,
  99388. FLAC__StreamDecoderLengthCallback length_callback,
  99389. FLAC__StreamDecoderEofCallback eof_callback,
  99390. FLAC__StreamDecoderWriteCallback write_callback,
  99391. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99392. FLAC__StreamDecoderErrorCallback error_callback,
  99393. void *client_data,
  99394. FLAC__bool is_ogg
  99395. )
  99396. {
  99397. FLAC__ASSERT(0 != decoder);
  99398. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99399. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  99400. #if !FLAC__HAS_OGG
  99401. if(is_ogg)
  99402. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  99403. #endif
  99404. if(
  99405. 0 == read_callback ||
  99406. 0 == write_callback ||
  99407. 0 == error_callback ||
  99408. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  99409. )
  99410. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  99411. #if FLAC__HAS_OGG
  99412. decoder->private_->is_ogg = is_ogg;
  99413. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  99414. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  99415. #endif
  99416. /*
  99417. * get the CPU info and set the function pointers
  99418. */
  99419. FLAC__cpu_info(&decoder->private_->cpuinfo);
  99420. /* first default to the non-asm routines */
  99421. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  99422. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  99423. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  99424. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  99425. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  99426. /* now override with asm where appropriate */
  99427. #ifndef FLAC__NO_ASM
  99428. if(decoder->private_->cpuinfo.use_asm) {
  99429. #ifdef FLAC__CPU_IA32
  99430. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  99431. #ifdef FLAC__HAS_NASM
  99432. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  99433. if(decoder->private_->cpuinfo.data.ia32.bswap)
  99434. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  99435. #endif
  99436. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  99437. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99438. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99439. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99440. }
  99441. else {
  99442. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99443. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  99444. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  99445. }
  99446. #endif
  99447. #elif defined FLAC__CPU_PPC
  99448. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  99449. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  99450. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  99451. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  99452. }
  99453. #endif
  99454. }
  99455. #endif
  99456. /* from here on, errors are fatal */
  99457. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  99458. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99459. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99460. }
  99461. decoder->private_->read_callback = read_callback;
  99462. decoder->private_->seek_callback = seek_callback;
  99463. decoder->private_->tell_callback = tell_callback;
  99464. decoder->private_->length_callback = length_callback;
  99465. decoder->private_->eof_callback = eof_callback;
  99466. decoder->private_->write_callback = write_callback;
  99467. decoder->private_->metadata_callback = metadata_callback;
  99468. decoder->private_->error_callback = error_callback;
  99469. decoder->private_->client_data = client_data;
  99470. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99471. decoder->private_->samples_decoded = 0;
  99472. decoder->private_->has_stream_info = false;
  99473. decoder->private_->cached = false;
  99474. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99475. decoder->private_->is_seeking = false;
  99476. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  99477. if(!FLAC__stream_decoder_reset(decoder)) {
  99478. /* above call sets the state for us */
  99479. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99480. }
  99481. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  99482. }
  99483. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  99484. FLAC__StreamDecoder *decoder,
  99485. FLAC__StreamDecoderReadCallback read_callback,
  99486. FLAC__StreamDecoderSeekCallback seek_callback,
  99487. FLAC__StreamDecoderTellCallback tell_callback,
  99488. FLAC__StreamDecoderLengthCallback length_callback,
  99489. FLAC__StreamDecoderEofCallback eof_callback,
  99490. FLAC__StreamDecoderWriteCallback write_callback,
  99491. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99492. FLAC__StreamDecoderErrorCallback error_callback,
  99493. void *client_data
  99494. )
  99495. {
  99496. return init_stream_internal_dec(
  99497. decoder,
  99498. read_callback,
  99499. seek_callback,
  99500. tell_callback,
  99501. length_callback,
  99502. eof_callback,
  99503. write_callback,
  99504. metadata_callback,
  99505. error_callback,
  99506. client_data,
  99507. /*is_ogg=*/false
  99508. );
  99509. }
  99510. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  99511. FLAC__StreamDecoder *decoder,
  99512. FLAC__StreamDecoderReadCallback read_callback,
  99513. FLAC__StreamDecoderSeekCallback seek_callback,
  99514. FLAC__StreamDecoderTellCallback tell_callback,
  99515. FLAC__StreamDecoderLengthCallback length_callback,
  99516. FLAC__StreamDecoderEofCallback eof_callback,
  99517. FLAC__StreamDecoderWriteCallback write_callback,
  99518. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99519. FLAC__StreamDecoderErrorCallback error_callback,
  99520. void *client_data
  99521. )
  99522. {
  99523. return init_stream_internal_dec(
  99524. decoder,
  99525. read_callback,
  99526. seek_callback,
  99527. tell_callback,
  99528. length_callback,
  99529. eof_callback,
  99530. write_callback,
  99531. metadata_callback,
  99532. error_callback,
  99533. client_data,
  99534. /*is_ogg=*/true
  99535. );
  99536. }
  99537. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  99538. FLAC__StreamDecoder *decoder,
  99539. FILE *file,
  99540. FLAC__StreamDecoderWriteCallback write_callback,
  99541. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99542. FLAC__StreamDecoderErrorCallback error_callback,
  99543. void *client_data,
  99544. FLAC__bool is_ogg
  99545. )
  99546. {
  99547. FLAC__ASSERT(0 != decoder);
  99548. FLAC__ASSERT(0 != file);
  99549. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99550. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99551. if(0 == write_callback || 0 == error_callback)
  99552. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99553. /*
  99554. * To make sure that our file does not go unclosed after an error, we
  99555. * must assign the FILE pointer before any further error can occur in
  99556. * this routine.
  99557. */
  99558. if(file == stdin)
  99559. file = get_binary_stdin_(); /* just to be safe */
  99560. decoder->private_->file = file;
  99561. return init_stream_internal_dec(
  99562. decoder,
  99563. file_read_callback_dec,
  99564. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  99565. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  99566. decoder->private_->file == stdin? 0: file_length_callback_,
  99567. file_eof_callback_,
  99568. write_callback,
  99569. metadata_callback,
  99570. error_callback,
  99571. client_data,
  99572. is_ogg
  99573. );
  99574. }
  99575. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  99576. FLAC__StreamDecoder *decoder,
  99577. FILE *file,
  99578. FLAC__StreamDecoderWriteCallback write_callback,
  99579. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99580. FLAC__StreamDecoderErrorCallback error_callback,
  99581. void *client_data
  99582. )
  99583. {
  99584. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99585. }
  99586. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  99587. FLAC__StreamDecoder *decoder,
  99588. FILE *file,
  99589. FLAC__StreamDecoderWriteCallback write_callback,
  99590. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99591. FLAC__StreamDecoderErrorCallback error_callback,
  99592. void *client_data
  99593. )
  99594. {
  99595. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99596. }
  99597. static FLAC__StreamDecoderInitStatus init_file_internal_(
  99598. FLAC__StreamDecoder *decoder,
  99599. const char *filename,
  99600. FLAC__StreamDecoderWriteCallback write_callback,
  99601. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99602. FLAC__StreamDecoderErrorCallback error_callback,
  99603. void *client_data,
  99604. FLAC__bool is_ogg
  99605. )
  99606. {
  99607. FILE *file;
  99608. FLAC__ASSERT(0 != decoder);
  99609. /*
  99610. * To make sure that our file does not go unclosed after an error, we
  99611. * have to do the same entrance checks here that are later performed
  99612. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  99613. */
  99614. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99615. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99616. if(0 == write_callback || 0 == error_callback)
  99617. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99618. file = filename? fopen(filename, "rb") : stdin;
  99619. if(0 == file)
  99620. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  99621. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  99622. }
  99623. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  99624. FLAC__StreamDecoder *decoder,
  99625. const char *filename,
  99626. FLAC__StreamDecoderWriteCallback write_callback,
  99627. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99628. FLAC__StreamDecoderErrorCallback error_callback,
  99629. void *client_data
  99630. )
  99631. {
  99632. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99633. }
  99634. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  99635. FLAC__StreamDecoder *decoder,
  99636. const char *filename,
  99637. FLAC__StreamDecoderWriteCallback write_callback,
  99638. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99639. FLAC__StreamDecoderErrorCallback error_callback,
  99640. void *client_data
  99641. )
  99642. {
  99643. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99644. }
  99645. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  99646. {
  99647. FLAC__bool md5_failed = false;
  99648. unsigned i;
  99649. FLAC__ASSERT(0 != decoder);
  99650. FLAC__ASSERT(0 != decoder->private_);
  99651. FLAC__ASSERT(0 != decoder->protected_);
  99652. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  99653. return true;
  99654. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  99655. * always call FLAC__MD5Final()
  99656. */
  99657. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  99658. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99659. free(decoder->private_->seek_table.data.seek_table.points);
  99660. decoder->private_->seek_table.data.seek_table.points = 0;
  99661. decoder->private_->has_seek_table = false;
  99662. }
  99663. FLAC__bitreader_free(decoder->private_->input);
  99664. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99665. /* WATCHOUT:
  99666. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  99667. * output arrays have a buffer of up to 3 zeroes in front
  99668. * (at negative indices) for alignment purposes; we use 4
  99669. * to keep the data well-aligned.
  99670. */
  99671. if(0 != decoder->private_->output[i]) {
  99672. free(decoder->private_->output[i]-4);
  99673. decoder->private_->output[i] = 0;
  99674. }
  99675. if(0 != decoder->private_->residual_unaligned[i]) {
  99676. free(decoder->private_->residual_unaligned[i]);
  99677. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99678. }
  99679. }
  99680. decoder->private_->output_capacity = 0;
  99681. decoder->private_->output_channels = 0;
  99682. #if FLAC__HAS_OGG
  99683. if(decoder->private_->is_ogg)
  99684. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  99685. #endif
  99686. if(0 != decoder->private_->file) {
  99687. if(decoder->private_->file != stdin)
  99688. fclose(decoder->private_->file);
  99689. decoder->private_->file = 0;
  99690. }
  99691. if(decoder->private_->do_md5_checking) {
  99692. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  99693. md5_failed = true;
  99694. }
  99695. decoder->private_->is_seeking = false;
  99696. set_defaults_dec(decoder);
  99697. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99698. return !md5_failed;
  99699. }
  99700. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  99701. {
  99702. FLAC__ASSERT(0 != decoder);
  99703. FLAC__ASSERT(0 != decoder->private_);
  99704. FLAC__ASSERT(0 != decoder->protected_);
  99705. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99706. return false;
  99707. #if FLAC__HAS_OGG
  99708. /* can't check decoder->private_->is_ogg since that's not set until init time */
  99709. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  99710. return true;
  99711. #else
  99712. (void)value;
  99713. return false;
  99714. #endif
  99715. }
  99716. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  99717. {
  99718. FLAC__ASSERT(0 != decoder);
  99719. FLAC__ASSERT(0 != decoder->protected_);
  99720. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99721. return false;
  99722. decoder->protected_->md5_checking = value;
  99723. return true;
  99724. }
  99725. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99726. {
  99727. FLAC__ASSERT(0 != decoder);
  99728. FLAC__ASSERT(0 != decoder->private_);
  99729. FLAC__ASSERT(0 != decoder->protected_);
  99730. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99731. /* double protection */
  99732. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99733. return false;
  99734. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99735. return false;
  99736. decoder->private_->metadata_filter[type] = true;
  99737. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99738. decoder->private_->metadata_filter_ids_count = 0;
  99739. return true;
  99740. }
  99741. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99742. {
  99743. FLAC__ASSERT(0 != decoder);
  99744. FLAC__ASSERT(0 != decoder->private_);
  99745. FLAC__ASSERT(0 != decoder->protected_);
  99746. FLAC__ASSERT(0 != id);
  99747. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99748. return false;
  99749. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99750. return true;
  99751. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99752. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99753. 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))) {
  99754. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99755. return false;
  99756. }
  99757. decoder->private_->metadata_filter_ids_capacity *= 2;
  99758. }
  99759. 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));
  99760. decoder->private_->metadata_filter_ids_count++;
  99761. return true;
  99762. }
  99763. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  99764. {
  99765. unsigned i;
  99766. FLAC__ASSERT(0 != decoder);
  99767. FLAC__ASSERT(0 != decoder->private_);
  99768. FLAC__ASSERT(0 != decoder->protected_);
  99769. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99770. return false;
  99771. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  99772. decoder->private_->metadata_filter[i] = true;
  99773. decoder->private_->metadata_filter_ids_count = 0;
  99774. return true;
  99775. }
  99776. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99777. {
  99778. FLAC__ASSERT(0 != decoder);
  99779. FLAC__ASSERT(0 != decoder->private_);
  99780. FLAC__ASSERT(0 != decoder->protected_);
  99781. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99782. /* double protection */
  99783. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99784. return false;
  99785. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99786. return false;
  99787. decoder->private_->metadata_filter[type] = false;
  99788. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99789. decoder->private_->metadata_filter_ids_count = 0;
  99790. return true;
  99791. }
  99792. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99793. {
  99794. FLAC__ASSERT(0 != decoder);
  99795. FLAC__ASSERT(0 != decoder->private_);
  99796. FLAC__ASSERT(0 != decoder->protected_);
  99797. FLAC__ASSERT(0 != id);
  99798. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99799. return false;
  99800. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99801. return true;
  99802. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99803. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99804. 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))) {
  99805. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99806. return false;
  99807. }
  99808. decoder->private_->metadata_filter_ids_capacity *= 2;
  99809. }
  99810. 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));
  99811. decoder->private_->metadata_filter_ids_count++;
  99812. return true;
  99813. }
  99814. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  99815. {
  99816. FLAC__ASSERT(0 != decoder);
  99817. FLAC__ASSERT(0 != decoder->private_);
  99818. FLAC__ASSERT(0 != decoder->protected_);
  99819. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99820. return false;
  99821. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  99822. decoder->private_->metadata_filter_ids_count = 0;
  99823. return true;
  99824. }
  99825. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  99826. {
  99827. FLAC__ASSERT(0 != decoder);
  99828. FLAC__ASSERT(0 != decoder->protected_);
  99829. return decoder->protected_->state;
  99830. }
  99831. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  99832. {
  99833. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  99834. }
  99835. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  99836. {
  99837. FLAC__ASSERT(0 != decoder);
  99838. FLAC__ASSERT(0 != decoder->protected_);
  99839. return decoder->protected_->md5_checking;
  99840. }
  99841. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  99842. {
  99843. FLAC__ASSERT(0 != decoder);
  99844. FLAC__ASSERT(0 != decoder->protected_);
  99845. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  99846. }
  99847. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  99848. {
  99849. FLAC__ASSERT(0 != decoder);
  99850. FLAC__ASSERT(0 != decoder->protected_);
  99851. return decoder->protected_->channels;
  99852. }
  99853. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  99854. {
  99855. FLAC__ASSERT(0 != decoder);
  99856. FLAC__ASSERT(0 != decoder->protected_);
  99857. return decoder->protected_->channel_assignment;
  99858. }
  99859. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  99860. {
  99861. FLAC__ASSERT(0 != decoder);
  99862. FLAC__ASSERT(0 != decoder->protected_);
  99863. return decoder->protected_->bits_per_sample;
  99864. }
  99865. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  99866. {
  99867. FLAC__ASSERT(0 != decoder);
  99868. FLAC__ASSERT(0 != decoder->protected_);
  99869. return decoder->protected_->sample_rate;
  99870. }
  99871. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  99872. {
  99873. FLAC__ASSERT(0 != decoder);
  99874. FLAC__ASSERT(0 != decoder->protected_);
  99875. return decoder->protected_->blocksize;
  99876. }
  99877. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  99878. {
  99879. FLAC__ASSERT(0 != decoder);
  99880. FLAC__ASSERT(0 != decoder->private_);
  99881. FLAC__ASSERT(0 != position);
  99882. #if FLAC__HAS_OGG
  99883. if(decoder->private_->is_ogg)
  99884. return false;
  99885. #endif
  99886. if(0 == decoder->private_->tell_callback)
  99887. return false;
  99888. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  99889. return false;
  99890. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  99891. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  99892. return false;
  99893. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  99894. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  99895. return true;
  99896. }
  99897. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  99898. {
  99899. FLAC__ASSERT(0 != decoder);
  99900. FLAC__ASSERT(0 != decoder->private_);
  99901. FLAC__ASSERT(0 != decoder->protected_);
  99902. decoder->private_->samples_decoded = 0;
  99903. decoder->private_->do_md5_checking = false;
  99904. #if FLAC__HAS_OGG
  99905. if(decoder->private_->is_ogg)
  99906. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  99907. #endif
  99908. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  99909. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99910. return false;
  99911. }
  99912. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  99913. return true;
  99914. }
  99915. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  99916. {
  99917. FLAC__ASSERT(0 != decoder);
  99918. FLAC__ASSERT(0 != decoder->private_);
  99919. FLAC__ASSERT(0 != decoder->protected_);
  99920. if(!FLAC__stream_decoder_flush(decoder)) {
  99921. /* above call sets the state for us */
  99922. return false;
  99923. }
  99924. #if FLAC__HAS_OGG
  99925. /*@@@ could go in !internal_reset_hack block below */
  99926. if(decoder->private_->is_ogg)
  99927. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  99928. #endif
  99929. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  99930. * (internal_reset_hack) don't try to rewind since we are already at
  99931. * the beginning of the stream and don't want to fail if the input is
  99932. * not seekable.
  99933. */
  99934. if(!decoder->private_->internal_reset_hack) {
  99935. if(decoder->private_->file == stdin)
  99936. return false; /* can't rewind stdin, reset fails */
  99937. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  99938. return false; /* seekable and seek fails, reset fails */
  99939. }
  99940. else
  99941. decoder->private_->internal_reset_hack = false;
  99942. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  99943. decoder->private_->has_stream_info = false;
  99944. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99945. free(decoder->private_->seek_table.data.seek_table.points);
  99946. decoder->private_->seek_table.data.seek_table.points = 0;
  99947. decoder->private_->has_seek_table = false;
  99948. }
  99949. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99950. /*
  99951. * This goes in reset() and not flush() because according to the spec, a
  99952. * fixed-blocksize stream must stay that way through the whole stream.
  99953. */
  99954. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99955. /* We initialize the FLAC__MD5Context even though we may never use it. This
  99956. * is because md5 checking may be turned on to start and then turned off if
  99957. * a seek occurs. So we init the context here and finalize it in
  99958. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  99959. * properly.
  99960. */
  99961. FLAC__MD5Init(&decoder->private_->md5context);
  99962. decoder->private_->first_frame_offset = 0;
  99963. decoder->private_->unparseable_frame_count = 0;
  99964. return true;
  99965. }
  99966. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  99967. {
  99968. FLAC__bool got_a_frame;
  99969. FLAC__ASSERT(0 != decoder);
  99970. FLAC__ASSERT(0 != decoder->protected_);
  99971. while(1) {
  99972. switch(decoder->protected_->state) {
  99973. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  99974. if(!find_metadata_(decoder))
  99975. return false; /* above function sets the status for us */
  99976. break;
  99977. case FLAC__STREAM_DECODER_READ_METADATA:
  99978. if(!read_metadata_(decoder))
  99979. return false; /* above function sets the status for us */
  99980. else
  99981. return true;
  99982. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  99983. if(!frame_sync_(decoder))
  99984. return true; /* above function sets the status for us */
  99985. break;
  99986. case FLAC__STREAM_DECODER_READ_FRAME:
  99987. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  99988. return false; /* above function sets the status for us */
  99989. if(got_a_frame)
  99990. return true; /* above function sets the status for us */
  99991. break;
  99992. case FLAC__STREAM_DECODER_END_OF_STREAM:
  99993. case FLAC__STREAM_DECODER_ABORTED:
  99994. return true;
  99995. default:
  99996. FLAC__ASSERT(0);
  99997. return false;
  99998. }
  99999. }
  100000. }
  100001. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  100002. {
  100003. FLAC__ASSERT(0 != decoder);
  100004. FLAC__ASSERT(0 != decoder->protected_);
  100005. while(1) {
  100006. switch(decoder->protected_->state) {
  100007. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100008. if(!find_metadata_(decoder))
  100009. return false; /* above function sets the status for us */
  100010. break;
  100011. case FLAC__STREAM_DECODER_READ_METADATA:
  100012. if(!read_metadata_(decoder))
  100013. return false; /* above function sets the status for us */
  100014. break;
  100015. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100016. case FLAC__STREAM_DECODER_READ_FRAME:
  100017. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100018. case FLAC__STREAM_DECODER_ABORTED:
  100019. return true;
  100020. default:
  100021. FLAC__ASSERT(0);
  100022. return false;
  100023. }
  100024. }
  100025. }
  100026. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  100027. {
  100028. FLAC__bool dummy;
  100029. FLAC__ASSERT(0 != decoder);
  100030. FLAC__ASSERT(0 != decoder->protected_);
  100031. while(1) {
  100032. switch(decoder->protected_->state) {
  100033. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100034. if(!find_metadata_(decoder))
  100035. return false; /* above function sets the status for us */
  100036. break;
  100037. case FLAC__STREAM_DECODER_READ_METADATA:
  100038. if(!read_metadata_(decoder))
  100039. return false; /* above function sets the status for us */
  100040. break;
  100041. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100042. if(!frame_sync_(decoder))
  100043. return true; /* above function sets the status for us */
  100044. break;
  100045. case FLAC__STREAM_DECODER_READ_FRAME:
  100046. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  100047. return false; /* above function sets the status for us */
  100048. break;
  100049. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100050. case FLAC__STREAM_DECODER_ABORTED:
  100051. return true;
  100052. default:
  100053. FLAC__ASSERT(0);
  100054. return false;
  100055. }
  100056. }
  100057. }
  100058. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  100059. {
  100060. FLAC__bool got_a_frame;
  100061. FLAC__ASSERT(0 != decoder);
  100062. FLAC__ASSERT(0 != decoder->protected_);
  100063. while(1) {
  100064. switch(decoder->protected_->state) {
  100065. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100066. case FLAC__STREAM_DECODER_READ_METADATA:
  100067. return false; /* above function sets the status for us */
  100068. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100069. if(!frame_sync_(decoder))
  100070. return true; /* above function sets the status for us */
  100071. break;
  100072. case FLAC__STREAM_DECODER_READ_FRAME:
  100073. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  100074. return false; /* above function sets the status for us */
  100075. if(got_a_frame)
  100076. return true; /* above function sets the status for us */
  100077. break;
  100078. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100079. case FLAC__STREAM_DECODER_ABORTED:
  100080. return true;
  100081. default:
  100082. FLAC__ASSERT(0);
  100083. return false;
  100084. }
  100085. }
  100086. }
  100087. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  100088. {
  100089. FLAC__uint64 length;
  100090. FLAC__ASSERT(0 != decoder);
  100091. if(
  100092. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  100093. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  100094. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  100095. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  100096. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  100097. )
  100098. return false;
  100099. if(0 == decoder->private_->seek_callback)
  100100. return false;
  100101. FLAC__ASSERT(decoder->private_->seek_callback);
  100102. FLAC__ASSERT(decoder->private_->tell_callback);
  100103. FLAC__ASSERT(decoder->private_->length_callback);
  100104. FLAC__ASSERT(decoder->private_->eof_callback);
  100105. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  100106. return false;
  100107. decoder->private_->is_seeking = true;
  100108. /* turn off md5 checking if a seek is attempted */
  100109. decoder->private_->do_md5_checking = false;
  100110. /* 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) */
  100111. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  100112. decoder->private_->is_seeking = false;
  100113. return false;
  100114. }
  100115. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  100116. if(
  100117. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  100118. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  100119. ) {
  100120. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  100121. /* above call sets the state for us */
  100122. decoder->private_->is_seeking = false;
  100123. return false;
  100124. }
  100125. /* check this again in case we didn't know total_samples the first time */
  100126. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100127. decoder->private_->is_seeking = false;
  100128. return false;
  100129. }
  100130. }
  100131. {
  100132. const FLAC__bool ok =
  100133. #if FLAC__HAS_OGG
  100134. decoder->private_->is_ogg?
  100135. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  100136. #endif
  100137. seek_to_absolute_sample_(decoder, length, sample)
  100138. ;
  100139. decoder->private_->is_seeking = false;
  100140. return ok;
  100141. }
  100142. }
  100143. /***********************************************************************
  100144. *
  100145. * Protected class methods
  100146. *
  100147. ***********************************************************************/
  100148. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  100149. {
  100150. FLAC__ASSERT(0 != decoder);
  100151. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100152. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  100153. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  100154. }
  100155. /***********************************************************************
  100156. *
  100157. * Private class methods
  100158. *
  100159. ***********************************************************************/
  100160. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  100161. {
  100162. #if FLAC__HAS_OGG
  100163. decoder->private_->is_ogg = false;
  100164. #endif
  100165. decoder->private_->read_callback = 0;
  100166. decoder->private_->seek_callback = 0;
  100167. decoder->private_->tell_callback = 0;
  100168. decoder->private_->length_callback = 0;
  100169. decoder->private_->eof_callback = 0;
  100170. decoder->private_->write_callback = 0;
  100171. decoder->private_->metadata_callback = 0;
  100172. decoder->private_->error_callback = 0;
  100173. decoder->private_->client_data = 0;
  100174. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  100175. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  100176. decoder->private_->metadata_filter_ids_count = 0;
  100177. decoder->protected_->md5_checking = false;
  100178. #if FLAC__HAS_OGG
  100179. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  100180. #endif
  100181. }
  100182. /*
  100183. * This will forcibly set stdin to binary mode (for OSes that require it)
  100184. */
  100185. FILE *get_binary_stdin_(void)
  100186. {
  100187. /* if something breaks here it is probably due to the presence or
  100188. * absence of an underscore before the identifiers 'setmode',
  100189. * 'fileno', and/or 'O_BINARY'; check your system header files.
  100190. */
  100191. #if defined _MSC_VER || defined __MINGW32__
  100192. _setmode(_fileno(stdin), _O_BINARY);
  100193. #elif defined __CYGWIN__
  100194. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  100195. setmode(_fileno(stdin), _O_BINARY);
  100196. #elif defined __EMX__
  100197. setmode(fileno(stdin), O_BINARY);
  100198. #endif
  100199. return stdin;
  100200. }
  100201. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  100202. {
  100203. unsigned i;
  100204. FLAC__int32 *tmp;
  100205. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  100206. return true;
  100207. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  100208. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  100209. if(0 != decoder->private_->output[i]) {
  100210. free(decoder->private_->output[i]-4);
  100211. decoder->private_->output[i] = 0;
  100212. }
  100213. if(0 != decoder->private_->residual_unaligned[i]) {
  100214. free(decoder->private_->residual_unaligned[i]);
  100215. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  100216. }
  100217. }
  100218. for(i = 0; i < channels; i++) {
  100219. /* WATCHOUT:
  100220. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  100221. * output arrays have a buffer of up to 3 zeroes in front
  100222. * (at negative indices) for alignment purposes; we use 4
  100223. * to keep the data well-aligned.
  100224. */
  100225. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  100226. if(tmp == 0) {
  100227. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100228. return false;
  100229. }
  100230. memset(tmp, 0, sizeof(FLAC__int32)*4);
  100231. decoder->private_->output[i] = tmp + 4;
  100232. /* WATCHOUT:
  100233. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  100234. */
  100235. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  100236. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100237. return false;
  100238. }
  100239. }
  100240. decoder->private_->output_capacity = size;
  100241. decoder->private_->output_channels = channels;
  100242. return true;
  100243. }
  100244. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  100245. {
  100246. size_t i;
  100247. FLAC__ASSERT(0 != decoder);
  100248. FLAC__ASSERT(0 != decoder->private_);
  100249. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  100250. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  100251. return true;
  100252. return false;
  100253. }
  100254. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  100255. {
  100256. FLAC__uint32 x;
  100257. unsigned i, id_;
  100258. FLAC__bool first = true;
  100259. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100260. for(i = id_ = 0; i < 4; ) {
  100261. if(decoder->private_->cached) {
  100262. x = (FLAC__uint32)decoder->private_->lookahead;
  100263. decoder->private_->cached = false;
  100264. }
  100265. else {
  100266. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100267. return false; /* read_callback_ sets the state for us */
  100268. }
  100269. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  100270. first = true;
  100271. i++;
  100272. id_ = 0;
  100273. continue;
  100274. }
  100275. if(x == ID3V2_TAG_[id_]) {
  100276. id_++;
  100277. i = 0;
  100278. if(id_ == 3) {
  100279. if(!skip_id3v2_tag_(decoder))
  100280. return false; /* skip_id3v2_tag_ sets the state for us */
  100281. }
  100282. continue;
  100283. }
  100284. id_ = 0;
  100285. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100286. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100287. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100288. return false; /* read_callback_ sets the state for us */
  100289. /* 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 */
  100290. /* else we have to check if the second byte is the end of a sync code */
  100291. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100292. decoder->private_->lookahead = (FLAC__byte)x;
  100293. decoder->private_->cached = true;
  100294. }
  100295. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100296. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100297. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100298. return true;
  100299. }
  100300. }
  100301. i = 0;
  100302. if(first) {
  100303. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100304. first = false;
  100305. }
  100306. }
  100307. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  100308. return true;
  100309. }
  100310. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  100311. {
  100312. FLAC__bool is_last;
  100313. FLAC__uint32 i, x, type, length;
  100314. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100315. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  100316. return false; /* read_callback_ sets the state for us */
  100317. is_last = x? true : false;
  100318. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  100319. return false; /* read_callback_ sets the state for us */
  100320. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  100321. return false; /* read_callback_ sets the state for us */
  100322. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  100323. if(!read_metadata_streaminfo_(decoder, is_last, length))
  100324. return false;
  100325. decoder->private_->has_stream_info = true;
  100326. 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))
  100327. decoder->private_->do_md5_checking = false;
  100328. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  100329. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  100330. }
  100331. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  100332. if(!read_metadata_seektable_(decoder, is_last, length))
  100333. return false;
  100334. decoder->private_->has_seek_table = true;
  100335. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  100336. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  100337. }
  100338. else {
  100339. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  100340. unsigned real_length = length;
  100341. FLAC__StreamMetadata block;
  100342. block.is_last = is_last;
  100343. block.type = (FLAC__MetadataType)type;
  100344. block.length = length;
  100345. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  100346. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  100347. return false; /* read_callback_ sets the state for us */
  100348. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  100349. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  100350. return false;
  100351. }
  100352. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  100353. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  100354. skip_it = !skip_it;
  100355. }
  100356. if(skip_it) {
  100357. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100358. return false; /* read_callback_ sets the state for us */
  100359. }
  100360. else {
  100361. switch(type) {
  100362. case FLAC__METADATA_TYPE_PADDING:
  100363. /* skip the padding bytes */
  100364. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100365. return false; /* read_callback_ sets the state for us */
  100366. break;
  100367. case FLAC__METADATA_TYPE_APPLICATION:
  100368. /* remember, we read the ID already */
  100369. if(real_length > 0) {
  100370. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  100371. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100372. return false;
  100373. }
  100374. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  100375. return false; /* read_callback_ sets the state for us */
  100376. }
  100377. else
  100378. block.data.application.data = 0;
  100379. break;
  100380. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100381. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  100382. return false;
  100383. break;
  100384. case FLAC__METADATA_TYPE_CUESHEET:
  100385. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  100386. return false;
  100387. break;
  100388. case FLAC__METADATA_TYPE_PICTURE:
  100389. if(!read_metadata_picture_(decoder, &block.data.picture))
  100390. return false;
  100391. break;
  100392. case FLAC__METADATA_TYPE_STREAMINFO:
  100393. case FLAC__METADATA_TYPE_SEEKTABLE:
  100394. FLAC__ASSERT(0);
  100395. break;
  100396. default:
  100397. if(real_length > 0) {
  100398. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  100399. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100400. return false;
  100401. }
  100402. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  100403. return false; /* read_callback_ sets the state for us */
  100404. }
  100405. else
  100406. block.data.unknown.data = 0;
  100407. break;
  100408. }
  100409. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  100410. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  100411. /* now we have to free any malloc()ed data in the block */
  100412. switch(type) {
  100413. case FLAC__METADATA_TYPE_PADDING:
  100414. break;
  100415. case FLAC__METADATA_TYPE_APPLICATION:
  100416. if(0 != block.data.application.data)
  100417. free(block.data.application.data);
  100418. break;
  100419. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100420. if(0 != block.data.vorbis_comment.vendor_string.entry)
  100421. free(block.data.vorbis_comment.vendor_string.entry);
  100422. if(block.data.vorbis_comment.num_comments > 0)
  100423. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  100424. if(0 != block.data.vorbis_comment.comments[i].entry)
  100425. free(block.data.vorbis_comment.comments[i].entry);
  100426. if(0 != block.data.vorbis_comment.comments)
  100427. free(block.data.vorbis_comment.comments);
  100428. break;
  100429. case FLAC__METADATA_TYPE_CUESHEET:
  100430. if(block.data.cue_sheet.num_tracks > 0)
  100431. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  100432. if(0 != block.data.cue_sheet.tracks[i].indices)
  100433. free(block.data.cue_sheet.tracks[i].indices);
  100434. if(0 != block.data.cue_sheet.tracks)
  100435. free(block.data.cue_sheet.tracks);
  100436. break;
  100437. case FLAC__METADATA_TYPE_PICTURE:
  100438. if(0 != block.data.picture.mime_type)
  100439. free(block.data.picture.mime_type);
  100440. if(0 != block.data.picture.description)
  100441. free(block.data.picture.description);
  100442. if(0 != block.data.picture.data)
  100443. free(block.data.picture.data);
  100444. break;
  100445. case FLAC__METADATA_TYPE_STREAMINFO:
  100446. case FLAC__METADATA_TYPE_SEEKTABLE:
  100447. FLAC__ASSERT(0);
  100448. default:
  100449. if(0 != block.data.unknown.data)
  100450. free(block.data.unknown.data);
  100451. break;
  100452. }
  100453. }
  100454. }
  100455. if(is_last) {
  100456. /* if this fails, it's OK, it's just a hint for the seek routine */
  100457. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  100458. decoder->private_->first_frame_offset = 0;
  100459. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100460. }
  100461. return true;
  100462. }
  100463. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100464. {
  100465. FLAC__uint32 x;
  100466. unsigned bits, used_bits = 0;
  100467. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100468. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  100469. decoder->private_->stream_info.is_last = is_last;
  100470. decoder->private_->stream_info.length = length;
  100471. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  100472. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  100473. return false; /* read_callback_ sets the state for us */
  100474. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  100475. used_bits += bits;
  100476. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  100477. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  100478. return false; /* read_callback_ sets the state for us */
  100479. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  100480. used_bits += bits;
  100481. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  100482. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  100483. return false; /* read_callback_ sets the state for us */
  100484. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  100485. used_bits += bits;
  100486. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  100487. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  100488. return false; /* read_callback_ sets the state for us */
  100489. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  100490. used_bits += bits;
  100491. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  100492. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  100493. return false; /* read_callback_ sets the state for us */
  100494. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  100495. used_bits += bits;
  100496. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  100497. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  100498. return false; /* read_callback_ sets the state for us */
  100499. decoder->private_->stream_info.data.stream_info.channels = x+1;
  100500. used_bits += bits;
  100501. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  100502. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  100503. return false; /* read_callback_ sets the state for us */
  100504. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  100505. used_bits += bits;
  100506. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  100507. 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))
  100508. return false; /* read_callback_ sets the state for us */
  100509. used_bits += bits;
  100510. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  100511. return false; /* read_callback_ sets the state for us */
  100512. used_bits += 16*8;
  100513. /* skip the rest of the block */
  100514. FLAC__ASSERT(used_bits % 8 == 0);
  100515. length -= (used_bits / 8);
  100516. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100517. return false; /* read_callback_ sets the state for us */
  100518. return true;
  100519. }
  100520. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100521. {
  100522. FLAC__uint32 i, x;
  100523. FLAC__uint64 xx;
  100524. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100525. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  100526. decoder->private_->seek_table.is_last = is_last;
  100527. decoder->private_->seek_table.length = length;
  100528. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  100529. /* use realloc since we may pass through here several times (e.g. after seeking) */
  100530. 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)))) {
  100531. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100532. return false;
  100533. }
  100534. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  100535. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  100536. return false; /* read_callback_ sets the state for us */
  100537. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  100538. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  100539. return false; /* read_callback_ sets the state for us */
  100540. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  100541. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  100542. return false; /* read_callback_ sets the state for us */
  100543. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  100544. }
  100545. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  100546. /* if there is a partial point left, skip over it */
  100547. if(length > 0) {
  100548. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  100549. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100550. return false; /* read_callback_ sets the state for us */
  100551. }
  100552. return true;
  100553. }
  100554. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  100555. {
  100556. FLAC__uint32 i;
  100557. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100558. /* read vendor string */
  100559. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100560. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  100561. return false; /* read_callback_ sets the state for us */
  100562. if(obj->vendor_string.length > 0) {
  100563. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  100564. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100565. return false;
  100566. }
  100567. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  100568. return false; /* read_callback_ sets the state for us */
  100569. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  100570. }
  100571. else
  100572. obj->vendor_string.entry = 0;
  100573. /* read num comments */
  100574. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  100575. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  100576. return false; /* read_callback_ sets the state for us */
  100577. /* read comments */
  100578. if(obj->num_comments > 0) {
  100579. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  100580. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100581. return false;
  100582. }
  100583. for(i = 0; i < obj->num_comments; i++) {
  100584. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100585. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  100586. return false; /* read_callback_ sets the state for us */
  100587. if(obj->comments[i].length > 0) {
  100588. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  100589. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100590. return false;
  100591. }
  100592. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  100593. return false; /* read_callback_ sets the state for us */
  100594. obj->comments[i].entry[obj->comments[i].length] = '\0';
  100595. }
  100596. else
  100597. obj->comments[i].entry = 0;
  100598. }
  100599. }
  100600. else {
  100601. obj->comments = 0;
  100602. }
  100603. return true;
  100604. }
  100605. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  100606. {
  100607. FLAC__uint32 i, j, x;
  100608. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100609. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  100610. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  100611. 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))
  100612. return false; /* read_callback_ sets the state for us */
  100613. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  100614. return false; /* read_callback_ sets the state for us */
  100615. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  100616. return false; /* read_callback_ sets the state for us */
  100617. obj->is_cd = x? true : false;
  100618. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  100619. return false; /* read_callback_ sets the state for us */
  100620. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  100621. return false; /* read_callback_ sets the state for us */
  100622. obj->num_tracks = x;
  100623. if(obj->num_tracks > 0) {
  100624. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  100625. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100626. return false;
  100627. }
  100628. for(i = 0; i < obj->num_tracks; i++) {
  100629. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  100630. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  100631. return false; /* read_callback_ sets the state for us */
  100632. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  100633. return false; /* read_callback_ sets the state for us */
  100634. track->number = (FLAC__byte)x;
  100635. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  100636. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  100637. return false; /* read_callback_ sets the state for us */
  100638. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  100639. return false; /* read_callback_ sets the state for us */
  100640. track->type = x;
  100641. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  100642. return false; /* read_callback_ sets the state for us */
  100643. track->pre_emphasis = x;
  100644. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_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_TRACK_NUM_INDICES_LEN))
  100647. return false; /* read_callback_ sets the state for us */
  100648. track->num_indices = (FLAC__byte)x;
  100649. if(track->num_indices > 0) {
  100650. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  100651. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100652. return false;
  100653. }
  100654. for(j = 0; j < track->num_indices; j++) {
  100655. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  100656. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  100657. return false; /* read_callback_ sets the state for us */
  100658. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  100659. return false; /* read_callback_ sets the state for us */
  100660. index->number = (FLAC__byte)x;
  100661. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  100662. return false; /* read_callback_ sets the state for us */
  100663. }
  100664. }
  100665. }
  100666. }
  100667. return true;
  100668. }
  100669. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  100670. {
  100671. FLAC__uint32 x;
  100672. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100673. /* read type */
  100674. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  100675. return false; /* read_callback_ sets the state for us */
  100676. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  100677. /* read MIME type */
  100678. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  100679. return false; /* read_callback_ sets the state for us */
  100680. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  100681. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100682. return false;
  100683. }
  100684. if(x > 0) {
  100685. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  100686. return false; /* read_callback_ sets the state for us */
  100687. }
  100688. obj->mime_type[x] = '\0';
  100689. /* read description */
  100690. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  100691. return false; /* read_callback_ sets the state for us */
  100692. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  100693. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100694. return false;
  100695. }
  100696. if(x > 0) {
  100697. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  100698. return false; /* read_callback_ sets the state for us */
  100699. }
  100700. obj->description[x] = '\0';
  100701. /* read width */
  100702. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  100703. return false; /* read_callback_ sets the state for us */
  100704. /* read height */
  100705. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  100706. return false; /* read_callback_ sets the state for us */
  100707. /* read depth */
  100708. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  100709. return false; /* read_callback_ sets the state for us */
  100710. /* read colors */
  100711. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  100712. return false; /* read_callback_ sets the state for us */
  100713. /* read data */
  100714. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  100715. return false; /* read_callback_ sets the state for us */
  100716. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  100717. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100718. return false;
  100719. }
  100720. if(obj->data_length > 0) {
  100721. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  100722. return false; /* read_callback_ sets the state for us */
  100723. }
  100724. return true;
  100725. }
  100726. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  100727. {
  100728. FLAC__uint32 x;
  100729. unsigned i, skip;
  100730. /* skip the version and flags bytes */
  100731. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  100732. return false; /* read_callback_ sets the state for us */
  100733. /* get the size (in bytes) to skip */
  100734. skip = 0;
  100735. for(i = 0; i < 4; i++) {
  100736. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100737. return false; /* read_callback_ sets the state for us */
  100738. skip <<= 7;
  100739. skip |= (x & 0x7f);
  100740. }
  100741. /* skip the rest of the tag */
  100742. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  100743. return false; /* read_callback_ sets the state for us */
  100744. return true;
  100745. }
  100746. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  100747. {
  100748. FLAC__uint32 x;
  100749. FLAC__bool first = true;
  100750. /* If we know the total number of samples in the stream, stop if we've read that many. */
  100751. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  100752. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  100753. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100754. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  100755. return true;
  100756. }
  100757. }
  100758. /* make sure we're byte aligned */
  100759. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  100760. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  100761. return false; /* read_callback_ sets the state for us */
  100762. }
  100763. while(1) {
  100764. if(decoder->private_->cached) {
  100765. x = (FLAC__uint32)decoder->private_->lookahead;
  100766. decoder->private_->cached = false;
  100767. }
  100768. else {
  100769. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100770. return false; /* read_callback_ sets the state for us */
  100771. }
  100772. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100773. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100774. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100775. return false; /* read_callback_ sets the state for us */
  100776. /* 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 */
  100777. /* else we have to check if the second byte is the end of a sync code */
  100778. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100779. decoder->private_->lookahead = (FLAC__byte)x;
  100780. decoder->private_->cached = true;
  100781. }
  100782. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100783. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100784. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100785. return true;
  100786. }
  100787. }
  100788. if(first) {
  100789. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100790. first = false;
  100791. }
  100792. }
  100793. return true;
  100794. }
  100795. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  100796. {
  100797. unsigned channel;
  100798. unsigned i;
  100799. FLAC__int32 mid, side;
  100800. unsigned frame_crc; /* the one we calculate from the input stream */
  100801. FLAC__uint32 x;
  100802. *got_a_frame = false;
  100803. /* init the CRC */
  100804. frame_crc = 0;
  100805. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  100806. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  100807. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  100808. if(!read_frame_header_(decoder))
  100809. return false;
  100810. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  100811. return true;
  100812. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  100813. return false;
  100814. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100815. /*
  100816. * first figure the correct bits-per-sample of the subframe
  100817. */
  100818. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  100819. switch(decoder->private_->frame.header.channel_assignment) {
  100820. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100821. /* no adjustment needed */
  100822. break;
  100823. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100824. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100825. if(channel == 1)
  100826. bps++;
  100827. break;
  100828. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100829. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100830. if(channel == 0)
  100831. bps++;
  100832. break;
  100833. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100834. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100835. if(channel == 1)
  100836. bps++;
  100837. break;
  100838. default:
  100839. FLAC__ASSERT(0);
  100840. }
  100841. /*
  100842. * now read it
  100843. */
  100844. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  100845. return false;
  100846. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  100847. return true;
  100848. }
  100849. if(!read_zero_padding_(decoder))
  100850. return false;
  100851. 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) */
  100852. return true;
  100853. /*
  100854. * Read the frame CRC-16 from the footer and check
  100855. */
  100856. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  100857. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  100858. return false; /* read_callback_ sets the state for us */
  100859. if(frame_crc == x) {
  100860. if(do_full_decode) {
  100861. /* Undo any special channel coding */
  100862. switch(decoder->private_->frame.header.channel_assignment) {
  100863. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  100864. /* do nothing */
  100865. break;
  100866. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  100867. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100868. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100869. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  100870. break;
  100871. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  100872. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100873. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  100874. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  100875. break;
  100876. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  100877. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  100878. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  100879. #if 1
  100880. mid = decoder->private_->output[0][i];
  100881. side = decoder->private_->output[1][i];
  100882. mid <<= 1;
  100883. mid |= (side & 1); /* i.e. if 'side' is odd... */
  100884. decoder->private_->output[0][i] = (mid + side) >> 1;
  100885. decoder->private_->output[1][i] = (mid - side) >> 1;
  100886. #else
  100887. /* OPT: without 'side' temp variable */
  100888. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  100889. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  100890. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  100891. #endif
  100892. }
  100893. break;
  100894. default:
  100895. FLAC__ASSERT(0);
  100896. break;
  100897. }
  100898. }
  100899. }
  100900. else {
  100901. /* Bad frame, emit error and zero the output signal */
  100902. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  100903. if(do_full_decode) {
  100904. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  100905. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  100906. }
  100907. }
  100908. }
  100909. *got_a_frame = true;
  100910. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  100911. if(decoder->private_->next_fixed_block_size)
  100912. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  100913. /* put the latest values into the public section of the decoder instance */
  100914. decoder->protected_->channels = decoder->private_->frame.header.channels;
  100915. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  100916. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  100917. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  100918. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  100919. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  100920. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  100921. /* write it */
  100922. if(do_full_decode) {
  100923. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  100924. return false;
  100925. }
  100926. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100927. return true;
  100928. }
  100929. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  100930. {
  100931. FLAC__uint32 x;
  100932. FLAC__uint64 xx;
  100933. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  100934. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  100935. unsigned raw_header_len;
  100936. FLAC__bool is_unparseable = false;
  100937. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100938. /* init the raw header with the saved bits from synchronization */
  100939. raw_header[0] = decoder->private_->header_warmup[0];
  100940. raw_header[1] = decoder->private_->header_warmup[1];
  100941. raw_header_len = 2;
  100942. /* check to make sure that reserved bit is 0 */
  100943. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  100944. is_unparseable = true;
  100945. /*
  100946. * Note that along the way as we read the header, we look for a sync
  100947. * code inside. If we find one it would indicate that our original
  100948. * sync was bad since there cannot be a sync code in a valid header.
  100949. *
  100950. * Three kinds of things can go wrong when reading the frame header:
  100951. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  100952. * If we don't find a sync code, it can end up looking like we read
  100953. * a valid but unparseable header, until getting to the frame header
  100954. * CRC. Even then we could get a false positive on the CRC.
  100955. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  100956. * future encoder).
  100957. * 3) We may be on a damaged frame which appears valid but unparseable.
  100958. *
  100959. * For all these reasons, we try and read a complete frame header as
  100960. * long as it seems valid, even if unparseable, up until the frame
  100961. * header CRC.
  100962. */
  100963. /*
  100964. * read in the raw header as bytes so we can CRC it, and parse it on the way
  100965. */
  100966. for(i = 0; i < 2; i++) {
  100967. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100968. return false; /* read_callback_ sets the state for us */
  100969. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100970. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  100971. decoder->private_->lookahead = (FLAC__byte)x;
  100972. decoder->private_->cached = true;
  100973. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  100974. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100975. return true;
  100976. }
  100977. raw_header[raw_header_len++] = (FLAC__byte)x;
  100978. }
  100979. switch(x = raw_header[2] >> 4) {
  100980. case 0:
  100981. is_unparseable = true;
  100982. break;
  100983. case 1:
  100984. decoder->private_->frame.header.blocksize = 192;
  100985. break;
  100986. case 2:
  100987. case 3:
  100988. case 4:
  100989. case 5:
  100990. decoder->private_->frame.header.blocksize = 576 << (x-2);
  100991. break;
  100992. case 6:
  100993. case 7:
  100994. blocksize_hint = x;
  100995. break;
  100996. case 8:
  100997. case 9:
  100998. case 10:
  100999. case 11:
  101000. case 12:
  101001. case 13:
  101002. case 14:
  101003. case 15:
  101004. decoder->private_->frame.header.blocksize = 256 << (x-8);
  101005. break;
  101006. default:
  101007. FLAC__ASSERT(0);
  101008. break;
  101009. }
  101010. switch(x = raw_header[2] & 0x0f) {
  101011. case 0:
  101012. if(decoder->private_->has_stream_info)
  101013. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  101014. else
  101015. is_unparseable = true;
  101016. break;
  101017. case 1:
  101018. decoder->private_->frame.header.sample_rate = 88200;
  101019. break;
  101020. case 2:
  101021. decoder->private_->frame.header.sample_rate = 176400;
  101022. break;
  101023. case 3:
  101024. decoder->private_->frame.header.sample_rate = 192000;
  101025. break;
  101026. case 4:
  101027. decoder->private_->frame.header.sample_rate = 8000;
  101028. break;
  101029. case 5:
  101030. decoder->private_->frame.header.sample_rate = 16000;
  101031. break;
  101032. case 6:
  101033. decoder->private_->frame.header.sample_rate = 22050;
  101034. break;
  101035. case 7:
  101036. decoder->private_->frame.header.sample_rate = 24000;
  101037. break;
  101038. case 8:
  101039. decoder->private_->frame.header.sample_rate = 32000;
  101040. break;
  101041. case 9:
  101042. decoder->private_->frame.header.sample_rate = 44100;
  101043. break;
  101044. case 10:
  101045. decoder->private_->frame.header.sample_rate = 48000;
  101046. break;
  101047. case 11:
  101048. decoder->private_->frame.header.sample_rate = 96000;
  101049. break;
  101050. case 12:
  101051. case 13:
  101052. case 14:
  101053. sample_rate_hint = x;
  101054. break;
  101055. case 15:
  101056. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101057. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101058. return true;
  101059. default:
  101060. FLAC__ASSERT(0);
  101061. }
  101062. x = (unsigned)(raw_header[3] >> 4);
  101063. if(x & 8) {
  101064. decoder->private_->frame.header.channels = 2;
  101065. switch(x & 7) {
  101066. case 0:
  101067. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  101068. break;
  101069. case 1:
  101070. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  101071. break;
  101072. case 2:
  101073. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  101074. break;
  101075. default:
  101076. is_unparseable = true;
  101077. break;
  101078. }
  101079. }
  101080. else {
  101081. decoder->private_->frame.header.channels = (unsigned)x + 1;
  101082. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  101083. }
  101084. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  101085. case 0:
  101086. if(decoder->private_->has_stream_info)
  101087. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  101088. else
  101089. is_unparseable = true;
  101090. break;
  101091. case 1:
  101092. decoder->private_->frame.header.bits_per_sample = 8;
  101093. break;
  101094. case 2:
  101095. decoder->private_->frame.header.bits_per_sample = 12;
  101096. break;
  101097. case 4:
  101098. decoder->private_->frame.header.bits_per_sample = 16;
  101099. break;
  101100. case 5:
  101101. decoder->private_->frame.header.bits_per_sample = 20;
  101102. break;
  101103. case 6:
  101104. decoder->private_->frame.header.bits_per_sample = 24;
  101105. break;
  101106. case 3:
  101107. case 7:
  101108. is_unparseable = true;
  101109. break;
  101110. default:
  101111. FLAC__ASSERT(0);
  101112. break;
  101113. }
  101114. /* check to make sure that reserved bit is 0 */
  101115. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  101116. is_unparseable = true;
  101117. /* read the frame's starting sample number (or frame number as the case may be) */
  101118. if(
  101119. raw_header[1] & 0x01 ||
  101120. /*@@@ 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 */
  101121. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  101122. ) { /* variable blocksize */
  101123. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  101124. return false; /* read_callback_ sets the state for us */
  101125. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  101126. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  101127. decoder->private_->cached = true;
  101128. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101129. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101130. return true;
  101131. }
  101132. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  101133. decoder->private_->frame.header.number.sample_number = xx;
  101134. }
  101135. else { /* fixed blocksize */
  101136. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  101137. return false; /* read_callback_ sets the state for us */
  101138. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  101139. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  101140. decoder->private_->cached = true;
  101141. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101142. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101143. return true;
  101144. }
  101145. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  101146. decoder->private_->frame.header.number.frame_number = x;
  101147. }
  101148. if(blocksize_hint) {
  101149. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101150. return false; /* read_callback_ sets the state for us */
  101151. raw_header[raw_header_len++] = (FLAC__byte)x;
  101152. if(blocksize_hint == 7) {
  101153. FLAC__uint32 _x;
  101154. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  101155. return false; /* read_callback_ sets the state for us */
  101156. raw_header[raw_header_len++] = (FLAC__byte)_x;
  101157. x = (x << 8) | _x;
  101158. }
  101159. decoder->private_->frame.header.blocksize = x+1;
  101160. }
  101161. if(sample_rate_hint) {
  101162. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101163. return false; /* read_callback_ sets the state for us */
  101164. raw_header[raw_header_len++] = (FLAC__byte)x;
  101165. if(sample_rate_hint != 12) {
  101166. FLAC__uint32 _x;
  101167. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  101168. return false; /* read_callback_ sets the state for us */
  101169. raw_header[raw_header_len++] = (FLAC__byte)_x;
  101170. x = (x << 8) | _x;
  101171. }
  101172. if(sample_rate_hint == 12)
  101173. decoder->private_->frame.header.sample_rate = x*1000;
  101174. else if(sample_rate_hint == 13)
  101175. decoder->private_->frame.header.sample_rate = x;
  101176. else
  101177. decoder->private_->frame.header.sample_rate = x*10;
  101178. }
  101179. /* read the CRC-8 byte */
  101180. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101181. return false; /* read_callback_ sets the state for us */
  101182. crc8 = (FLAC__byte)x;
  101183. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  101184. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101185. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101186. return true;
  101187. }
  101188. /* calculate the sample number from the frame number if needed */
  101189. decoder->private_->next_fixed_block_size = 0;
  101190. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  101191. x = decoder->private_->frame.header.number.frame_number;
  101192. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  101193. if(decoder->private_->fixed_block_size)
  101194. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  101195. else if(decoder->private_->has_stream_info) {
  101196. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  101197. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  101198. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101199. }
  101200. else
  101201. is_unparseable = true;
  101202. }
  101203. else if(x == 0) {
  101204. decoder->private_->frame.header.number.sample_number = 0;
  101205. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  101206. }
  101207. else {
  101208. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  101209. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  101210. }
  101211. }
  101212. if(is_unparseable) {
  101213. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101214. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101215. return true;
  101216. }
  101217. return true;
  101218. }
  101219. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101220. {
  101221. FLAC__uint32 x;
  101222. FLAC__bool wasted_bits;
  101223. unsigned i;
  101224. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  101225. return false; /* read_callback_ sets the state for us */
  101226. wasted_bits = (x & 1);
  101227. x &= 0xfe;
  101228. if(wasted_bits) {
  101229. unsigned u;
  101230. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  101231. return false; /* read_callback_ sets the state for us */
  101232. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  101233. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  101234. }
  101235. else
  101236. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  101237. /*
  101238. * Lots of magic numbers here
  101239. */
  101240. if(x & 0x80) {
  101241. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101242. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101243. return true;
  101244. }
  101245. else if(x == 0) {
  101246. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  101247. return false;
  101248. }
  101249. else if(x == 2) {
  101250. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  101251. return false;
  101252. }
  101253. else if(x < 16) {
  101254. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101255. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101256. return true;
  101257. }
  101258. else if(x <= 24) {
  101259. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  101260. return false;
  101261. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101262. return true;
  101263. }
  101264. else if(x < 64) {
  101265. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101266. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101267. return true;
  101268. }
  101269. else {
  101270. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  101271. return false;
  101272. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101273. return true;
  101274. }
  101275. if(wasted_bits && do_full_decode) {
  101276. x = decoder->private_->frame.subframes[channel].wasted_bits;
  101277. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101278. decoder->private_->output[channel][i] <<= x;
  101279. }
  101280. return true;
  101281. }
  101282. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101283. {
  101284. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  101285. FLAC__int32 x;
  101286. unsigned i;
  101287. FLAC__int32 *output = decoder->private_->output[channel];
  101288. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  101289. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101290. return false; /* read_callback_ sets the state for us */
  101291. subframe->value = x;
  101292. /* decode the subframe */
  101293. if(do_full_decode) {
  101294. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101295. output[i] = x;
  101296. }
  101297. return true;
  101298. }
  101299. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101300. {
  101301. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  101302. FLAC__int32 i32;
  101303. FLAC__uint32 u32;
  101304. unsigned u;
  101305. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  101306. subframe->residual = decoder->private_->residual[channel];
  101307. subframe->order = order;
  101308. /* read warm-up samples */
  101309. for(u = 0; u < order; u++) {
  101310. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101311. return false; /* read_callback_ sets the state for us */
  101312. subframe->warmup[u] = i32;
  101313. }
  101314. /* read entropy coding method info */
  101315. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101316. return false; /* read_callback_ sets the state for us */
  101317. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101318. switch(subframe->entropy_coding_method.type) {
  101319. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101320. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101321. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101322. return false; /* read_callback_ sets the state for us */
  101323. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101324. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101325. break;
  101326. default:
  101327. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101328. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101329. return true;
  101330. }
  101331. /* read residual */
  101332. switch(subframe->entropy_coding_method.type) {
  101333. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101334. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101335. 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))
  101336. return false;
  101337. break;
  101338. default:
  101339. FLAC__ASSERT(0);
  101340. }
  101341. /* decode the subframe */
  101342. if(do_full_decode) {
  101343. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101344. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  101345. }
  101346. return true;
  101347. }
  101348. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101349. {
  101350. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  101351. FLAC__int32 i32;
  101352. FLAC__uint32 u32;
  101353. unsigned u;
  101354. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  101355. subframe->residual = decoder->private_->residual[channel];
  101356. subframe->order = order;
  101357. /* read warm-up samples */
  101358. for(u = 0; u < order; u++) {
  101359. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101360. return false; /* read_callback_ sets the state for us */
  101361. subframe->warmup[u] = i32;
  101362. }
  101363. /* read qlp coeff precision */
  101364. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  101365. return false; /* read_callback_ sets the state for us */
  101366. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  101367. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101368. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101369. return true;
  101370. }
  101371. subframe->qlp_coeff_precision = u32+1;
  101372. /* read qlp shift */
  101373. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  101374. return false; /* read_callback_ sets the state for us */
  101375. subframe->quantization_level = i32;
  101376. /* read quantized lp coefficiencts */
  101377. for(u = 0; u < order; u++) {
  101378. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  101379. return false; /* read_callback_ sets the state for us */
  101380. subframe->qlp_coeff[u] = i32;
  101381. }
  101382. /* read entropy coding method info */
  101383. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101384. return false; /* read_callback_ sets the state for us */
  101385. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101386. switch(subframe->entropy_coding_method.type) {
  101387. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101388. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101389. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101390. return false; /* read_callback_ sets the state for us */
  101391. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101392. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101393. break;
  101394. default:
  101395. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101396. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101397. return true;
  101398. }
  101399. /* read residual */
  101400. switch(subframe->entropy_coding_method.type) {
  101401. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101402. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101403. 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))
  101404. return false;
  101405. break;
  101406. default:
  101407. FLAC__ASSERT(0);
  101408. }
  101409. /* decode the subframe */
  101410. if(do_full_decode) {
  101411. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101412. /*@@@@@@ technically not pessimistic enough, should be more like
  101413. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  101414. */
  101415. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  101416. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  101417. if(order <= 8)
  101418. 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);
  101419. else
  101420. 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);
  101421. }
  101422. else
  101423. 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);
  101424. else
  101425. 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);
  101426. }
  101427. return true;
  101428. }
  101429. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101430. {
  101431. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  101432. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  101433. unsigned i;
  101434. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  101435. subframe->data = residual;
  101436. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  101437. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101438. return false; /* read_callback_ sets the state for us */
  101439. residual[i] = x;
  101440. }
  101441. /* decode the subframe */
  101442. if(do_full_decode)
  101443. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  101444. return true;
  101445. }
  101446. 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)
  101447. {
  101448. FLAC__uint32 rice_parameter;
  101449. int i;
  101450. unsigned partition, sample, u;
  101451. const unsigned partitions = 1u << partition_order;
  101452. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  101453. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  101454. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  101455. /* sanity checks */
  101456. if(partition_order == 0) {
  101457. if(decoder->private_->frame.header.blocksize < predictor_order) {
  101458. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101459. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101460. return true;
  101461. }
  101462. }
  101463. else {
  101464. if(partition_samples < predictor_order) {
  101465. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101466. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101467. return true;
  101468. }
  101469. }
  101470. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  101471. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  101472. return false;
  101473. }
  101474. sample = 0;
  101475. for(partition = 0; partition < partitions; partition++) {
  101476. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  101477. return false; /* read_callback_ sets the state for us */
  101478. partitioned_rice_contents->parameters[partition] = rice_parameter;
  101479. if(rice_parameter < pesc) {
  101480. partitioned_rice_contents->raw_bits[partition] = 0;
  101481. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  101482. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  101483. return false; /* read_callback_ sets the state for us */
  101484. sample += u;
  101485. }
  101486. else {
  101487. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  101488. return false; /* read_callback_ sets the state for us */
  101489. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  101490. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  101491. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  101492. return false; /* read_callback_ sets the state for us */
  101493. residual[sample] = i;
  101494. }
  101495. }
  101496. }
  101497. return true;
  101498. }
  101499. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  101500. {
  101501. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  101502. FLAC__uint32 zero = 0;
  101503. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  101504. return false; /* read_callback_ sets the state for us */
  101505. if(zero != 0) {
  101506. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101507. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101508. }
  101509. }
  101510. return true;
  101511. }
  101512. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  101513. {
  101514. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  101515. if(
  101516. #if FLAC__HAS_OGG
  101517. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101518. !decoder->private_->is_ogg &&
  101519. #endif
  101520. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101521. ) {
  101522. *bytes = 0;
  101523. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101524. return false;
  101525. }
  101526. else if(*bytes > 0) {
  101527. /* While seeking, it is possible for our seek to land in the
  101528. * middle of audio data that looks exactly like a frame header
  101529. * from a future version of an encoder. When that happens, our
  101530. * error callback will get an
  101531. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  101532. * unparseable_frame_count. But there is a remote possibility
  101533. * that it is properly synced at such a "future-codec frame",
  101534. * so to make sure, we wait to see many "unparseable" errors in
  101535. * a row before bailing out.
  101536. */
  101537. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  101538. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101539. return false;
  101540. }
  101541. else {
  101542. const FLAC__StreamDecoderReadStatus status =
  101543. #if FLAC__HAS_OGG
  101544. decoder->private_->is_ogg?
  101545. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  101546. #endif
  101547. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  101548. ;
  101549. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  101550. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101551. return false;
  101552. }
  101553. else if(*bytes == 0) {
  101554. if(
  101555. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  101556. (
  101557. #if FLAC__HAS_OGG
  101558. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101559. !decoder->private_->is_ogg &&
  101560. #endif
  101561. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101562. )
  101563. ) {
  101564. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101565. return false;
  101566. }
  101567. else
  101568. return true;
  101569. }
  101570. else
  101571. return true;
  101572. }
  101573. }
  101574. else {
  101575. /* abort to avoid a deadlock */
  101576. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101577. return false;
  101578. }
  101579. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  101580. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  101581. * and at the same time hit the end of the stream (for example, seeking
  101582. * to a point that is after the beginning of the last Ogg page). There
  101583. * is no way to report an Ogg sync loss through the callbacks (see note
  101584. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  101585. * So to keep the decoder from stopping at this point we gate the call
  101586. * to the eof_callback and let the Ogg decoder aspect set the
  101587. * end-of-stream state when it is needed.
  101588. */
  101589. }
  101590. #if FLAC__HAS_OGG
  101591. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  101592. {
  101593. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  101594. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  101595. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101596. /* we don't really have a way to handle lost sync via read
  101597. * callback so we'll let it pass and let the underlying
  101598. * FLAC decoder catch the error
  101599. */
  101600. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  101601. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101602. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  101603. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101604. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  101605. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  101606. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  101607. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  101608. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  101609. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101610. default:
  101611. FLAC__ASSERT(0);
  101612. /* double protection */
  101613. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101614. }
  101615. }
  101616. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101617. {
  101618. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  101619. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  101620. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  101621. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  101622. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  101623. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  101624. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  101625. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101626. default:
  101627. /* double protection: */
  101628. FLAC__ASSERT(0);
  101629. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101630. }
  101631. }
  101632. #endif
  101633. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  101634. {
  101635. if(decoder->private_->is_seeking) {
  101636. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  101637. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  101638. FLAC__uint64 target_sample = decoder->private_->target_sample;
  101639. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101640. #if FLAC__HAS_OGG
  101641. decoder->private_->got_a_frame = true;
  101642. #endif
  101643. decoder->private_->last_frame = *frame; /* save the frame */
  101644. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  101645. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  101646. /* kick out of seek mode */
  101647. decoder->private_->is_seeking = false;
  101648. /* shift out the samples before target_sample */
  101649. if(delta > 0) {
  101650. unsigned channel;
  101651. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  101652. for(channel = 0; channel < frame->header.channels; channel++)
  101653. newbuffer[channel] = buffer[channel] + delta;
  101654. decoder->private_->last_frame.header.blocksize -= delta;
  101655. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  101656. /* write the relevant samples */
  101657. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  101658. }
  101659. else {
  101660. /* write the relevant samples */
  101661. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101662. }
  101663. }
  101664. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  101665. }
  101666. /*
  101667. * If we never got STREAMINFO, turn off MD5 checking to save
  101668. * cycles since we don't have a sum to compare to anyway
  101669. */
  101670. if(!decoder->private_->has_stream_info)
  101671. decoder->private_->do_md5_checking = false;
  101672. if(decoder->private_->do_md5_checking) {
  101673. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  101674. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  101675. }
  101676. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101677. }
  101678. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  101679. {
  101680. if(!decoder->private_->is_seeking)
  101681. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  101682. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  101683. decoder->private_->unparseable_frame_count++;
  101684. }
  101685. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101686. {
  101687. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  101688. FLAC__int64 pos = -1;
  101689. int i;
  101690. unsigned approx_bytes_per_frame;
  101691. FLAC__bool first_seek = true;
  101692. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  101693. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  101694. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101695. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  101696. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  101697. /* take these from the current frame in case they've changed mid-stream */
  101698. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  101699. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  101700. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  101701. /* use values from stream info if we didn't decode a frame */
  101702. if(channels == 0)
  101703. channels = decoder->private_->stream_info.data.stream_info.channels;
  101704. if(bps == 0)
  101705. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  101706. /* we are just guessing here */
  101707. if(max_framesize > 0)
  101708. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  101709. /*
  101710. * Check if it's a known fixed-blocksize stream. Note that though
  101711. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  101712. * never get a STREAMINFO block when decoding so the value of
  101713. * min_blocksize might be zero.
  101714. */
  101715. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  101716. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  101717. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  101718. }
  101719. else
  101720. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  101721. /*
  101722. * First, we set an upper and lower bound on where in the
  101723. * stream we will search. For now we assume the worst case
  101724. * scenario, which is our best guess at the beginning of
  101725. * the first frame and end of the stream.
  101726. */
  101727. lower_bound = first_frame_offset;
  101728. lower_bound_sample = 0;
  101729. upper_bound = stream_length;
  101730. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  101731. /*
  101732. * Now we refine the bounds if we have a seektable with
  101733. * suitable points. Note that according to the spec they
  101734. * must be ordered by ascending sample number.
  101735. *
  101736. * Note: to protect against invalid seek tables we will ignore points
  101737. * that have frame_samples==0 or sample_number>=total_samples
  101738. */
  101739. if(seek_table) {
  101740. FLAC__uint64 new_lower_bound = lower_bound;
  101741. FLAC__uint64 new_upper_bound = upper_bound;
  101742. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  101743. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  101744. /* find the closest seek point <= target_sample, if it exists */
  101745. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  101746. if(
  101747. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101748. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101749. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101750. seek_table->points[i].sample_number <= target_sample
  101751. )
  101752. break;
  101753. }
  101754. if(i >= 0) { /* i.e. we found a suitable seek point... */
  101755. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101756. new_lower_bound_sample = seek_table->points[i].sample_number;
  101757. }
  101758. /* find the closest seek point > target_sample, if it exists */
  101759. for(i = 0; i < (int)seek_table->num_points; i++) {
  101760. if(
  101761. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101762. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101763. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101764. seek_table->points[i].sample_number > target_sample
  101765. )
  101766. break;
  101767. }
  101768. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  101769. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101770. new_upper_bound_sample = seek_table->points[i].sample_number;
  101771. }
  101772. /* final protection against unsorted seek tables; keep original values if bogus */
  101773. if(new_upper_bound >= new_lower_bound) {
  101774. lower_bound = new_lower_bound;
  101775. upper_bound = new_upper_bound;
  101776. lower_bound_sample = new_lower_bound_sample;
  101777. upper_bound_sample = new_upper_bound_sample;
  101778. }
  101779. }
  101780. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  101781. /* there are 2 insidious ways that the following equality occurs, which
  101782. * we need to fix:
  101783. * 1) total_samples is 0 (unknown) and target_sample is 0
  101784. * 2) total_samples is 0 (unknown) and target_sample happens to be
  101785. * exactly equal to the last seek point in the seek table; this
  101786. * means there is no seek point above it, and upper_bound_samples
  101787. * remains equal to the estimate (of target_samples) we made above
  101788. * in either case it does not hurt to move upper_bound_sample up by 1
  101789. */
  101790. if(upper_bound_sample == lower_bound_sample)
  101791. upper_bound_sample++;
  101792. decoder->private_->target_sample = target_sample;
  101793. while(1) {
  101794. /* check if the bounds are still ok */
  101795. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  101796. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101797. return false;
  101798. }
  101799. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101800. #if defined _MSC_VER || defined __MINGW32__
  101801. /* with VC++ you have to spoon feed it the casting */
  101802. 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;
  101803. #else
  101804. 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;
  101805. #endif
  101806. #else
  101807. /* a little less accurate: */
  101808. if(upper_bound - lower_bound < 0xffffffff)
  101809. 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;
  101810. else /* @@@ WATCHOUT, ~2TB limit */
  101811. 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;
  101812. #endif
  101813. if(pos >= (FLAC__int64)upper_bound)
  101814. pos = (FLAC__int64)upper_bound - 1;
  101815. if(pos < (FLAC__int64)lower_bound)
  101816. pos = (FLAC__int64)lower_bound;
  101817. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101818. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101819. return false;
  101820. }
  101821. if(!FLAC__stream_decoder_flush(decoder)) {
  101822. /* above call sets the state for us */
  101823. return false;
  101824. }
  101825. /* Now we need to get a frame. First we need to reset our
  101826. * unparseable_frame_count; if we get too many unparseable
  101827. * frames in a row, the read callback will return
  101828. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  101829. * FLAC__stream_decoder_process_single() to return false.
  101830. */
  101831. decoder->private_->unparseable_frame_count = 0;
  101832. if(!FLAC__stream_decoder_process_single(decoder)) {
  101833. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101834. return false;
  101835. }
  101836. /* our write callback will change the state when it gets to the target frame */
  101837. /* 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 */
  101838. #if 0
  101839. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  101840. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  101841. break;
  101842. #endif
  101843. if(!decoder->private_->is_seeking)
  101844. break;
  101845. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101846. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  101847. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  101848. if (pos == (FLAC__int64)lower_bound) {
  101849. /* can't move back any more than the first frame, something is fatally wrong */
  101850. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101851. return false;
  101852. }
  101853. /* our last move backwards wasn't big enough, try again */
  101854. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  101855. continue;
  101856. }
  101857. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  101858. first_seek = false;
  101859. /* make sure we are not seeking in corrupted stream */
  101860. if (this_frame_sample < lower_bound_sample) {
  101861. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101862. return false;
  101863. }
  101864. /* we need to narrow the search */
  101865. if(target_sample < this_frame_sample) {
  101866. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  101867. /*@@@@@@ what will decode position be if at end of stream? */
  101868. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  101869. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101870. return false;
  101871. }
  101872. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  101873. }
  101874. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  101875. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  101876. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  101877. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101878. return false;
  101879. }
  101880. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  101881. }
  101882. }
  101883. return true;
  101884. }
  101885. #if FLAC__HAS_OGG
  101886. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101887. {
  101888. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  101889. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  101890. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  101891. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  101892. FLAC__bool did_a_seek;
  101893. unsigned iteration = 0;
  101894. /* In the first iterations, we will calculate the target byte position
  101895. * by the distance from the target sample to left_sample and
  101896. * right_sample (let's call it "proportional search"). After that, we
  101897. * will switch to binary search.
  101898. */
  101899. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  101900. /* We will switch to a linear search once our current sample is less
  101901. * than this number of samples ahead of the target sample
  101902. */
  101903. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  101904. /* If the total number of samples is unknown, use a large value, and
  101905. * force binary search immediately.
  101906. */
  101907. if(right_sample == 0) {
  101908. right_sample = (FLAC__uint64)(-1);
  101909. BINARY_SEARCH_AFTER_ITERATION = 0;
  101910. }
  101911. decoder->private_->target_sample = target_sample;
  101912. for( ; ; iteration++) {
  101913. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  101914. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  101915. pos = (right_pos + left_pos) / 2;
  101916. }
  101917. else {
  101918. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101919. #if defined _MSC_VER || defined __MINGW32__
  101920. /* with MSVC you have to spoon feed it the casting */
  101921. 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));
  101922. #else
  101923. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  101924. #endif
  101925. #else
  101926. /* a little less accurate: */
  101927. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  101928. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  101929. else /* @@@ WATCHOUT, ~2TB limit */
  101930. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  101931. #endif
  101932. /* @@@ TODO: might want to limit pos to some distance
  101933. * before EOF, to make sure we land before the last frame,
  101934. * thereby getting a this_frame_sample and so having a better
  101935. * estimate.
  101936. */
  101937. }
  101938. /* physical seek */
  101939. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  101940. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101941. return false;
  101942. }
  101943. if(!FLAC__stream_decoder_flush(decoder)) {
  101944. /* above call sets the state for us */
  101945. return false;
  101946. }
  101947. did_a_seek = true;
  101948. }
  101949. else
  101950. did_a_seek = false;
  101951. decoder->private_->got_a_frame = false;
  101952. if(!FLAC__stream_decoder_process_single(decoder)) {
  101953. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101954. return false;
  101955. }
  101956. if(!decoder->private_->got_a_frame) {
  101957. if(did_a_seek) {
  101958. /* this can happen if we seek to a point after the last frame; we drop
  101959. * to binary search right away in this case to avoid any wasted
  101960. * iterations of proportional search.
  101961. */
  101962. right_pos = pos;
  101963. BINARY_SEARCH_AFTER_ITERATION = 0;
  101964. }
  101965. else {
  101966. /* this can probably only happen if total_samples is unknown and the
  101967. * target_sample is past the end of the stream
  101968. */
  101969. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101970. return false;
  101971. }
  101972. }
  101973. /* our write callback will change the state when it gets to the target frame */
  101974. else if(!decoder->private_->is_seeking) {
  101975. break;
  101976. }
  101977. else {
  101978. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  101979. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101980. if (did_a_seek) {
  101981. if (this_frame_sample <= target_sample) {
  101982. /* The 'equal' case should not happen, since
  101983. * FLAC__stream_decoder_process_single()
  101984. * should recognize that it has hit the
  101985. * target sample and we would exit through
  101986. * the 'break' above.
  101987. */
  101988. FLAC__ASSERT(this_frame_sample != target_sample);
  101989. left_sample = this_frame_sample;
  101990. /* sanity check to avoid infinite loop */
  101991. if (left_pos == pos) {
  101992. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  101993. return false;
  101994. }
  101995. left_pos = pos;
  101996. }
  101997. else if(this_frame_sample > target_sample) {
  101998. right_sample = this_frame_sample;
  101999. /* sanity check to avoid infinite loop */
  102000. if (right_pos == pos) {
  102001. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102002. return false;
  102003. }
  102004. right_pos = pos;
  102005. }
  102006. }
  102007. }
  102008. }
  102009. return true;
  102010. }
  102011. #endif
  102012. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  102013. {
  102014. (void)client_data;
  102015. if(*bytes > 0) {
  102016. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  102017. if(ferror(decoder->private_->file))
  102018. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  102019. else if(*bytes == 0)
  102020. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  102021. else
  102022. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  102023. }
  102024. else
  102025. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  102026. }
  102027. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  102028. {
  102029. (void)client_data;
  102030. if(decoder->private_->file == stdin)
  102031. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  102032. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  102033. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  102034. else
  102035. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  102036. }
  102037. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  102038. {
  102039. off_t pos;
  102040. (void)client_data;
  102041. if(decoder->private_->file == stdin)
  102042. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  102043. else if((pos = ftello(decoder->private_->file)) < 0)
  102044. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  102045. else {
  102046. *absolute_byte_offset = (FLAC__uint64)pos;
  102047. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  102048. }
  102049. }
  102050. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  102051. {
  102052. struct stat filestats;
  102053. (void)client_data;
  102054. if(decoder->private_->file == stdin)
  102055. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  102056. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  102057. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  102058. else {
  102059. *stream_length = (FLAC__uint64)filestats.st_size;
  102060. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  102061. }
  102062. }
  102063. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  102064. {
  102065. (void)client_data;
  102066. return feof(decoder->private_->file)? true : false;
  102067. }
  102068. #endif
  102069. /*** End of inlined file: stream_decoder.c ***/
  102070. /*** Start of inlined file: stream_encoder.c ***/
  102071. /*** Start of inlined file: juce_FlacHeader.h ***/
  102072. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  102073. // tasks..
  102074. #define VERSION "1.2.1"
  102075. #define FLAC__NO_DLL 1
  102076. #if JUCE_MSVC
  102077. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  102078. #endif
  102079. #if JUCE_MAC
  102080. #define FLAC__SYS_DARWIN 1
  102081. #endif
  102082. /*** End of inlined file: juce_FlacHeader.h ***/
  102083. #if JUCE_USE_FLAC
  102084. #if HAVE_CONFIG_H
  102085. # include <config.h>
  102086. #endif
  102087. #if defined _MSC_VER || defined __MINGW32__
  102088. #include <io.h> /* for _setmode() */
  102089. #include <fcntl.h> /* for _O_BINARY */
  102090. #endif
  102091. #if defined __CYGWIN__ || defined __EMX__
  102092. #include <io.h> /* for setmode(), O_BINARY */
  102093. #include <fcntl.h> /* for _O_BINARY */
  102094. #endif
  102095. #include <limits.h>
  102096. #include <stdio.h>
  102097. #include <stdlib.h> /* for malloc() */
  102098. #include <string.h> /* for memcpy() */
  102099. #include <sys/types.h> /* for off_t */
  102100. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  102101. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  102102. #define fseeko fseek
  102103. #define ftello ftell
  102104. #endif
  102105. #endif
  102106. /*** Start of inlined file: stream_encoder.h ***/
  102107. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  102108. #define FLAC__PROTECTED__STREAM_ENCODER_H
  102109. #if FLAC__HAS_OGG
  102110. #include "private/ogg_encoder_aspect.h"
  102111. #endif
  102112. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102113. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  102114. typedef enum {
  102115. FLAC__APODIZATION_BARTLETT,
  102116. FLAC__APODIZATION_BARTLETT_HANN,
  102117. FLAC__APODIZATION_BLACKMAN,
  102118. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  102119. FLAC__APODIZATION_CONNES,
  102120. FLAC__APODIZATION_FLATTOP,
  102121. FLAC__APODIZATION_GAUSS,
  102122. FLAC__APODIZATION_HAMMING,
  102123. FLAC__APODIZATION_HANN,
  102124. FLAC__APODIZATION_KAISER_BESSEL,
  102125. FLAC__APODIZATION_NUTTALL,
  102126. FLAC__APODIZATION_RECTANGLE,
  102127. FLAC__APODIZATION_TRIANGLE,
  102128. FLAC__APODIZATION_TUKEY,
  102129. FLAC__APODIZATION_WELCH
  102130. } FLAC__ApodizationFunction;
  102131. typedef struct {
  102132. FLAC__ApodizationFunction type;
  102133. union {
  102134. struct {
  102135. FLAC__real stddev;
  102136. } gauss;
  102137. struct {
  102138. FLAC__real p;
  102139. } tukey;
  102140. } parameters;
  102141. } FLAC__ApodizationSpecification;
  102142. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102143. typedef struct FLAC__StreamEncoderProtected {
  102144. FLAC__StreamEncoderState state;
  102145. FLAC__bool verify;
  102146. FLAC__bool streamable_subset;
  102147. FLAC__bool do_md5;
  102148. FLAC__bool do_mid_side_stereo;
  102149. FLAC__bool loose_mid_side_stereo;
  102150. unsigned channels;
  102151. unsigned bits_per_sample;
  102152. unsigned sample_rate;
  102153. unsigned blocksize;
  102154. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102155. unsigned num_apodizations;
  102156. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  102157. #endif
  102158. unsigned max_lpc_order;
  102159. unsigned qlp_coeff_precision;
  102160. FLAC__bool do_qlp_coeff_prec_search;
  102161. FLAC__bool do_exhaustive_model_search;
  102162. FLAC__bool do_escape_coding;
  102163. unsigned min_residual_partition_order;
  102164. unsigned max_residual_partition_order;
  102165. unsigned rice_parameter_search_dist;
  102166. FLAC__uint64 total_samples_estimate;
  102167. FLAC__StreamMetadata **metadata;
  102168. unsigned num_metadata_blocks;
  102169. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  102170. #if FLAC__HAS_OGG
  102171. FLAC__OggEncoderAspect ogg_encoder_aspect;
  102172. #endif
  102173. } FLAC__StreamEncoderProtected;
  102174. #endif
  102175. /*** End of inlined file: stream_encoder.h ***/
  102176. #if FLAC__HAS_OGG
  102177. #include "include/private/ogg_helper.h"
  102178. #include "include/private/ogg_mapping.h"
  102179. #endif
  102180. /*** Start of inlined file: stream_encoder_framing.h ***/
  102181. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  102182. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  102183. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  102184. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  102185. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102186. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102187. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102188. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102189. #endif
  102190. /*** End of inlined file: stream_encoder_framing.h ***/
  102191. /*** Start of inlined file: window.h ***/
  102192. #ifndef FLAC__PRIVATE__WINDOW_H
  102193. #define FLAC__PRIVATE__WINDOW_H
  102194. #ifdef HAVE_CONFIG_H
  102195. #include <config.h>
  102196. #endif
  102197. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102198. /*
  102199. * FLAC__window_*()
  102200. * --------------------------------------------------------------------
  102201. * Calculates window coefficients according to different apodization
  102202. * functions.
  102203. *
  102204. * OUT window[0,L-1]
  102205. * IN L (number of points in window)
  102206. */
  102207. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  102208. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  102209. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  102210. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  102211. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  102212. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  102213. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  102214. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  102215. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  102216. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  102217. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  102218. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  102219. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  102220. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  102221. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  102222. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  102223. #endif
  102224. /*** End of inlined file: window.h ***/
  102225. #ifndef FLaC__INLINE
  102226. #define FLaC__INLINE
  102227. #endif
  102228. #ifdef min
  102229. #undef min
  102230. #endif
  102231. #define min(x,y) ((x)<(y)?(x):(y))
  102232. #ifdef max
  102233. #undef max
  102234. #endif
  102235. #define max(x,y) ((x)>(y)?(x):(y))
  102236. /* Exact Rice codeword length calculation is off by default. The simple
  102237. * (and fast) estimation (of how many bits a residual value will be
  102238. * encoded with) in this encoder is very good, almost always yielding
  102239. * compression within 0.1% of exact calculation.
  102240. */
  102241. #undef EXACT_RICE_BITS_CALCULATION
  102242. /* Rice parameter searching is off by default. The simple (and fast)
  102243. * parameter estimation in this encoder is very good, almost always
  102244. * yielding compression within 0.1% of the optimal parameters.
  102245. */
  102246. #undef ENABLE_RICE_PARAMETER_SEARCH
  102247. typedef struct {
  102248. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  102249. unsigned size; /* of each data[] in samples */
  102250. unsigned tail;
  102251. } verify_input_fifo;
  102252. typedef struct {
  102253. const FLAC__byte *data;
  102254. unsigned capacity;
  102255. unsigned bytes;
  102256. } verify_output;
  102257. typedef enum {
  102258. ENCODER_IN_MAGIC = 0,
  102259. ENCODER_IN_METADATA = 1,
  102260. ENCODER_IN_AUDIO = 2
  102261. } EncoderStateHint;
  102262. static struct CompressionLevels {
  102263. FLAC__bool do_mid_side_stereo;
  102264. FLAC__bool loose_mid_side_stereo;
  102265. unsigned max_lpc_order;
  102266. unsigned qlp_coeff_precision;
  102267. FLAC__bool do_qlp_coeff_prec_search;
  102268. FLAC__bool do_escape_coding;
  102269. FLAC__bool do_exhaustive_model_search;
  102270. unsigned min_residual_partition_order;
  102271. unsigned max_residual_partition_order;
  102272. unsigned rice_parameter_search_dist;
  102273. } compression_levels_[] = {
  102274. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  102275. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  102276. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  102277. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  102278. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  102279. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  102280. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  102281. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  102282. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  102283. };
  102284. /***********************************************************************
  102285. *
  102286. * Private class method prototypes
  102287. *
  102288. ***********************************************************************/
  102289. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  102290. static void free_(FLAC__StreamEncoder *encoder);
  102291. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  102292. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  102293. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  102294. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  102295. #if FLAC__HAS_OGG
  102296. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  102297. #endif
  102298. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  102299. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  102300. static FLAC__bool process_subframe_(
  102301. FLAC__StreamEncoder *encoder,
  102302. unsigned min_partition_order,
  102303. unsigned max_partition_order,
  102304. const FLAC__FrameHeader *frame_header,
  102305. unsigned subframe_bps,
  102306. const FLAC__int32 integer_signal[],
  102307. FLAC__Subframe *subframe[2],
  102308. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  102309. FLAC__int32 *residual[2],
  102310. unsigned *best_subframe,
  102311. unsigned *best_bits
  102312. );
  102313. static FLAC__bool add_subframe_(
  102314. FLAC__StreamEncoder *encoder,
  102315. unsigned blocksize,
  102316. unsigned subframe_bps,
  102317. const FLAC__Subframe *subframe,
  102318. FLAC__BitWriter *frame
  102319. );
  102320. static unsigned evaluate_constant_subframe_(
  102321. FLAC__StreamEncoder *encoder,
  102322. const FLAC__int32 signal,
  102323. unsigned blocksize,
  102324. unsigned subframe_bps,
  102325. FLAC__Subframe *subframe
  102326. );
  102327. static unsigned evaluate_fixed_subframe_(
  102328. FLAC__StreamEncoder *encoder,
  102329. const FLAC__int32 signal[],
  102330. FLAC__int32 residual[],
  102331. FLAC__uint64 abs_residual_partition_sums[],
  102332. unsigned raw_bits_per_partition[],
  102333. unsigned blocksize,
  102334. unsigned subframe_bps,
  102335. unsigned order,
  102336. unsigned rice_parameter,
  102337. unsigned rice_parameter_limit,
  102338. unsigned min_partition_order,
  102339. unsigned max_partition_order,
  102340. FLAC__bool do_escape_coding,
  102341. unsigned rice_parameter_search_dist,
  102342. FLAC__Subframe *subframe,
  102343. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102344. );
  102345. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102346. static unsigned evaluate_lpc_subframe_(
  102347. FLAC__StreamEncoder *encoder,
  102348. const FLAC__int32 signal[],
  102349. FLAC__int32 residual[],
  102350. FLAC__uint64 abs_residual_partition_sums[],
  102351. unsigned raw_bits_per_partition[],
  102352. const FLAC__real lp_coeff[],
  102353. unsigned blocksize,
  102354. unsigned subframe_bps,
  102355. unsigned order,
  102356. unsigned qlp_coeff_precision,
  102357. unsigned rice_parameter,
  102358. unsigned rice_parameter_limit,
  102359. unsigned min_partition_order,
  102360. unsigned max_partition_order,
  102361. FLAC__bool do_escape_coding,
  102362. unsigned rice_parameter_search_dist,
  102363. FLAC__Subframe *subframe,
  102364. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102365. );
  102366. #endif
  102367. static unsigned evaluate_verbatim_subframe_(
  102368. FLAC__StreamEncoder *encoder,
  102369. const FLAC__int32 signal[],
  102370. unsigned blocksize,
  102371. unsigned subframe_bps,
  102372. FLAC__Subframe *subframe
  102373. );
  102374. static unsigned find_best_partition_order_(
  102375. struct FLAC__StreamEncoderPrivate *private_,
  102376. const FLAC__int32 residual[],
  102377. FLAC__uint64 abs_residual_partition_sums[],
  102378. unsigned raw_bits_per_partition[],
  102379. unsigned residual_samples,
  102380. unsigned predictor_order,
  102381. unsigned rice_parameter,
  102382. unsigned rice_parameter_limit,
  102383. unsigned min_partition_order,
  102384. unsigned max_partition_order,
  102385. unsigned bps,
  102386. FLAC__bool do_escape_coding,
  102387. unsigned rice_parameter_search_dist,
  102388. FLAC__EntropyCodingMethod *best_ecm
  102389. );
  102390. static void precompute_partition_info_sums_(
  102391. const FLAC__int32 residual[],
  102392. FLAC__uint64 abs_residual_partition_sums[],
  102393. unsigned residual_samples,
  102394. unsigned predictor_order,
  102395. unsigned min_partition_order,
  102396. unsigned max_partition_order,
  102397. unsigned bps
  102398. );
  102399. static void precompute_partition_info_escapes_(
  102400. const FLAC__int32 residual[],
  102401. unsigned raw_bits_per_partition[],
  102402. unsigned residual_samples,
  102403. unsigned predictor_order,
  102404. unsigned min_partition_order,
  102405. unsigned max_partition_order
  102406. );
  102407. static FLAC__bool set_partitioned_rice_(
  102408. #ifdef EXACT_RICE_BITS_CALCULATION
  102409. const FLAC__int32 residual[],
  102410. #endif
  102411. const FLAC__uint64 abs_residual_partition_sums[],
  102412. const unsigned raw_bits_per_partition[],
  102413. const unsigned residual_samples,
  102414. const unsigned predictor_order,
  102415. const unsigned suggested_rice_parameter,
  102416. const unsigned rice_parameter_limit,
  102417. const unsigned rice_parameter_search_dist,
  102418. const unsigned partition_order,
  102419. const FLAC__bool search_for_escapes,
  102420. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  102421. unsigned *bits
  102422. );
  102423. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  102424. /* verify-related routines: */
  102425. static void append_to_verify_fifo_(
  102426. verify_input_fifo *fifo,
  102427. const FLAC__int32 * const input[],
  102428. unsigned input_offset,
  102429. unsigned channels,
  102430. unsigned wide_samples
  102431. );
  102432. static void append_to_verify_fifo_interleaved_(
  102433. verify_input_fifo *fifo,
  102434. const FLAC__int32 input[],
  102435. unsigned input_offset,
  102436. unsigned channels,
  102437. unsigned wide_samples
  102438. );
  102439. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102440. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  102441. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  102442. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  102443. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102444. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  102445. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  102446. 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);
  102447. static FILE *get_binary_stdout_(void);
  102448. /***********************************************************************
  102449. *
  102450. * Private class data
  102451. *
  102452. ***********************************************************************/
  102453. typedef struct FLAC__StreamEncoderPrivate {
  102454. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  102455. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  102456. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  102457. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102458. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  102459. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  102460. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  102461. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  102462. #endif
  102463. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  102464. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  102465. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  102466. FLAC__int32 *residual_workspace_mid_side[2][2];
  102467. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  102468. FLAC__Subframe subframe_workspace_mid_side[2][2];
  102469. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102470. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  102471. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  102472. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  102473. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102474. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  102475. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  102476. unsigned best_subframe_mid_side[2];
  102477. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  102478. unsigned best_subframe_bits_mid_side[2];
  102479. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  102480. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  102481. FLAC__BitWriter *frame; /* the current frame being worked on */
  102482. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  102483. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  102484. FLAC__ChannelAssignment last_channel_assignment;
  102485. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  102486. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  102487. unsigned current_sample_number;
  102488. unsigned current_frame_number;
  102489. FLAC__MD5Context md5context;
  102490. FLAC__CPUInfo cpuinfo;
  102491. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102492. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102493. #else
  102494. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102495. #endif
  102496. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102497. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  102498. 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[]);
  102499. 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[]);
  102500. 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[]);
  102501. #endif
  102502. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  102503. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  102504. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  102505. FLAC__bool disable_constant_subframes;
  102506. FLAC__bool disable_fixed_subframes;
  102507. FLAC__bool disable_verbatim_subframes;
  102508. #if FLAC__HAS_OGG
  102509. FLAC__bool is_ogg;
  102510. #endif
  102511. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  102512. FLAC__StreamEncoderSeekCallback seek_callback;
  102513. FLAC__StreamEncoderTellCallback tell_callback;
  102514. FLAC__StreamEncoderWriteCallback write_callback;
  102515. FLAC__StreamEncoderMetadataCallback metadata_callback;
  102516. FLAC__StreamEncoderProgressCallback progress_callback;
  102517. void *client_data;
  102518. unsigned first_seekpoint_to_check;
  102519. FILE *file; /* only used when encoding to a file */
  102520. FLAC__uint64 bytes_written;
  102521. FLAC__uint64 samples_written;
  102522. unsigned frames_written;
  102523. unsigned total_frames_estimate;
  102524. /* unaligned (original) pointers to allocated data */
  102525. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  102526. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  102527. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102528. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  102529. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  102530. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  102531. FLAC__real *windowed_signal_unaligned;
  102532. #endif
  102533. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  102534. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  102535. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  102536. unsigned *raw_bits_per_partition_unaligned;
  102537. /*
  102538. * These fields have been moved here from private function local
  102539. * declarations merely to save stack space during encoding.
  102540. */
  102541. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102542. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  102543. #endif
  102544. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  102545. /*
  102546. * The data for the verify section
  102547. */
  102548. struct {
  102549. FLAC__StreamDecoder *decoder;
  102550. EncoderStateHint state_hint;
  102551. FLAC__bool needs_magic_hack;
  102552. verify_input_fifo input_fifo;
  102553. verify_output output;
  102554. struct {
  102555. FLAC__uint64 absolute_sample;
  102556. unsigned frame_number;
  102557. unsigned channel;
  102558. unsigned sample;
  102559. FLAC__int32 expected;
  102560. FLAC__int32 got;
  102561. } error_stats;
  102562. } verify;
  102563. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  102564. } FLAC__StreamEncoderPrivate;
  102565. /***********************************************************************
  102566. *
  102567. * Public static class data
  102568. *
  102569. ***********************************************************************/
  102570. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  102571. "FLAC__STREAM_ENCODER_OK",
  102572. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  102573. "FLAC__STREAM_ENCODER_OGG_ERROR",
  102574. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  102575. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  102576. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  102577. "FLAC__STREAM_ENCODER_IO_ERROR",
  102578. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  102579. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  102580. };
  102581. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  102582. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  102583. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  102584. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  102585. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  102586. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  102587. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  102588. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  102589. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  102590. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  102591. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  102592. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  102593. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  102594. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  102595. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  102596. };
  102597. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  102598. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  102599. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  102600. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  102601. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  102602. };
  102603. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  102604. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  102605. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  102606. };
  102607. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  102608. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  102609. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  102610. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  102611. };
  102612. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  102613. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  102614. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  102615. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  102616. };
  102617. /* Number of samples that will be overread to watch for end of stream. By
  102618. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  102619. * always try to read blocksize+1 samples before encoding a block, so that
  102620. * even if the stream has a total sample count that is an integral multiple
  102621. * of the blocksize, we will still notice when we are encoding the last
  102622. * block. This is needed, for example, to correctly set the end-of-stream
  102623. * marker in Ogg FLAC.
  102624. *
  102625. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  102626. * not really any reason to change it.
  102627. */
  102628. static const unsigned OVERREAD_ = 1;
  102629. /***********************************************************************
  102630. *
  102631. * Class constructor/destructor
  102632. *
  102633. */
  102634. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  102635. {
  102636. FLAC__StreamEncoder *encoder;
  102637. unsigned i;
  102638. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  102639. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  102640. if(encoder == 0) {
  102641. return 0;
  102642. }
  102643. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  102644. if(encoder->protected_ == 0) {
  102645. free(encoder);
  102646. return 0;
  102647. }
  102648. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  102649. if(encoder->private_ == 0) {
  102650. free(encoder->protected_);
  102651. free(encoder);
  102652. return 0;
  102653. }
  102654. encoder->private_->frame = FLAC__bitwriter_new();
  102655. if(encoder->private_->frame == 0) {
  102656. free(encoder->private_);
  102657. free(encoder->protected_);
  102658. free(encoder);
  102659. return 0;
  102660. }
  102661. encoder->private_->file = 0;
  102662. set_defaults_enc(encoder);
  102663. encoder->private_->is_being_deleted = false;
  102664. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102665. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  102666. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  102667. }
  102668. for(i = 0; i < 2; i++) {
  102669. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  102670. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  102671. }
  102672. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102673. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  102674. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  102675. }
  102676. for(i = 0; i < 2; i++) {
  102677. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  102678. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  102679. }
  102680. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102681. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102682. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102683. }
  102684. for(i = 0; i < 2; i++) {
  102685. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102686. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102687. }
  102688. for(i = 0; i < 2; i++)
  102689. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  102690. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  102691. return encoder;
  102692. }
  102693. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  102694. {
  102695. unsigned i;
  102696. FLAC__ASSERT(0 != encoder);
  102697. FLAC__ASSERT(0 != encoder->protected_);
  102698. FLAC__ASSERT(0 != encoder->private_);
  102699. FLAC__ASSERT(0 != encoder->private_->frame);
  102700. encoder->private_->is_being_deleted = true;
  102701. (void)FLAC__stream_encoder_finish(encoder);
  102702. if(0 != encoder->private_->verify.decoder)
  102703. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  102704. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102705. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102706. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102707. }
  102708. for(i = 0; i < 2; i++) {
  102709. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102710. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102711. }
  102712. for(i = 0; i < 2; i++)
  102713. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  102714. FLAC__bitwriter_delete(encoder->private_->frame);
  102715. free(encoder->private_);
  102716. free(encoder->protected_);
  102717. free(encoder);
  102718. }
  102719. /***********************************************************************
  102720. *
  102721. * Public class methods
  102722. *
  102723. ***********************************************************************/
  102724. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  102725. FLAC__StreamEncoder *encoder,
  102726. FLAC__StreamEncoderReadCallback read_callback,
  102727. FLAC__StreamEncoderWriteCallback write_callback,
  102728. FLAC__StreamEncoderSeekCallback seek_callback,
  102729. FLAC__StreamEncoderTellCallback tell_callback,
  102730. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102731. void *client_data,
  102732. FLAC__bool is_ogg
  102733. )
  102734. {
  102735. unsigned i;
  102736. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  102737. FLAC__ASSERT(0 != encoder);
  102738. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102739. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102740. #if !FLAC__HAS_OGG
  102741. if(is_ogg)
  102742. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  102743. #endif
  102744. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  102745. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  102746. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  102747. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  102748. if(encoder->protected_->channels != 2) {
  102749. encoder->protected_->do_mid_side_stereo = false;
  102750. encoder->protected_->loose_mid_side_stereo = false;
  102751. }
  102752. else if(!encoder->protected_->do_mid_side_stereo)
  102753. encoder->protected_->loose_mid_side_stereo = false;
  102754. if(encoder->protected_->bits_per_sample >= 32)
  102755. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  102756. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  102757. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  102758. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  102759. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  102760. if(encoder->protected_->blocksize == 0) {
  102761. if(encoder->protected_->max_lpc_order == 0)
  102762. encoder->protected_->blocksize = 1152;
  102763. else
  102764. encoder->protected_->blocksize = 4096;
  102765. }
  102766. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  102767. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  102768. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  102769. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  102770. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  102771. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  102772. if(encoder->protected_->qlp_coeff_precision == 0) {
  102773. if(encoder->protected_->bits_per_sample < 16) {
  102774. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  102775. /* @@@ until then we'll make a guess */
  102776. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  102777. }
  102778. else if(encoder->protected_->bits_per_sample == 16) {
  102779. if(encoder->protected_->blocksize <= 192)
  102780. encoder->protected_->qlp_coeff_precision = 7;
  102781. else if(encoder->protected_->blocksize <= 384)
  102782. encoder->protected_->qlp_coeff_precision = 8;
  102783. else if(encoder->protected_->blocksize <= 576)
  102784. encoder->protected_->qlp_coeff_precision = 9;
  102785. else if(encoder->protected_->blocksize <= 1152)
  102786. encoder->protected_->qlp_coeff_precision = 10;
  102787. else if(encoder->protected_->blocksize <= 2304)
  102788. encoder->protected_->qlp_coeff_precision = 11;
  102789. else if(encoder->protected_->blocksize <= 4608)
  102790. encoder->protected_->qlp_coeff_precision = 12;
  102791. else
  102792. encoder->protected_->qlp_coeff_precision = 13;
  102793. }
  102794. else {
  102795. if(encoder->protected_->blocksize <= 384)
  102796. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  102797. else if(encoder->protected_->blocksize <= 1152)
  102798. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  102799. else
  102800. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  102801. }
  102802. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  102803. }
  102804. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  102805. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  102806. if(encoder->protected_->streamable_subset) {
  102807. if(
  102808. encoder->protected_->blocksize != 192 &&
  102809. encoder->protected_->blocksize != 576 &&
  102810. encoder->protected_->blocksize != 1152 &&
  102811. encoder->protected_->blocksize != 2304 &&
  102812. encoder->protected_->blocksize != 4608 &&
  102813. encoder->protected_->blocksize != 256 &&
  102814. encoder->protected_->blocksize != 512 &&
  102815. encoder->protected_->blocksize != 1024 &&
  102816. encoder->protected_->blocksize != 2048 &&
  102817. encoder->protected_->blocksize != 4096 &&
  102818. encoder->protected_->blocksize != 8192 &&
  102819. encoder->protected_->blocksize != 16384
  102820. )
  102821. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102822. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  102823. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102824. if(
  102825. encoder->protected_->bits_per_sample != 8 &&
  102826. encoder->protected_->bits_per_sample != 12 &&
  102827. encoder->protected_->bits_per_sample != 16 &&
  102828. encoder->protected_->bits_per_sample != 20 &&
  102829. encoder->protected_->bits_per_sample != 24
  102830. )
  102831. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102832. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  102833. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102834. if(
  102835. encoder->protected_->sample_rate <= 48000 &&
  102836. (
  102837. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  102838. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  102839. )
  102840. ) {
  102841. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  102842. }
  102843. }
  102844. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  102845. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  102846. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  102847. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  102848. #if FLAC__HAS_OGG
  102849. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  102850. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  102851. unsigned i;
  102852. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  102853. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102854. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  102855. for( ; i > 0; i--)
  102856. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  102857. encoder->protected_->metadata[0] = vc;
  102858. break;
  102859. }
  102860. }
  102861. }
  102862. #endif
  102863. /* keep track of any SEEKTABLE block */
  102864. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  102865. unsigned i;
  102866. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102867. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  102868. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  102869. break; /* take only the first one */
  102870. }
  102871. }
  102872. }
  102873. /* validate metadata */
  102874. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  102875. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102876. metadata_has_seektable = false;
  102877. metadata_has_vorbis_comment = false;
  102878. metadata_picture_has_type1 = false;
  102879. metadata_picture_has_type2 = false;
  102880. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  102881. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  102882. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  102883. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102884. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  102885. if(metadata_has_seektable) /* only one is allowed */
  102886. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102887. metadata_has_seektable = true;
  102888. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  102889. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102890. }
  102891. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102892. if(metadata_has_vorbis_comment) /* only one is allowed */
  102893. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102894. metadata_has_vorbis_comment = true;
  102895. }
  102896. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  102897. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  102898. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102899. }
  102900. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  102901. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  102902. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102903. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  102904. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  102905. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102906. metadata_picture_has_type1 = true;
  102907. /* standard icon must be 32x32 pixel PNG */
  102908. if(
  102909. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  102910. (
  102911. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  102912. m->data.picture.width != 32 ||
  102913. m->data.picture.height != 32
  102914. )
  102915. )
  102916. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102917. }
  102918. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  102919. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  102920. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  102921. metadata_picture_has_type2 = true;
  102922. }
  102923. }
  102924. }
  102925. encoder->private_->input_capacity = 0;
  102926. for(i = 0; i < encoder->protected_->channels; i++) {
  102927. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  102928. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102929. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  102930. #endif
  102931. }
  102932. for(i = 0; i < 2; i++) {
  102933. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  102934. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102935. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  102936. #endif
  102937. }
  102938. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102939. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  102940. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  102941. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  102942. #endif
  102943. for(i = 0; i < encoder->protected_->channels; i++) {
  102944. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  102945. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  102946. encoder->private_->best_subframe[i] = 0;
  102947. }
  102948. for(i = 0; i < 2; i++) {
  102949. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  102950. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  102951. encoder->private_->best_subframe_mid_side[i] = 0;
  102952. }
  102953. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  102954. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  102955. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102956. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  102957. #else
  102958. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  102959. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  102960. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  102961. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  102962. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  102963. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  102964. 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);
  102965. #endif
  102966. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  102967. encoder->private_->loose_mid_side_stereo_frames = 1;
  102968. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  102969. encoder->private_->current_sample_number = 0;
  102970. encoder->private_->current_frame_number = 0;
  102971. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  102972. 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? */
  102973. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  102974. /*
  102975. * get the CPU info and set the function pointers
  102976. */
  102977. FLAC__cpu_info(&encoder->private_->cpuinfo);
  102978. /* first default to the non-asm routines */
  102979. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102980. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  102981. #endif
  102982. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  102983. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102984. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  102985. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  102986. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  102987. #endif
  102988. /* now override with asm where appropriate */
  102989. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102990. # ifndef FLAC__NO_ASM
  102991. if(encoder->private_->cpuinfo.use_asm) {
  102992. # ifdef FLAC__CPU_IA32
  102993. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  102994. # ifdef FLAC__HAS_NASM
  102995. if(encoder->private_->cpuinfo.data.ia32.sse) {
  102996. if(encoder->protected_->max_lpc_order < 4)
  102997. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  102998. else if(encoder->protected_->max_lpc_order < 8)
  102999. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  103000. else if(encoder->protected_->max_lpc_order < 12)
  103001. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  103002. else
  103003. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  103004. }
  103005. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  103006. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  103007. else
  103008. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  103009. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  103010. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  103011. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  103012. }
  103013. else {
  103014. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  103015. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  103016. }
  103017. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  103018. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  103019. # endif /* FLAC__HAS_NASM */
  103020. # endif /* FLAC__CPU_IA32 */
  103021. }
  103022. # endif /* !FLAC__NO_ASM */
  103023. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  103024. /* finally override based on wide-ness if necessary */
  103025. if(encoder->private_->use_wide_by_block) {
  103026. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  103027. }
  103028. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  103029. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  103030. #if FLAC__HAS_OGG
  103031. encoder->private_->is_ogg = is_ogg;
  103032. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  103033. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  103034. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103035. }
  103036. #endif
  103037. encoder->private_->read_callback = read_callback;
  103038. encoder->private_->write_callback = write_callback;
  103039. encoder->private_->seek_callback = seek_callback;
  103040. encoder->private_->tell_callback = tell_callback;
  103041. encoder->private_->metadata_callback = metadata_callback;
  103042. encoder->private_->client_data = client_data;
  103043. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  103044. /* the above function sets the state for us in case of an error */
  103045. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103046. }
  103047. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  103048. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103049. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103050. }
  103051. /*
  103052. * Set up the verify stuff if necessary
  103053. */
  103054. if(encoder->protected_->verify) {
  103055. /*
  103056. * First, set up the fifo which will hold the
  103057. * original signal to compare against
  103058. */
  103059. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  103060. for(i = 0; i < encoder->protected_->channels; i++) {
  103061. 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))) {
  103062. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103063. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103064. }
  103065. }
  103066. encoder->private_->verify.input_fifo.tail = 0;
  103067. /*
  103068. * Now set up a stream decoder for verification
  103069. */
  103070. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  103071. if(0 == encoder->private_->verify.decoder) {
  103072. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  103073. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103074. }
  103075. 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) {
  103076. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  103077. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103078. }
  103079. }
  103080. encoder->private_->verify.error_stats.absolute_sample = 0;
  103081. encoder->private_->verify.error_stats.frame_number = 0;
  103082. encoder->private_->verify.error_stats.channel = 0;
  103083. encoder->private_->verify.error_stats.sample = 0;
  103084. encoder->private_->verify.error_stats.expected = 0;
  103085. encoder->private_->verify.error_stats.got = 0;
  103086. /*
  103087. * These must be done before we write any metadata, because that
  103088. * calls the write_callback, which uses these values.
  103089. */
  103090. encoder->private_->first_seekpoint_to_check = 0;
  103091. encoder->private_->samples_written = 0;
  103092. encoder->protected_->streaminfo_offset = 0;
  103093. encoder->protected_->seektable_offset = 0;
  103094. encoder->protected_->audio_offset = 0;
  103095. /*
  103096. * write the stream header
  103097. */
  103098. if(encoder->protected_->verify)
  103099. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  103100. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  103101. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103102. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103103. }
  103104. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103105. /* the above function sets the state for us in case of an error */
  103106. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103107. }
  103108. /*
  103109. * write the STREAMINFO metadata block
  103110. */
  103111. if(encoder->protected_->verify)
  103112. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  103113. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  103114. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  103115. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  103116. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  103117. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  103118. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  103119. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  103120. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  103121. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  103122. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  103123. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  103124. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  103125. if(encoder->protected_->do_md5)
  103126. FLAC__MD5Init(&encoder->private_->md5context);
  103127. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  103128. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103129. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103130. }
  103131. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103132. /* the above function sets the state for us in case of an error */
  103133. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103134. }
  103135. /*
  103136. * Now that the STREAMINFO block is written, we can init this to an
  103137. * absurdly-high value...
  103138. */
  103139. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  103140. /* ... and clear this to 0 */
  103141. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  103142. /*
  103143. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  103144. * if not, we will write an empty one (FLAC__add_metadata_block()
  103145. * automatically supplies the vendor string).
  103146. *
  103147. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  103148. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  103149. * true it will have already insured that the metadata list is properly
  103150. * ordered.)
  103151. */
  103152. if(!metadata_has_vorbis_comment) {
  103153. FLAC__StreamMetadata vorbis_comment;
  103154. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  103155. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  103156. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  103157. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  103158. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  103159. vorbis_comment.data.vorbis_comment.num_comments = 0;
  103160. vorbis_comment.data.vorbis_comment.comments = 0;
  103161. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  103162. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103163. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103164. }
  103165. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103166. /* the above function sets the state for us in case of an error */
  103167. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103168. }
  103169. }
  103170. /*
  103171. * write the user's metadata blocks
  103172. */
  103173. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  103174. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  103175. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  103176. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103177. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103178. }
  103179. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103180. /* the above function sets the state for us in case of an error */
  103181. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103182. }
  103183. }
  103184. /* now that all the metadata is written, we save the stream offset */
  103185. 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 */
  103186. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103187. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103188. }
  103189. if(encoder->protected_->verify)
  103190. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  103191. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  103192. }
  103193. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  103194. FLAC__StreamEncoder *encoder,
  103195. FLAC__StreamEncoderWriteCallback write_callback,
  103196. FLAC__StreamEncoderSeekCallback seek_callback,
  103197. FLAC__StreamEncoderTellCallback tell_callback,
  103198. FLAC__StreamEncoderMetadataCallback metadata_callback,
  103199. void *client_data
  103200. )
  103201. {
  103202. return init_stream_internal_enc(
  103203. encoder,
  103204. /*read_callback=*/0,
  103205. write_callback,
  103206. seek_callback,
  103207. tell_callback,
  103208. metadata_callback,
  103209. client_data,
  103210. /*is_ogg=*/false
  103211. );
  103212. }
  103213. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  103214. FLAC__StreamEncoder *encoder,
  103215. FLAC__StreamEncoderReadCallback read_callback,
  103216. FLAC__StreamEncoderWriteCallback write_callback,
  103217. FLAC__StreamEncoderSeekCallback seek_callback,
  103218. FLAC__StreamEncoderTellCallback tell_callback,
  103219. FLAC__StreamEncoderMetadataCallback metadata_callback,
  103220. void *client_data
  103221. )
  103222. {
  103223. return init_stream_internal_enc(
  103224. encoder,
  103225. read_callback,
  103226. write_callback,
  103227. seek_callback,
  103228. tell_callback,
  103229. metadata_callback,
  103230. client_data,
  103231. /*is_ogg=*/true
  103232. );
  103233. }
  103234. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  103235. FLAC__StreamEncoder *encoder,
  103236. FILE *file,
  103237. FLAC__StreamEncoderProgressCallback progress_callback,
  103238. void *client_data,
  103239. FLAC__bool is_ogg
  103240. )
  103241. {
  103242. FLAC__StreamEncoderInitStatus init_status;
  103243. FLAC__ASSERT(0 != encoder);
  103244. FLAC__ASSERT(0 != file);
  103245. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103246. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  103247. /* double protection */
  103248. if(file == 0) {
  103249. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  103250. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103251. }
  103252. /*
  103253. * To make sure that our file does not go unclosed after an error, we
  103254. * must assign the FILE pointer before any further error can occur in
  103255. * this routine.
  103256. */
  103257. if(file == stdout)
  103258. file = get_binary_stdout_(); /* just to be safe */
  103259. encoder->private_->file = file;
  103260. encoder->private_->progress_callback = progress_callback;
  103261. encoder->private_->bytes_written = 0;
  103262. encoder->private_->samples_written = 0;
  103263. encoder->private_->frames_written = 0;
  103264. init_status = init_stream_internal_enc(
  103265. encoder,
  103266. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  103267. file_write_callback_,
  103268. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  103269. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  103270. /*metadata_callback=*/0,
  103271. client_data,
  103272. is_ogg
  103273. );
  103274. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  103275. /* the above function sets the state for us in case of an error */
  103276. return init_status;
  103277. }
  103278. {
  103279. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  103280. FLAC__ASSERT(blocksize != 0);
  103281. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  103282. }
  103283. return init_status;
  103284. }
  103285. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  103286. FLAC__StreamEncoder *encoder,
  103287. FILE *file,
  103288. FLAC__StreamEncoderProgressCallback progress_callback,
  103289. void *client_data
  103290. )
  103291. {
  103292. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  103293. }
  103294. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  103295. FLAC__StreamEncoder *encoder,
  103296. FILE *file,
  103297. FLAC__StreamEncoderProgressCallback progress_callback,
  103298. void *client_data
  103299. )
  103300. {
  103301. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  103302. }
  103303. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  103304. FLAC__StreamEncoder *encoder,
  103305. const char *filename,
  103306. FLAC__StreamEncoderProgressCallback progress_callback,
  103307. void *client_data,
  103308. FLAC__bool is_ogg
  103309. )
  103310. {
  103311. FILE *file;
  103312. FLAC__ASSERT(0 != encoder);
  103313. /*
  103314. * To make sure that our file does not go unclosed after an error, we
  103315. * have to do the same entrance checks here that are later performed
  103316. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  103317. */
  103318. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103319. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  103320. file = filename? fopen(filename, "w+b") : stdout;
  103321. if(file == 0) {
  103322. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  103323. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103324. }
  103325. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  103326. }
  103327. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  103328. FLAC__StreamEncoder *encoder,
  103329. const char *filename,
  103330. FLAC__StreamEncoderProgressCallback progress_callback,
  103331. void *client_data
  103332. )
  103333. {
  103334. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  103335. }
  103336. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  103337. FLAC__StreamEncoder *encoder,
  103338. const char *filename,
  103339. FLAC__StreamEncoderProgressCallback progress_callback,
  103340. void *client_data
  103341. )
  103342. {
  103343. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  103344. }
  103345. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  103346. {
  103347. FLAC__bool error = false;
  103348. FLAC__ASSERT(0 != encoder);
  103349. FLAC__ASSERT(0 != encoder->private_);
  103350. FLAC__ASSERT(0 != encoder->protected_);
  103351. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  103352. return true;
  103353. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  103354. if(encoder->private_->current_sample_number != 0) {
  103355. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  103356. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  103357. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  103358. error = true;
  103359. }
  103360. }
  103361. if(encoder->protected_->do_md5)
  103362. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  103363. if(!encoder->private_->is_being_deleted) {
  103364. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  103365. if(encoder->private_->seek_callback) {
  103366. #if FLAC__HAS_OGG
  103367. if(encoder->private_->is_ogg)
  103368. update_ogg_metadata_(encoder);
  103369. else
  103370. #endif
  103371. update_metadata_(encoder);
  103372. /* check if an error occurred while updating metadata */
  103373. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  103374. error = true;
  103375. }
  103376. if(encoder->private_->metadata_callback)
  103377. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  103378. }
  103379. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  103380. if(!error)
  103381. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  103382. error = true;
  103383. }
  103384. }
  103385. if(0 != encoder->private_->file) {
  103386. if(encoder->private_->file != stdout)
  103387. fclose(encoder->private_->file);
  103388. encoder->private_->file = 0;
  103389. }
  103390. #if FLAC__HAS_OGG
  103391. if(encoder->private_->is_ogg)
  103392. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  103393. #endif
  103394. free_(encoder);
  103395. set_defaults_enc(encoder);
  103396. if(!error)
  103397. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  103398. return !error;
  103399. }
  103400. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  103401. {
  103402. FLAC__ASSERT(0 != encoder);
  103403. FLAC__ASSERT(0 != encoder->private_);
  103404. FLAC__ASSERT(0 != encoder->protected_);
  103405. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103406. return false;
  103407. #if FLAC__HAS_OGG
  103408. /* can't check encoder->private_->is_ogg since that's not set until init time */
  103409. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  103410. return true;
  103411. #else
  103412. (void)value;
  103413. return false;
  103414. #endif
  103415. }
  103416. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103417. {
  103418. FLAC__ASSERT(0 != encoder);
  103419. FLAC__ASSERT(0 != encoder->private_);
  103420. FLAC__ASSERT(0 != encoder->protected_);
  103421. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103422. return false;
  103423. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  103424. encoder->protected_->verify = value;
  103425. #endif
  103426. return true;
  103427. }
  103428. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103429. {
  103430. FLAC__ASSERT(0 != encoder);
  103431. FLAC__ASSERT(0 != encoder->private_);
  103432. FLAC__ASSERT(0 != encoder->protected_);
  103433. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103434. return false;
  103435. encoder->protected_->streamable_subset = value;
  103436. return true;
  103437. }
  103438. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103439. {
  103440. FLAC__ASSERT(0 != encoder);
  103441. FLAC__ASSERT(0 != encoder->private_);
  103442. FLAC__ASSERT(0 != encoder->protected_);
  103443. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103444. return false;
  103445. encoder->protected_->do_md5 = value;
  103446. return true;
  103447. }
  103448. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  103449. {
  103450. FLAC__ASSERT(0 != encoder);
  103451. FLAC__ASSERT(0 != encoder->private_);
  103452. FLAC__ASSERT(0 != encoder->protected_);
  103453. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103454. return false;
  103455. encoder->protected_->channels = value;
  103456. return true;
  103457. }
  103458. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  103459. {
  103460. FLAC__ASSERT(0 != encoder);
  103461. FLAC__ASSERT(0 != encoder->private_);
  103462. FLAC__ASSERT(0 != encoder->protected_);
  103463. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103464. return false;
  103465. encoder->protected_->bits_per_sample = value;
  103466. return true;
  103467. }
  103468. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  103469. {
  103470. FLAC__ASSERT(0 != encoder);
  103471. FLAC__ASSERT(0 != encoder->private_);
  103472. FLAC__ASSERT(0 != encoder->protected_);
  103473. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103474. return false;
  103475. encoder->protected_->sample_rate = value;
  103476. return true;
  103477. }
  103478. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  103479. {
  103480. FLAC__bool ok = true;
  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. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  103487. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  103488. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  103489. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  103490. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103491. #if 0
  103492. /* was: */
  103493. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  103494. /* but it's too hard to specify the string in a locale-specific way */
  103495. #else
  103496. encoder->protected_->num_apodizations = 1;
  103497. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103498. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103499. #endif
  103500. #endif
  103501. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  103502. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  103503. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  103504. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  103505. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  103506. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  103507. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  103508. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  103509. return ok;
  103510. }
  103511. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  103512. {
  103513. FLAC__ASSERT(0 != encoder);
  103514. FLAC__ASSERT(0 != encoder->private_);
  103515. FLAC__ASSERT(0 != encoder->protected_);
  103516. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103517. return false;
  103518. encoder->protected_->blocksize = value;
  103519. return true;
  103520. }
  103521. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103522. {
  103523. FLAC__ASSERT(0 != encoder);
  103524. FLAC__ASSERT(0 != encoder->private_);
  103525. FLAC__ASSERT(0 != encoder->protected_);
  103526. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103527. return false;
  103528. encoder->protected_->do_mid_side_stereo = value;
  103529. return true;
  103530. }
  103531. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103532. {
  103533. FLAC__ASSERT(0 != encoder);
  103534. FLAC__ASSERT(0 != encoder->private_);
  103535. FLAC__ASSERT(0 != encoder->protected_);
  103536. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103537. return false;
  103538. encoder->protected_->loose_mid_side_stereo = value;
  103539. return true;
  103540. }
  103541. /*@@@@add to tests*/
  103542. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  103543. {
  103544. FLAC__ASSERT(0 != encoder);
  103545. FLAC__ASSERT(0 != encoder->private_);
  103546. FLAC__ASSERT(0 != encoder->protected_);
  103547. FLAC__ASSERT(0 != specification);
  103548. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103549. return false;
  103550. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  103551. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  103552. #else
  103553. encoder->protected_->num_apodizations = 0;
  103554. while(1) {
  103555. const char *s = strchr(specification, ';');
  103556. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  103557. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  103558. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  103559. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  103560. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  103561. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  103562. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  103563. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  103564. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  103565. else if(n==6 && 0 == strncmp("connes" , specification, n))
  103566. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  103567. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  103568. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  103569. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  103570. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  103571. if (stddev > 0.0 && stddev <= 0.5) {
  103572. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  103573. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  103574. }
  103575. }
  103576. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  103577. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  103578. else if(n==4 && 0 == strncmp("hann" , specification, n))
  103579. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  103580. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  103581. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  103582. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  103583. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  103584. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  103585. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  103586. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  103587. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  103588. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  103589. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  103590. if (p >= 0.0 && p <= 1.0) {
  103591. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  103592. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  103593. }
  103594. }
  103595. else if(n==5 && 0 == strncmp("welch" , specification, n))
  103596. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  103597. if (encoder->protected_->num_apodizations == 32)
  103598. break;
  103599. if (s)
  103600. specification = s+1;
  103601. else
  103602. break;
  103603. }
  103604. if(encoder->protected_->num_apodizations == 0) {
  103605. encoder->protected_->num_apodizations = 1;
  103606. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103607. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103608. }
  103609. #endif
  103610. return true;
  103611. }
  103612. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  103613. {
  103614. FLAC__ASSERT(0 != encoder);
  103615. FLAC__ASSERT(0 != encoder->private_);
  103616. FLAC__ASSERT(0 != encoder->protected_);
  103617. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103618. return false;
  103619. encoder->protected_->max_lpc_order = value;
  103620. return true;
  103621. }
  103622. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  103623. {
  103624. FLAC__ASSERT(0 != encoder);
  103625. FLAC__ASSERT(0 != encoder->private_);
  103626. FLAC__ASSERT(0 != encoder->protected_);
  103627. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103628. return false;
  103629. encoder->protected_->qlp_coeff_precision = value;
  103630. return true;
  103631. }
  103632. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103633. {
  103634. FLAC__ASSERT(0 != encoder);
  103635. FLAC__ASSERT(0 != encoder->private_);
  103636. FLAC__ASSERT(0 != encoder->protected_);
  103637. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103638. return false;
  103639. encoder->protected_->do_qlp_coeff_prec_search = value;
  103640. return true;
  103641. }
  103642. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103643. {
  103644. FLAC__ASSERT(0 != encoder);
  103645. FLAC__ASSERT(0 != encoder->private_);
  103646. FLAC__ASSERT(0 != encoder->protected_);
  103647. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103648. return false;
  103649. #if 0
  103650. /*@@@ deprecated: */
  103651. encoder->protected_->do_escape_coding = value;
  103652. #else
  103653. (void)value;
  103654. #endif
  103655. return true;
  103656. }
  103657. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103658. {
  103659. FLAC__ASSERT(0 != encoder);
  103660. FLAC__ASSERT(0 != encoder->private_);
  103661. FLAC__ASSERT(0 != encoder->protected_);
  103662. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103663. return false;
  103664. encoder->protected_->do_exhaustive_model_search = value;
  103665. return true;
  103666. }
  103667. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103668. {
  103669. FLAC__ASSERT(0 != encoder);
  103670. FLAC__ASSERT(0 != encoder->private_);
  103671. FLAC__ASSERT(0 != encoder->protected_);
  103672. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103673. return false;
  103674. encoder->protected_->min_residual_partition_order = value;
  103675. return true;
  103676. }
  103677. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103678. {
  103679. FLAC__ASSERT(0 != encoder);
  103680. FLAC__ASSERT(0 != encoder->private_);
  103681. FLAC__ASSERT(0 != encoder->protected_);
  103682. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103683. return false;
  103684. encoder->protected_->max_residual_partition_order = value;
  103685. return true;
  103686. }
  103687. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  103688. {
  103689. FLAC__ASSERT(0 != encoder);
  103690. FLAC__ASSERT(0 != encoder->private_);
  103691. FLAC__ASSERT(0 != encoder->protected_);
  103692. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103693. return false;
  103694. #if 0
  103695. /*@@@ deprecated: */
  103696. encoder->protected_->rice_parameter_search_dist = value;
  103697. #else
  103698. (void)value;
  103699. #endif
  103700. return true;
  103701. }
  103702. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  103703. {
  103704. FLAC__ASSERT(0 != encoder);
  103705. FLAC__ASSERT(0 != encoder->private_);
  103706. FLAC__ASSERT(0 != encoder->protected_);
  103707. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103708. return false;
  103709. encoder->protected_->total_samples_estimate = value;
  103710. return true;
  103711. }
  103712. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  103713. {
  103714. FLAC__ASSERT(0 != encoder);
  103715. FLAC__ASSERT(0 != encoder->private_);
  103716. FLAC__ASSERT(0 != encoder->protected_);
  103717. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103718. return false;
  103719. if(0 == metadata)
  103720. num_blocks = 0;
  103721. if(0 == num_blocks)
  103722. metadata = 0;
  103723. /* realloc() does not do exactly what we want so... */
  103724. if(encoder->protected_->metadata) {
  103725. free(encoder->protected_->metadata);
  103726. encoder->protected_->metadata = 0;
  103727. encoder->protected_->num_metadata_blocks = 0;
  103728. }
  103729. if(num_blocks) {
  103730. FLAC__StreamMetadata **m;
  103731. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  103732. return false;
  103733. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  103734. encoder->protected_->metadata = m;
  103735. encoder->protected_->num_metadata_blocks = num_blocks;
  103736. }
  103737. #if FLAC__HAS_OGG
  103738. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  103739. return false;
  103740. #endif
  103741. return true;
  103742. }
  103743. /*
  103744. * These three functions are not static, but not publically exposed in
  103745. * include/FLAC/ either. They are used by the test suite.
  103746. */
  103747. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103748. {
  103749. FLAC__ASSERT(0 != encoder);
  103750. FLAC__ASSERT(0 != encoder->private_);
  103751. FLAC__ASSERT(0 != encoder->protected_);
  103752. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103753. return false;
  103754. encoder->private_->disable_constant_subframes = value;
  103755. return true;
  103756. }
  103757. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103758. {
  103759. FLAC__ASSERT(0 != encoder);
  103760. FLAC__ASSERT(0 != encoder->private_);
  103761. FLAC__ASSERT(0 != encoder->protected_);
  103762. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103763. return false;
  103764. encoder->private_->disable_fixed_subframes = value;
  103765. return true;
  103766. }
  103767. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103768. {
  103769. FLAC__ASSERT(0 != encoder);
  103770. FLAC__ASSERT(0 != encoder->private_);
  103771. FLAC__ASSERT(0 != encoder->protected_);
  103772. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103773. return false;
  103774. encoder->private_->disable_verbatim_subframes = value;
  103775. return true;
  103776. }
  103777. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  103778. {
  103779. FLAC__ASSERT(0 != encoder);
  103780. FLAC__ASSERT(0 != encoder->private_);
  103781. FLAC__ASSERT(0 != encoder->protected_);
  103782. return encoder->protected_->state;
  103783. }
  103784. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  103785. {
  103786. FLAC__ASSERT(0 != encoder);
  103787. FLAC__ASSERT(0 != encoder->private_);
  103788. FLAC__ASSERT(0 != encoder->protected_);
  103789. if(encoder->protected_->verify)
  103790. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  103791. else
  103792. return FLAC__STREAM_DECODER_UNINITIALIZED;
  103793. }
  103794. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  103795. {
  103796. FLAC__ASSERT(0 != encoder);
  103797. FLAC__ASSERT(0 != encoder->private_);
  103798. FLAC__ASSERT(0 != encoder->protected_);
  103799. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  103800. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  103801. else
  103802. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  103803. }
  103804. 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)
  103805. {
  103806. FLAC__ASSERT(0 != encoder);
  103807. FLAC__ASSERT(0 != encoder->private_);
  103808. FLAC__ASSERT(0 != encoder->protected_);
  103809. if(0 != absolute_sample)
  103810. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  103811. if(0 != frame_number)
  103812. *frame_number = encoder->private_->verify.error_stats.frame_number;
  103813. if(0 != channel)
  103814. *channel = encoder->private_->verify.error_stats.channel;
  103815. if(0 != sample)
  103816. *sample = encoder->private_->verify.error_stats.sample;
  103817. if(0 != expected)
  103818. *expected = encoder->private_->verify.error_stats.expected;
  103819. if(0 != got)
  103820. *got = encoder->private_->verify.error_stats.got;
  103821. }
  103822. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  103823. {
  103824. FLAC__ASSERT(0 != encoder);
  103825. FLAC__ASSERT(0 != encoder->private_);
  103826. FLAC__ASSERT(0 != encoder->protected_);
  103827. return encoder->protected_->verify;
  103828. }
  103829. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  103830. {
  103831. FLAC__ASSERT(0 != encoder);
  103832. FLAC__ASSERT(0 != encoder->private_);
  103833. FLAC__ASSERT(0 != encoder->protected_);
  103834. return encoder->protected_->streamable_subset;
  103835. }
  103836. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  103837. {
  103838. FLAC__ASSERT(0 != encoder);
  103839. FLAC__ASSERT(0 != encoder->private_);
  103840. FLAC__ASSERT(0 != encoder->protected_);
  103841. return encoder->protected_->do_md5;
  103842. }
  103843. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  103844. {
  103845. FLAC__ASSERT(0 != encoder);
  103846. FLAC__ASSERT(0 != encoder->private_);
  103847. FLAC__ASSERT(0 != encoder->protected_);
  103848. return encoder->protected_->channels;
  103849. }
  103850. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  103851. {
  103852. FLAC__ASSERT(0 != encoder);
  103853. FLAC__ASSERT(0 != encoder->private_);
  103854. FLAC__ASSERT(0 != encoder->protected_);
  103855. return encoder->protected_->bits_per_sample;
  103856. }
  103857. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  103858. {
  103859. FLAC__ASSERT(0 != encoder);
  103860. FLAC__ASSERT(0 != encoder->private_);
  103861. FLAC__ASSERT(0 != encoder->protected_);
  103862. return encoder->protected_->sample_rate;
  103863. }
  103864. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  103865. {
  103866. FLAC__ASSERT(0 != encoder);
  103867. FLAC__ASSERT(0 != encoder->private_);
  103868. FLAC__ASSERT(0 != encoder->protected_);
  103869. return encoder->protected_->blocksize;
  103870. }
  103871. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  103872. {
  103873. FLAC__ASSERT(0 != encoder);
  103874. FLAC__ASSERT(0 != encoder->private_);
  103875. FLAC__ASSERT(0 != encoder->protected_);
  103876. return encoder->protected_->do_mid_side_stereo;
  103877. }
  103878. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  103879. {
  103880. FLAC__ASSERT(0 != encoder);
  103881. FLAC__ASSERT(0 != encoder->private_);
  103882. FLAC__ASSERT(0 != encoder->protected_);
  103883. return encoder->protected_->loose_mid_side_stereo;
  103884. }
  103885. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  103886. {
  103887. FLAC__ASSERT(0 != encoder);
  103888. FLAC__ASSERT(0 != encoder->private_);
  103889. FLAC__ASSERT(0 != encoder->protected_);
  103890. return encoder->protected_->max_lpc_order;
  103891. }
  103892. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  103893. {
  103894. FLAC__ASSERT(0 != encoder);
  103895. FLAC__ASSERT(0 != encoder->private_);
  103896. FLAC__ASSERT(0 != encoder->protected_);
  103897. return encoder->protected_->qlp_coeff_precision;
  103898. }
  103899. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  103900. {
  103901. FLAC__ASSERT(0 != encoder);
  103902. FLAC__ASSERT(0 != encoder->private_);
  103903. FLAC__ASSERT(0 != encoder->protected_);
  103904. return encoder->protected_->do_qlp_coeff_prec_search;
  103905. }
  103906. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  103907. {
  103908. FLAC__ASSERT(0 != encoder);
  103909. FLAC__ASSERT(0 != encoder->private_);
  103910. FLAC__ASSERT(0 != encoder->protected_);
  103911. return encoder->protected_->do_escape_coding;
  103912. }
  103913. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  103914. {
  103915. FLAC__ASSERT(0 != encoder);
  103916. FLAC__ASSERT(0 != encoder->private_);
  103917. FLAC__ASSERT(0 != encoder->protected_);
  103918. return encoder->protected_->do_exhaustive_model_search;
  103919. }
  103920. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  103921. {
  103922. FLAC__ASSERT(0 != encoder);
  103923. FLAC__ASSERT(0 != encoder->private_);
  103924. FLAC__ASSERT(0 != encoder->protected_);
  103925. return encoder->protected_->min_residual_partition_order;
  103926. }
  103927. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  103928. {
  103929. FLAC__ASSERT(0 != encoder);
  103930. FLAC__ASSERT(0 != encoder->private_);
  103931. FLAC__ASSERT(0 != encoder->protected_);
  103932. return encoder->protected_->max_residual_partition_order;
  103933. }
  103934. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  103935. {
  103936. FLAC__ASSERT(0 != encoder);
  103937. FLAC__ASSERT(0 != encoder->private_);
  103938. FLAC__ASSERT(0 != encoder->protected_);
  103939. return encoder->protected_->rice_parameter_search_dist;
  103940. }
  103941. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  103942. {
  103943. FLAC__ASSERT(0 != encoder);
  103944. FLAC__ASSERT(0 != encoder->private_);
  103945. FLAC__ASSERT(0 != encoder->protected_);
  103946. return encoder->protected_->total_samples_estimate;
  103947. }
  103948. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  103949. {
  103950. unsigned i, j = 0, channel;
  103951. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  103952. FLAC__ASSERT(0 != encoder);
  103953. FLAC__ASSERT(0 != encoder->private_);
  103954. FLAC__ASSERT(0 != encoder->protected_);
  103955. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  103956. do {
  103957. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  103958. if(encoder->protected_->verify)
  103959. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  103960. for(channel = 0; channel < channels; channel++)
  103961. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  103962. if(encoder->protected_->do_mid_side_stereo) {
  103963. FLAC__ASSERT(channels == 2);
  103964. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  103965. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  103966. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  103967. 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' ! */
  103968. }
  103969. }
  103970. else
  103971. j += n;
  103972. encoder->private_->current_sample_number += n;
  103973. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  103974. if(encoder->private_->current_sample_number > blocksize) {
  103975. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  103976. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  103977. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  103978. return false;
  103979. /* move unprocessed overread samples to beginnings of arrays */
  103980. for(channel = 0; channel < channels; channel++)
  103981. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  103982. if(encoder->protected_->do_mid_side_stereo) {
  103983. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  103984. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  103985. }
  103986. encoder->private_->current_sample_number = 1;
  103987. }
  103988. } while(j < samples);
  103989. return true;
  103990. }
  103991. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  103992. {
  103993. unsigned i, j, k, channel;
  103994. FLAC__int32 x, mid, side;
  103995. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  103996. FLAC__ASSERT(0 != encoder);
  103997. FLAC__ASSERT(0 != encoder->private_);
  103998. FLAC__ASSERT(0 != encoder->protected_);
  103999. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104000. j = k = 0;
  104001. /*
  104002. * we have several flavors of the same basic loop, optimized for
  104003. * different conditions:
  104004. */
  104005. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  104006. /*
  104007. * stereo coding: unroll channel loop
  104008. */
  104009. do {
  104010. if(encoder->protected_->verify)
  104011. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  104012. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  104013. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  104014. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  104015. x = buffer[k++];
  104016. encoder->private_->integer_signal[1][i] = x;
  104017. mid += x;
  104018. side -= x;
  104019. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  104020. encoder->private_->integer_signal_mid_side[1][i] = side;
  104021. encoder->private_->integer_signal_mid_side[0][i] = mid;
  104022. }
  104023. encoder->private_->current_sample_number = i;
  104024. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  104025. if(i > blocksize) {
  104026. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  104027. return false;
  104028. /* move unprocessed overread samples to beginnings of arrays */
  104029. FLAC__ASSERT(i == blocksize+OVERREAD_);
  104030. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  104031. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  104032. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  104033. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  104034. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  104035. encoder->private_->current_sample_number = 1;
  104036. }
  104037. } while(j < samples);
  104038. }
  104039. else {
  104040. /*
  104041. * independent channel coding: buffer each channel in inner loop
  104042. */
  104043. do {
  104044. if(encoder->protected_->verify)
  104045. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  104046. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  104047. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  104048. for(channel = 0; channel < channels; channel++)
  104049. encoder->private_->integer_signal[channel][i] = buffer[k++];
  104050. }
  104051. encoder->private_->current_sample_number = i;
  104052. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  104053. if(i > blocksize) {
  104054. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  104055. return false;
  104056. /* move unprocessed overread samples to beginnings of arrays */
  104057. FLAC__ASSERT(i == blocksize+OVERREAD_);
  104058. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  104059. for(channel = 0; channel < channels; channel++)
  104060. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  104061. encoder->private_->current_sample_number = 1;
  104062. }
  104063. } while(j < samples);
  104064. }
  104065. return true;
  104066. }
  104067. /***********************************************************************
  104068. *
  104069. * Private class methods
  104070. *
  104071. ***********************************************************************/
  104072. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  104073. {
  104074. FLAC__ASSERT(0 != encoder);
  104075. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  104076. encoder->protected_->verify = true;
  104077. #else
  104078. encoder->protected_->verify = false;
  104079. #endif
  104080. encoder->protected_->streamable_subset = true;
  104081. encoder->protected_->do_md5 = true;
  104082. encoder->protected_->do_mid_side_stereo = false;
  104083. encoder->protected_->loose_mid_side_stereo = false;
  104084. encoder->protected_->channels = 2;
  104085. encoder->protected_->bits_per_sample = 16;
  104086. encoder->protected_->sample_rate = 44100;
  104087. encoder->protected_->blocksize = 0;
  104088. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104089. encoder->protected_->num_apodizations = 1;
  104090. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  104091. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  104092. #endif
  104093. encoder->protected_->max_lpc_order = 0;
  104094. encoder->protected_->qlp_coeff_precision = 0;
  104095. encoder->protected_->do_qlp_coeff_prec_search = false;
  104096. encoder->protected_->do_exhaustive_model_search = false;
  104097. encoder->protected_->do_escape_coding = false;
  104098. encoder->protected_->min_residual_partition_order = 0;
  104099. encoder->protected_->max_residual_partition_order = 0;
  104100. encoder->protected_->rice_parameter_search_dist = 0;
  104101. encoder->protected_->total_samples_estimate = 0;
  104102. encoder->protected_->metadata = 0;
  104103. encoder->protected_->num_metadata_blocks = 0;
  104104. encoder->private_->seek_table = 0;
  104105. encoder->private_->disable_constant_subframes = false;
  104106. encoder->private_->disable_fixed_subframes = false;
  104107. encoder->private_->disable_verbatim_subframes = false;
  104108. #if FLAC__HAS_OGG
  104109. encoder->private_->is_ogg = false;
  104110. #endif
  104111. encoder->private_->read_callback = 0;
  104112. encoder->private_->write_callback = 0;
  104113. encoder->private_->seek_callback = 0;
  104114. encoder->private_->tell_callback = 0;
  104115. encoder->private_->metadata_callback = 0;
  104116. encoder->private_->progress_callback = 0;
  104117. encoder->private_->client_data = 0;
  104118. #if FLAC__HAS_OGG
  104119. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  104120. #endif
  104121. }
  104122. void free_(FLAC__StreamEncoder *encoder)
  104123. {
  104124. unsigned i, channel;
  104125. FLAC__ASSERT(0 != encoder);
  104126. if(encoder->protected_->metadata) {
  104127. free(encoder->protected_->metadata);
  104128. encoder->protected_->metadata = 0;
  104129. encoder->protected_->num_metadata_blocks = 0;
  104130. }
  104131. for(i = 0; i < encoder->protected_->channels; i++) {
  104132. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  104133. free(encoder->private_->integer_signal_unaligned[i]);
  104134. encoder->private_->integer_signal_unaligned[i] = 0;
  104135. }
  104136. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104137. if(0 != encoder->private_->real_signal_unaligned[i]) {
  104138. free(encoder->private_->real_signal_unaligned[i]);
  104139. encoder->private_->real_signal_unaligned[i] = 0;
  104140. }
  104141. #endif
  104142. }
  104143. for(i = 0; i < 2; i++) {
  104144. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  104145. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  104146. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  104147. }
  104148. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104149. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  104150. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  104151. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  104152. }
  104153. #endif
  104154. }
  104155. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104156. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  104157. if(0 != encoder->private_->window_unaligned[i]) {
  104158. free(encoder->private_->window_unaligned[i]);
  104159. encoder->private_->window_unaligned[i] = 0;
  104160. }
  104161. }
  104162. if(0 != encoder->private_->windowed_signal_unaligned) {
  104163. free(encoder->private_->windowed_signal_unaligned);
  104164. encoder->private_->windowed_signal_unaligned = 0;
  104165. }
  104166. #endif
  104167. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104168. for(i = 0; i < 2; i++) {
  104169. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  104170. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  104171. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  104172. }
  104173. }
  104174. }
  104175. for(channel = 0; channel < 2; channel++) {
  104176. for(i = 0; i < 2; i++) {
  104177. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  104178. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  104179. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  104180. }
  104181. }
  104182. }
  104183. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  104184. free(encoder->private_->abs_residual_partition_sums_unaligned);
  104185. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  104186. }
  104187. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  104188. free(encoder->private_->raw_bits_per_partition_unaligned);
  104189. encoder->private_->raw_bits_per_partition_unaligned = 0;
  104190. }
  104191. if(encoder->protected_->verify) {
  104192. for(i = 0; i < encoder->protected_->channels; i++) {
  104193. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  104194. free(encoder->private_->verify.input_fifo.data[i]);
  104195. encoder->private_->verify.input_fifo.data[i] = 0;
  104196. }
  104197. }
  104198. }
  104199. FLAC__bitwriter_free(encoder->private_->frame);
  104200. }
  104201. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  104202. {
  104203. FLAC__bool ok;
  104204. unsigned i, channel;
  104205. FLAC__ASSERT(new_blocksize > 0);
  104206. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104207. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  104208. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  104209. if(new_blocksize <= encoder->private_->input_capacity)
  104210. return true;
  104211. ok = true;
  104212. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  104213. * requires that the input arrays (in our case the integer signals)
  104214. * have a buffer of up to 3 zeroes in front (at negative indices) for
  104215. * alignment purposes; we use 4 in front to keep the data well-aligned.
  104216. */
  104217. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  104218. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  104219. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  104220. encoder->private_->integer_signal[i] += 4;
  104221. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104222. #if 0 /* @@@ currently unused */
  104223. if(encoder->protected_->max_lpc_order > 0)
  104224. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  104225. #endif
  104226. #endif
  104227. }
  104228. for(i = 0; ok && i < 2; i++) {
  104229. 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]);
  104230. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  104231. encoder->private_->integer_signal_mid_side[i] += 4;
  104232. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104233. #if 0 /* @@@ currently unused */
  104234. if(encoder->protected_->max_lpc_order > 0)
  104235. 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]);
  104236. #endif
  104237. #endif
  104238. }
  104239. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104240. if(ok && encoder->protected_->max_lpc_order > 0) {
  104241. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  104242. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  104243. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  104244. }
  104245. #endif
  104246. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  104247. for(i = 0; ok && i < 2; i++) {
  104248. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  104249. }
  104250. }
  104251. for(channel = 0; ok && channel < 2; channel++) {
  104252. for(i = 0; ok && i < 2; i++) {
  104253. 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]);
  104254. }
  104255. }
  104256. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  104257. /*@@@ 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) */
  104258. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  104259. if(encoder->protected_->do_escape_coding)
  104260. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  104261. /* now adjust the windows if the blocksize has changed */
  104262. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104263. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  104264. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  104265. switch(encoder->protected_->apodizations[i].type) {
  104266. case FLAC__APODIZATION_BARTLETT:
  104267. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  104268. break;
  104269. case FLAC__APODIZATION_BARTLETT_HANN:
  104270. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  104271. break;
  104272. case FLAC__APODIZATION_BLACKMAN:
  104273. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  104274. break;
  104275. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  104276. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  104277. break;
  104278. case FLAC__APODIZATION_CONNES:
  104279. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  104280. break;
  104281. case FLAC__APODIZATION_FLATTOP:
  104282. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  104283. break;
  104284. case FLAC__APODIZATION_GAUSS:
  104285. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  104286. break;
  104287. case FLAC__APODIZATION_HAMMING:
  104288. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  104289. break;
  104290. case FLAC__APODIZATION_HANN:
  104291. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  104292. break;
  104293. case FLAC__APODIZATION_KAISER_BESSEL:
  104294. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  104295. break;
  104296. case FLAC__APODIZATION_NUTTALL:
  104297. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  104298. break;
  104299. case FLAC__APODIZATION_RECTANGLE:
  104300. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  104301. break;
  104302. case FLAC__APODIZATION_TRIANGLE:
  104303. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  104304. break;
  104305. case FLAC__APODIZATION_TUKEY:
  104306. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  104307. break;
  104308. case FLAC__APODIZATION_WELCH:
  104309. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  104310. break;
  104311. default:
  104312. FLAC__ASSERT(0);
  104313. /* double protection */
  104314. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  104315. break;
  104316. }
  104317. }
  104318. }
  104319. #endif
  104320. if(ok)
  104321. encoder->private_->input_capacity = new_blocksize;
  104322. else
  104323. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104324. return ok;
  104325. }
  104326. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  104327. {
  104328. const FLAC__byte *buffer;
  104329. size_t bytes;
  104330. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104331. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  104332. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104333. return false;
  104334. }
  104335. if(encoder->protected_->verify) {
  104336. encoder->private_->verify.output.data = buffer;
  104337. encoder->private_->verify.output.bytes = bytes;
  104338. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  104339. encoder->private_->verify.needs_magic_hack = true;
  104340. }
  104341. else {
  104342. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  104343. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104344. FLAC__bitwriter_clear(encoder->private_->frame);
  104345. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  104346. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  104347. return false;
  104348. }
  104349. }
  104350. }
  104351. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104352. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104353. FLAC__bitwriter_clear(encoder->private_->frame);
  104354. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104355. return false;
  104356. }
  104357. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104358. FLAC__bitwriter_clear(encoder->private_->frame);
  104359. if(samples > 0) {
  104360. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  104361. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  104362. }
  104363. return true;
  104364. }
  104365. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  104366. {
  104367. FLAC__StreamEncoderWriteStatus status;
  104368. FLAC__uint64 output_position = 0;
  104369. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  104370. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  104371. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104372. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  104373. }
  104374. /*
  104375. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  104376. */
  104377. if(samples == 0) {
  104378. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  104379. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  104380. encoder->protected_->streaminfo_offset = output_position;
  104381. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  104382. encoder->protected_->seektable_offset = output_position;
  104383. }
  104384. /*
  104385. * Mark the current seek point if hit (if audio_offset == 0 that
  104386. * means we're still writing metadata and haven't hit the first
  104387. * frame yet)
  104388. */
  104389. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  104390. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  104391. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  104392. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  104393. FLAC__uint64 test_sample;
  104394. unsigned i;
  104395. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  104396. test_sample = encoder->private_->seek_table->points[i].sample_number;
  104397. if(test_sample > frame_last_sample) {
  104398. break;
  104399. }
  104400. else if(test_sample >= frame_first_sample) {
  104401. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  104402. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  104403. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  104404. encoder->private_->first_seekpoint_to_check++;
  104405. /* DO NOT: "break;" and here's why:
  104406. * The seektable template may contain more than one target
  104407. * sample for any given frame; we will keep looping, generating
  104408. * duplicate seekpoints for them, and we'll clean it up later,
  104409. * just before writing the seektable back to the metadata.
  104410. */
  104411. }
  104412. else {
  104413. encoder->private_->first_seekpoint_to_check++;
  104414. }
  104415. }
  104416. }
  104417. #if FLAC__HAS_OGG
  104418. if(encoder->private_->is_ogg) {
  104419. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  104420. &encoder->protected_->ogg_encoder_aspect,
  104421. buffer,
  104422. bytes,
  104423. samples,
  104424. encoder->private_->current_frame_number,
  104425. is_last_block,
  104426. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  104427. encoder,
  104428. encoder->private_->client_data
  104429. );
  104430. }
  104431. else
  104432. #endif
  104433. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  104434. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104435. encoder->private_->bytes_written += bytes;
  104436. encoder->private_->samples_written += samples;
  104437. /* we keep a high watermark on the number of frames written because
  104438. * when the encoder goes back to write metadata, 'current_frame'
  104439. * will drop back to 0.
  104440. */
  104441. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  104442. }
  104443. else
  104444. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104445. return status;
  104446. }
  104447. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104448. void update_metadata_(const FLAC__StreamEncoder *encoder)
  104449. {
  104450. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104451. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104452. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104453. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104454. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104455. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  104456. FLAC__StreamEncoderSeekStatus seek_status;
  104457. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104458. /* All this is based on intimate knowledge of the stream header
  104459. * layout, but a change to the header format that would break this
  104460. * would also break all streams encoded in the previous format.
  104461. */
  104462. /*
  104463. * Write MD5 signature
  104464. */
  104465. {
  104466. const unsigned md5_offset =
  104467. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104468. (
  104469. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104470. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104471. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104472. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104473. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104474. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104475. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104476. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104477. ) / 8;
  104478. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  104479. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104480. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104481. return;
  104482. }
  104483. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104484. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104485. return;
  104486. }
  104487. }
  104488. /*
  104489. * Write total samples
  104490. */
  104491. {
  104492. const unsigned total_samples_byte_offset =
  104493. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104494. (
  104495. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104496. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104497. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104498. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104499. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104500. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104501. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104502. - 4
  104503. ) / 8;
  104504. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  104505. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104506. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104507. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104508. b[4] = (FLAC__byte)(samples & 0xFF);
  104509. 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) {
  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, b, 5, 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 min/max framesize
  104521. */
  104522. {
  104523. const unsigned min_framesize_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. ) / 8;
  104529. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104530. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104531. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104532. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104533. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104534. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104535. 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) {
  104536. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104537. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104538. return;
  104539. }
  104540. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104541. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104542. return;
  104543. }
  104544. }
  104545. /*
  104546. * Write seektable
  104547. */
  104548. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104549. unsigned i;
  104550. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104551. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104552. 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) {
  104553. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104554. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104555. return;
  104556. }
  104557. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  104558. FLAC__uint64 xx;
  104559. unsigned x;
  104560. xx = encoder->private_->seek_table->points[i].sample_number;
  104561. b[7] = (FLAC__byte)xx; xx >>= 8;
  104562. b[6] = (FLAC__byte)xx; xx >>= 8;
  104563. b[5] = (FLAC__byte)xx; xx >>= 8;
  104564. b[4] = (FLAC__byte)xx; xx >>= 8;
  104565. b[3] = (FLAC__byte)xx; xx >>= 8;
  104566. b[2] = (FLAC__byte)xx; xx >>= 8;
  104567. b[1] = (FLAC__byte)xx; xx >>= 8;
  104568. b[0] = (FLAC__byte)xx; xx >>= 8;
  104569. xx = encoder->private_->seek_table->points[i].stream_offset;
  104570. b[15] = (FLAC__byte)xx; xx >>= 8;
  104571. b[14] = (FLAC__byte)xx; xx >>= 8;
  104572. b[13] = (FLAC__byte)xx; xx >>= 8;
  104573. b[12] = (FLAC__byte)xx; xx >>= 8;
  104574. b[11] = (FLAC__byte)xx; xx >>= 8;
  104575. b[10] = (FLAC__byte)xx; xx >>= 8;
  104576. b[9] = (FLAC__byte)xx; xx >>= 8;
  104577. b[8] = (FLAC__byte)xx; xx >>= 8;
  104578. x = encoder->private_->seek_table->points[i].frame_samples;
  104579. b[17] = (FLAC__byte)x; x >>= 8;
  104580. b[16] = (FLAC__byte)x; x >>= 8;
  104581. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104582. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104583. return;
  104584. }
  104585. }
  104586. }
  104587. }
  104588. #if FLAC__HAS_OGG
  104589. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104590. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  104591. {
  104592. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  104593. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  104594. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  104595. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  104596. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  104597. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  104598. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  104599. FLAC__STREAM_SYNC_LENGTH
  104600. ;
  104601. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104602. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104603. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104604. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104605. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104606. ogg_page page;
  104607. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104608. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  104609. /* Pre-check that client supports seeking, since we don't want the
  104610. * ogg_helper code to ever have to deal with this condition.
  104611. */
  104612. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  104613. return;
  104614. /* All this is based on intimate knowledge of the stream header
  104615. * layout, but a change to the header format that would break this
  104616. * would also break all streams encoded in the previous format.
  104617. */
  104618. /**
  104619. ** Write STREAMINFO stats
  104620. **/
  104621. simple_ogg_page__init(&page);
  104622. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104623. simple_ogg_page__clear(&page);
  104624. return; /* state already set */
  104625. }
  104626. /*
  104627. * Write MD5 signature
  104628. */
  104629. {
  104630. const unsigned md5_offset =
  104631. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104632. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104633. (
  104634. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104635. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104636. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104637. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104638. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104639. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104640. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104641. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104642. ) / 8;
  104643. if(md5_offset + 16 > (unsigned)page.body_len) {
  104644. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104645. simple_ogg_page__clear(&page);
  104646. return;
  104647. }
  104648. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  104649. }
  104650. /*
  104651. * Write total samples
  104652. */
  104653. {
  104654. const unsigned total_samples_byte_offset =
  104655. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104656. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104657. (
  104658. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104659. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104660. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104661. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104662. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104663. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104664. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104665. - 4
  104666. ) / 8;
  104667. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  104668. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104669. simple_ogg_page__clear(&page);
  104670. return;
  104671. }
  104672. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  104673. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  104674. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104675. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104676. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104677. b[4] = (FLAC__byte)(samples & 0xFF);
  104678. memcpy(page.body + total_samples_byte_offset, b, 5);
  104679. }
  104680. /*
  104681. * Write min/max framesize
  104682. */
  104683. {
  104684. const unsigned min_framesize_offset =
  104685. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104686. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104687. (
  104688. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104689. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104690. ) / 8;
  104691. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  104692. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104693. simple_ogg_page__clear(&page);
  104694. return;
  104695. }
  104696. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104697. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104698. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104699. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104700. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104701. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104702. memcpy(page.body + min_framesize_offset, b, 6);
  104703. }
  104704. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104705. simple_ogg_page__clear(&page);
  104706. return; /* state already set */
  104707. }
  104708. simple_ogg_page__clear(&page);
  104709. /*
  104710. * Write seektable
  104711. */
  104712. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104713. unsigned i;
  104714. FLAC__byte *p;
  104715. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104716. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104717. simple_ogg_page__init(&page);
  104718. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104719. simple_ogg_page__clear(&page);
  104720. return; /* state already set */
  104721. }
  104722. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  104723. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104724. simple_ogg_page__clear(&page);
  104725. return;
  104726. }
  104727. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  104728. FLAC__uint64 xx;
  104729. unsigned x;
  104730. xx = encoder->private_->seek_table->points[i].sample_number;
  104731. b[7] = (FLAC__byte)xx; xx >>= 8;
  104732. b[6] = (FLAC__byte)xx; xx >>= 8;
  104733. b[5] = (FLAC__byte)xx; xx >>= 8;
  104734. b[4] = (FLAC__byte)xx; xx >>= 8;
  104735. b[3] = (FLAC__byte)xx; xx >>= 8;
  104736. b[2] = (FLAC__byte)xx; xx >>= 8;
  104737. b[1] = (FLAC__byte)xx; xx >>= 8;
  104738. b[0] = (FLAC__byte)xx; xx >>= 8;
  104739. xx = encoder->private_->seek_table->points[i].stream_offset;
  104740. b[15] = (FLAC__byte)xx; xx >>= 8;
  104741. b[14] = (FLAC__byte)xx; xx >>= 8;
  104742. b[13] = (FLAC__byte)xx; xx >>= 8;
  104743. b[12] = (FLAC__byte)xx; xx >>= 8;
  104744. b[11] = (FLAC__byte)xx; xx >>= 8;
  104745. b[10] = (FLAC__byte)xx; xx >>= 8;
  104746. b[9] = (FLAC__byte)xx; xx >>= 8;
  104747. b[8] = (FLAC__byte)xx; xx >>= 8;
  104748. x = encoder->private_->seek_table->points[i].frame_samples;
  104749. b[17] = (FLAC__byte)x; x >>= 8;
  104750. b[16] = (FLAC__byte)x; x >>= 8;
  104751. memcpy(p, b, 18);
  104752. }
  104753. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104754. simple_ogg_page__clear(&page);
  104755. return; /* state already set */
  104756. }
  104757. simple_ogg_page__clear(&page);
  104758. }
  104759. }
  104760. #endif
  104761. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  104762. {
  104763. FLAC__uint16 crc;
  104764. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104765. /*
  104766. * Accumulate raw signal to the MD5 signature
  104767. */
  104768. 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)) {
  104769. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104770. return false;
  104771. }
  104772. /*
  104773. * Process the frame header and subframes into the frame bitbuffer
  104774. */
  104775. if(!process_subframes_(encoder, is_fractional_block)) {
  104776. /* the above function sets the state for us in case of an error */
  104777. return false;
  104778. }
  104779. /*
  104780. * Zero-pad the frame to a byte_boundary
  104781. */
  104782. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  104783. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104784. return false;
  104785. }
  104786. /*
  104787. * CRC-16 the whole thing
  104788. */
  104789. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104790. if(
  104791. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  104792. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  104793. ) {
  104794. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104795. return false;
  104796. }
  104797. /*
  104798. * Write it
  104799. */
  104800. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  104801. /* the above function sets the state for us in case of an error */
  104802. return false;
  104803. }
  104804. /*
  104805. * Get ready for the next frame
  104806. */
  104807. encoder->private_->current_sample_number = 0;
  104808. encoder->private_->current_frame_number++;
  104809. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  104810. return true;
  104811. }
  104812. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  104813. {
  104814. FLAC__FrameHeader frame_header;
  104815. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  104816. FLAC__bool do_independent, do_mid_side;
  104817. /*
  104818. * Calculate the min,max Rice partition orders
  104819. */
  104820. if(is_fractional_block) {
  104821. max_partition_order = 0;
  104822. }
  104823. else {
  104824. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  104825. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  104826. }
  104827. min_partition_order = min(min_partition_order, max_partition_order);
  104828. /*
  104829. * Setup the frame
  104830. */
  104831. frame_header.blocksize = encoder->protected_->blocksize;
  104832. frame_header.sample_rate = encoder->protected_->sample_rate;
  104833. frame_header.channels = encoder->protected_->channels;
  104834. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  104835. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  104836. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  104837. frame_header.number.frame_number = encoder->private_->current_frame_number;
  104838. /*
  104839. * Figure out what channel assignments to try
  104840. */
  104841. if(encoder->protected_->do_mid_side_stereo) {
  104842. if(encoder->protected_->loose_mid_side_stereo) {
  104843. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  104844. do_independent = true;
  104845. do_mid_side = true;
  104846. }
  104847. else {
  104848. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  104849. do_mid_side = !do_independent;
  104850. }
  104851. }
  104852. else {
  104853. do_independent = true;
  104854. do_mid_side = true;
  104855. }
  104856. }
  104857. else {
  104858. do_independent = true;
  104859. do_mid_side = false;
  104860. }
  104861. FLAC__ASSERT(do_independent || do_mid_side);
  104862. /*
  104863. * Check for wasted bits; set effective bps for each subframe
  104864. */
  104865. if(do_independent) {
  104866. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104867. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  104868. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  104869. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  104870. }
  104871. }
  104872. if(do_mid_side) {
  104873. FLAC__ASSERT(encoder->protected_->channels == 2);
  104874. for(channel = 0; channel < 2; channel++) {
  104875. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  104876. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  104877. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  104878. }
  104879. }
  104880. /*
  104881. * First do a normal encoding pass of each independent channel
  104882. */
  104883. if(do_independent) {
  104884. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104885. if(!
  104886. process_subframe_(
  104887. encoder,
  104888. min_partition_order,
  104889. max_partition_order,
  104890. &frame_header,
  104891. encoder->private_->subframe_bps[channel],
  104892. encoder->private_->integer_signal[channel],
  104893. encoder->private_->subframe_workspace_ptr[channel],
  104894. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  104895. encoder->private_->residual_workspace[channel],
  104896. encoder->private_->best_subframe+channel,
  104897. encoder->private_->best_subframe_bits+channel
  104898. )
  104899. )
  104900. return false;
  104901. }
  104902. }
  104903. /*
  104904. * Now do mid and side channels if requested
  104905. */
  104906. if(do_mid_side) {
  104907. FLAC__ASSERT(encoder->protected_->channels == 2);
  104908. for(channel = 0; channel < 2; channel++) {
  104909. if(!
  104910. process_subframe_(
  104911. encoder,
  104912. min_partition_order,
  104913. max_partition_order,
  104914. &frame_header,
  104915. encoder->private_->subframe_bps_mid_side[channel],
  104916. encoder->private_->integer_signal_mid_side[channel],
  104917. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  104918. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  104919. encoder->private_->residual_workspace_mid_side[channel],
  104920. encoder->private_->best_subframe_mid_side+channel,
  104921. encoder->private_->best_subframe_bits_mid_side+channel
  104922. )
  104923. )
  104924. return false;
  104925. }
  104926. }
  104927. /*
  104928. * Compose the frame bitbuffer
  104929. */
  104930. if(do_mid_side) {
  104931. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  104932. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  104933. FLAC__ChannelAssignment channel_assignment;
  104934. FLAC__ASSERT(encoder->protected_->channels == 2);
  104935. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  104936. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  104937. }
  104938. else {
  104939. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  104940. unsigned min_bits;
  104941. int ca;
  104942. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  104943. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  104944. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  104945. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  104946. FLAC__ASSERT(do_independent && do_mid_side);
  104947. /* We have to figure out which channel assignent results in the smallest frame */
  104948. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  104949. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  104950. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  104951. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  104952. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  104953. min_bits = bits[channel_assignment];
  104954. for(ca = 1; ca <= 3; ca++) {
  104955. if(bits[ca] < min_bits) {
  104956. min_bits = bits[ca];
  104957. channel_assignment = (FLAC__ChannelAssignment)ca;
  104958. }
  104959. }
  104960. }
  104961. frame_header.channel_assignment = channel_assignment;
  104962. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  104963. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  104964. return false;
  104965. }
  104966. switch(channel_assignment) {
  104967. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  104968. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  104969. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  104970. break;
  104971. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  104972. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  104973. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104974. break;
  104975. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  104976. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104977. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  104978. break;
  104979. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  104980. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  104981. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  104982. break;
  104983. default:
  104984. FLAC__ASSERT(0);
  104985. }
  104986. switch(channel_assignment) {
  104987. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  104988. left_bps = encoder->private_->subframe_bps [0];
  104989. right_bps = encoder->private_->subframe_bps [1];
  104990. break;
  104991. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  104992. left_bps = encoder->private_->subframe_bps [0];
  104993. right_bps = encoder->private_->subframe_bps_mid_side[1];
  104994. break;
  104995. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  104996. left_bps = encoder->private_->subframe_bps_mid_side[1];
  104997. right_bps = encoder->private_->subframe_bps [1];
  104998. break;
  104999. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  105000. left_bps = encoder->private_->subframe_bps_mid_side[0];
  105001. right_bps = encoder->private_->subframe_bps_mid_side[1];
  105002. break;
  105003. default:
  105004. FLAC__ASSERT(0);
  105005. }
  105006. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  105007. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  105008. return false;
  105009. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  105010. return false;
  105011. }
  105012. else {
  105013. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  105014. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105015. return false;
  105016. }
  105017. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  105018. 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)) {
  105019. /* the above function sets the state for us in case of an error */
  105020. return false;
  105021. }
  105022. }
  105023. }
  105024. if(encoder->protected_->loose_mid_side_stereo) {
  105025. encoder->private_->loose_mid_side_stereo_frame_count++;
  105026. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  105027. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  105028. }
  105029. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  105030. return true;
  105031. }
  105032. FLAC__bool process_subframe_(
  105033. FLAC__StreamEncoder *encoder,
  105034. unsigned min_partition_order,
  105035. unsigned max_partition_order,
  105036. const FLAC__FrameHeader *frame_header,
  105037. unsigned subframe_bps,
  105038. const FLAC__int32 integer_signal[],
  105039. FLAC__Subframe *subframe[2],
  105040. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  105041. FLAC__int32 *residual[2],
  105042. unsigned *best_subframe,
  105043. unsigned *best_bits
  105044. )
  105045. {
  105046. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105047. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  105048. #else
  105049. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  105050. #endif
  105051. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105052. FLAC__double lpc_residual_bits_per_sample;
  105053. 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 */
  105054. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  105055. unsigned min_lpc_order, max_lpc_order, lpc_order;
  105056. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  105057. #endif
  105058. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  105059. unsigned rice_parameter;
  105060. unsigned _candidate_bits, _best_bits;
  105061. unsigned _best_subframe;
  105062. /* only use RICE2 partitions if stream bps > 16 */
  105063. 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;
  105064. FLAC__ASSERT(frame_header->blocksize > 0);
  105065. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  105066. _best_subframe = 0;
  105067. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  105068. _best_bits = UINT_MAX;
  105069. else
  105070. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  105071. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  105072. unsigned signal_is_constant = false;
  105073. 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);
  105074. /* check for constant subframe */
  105075. if(
  105076. !encoder->private_->disable_constant_subframes &&
  105077. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105078. fixed_residual_bits_per_sample[1] == 0.0
  105079. #else
  105080. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  105081. #endif
  105082. ) {
  105083. /* the above means it's possible all samples are the same value; now double-check it: */
  105084. unsigned i;
  105085. signal_is_constant = true;
  105086. for(i = 1; i < frame_header->blocksize; i++) {
  105087. if(integer_signal[0] != integer_signal[i]) {
  105088. signal_is_constant = false;
  105089. break;
  105090. }
  105091. }
  105092. }
  105093. if(signal_is_constant) {
  105094. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  105095. if(_candidate_bits < _best_bits) {
  105096. _best_subframe = !_best_subframe;
  105097. _best_bits = _candidate_bits;
  105098. }
  105099. }
  105100. else {
  105101. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  105102. /* encode fixed */
  105103. if(encoder->protected_->do_exhaustive_model_search) {
  105104. min_fixed_order = 0;
  105105. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  105106. }
  105107. else {
  105108. min_fixed_order = max_fixed_order = guess_fixed_order;
  105109. }
  105110. if(max_fixed_order >= frame_header->blocksize)
  105111. max_fixed_order = frame_header->blocksize - 1;
  105112. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  105113. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105114. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  105115. continue; /* don't even try */
  105116. 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 */
  105117. #else
  105118. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  105119. continue; /* don't even try */
  105120. 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 */
  105121. #endif
  105122. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  105123. if(rice_parameter >= rice_parameter_limit) {
  105124. #ifdef DEBUG_VERBOSE
  105125. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  105126. #endif
  105127. rice_parameter = rice_parameter_limit - 1;
  105128. }
  105129. _candidate_bits =
  105130. evaluate_fixed_subframe_(
  105131. encoder,
  105132. integer_signal,
  105133. residual[!_best_subframe],
  105134. encoder->private_->abs_residual_partition_sums,
  105135. encoder->private_->raw_bits_per_partition,
  105136. frame_header->blocksize,
  105137. subframe_bps,
  105138. fixed_order,
  105139. rice_parameter,
  105140. rice_parameter_limit,
  105141. min_partition_order,
  105142. max_partition_order,
  105143. encoder->protected_->do_escape_coding,
  105144. encoder->protected_->rice_parameter_search_dist,
  105145. subframe[!_best_subframe],
  105146. partitioned_rice_contents[!_best_subframe]
  105147. );
  105148. if(_candidate_bits < _best_bits) {
  105149. _best_subframe = !_best_subframe;
  105150. _best_bits = _candidate_bits;
  105151. }
  105152. }
  105153. }
  105154. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105155. /* encode lpc */
  105156. if(encoder->protected_->max_lpc_order > 0) {
  105157. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  105158. max_lpc_order = frame_header->blocksize-1;
  105159. else
  105160. max_lpc_order = encoder->protected_->max_lpc_order;
  105161. if(max_lpc_order > 0) {
  105162. unsigned a;
  105163. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  105164. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  105165. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  105166. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  105167. if(autoc[0] != 0.0) {
  105168. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  105169. if(encoder->protected_->do_exhaustive_model_search) {
  105170. min_lpc_order = 1;
  105171. }
  105172. else {
  105173. const unsigned guess_lpc_order =
  105174. FLAC__lpc_compute_best_order(
  105175. lpc_error,
  105176. max_lpc_order,
  105177. frame_header->blocksize,
  105178. subframe_bps + (
  105179. encoder->protected_->do_qlp_coeff_prec_search?
  105180. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  105181. encoder->protected_->qlp_coeff_precision
  105182. )
  105183. );
  105184. min_lpc_order = max_lpc_order = guess_lpc_order;
  105185. }
  105186. if(max_lpc_order >= frame_header->blocksize)
  105187. max_lpc_order = frame_header->blocksize - 1;
  105188. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  105189. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  105190. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  105191. continue; /* don't even try */
  105192. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  105193. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  105194. if(rice_parameter >= rice_parameter_limit) {
  105195. #ifdef DEBUG_VERBOSE
  105196. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  105197. #endif
  105198. rice_parameter = rice_parameter_limit - 1;
  105199. }
  105200. if(encoder->protected_->do_qlp_coeff_prec_search) {
  105201. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  105202. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  105203. if(subframe_bps <= 17) {
  105204. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  105205. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  105206. }
  105207. else
  105208. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  105209. }
  105210. else {
  105211. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  105212. }
  105213. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  105214. _candidate_bits =
  105215. evaluate_lpc_subframe_(
  105216. encoder,
  105217. integer_signal,
  105218. residual[!_best_subframe],
  105219. encoder->private_->abs_residual_partition_sums,
  105220. encoder->private_->raw_bits_per_partition,
  105221. encoder->private_->lp_coeff[lpc_order-1],
  105222. frame_header->blocksize,
  105223. subframe_bps,
  105224. lpc_order,
  105225. qlp_coeff_precision,
  105226. rice_parameter,
  105227. rice_parameter_limit,
  105228. min_partition_order,
  105229. max_partition_order,
  105230. encoder->protected_->do_escape_coding,
  105231. encoder->protected_->rice_parameter_search_dist,
  105232. subframe[!_best_subframe],
  105233. partitioned_rice_contents[!_best_subframe]
  105234. );
  105235. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  105236. if(_candidate_bits < _best_bits) {
  105237. _best_subframe = !_best_subframe;
  105238. _best_bits = _candidate_bits;
  105239. }
  105240. }
  105241. }
  105242. }
  105243. }
  105244. }
  105245. }
  105246. }
  105247. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  105248. }
  105249. }
  105250. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  105251. if(_best_bits == UINT_MAX) {
  105252. FLAC__ASSERT(_best_subframe == 0);
  105253. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  105254. }
  105255. *best_subframe = _best_subframe;
  105256. *best_bits = _best_bits;
  105257. return true;
  105258. }
  105259. FLAC__bool add_subframe_(
  105260. FLAC__StreamEncoder *encoder,
  105261. unsigned blocksize,
  105262. unsigned subframe_bps,
  105263. const FLAC__Subframe *subframe,
  105264. FLAC__BitWriter *frame
  105265. )
  105266. {
  105267. switch(subframe->type) {
  105268. case FLAC__SUBFRAME_TYPE_CONSTANT:
  105269. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  105270. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105271. return false;
  105272. }
  105273. break;
  105274. case FLAC__SUBFRAME_TYPE_FIXED:
  105275. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  105276. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105277. return false;
  105278. }
  105279. break;
  105280. case FLAC__SUBFRAME_TYPE_LPC:
  105281. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  105282. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105283. return false;
  105284. }
  105285. break;
  105286. case FLAC__SUBFRAME_TYPE_VERBATIM:
  105287. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  105288. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105289. return false;
  105290. }
  105291. break;
  105292. default:
  105293. FLAC__ASSERT(0);
  105294. }
  105295. return true;
  105296. }
  105297. #define SPOTCHECK_ESTIMATE 0
  105298. #if SPOTCHECK_ESTIMATE
  105299. static void spotcheck_subframe_estimate_(
  105300. FLAC__StreamEncoder *encoder,
  105301. unsigned blocksize,
  105302. unsigned subframe_bps,
  105303. const FLAC__Subframe *subframe,
  105304. unsigned estimate
  105305. )
  105306. {
  105307. FLAC__bool ret;
  105308. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  105309. if(frame == 0) {
  105310. fprintf(stderr, "EST: can't allocate frame\n");
  105311. return;
  105312. }
  105313. if(!FLAC__bitwriter_init(frame)) {
  105314. fprintf(stderr, "EST: can't init frame\n");
  105315. return;
  105316. }
  105317. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  105318. FLAC__ASSERT(ret);
  105319. {
  105320. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  105321. if(estimate != actual)
  105322. 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);
  105323. }
  105324. FLAC__bitwriter_delete(frame);
  105325. }
  105326. #endif
  105327. unsigned evaluate_constant_subframe_(
  105328. FLAC__StreamEncoder *encoder,
  105329. const FLAC__int32 signal,
  105330. unsigned blocksize,
  105331. unsigned subframe_bps,
  105332. FLAC__Subframe *subframe
  105333. )
  105334. {
  105335. unsigned estimate;
  105336. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  105337. subframe->data.constant.value = signal;
  105338. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  105339. #if SPOTCHECK_ESTIMATE
  105340. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105341. #else
  105342. (void)encoder, (void)blocksize;
  105343. #endif
  105344. return estimate;
  105345. }
  105346. unsigned evaluate_fixed_subframe_(
  105347. FLAC__StreamEncoder *encoder,
  105348. const FLAC__int32 signal[],
  105349. FLAC__int32 residual[],
  105350. FLAC__uint64 abs_residual_partition_sums[],
  105351. unsigned raw_bits_per_partition[],
  105352. unsigned blocksize,
  105353. unsigned subframe_bps,
  105354. unsigned order,
  105355. unsigned rice_parameter,
  105356. unsigned rice_parameter_limit,
  105357. unsigned min_partition_order,
  105358. unsigned max_partition_order,
  105359. FLAC__bool do_escape_coding,
  105360. unsigned rice_parameter_search_dist,
  105361. FLAC__Subframe *subframe,
  105362. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105363. )
  105364. {
  105365. unsigned i, residual_bits, estimate;
  105366. const unsigned residual_samples = blocksize - order;
  105367. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  105368. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  105369. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105370. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105371. subframe->data.fixed.residual = residual;
  105372. residual_bits =
  105373. find_best_partition_order_(
  105374. encoder->private_,
  105375. residual,
  105376. abs_residual_partition_sums,
  105377. raw_bits_per_partition,
  105378. residual_samples,
  105379. order,
  105380. rice_parameter,
  105381. rice_parameter_limit,
  105382. min_partition_order,
  105383. max_partition_order,
  105384. subframe_bps,
  105385. do_escape_coding,
  105386. rice_parameter_search_dist,
  105387. &subframe->data.fixed.entropy_coding_method
  105388. );
  105389. subframe->data.fixed.order = order;
  105390. for(i = 0; i < order; i++)
  105391. subframe->data.fixed.warmup[i] = signal[i];
  105392. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  105393. #if SPOTCHECK_ESTIMATE
  105394. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105395. #endif
  105396. return estimate;
  105397. }
  105398. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105399. unsigned evaluate_lpc_subframe_(
  105400. FLAC__StreamEncoder *encoder,
  105401. const FLAC__int32 signal[],
  105402. FLAC__int32 residual[],
  105403. FLAC__uint64 abs_residual_partition_sums[],
  105404. unsigned raw_bits_per_partition[],
  105405. const FLAC__real lp_coeff[],
  105406. unsigned blocksize,
  105407. unsigned subframe_bps,
  105408. unsigned order,
  105409. unsigned qlp_coeff_precision,
  105410. unsigned rice_parameter,
  105411. unsigned rice_parameter_limit,
  105412. unsigned min_partition_order,
  105413. unsigned max_partition_order,
  105414. FLAC__bool do_escape_coding,
  105415. unsigned rice_parameter_search_dist,
  105416. FLAC__Subframe *subframe,
  105417. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105418. )
  105419. {
  105420. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  105421. unsigned i, residual_bits, estimate;
  105422. int quantization, ret;
  105423. const unsigned residual_samples = blocksize - order;
  105424. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  105425. if(subframe_bps <= 16) {
  105426. FLAC__ASSERT(order > 0);
  105427. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  105428. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  105429. }
  105430. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  105431. if(ret != 0)
  105432. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  105433. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  105434. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  105435. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105436. else
  105437. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105438. else
  105439. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105440. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  105441. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105442. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105443. subframe->data.lpc.residual = residual;
  105444. residual_bits =
  105445. find_best_partition_order_(
  105446. encoder->private_,
  105447. residual,
  105448. abs_residual_partition_sums,
  105449. raw_bits_per_partition,
  105450. residual_samples,
  105451. order,
  105452. rice_parameter,
  105453. rice_parameter_limit,
  105454. min_partition_order,
  105455. max_partition_order,
  105456. subframe_bps,
  105457. do_escape_coding,
  105458. rice_parameter_search_dist,
  105459. &subframe->data.lpc.entropy_coding_method
  105460. );
  105461. subframe->data.lpc.order = order;
  105462. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  105463. subframe->data.lpc.quantization_level = quantization;
  105464. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  105465. for(i = 0; i < order; i++)
  105466. subframe->data.lpc.warmup[i] = signal[i];
  105467. 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;
  105468. #if SPOTCHECK_ESTIMATE
  105469. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105470. #endif
  105471. return estimate;
  105472. }
  105473. #endif
  105474. unsigned evaluate_verbatim_subframe_(
  105475. FLAC__StreamEncoder *encoder,
  105476. const FLAC__int32 signal[],
  105477. unsigned blocksize,
  105478. unsigned subframe_bps,
  105479. FLAC__Subframe *subframe
  105480. )
  105481. {
  105482. unsigned estimate;
  105483. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  105484. subframe->data.verbatim.data = signal;
  105485. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  105486. #if SPOTCHECK_ESTIMATE
  105487. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105488. #else
  105489. (void)encoder;
  105490. #endif
  105491. return estimate;
  105492. }
  105493. unsigned find_best_partition_order_(
  105494. FLAC__StreamEncoderPrivate *private_,
  105495. const FLAC__int32 residual[],
  105496. FLAC__uint64 abs_residual_partition_sums[],
  105497. unsigned raw_bits_per_partition[],
  105498. unsigned residual_samples,
  105499. unsigned predictor_order,
  105500. unsigned rice_parameter,
  105501. unsigned rice_parameter_limit,
  105502. unsigned min_partition_order,
  105503. unsigned max_partition_order,
  105504. unsigned bps,
  105505. FLAC__bool do_escape_coding,
  105506. unsigned rice_parameter_search_dist,
  105507. FLAC__EntropyCodingMethod *best_ecm
  105508. )
  105509. {
  105510. unsigned residual_bits, best_residual_bits = 0;
  105511. unsigned best_parameters_index = 0;
  105512. unsigned best_partition_order = 0;
  105513. const unsigned blocksize = residual_samples + predictor_order;
  105514. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  105515. min_partition_order = min(min_partition_order, max_partition_order);
  105516. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  105517. if(do_escape_coding)
  105518. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  105519. {
  105520. int partition_order;
  105521. unsigned sum;
  105522. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  105523. if(!
  105524. set_partitioned_rice_(
  105525. #ifdef EXACT_RICE_BITS_CALCULATION
  105526. residual,
  105527. #endif
  105528. abs_residual_partition_sums+sum,
  105529. raw_bits_per_partition+sum,
  105530. residual_samples,
  105531. predictor_order,
  105532. rice_parameter,
  105533. rice_parameter_limit,
  105534. rice_parameter_search_dist,
  105535. (unsigned)partition_order,
  105536. do_escape_coding,
  105537. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  105538. &residual_bits
  105539. )
  105540. )
  105541. {
  105542. FLAC__ASSERT(best_residual_bits != 0);
  105543. break;
  105544. }
  105545. sum += 1u << partition_order;
  105546. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  105547. best_residual_bits = residual_bits;
  105548. best_parameters_index = !best_parameters_index;
  105549. best_partition_order = partition_order;
  105550. }
  105551. }
  105552. }
  105553. best_ecm->data.partitioned_rice.order = best_partition_order;
  105554. {
  105555. /*
  105556. * We are allowed to de-const the pointer based on our special
  105557. * knowledge; it is const to the outside world.
  105558. */
  105559. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  105560. unsigned partition;
  105561. /* save best parameters and raw_bits */
  105562. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  105563. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  105564. if(do_escape_coding)
  105565. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  105566. /*
  105567. * Now need to check if the type should be changed to
  105568. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  105569. * size of the rice parameters.
  105570. */
  105571. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  105572. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  105573. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  105574. break;
  105575. }
  105576. }
  105577. }
  105578. return best_residual_bits;
  105579. }
  105580. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105581. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  105582. const FLAC__int32 residual[],
  105583. FLAC__uint64 abs_residual_partition_sums[],
  105584. unsigned blocksize,
  105585. unsigned predictor_order,
  105586. unsigned min_partition_order,
  105587. unsigned max_partition_order
  105588. );
  105589. #endif
  105590. void precompute_partition_info_sums_(
  105591. const FLAC__int32 residual[],
  105592. FLAC__uint64 abs_residual_partition_sums[],
  105593. unsigned residual_samples,
  105594. unsigned predictor_order,
  105595. unsigned min_partition_order,
  105596. unsigned max_partition_order,
  105597. unsigned bps
  105598. )
  105599. {
  105600. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  105601. unsigned partitions = 1u << max_partition_order;
  105602. FLAC__ASSERT(default_partition_samples > predictor_order);
  105603. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105604. /* slightly pessimistic but still catches all common cases */
  105605. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105606. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105607. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  105608. return;
  105609. }
  105610. #endif
  105611. /* first do max_partition_order */
  105612. {
  105613. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  105614. /* slightly pessimistic but still catches all common cases */
  105615. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105616. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105617. FLAC__uint32 abs_residual_partition_sum;
  105618. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105619. end += default_partition_samples;
  105620. abs_residual_partition_sum = 0;
  105621. for( ; residual_sample < end; residual_sample++)
  105622. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105623. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105624. }
  105625. }
  105626. else { /* have to pessimistically use 64 bits for accumulator */
  105627. FLAC__uint64 abs_residual_partition_sum;
  105628. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105629. end += default_partition_samples;
  105630. abs_residual_partition_sum = 0;
  105631. for( ; residual_sample < end; residual_sample++)
  105632. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105633. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105634. }
  105635. }
  105636. }
  105637. /* now merge partitions for lower orders */
  105638. {
  105639. unsigned from_partition = 0, to_partition = partitions;
  105640. int partition_order;
  105641. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  105642. unsigned i;
  105643. partitions >>= 1;
  105644. for(i = 0; i < partitions; i++) {
  105645. abs_residual_partition_sums[to_partition++] =
  105646. abs_residual_partition_sums[from_partition ] +
  105647. abs_residual_partition_sums[from_partition+1];
  105648. from_partition += 2;
  105649. }
  105650. }
  105651. }
  105652. }
  105653. void precompute_partition_info_escapes_(
  105654. const FLAC__int32 residual[],
  105655. unsigned raw_bits_per_partition[],
  105656. unsigned residual_samples,
  105657. unsigned predictor_order,
  105658. unsigned min_partition_order,
  105659. unsigned max_partition_order
  105660. )
  105661. {
  105662. int partition_order;
  105663. unsigned from_partition, to_partition = 0;
  105664. const unsigned blocksize = residual_samples + predictor_order;
  105665. /* first do max_partition_order */
  105666. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  105667. FLAC__int32 r;
  105668. FLAC__uint32 rmax;
  105669. unsigned partition, partition_sample, partition_samples, residual_sample;
  105670. const unsigned partitions = 1u << partition_order;
  105671. const unsigned default_partition_samples = blocksize >> partition_order;
  105672. FLAC__ASSERT(default_partition_samples > predictor_order);
  105673. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105674. partition_samples = default_partition_samples;
  105675. if(partition == 0)
  105676. partition_samples -= predictor_order;
  105677. rmax = 0;
  105678. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  105679. r = residual[residual_sample++];
  105680. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  105681. if(r < 0)
  105682. rmax |= ~r;
  105683. else
  105684. rmax |= r;
  105685. }
  105686. /* now we know all residual values are in the range [-rmax-1,rmax] */
  105687. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  105688. }
  105689. to_partition = partitions;
  105690. break; /*@@@ yuck, should remove the 'for' loop instead */
  105691. }
  105692. /* now merge partitions for lower orders */
  105693. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  105694. unsigned m;
  105695. unsigned i;
  105696. const unsigned partitions = 1u << partition_order;
  105697. for(i = 0; i < partitions; i++) {
  105698. m = raw_bits_per_partition[from_partition];
  105699. from_partition++;
  105700. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  105701. from_partition++;
  105702. to_partition++;
  105703. }
  105704. }
  105705. }
  105706. #ifdef EXACT_RICE_BITS_CALCULATION
  105707. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105708. const unsigned rice_parameter,
  105709. const unsigned partition_samples,
  105710. const FLAC__int32 *residual
  105711. )
  105712. {
  105713. unsigned i, partition_bits =
  105714. 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 */
  105715. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  105716. ;
  105717. for(i = 0; i < partition_samples; i++)
  105718. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  105719. return partition_bits;
  105720. }
  105721. #else
  105722. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105723. const unsigned rice_parameter,
  105724. const unsigned partition_samples,
  105725. const FLAC__uint64 abs_residual_partition_sum
  105726. )
  105727. {
  105728. return
  105729. 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 */
  105730. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  105731. (
  105732. rice_parameter?
  105733. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  105734. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  105735. )
  105736. - (partition_samples >> 1)
  105737. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  105738. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  105739. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  105740. * So the subtraction term tries to guess how many extra bits were contributed.
  105741. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  105742. */
  105743. ;
  105744. }
  105745. #endif
  105746. FLAC__bool set_partitioned_rice_(
  105747. #ifdef EXACT_RICE_BITS_CALCULATION
  105748. const FLAC__int32 residual[],
  105749. #endif
  105750. const FLAC__uint64 abs_residual_partition_sums[],
  105751. const unsigned raw_bits_per_partition[],
  105752. const unsigned residual_samples,
  105753. const unsigned predictor_order,
  105754. const unsigned suggested_rice_parameter,
  105755. const unsigned rice_parameter_limit,
  105756. const unsigned rice_parameter_search_dist,
  105757. const unsigned partition_order,
  105758. const FLAC__bool search_for_escapes,
  105759. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  105760. unsigned *bits
  105761. )
  105762. {
  105763. unsigned rice_parameter, partition_bits;
  105764. unsigned best_partition_bits, best_rice_parameter = 0;
  105765. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  105766. unsigned *parameters, *raw_bits;
  105767. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105768. unsigned min_rice_parameter, max_rice_parameter;
  105769. #else
  105770. (void)rice_parameter_search_dist;
  105771. #endif
  105772. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105773. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  105774. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  105775. parameters = partitioned_rice_contents->parameters;
  105776. raw_bits = partitioned_rice_contents->raw_bits;
  105777. if(partition_order == 0) {
  105778. best_partition_bits = (unsigned)(-1);
  105779. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105780. if(rice_parameter_search_dist) {
  105781. if(suggested_rice_parameter < rice_parameter_search_dist)
  105782. min_rice_parameter = 0;
  105783. else
  105784. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  105785. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  105786. if(max_rice_parameter >= rice_parameter_limit) {
  105787. #ifdef DEBUG_VERBOSE
  105788. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  105789. #endif
  105790. max_rice_parameter = rice_parameter_limit - 1;
  105791. }
  105792. }
  105793. else
  105794. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  105795. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105796. #else
  105797. rice_parameter = suggested_rice_parameter;
  105798. #endif
  105799. #ifdef EXACT_RICE_BITS_CALCULATION
  105800. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  105801. #else
  105802. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  105803. #endif
  105804. if(partition_bits < best_partition_bits) {
  105805. best_rice_parameter = rice_parameter;
  105806. best_partition_bits = partition_bits;
  105807. }
  105808. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105809. }
  105810. #endif
  105811. if(search_for_escapes) {
  105812. 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;
  105813. if(partition_bits <= best_partition_bits) {
  105814. raw_bits[0] = raw_bits_per_partition[0];
  105815. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  105816. best_partition_bits = partition_bits;
  105817. }
  105818. else
  105819. raw_bits[0] = 0;
  105820. }
  105821. parameters[0] = best_rice_parameter;
  105822. bits_ += best_partition_bits;
  105823. }
  105824. else {
  105825. unsigned partition, residual_sample;
  105826. unsigned partition_samples;
  105827. FLAC__uint64 mean, k;
  105828. const unsigned partitions = 1u << partition_order;
  105829. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105830. partition_samples = (residual_samples+predictor_order) >> partition_order;
  105831. if(partition == 0) {
  105832. if(partition_samples <= predictor_order)
  105833. return false;
  105834. else
  105835. partition_samples -= predictor_order;
  105836. }
  105837. mean = abs_residual_partition_sums[partition];
  105838. /* we are basically calculating the size in bits of the
  105839. * average residual magnitude in the partition:
  105840. * rice_parameter = floor(log2(mean/partition_samples))
  105841. * 'mean' is not a good name for the variable, it is
  105842. * actually the sum of magnitudes of all residual values
  105843. * in the partition, so the actual mean is
  105844. * mean/partition_samples
  105845. */
  105846. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  105847. ;
  105848. if(rice_parameter >= rice_parameter_limit) {
  105849. #ifdef DEBUG_VERBOSE
  105850. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  105851. #endif
  105852. rice_parameter = rice_parameter_limit - 1;
  105853. }
  105854. best_partition_bits = (unsigned)(-1);
  105855. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105856. if(rice_parameter_search_dist) {
  105857. if(rice_parameter < rice_parameter_search_dist)
  105858. min_rice_parameter = 0;
  105859. else
  105860. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  105861. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  105862. if(max_rice_parameter >= rice_parameter_limit) {
  105863. #ifdef DEBUG_VERBOSE
  105864. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  105865. #endif
  105866. max_rice_parameter = rice_parameter_limit - 1;
  105867. }
  105868. }
  105869. else
  105870. min_rice_parameter = max_rice_parameter = rice_parameter;
  105871. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  105872. #endif
  105873. #ifdef EXACT_RICE_BITS_CALCULATION
  105874. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  105875. #else
  105876. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  105877. #endif
  105878. if(partition_bits < best_partition_bits) {
  105879. best_rice_parameter = rice_parameter;
  105880. best_partition_bits = partition_bits;
  105881. }
  105882. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105883. }
  105884. #endif
  105885. if(search_for_escapes) {
  105886. 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;
  105887. if(partition_bits <= best_partition_bits) {
  105888. raw_bits[partition] = raw_bits_per_partition[partition];
  105889. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  105890. best_partition_bits = partition_bits;
  105891. }
  105892. else
  105893. raw_bits[partition] = 0;
  105894. }
  105895. parameters[partition] = best_rice_parameter;
  105896. bits_ += best_partition_bits;
  105897. residual_sample += partition_samples;
  105898. }
  105899. }
  105900. *bits = bits_;
  105901. return true;
  105902. }
  105903. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  105904. {
  105905. unsigned i, shift;
  105906. FLAC__int32 x = 0;
  105907. for(i = 0; i < samples && !(x&1); i++)
  105908. x |= signal[i];
  105909. if(x == 0) {
  105910. shift = 0;
  105911. }
  105912. else {
  105913. for(shift = 0; !(x&1); shift++)
  105914. x >>= 1;
  105915. }
  105916. if(shift > 0) {
  105917. for(i = 0; i < samples; i++)
  105918. signal[i] >>= shift;
  105919. }
  105920. return shift;
  105921. }
  105922. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  105923. {
  105924. unsigned channel;
  105925. for(channel = 0; channel < channels; channel++)
  105926. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  105927. fifo->tail += wide_samples;
  105928. FLAC__ASSERT(fifo->tail <= fifo->size);
  105929. }
  105930. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  105931. {
  105932. unsigned channel;
  105933. unsigned sample, wide_sample;
  105934. unsigned tail = fifo->tail;
  105935. sample = input_offset * channels;
  105936. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  105937. for(channel = 0; channel < channels; channel++)
  105938. fifo->data[channel][tail] = input[sample++];
  105939. tail++;
  105940. }
  105941. fifo->tail = tail;
  105942. FLAC__ASSERT(fifo->tail <= fifo->size);
  105943. }
  105944. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  105945. {
  105946. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  105947. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  105948. (void)decoder;
  105949. if(encoder->private_->verify.needs_magic_hack) {
  105950. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  105951. *bytes = FLAC__STREAM_SYNC_LENGTH;
  105952. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  105953. encoder->private_->verify.needs_magic_hack = false;
  105954. }
  105955. else {
  105956. if(encoded_bytes == 0) {
  105957. /*
  105958. * If we get here, a FIFO underflow has occurred,
  105959. * which means there is a bug somewhere.
  105960. */
  105961. FLAC__ASSERT(0);
  105962. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  105963. }
  105964. else if(encoded_bytes < *bytes)
  105965. *bytes = encoded_bytes;
  105966. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  105967. encoder->private_->verify.output.data += *bytes;
  105968. encoder->private_->verify.output.bytes -= *bytes;
  105969. }
  105970. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  105971. }
  105972. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  105973. {
  105974. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  105975. unsigned channel;
  105976. const unsigned channels = frame->header.channels;
  105977. const unsigned blocksize = frame->header.blocksize;
  105978. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  105979. (void)decoder;
  105980. for(channel = 0; channel < channels; channel++) {
  105981. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  105982. unsigned i, sample = 0;
  105983. FLAC__int32 expect = 0, got = 0;
  105984. for(i = 0; i < blocksize; i++) {
  105985. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  105986. sample = i;
  105987. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  105988. got = (FLAC__int32)buffer[channel][i];
  105989. break;
  105990. }
  105991. }
  105992. FLAC__ASSERT(i < blocksize);
  105993. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  105994. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  105995. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  105996. encoder->private_->verify.error_stats.channel = channel;
  105997. encoder->private_->verify.error_stats.sample = sample;
  105998. encoder->private_->verify.error_stats.expected = expect;
  105999. encoder->private_->verify.error_stats.got = got;
  106000. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  106001. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  106002. }
  106003. }
  106004. /* dequeue the frame from the fifo */
  106005. encoder->private_->verify.input_fifo.tail -= blocksize;
  106006. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  106007. for(channel = 0; channel < channels; channel++)
  106008. 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]));
  106009. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  106010. }
  106011. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  106012. {
  106013. (void)decoder, (void)metadata, (void)client_data;
  106014. }
  106015. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  106016. {
  106017. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  106018. (void)decoder, (void)status;
  106019. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  106020. }
  106021. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  106022. {
  106023. (void)client_data;
  106024. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  106025. if (*bytes == 0) {
  106026. if (feof(encoder->private_->file))
  106027. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  106028. else if (ferror(encoder->private_->file))
  106029. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  106030. }
  106031. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  106032. }
  106033. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  106034. {
  106035. (void)client_data;
  106036. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  106037. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  106038. else
  106039. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  106040. }
  106041. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  106042. {
  106043. off_t offset;
  106044. (void)client_data;
  106045. offset = ftello(encoder->private_->file);
  106046. if(offset < 0) {
  106047. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  106048. }
  106049. else {
  106050. *absolute_byte_offset = (FLAC__uint64)offset;
  106051. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  106052. }
  106053. }
  106054. #ifdef FLAC__VALGRIND_TESTING
  106055. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  106056. {
  106057. size_t ret = fwrite(ptr, size, nmemb, stream);
  106058. if(!ferror(stream))
  106059. fflush(stream);
  106060. return ret;
  106061. }
  106062. #else
  106063. #define local__fwrite fwrite
  106064. #endif
  106065. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  106066. {
  106067. (void)client_data, (void)current_frame;
  106068. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  106069. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  106070. #if FLAC__HAS_OGG
  106071. /* We would like to be able to use 'samples > 0' in the
  106072. * clause here but currently because of the nature of our
  106073. * Ogg writing implementation, 'samples' is always 0 (see
  106074. * ogg_encoder_aspect.c). The downside is extra progress
  106075. * callbacks.
  106076. */
  106077. encoder->private_->is_ogg? true :
  106078. #endif
  106079. samples > 0
  106080. );
  106081. if(call_it) {
  106082. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  106083. * because at this point in the callback chain, the stats
  106084. * have not been updated. Only after we return and control
  106085. * gets back to write_frame_() are the stats updated
  106086. */
  106087. 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);
  106088. }
  106089. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  106090. }
  106091. else
  106092. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  106093. }
  106094. /*
  106095. * This will forcibly set stdout to binary mode (for OSes that require it)
  106096. */
  106097. FILE *get_binary_stdout_(void)
  106098. {
  106099. /* if something breaks here it is probably due to the presence or
  106100. * absence of an underscore before the identifiers 'setmode',
  106101. * 'fileno', and/or 'O_BINARY'; check your system header files.
  106102. */
  106103. #if defined _MSC_VER || defined __MINGW32__
  106104. _setmode(_fileno(stdout), _O_BINARY);
  106105. #elif defined __CYGWIN__
  106106. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  106107. setmode(_fileno(stdout), _O_BINARY);
  106108. #elif defined __EMX__
  106109. setmode(fileno(stdout), O_BINARY);
  106110. #endif
  106111. return stdout;
  106112. }
  106113. #endif
  106114. /*** End of inlined file: stream_encoder.c ***/
  106115. /*** Start of inlined file: stream_encoder_framing.c ***/
  106116. /*** Start of inlined file: juce_FlacHeader.h ***/
  106117. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106118. // tasks..
  106119. #define VERSION "1.2.1"
  106120. #define FLAC__NO_DLL 1
  106121. #if JUCE_MSVC
  106122. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106123. #endif
  106124. #if JUCE_MAC
  106125. #define FLAC__SYS_DARWIN 1
  106126. #endif
  106127. /*** End of inlined file: juce_FlacHeader.h ***/
  106128. #if JUCE_USE_FLAC
  106129. #if HAVE_CONFIG_H
  106130. # include <config.h>
  106131. #endif
  106132. #include <stdio.h>
  106133. #include <string.h> /* for strlen() */
  106134. #ifdef max
  106135. #undef max
  106136. #endif
  106137. #define max(x,y) ((x)>(y)?(x):(y))
  106138. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  106139. 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);
  106140. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  106141. {
  106142. unsigned i, j;
  106143. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  106144. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  106145. return false;
  106146. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  106147. return false;
  106148. /*
  106149. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  106150. */
  106151. i = metadata->length;
  106152. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  106153. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  106154. i -= metadata->data.vorbis_comment.vendor_string.length;
  106155. i += vendor_string_length;
  106156. }
  106157. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  106158. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  106159. return false;
  106160. switch(metadata->type) {
  106161. case FLAC__METADATA_TYPE_STREAMINFO:
  106162. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  106163. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  106164. return false;
  106165. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  106166. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  106167. return false;
  106168. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  106169. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  106170. return false;
  106171. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  106172. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  106173. return false;
  106174. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  106175. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  106176. return false;
  106177. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  106178. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  106179. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  106180. return false;
  106181. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  106182. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  106183. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  106184. return false;
  106185. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  106186. return false;
  106187. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  106188. return false;
  106189. break;
  106190. case FLAC__METADATA_TYPE_PADDING:
  106191. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  106192. return false;
  106193. break;
  106194. case FLAC__METADATA_TYPE_APPLICATION:
  106195. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  106196. return false;
  106197. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  106198. return false;
  106199. break;
  106200. case FLAC__METADATA_TYPE_SEEKTABLE:
  106201. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  106202. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  106203. return false;
  106204. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  106205. return false;
  106206. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  106207. return false;
  106208. }
  106209. break;
  106210. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  106211. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  106212. return false;
  106213. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  106214. return false;
  106215. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  106216. return false;
  106217. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  106218. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  106219. return false;
  106220. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  106221. return false;
  106222. }
  106223. break;
  106224. case FLAC__METADATA_TYPE_CUESHEET:
  106225. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  106226. 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))
  106227. return false;
  106228. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  106229. return false;
  106230. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  106231. return false;
  106232. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  106233. return false;
  106234. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  106235. return false;
  106236. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  106237. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  106238. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  106239. return false;
  106240. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  106241. return false;
  106242. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  106243. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  106244. return false;
  106245. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  106246. return false;
  106247. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  106248. return false;
  106249. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  106250. return false;
  106251. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  106252. return false;
  106253. for(j = 0; j < track->num_indices; j++) {
  106254. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  106255. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  106256. return false;
  106257. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  106258. return false;
  106259. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  106260. return false;
  106261. }
  106262. }
  106263. break;
  106264. case FLAC__METADATA_TYPE_PICTURE:
  106265. {
  106266. size_t len;
  106267. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  106268. return false;
  106269. len = strlen(metadata->data.picture.mime_type);
  106270. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  106271. return false;
  106272. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  106273. return false;
  106274. len = strlen((const char *)metadata->data.picture.description);
  106275. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  106276. return false;
  106277. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  106278. return false;
  106279. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  106280. return false;
  106281. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  106282. return false;
  106283. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  106284. return false;
  106285. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  106286. return false;
  106287. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  106288. return false;
  106289. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  106290. return false;
  106291. }
  106292. break;
  106293. default:
  106294. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  106295. return false;
  106296. break;
  106297. }
  106298. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  106299. return true;
  106300. }
  106301. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  106302. {
  106303. unsigned u, blocksize_hint, sample_rate_hint;
  106304. FLAC__byte crc;
  106305. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  106306. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  106307. return false;
  106308. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  106309. return false;
  106310. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  106311. return false;
  106312. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  106313. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  106314. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  106315. blocksize_hint = 0;
  106316. switch(header->blocksize) {
  106317. case 192: u = 1; break;
  106318. case 576: u = 2; break;
  106319. case 1152: u = 3; break;
  106320. case 2304: u = 4; break;
  106321. case 4608: u = 5; break;
  106322. case 256: u = 8; break;
  106323. case 512: u = 9; break;
  106324. case 1024: u = 10; break;
  106325. case 2048: u = 11; break;
  106326. case 4096: u = 12; break;
  106327. case 8192: u = 13; break;
  106328. case 16384: u = 14; break;
  106329. case 32768: u = 15; break;
  106330. default:
  106331. if(header->blocksize <= 0x100)
  106332. blocksize_hint = u = 6;
  106333. else
  106334. blocksize_hint = u = 7;
  106335. break;
  106336. }
  106337. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  106338. return false;
  106339. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  106340. sample_rate_hint = 0;
  106341. switch(header->sample_rate) {
  106342. case 88200: u = 1; break;
  106343. case 176400: u = 2; break;
  106344. case 192000: u = 3; break;
  106345. case 8000: u = 4; break;
  106346. case 16000: u = 5; break;
  106347. case 22050: u = 6; break;
  106348. case 24000: u = 7; break;
  106349. case 32000: u = 8; break;
  106350. case 44100: u = 9; break;
  106351. case 48000: u = 10; break;
  106352. case 96000: u = 11; break;
  106353. default:
  106354. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  106355. sample_rate_hint = u = 12;
  106356. else if(header->sample_rate % 10 == 0)
  106357. sample_rate_hint = u = 14;
  106358. else if(header->sample_rate <= 0xffff)
  106359. sample_rate_hint = u = 13;
  106360. else
  106361. u = 0;
  106362. break;
  106363. }
  106364. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  106365. return false;
  106366. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  106367. switch(header->channel_assignment) {
  106368. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  106369. u = header->channels - 1;
  106370. break;
  106371. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  106372. FLAC__ASSERT(header->channels == 2);
  106373. u = 8;
  106374. break;
  106375. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  106376. FLAC__ASSERT(header->channels == 2);
  106377. u = 9;
  106378. break;
  106379. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  106380. FLAC__ASSERT(header->channels == 2);
  106381. u = 10;
  106382. break;
  106383. default:
  106384. FLAC__ASSERT(0);
  106385. }
  106386. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  106387. return false;
  106388. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  106389. switch(header->bits_per_sample) {
  106390. case 8 : u = 1; break;
  106391. case 12: u = 2; break;
  106392. case 16: u = 4; break;
  106393. case 20: u = 5; break;
  106394. case 24: u = 6; break;
  106395. default: u = 0; break;
  106396. }
  106397. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  106398. return false;
  106399. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  106400. return false;
  106401. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  106402. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  106403. return false;
  106404. }
  106405. else {
  106406. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  106407. return false;
  106408. }
  106409. if(blocksize_hint)
  106410. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  106411. return false;
  106412. switch(sample_rate_hint) {
  106413. case 12:
  106414. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  106415. return false;
  106416. break;
  106417. case 13:
  106418. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  106419. return false;
  106420. break;
  106421. case 14:
  106422. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  106423. return false;
  106424. break;
  106425. }
  106426. /* write the CRC */
  106427. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  106428. return false;
  106429. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  106430. return false;
  106431. return true;
  106432. }
  106433. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106434. {
  106435. FLAC__bool ok;
  106436. ok =
  106437. 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) &&
  106438. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  106439. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  106440. ;
  106441. return ok;
  106442. }
  106443. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106444. {
  106445. unsigned i;
  106446. 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))
  106447. return false;
  106448. if(wasted_bits)
  106449. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106450. return false;
  106451. for(i = 0; i < subframe->order; i++)
  106452. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106453. return false;
  106454. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106455. return false;
  106456. switch(subframe->entropy_coding_method.type) {
  106457. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106458. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106459. if(!add_residual_partitioned_rice_(
  106460. bw,
  106461. subframe->residual,
  106462. residual_samples,
  106463. subframe->order,
  106464. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106465. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106466. subframe->entropy_coding_method.data.partitioned_rice.order,
  106467. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106468. ))
  106469. return false;
  106470. break;
  106471. default:
  106472. FLAC__ASSERT(0);
  106473. }
  106474. return true;
  106475. }
  106476. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106477. {
  106478. unsigned i;
  106479. 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))
  106480. return false;
  106481. if(wasted_bits)
  106482. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106483. return false;
  106484. for(i = 0; i < subframe->order; i++)
  106485. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106486. return false;
  106487. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  106488. return false;
  106489. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  106490. return false;
  106491. for(i = 0; i < subframe->order; i++)
  106492. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  106493. return false;
  106494. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106495. return false;
  106496. switch(subframe->entropy_coding_method.type) {
  106497. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106498. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106499. if(!add_residual_partitioned_rice_(
  106500. bw,
  106501. subframe->residual,
  106502. residual_samples,
  106503. subframe->order,
  106504. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106505. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106506. subframe->entropy_coding_method.data.partitioned_rice.order,
  106507. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106508. ))
  106509. return false;
  106510. break;
  106511. default:
  106512. FLAC__ASSERT(0);
  106513. }
  106514. return true;
  106515. }
  106516. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106517. {
  106518. unsigned i;
  106519. const FLAC__int32 *signal = subframe->data;
  106520. 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))
  106521. return false;
  106522. if(wasted_bits)
  106523. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106524. return false;
  106525. for(i = 0; i < samples; i++)
  106526. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  106527. return false;
  106528. return true;
  106529. }
  106530. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  106531. {
  106532. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  106533. return false;
  106534. switch(method->type) {
  106535. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106536. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106537. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  106538. return false;
  106539. break;
  106540. default:
  106541. FLAC__ASSERT(0);
  106542. }
  106543. return true;
  106544. }
  106545. 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)
  106546. {
  106547. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  106548. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  106549. if(partition_order == 0) {
  106550. unsigned i;
  106551. if(raw_bits[0] == 0) {
  106552. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  106553. return false;
  106554. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  106555. return false;
  106556. }
  106557. else {
  106558. FLAC__ASSERT(rice_parameters[0] == 0);
  106559. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106560. return false;
  106561. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106562. return false;
  106563. for(i = 0; i < residual_samples; i++) {
  106564. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  106565. return false;
  106566. }
  106567. }
  106568. return true;
  106569. }
  106570. else {
  106571. unsigned i, j, k = 0, k_last = 0;
  106572. unsigned partition_samples;
  106573. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  106574. for(i = 0; i < (1u<<partition_order); i++) {
  106575. partition_samples = default_partition_samples;
  106576. if(i == 0)
  106577. partition_samples -= predictor_order;
  106578. k += partition_samples;
  106579. if(raw_bits[i] == 0) {
  106580. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  106581. return false;
  106582. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  106583. return false;
  106584. }
  106585. else {
  106586. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106587. return false;
  106588. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106589. return false;
  106590. for(j = k_last; j < k; j++) {
  106591. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  106592. return false;
  106593. }
  106594. }
  106595. k_last = k;
  106596. }
  106597. return true;
  106598. }
  106599. }
  106600. #endif
  106601. /*** End of inlined file: stream_encoder_framing.c ***/
  106602. /*** Start of inlined file: window_flac.c ***/
  106603. /*** Start of inlined file: juce_FlacHeader.h ***/
  106604. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106605. // tasks..
  106606. #define VERSION "1.2.1"
  106607. #define FLAC__NO_DLL 1
  106608. #if JUCE_MSVC
  106609. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106610. #endif
  106611. #if JUCE_MAC
  106612. #define FLAC__SYS_DARWIN 1
  106613. #endif
  106614. /*** End of inlined file: juce_FlacHeader.h ***/
  106615. #if JUCE_USE_FLAC
  106616. #if HAVE_CONFIG_H
  106617. # include <config.h>
  106618. #endif
  106619. #include <math.h>
  106620. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  106621. #ifndef M_PI
  106622. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  106623. #define M_PI 3.14159265358979323846
  106624. #endif
  106625. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  106626. {
  106627. const FLAC__int32 N = L - 1;
  106628. FLAC__int32 n;
  106629. if (L & 1) {
  106630. for (n = 0; n <= N/2; n++)
  106631. window[n] = 2.0f * n / (float)N;
  106632. for (; n <= N; n++)
  106633. window[n] = 2.0f - 2.0f * n / (float)N;
  106634. }
  106635. else {
  106636. for (n = 0; n <= L/2-1; n++)
  106637. window[n] = 2.0f * n / (float)N;
  106638. for (; n <= N; n++)
  106639. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  106640. }
  106641. }
  106642. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  106643. {
  106644. const FLAC__int32 N = L - 1;
  106645. FLAC__int32 n;
  106646. for (n = 0; n < L; n++)
  106647. 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)));
  106648. }
  106649. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  106650. {
  106651. const FLAC__int32 N = L - 1;
  106652. FLAC__int32 n;
  106653. for (n = 0; n < L; n++)
  106654. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  106655. }
  106656. /* 4-term -92dB side-lobe */
  106657. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  106658. {
  106659. const FLAC__int32 N = L - 1;
  106660. FLAC__int32 n;
  106661. for (n = 0; n <= N; n++)
  106662. 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));
  106663. }
  106664. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  106665. {
  106666. const FLAC__int32 N = L - 1;
  106667. const double N2 = (double)N / 2.;
  106668. FLAC__int32 n;
  106669. for (n = 0; n <= N; n++) {
  106670. double k = ((double)n - N2) / N2;
  106671. k = 1.0f - k * k;
  106672. window[n] = (FLAC__real)(k * k);
  106673. }
  106674. }
  106675. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  106676. {
  106677. const FLAC__int32 N = L - 1;
  106678. FLAC__int32 n;
  106679. for (n = 0; n < L; n++)
  106680. 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));
  106681. }
  106682. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  106683. {
  106684. const FLAC__int32 N = L - 1;
  106685. const double N2 = (double)N / 2.;
  106686. FLAC__int32 n;
  106687. for (n = 0; n <= N; n++) {
  106688. const double k = ((double)n - N2) / (stddev * N2);
  106689. window[n] = (FLAC__real)exp(-0.5f * k * k);
  106690. }
  106691. }
  106692. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  106693. {
  106694. const FLAC__int32 N = L - 1;
  106695. FLAC__int32 n;
  106696. for (n = 0; n < L; n++)
  106697. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  106698. }
  106699. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  106700. {
  106701. const FLAC__int32 N = L - 1;
  106702. FLAC__int32 n;
  106703. for (n = 0; n < L; n++)
  106704. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  106705. }
  106706. void FLAC__window_kaiser_bessel(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)(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));
  106712. }
  106713. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  106714. {
  106715. const FLAC__int32 N = L - 1;
  106716. FLAC__int32 n;
  106717. for (n = 0; n < L; n++)
  106718. 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));
  106719. }
  106720. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  106721. {
  106722. FLAC__int32 n;
  106723. for (n = 0; n < L; n++)
  106724. window[n] = 1.0f;
  106725. }
  106726. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  106727. {
  106728. FLAC__int32 n;
  106729. if (L & 1) {
  106730. for (n = 1; n <= L+1/2; n++)
  106731. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  106732. for (; n <= L; n++)
  106733. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  106734. }
  106735. else {
  106736. for (n = 1; n <= L/2; n++)
  106737. window[n-1] = 2.0f * n / (float)L;
  106738. for (; n <= L; n++)
  106739. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  106740. }
  106741. }
  106742. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  106743. {
  106744. if (p <= 0.0)
  106745. FLAC__window_rectangle(window, L);
  106746. else if (p >= 1.0)
  106747. FLAC__window_hann(window, L);
  106748. else {
  106749. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  106750. FLAC__int32 n;
  106751. /* start with rectangle... */
  106752. FLAC__window_rectangle(window, L);
  106753. /* ...replace ends with hann */
  106754. if (Np > 0) {
  106755. for (n = 0; n <= Np; n++) {
  106756. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  106757. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  106758. }
  106759. }
  106760. }
  106761. }
  106762. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  106763. {
  106764. const FLAC__int32 N = L - 1;
  106765. const double N2 = (double)N / 2.;
  106766. FLAC__int32 n;
  106767. for (n = 0; n <= N; n++) {
  106768. const double k = ((double)n - N2) / N2;
  106769. window[n] = (FLAC__real)(1.0f - k * k);
  106770. }
  106771. }
  106772. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  106773. #endif
  106774. /*** End of inlined file: window_flac.c ***/
  106775. #else
  106776. #include <FLAC/all.h>
  106777. #endif
  106778. }
  106779. #undef max
  106780. #undef min
  106781. BEGIN_JUCE_NAMESPACE
  106782. static const char* const flacFormatName = "FLAC file";
  106783. static const char* const flacExtensions[] = { ".flac", 0 };
  106784. class FlacReader : public AudioFormatReader
  106785. {
  106786. public:
  106787. FlacReader (InputStream* const in)
  106788. : AudioFormatReader (in, TRANS (flacFormatName)),
  106789. reservoir (2, 0),
  106790. reservoirStart (0),
  106791. samplesInReservoir (0),
  106792. scanningForLength (false)
  106793. {
  106794. using namespace FlacNamespace;
  106795. lengthInSamples = 0;
  106796. decoder = FLAC__stream_decoder_new();
  106797. ok = FLAC__stream_decoder_init_stream (decoder,
  106798. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  106799. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  106800. this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  106801. if (ok)
  106802. {
  106803. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106804. if (lengthInSamples == 0 && sampleRate > 0)
  106805. {
  106806. // the length hasn't been stored in the metadata, so we'll need to
  106807. // work it out the length the hard way, by scanning the whole file..
  106808. scanningForLength = true;
  106809. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  106810. scanningForLength = false;
  106811. const int64 tempLength = lengthInSamples;
  106812. FLAC__stream_decoder_reset (decoder);
  106813. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  106814. lengthInSamples = tempLength;
  106815. }
  106816. }
  106817. }
  106818. ~FlacReader()
  106819. {
  106820. FlacNamespace::FLAC__stream_decoder_delete (decoder);
  106821. }
  106822. void useMetadata (const FlacNamespace::FLAC__StreamMetadata_StreamInfo& info)
  106823. {
  106824. sampleRate = info.sample_rate;
  106825. bitsPerSample = info.bits_per_sample;
  106826. lengthInSamples = (unsigned int) info.total_samples;
  106827. numChannels = info.channels;
  106828. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  106829. }
  106830. // returns the number of samples read
  106831. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  106832. int64 startSampleInFile, int numSamples)
  106833. {
  106834. using namespace FlacNamespace;
  106835. if (! ok)
  106836. return false;
  106837. while (numSamples > 0)
  106838. {
  106839. if (startSampleInFile >= reservoirStart
  106840. && startSampleInFile < reservoirStart + samplesInReservoir)
  106841. {
  106842. const int num = (int) jmin ((int64) numSamples,
  106843. reservoirStart + samplesInReservoir - startSampleInFile);
  106844. jassert (num > 0);
  106845. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  106846. if (destSamples[i] != 0)
  106847. memcpy (destSamples[i] + startOffsetInDestBuffer,
  106848. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  106849. sizeof (int) * num);
  106850. startOffsetInDestBuffer += num;
  106851. startSampleInFile += num;
  106852. numSamples -= num;
  106853. }
  106854. else
  106855. {
  106856. if (startSampleInFile >= (int) lengthInSamples)
  106857. {
  106858. samplesInReservoir = 0;
  106859. }
  106860. else if (startSampleInFile < reservoirStart
  106861. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  106862. {
  106863. // had some problems with flac crashing if the read pos is aligned more
  106864. // accurately than this. Probably fixed in newer versions of the library, though.
  106865. reservoirStart = (int) (startSampleInFile & ~511);
  106866. samplesInReservoir = 0;
  106867. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  106868. }
  106869. else
  106870. {
  106871. reservoirStart += samplesInReservoir;
  106872. samplesInReservoir = 0;
  106873. FLAC__stream_decoder_process_single (decoder);
  106874. }
  106875. if (samplesInReservoir == 0)
  106876. break;
  106877. }
  106878. }
  106879. if (numSamples > 0)
  106880. {
  106881. for (int i = numDestChannels; --i >= 0;)
  106882. if (destSamples[i] != 0)
  106883. zeromem (destSamples[i] + startOffsetInDestBuffer,
  106884. sizeof (int) * numSamples);
  106885. }
  106886. return true;
  106887. }
  106888. void useSamples (const FlacNamespace::FLAC__int32* const buffer[], int numSamples)
  106889. {
  106890. if (scanningForLength)
  106891. {
  106892. lengthInSamples += numSamples;
  106893. }
  106894. else
  106895. {
  106896. if (numSamples > reservoir.getNumSamples())
  106897. reservoir.setSize (numChannels, numSamples, false, false, true);
  106898. const int bitsToShift = 32 - bitsPerSample;
  106899. for (int i = 0; i < (int) numChannels; ++i)
  106900. {
  106901. const FlacNamespace::FLAC__int32* src = buffer[i];
  106902. int n = i;
  106903. while (src == 0 && n > 0)
  106904. src = buffer [--n];
  106905. if (src != 0)
  106906. {
  106907. int* dest = reinterpret_cast<int*> (reservoir.getSampleData(i));
  106908. for (int j = 0; j < numSamples; ++j)
  106909. dest[j] = src[j] << bitsToShift;
  106910. }
  106911. }
  106912. samplesInReservoir = numSamples;
  106913. }
  106914. }
  106915. static FlacNamespace::FLAC__StreamDecoderReadStatus readCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__byte buffer[], size_t* bytes, void* client_data)
  106916. {
  106917. using namespace FlacNamespace;
  106918. *bytes = (size_t) static_cast <const FlacReader*> (client_data)->input->read (buffer, (int) *bytes);
  106919. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  106920. }
  106921. static FlacNamespace::FLAC__StreamDecoderSeekStatus seekCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64 absolute_byte_offset, void* client_data)
  106922. {
  106923. using namespace FlacNamespace;
  106924. static_cast <const FlacReader*> (client_data)->input->setPosition ((int) absolute_byte_offset);
  106925. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  106926. }
  106927. static FlacNamespace::FLAC__StreamDecoderTellStatus tellCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  106928. {
  106929. using namespace FlacNamespace;
  106930. *absolute_byte_offset = static_cast <const FlacReader*> (client_data)->input->getPosition();
  106931. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  106932. }
  106933. static FlacNamespace::FLAC__StreamDecoderLengthStatus lengthCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* stream_length, void* client_data)
  106934. {
  106935. using namespace FlacNamespace;
  106936. *stream_length = static_cast <const FlacReader*> (client_data)->input->getTotalLength();
  106937. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  106938. }
  106939. static FlacNamespace::FLAC__bool eofCallback_ (const FlacNamespace::FLAC__StreamDecoder*, void* client_data)
  106940. {
  106941. return static_cast <const FlacReader*> (client_data)->input->isExhausted();
  106942. }
  106943. static FlacNamespace::FLAC__StreamDecoderWriteStatus writeCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  106944. const FlacNamespace::FLAC__Frame* frame,
  106945. const FlacNamespace::FLAC__int32* const buffer[],
  106946. void* client_data)
  106947. {
  106948. using namespace FlacNamespace;
  106949. static_cast <FlacReader*> (client_data)->useSamples (buffer, frame->header.blocksize);
  106950. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  106951. }
  106952. static void metadataCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  106953. const FlacNamespace::FLAC__StreamMetadata* metadata,
  106954. void* client_data)
  106955. {
  106956. static_cast <FlacReader*> (client_data)->useMetadata (metadata->data.stream_info);
  106957. }
  106958. static void errorCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__StreamDecoderErrorStatus, void*)
  106959. {
  106960. }
  106961. juce_UseDebuggingNewOperator
  106962. private:
  106963. FlacNamespace::FLAC__StreamDecoder* decoder;
  106964. AudioSampleBuffer reservoir;
  106965. int reservoirStart, samplesInReservoir;
  106966. bool ok, scanningForLength;
  106967. FlacReader (const FlacReader&);
  106968. FlacReader& operator= (const FlacReader&);
  106969. };
  106970. class FlacWriter : public AudioFormatWriter
  106971. {
  106972. public:
  106973. FlacWriter (OutputStream* const out, double sampleRate_,
  106974. int numChannels_, int bitsPerSample_, int qualityOptionIndex)
  106975. : AudioFormatWriter (out, TRANS (flacFormatName),
  106976. sampleRate_, numChannels_, bitsPerSample_)
  106977. {
  106978. using namespace FlacNamespace;
  106979. encoder = FLAC__stream_encoder_new();
  106980. if (qualityOptionIndex > 0)
  106981. FLAC__stream_encoder_set_compression_level (encoder, jmin (8, qualityOptionIndex));
  106982. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  106983. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  106984. FLAC__stream_encoder_set_channels (encoder, numChannels);
  106985. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin ((unsigned int) 24, bitsPerSample));
  106986. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  106987. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  106988. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  106989. ok = FLAC__stream_encoder_init_stream (encoder,
  106990. encodeWriteCallback, encodeSeekCallback,
  106991. encodeTellCallback, encodeMetadataCallback,
  106992. this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  106993. }
  106994. ~FlacWriter()
  106995. {
  106996. if (ok)
  106997. {
  106998. FlacNamespace::FLAC__stream_encoder_finish (encoder);
  106999. output->flush();
  107000. }
  107001. else
  107002. {
  107003. output = 0; // to stop the base class deleting this, as it needs to be returned
  107004. // to the caller of createWriter()
  107005. }
  107006. FlacNamespace::FLAC__stream_encoder_delete (encoder);
  107007. }
  107008. bool write (const int** samplesToWrite, int numSamples)
  107009. {
  107010. using namespace FlacNamespace;
  107011. if (! ok)
  107012. return false;
  107013. int* buf[3];
  107014. const int bitsToShift = 32 - bitsPerSample;
  107015. if (bitsToShift > 0)
  107016. {
  107017. const int numChannelsToWrite = (samplesToWrite[1] == 0) ? 1 : 2;
  107018. HeapBlock<int> temp (numSamples * numChannelsToWrite);
  107019. buf[0] = temp.getData();
  107020. buf[1] = temp.getData() + numSamples;
  107021. buf[2] = 0;
  107022. for (int i = numChannelsToWrite; --i >= 0;)
  107023. {
  107024. if (samplesToWrite[i] != 0)
  107025. {
  107026. for (int j = 0; j < numSamples; ++j)
  107027. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  107028. }
  107029. }
  107030. samplesToWrite = const_cast<const int**> (buf);
  107031. }
  107032. return FLAC__stream_encoder_process (encoder,
  107033. (const FLAC__int32**) samplesToWrite,
  107034. numSamples) != 0;
  107035. }
  107036. bool writeData (const void* const data, const int size) const
  107037. {
  107038. return output->write (data, size);
  107039. }
  107040. static void packUint32 (FlacNamespace::FLAC__uint32 val, FlacNamespace::FLAC__byte* b, const int bytes)
  107041. {
  107042. using namespace FlacNamespace;
  107043. b += bytes;
  107044. for (int i = 0; i < bytes; ++i)
  107045. {
  107046. *(--b) = (FLAC__byte) (val & 0xff);
  107047. val >>= 8;
  107048. }
  107049. }
  107050. void writeMetaData (const FlacNamespace::FLAC__StreamMetadata* metadata)
  107051. {
  107052. using namespace FlacNamespace;
  107053. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  107054. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  107055. const unsigned int channelsMinus1 = info.channels - 1;
  107056. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  107057. packUint32 (info.min_blocksize, buffer, 2);
  107058. packUint32 (info.max_blocksize, buffer + 2, 2);
  107059. packUint32 (info.min_framesize, buffer + 4, 3);
  107060. packUint32 (info.max_framesize, buffer + 7, 3);
  107061. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  107062. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  107063. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  107064. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  107065. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  107066. memcpy (buffer + 18, info.md5sum, 16);
  107067. const bool seekOk = output->setPosition (4);
  107068. (void) seekOk;
  107069. // if this fails, you've given it an output stream that can't seek! It needs
  107070. // to be able to seek back to write the header
  107071. jassert (seekOk);
  107072. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  107073. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  107074. }
  107075. static FlacNamespace::FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FlacNamespace::FLAC__StreamEncoder*,
  107076. const FlacNamespace::FLAC__byte buffer[],
  107077. size_t bytes,
  107078. unsigned int /*samples*/,
  107079. unsigned int /*current_frame*/,
  107080. void* client_data)
  107081. {
  107082. using namespace FlacNamespace;
  107083. return static_cast <FlacWriter*> (client_data)->writeData (buffer, (int) bytes)
  107084. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  107085. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  107086. }
  107087. static FlacNamespace::FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64, void*)
  107088. {
  107089. using namespace FlacNamespace;
  107090. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  107091. }
  107092. static FlacNamespace::FLAC__StreamEncoderTellStatus encodeTellCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  107093. {
  107094. using namespace FlacNamespace;
  107095. if (client_data == 0)
  107096. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  107097. *absolute_byte_offset = (FLAC__uint64) static_cast <FlacWriter*> (client_data)->output->getPosition();
  107098. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  107099. }
  107100. static void encodeMetadataCallback (const FlacNamespace::FLAC__StreamEncoder*, const FlacNamespace::FLAC__StreamMetadata* metadata, void* client_data)
  107101. {
  107102. static_cast <FlacWriter*> (client_data)->writeMetaData (metadata);
  107103. }
  107104. juce_UseDebuggingNewOperator
  107105. bool ok;
  107106. private:
  107107. FlacNamespace::FLAC__StreamEncoder* encoder;
  107108. FlacWriter (const FlacWriter&);
  107109. FlacWriter& operator= (const FlacWriter&);
  107110. };
  107111. FlacAudioFormat::FlacAudioFormat()
  107112. : AudioFormat (TRANS (flacFormatName), StringArray (flacExtensions))
  107113. {
  107114. }
  107115. FlacAudioFormat::~FlacAudioFormat()
  107116. {
  107117. }
  107118. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  107119. {
  107120. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  107121. return Array <int> (rates);
  107122. }
  107123. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  107124. {
  107125. const int depths[] = { 16, 24, 0 };
  107126. return Array <int> (depths);
  107127. }
  107128. bool FlacAudioFormat::canDoStereo() { return true; }
  107129. bool FlacAudioFormat::canDoMono() { return true; }
  107130. bool FlacAudioFormat::isCompressed() { return true; }
  107131. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  107132. const bool deleteStreamIfOpeningFails)
  107133. {
  107134. ScopedPointer<FlacReader> r (new FlacReader (in));
  107135. if (r->sampleRate != 0)
  107136. return r.release();
  107137. if (! deleteStreamIfOpeningFails)
  107138. r->input = 0;
  107139. return 0;
  107140. }
  107141. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  107142. double sampleRate,
  107143. unsigned int numberOfChannels,
  107144. int bitsPerSample,
  107145. const StringPairArray& /*metadataValues*/,
  107146. int qualityOptionIndex)
  107147. {
  107148. if (getPossibleBitDepths().contains (bitsPerSample))
  107149. {
  107150. ScopedPointer<FlacWriter> w (new FlacWriter (out, sampleRate, numberOfChannels, bitsPerSample, qualityOptionIndex));
  107151. if (w->ok)
  107152. return w.release();
  107153. }
  107154. return 0;
  107155. }
  107156. END_JUCE_NAMESPACE
  107157. #endif
  107158. /*** End of inlined file: juce_FlacAudioFormat.cpp ***/
  107159. /*** Start of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  107160. #if JUCE_USE_OGGVORBIS
  107161. #if JUCE_MAC
  107162. #define __MACOSX__ 1
  107163. #endif
  107164. namespace OggVorbisNamespace
  107165. {
  107166. #if JUCE_INCLUDE_OGGVORBIS_CODE
  107167. /*** Start of inlined file: vorbisenc.h ***/
  107168. #ifndef _OV_ENC_H_
  107169. #define _OV_ENC_H_
  107170. #ifdef __cplusplus
  107171. extern "C"
  107172. {
  107173. #endif /* __cplusplus */
  107174. /*** Start of inlined file: codec.h ***/
  107175. #ifndef _vorbis_codec_h_
  107176. #define _vorbis_codec_h_
  107177. #ifdef __cplusplus
  107178. extern "C"
  107179. {
  107180. #endif /* __cplusplus */
  107181. /*** Start of inlined file: ogg.h ***/
  107182. #ifndef _OGG_H
  107183. #define _OGG_H
  107184. #ifdef __cplusplus
  107185. extern "C" {
  107186. #endif
  107187. /*** Start of inlined file: os_types.h ***/
  107188. #ifndef _OS_TYPES_H
  107189. #define _OS_TYPES_H
  107190. /* make it easy on the folks that want to compile the libs with a
  107191. different malloc than stdlib */
  107192. #define _ogg_malloc malloc
  107193. #define _ogg_calloc calloc
  107194. #define _ogg_realloc realloc
  107195. #define _ogg_free free
  107196. #if defined(_WIN32)
  107197. # if defined(__CYGWIN__)
  107198. # include <_G_config.h>
  107199. typedef _G_int64_t ogg_int64_t;
  107200. typedef _G_int32_t ogg_int32_t;
  107201. typedef _G_uint32_t ogg_uint32_t;
  107202. typedef _G_int16_t ogg_int16_t;
  107203. typedef _G_uint16_t ogg_uint16_t;
  107204. # elif defined(__MINGW32__)
  107205. typedef short ogg_int16_t;
  107206. typedef unsigned short ogg_uint16_t;
  107207. typedef int ogg_int32_t;
  107208. typedef unsigned int ogg_uint32_t;
  107209. typedef long long ogg_int64_t;
  107210. typedef unsigned long long ogg_uint64_t;
  107211. # elif defined(__MWERKS__)
  107212. typedef long long ogg_int64_t;
  107213. typedef int ogg_int32_t;
  107214. typedef unsigned int ogg_uint32_t;
  107215. typedef short ogg_int16_t;
  107216. typedef unsigned short ogg_uint16_t;
  107217. # else
  107218. /* MSVC/Borland */
  107219. typedef __int64 ogg_int64_t;
  107220. typedef __int32 ogg_int32_t;
  107221. typedef unsigned __int32 ogg_uint32_t;
  107222. typedef __int16 ogg_int16_t;
  107223. typedef unsigned __int16 ogg_uint16_t;
  107224. # endif
  107225. #elif defined(__MACOS__)
  107226. # include <sys/types.h>
  107227. typedef SInt16 ogg_int16_t;
  107228. typedef UInt16 ogg_uint16_t;
  107229. typedef SInt32 ogg_int32_t;
  107230. typedef UInt32 ogg_uint32_t;
  107231. typedef SInt64 ogg_int64_t;
  107232. #elif defined(__MACOSX__) /* MacOS X Framework build */
  107233. # include <sys/types.h>
  107234. typedef int16_t ogg_int16_t;
  107235. typedef u_int16_t ogg_uint16_t;
  107236. typedef int32_t ogg_int32_t;
  107237. typedef u_int32_t ogg_uint32_t;
  107238. typedef int64_t ogg_int64_t;
  107239. #elif defined(__BEOS__)
  107240. /* Be */
  107241. # include <inttypes.h>
  107242. typedef int16_t ogg_int16_t;
  107243. typedef u_int16_t ogg_uint16_t;
  107244. typedef int32_t ogg_int32_t;
  107245. typedef u_int32_t ogg_uint32_t;
  107246. typedef int64_t ogg_int64_t;
  107247. #elif defined (__EMX__)
  107248. /* OS/2 GCC */
  107249. typedef short ogg_int16_t;
  107250. typedef unsigned short ogg_uint16_t;
  107251. typedef int ogg_int32_t;
  107252. typedef unsigned int ogg_uint32_t;
  107253. typedef long long ogg_int64_t;
  107254. #elif defined (DJGPP)
  107255. /* DJGPP */
  107256. typedef short ogg_int16_t;
  107257. typedef int ogg_int32_t;
  107258. typedef unsigned int ogg_uint32_t;
  107259. typedef long long ogg_int64_t;
  107260. #elif defined(R5900)
  107261. /* PS2 EE */
  107262. typedef long ogg_int64_t;
  107263. typedef int ogg_int32_t;
  107264. typedef unsigned ogg_uint32_t;
  107265. typedef short ogg_int16_t;
  107266. #elif defined(__SYMBIAN32__)
  107267. /* Symbian GCC */
  107268. typedef signed short ogg_int16_t;
  107269. typedef unsigned short ogg_uint16_t;
  107270. typedef signed int ogg_int32_t;
  107271. typedef unsigned int ogg_uint32_t;
  107272. typedef long long int ogg_int64_t;
  107273. #else
  107274. # include <sys/types.h>
  107275. /*** Start of inlined file: config_types.h ***/
  107276. #ifndef __CONFIG_TYPES_H__
  107277. #define __CONFIG_TYPES_H__
  107278. typedef int16_t ogg_int16_t;
  107279. typedef unsigned short ogg_uint16_t;
  107280. typedef int32_t ogg_int32_t;
  107281. typedef unsigned int ogg_uint32_t;
  107282. typedef int64_t ogg_int64_t;
  107283. #endif
  107284. /*** End of inlined file: config_types.h ***/
  107285. #endif
  107286. #endif /* _OS_TYPES_H */
  107287. /*** End of inlined file: os_types.h ***/
  107288. typedef struct {
  107289. long endbyte;
  107290. int endbit;
  107291. unsigned char *buffer;
  107292. unsigned char *ptr;
  107293. long storage;
  107294. } oggpack_buffer;
  107295. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  107296. typedef struct {
  107297. unsigned char *header;
  107298. long header_len;
  107299. unsigned char *body;
  107300. long body_len;
  107301. } ogg_page;
  107302. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  107303. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  107304. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  107305. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  107306. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  107307. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  107308. }
  107309. /* ogg_stream_state contains the current encode/decode state of a logical
  107310. Ogg bitstream **********************************************************/
  107311. typedef struct {
  107312. unsigned char *body_data; /* bytes from packet bodies */
  107313. long body_storage; /* storage elements allocated */
  107314. long body_fill; /* elements stored; fill mark */
  107315. long body_returned; /* elements of fill returned */
  107316. int *lacing_vals; /* The values that will go to the segment table */
  107317. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  107318. this way, but it is simple coupled to the
  107319. lacing fifo */
  107320. long lacing_storage;
  107321. long lacing_fill;
  107322. long lacing_packet;
  107323. long lacing_returned;
  107324. unsigned char header[282]; /* working space for header encode */
  107325. int header_fill;
  107326. int e_o_s; /* set when we have buffered the last packet in the
  107327. logical bitstream */
  107328. int b_o_s; /* set after we've written the initial page
  107329. of a logical bitstream */
  107330. long serialno;
  107331. long pageno;
  107332. ogg_int64_t packetno; /* sequence number for decode; the framing
  107333. knows where there's a hole in the data,
  107334. but we need coupling so that the codec
  107335. (which is in a seperate abstraction
  107336. layer) also knows about the gap */
  107337. ogg_int64_t granulepos;
  107338. } ogg_stream_state;
  107339. /* ogg_packet is used to encapsulate the data and metadata belonging
  107340. to a single raw Ogg/Vorbis packet *************************************/
  107341. typedef struct {
  107342. unsigned char *packet;
  107343. long bytes;
  107344. long b_o_s;
  107345. long e_o_s;
  107346. ogg_int64_t granulepos;
  107347. ogg_int64_t packetno; /* sequence number for decode; the framing
  107348. knows where there's a hole in the data,
  107349. but we need coupling so that the codec
  107350. (which is in a seperate abstraction
  107351. layer) also knows about the gap */
  107352. } ogg_packet;
  107353. typedef struct {
  107354. unsigned char *data;
  107355. int storage;
  107356. int fill;
  107357. int returned;
  107358. int unsynced;
  107359. int headerbytes;
  107360. int bodybytes;
  107361. } ogg_sync_state;
  107362. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  107363. extern void oggpack_writeinit(oggpack_buffer *b);
  107364. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  107365. extern void oggpack_writealign(oggpack_buffer *b);
  107366. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  107367. extern void oggpack_reset(oggpack_buffer *b);
  107368. extern void oggpack_writeclear(oggpack_buffer *b);
  107369. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107370. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  107371. extern long oggpack_look(oggpack_buffer *b,int bits);
  107372. extern long oggpack_look1(oggpack_buffer *b);
  107373. extern void oggpack_adv(oggpack_buffer *b,int bits);
  107374. extern void oggpack_adv1(oggpack_buffer *b);
  107375. extern long oggpack_read(oggpack_buffer *b,int bits);
  107376. extern long oggpack_read1(oggpack_buffer *b);
  107377. extern long oggpack_bytes(oggpack_buffer *b);
  107378. extern long oggpack_bits(oggpack_buffer *b);
  107379. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  107380. extern void oggpackB_writeinit(oggpack_buffer *b);
  107381. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  107382. extern void oggpackB_writealign(oggpack_buffer *b);
  107383. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  107384. extern void oggpackB_reset(oggpack_buffer *b);
  107385. extern void oggpackB_writeclear(oggpack_buffer *b);
  107386. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107387. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  107388. extern long oggpackB_look(oggpack_buffer *b,int bits);
  107389. extern long oggpackB_look1(oggpack_buffer *b);
  107390. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  107391. extern void oggpackB_adv1(oggpack_buffer *b);
  107392. extern long oggpackB_read(oggpack_buffer *b,int bits);
  107393. extern long oggpackB_read1(oggpack_buffer *b);
  107394. extern long oggpackB_bytes(oggpack_buffer *b);
  107395. extern long oggpackB_bits(oggpack_buffer *b);
  107396. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  107397. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  107398. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  107399. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  107400. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  107401. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  107402. extern int ogg_sync_init(ogg_sync_state *oy);
  107403. extern int ogg_sync_clear(ogg_sync_state *oy);
  107404. extern int ogg_sync_reset(ogg_sync_state *oy);
  107405. extern int ogg_sync_destroy(ogg_sync_state *oy);
  107406. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  107407. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  107408. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  107409. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  107410. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  107411. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  107412. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  107413. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  107414. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  107415. extern int ogg_stream_clear(ogg_stream_state *os);
  107416. extern int ogg_stream_reset(ogg_stream_state *os);
  107417. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  107418. extern int ogg_stream_destroy(ogg_stream_state *os);
  107419. extern int ogg_stream_eos(ogg_stream_state *os);
  107420. extern void ogg_page_checksum_set(ogg_page *og);
  107421. extern int ogg_page_version(ogg_page *og);
  107422. extern int ogg_page_continued(ogg_page *og);
  107423. extern int ogg_page_bos(ogg_page *og);
  107424. extern int ogg_page_eos(ogg_page *og);
  107425. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  107426. extern int ogg_page_serialno(ogg_page *og);
  107427. extern long ogg_page_pageno(ogg_page *og);
  107428. extern int ogg_page_packets(ogg_page *og);
  107429. extern void ogg_packet_clear(ogg_packet *op);
  107430. #ifdef __cplusplus
  107431. }
  107432. #endif
  107433. #endif /* _OGG_H */
  107434. /*** End of inlined file: ogg.h ***/
  107435. typedef struct vorbis_info{
  107436. int version;
  107437. int channels;
  107438. long rate;
  107439. /* The below bitrate declarations are *hints*.
  107440. Combinations of the three values carry the following implications:
  107441. all three set to the same value:
  107442. implies a fixed rate bitstream
  107443. only nominal set:
  107444. implies a VBR stream that averages the nominal bitrate. No hard
  107445. upper/lower limit
  107446. upper and or lower set:
  107447. implies a VBR bitstream that obeys the bitrate limits. nominal
  107448. may also be set to give a nominal rate.
  107449. none set:
  107450. the coder does not care to speculate.
  107451. */
  107452. long bitrate_upper;
  107453. long bitrate_nominal;
  107454. long bitrate_lower;
  107455. long bitrate_window;
  107456. void *codec_setup;
  107457. } vorbis_info;
  107458. /* vorbis_dsp_state buffers the current vorbis audio
  107459. analysis/synthesis state. The DSP state belongs to a specific
  107460. logical bitstream ****************************************************/
  107461. typedef struct vorbis_dsp_state{
  107462. int analysisp;
  107463. vorbis_info *vi;
  107464. float **pcm;
  107465. float **pcmret;
  107466. int pcm_storage;
  107467. int pcm_current;
  107468. int pcm_returned;
  107469. int preextrapolate;
  107470. int eofflag;
  107471. long lW;
  107472. long W;
  107473. long nW;
  107474. long centerW;
  107475. ogg_int64_t granulepos;
  107476. ogg_int64_t sequence;
  107477. ogg_int64_t glue_bits;
  107478. ogg_int64_t time_bits;
  107479. ogg_int64_t floor_bits;
  107480. ogg_int64_t res_bits;
  107481. void *backend_state;
  107482. } vorbis_dsp_state;
  107483. typedef struct vorbis_block{
  107484. /* necessary stream state for linking to the framing abstraction */
  107485. float **pcm; /* this is a pointer into local storage */
  107486. oggpack_buffer opb;
  107487. long lW;
  107488. long W;
  107489. long nW;
  107490. int pcmend;
  107491. int mode;
  107492. int eofflag;
  107493. ogg_int64_t granulepos;
  107494. ogg_int64_t sequence;
  107495. vorbis_dsp_state *vd; /* For read-only access of configuration */
  107496. /* local storage to avoid remallocing; it's up to the mapping to
  107497. structure it */
  107498. void *localstore;
  107499. long localtop;
  107500. long localalloc;
  107501. long totaluse;
  107502. struct alloc_chain *reap;
  107503. /* bitmetrics for the frame */
  107504. long glue_bits;
  107505. long time_bits;
  107506. long floor_bits;
  107507. long res_bits;
  107508. void *internal;
  107509. } vorbis_block;
  107510. /* vorbis_block is a single block of data to be processed as part of
  107511. the analysis/synthesis stream; it belongs to a specific logical
  107512. bitstream, but is independant from other vorbis_blocks belonging to
  107513. that logical bitstream. *************************************************/
  107514. struct alloc_chain{
  107515. void *ptr;
  107516. struct alloc_chain *next;
  107517. };
  107518. /* vorbis_info contains all the setup information specific to the
  107519. specific compression/decompression mode in progress (eg,
  107520. psychoacoustic settings, channel setup, options, codebook
  107521. etc). vorbis_info and substructures are in backends.h.
  107522. *********************************************************************/
  107523. /* the comments are not part of vorbis_info so that vorbis_info can be
  107524. static storage */
  107525. typedef struct vorbis_comment{
  107526. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  107527. whatever vendor is set to in encode */
  107528. char **user_comments;
  107529. int *comment_lengths;
  107530. int comments;
  107531. char *vendor;
  107532. } vorbis_comment;
  107533. /* libvorbis encodes in two abstraction layers; first we perform DSP
  107534. and produce a packet (see docs/analysis.txt). The packet is then
  107535. coded into a framed OggSquish bitstream by the second layer (see
  107536. docs/framing.txt). Decode is the reverse process; we sync/frame
  107537. the bitstream and extract individual packets, then decode the
  107538. packet back into PCM audio.
  107539. The extra framing/packetizing is used in streaming formats, such as
  107540. files. Over the net (such as with UDP), the framing and
  107541. packetization aren't necessary as they're provided by the transport
  107542. and the streaming layer is not used */
  107543. /* Vorbis PRIMITIVES: general ***************************************/
  107544. extern void vorbis_info_init(vorbis_info *vi);
  107545. extern void vorbis_info_clear(vorbis_info *vi);
  107546. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  107547. extern void vorbis_comment_init(vorbis_comment *vc);
  107548. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  107549. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  107550. const char *tag, char *contents);
  107551. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  107552. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  107553. extern void vorbis_comment_clear(vorbis_comment *vc);
  107554. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  107555. extern int vorbis_block_clear(vorbis_block *vb);
  107556. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  107557. extern double vorbis_granule_time(vorbis_dsp_state *v,
  107558. ogg_int64_t granulepos);
  107559. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  107560. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107561. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  107562. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  107563. vorbis_comment *vc,
  107564. ogg_packet *op,
  107565. ogg_packet *op_comm,
  107566. ogg_packet *op_code);
  107567. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  107568. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  107569. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  107570. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  107571. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  107572. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  107573. ogg_packet *op);
  107574. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  107575. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  107576. ogg_packet *op);
  107577. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107578. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  107579. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  107580. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  107581. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  107582. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  107583. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  107584. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  107585. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  107586. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  107587. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  107588. /* Vorbis ERRORS and return codes ***********************************/
  107589. #define OV_FALSE -1
  107590. #define OV_EOF -2
  107591. #define OV_HOLE -3
  107592. #define OV_EREAD -128
  107593. #define OV_EFAULT -129
  107594. #define OV_EIMPL -130
  107595. #define OV_EINVAL -131
  107596. #define OV_ENOTVORBIS -132
  107597. #define OV_EBADHEADER -133
  107598. #define OV_EVERSION -134
  107599. #define OV_ENOTAUDIO -135
  107600. #define OV_EBADPACKET -136
  107601. #define OV_EBADLINK -137
  107602. #define OV_ENOSEEK -138
  107603. #ifdef __cplusplus
  107604. }
  107605. #endif /* __cplusplus */
  107606. #endif
  107607. /*** End of inlined file: codec.h ***/
  107608. extern int vorbis_encode_init(vorbis_info *vi,
  107609. long channels,
  107610. long rate,
  107611. long max_bitrate,
  107612. long nominal_bitrate,
  107613. long min_bitrate);
  107614. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  107615. long channels,
  107616. long rate,
  107617. long max_bitrate,
  107618. long nominal_bitrate,
  107619. long min_bitrate);
  107620. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  107621. long channels,
  107622. long rate,
  107623. float quality /* quality level from 0. (lo) to 1. (hi) */
  107624. );
  107625. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  107626. long channels,
  107627. long rate,
  107628. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  107629. );
  107630. extern int vorbis_encode_setup_init(vorbis_info *vi);
  107631. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  107632. /* deprecated rate management supported only for compatability */
  107633. #define OV_ECTL_RATEMANAGE_GET 0x10
  107634. #define OV_ECTL_RATEMANAGE_SET 0x11
  107635. #define OV_ECTL_RATEMANAGE_AVG 0x12
  107636. #define OV_ECTL_RATEMANAGE_HARD 0x13
  107637. struct ovectl_ratemanage_arg {
  107638. int management_active;
  107639. long bitrate_hard_min;
  107640. long bitrate_hard_max;
  107641. double bitrate_hard_window;
  107642. long bitrate_av_lo;
  107643. long bitrate_av_hi;
  107644. double bitrate_av_window;
  107645. double bitrate_av_window_center;
  107646. };
  107647. /* new rate setup */
  107648. #define OV_ECTL_RATEMANAGE2_GET 0x14
  107649. #define OV_ECTL_RATEMANAGE2_SET 0x15
  107650. struct ovectl_ratemanage2_arg {
  107651. int management_active;
  107652. long bitrate_limit_min_kbps;
  107653. long bitrate_limit_max_kbps;
  107654. long bitrate_limit_reservoir_bits;
  107655. double bitrate_limit_reservoir_bias;
  107656. long bitrate_average_kbps;
  107657. double bitrate_average_damping;
  107658. };
  107659. #define OV_ECTL_LOWPASS_GET 0x20
  107660. #define OV_ECTL_LOWPASS_SET 0x21
  107661. #define OV_ECTL_IBLOCK_GET 0x30
  107662. #define OV_ECTL_IBLOCK_SET 0x31
  107663. #ifdef __cplusplus
  107664. }
  107665. #endif /* __cplusplus */
  107666. #endif
  107667. /*** End of inlined file: vorbisenc.h ***/
  107668. /*** Start of inlined file: vorbisfile.h ***/
  107669. #ifndef _OV_FILE_H_
  107670. #define _OV_FILE_H_
  107671. #ifdef __cplusplus
  107672. extern "C"
  107673. {
  107674. #endif /* __cplusplus */
  107675. #include <stdio.h>
  107676. /* The function prototypes for the callbacks are basically the same as for
  107677. * the stdio functions fread, fseek, fclose, ftell.
  107678. * The one difference is that the FILE * arguments have been replaced with
  107679. * a void * - this is to be used as a pointer to whatever internal data these
  107680. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  107681. *
  107682. * If you use other functions, check the docs for these functions and return
  107683. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  107684. * unseekable
  107685. */
  107686. typedef struct {
  107687. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  107688. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  107689. int (*close_func) (void *datasource);
  107690. long (*tell_func) (void *datasource);
  107691. } ov_callbacks;
  107692. #define NOTOPEN 0
  107693. #define PARTOPEN 1
  107694. #define OPENED 2
  107695. #define STREAMSET 3
  107696. #define INITSET 4
  107697. typedef struct OggVorbis_File {
  107698. void *datasource; /* Pointer to a FILE *, etc. */
  107699. int seekable;
  107700. ogg_int64_t offset;
  107701. ogg_int64_t end;
  107702. ogg_sync_state oy;
  107703. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  107704. stream appears */
  107705. int links;
  107706. ogg_int64_t *offsets;
  107707. ogg_int64_t *dataoffsets;
  107708. long *serialnos;
  107709. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  107710. compatability; x2 size, stores both
  107711. beginning and end values */
  107712. vorbis_info *vi;
  107713. vorbis_comment *vc;
  107714. /* Decoding working state local storage */
  107715. ogg_int64_t pcm_offset;
  107716. int ready_state;
  107717. long current_serialno;
  107718. int current_link;
  107719. double bittrack;
  107720. double samptrack;
  107721. ogg_stream_state os; /* take physical pages, weld into a logical
  107722. stream of packets */
  107723. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  107724. vorbis_block vb; /* local working space for packet->PCM decode */
  107725. ov_callbacks callbacks;
  107726. } OggVorbis_File;
  107727. extern int ov_clear(OggVorbis_File *vf);
  107728. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107729. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  107730. char *initial, long ibytes, ov_callbacks callbacks);
  107731. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107732. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  107733. char *initial, long ibytes, ov_callbacks callbacks);
  107734. extern int ov_test_open(OggVorbis_File *vf);
  107735. extern long ov_bitrate(OggVorbis_File *vf,int i);
  107736. extern long ov_bitrate_instant(OggVorbis_File *vf);
  107737. extern long ov_streams(OggVorbis_File *vf);
  107738. extern long ov_seekable(OggVorbis_File *vf);
  107739. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  107740. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  107741. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  107742. extern double ov_time_total(OggVorbis_File *vf,int i);
  107743. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107744. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107745. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  107746. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  107747. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  107748. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107749. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107750. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107751. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  107752. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  107753. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  107754. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  107755. extern double ov_time_tell(OggVorbis_File *vf);
  107756. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  107757. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  107758. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  107759. int *bitstream);
  107760. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  107761. int bigendianp,int word,int sgned,int *bitstream);
  107762. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  107763. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  107764. extern int ov_halfrate_p(OggVorbis_File *vf);
  107765. #ifdef __cplusplus
  107766. }
  107767. #endif /* __cplusplus */
  107768. #endif
  107769. /*** End of inlined file: vorbisfile.h ***/
  107770. /*** Start of inlined file: bitwise.c ***/
  107771. /* We're 'LSb' endian; if we write a word but read individual bits,
  107772. then we'll read the lsb first */
  107773. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  107774. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107775. // tasks..
  107776. #if JUCE_MSVC
  107777. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107778. #endif
  107779. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  107780. #if JUCE_USE_OGGVORBIS
  107781. #include <string.h>
  107782. #include <stdlib.h>
  107783. #define BUFFER_INCREMENT 256
  107784. static const unsigned long mask[]=
  107785. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  107786. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  107787. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  107788. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  107789. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  107790. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  107791. 0x3fffffff,0x7fffffff,0xffffffff };
  107792. static const unsigned int mask8B[]=
  107793. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  107794. void oggpack_writeinit(oggpack_buffer *b){
  107795. memset(b,0,sizeof(*b));
  107796. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  107797. b->buffer[0]='\0';
  107798. b->storage=BUFFER_INCREMENT;
  107799. }
  107800. void oggpackB_writeinit(oggpack_buffer *b){
  107801. oggpack_writeinit(b);
  107802. }
  107803. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  107804. long bytes=bits>>3;
  107805. bits-=bytes*8;
  107806. b->ptr=b->buffer+bytes;
  107807. b->endbit=bits;
  107808. b->endbyte=bytes;
  107809. *b->ptr&=mask[bits];
  107810. }
  107811. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  107812. long bytes=bits>>3;
  107813. bits-=bytes*8;
  107814. b->ptr=b->buffer+bytes;
  107815. b->endbit=bits;
  107816. b->endbyte=bytes;
  107817. *b->ptr&=mask8B[bits];
  107818. }
  107819. /* Takes only up to 32 bits. */
  107820. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  107821. if(b->endbyte+4>=b->storage){
  107822. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  107823. b->storage+=BUFFER_INCREMENT;
  107824. b->ptr=b->buffer+b->endbyte;
  107825. }
  107826. value&=mask[bits];
  107827. bits+=b->endbit;
  107828. b->ptr[0]|=value<<b->endbit;
  107829. if(bits>=8){
  107830. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  107831. if(bits>=16){
  107832. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  107833. if(bits>=24){
  107834. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  107835. if(bits>=32){
  107836. if(b->endbit)
  107837. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  107838. else
  107839. b->ptr[4]=0;
  107840. }
  107841. }
  107842. }
  107843. }
  107844. b->endbyte+=bits/8;
  107845. b->ptr+=bits/8;
  107846. b->endbit=bits&7;
  107847. }
  107848. /* Takes only up to 32 bits. */
  107849. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  107850. if(b->endbyte+4>=b->storage){
  107851. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  107852. b->storage+=BUFFER_INCREMENT;
  107853. b->ptr=b->buffer+b->endbyte;
  107854. }
  107855. value=(value&mask[bits])<<(32-bits);
  107856. bits+=b->endbit;
  107857. b->ptr[0]|=value>>(24+b->endbit);
  107858. if(bits>=8){
  107859. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  107860. if(bits>=16){
  107861. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  107862. if(bits>=24){
  107863. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  107864. if(bits>=32){
  107865. if(b->endbit)
  107866. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  107867. else
  107868. b->ptr[4]=0;
  107869. }
  107870. }
  107871. }
  107872. }
  107873. b->endbyte+=bits/8;
  107874. b->ptr+=bits/8;
  107875. b->endbit=bits&7;
  107876. }
  107877. void oggpack_writealign(oggpack_buffer *b){
  107878. int bits=8-b->endbit;
  107879. if(bits<8)
  107880. oggpack_write(b,0,bits);
  107881. }
  107882. void oggpackB_writealign(oggpack_buffer *b){
  107883. int bits=8-b->endbit;
  107884. if(bits<8)
  107885. oggpackB_write(b,0,bits);
  107886. }
  107887. static void oggpack_writecopy_helper(oggpack_buffer *b,
  107888. void *source,
  107889. long bits,
  107890. void (*w)(oggpack_buffer *,
  107891. unsigned long,
  107892. int),
  107893. int msb){
  107894. unsigned char *ptr=(unsigned char *)source;
  107895. long bytes=bits/8;
  107896. bits-=bytes*8;
  107897. if(b->endbit){
  107898. int i;
  107899. /* unaligned copy. Do it the hard way. */
  107900. for(i=0;i<bytes;i++)
  107901. w(b,(unsigned long)(ptr[i]),8);
  107902. }else{
  107903. /* aligned block copy */
  107904. if(b->endbyte+bytes+1>=b->storage){
  107905. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  107906. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  107907. b->ptr=b->buffer+b->endbyte;
  107908. }
  107909. memmove(b->ptr,source,bytes);
  107910. b->ptr+=bytes;
  107911. b->endbyte+=bytes;
  107912. *b->ptr=0;
  107913. }
  107914. if(bits){
  107915. if(msb)
  107916. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  107917. else
  107918. w(b,(unsigned long)(ptr[bytes]),bits);
  107919. }
  107920. }
  107921. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  107922. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  107923. }
  107924. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  107925. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  107926. }
  107927. void oggpack_reset(oggpack_buffer *b){
  107928. b->ptr=b->buffer;
  107929. b->buffer[0]=0;
  107930. b->endbit=b->endbyte=0;
  107931. }
  107932. void oggpackB_reset(oggpack_buffer *b){
  107933. oggpack_reset(b);
  107934. }
  107935. void oggpack_writeclear(oggpack_buffer *b){
  107936. _ogg_free(b->buffer);
  107937. memset(b,0,sizeof(*b));
  107938. }
  107939. void oggpackB_writeclear(oggpack_buffer *b){
  107940. oggpack_writeclear(b);
  107941. }
  107942. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  107943. memset(b,0,sizeof(*b));
  107944. b->buffer=b->ptr=buf;
  107945. b->storage=bytes;
  107946. }
  107947. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  107948. oggpack_readinit(b,buf,bytes);
  107949. }
  107950. /* Read in bits without advancing the bitptr; bits <= 32 */
  107951. long oggpack_look(oggpack_buffer *b,int bits){
  107952. unsigned long ret;
  107953. unsigned long m=mask[bits];
  107954. bits+=b->endbit;
  107955. if(b->endbyte+4>=b->storage){
  107956. /* not the main path */
  107957. if(b->endbyte*8+bits>b->storage*8)return(-1);
  107958. }
  107959. ret=b->ptr[0]>>b->endbit;
  107960. if(bits>8){
  107961. ret|=b->ptr[1]<<(8-b->endbit);
  107962. if(bits>16){
  107963. ret|=b->ptr[2]<<(16-b->endbit);
  107964. if(bits>24){
  107965. ret|=b->ptr[3]<<(24-b->endbit);
  107966. if(bits>32 && b->endbit)
  107967. ret|=b->ptr[4]<<(32-b->endbit);
  107968. }
  107969. }
  107970. }
  107971. return(m&ret);
  107972. }
  107973. /* Read in bits without advancing the bitptr; bits <= 32 */
  107974. long oggpackB_look(oggpack_buffer *b,int bits){
  107975. unsigned long ret;
  107976. int m=32-bits;
  107977. bits+=b->endbit;
  107978. if(b->endbyte+4>=b->storage){
  107979. /* not the main path */
  107980. if(b->endbyte*8+bits>b->storage*8)return(-1);
  107981. }
  107982. ret=b->ptr[0]<<(24+b->endbit);
  107983. if(bits>8){
  107984. ret|=b->ptr[1]<<(16+b->endbit);
  107985. if(bits>16){
  107986. ret|=b->ptr[2]<<(8+b->endbit);
  107987. if(bits>24){
  107988. ret|=b->ptr[3]<<(b->endbit);
  107989. if(bits>32 && b->endbit)
  107990. ret|=b->ptr[4]>>(8-b->endbit);
  107991. }
  107992. }
  107993. }
  107994. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  107995. }
  107996. long oggpack_look1(oggpack_buffer *b){
  107997. if(b->endbyte>=b->storage)return(-1);
  107998. return((b->ptr[0]>>b->endbit)&1);
  107999. }
  108000. long oggpackB_look1(oggpack_buffer *b){
  108001. if(b->endbyte>=b->storage)return(-1);
  108002. return((b->ptr[0]>>(7-b->endbit))&1);
  108003. }
  108004. void oggpack_adv(oggpack_buffer *b,int bits){
  108005. bits+=b->endbit;
  108006. b->ptr+=bits/8;
  108007. b->endbyte+=bits/8;
  108008. b->endbit=bits&7;
  108009. }
  108010. void oggpackB_adv(oggpack_buffer *b,int bits){
  108011. oggpack_adv(b,bits);
  108012. }
  108013. void oggpack_adv1(oggpack_buffer *b){
  108014. if(++(b->endbit)>7){
  108015. b->endbit=0;
  108016. b->ptr++;
  108017. b->endbyte++;
  108018. }
  108019. }
  108020. void oggpackB_adv1(oggpack_buffer *b){
  108021. oggpack_adv1(b);
  108022. }
  108023. /* bits <= 32 */
  108024. long oggpack_read(oggpack_buffer *b,int bits){
  108025. long ret;
  108026. unsigned long m=mask[bits];
  108027. bits+=b->endbit;
  108028. if(b->endbyte+4>=b->storage){
  108029. /* not the main path */
  108030. ret=-1L;
  108031. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  108032. }
  108033. ret=b->ptr[0]>>b->endbit;
  108034. if(bits>8){
  108035. ret|=b->ptr[1]<<(8-b->endbit);
  108036. if(bits>16){
  108037. ret|=b->ptr[2]<<(16-b->endbit);
  108038. if(bits>24){
  108039. ret|=b->ptr[3]<<(24-b->endbit);
  108040. if(bits>32 && b->endbit){
  108041. ret|=b->ptr[4]<<(32-b->endbit);
  108042. }
  108043. }
  108044. }
  108045. }
  108046. ret&=m;
  108047. overflow:
  108048. b->ptr+=bits/8;
  108049. b->endbyte+=bits/8;
  108050. b->endbit=bits&7;
  108051. return(ret);
  108052. }
  108053. /* bits <= 32 */
  108054. long oggpackB_read(oggpack_buffer *b,int bits){
  108055. long ret;
  108056. long m=32-bits;
  108057. bits+=b->endbit;
  108058. if(b->endbyte+4>=b->storage){
  108059. /* not the main path */
  108060. ret=-1L;
  108061. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  108062. }
  108063. ret=b->ptr[0]<<(24+b->endbit);
  108064. if(bits>8){
  108065. ret|=b->ptr[1]<<(16+b->endbit);
  108066. if(bits>16){
  108067. ret|=b->ptr[2]<<(8+b->endbit);
  108068. if(bits>24){
  108069. ret|=b->ptr[3]<<(b->endbit);
  108070. if(bits>32 && b->endbit)
  108071. ret|=b->ptr[4]>>(8-b->endbit);
  108072. }
  108073. }
  108074. }
  108075. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  108076. overflow:
  108077. b->ptr+=bits/8;
  108078. b->endbyte+=bits/8;
  108079. b->endbit=bits&7;
  108080. return(ret);
  108081. }
  108082. long oggpack_read1(oggpack_buffer *b){
  108083. long ret;
  108084. if(b->endbyte>=b->storage){
  108085. /* not the main path */
  108086. ret=-1L;
  108087. goto overflow;
  108088. }
  108089. ret=(b->ptr[0]>>b->endbit)&1;
  108090. overflow:
  108091. b->endbit++;
  108092. if(b->endbit>7){
  108093. b->endbit=0;
  108094. b->ptr++;
  108095. b->endbyte++;
  108096. }
  108097. return(ret);
  108098. }
  108099. long oggpackB_read1(oggpack_buffer *b){
  108100. long ret;
  108101. if(b->endbyte>=b->storage){
  108102. /* not the main path */
  108103. ret=-1L;
  108104. goto overflow;
  108105. }
  108106. ret=(b->ptr[0]>>(7-b->endbit))&1;
  108107. overflow:
  108108. b->endbit++;
  108109. if(b->endbit>7){
  108110. b->endbit=0;
  108111. b->ptr++;
  108112. b->endbyte++;
  108113. }
  108114. return(ret);
  108115. }
  108116. long oggpack_bytes(oggpack_buffer *b){
  108117. return(b->endbyte+(b->endbit+7)/8);
  108118. }
  108119. long oggpack_bits(oggpack_buffer *b){
  108120. return(b->endbyte*8+b->endbit);
  108121. }
  108122. long oggpackB_bytes(oggpack_buffer *b){
  108123. return oggpack_bytes(b);
  108124. }
  108125. long oggpackB_bits(oggpack_buffer *b){
  108126. return oggpack_bits(b);
  108127. }
  108128. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  108129. return(b->buffer);
  108130. }
  108131. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  108132. return oggpack_get_buffer(b);
  108133. }
  108134. /* Self test of the bitwise routines; everything else is based on
  108135. them, so they damned well better be solid. */
  108136. #ifdef _V_SELFTEST
  108137. #include <stdio.h>
  108138. static int ilog(unsigned int v){
  108139. int ret=0;
  108140. while(v){
  108141. ret++;
  108142. v>>=1;
  108143. }
  108144. return(ret);
  108145. }
  108146. oggpack_buffer o;
  108147. oggpack_buffer r;
  108148. void report(char *in){
  108149. fprintf(stderr,"%s",in);
  108150. exit(1);
  108151. }
  108152. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  108153. long bytes,i;
  108154. unsigned char *buffer;
  108155. oggpack_reset(&o);
  108156. for(i=0;i<vals;i++)
  108157. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  108158. buffer=oggpack_get_buffer(&o);
  108159. bytes=oggpack_bytes(&o);
  108160. if(bytes!=compsize)report("wrong number of bytes!\n");
  108161. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  108162. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  108163. report("wrote incorrect value!\n");
  108164. }
  108165. oggpack_readinit(&r,buffer,bytes);
  108166. for(i=0;i<vals;i++){
  108167. int tbit=bits?bits:ilog(b[i]);
  108168. if(oggpack_look(&r,tbit)==-1)
  108169. report("out of data!\n");
  108170. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  108171. report("looked at incorrect value!\n");
  108172. if(tbit==1)
  108173. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  108174. report("looked at single bit incorrect value!\n");
  108175. if(tbit==1){
  108176. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  108177. report("read incorrect single bit value!\n");
  108178. }else{
  108179. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  108180. report("read incorrect value!\n");
  108181. }
  108182. }
  108183. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108184. }
  108185. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  108186. long bytes,i;
  108187. unsigned char *buffer;
  108188. oggpackB_reset(&o);
  108189. for(i=0;i<vals;i++)
  108190. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  108191. buffer=oggpackB_get_buffer(&o);
  108192. bytes=oggpackB_bytes(&o);
  108193. if(bytes!=compsize)report("wrong number of bytes!\n");
  108194. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  108195. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  108196. report("wrote incorrect value!\n");
  108197. }
  108198. oggpackB_readinit(&r,buffer,bytes);
  108199. for(i=0;i<vals;i++){
  108200. int tbit=bits?bits:ilog(b[i]);
  108201. if(oggpackB_look(&r,tbit)==-1)
  108202. report("out of data!\n");
  108203. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  108204. report("looked at incorrect value!\n");
  108205. if(tbit==1)
  108206. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  108207. report("looked at single bit incorrect value!\n");
  108208. if(tbit==1){
  108209. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  108210. report("read incorrect single bit value!\n");
  108211. }else{
  108212. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  108213. report("read incorrect value!\n");
  108214. }
  108215. }
  108216. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108217. }
  108218. int main(void){
  108219. unsigned char *buffer;
  108220. long bytes,i;
  108221. static unsigned long testbuffer1[]=
  108222. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  108223. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  108224. int test1size=43;
  108225. static unsigned long testbuffer2[]=
  108226. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  108227. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  108228. 85525151,0,12321,1,349528352};
  108229. int test2size=21;
  108230. static unsigned long testbuffer3[]=
  108231. {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,
  108232. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  108233. int test3size=56;
  108234. static unsigned long large[]=
  108235. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  108236. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  108237. 85525151,0,12321,1,2146528352};
  108238. int onesize=33;
  108239. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  108240. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  108241. 223,4};
  108242. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  108243. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  108244. 245,251,128};
  108245. int twosize=6;
  108246. static int two[6]={61,255,255,251,231,29};
  108247. static int twoB[6]={247,63,255,253,249,120};
  108248. int threesize=54;
  108249. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  108250. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  108251. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  108252. 100,52,4,14,18,86,77,1};
  108253. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  108254. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  108255. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  108256. 200,20,254,4,58,106,176,144,0};
  108257. int foursize=38;
  108258. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  108259. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  108260. 28,2,133,0,1};
  108261. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  108262. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  108263. 129,10,4,32};
  108264. int fivesize=45;
  108265. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  108266. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  108267. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  108268. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  108269. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  108270. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  108271. int sixsize=7;
  108272. static int six[7]={17,177,170,242,169,19,148};
  108273. static int sixB[7]={136,141,85,79,149,200,41};
  108274. /* Test read/write together */
  108275. /* Later we test against pregenerated bitstreams */
  108276. oggpack_writeinit(&o);
  108277. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  108278. cliptest(testbuffer1,test1size,0,one,onesize);
  108279. fprintf(stderr,"ok.");
  108280. fprintf(stderr,"\nNull bit call (LSb): ");
  108281. cliptest(testbuffer3,test3size,0,two,twosize);
  108282. fprintf(stderr,"ok.");
  108283. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  108284. cliptest(testbuffer2,test2size,0,three,threesize);
  108285. fprintf(stderr,"ok.");
  108286. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  108287. oggpack_reset(&o);
  108288. for(i=0;i<test2size;i++)
  108289. oggpack_write(&o,large[i],32);
  108290. buffer=oggpack_get_buffer(&o);
  108291. bytes=oggpack_bytes(&o);
  108292. oggpack_readinit(&r,buffer,bytes);
  108293. for(i=0;i<test2size;i++){
  108294. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  108295. if(oggpack_look(&r,32)!=large[i]){
  108296. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  108297. oggpack_look(&r,32),large[i]);
  108298. report("read incorrect value!\n");
  108299. }
  108300. oggpack_adv(&r,32);
  108301. }
  108302. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108303. fprintf(stderr,"ok.");
  108304. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  108305. cliptest(testbuffer1,test1size,7,four,foursize);
  108306. fprintf(stderr,"ok.");
  108307. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  108308. cliptest(testbuffer2,test2size,17,five,fivesize);
  108309. fprintf(stderr,"ok.");
  108310. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  108311. cliptest(testbuffer3,test3size,1,six,sixsize);
  108312. fprintf(stderr,"ok.");
  108313. fprintf(stderr,"\nTesting read past end (LSb): ");
  108314. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108315. for(i=0;i<64;i++){
  108316. if(oggpack_read(&r,1)!=0){
  108317. fprintf(stderr,"failed; got -1 prematurely.\n");
  108318. exit(1);
  108319. }
  108320. }
  108321. if(oggpack_look(&r,1)!=-1 ||
  108322. oggpack_read(&r,1)!=-1){
  108323. fprintf(stderr,"failed; read past end without -1.\n");
  108324. exit(1);
  108325. }
  108326. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108327. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  108328. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108329. exit(1);
  108330. }
  108331. if(oggpack_look(&r,18)!=0 ||
  108332. oggpack_look(&r,18)!=0){
  108333. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108334. exit(1);
  108335. }
  108336. if(oggpack_look(&r,19)!=-1 ||
  108337. oggpack_look(&r,19)!=-1){
  108338. fprintf(stderr,"failed; read past end without -1.\n");
  108339. exit(1);
  108340. }
  108341. if(oggpack_look(&r,32)!=-1 ||
  108342. oggpack_look(&r,32)!=-1){
  108343. fprintf(stderr,"failed; read past end without -1.\n");
  108344. exit(1);
  108345. }
  108346. oggpack_writeclear(&o);
  108347. fprintf(stderr,"ok.\n");
  108348. /********** lazy, cut-n-paste retest with MSb packing ***********/
  108349. /* Test read/write together */
  108350. /* Later we test against pregenerated bitstreams */
  108351. oggpackB_writeinit(&o);
  108352. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  108353. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  108354. fprintf(stderr,"ok.");
  108355. fprintf(stderr,"\nNull bit call (MSb): ");
  108356. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  108357. fprintf(stderr,"ok.");
  108358. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  108359. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  108360. fprintf(stderr,"ok.");
  108361. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  108362. oggpackB_reset(&o);
  108363. for(i=0;i<test2size;i++)
  108364. oggpackB_write(&o,large[i],32);
  108365. buffer=oggpackB_get_buffer(&o);
  108366. bytes=oggpackB_bytes(&o);
  108367. oggpackB_readinit(&r,buffer,bytes);
  108368. for(i=0;i<test2size;i++){
  108369. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  108370. if(oggpackB_look(&r,32)!=large[i]){
  108371. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  108372. oggpackB_look(&r,32),large[i]);
  108373. report("read incorrect value!\n");
  108374. }
  108375. oggpackB_adv(&r,32);
  108376. }
  108377. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108378. fprintf(stderr,"ok.");
  108379. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  108380. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  108381. fprintf(stderr,"ok.");
  108382. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  108383. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  108384. fprintf(stderr,"ok.");
  108385. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  108386. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  108387. fprintf(stderr,"ok.");
  108388. fprintf(stderr,"\nTesting read past end (MSb): ");
  108389. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108390. for(i=0;i<64;i++){
  108391. if(oggpackB_read(&r,1)!=0){
  108392. fprintf(stderr,"failed; got -1 prematurely.\n");
  108393. exit(1);
  108394. }
  108395. }
  108396. if(oggpackB_look(&r,1)!=-1 ||
  108397. oggpackB_read(&r,1)!=-1){
  108398. fprintf(stderr,"failed; read past end without -1.\n");
  108399. exit(1);
  108400. }
  108401. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108402. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  108403. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108404. exit(1);
  108405. }
  108406. if(oggpackB_look(&r,18)!=0 ||
  108407. oggpackB_look(&r,18)!=0){
  108408. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108409. exit(1);
  108410. }
  108411. if(oggpackB_look(&r,19)!=-1 ||
  108412. oggpackB_look(&r,19)!=-1){
  108413. fprintf(stderr,"failed; read past end without -1.\n");
  108414. exit(1);
  108415. }
  108416. if(oggpackB_look(&r,32)!=-1 ||
  108417. oggpackB_look(&r,32)!=-1){
  108418. fprintf(stderr,"failed; read past end without -1.\n");
  108419. exit(1);
  108420. }
  108421. oggpackB_writeclear(&o);
  108422. fprintf(stderr,"ok.\n\n");
  108423. return(0);
  108424. }
  108425. #endif /* _V_SELFTEST */
  108426. #undef BUFFER_INCREMENT
  108427. #endif
  108428. /*** End of inlined file: bitwise.c ***/
  108429. /*** Start of inlined file: framing.c ***/
  108430. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  108431. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108432. // tasks..
  108433. #if JUCE_MSVC
  108434. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108435. #endif
  108436. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  108437. #if JUCE_USE_OGGVORBIS
  108438. #include <stdlib.h>
  108439. #include <string.h>
  108440. /* A complete description of Ogg framing exists in docs/framing.html */
  108441. int ogg_page_version(ogg_page *og){
  108442. return((int)(og->header[4]));
  108443. }
  108444. int ogg_page_continued(ogg_page *og){
  108445. return((int)(og->header[5]&0x01));
  108446. }
  108447. int ogg_page_bos(ogg_page *og){
  108448. return((int)(og->header[5]&0x02));
  108449. }
  108450. int ogg_page_eos(ogg_page *og){
  108451. return((int)(og->header[5]&0x04));
  108452. }
  108453. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  108454. unsigned char *page=og->header;
  108455. ogg_int64_t granulepos=page[13]&(0xff);
  108456. granulepos= (granulepos<<8)|(page[12]&0xff);
  108457. granulepos= (granulepos<<8)|(page[11]&0xff);
  108458. granulepos= (granulepos<<8)|(page[10]&0xff);
  108459. granulepos= (granulepos<<8)|(page[9]&0xff);
  108460. granulepos= (granulepos<<8)|(page[8]&0xff);
  108461. granulepos= (granulepos<<8)|(page[7]&0xff);
  108462. granulepos= (granulepos<<8)|(page[6]&0xff);
  108463. return(granulepos);
  108464. }
  108465. int ogg_page_serialno(ogg_page *og){
  108466. return(og->header[14] |
  108467. (og->header[15]<<8) |
  108468. (og->header[16]<<16) |
  108469. (og->header[17]<<24));
  108470. }
  108471. long ogg_page_pageno(ogg_page *og){
  108472. return(og->header[18] |
  108473. (og->header[19]<<8) |
  108474. (og->header[20]<<16) |
  108475. (og->header[21]<<24));
  108476. }
  108477. /* returns the number of packets that are completed on this page (if
  108478. the leading packet is begun on a previous page, but ends on this
  108479. page, it's counted */
  108480. /* NOTE:
  108481. If a page consists of a packet begun on a previous page, and a new
  108482. packet begun (but not completed) on this page, the return will be:
  108483. ogg_page_packets(page) ==1,
  108484. ogg_page_continued(page) !=0
  108485. If a page happens to be a single packet that was begun on a
  108486. previous page, and spans to the next page (in the case of a three or
  108487. more page packet), the return will be:
  108488. ogg_page_packets(page) ==0,
  108489. ogg_page_continued(page) !=0
  108490. */
  108491. int ogg_page_packets(ogg_page *og){
  108492. int i,n=og->header[26],count=0;
  108493. for(i=0;i<n;i++)
  108494. if(og->header[27+i]<255)count++;
  108495. return(count);
  108496. }
  108497. #if 0
  108498. /* helper to initialize lookup for direct-table CRC (illustrative; we
  108499. use the static init below) */
  108500. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  108501. int i;
  108502. unsigned long r;
  108503. r = index << 24;
  108504. for (i=0; i<8; i++)
  108505. if (r & 0x80000000UL)
  108506. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  108507. polynomial, although we use an
  108508. unreflected alg and an init/final
  108509. of 0, not 0xffffffff */
  108510. else
  108511. r<<=1;
  108512. return (r & 0xffffffffUL);
  108513. }
  108514. #endif
  108515. static const ogg_uint32_t crc_lookup[256]={
  108516. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  108517. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  108518. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  108519. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  108520. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  108521. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  108522. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  108523. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  108524. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  108525. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  108526. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  108527. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  108528. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  108529. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  108530. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  108531. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  108532. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  108533. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  108534. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  108535. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  108536. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  108537. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  108538. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  108539. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  108540. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  108541. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  108542. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  108543. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  108544. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  108545. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  108546. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  108547. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  108548. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  108549. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  108550. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  108551. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  108552. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  108553. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  108554. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  108555. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  108556. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  108557. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  108558. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  108559. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  108560. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  108561. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  108562. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  108563. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  108564. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  108565. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  108566. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  108567. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  108568. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  108569. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  108570. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  108571. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  108572. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  108573. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  108574. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  108575. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  108576. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  108577. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  108578. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  108579. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  108580. /* init the encode/decode logical stream state */
  108581. int ogg_stream_init(ogg_stream_state *os,int serialno){
  108582. if(os){
  108583. memset(os,0,sizeof(*os));
  108584. os->body_storage=16*1024;
  108585. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  108586. os->lacing_storage=1024;
  108587. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  108588. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  108589. os->serialno=serialno;
  108590. return(0);
  108591. }
  108592. return(-1);
  108593. }
  108594. /* _clear does not free os, only the non-flat storage within */
  108595. int ogg_stream_clear(ogg_stream_state *os){
  108596. if(os){
  108597. if(os->body_data)_ogg_free(os->body_data);
  108598. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  108599. if(os->granule_vals)_ogg_free(os->granule_vals);
  108600. memset(os,0,sizeof(*os));
  108601. }
  108602. return(0);
  108603. }
  108604. int ogg_stream_destroy(ogg_stream_state *os){
  108605. if(os){
  108606. ogg_stream_clear(os);
  108607. _ogg_free(os);
  108608. }
  108609. return(0);
  108610. }
  108611. /* Helpers for ogg_stream_encode; this keeps the structure and
  108612. what's happening fairly clear */
  108613. static void _os_body_expand(ogg_stream_state *os,int needed){
  108614. if(os->body_storage<=os->body_fill+needed){
  108615. os->body_storage+=(needed+1024);
  108616. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  108617. }
  108618. }
  108619. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  108620. if(os->lacing_storage<=os->lacing_fill+needed){
  108621. os->lacing_storage+=(needed+32);
  108622. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  108623. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  108624. }
  108625. }
  108626. /* checksum the page */
  108627. /* Direct table CRC; note that this will be faster in the future if we
  108628. perform the checksum silmultaneously with other copies */
  108629. void ogg_page_checksum_set(ogg_page *og){
  108630. if(og){
  108631. ogg_uint32_t crc_reg=0;
  108632. int i;
  108633. /* safety; needed for API behavior, but not framing code */
  108634. og->header[22]=0;
  108635. og->header[23]=0;
  108636. og->header[24]=0;
  108637. og->header[25]=0;
  108638. for(i=0;i<og->header_len;i++)
  108639. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  108640. for(i=0;i<og->body_len;i++)
  108641. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  108642. og->header[22]=(unsigned char)(crc_reg&0xff);
  108643. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  108644. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  108645. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  108646. }
  108647. }
  108648. /* submit data to the internal buffer of the framing engine */
  108649. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  108650. int lacing_vals=op->bytes/255+1,i;
  108651. if(os->body_returned){
  108652. /* advance packet data according to the body_returned pointer. We
  108653. had to keep it around to return a pointer into the buffer last
  108654. call */
  108655. os->body_fill-=os->body_returned;
  108656. if(os->body_fill)
  108657. memmove(os->body_data,os->body_data+os->body_returned,
  108658. os->body_fill);
  108659. os->body_returned=0;
  108660. }
  108661. /* make sure we have the buffer storage */
  108662. _os_body_expand(os,op->bytes);
  108663. _os_lacing_expand(os,lacing_vals);
  108664. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  108665. the liability of overly clean abstraction for the time being. It
  108666. will actually be fairly easy to eliminate the extra copy in the
  108667. future */
  108668. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  108669. os->body_fill+=op->bytes;
  108670. /* Store lacing vals for this packet */
  108671. for(i=0;i<lacing_vals-1;i++){
  108672. os->lacing_vals[os->lacing_fill+i]=255;
  108673. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  108674. }
  108675. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  108676. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  108677. /* flag the first segment as the beginning of the packet */
  108678. os->lacing_vals[os->lacing_fill]|= 0x100;
  108679. os->lacing_fill+=lacing_vals;
  108680. /* for the sake of completeness */
  108681. os->packetno++;
  108682. if(op->e_o_s)os->e_o_s=1;
  108683. return(0);
  108684. }
  108685. /* This will flush remaining packets into a page (returning nonzero),
  108686. even if there is not enough data to trigger a flush normally
  108687. (undersized page). If there are no packets or partial packets to
  108688. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  108689. try to flush a normal sized page like ogg_stream_pageout; a call to
  108690. ogg_stream_flush does not guarantee that all packets have flushed.
  108691. Only a return value of 0 from ogg_stream_flush indicates all packet
  108692. data is flushed into pages.
  108693. since ogg_stream_flush will flush the last page in a stream even if
  108694. it's undersized, you almost certainly want to use ogg_stream_pageout
  108695. (and *not* ogg_stream_flush) unless you specifically need to flush
  108696. an page regardless of size in the middle of a stream. */
  108697. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  108698. int i;
  108699. int vals=0;
  108700. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  108701. int bytes=0;
  108702. long acc=0;
  108703. ogg_int64_t granule_pos=-1;
  108704. if(maxvals==0)return(0);
  108705. /* construct a page */
  108706. /* decide how many segments to include */
  108707. /* If this is the initial header case, the first page must only include
  108708. the initial header packet */
  108709. if(os->b_o_s==0){ /* 'initial header page' case */
  108710. granule_pos=0;
  108711. for(vals=0;vals<maxvals;vals++){
  108712. if((os->lacing_vals[vals]&0x0ff)<255){
  108713. vals++;
  108714. break;
  108715. }
  108716. }
  108717. }else{
  108718. for(vals=0;vals<maxvals;vals++){
  108719. if(acc>4096)break;
  108720. acc+=os->lacing_vals[vals]&0x0ff;
  108721. if((os->lacing_vals[vals]&0xff)<255)
  108722. granule_pos=os->granule_vals[vals];
  108723. }
  108724. }
  108725. /* construct the header in temp storage */
  108726. memcpy(os->header,"OggS",4);
  108727. /* stream structure version */
  108728. os->header[4]=0x00;
  108729. /* continued packet flag? */
  108730. os->header[5]=0x00;
  108731. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  108732. /* first page flag? */
  108733. if(os->b_o_s==0)os->header[5]|=0x02;
  108734. /* last page flag? */
  108735. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  108736. os->b_o_s=1;
  108737. /* 64 bits of PCM position */
  108738. for(i=6;i<14;i++){
  108739. os->header[i]=(unsigned char)(granule_pos&0xff);
  108740. granule_pos>>=8;
  108741. }
  108742. /* 32 bits of stream serial number */
  108743. {
  108744. long serialno=os->serialno;
  108745. for(i=14;i<18;i++){
  108746. os->header[i]=(unsigned char)(serialno&0xff);
  108747. serialno>>=8;
  108748. }
  108749. }
  108750. /* 32 bits of page counter (we have both counter and page header
  108751. because this val can roll over) */
  108752. if(os->pageno==-1)os->pageno=0; /* because someone called
  108753. stream_reset; this would be a
  108754. strange thing to do in an
  108755. encode stream, but it has
  108756. plausible uses */
  108757. {
  108758. long pageno=os->pageno++;
  108759. for(i=18;i<22;i++){
  108760. os->header[i]=(unsigned char)(pageno&0xff);
  108761. pageno>>=8;
  108762. }
  108763. }
  108764. /* zero for computation; filled in later */
  108765. os->header[22]=0;
  108766. os->header[23]=0;
  108767. os->header[24]=0;
  108768. os->header[25]=0;
  108769. /* segment table */
  108770. os->header[26]=(unsigned char)(vals&0xff);
  108771. for(i=0;i<vals;i++)
  108772. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  108773. /* set pointers in the ogg_page struct */
  108774. og->header=os->header;
  108775. og->header_len=os->header_fill=vals+27;
  108776. og->body=os->body_data+os->body_returned;
  108777. og->body_len=bytes;
  108778. /* advance the lacing data and set the body_returned pointer */
  108779. os->lacing_fill-=vals;
  108780. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  108781. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  108782. os->body_returned+=bytes;
  108783. /* calculate the checksum */
  108784. ogg_page_checksum_set(og);
  108785. /* done */
  108786. return(1);
  108787. }
  108788. /* This constructs pages from buffered packet segments. The pointers
  108789. returned are to static buffers; do not free. The returned buffers are
  108790. good only until the next call (using the same ogg_stream_state) */
  108791. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  108792. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  108793. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  108794. os->lacing_fill>=255 || /* 'segment table full' case */
  108795. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  108796. return(ogg_stream_flush(os,og));
  108797. }
  108798. /* not enough data to construct a page and not end of stream */
  108799. return(0);
  108800. }
  108801. int ogg_stream_eos(ogg_stream_state *os){
  108802. return os->e_o_s;
  108803. }
  108804. /* DECODING PRIMITIVES: packet streaming layer **********************/
  108805. /* This has two layers to place more of the multi-serialno and paging
  108806. control in the application's hands. First, we expose a data buffer
  108807. using ogg_sync_buffer(). The app either copies into the
  108808. buffer, or passes it directly to read(), etc. We then call
  108809. ogg_sync_wrote() to tell how many bytes we just added.
  108810. Pages are returned (pointers into the buffer in ogg_sync_state)
  108811. by ogg_sync_pageout(). The page is then submitted to
  108812. ogg_stream_pagein() along with the appropriate
  108813. ogg_stream_state* (ie, matching serialno). We then get raw
  108814. packets out calling ogg_stream_packetout() with a
  108815. ogg_stream_state. */
  108816. /* initialize the struct to a known state */
  108817. int ogg_sync_init(ogg_sync_state *oy){
  108818. if(oy){
  108819. memset(oy,0,sizeof(*oy));
  108820. }
  108821. return(0);
  108822. }
  108823. /* clear non-flat storage within */
  108824. int ogg_sync_clear(ogg_sync_state *oy){
  108825. if(oy){
  108826. if(oy->data)_ogg_free(oy->data);
  108827. ogg_sync_init(oy);
  108828. }
  108829. return(0);
  108830. }
  108831. int ogg_sync_destroy(ogg_sync_state *oy){
  108832. if(oy){
  108833. ogg_sync_clear(oy);
  108834. _ogg_free(oy);
  108835. }
  108836. return(0);
  108837. }
  108838. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  108839. /* first, clear out any space that has been previously returned */
  108840. if(oy->returned){
  108841. oy->fill-=oy->returned;
  108842. if(oy->fill>0)
  108843. memmove(oy->data,oy->data+oy->returned,oy->fill);
  108844. oy->returned=0;
  108845. }
  108846. if(size>oy->storage-oy->fill){
  108847. /* We need to extend the internal buffer */
  108848. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  108849. if(oy->data)
  108850. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  108851. else
  108852. oy->data=(unsigned char*) _ogg_malloc(newsize);
  108853. oy->storage=newsize;
  108854. }
  108855. /* expose a segment at least as large as requested at the fill mark */
  108856. return((char *)oy->data+oy->fill);
  108857. }
  108858. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  108859. if(oy->fill+bytes>oy->storage)return(-1);
  108860. oy->fill+=bytes;
  108861. return(0);
  108862. }
  108863. /* sync the stream. This is meant to be useful for finding page
  108864. boundaries.
  108865. return values for this:
  108866. -n) skipped n bytes
  108867. 0) page not ready; more data (no bytes skipped)
  108868. n) page synced at current location; page length n bytes
  108869. */
  108870. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  108871. unsigned char *page=oy->data+oy->returned;
  108872. unsigned char *next;
  108873. long bytes=oy->fill-oy->returned;
  108874. if(oy->headerbytes==0){
  108875. int headerbytes,i;
  108876. if(bytes<27)return(0); /* not enough for a header */
  108877. /* verify capture pattern */
  108878. if(memcmp(page,"OggS",4))goto sync_fail;
  108879. headerbytes=page[26]+27;
  108880. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  108881. /* count up body length in the segment table */
  108882. for(i=0;i<page[26];i++)
  108883. oy->bodybytes+=page[27+i];
  108884. oy->headerbytes=headerbytes;
  108885. }
  108886. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  108887. /* The whole test page is buffered. Verify the checksum */
  108888. {
  108889. /* Grab the checksum bytes, set the header field to zero */
  108890. char chksum[4];
  108891. ogg_page log;
  108892. memcpy(chksum,page+22,4);
  108893. memset(page+22,0,4);
  108894. /* set up a temp page struct and recompute the checksum */
  108895. log.header=page;
  108896. log.header_len=oy->headerbytes;
  108897. log.body=page+oy->headerbytes;
  108898. log.body_len=oy->bodybytes;
  108899. ogg_page_checksum_set(&log);
  108900. /* Compare */
  108901. if(memcmp(chksum,page+22,4)){
  108902. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  108903. at all) */
  108904. /* replace the computed checksum with the one actually read in */
  108905. memcpy(page+22,chksum,4);
  108906. /* Bad checksum. Lose sync */
  108907. goto sync_fail;
  108908. }
  108909. }
  108910. /* yes, have a whole page all ready to go */
  108911. {
  108912. unsigned char *page=oy->data+oy->returned;
  108913. long bytes;
  108914. if(og){
  108915. og->header=page;
  108916. og->header_len=oy->headerbytes;
  108917. og->body=page+oy->headerbytes;
  108918. og->body_len=oy->bodybytes;
  108919. }
  108920. oy->unsynced=0;
  108921. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  108922. oy->headerbytes=0;
  108923. oy->bodybytes=0;
  108924. return(bytes);
  108925. }
  108926. sync_fail:
  108927. oy->headerbytes=0;
  108928. oy->bodybytes=0;
  108929. /* search for possible capture */
  108930. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  108931. if(!next)
  108932. next=oy->data+oy->fill;
  108933. oy->returned=next-oy->data;
  108934. return(-(next-page));
  108935. }
  108936. /* sync the stream and get a page. Keep trying until we find a page.
  108937. Supress 'sync errors' after reporting the first.
  108938. return values:
  108939. -1) recapture (hole in data)
  108940. 0) need more data
  108941. 1) page returned
  108942. Returns pointers into buffered data; invalidated by next call to
  108943. _stream, _clear, _init, or _buffer */
  108944. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  108945. /* all we need to do is verify a page at the head of the stream
  108946. buffer. If it doesn't verify, we look for the next potential
  108947. frame */
  108948. for(;;){
  108949. long ret=ogg_sync_pageseek(oy,og);
  108950. if(ret>0){
  108951. /* have a page */
  108952. return(1);
  108953. }
  108954. if(ret==0){
  108955. /* need more data */
  108956. return(0);
  108957. }
  108958. /* head did not start a synced page... skipped some bytes */
  108959. if(!oy->unsynced){
  108960. oy->unsynced=1;
  108961. return(-1);
  108962. }
  108963. /* loop. keep looking */
  108964. }
  108965. }
  108966. /* add the incoming page to the stream state; we decompose the page
  108967. into packet segments here as well. */
  108968. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  108969. unsigned char *header=og->header;
  108970. unsigned char *body=og->body;
  108971. long bodysize=og->body_len;
  108972. int segptr=0;
  108973. int version=ogg_page_version(og);
  108974. int continued=ogg_page_continued(og);
  108975. int bos=ogg_page_bos(og);
  108976. int eos=ogg_page_eos(og);
  108977. ogg_int64_t granulepos=ogg_page_granulepos(og);
  108978. int serialno=ogg_page_serialno(og);
  108979. long pageno=ogg_page_pageno(og);
  108980. int segments=header[26];
  108981. /* clean up 'returned data' */
  108982. {
  108983. long lr=os->lacing_returned;
  108984. long br=os->body_returned;
  108985. /* body data */
  108986. if(br){
  108987. os->body_fill-=br;
  108988. if(os->body_fill)
  108989. memmove(os->body_data,os->body_data+br,os->body_fill);
  108990. os->body_returned=0;
  108991. }
  108992. if(lr){
  108993. /* segment table */
  108994. if(os->lacing_fill-lr){
  108995. memmove(os->lacing_vals,os->lacing_vals+lr,
  108996. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  108997. memmove(os->granule_vals,os->granule_vals+lr,
  108998. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  108999. }
  109000. os->lacing_fill-=lr;
  109001. os->lacing_packet-=lr;
  109002. os->lacing_returned=0;
  109003. }
  109004. }
  109005. /* check the serial number */
  109006. if(serialno!=os->serialno)return(-1);
  109007. if(version>0)return(-1);
  109008. _os_lacing_expand(os,segments+1);
  109009. /* are we in sequence? */
  109010. if(pageno!=os->pageno){
  109011. int i;
  109012. /* unroll previous partial packet (if any) */
  109013. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  109014. os->body_fill-=os->lacing_vals[i]&0xff;
  109015. os->lacing_fill=os->lacing_packet;
  109016. /* make a note of dropped data in segment table */
  109017. if(os->pageno!=-1){
  109018. os->lacing_vals[os->lacing_fill++]=0x400;
  109019. os->lacing_packet++;
  109020. }
  109021. }
  109022. /* are we a 'continued packet' page? If so, we may need to skip
  109023. some segments */
  109024. if(continued){
  109025. if(os->lacing_fill<1 ||
  109026. os->lacing_vals[os->lacing_fill-1]==0x400){
  109027. bos=0;
  109028. for(;segptr<segments;segptr++){
  109029. int val=header[27+segptr];
  109030. body+=val;
  109031. bodysize-=val;
  109032. if(val<255){
  109033. segptr++;
  109034. break;
  109035. }
  109036. }
  109037. }
  109038. }
  109039. if(bodysize){
  109040. _os_body_expand(os,bodysize);
  109041. memcpy(os->body_data+os->body_fill,body,bodysize);
  109042. os->body_fill+=bodysize;
  109043. }
  109044. {
  109045. int saved=-1;
  109046. while(segptr<segments){
  109047. int val=header[27+segptr];
  109048. os->lacing_vals[os->lacing_fill]=val;
  109049. os->granule_vals[os->lacing_fill]=-1;
  109050. if(bos){
  109051. os->lacing_vals[os->lacing_fill]|=0x100;
  109052. bos=0;
  109053. }
  109054. if(val<255)saved=os->lacing_fill;
  109055. os->lacing_fill++;
  109056. segptr++;
  109057. if(val<255)os->lacing_packet=os->lacing_fill;
  109058. }
  109059. /* set the granulepos on the last granuleval of the last full packet */
  109060. if(saved!=-1){
  109061. os->granule_vals[saved]=granulepos;
  109062. }
  109063. }
  109064. if(eos){
  109065. os->e_o_s=1;
  109066. if(os->lacing_fill>0)
  109067. os->lacing_vals[os->lacing_fill-1]|=0x200;
  109068. }
  109069. os->pageno=pageno+1;
  109070. return(0);
  109071. }
  109072. /* clear things to an initial state. Good to call, eg, before seeking */
  109073. int ogg_sync_reset(ogg_sync_state *oy){
  109074. oy->fill=0;
  109075. oy->returned=0;
  109076. oy->unsynced=0;
  109077. oy->headerbytes=0;
  109078. oy->bodybytes=0;
  109079. return(0);
  109080. }
  109081. int ogg_stream_reset(ogg_stream_state *os){
  109082. os->body_fill=0;
  109083. os->body_returned=0;
  109084. os->lacing_fill=0;
  109085. os->lacing_packet=0;
  109086. os->lacing_returned=0;
  109087. os->header_fill=0;
  109088. os->e_o_s=0;
  109089. os->b_o_s=0;
  109090. os->pageno=-1;
  109091. os->packetno=0;
  109092. os->granulepos=0;
  109093. return(0);
  109094. }
  109095. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  109096. ogg_stream_reset(os);
  109097. os->serialno=serialno;
  109098. return(0);
  109099. }
  109100. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  109101. /* The last part of decode. We have the stream broken into packet
  109102. segments. Now we need to group them into packets (or return the
  109103. out of sync markers) */
  109104. int ptr=os->lacing_returned;
  109105. if(os->lacing_packet<=ptr)return(0);
  109106. if(os->lacing_vals[ptr]&0x400){
  109107. /* we need to tell the codec there's a gap; it might need to
  109108. handle previous packet dependencies. */
  109109. os->lacing_returned++;
  109110. os->packetno++;
  109111. return(-1);
  109112. }
  109113. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  109114. to ask if there's a whole packet
  109115. waiting */
  109116. /* Gather the whole packet. We'll have no holes or a partial packet */
  109117. {
  109118. int size=os->lacing_vals[ptr]&0xff;
  109119. int bytes=size;
  109120. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  109121. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  109122. while(size==255){
  109123. int val=os->lacing_vals[++ptr];
  109124. size=val&0xff;
  109125. if(val&0x200)eos=0x200;
  109126. bytes+=size;
  109127. }
  109128. if(op){
  109129. op->e_o_s=eos;
  109130. op->b_o_s=bos;
  109131. op->packet=os->body_data+os->body_returned;
  109132. op->packetno=os->packetno;
  109133. op->granulepos=os->granule_vals[ptr];
  109134. op->bytes=bytes;
  109135. }
  109136. if(adv){
  109137. os->body_returned+=bytes;
  109138. os->lacing_returned=ptr+1;
  109139. os->packetno++;
  109140. }
  109141. }
  109142. return(1);
  109143. }
  109144. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  109145. return _packetout(os,op,1);
  109146. }
  109147. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  109148. return _packetout(os,op,0);
  109149. }
  109150. void ogg_packet_clear(ogg_packet *op) {
  109151. _ogg_free(op->packet);
  109152. memset(op, 0, sizeof(*op));
  109153. }
  109154. #ifdef _V_SELFTEST
  109155. #include <stdio.h>
  109156. ogg_stream_state os_en, os_de;
  109157. ogg_sync_state oy;
  109158. void checkpacket(ogg_packet *op,int len, int no, int pos){
  109159. long j;
  109160. static int sequence=0;
  109161. static int lastno=0;
  109162. if(op->bytes!=len){
  109163. fprintf(stderr,"incorrect packet length!\n");
  109164. exit(1);
  109165. }
  109166. if(op->granulepos!=pos){
  109167. fprintf(stderr,"incorrect packet position!\n");
  109168. exit(1);
  109169. }
  109170. /* packet number just follows sequence/gap; adjust the input number
  109171. for that */
  109172. if(no==0){
  109173. sequence=0;
  109174. }else{
  109175. sequence++;
  109176. if(no>lastno+1)
  109177. sequence++;
  109178. }
  109179. lastno=no;
  109180. if(op->packetno!=sequence){
  109181. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  109182. (long)(op->packetno),sequence);
  109183. exit(1);
  109184. }
  109185. /* Test data */
  109186. for(j=0;j<op->bytes;j++)
  109187. if(op->packet[j]!=((j+no)&0xff)){
  109188. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  109189. j,op->packet[j],(j+no)&0xff);
  109190. exit(1);
  109191. }
  109192. }
  109193. void check_page(unsigned char *data,const int *header,ogg_page *og){
  109194. long j;
  109195. /* Test data */
  109196. for(j=0;j<og->body_len;j++)
  109197. if(og->body[j]!=data[j]){
  109198. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  109199. j,data[j],og->body[j]);
  109200. exit(1);
  109201. }
  109202. /* Test header */
  109203. for(j=0;j<og->header_len;j++){
  109204. if(og->header[j]!=header[j]){
  109205. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  109206. for(j=0;j<header[26]+27;j++)
  109207. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  109208. fprintf(stderr,"\n");
  109209. exit(1);
  109210. }
  109211. }
  109212. if(og->header_len!=header[26]+27){
  109213. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  109214. og->header_len,header[26]+27);
  109215. exit(1);
  109216. }
  109217. }
  109218. void print_header(ogg_page *og){
  109219. int j;
  109220. fprintf(stderr,"\nHEADER:\n");
  109221. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  109222. og->header[0],og->header[1],og->header[2],og->header[3],
  109223. (int)og->header[4],(int)og->header[5]);
  109224. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  109225. (og->header[9]<<24)|(og->header[8]<<16)|
  109226. (og->header[7]<<8)|og->header[6],
  109227. (og->header[17]<<24)|(og->header[16]<<16)|
  109228. (og->header[15]<<8)|og->header[14],
  109229. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  109230. (og->header[19]<<8)|og->header[18]);
  109231. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  109232. (int)og->header[22],(int)og->header[23],
  109233. (int)og->header[24],(int)og->header[25],
  109234. (int)og->header[26]);
  109235. for(j=27;j<og->header_len;j++)
  109236. fprintf(stderr,"%d ",(int)og->header[j]);
  109237. fprintf(stderr,")\n\n");
  109238. }
  109239. void copy_page(ogg_page *og){
  109240. unsigned char *temp=_ogg_malloc(og->header_len);
  109241. memcpy(temp,og->header,og->header_len);
  109242. og->header=temp;
  109243. temp=_ogg_malloc(og->body_len);
  109244. memcpy(temp,og->body,og->body_len);
  109245. og->body=temp;
  109246. }
  109247. void free_page(ogg_page *og){
  109248. _ogg_free (og->header);
  109249. _ogg_free (og->body);
  109250. }
  109251. void error(void){
  109252. fprintf(stderr,"error!\n");
  109253. exit(1);
  109254. }
  109255. /* 17 only */
  109256. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  109257. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109258. 0x01,0x02,0x03,0x04,0,0,0,0,
  109259. 0x15,0xed,0xec,0x91,
  109260. 1,
  109261. 17};
  109262. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109263. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109264. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109265. 0x01,0x02,0x03,0x04,0,0,0,0,
  109266. 0x59,0x10,0x6c,0x2c,
  109267. 1,
  109268. 17};
  109269. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109270. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  109271. 0x01,0x02,0x03,0x04,1,0,0,0,
  109272. 0x89,0x33,0x85,0xce,
  109273. 13,
  109274. 254,255,0,255,1,255,245,255,255,0,
  109275. 255,255,90};
  109276. /* nil packets; beginning,middle,end */
  109277. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109278. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109279. 0x01,0x02,0x03,0x04,0,0,0,0,
  109280. 0xff,0x7b,0x23,0x17,
  109281. 1,
  109282. 0};
  109283. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109284. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  109285. 0x01,0x02,0x03,0x04,1,0,0,0,
  109286. 0x5c,0x3f,0x66,0xcb,
  109287. 17,
  109288. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  109289. 255,255,90,0};
  109290. /* large initial packet */
  109291. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109292. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109293. 0x01,0x02,0x03,0x04,0,0,0,0,
  109294. 0x01,0x27,0x31,0xaa,
  109295. 18,
  109296. 255,255,255,255,255,255,255,255,
  109297. 255,255,255,255,255,255,255,255,255,10};
  109298. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109299. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109300. 0x01,0x02,0x03,0x04,1,0,0,0,
  109301. 0x7f,0x4e,0x8a,0xd2,
  109302. 4,
  109303. 255,4,255,0};
  109304. /* continuing packet test */
  109305. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109306. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109307. 0x01,0x02,0x03,0x04,0,0,0,0,
  109308. 0xff,0x7b,0x23,0x17,
  109309. 1,
  109310. 0};
  109311. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109312. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109313. 0x01,0x02,0x03,0x04,1,0,0,0,
  109314. 0x54,0x05,0x51,0xc8,
  109315. 17,
  109316. 255,255,255,255,255,255,255,255,
  109317. 255,255,255,255,255,255,255,255,255};
  109318. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109319. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  109320. 0x01,0x02,0x03,0x04,2,0,0,0,
  109321. 0xc8,0xc3,0xcb,0xed,
  109322. 5,
  109323. 10,255,4,255,0};
  109324. /* page with the 255 segment limit */
  109325. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109326. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109327. 0x01,0x02,0x03,0x04,0,0,0,0,
  109328. 0xff,0x7b,0x23,0x17,
  109329. 1,
  109330. 0};
  109331. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109332. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  109333. 0x01,0x02,0x03,0x04,1,0,0,0,
  109334. 0xed,0x2a,0x2e,0xa7,
  109335. 255,
  109336. 10,10,10,10,10,10,10,10,
  109337. 10,10,10,10,10,10,10,10,
  109338. 10,10,10,10,10,10,10,10,
  109339. 10,10,10,10,10,10,10,10,
  109340. 10,10,10,10,10,10,10,10,
  109341. 10,10,10,10,10,10,10,10,
  109342. 10,10,10,10,10,10,10,10,
  109343. 10,10,10,10,10,10,10,10,
  109344. 10,10,10,10,10,10,10,10,
  109345. 10,10,10,10,10,10,10,10,
  109346. 10,10,10,10,10,10,10,10,
  109347. 10,10,10,10,10,10,10,10,
  109348. 10,10,10,10,10,10,10,10,
  109349. 10,10,10,10,10,10,10,10,
  109350. 10,10,10,10,10,10,10,10,
  109351. 10,10,10,10,10,10,10,10,
  109352. 10,10,10,10,10,10,10,10,
  109353. 10,10,10,10,10,10,10,10,
  109354. 10,10,10,10,10,10,10,10,
  109355. 10,10,10,10,10,10,10,10,
  109356. 10,10,10,10,10,10,10,10,
  109357. 10,10,10,10,10,10,10,10,
  109358. 10,10,10,10,10,10,10,10,
  109359. 10,10,10,10,10,10,10,10,
  109360. 10,10,10,10,10,10,10,10,
  109361. 10,10,10,10,10,10,10,10,
  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};
  109368. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109369. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  109370. 0x01,0x02,0x03,0x04,2,0,0,0,
  109371. 0x6c,0x3b,0x82,0x3d,
  109372. 1,
  109373. 50};
  109374. /* packet that overspans over an entire page */
  109375. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109376. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109377. 0x01,0x02,0x03,0x04,0,0,0,0,
  109378. 0xff,0x7b,0x23,0x17,
  109379. 1,
  109380. 0};
  109381. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109382. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109383. 0x01,0x02,0x03,0x04,1,0,0,0,
  109384. 0x3c,0xd9,0x4d,0x3f,
  109385. 17,
  109386. 100,255,255,255,255,255,255,255,255,
  109387. 255,255,255,255,255,255,255,255};
  109388. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  109389. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109390. 0x01,0x02,0x03,0x04,2,0,0,0,
  109391. 0x01,0xd2,0xe5,0xe5,
  109392. 17,
  109393. 255,255,255,255,255,255,255,255,
  109394. 255,255,255,255,255,255,255,255,255};
  109395. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109396. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  109397. 0x01,0x02,0x03,0x04,3,0,0,0,
  109398. 0xef,0xdd,0x88,0xde,
  109399. 7,
  109400. 255,255,75,255,4,255,0};
  109401. /* packet that overspans over an entire page */
  109402. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109403. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109404. 0x01,0x02,0x03,0x04,0,0,0,0,
  109405. 0xff,0x7b,0x23,0x17,
  109406. 1,
  109407. 0};
  109408. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109409. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109410. 0x01,0x02,0x03,0x04,1,0,0,0,
  109411. 0x3c,0xd9,0x4d,0x3f,
  109412. 17,
  109413. 100,255,255,255,255,255,255,255,255,
  109414. 255,255,255,255,255,255,255,255};
  109415. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109416. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109417. 0x01,0x02,0x03,0x04,2,0,0,0,
  109418. 0xd4,0xe0,0x60,0xe5,
  109419. 1,0};
  109420. void test_pack(const int *pl, const int **headers, int byteskip,
  109421. int pageskip, int packetskip){
  109422. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  109423. long inptr=0;
  109424. long outptr=0;
  109425. long deptr=0;
  109426. long depacket=0;
  109427. long granule_pos=7,pageno=0;
  109428. int i,j,packets,pageout=pageskip;
  109429. int eosflag=0;
  109430. int bosflag=0;
  109431. int byteskipcount=0;
  109432. ogg_stream_reset(&os_en);
  109433. ogg_stream_reset(&os_de);
  109434. ogg_sync_reset(&oy);
  109435. for(packets=0;packets<packetskip;packets++)
  109436. depacket+=pl[packets];
  109437. for(packets=0;;packets++)if(pl[packets]==-1)break;
  109438. for(i=0;i<packets;i++){
  109439. /* construct a test packet */
  109440. ogg_packet op;
  109441. int len=pl[i];
  109442. op.packet=data+inptr;
  109443. op.bytes=len;
  109444. op.e_o_s=(pl[i+1]<0?1:0);
  109445. op.granulepos=granule_pos;
  109446. granule_pos+=1024;
  109447. for(j=0;j<len;j++)data[inptr++]=i+j;
  109448. /* submit the test packet */
  109449. ogg_stream_packetin(&os_en,&op);
  109450. /* retrieve any finished pages */
  109451. {
  109452. ogg_page og;
  109453. while(ogg_stream_pageout(&os_en,&og)){
  109454. /* We have a page. Check it carefully */
  109455. fprintf(stderr,"%ld, ",pageno);
  109456. if(headers[pageno]==NULL){
  109457. fprintf(stderr,"coded too many pages!\n");
  109458. exit(1);
  109459. }
  109460. check_page(data+outptr,headers[pageno],&og);
  109461. outptr+=og.body_len;
  109462. pageno++;
  109463. if(pageskip){
  109464. bosflag=1;
  109465. pageskip--;
  109466. deptr+=og.body_len;
  109467. }
  109468. /* have a complete page; submit it to sync/decode */
  109469. {
  109470. ogg_page og_de;
  109471. ogg_packet op_de,op_de2;
  109472. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  109473. char *next=buf;
  109474. byteskipcount+=og.header_len;
  109475. if(byteskipcount>byteskip){
  109476. memcpy(next,og.header,byteskipcount-byteskip);
  109477. next+=byteskipcount-byteskip;
  109478. byteskipcount=byteskip;
  109479. }
  109480. byteskipcount+=og.body_len;
  109481. if(byteskipcount>byteskip){
  109482. memcpy(next,og.body,byteskipcount-byteskip);
  109483. next+=byteskipcount-byteskip;
  109484. byteskipcount=byteskip;
  109485. }
  109486. ogg_sync_wrote(&oy,next-buf);
  109487. while(1){
  109488. int ret=ogg_sync_pageout(&oy,&og_de);
  109489. if(ret==0)break;
  109490. if(ret<0)continue;
  109491. /* got a page. Happy happy. Verify that it's good. */
  109492. fprintf(stderr,"(%ld), ",pageout);
  109493. check_page(data+deptr,headers[pageout],&og_de);
  109494. deptr+=og_de.body_len;
  109495. pageout++;
  109496. /* submit it to deconstitution */
  109497. ogg_stream_pagein(&os_de,&og_de);
  109498. /* packets out? */
  109499. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  109500. ogg_stream_packetpeek(&os_de,NULL);
  109501. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  109502. /* verify peek and out match */
  109503. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  109504. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  109505. depacket);
  109506. exit(1);
  109507. }
  109508. /* verify the packet! */
  109509. /* check data */
  109510. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  109511. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  109512. depacket);
  109513. exit(1);
  109514. }
  109515. /* check bos flag */
  109516. if(bosflag==0 && op_de.b_o_s==0){
  109517. fprintf(stderr,"b_o_s flag not set on packet!\n");
  109518. exit(1);
  109519. }
  109520. if(bosflag && op_de.b_o_s){
  109521. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  109522. exit(1);
  109523. }
  109524. bosflag=1;
  109525. depacket+=op_de.bytes;
  109526. /* check eos flag */
  109527. if(eosflag){
  109528. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  109529. exit(1);
  109530. }
  109531. if(op_de.e_o_s)eosflag=1;
  109532. /* check granulepos flag */
  109533. if(op_de.granulepos!=-1){
  109534. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  109535. }
  109536. }
  109537. }
  109538. }
  109539. }
  109540. }
  109541. }
  109542. _ogg_free(data);
  109543. if(headers[pageno]!=NULL){
  109544. fprintf(stderr,"did not write last page!\n");
  109545. exit(1);
  109546. }
  109547. if(headers[pageout]!=NULL){
  109548. fprintf(stderr,"did not decode last page!\n");
  109549. exit(1);
  109550. }
  109551. if(inptr!=outptr){
  109552. fprintf(stderr,"encoded page data incomplete!\n");
  109553. exit(1);
  109554. }
  109555. if(inptr!=deptr){
  109556. fprintf(stderr,"decoded page data incomplete!\n");
  109557. exit(1);
  109558. }
  109559. if(inptr!=depacket){
  109560. fprintf(stderr,"decoded packet data incomplete!\n");
  109561. exit(1);
  109562. }
  109563. if(!eosflag){
  109564. fprintf(stderr,"Never got a packet with EOS set!\n");
  109565. exit(1);
  109566. }
  109567. fprintf(stderr,"ok.\n");
  109568. }
  109569. int main(void){
  109570. ogg_stream_init(&os_en,0x04030201);
  109571. ogg_stream_init(&os_de,0x04030201);
  109572. ogg_sync_init(&oy);
  109573. /* Exercise each code path in the framing code. Also verify that
  109574. the checksums are working. */
  109575. {
  109576. /* 17 only */
  109577. const int packets[]={17, -1};
  109578. const int *headret[]={head1_0,NULL};
  109579. fprintf(stderr,"testing single page encoding... ");
  109580. test_pack(packets,headret,0,0,0);
  109581. }
  109582. {
  109583. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109584. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  109585. const int *headret[]={head1_1,head2_1,NULL};
  109586. fprintf(stderr,"testing basic page encoding... ");
  109587. test_pack(packets,headret,0,0,0);
  109588. }
  109589. {
  109590. /* nil packets; beginning,middle,end */
  109591. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  109592. const int *headret[]={head1_2,head2_2,NULL};
  109593. fprintf(stderr,"testing basic nil packets... ");
  109594. test_pack(packets,headret,0,0,0);
  109595. }
  109596. {
  109597. /* large initial packet */
  109598. const int packets[]={4345,259,255,-1};
  109599. const int *headret[]={head1_3,head2_3,NULL};
  109600. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  109601. test_pack(packets,headret,0,0,0);
  109602. }
  109603. {
  109604. /* continuing packet test */
  109605. const int packets[]={0,4345,259,255,-1};
  109606. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  109607. fprintf(stderr,"testing single packet page span... ");
  109608. test_pack(packets,headret,0,0,0);
  109609. }
  109610. /* page with the 255 segment limit */
  109611. {
  109612. const int packets[]={0,10,10,10,10,10,10,10,10,
  109613. 10,10,10,10,10,10,10,10,
  109614. 10,10,10,10,10,10,10,10,
  109615. 10,10,10,10,10,10,10,10,
  109616. 10,10,10,10,10,10,10,10,
  109617. 10,10,10,10,10,10,10,10,
  109618. 10,10,10,10,10,10,10,10,
  109619. 10,10,10,10,10,10,10,10,
  109620. 10,10,10,10,10,10,10,10,
  109621. 10,10,10,10,10,10,10,10,
  109622. 10,10,10,10,10,10,10,10,
  109623. 10,10,10,10,10,10,10,10,
  109624. 10,10,10,10,10,10,10,10,
  109625. 10,10,10,10,10,10,10,10,
  109626. 10,10,10,10,10,10,10,10,
  109627. 10,10,10,10,10,10,10,10,
  109628. 10,10,10,10,10,10,10,10,
  109629. 10,10,10,10,10,10,10,10,
  109630. 10,10,10,10,10,10,10,10,
  109631. 10,10,10,10,10,10,10,10,
  109632. 10,10,10,10,10,10,10,10,
  109633. 10,10,10,10,10,10,10,10,
  109634. 10,10,10,10,10,10,10,10,
  109635. 10,10,10,10,10,10,10,10,
  109636. 10,10,10,10,10,10,10,10,
  109637. 10,10,10,10,10,10,10,10,
  109638. 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,50,-1};
  109644. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  109645. fprintf(stderr,"testing max packet segments... ");
  109646. test_pack(packets,headret,0,0,0);
  109647. }
  109648. {
  109649. /* packet that overspans over an entire page */
  109650. const int packets[]={0,100,9000,259,255,-1};
  109651. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109652. fprintf(stderr,"testing very large packets... ");
  109653. test_pack(packets,headret,0,0,0);
  109654. }
  109655. {
  109656. /* test for the libogg 1.1.1 resync in large continuation bug
  109657. found by Josh Coalson) */
  109658. const int packets[]={0,100,9000,259,255,-1};
  109659. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109660. fprintf(stderr,"testing continuation resync in very large packets... ");
  109661. test_pack(packets,headret,100,2,3);
  109662. }
  109663. {
  109664. /* term only page. why not? */
  109665. const int packets[]={0,100,4080,-1};
  109666. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  109667. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  109668. test_pack(packets,headret,0,0,0);
  109669. }
  109670. {
  109671. /* build a bunch of pages for testing */
  109672. unsigned char *data=_ogg_malloc(1024*1024);
  109673. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  109674. int inptr=0,i,j;
  109675. ogg_page og[5];
  109676. ogg_stream_reset(&os_en);
  109677. for(i=0;pl[i]!=-1;i++){
  109678. ogg_packet op;
  109679. int len=pl[i];
  109680. op.packet=data+inptr;
  109681. op.bytes=len;
  109682. op.e_o_s=(pl[i+1]<0?1:0);
  109683. op.granulepos=(i+1)*1000;
  109684. for(j=0;j<len;j++)data[inptr++]=i+j;
  109685. ogg_stream_packetin(&os_en,&op);
  109686. }
  109687. _ogg_free(data);
  109688. /* retrieve finished pages */
  109689. for(i=0;i<5;i++){
  109690. if(ogg_stream_pageout(&os_en,&og[i])==0){
  109691. fprintf(stderr,"Too few pages output building sync tests!\n");
  109692. exit(1);
  109693. }
  109694. copy_page(&og[i]);
  109695. }
  109696. /* Test lost pages on pagein/packetout: no rollback */
  109697. {
  109698. ogg_page temp;
  109699. ogg_packet test;
  109700. fprintf(stderr,"Testing loss of pages... ");
  109701. ogg_sync_reset(&oy);
  109702. ogg_stream_reset(&os_de);
  109703. for(i=0;i<5;i++){
  109704. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109705. og[i].header_len);
  109706. ogg_sync_wrote(&oy,og[i].header_len);
  109707. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109708. ogg_sync_wrote(&oy,og[i].body_len);
  109709. }
  109710. ogg_sync_pageout(&oy,&temp);
  109711. ogg_stream_pagein(&os_de,&temp);
  109712. ogg_sync_pageout(&oy,&temp);
  109713. ogg_stream_pagein(&os_de,&temp);
  109714. ogg_sync_pageout(&oy,&temp);
  109715. /* skip */
  109716. ogg_sync_pageout(&oy,&temp);
  109717. ogg_stream_pagein(&os_de,&temp);
  109718. /* do we get the expected results/packets? */
  109719. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109720. checkpacket(&test,0,0,0);
  109721. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109722. checkpacket(&test,100,1,-1);
  109723. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109724. checkpacket(&test,4079,2,3000);
  109725. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109726. fprintf(stderr,"Error: loss of page did not return error\n");
  109727. exit(1);
  109728. }
  109729. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109730. checkpacket(&test,76,5,-1);
  109731. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109732. checkpacket(&test,34,6,-1);
  109733. fprintf(stderr,"ok.\n");
  109734. }
  109735. /* Test lost pages on pagein/packetout: rollback with continuation */
  109736. {
  109737. ogg_page temp;
  109738. ogg_packet test;
  109739. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  109740. ogg_sync_reset(&oy);
  109741. ogg_stream_reset(&os_de);
  109742. for(i=0;i<5;i++){
  109743. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109744. og[i].header_len);
  109745. ogg_sync_wrote(&oy,og[i].header_len);
  109746. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109747. ogg_sync_wrote(&oy,og[i].body_len);
  109748. }
  109749. ogg_sync_pageout(&oy,&temp);
  109750. ogg_stream_pagein(&os_de,&temp);
  109751. ogg_sync_pageout(&oy,&temp);
  109752. ogg_stream_pagein(&os_de,&temp);
  109753. ogg_sync_pageout(&oy,&temp);
  109754. ogg_stream_pagein(&os_de,&temp);
  109755. ogg_sync_pageout(&oy,&temp);
  109756. /* skip */
  109757. ogg_sync_pageout(&oy,&temp);
  109758. ogg_stream_pagein(&os_de,&temp);
  109759. /* do we get the expected results/packets? */
  109760. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109761. checkpacket(&test,0,0,0);
  109762. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109763. checkpacket(&test,100,1,-1);
  109764. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109765. checkpacket(&test,4079,2,3000);
  109766. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109767. checkpacket(&test,2956,3,4000);
  109768. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109769. fprintf(stderr,"Error: loss of page did not return error\n");
  109770. exit(1);
  109771. }
  109772. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109773. checkpacket(&test,300,13,14000);
  109774. fprintf(stderr,"ok.\n");
  109775. }
  109776. /* the rest only test sync */
  109777. {
  109778. ogg_page og_de;
  109779. /* Test fractional page inputs: incomplete capture */
  109780. fprintf(stderr,"Testing sync on partial inputs... ");
  109781. ogg_sync_reset(&oy);
  109782. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109783. 3);
  109784. ogg_sync_wrote(&oy,3);
  109785. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109786. /* Test fractional page inputs: incomplete fixed header */
  109787. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  109788. 20);
  109789. ogg_sync_wrote(&oy,20);
  109790. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109791. /* Test fractional page inputs: incomplete header */
  109792. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  109793. 5);
  109794. ogg_sync_wrote(&oy,5);
  109795. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109796. /* Test fractional page inputs: incomplete body */
  109797. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  109798. og[1].header_len-28);
  109799. ogg_sync_wrote(&oy,og[1].header_len-28);
  109800. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109801. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  109802. ogg_sync_wrote(&oy,1000);
  109803. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109804. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  109805. og[1].body_len-1000);
  109806. ogg_sync_wrote(&oy,og[1].body_len-1000);
  109807. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109808. fprintf(stderr,"ok.\n");
  109809. }
  109810. /* Test fractional page inputs: page + incomplete capture */
  109811. {
  109812. ogg_page og_de;
  109813. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  109814. ogg_sync_reset(&oy);
  109815. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109816. og[1].header_len);
  109817. ogg_sync_wrote(&oy,og[1].header_len);
  109818. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109819. og[1].body_len);
  109820. ogg_sync_wrote(&oy,og[1].body_len);
  109821. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109822. 20);
  109823. ogg_sync_wrote(&oy,20);
  109824. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109825. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109826. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  109827. og[1].header_len-20);
  109828. ogg_sync_wrote(&oy,og[1].header_len-20);
  109829. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109830. og[1].body_len);
  109831. ogg_sync_wrote(&oy,og[1].body_len);
  109832. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109833. fprintf(stderr,"ok.\n");
  109834. }
  109835. /* Test recapture: garbage + page */
  109836. {
  109837. ogg_page og_de;
  109838. fprintf(stderr,"Testing search for capture... ");
  109839. ogg_sync_reset(&oy);
  109840. /* 'garbage' */
  109841. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109842. og[1].body_len);
  109843. ogg_sync_wrote(&oy,og[1].body_len);
  109844. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  109845. og[1].header_len);
  109846. ogg_sync_wrote(&oy,og[1].header_len);
  109847. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  109848. og[1].body_len);
  109849. ogg_sync_wrote(&oy,og[1].body_len);
  109850. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109851. 20);
  109852. ogg_sync_wrote(&oy,20);
  109853. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109854. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109855. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109856. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  109857. og[2].header_len-20);
  109858. ogg_sync_wrote(&oy,og[2].header_len-20);
  109859. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  109860. og[2].body_len);
  109861. ogg_sync_wrote(&oy,og[2].body_len);
  109862. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109863. fprintf(stderr,"ok.\n");
  109864. }
  109865. /* Test recapture: page + garbage + page */
  109866. {
  109867. ogg_page og_de;
  109868. fprintf(stderr,"Testing recapture... ");
  109869. ogg_sync_reset(&oy);
  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. og[2].header_len);
  109878. ogg_sync_wrote(&oy,og[2].header_len);
  109879. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  109880. og[2].header_len);
  109881. ogg_sync_wrote(&oy,og[2].header_len);
  109882. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109883. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  109884. og[2].body_len-5);
  109885. ogg_sync_wrote(&oy,og[2].body_len-5);
  109886. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  109887. og[3].header_len);
  109888. ogg_sync_wrote(&oy,og[3].header_len);
  109889. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  109890. og[3].body_len);
  109891. ogg_sync_wrote(&oy,og[3].body_len);
  109892. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  109893. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  109894. fprintf(stderr,"ok.\n");
  109895. }
  109896. /* Free page data that was previously copied */
  109897. {
  109898. for(i=0;i<5;i++){
  109899. free_page(&og[i]);
  109900. }
  109901. }
  109902. }
  109903. return(0);
  109904. }
  109905. #endif
  109906. #endif
  109907. /*** End of inlined file: framing.c ***/
  109908. /*** Start of inlined file: analysis.c ***/
  109909. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  109910. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109911. // tasks..
  109912. #if JUCE_MSVC
  109913. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109914. #endif
  109915. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  109916. #if JUCE_USE_OGGVORBIS
  109917. #include <stdio.h>
  109918. #include <string.h>
  109919. #include <math.h>
  109920. /*** Start of inlined file: codec_internal.h ***/
  109921. #ifndef _V_CODECI_H_
  109922. #define _V_CODECI_H_
  109923. /*** Start of inlined file: envelope.h ***/
  109924. #ifndef _V_ENVELOPE_
  109925. #define _V_ENVELOPE_
  109926. /*** Start of inlined file: mdct.h ***/
  109927. #ifndef _OGG_mdct_H_
  109928. #define _OGG_mdct_H_
  109929. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  109930. #ifdef MDCT_INTEGERIZED
  109931. #define DATA_TYPE int
  109932. #define REG_TYPE register int
  109933. #define TRIGBITS 14
  109934. #define cPI3_8 6270
  109935. #define cPI2_8 11585
  109936. #define cPI1_8 15137
  109937. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  109938. #define MULT_NORM(x) ((x)>>TRIGBITS)
  109939. #define HALVE(x) ((x)>>1)
  109940. #else
  109941. #define DATA_TYPE float
  109942. #define REG_TYPE float
  109943. #define cPI3_8 .38268343236508977175F
  109944. #define cPI2_8 .70710678118654752441F
  109945. #define cPI1_8 .92387953251128675613F
  109946. #define FLOAT_CONV(x) (x)
  109947. #define MULT_NORM(x) (x)
  109948. #define HALVE(x) ((x)*.5f)
  109949. #endif
  109950. typedef struct {
  109951. int n;
  109952. int log2n;
  109953. DATA_TYPE *trig;
  109954. int *bitrev;
  109955. DATA_TYPE scale;
  109956. } mdct_lookup;
  109957. extern void mdct_init(mdct_lookup *lookup,int n);
  109958. extern void mdct_clear(mdct_lookup *l);
  109959. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  109960. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  109961. #endif
  109962. /*** End of inlined file: mdct.h ***/
  109963. #define VE_PRE 16
  109964. #define VE_WIN 4
  109965. #define VE_POST 2
  109966. #define VE_AMP (VE_PRE+VE_POST-1)
  109967. #define VE_BANDS 7
  109968. #define VE_NEARDC 15
  109969. #define VE_MINSTRETCH 2 /* a bit less than short block */
  109970. #define VE_MAXSTRETCH 12 /* one-third full block */
  109971. typedef struct {
  109972. float ampbuf[VE_AMP];
  109973. int ampptr;
  109974. float nearDC[VE_NEARDC];
  109975. float nearDC_acc;
  109976. float nearDC_partialacc;
  109977. int nearptr;
  109978. } envelope_filter_state;
  109979. typedef struct {
  109980. int begin;
  109981. int end;
  109982. float *window;
  109983. float total;
  109984. } envelope_band;
  109985. typedef struct {
  109986. int ch;
  109987. int winlength;
  109988. int searchstep;
  109989. float minenergy;
  109990. mdct_lookup mdct;
  109991. float *mdct_win;
  109992. envelope_band band[VE_BANDS];
  109993. envelope_filter_state *filter;
  109994. int stretch;
  109995. int *mark;
  109996. long storage;
  109997. long current;
  109998. long curmark;
  109999. long cursor;
  110000. } envelope_lookup;
  110001. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  110002. extern void _ve_envelope_clear(envelope_lookup *e);
  110003. extern long _ve_envelope_search(vorbis_dsp_state *v);
  110004. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  110005. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  110006. #endif
  110007. /*** End of inlined file: envelope.h ***/
  110008. /*** Start of inlined file: codebook.h ***/
  110009. #ifndef _V_CODEBOOK_H_
  110010. #define _V_CODEBOOK_H_
  110011. /* This structure encapsulates huffman and VQ style encoding books; it
  110012. doesn't do anything specific to either.
  110013. valuelist/quantlist are nonNULL (and q_* significant) only if
  110014. there's entry->value mapping to be done.
  110015. If encode-side mapping must be done (and thus the entry needs to be
  110016. hunted), the auxiliary encode pointer will point to a decision
  110017. tree. This is true of both VQ and huffman, but is mostly useful
  110018. with VQ.
  110019. */
  110020. typedef struct static_codebook{
  110021. long dim; /* codebook dimensions (elements per vector) */
  110022. long entries; /* codebook entries */
  110023. long *lengthlist; /* codeword lengths in bits */
  110024. /* mapping ***************************************************************/
  110025. int maptype; /* 0=none
  110026. 1=implicitly populated values from map column
  110027. 2=listed arbitrary values */
  110028. /* The below does a linear, single monotonic sequence mapping. */
  110029. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  110030. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  110031. int q_quant; /* bits: 0 < quant <= 16 */
  110032. int q_sequencep; /* bitflag */
  110033. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  110034. map == 2: list of dim*entries quantized entry vals
  110035. */
  110036. /* encode helpers ********************************************************/
  110037. struct encode_aux_nearestmatch *nearest_tree;
  110038. struct encode_aux_threshmatch *thresh_tree;
  110039. struct encode_aux_pigeonhole *pigeon_tree;
  110040. int allocedp;
  110041. } static_codebook;
  110042. /* this structures an arbitrary trained book to quickly find the
  110043. nearest cell match */
  110044. typedef struct encode_aux_nearestmatch{
  110045. /* pre-calculated partitioning tree */
  110046. long *ptr0;
  110047. long *ptr1;
  110048. long *p; /* decision points (each is an entry) */
  110049. long *q; /* decision points (each is an entry) */
  110050. long aux; /* number of tree entries */
  110051. long alloc;
  110052. } encode_aux_nearestmatch;
  110053. /* assumes a maptype of 1; encode side only, so that's OK */
  110054. typedef struct encode_aux_threshmatch{
  110055. float *quantthresh;
  110056. long *quantmap;
  110057. int quantvals;
  110058. int threshvals;
  110059. } encode_aux_threshmatch;
  110060. typedef struct encode_aux_pigeonhole{
  110061. float min;
  110062. float del;
  110063. int mapentries;
  110064. int quantvals;
  110065. long *pigeonmap;
  110066. long fittotal;
  110067. long *fitlist;
  110068. long *fitmap;
  110069. long *fitlength;
  110070. } encode_aux_pigeonhole;
  110071. typedef struct codebook{
  110072. long dim; /* codebook dimensions (elements per vector) */
  110073. long entries; /* codebook entries */
  110074. long used_entries; /* populated codebook entries */
  110075. const static_codebook *c;
  110076. /* for encode, the below are entry-ordered, fully populated */
  110077. /* for decode, the below are ordered by bitreversed codeword and only
  110078. used entries are populated */
  110079. float *valuelist; /* list of dim*entries actual entry values */
  110080. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  110081. int *dec_index; /* only used if sparseness collapsed */
  110082. char *dec_codelengths;
  110083. ogg_uint32_t *dec_firsttable;
  110084. int dec_firsttablen;
  110085. int dec_maxlength;
  110086. } codebook;
  110087. extern void vorbis_staticbook_clear(static_codebook *b);
  110088. extern void vorbis_staticbook_destroy(static_codebook *b);
  110089. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  110090. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  110091. extern void vorbis_book_clear(codebook *b);
  110092. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  110093. extern float *_book_logdist(const static_codebook *b,float *vals);
  110094. extern float _float32_unpack(long val);
  110095. extern long _float32_pack(float val);
  110096. extern int _best(codebook *book, float *a, int step);
  110097. extern int _ilog(unsigned int v);
  110098. extern long _book_maptype1_quantvals(const static_codebook *b);
  110099. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  110100. extern long vorbis_book_codeword(codebook *book,int entry);
  110101. extern long vorbis_book_codelen(codebook *book,int entry);
  110102. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  110103. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  110104. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  110105. extern int vorbis_book_errorv(codebook *book, float *a);
  110106. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  110107. oggpack_buffer *b);
  110108. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  110109. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  110110. oggpack_buffer *b,int n);
  110111. extern long vorbis_book_decodev_set(codebook *book, float *a,
  110112. oggpack_buffer *b,int n);
  110113. extern long vorbis_book_decodev_add(codebook *book, float *a,
  110114. oggpack_buffer *b,int n);
  110115. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  110116. long off,int ch,
  110117. oggpack_buffer *b,int n);
  110118. #endif
  110119. /*** End of inlined file: codebook.h ***/
  110120. #define BLOCKTYPE_IMPULSE 0
  110121. #define BLOCKTYPE_PADDING 1
  110122. #define BLOCKTYPE_TRANSITION 0
  110123. #define BLOCKTYPE_LONG 1
  110124. #define PACKETBLOBS 15
  110125. typedef struct vorbis_block_internal{
  110126. float **pcmdelay; /* this is a pointer into local storage */
  110127. float ampmax;
  110128. int blocktype;
  110129. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  110130. blob [PACKETBLOBS/2] points to
  110131. the oggpack_buffer in the
  110132. main vorbis_block */
  110133. } vorbis_block_internal;
  110134. typedef void vorbis_look_floor;
  110135. typedef void vorbis_look_residue;
  110136. typedef void vorbis_look_transform;
  110137. /* mode ************************************************************/
  110138. typedef struct {
  110139. int blockflag;
  110140. int windowtype;
  110141. int transformtype;
  110142. int mapping;
  110143. } vorbis_info_mode;
  110144. typedef void vorbis_info_floor;
  110145. typedef void vorbis_info_residue;
  110146. typedef void vorbis_info_mapping;
  110147. /*** Start of inlined file: psy.h ***/
  110148. #ifndef _V_PSY_H_
  110149. #define _V_PSY_H_
  110150. /*** Start of inlined file: smallft.h ***/
  110151. #ifndef _V_SMFT_H_
  110152. #define _V_SMFT_H_
  110153. typedef struct {
  110154. int n;
  110155. float *trigcache;
  110156. int *splitcache;
  110157. } drft_lookup;
  110158. extern void drft_forward(drft_lookup *l,float *data);
  110159. extern void drft_backward(drft_lookup *l,float *data);
  110160. extern void drft_init(drft_lookup *l,int n);
  110161. extern void drft_clear(drft_lookup *l);
  110162. #endif
  110163. /*** End of inlined file: smallft.h ***/
  110164. /*** Start of inlined file: backends.h ***/
  110165. /* this is exposed up here because we need it for static modes.
  110166. Lookups for each backend aren't exposed because there's no reason
  110167. to do so */
  110168. #ifndef _vorbis_backend_h_
  110169. #define _vorbis_backend_h_
  110170. /* this would all be simpler/shorter with templates, but.... */
  110171. /* Floor backend generic *****************************************/
  110172. typedef struct{
  110173. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  110174. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  110175. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  110176. void (*free_info) (vorbis_info_floor *);
  110177. void (*free_look) (vorbis_look_floor *);
  110178. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  110179. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  110180. void *buffer,float *);
  110181. } vorbis_func_floor;
  110182. typedef struct{
  110183. int order;
  110184. long rate;
  110185. long barkmap;
  110186. int ampbits;
  110187. int ampdB;
  110188. int numbooks; /* <= 16 */
  110189. int books[16];
  110190. float lessthan; /* encode-only config setting hacks for libvorbis */
  110191. float greaterthan; /* encode-only config setting hacks for libvorbis */
  110192. } vorbis_info_floor0;
  110193. #define VIF_POSIT 63
  110194. #define VIF_CLASS 16
  110195. #define VIF_PARTS 31
  110196. typedef struct{
  110197. int partitions; /* 0 to 31 */
  110198. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  110199. int class_dim[VIF_CLASS]; /* 1 to 8 */
  110200. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  110201. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  110202. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  110203. int mult; /* 1 2 3 or 4 */
  110204. int postlist[VIF_POSIT+2]; /* first two implicit */
  110205. /* encode side analysis parameters */
  110206. float maxover;
  110207. float maxunder;
  110208. float maxerr;
  110209. float twofitweight;
  110210. float twofitatten;
  110211. int n;
  110212. } vorbis_info_floor1;
  110213. /* Residue backend generic *****************************************/
  110214. typedef struct{
  110215. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  110216. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  110217. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  110218. vorbis_info_residue *);
  110219. void (*free_info) (vorbis_info_residue *);
  110220. void (*free_look) (vorbis_look_residue *);
  110221. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  110222. float **,int *,int);
  110223. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  110224. vorbis_look_residue *,
  110225. float **,float **,int *,int,long **);
  110226. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  110227. float **,int *,int);
  110228. } vorbis_func_residue;
  110229. typedef struct vorbis_info_residue0{
  110230. /* block-partitioned VQ coded straight residue */
  110231. long begin;
  110232. long end;
  110233. /* first stage (lossless partitioning) */
  110234. int grouping; /* group n vectors per partition */
  110235. int partitions; /* possible codebooks for a partition */
  110236. int groupbook; /* huffbook for partitioning */
  110237. int secondstages[64]; /* expanded out to pointers in lookup */
  110238. int booklist[256]; /* list of second stage books */
  110239. float classmetric1[64];
  110240. float classmetric2[64];
  110241. } vorbis_info_residue0;
  110242. /* Mapping backend generic *****************************************/
  110243. typedef struct{
  110244. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  110245. oggpack_buffer *);
  110246. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  110247. void (*free_info) (vorbis_info_mapping *);
  110248. int (*forward) (struct vorbis_block *vb);
  110249. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  110250. } vorbis_func_mapping;
  110251. typedef struct vorbis_info_mapping0{
  110252. int submaps; /* <= 16 */
  110253. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  110254. int floorsubmap[16]; /* [mux] submap to floors */
  110255. int residuesubmap[16]; /* [mux] submap to residue */
  110256. int coupling_steps;
  110257. int coupling_mag[256];
  110258. int coupling_ang[256];
  110259. } vorbis_info_mapping0;
  110260. #endif
  110261. /*** End of inlined file: backends.h ***/
  110262. #ifndef EHMER_MAX
  110263. #define EHMER_MAX 56
  110264. #endif
  110265. /* psychoacoustic setup ********************************************/
  110266. #define P_BANDS 17 /* 62Hz to 16kHz */
  110267. #define P_LEVELS 8 /* 30dB to 100dB */
  110268. #define P_LEVEL_0 30. /* 30 dB */
  110269. #define P_NOISECURVES 3
  110270. #define NOISE_COMPAND_LEVELS 40
  110271. typedef struct vorbis_info_psy{
  110272. int blockflag;
  110273. float ath_adjatt;
  110274. float ath_maxatt;
  110275. float tone_masteratt[P_NOISECURVES];
  110276. float tone_centerboost;
  110277. float tone_decay;
  110278. float tone_abs_limit;
  110279. float toneatt[P_BANDS];
  110280. int noisemaskp;
  110281. float noisemaxsupp;
  110282. float noisewindowlo;
  110283. float noisewindowhi;
  110284. int noisewindowlomin;
  110285. int noisewindowhimin;
  110286. int noisewindowfixed;
  110287. float noiseoff[P_NOISECURVES][P_BANDS];
  110288. float noisecompand[NOISE_COMPAND_LEVELS];
  110289. float max_curve_dB;
  110290. int normal_channel_p;
  110291. int normal_point_p;
  110292. int normal_start;
  110293. int normal_partition;
  110294. double normal_thresh;
  110295. } vorbis_info_psy;
  110296. typedef struct{
  110297. int eighth_octave_lines;
  110298. /* for block long/short tuning; encode only */
  110299. float preecho_thresh[VE_BANDS];
  110300. float postecho_thresh[VE_BANDS];
  110301. float stretch_penalty;
  110302. float preecho_minenergy;
  110303. float ampmax_att_per_sec;
  110304. /* channel coupling config */
  110305. int coupling_pkHz[PACKETBLOBS];
  110306. int coupling_pointlimit[2][PACKETBLOBS];
  110307. int coupling_prepointamp[PACKETBLOBS];
  110308. int coupling_postpointamp[PACKETBLOBS];
  110309. int sliding_lowpass[2][PACKETBLOBS];
  110310. } vorbis_info_psy_global;
  110311. typedef struct {
  110312. float ampmax;
  110313. int channels;
  110314. vorbis_info_psy_global *gi;
  110315. int coupling_pointlimit[2][P_NOISECURVES];
  110316. } vorbis_look_psy_global;
  110317. typedef struct {
  110318. int n;
  110319. struct vorbis_info_psy *vi;
  110320. float ***tonecurves;
  110321. float **noiseoffset;
  110322. float *ath;
  110323. long *octave; /* in n.ocshift format */
  110324. long *bark;
  110325. long firstoc;
  110326. long shiftoc;
  110327. int eighth_octave_lines; /* power of two, please */
  110328. int total_octave_lines;
  110329. long rate; /* cache it */
  110330. float m_val; /* Masking compensation value */
  110331. } vorbis_look_psy;
  110332. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  110333. vorbis_info_psy_global *gi,int n,long rate);
  110334. extern void _vp_psy_clear(vorbis_look_psy *p);
  110335. extern void *_vi_psy_dup(void *source);
  110336. extern void _vi_psy_free(vorbis_info_psy *i);
  110337. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  110338. extern void _vp_remove_floor(vorbis_look_psy *p,
  110339. float *mdct,
  110340. int *icodedflr,
  110341. float *residue,
  110342. int sliding_lowpass);
  110343. extern void _vp_noisemask(vorbis_look_psy *p,
  110344. float *logmdct,
  110345. float *logmask);
  110346. extern void _vp_tonemask(vorbis_look_psy *p,
  110347. float *logfft,
  110348. float *logmask,
  110349. float global_specmax,
  110350. float local_specmax);
  110351. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  110352. float *noise,
  110353. float *tone,
  110354. int offset_select,
  110355. float *logmask,
  110356. float *mdct,
  110357. float *logmdct);
  110358. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  110359. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  110360. vorbis_info_psy_global *g,
  110361. vorbis_look_psy *p,
  110362. vorbis_info_mapping0 *vi,
  110363. float **mdct);
  110364. extern void _vp_couple(int blobno,
  110365. vorbis_info_psy_global *g,
  110366. vorbis_look_psy *p,
  110367. vorbis_info_mapping0 *vi,
  110368. float **res,
  110369. float **mag_memo,
  110370. int **mag_sort,
  110371. int **ifloor,
  110372. int *nonzero,
  110373. int sliding_lowpass);
  110374. extern void _vp_noise_normalize(vorbis_look_psy *p,
  110375. float *in,float *out,int *sortedindex);
  110376. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  110377. float *magnitudes,int *sortedindex);
  110378. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  110379. vorbis_look_psy *p,
  110380. vorbis_info_mapping0 *vi,
  110381. float **mags);
  110382. extern void hf_reduction(vorbis_info_psy_global *g,
  110383. vorbis_look_psy *p,
  110384. vorbis_info_mapping0 *vi,
  110385. float **mdct);
  110386. #endif
  110387. /*** End of inlined file: psy.h ***/
  110388. /*** Start of inlined file: bitrate.h ***/
  110389. #ifndef _V_BITRATE_H_
  110390. #define _V_BITRATE_H_
  110391. /*** Start of inlined file: os.h ***/
  110392. #ifndef _OS_H
  110393. #define _OS_H
  110394. /********************************************************************
  110395. * *
  110396. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  110397. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  110398. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  110399. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  110400. * *
  110401. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  110402. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  110403. * *
  110404. ********************************************************************
  110405. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  110406. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  110407. ********************************************************************/
  110408. #ifdef HAVE_CONFIG_H
  110409. #include "config.h"
  110410. #endif
  110411. #include <math.h>
  110412. /*** Start of inlined file: misc.h ***/
  110413. #ifndef _V_RANDOM_H_
  110414. #define _V_RANDOM_H_
  110415. extern int analysis_noisy;
  110416. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  110417. extern void _vorbis_block_ripcord(vorbis_block *vb);
  110418. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110419. ogg_int64_t off);
  110420. #ifdef DEBUG_MALLOC
  110421. #define _VDBG_GRAPHFILE "malloc.m"
  110422. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  110423. extern void _VDBG_free(void *ptr,char *file,long line);
  110424. #ifndef MISC_C
  110425. #undef _ogg_malloc
  110426. #undef _ogg_calloc
  110427. #undef _ogg_realloc
  110428. #undef _ogg_free
  110429. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  110430. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  110431. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  110432. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  110433. #endif
  110434. #endif
  110435. #endif
  110436. /*** End of inlined file: misc.h ***/
  110437. #ifndef _V_IFDEFJAIL_H_
  110438. # define _V_IFDEFJAIL_H_
  110439. # ifdef __GNUC__
  110440. # define STIN static __inline__
  110441. # elif _WIN32
  110442. # define STIN static __inline
  110443. # else
  110444. # define STIN static
  110445. # endif
  110446. #ifdef DJGPP
  110447. # define rint(x) (floor((x)+0.5f))
  110448. #endif
  110449. #ifndef M_PI
  110450. # define M_PI (3.1415926536f)
  110451. #endif
  110452. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  110453. # include <malloc.h>
  110454. # define rint(x) (floor((x)+0.5f))
  110455. # define NO_FLOAT_MATH_LIB
  110456. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  110457. #endif
  110458. #if defined(__SYMBIAN32__) && defined(__WINS__)
  110459. void *_alloca(size_t size);
  110460. # define alloca _alloca
  110461. #endif
  110462. #ifndef FAST_HYPOT
  110463. # define FAST_HYPOT hypot
  110464. #endif
  110465. #endif
  110466. #ifdef HAVE_ALLOCA_H
  110467. # include <alloca.h>
  110468. #endif
  110469. #ifdef USE_MEMORY_H
  110470. # include <memory.h>
  110471. #endif
  110472. #ifndef min
  110473. # define min(x,y) ((x)>(y)?(y):(x))
  110474. #endif
  110475. #ifndef max
  110476. # define max(x,y) ((x)<(y)?(y):(x))
  110477. #endif
  110478. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  110479. # define VORBIS_FPU_CONTROL
  110480. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  110481. Because of encapsulation constraints (GCC can't see inside the asm
  110482. block and so we end up doing stupid things like a store/load that
  110483. is collectively a noop), we do it this way */
  110484. /* we must set up the fpu before this works!! */
  110485. typedef ogg_int16_t vorbis_fpu_control;
  110486. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110487. ogg_int16_t ret;
  110488. ogg_int16_t temp;
  110489. __asm__ __volatile__("fnstcw %0\n\t"
  110490. "movw %0,%%dx\n\t"
  110491. "orw $62463,%%dx\n\t"
  110492. "movw %%dx,%1\n\t"
  110493. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  110494. *fpu=ret;
  110495. }
  110496. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110497. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  110498. }
  110499. /* assumes the FPU is in round mode! */
  110500. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  110501. we get extra fst/fld to
  110502. truncate precision */
  110503. int i;
  110504. __asm__("fistl %0": "=m"(i) : "t"(f));
  110505. return(i);
  110506. }
  110507. #endif
  110508. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  110509. # define VORBIS_FPU_CONTROL
  110510. typedef ogg_int16_t vorbis_fpu_control;
  110511. static __inline int vorbis_ftoi(double f){
  110512. int i;
  110513. __asm{
  110514. fld f
  110515. fistp i
  110516. }
  110517. return i;
  110518. }
  110519. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110520. }
  110521. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110522. }
  110523. #endif
  110524. #ifndef VORBIS_FPU_CONTROL
  110525. typedef int vorbis_fpu_control;
  110526. static int vorbis_ftoi(double f){
  110527. return (int)(f+.5);
  110528. }
  110529. /* We don't have special code for this compiler/arch, so do it the slow way */
  110530. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  110531. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  110532. #endif
  110533. #endif /* _OS_H */
  110534. /*** End of inlined file: os.h ***/
  110535. /* encode side bitrate tracking */
  110536. typedef struct bitrate_manager_state {
  110537. int managed;
  110538. long avg_reservoir;
  110539. long minmax_reservoir;
  110540. long avg_bitsper;
  110541. long min_bitsper;
  110542. long max_bitsper;
  110543. long short_per_long;
  110544. double avgfloat;
  110545. vorbis_block *vb;
  110546. int choice;
  110547. } bitrate_manager_state;
  110548. typedef struct bitrate_manager_info{
  110549. long avg_rate;
  110550. long min_rate;
  110551. long max_rate;
  110552. long reservoir_bits;
  110553. double reservoir_bias;
  110554. double slew_damp;
  110555. } bitrate_manager_info;
  110556. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  110557. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  110558. extern int vorbis_bitrate_managed(vorbis_block *vb);
  110559. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  110560. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  110561. #endif
  110562. /*** End of inlined file: bitrate.h ***/
  110563. static int ilog(unsigned int v){
  110564. int ret=0;
  110565. while(v){
  110566. ret++;
  110567. v>>=1;
  110568. }
  110569. return(ret);
  110570. }
  110571. static int ilog2(unsigned int v){
  110572. int ret=0;
  110573. if(v)--v;
  110574. while(v){
  110575. ret++;
  110576. v>>=1;
  110577. }
  110578. return(ret);
  110579. }
  110580. typedef struct private_state {
  110581. /* local lookup storage */
  110582. envelope_lookup *ve; /* envelope lookup */
  110583. int window[2];
  110584. vorbis_look_transform **transform[2]; /* block, type */
  110585. drft_lookup fft_look[2];
  110586. int modebits;
  110587. vorbis_look_floor **flr;
  110588. vorbis_look_residue **residue;
  110589. vorbis_look_psy *psy;
  110590. vorbis_look_psy_global *psy_g_look;
  110591. /* local storage, only used on the encoding side. This way the
  110592. application does not need to worry about freeing some packets'
  110593. memory and not others'; packet storage is always tracked.
  110594. Cleared next call to a _dsp_ function */
  110595. unsigned char *header;
  110596. unsigned char *header1;
  110597. unsigned char *header2;
  110598. bitrate_manager_state bms;
  110599. ogg_int64_t sample_count;
  110600. } private_state;
  110601. /* codec_setup_info contains all the setup information specific to the
  110602. specific compression/decompression mode in progress (eg,
  110603. psychoacoustic settings, channel setup, options, codebook
  110604. etc).
  110605. *********************************************************************/
  110606. /*** Start of inlined file: highlevel.h ***/
  110607. typedef struct highlevel_byblocktype {
  110608. double tone_mask_setting;
  110609. double tone_peaklimit_setting;
  110610. double noise_bias_setting;
  110611. double noise_compand_setting;
  110612. } highlevel_byblocktype;
  110613. typedef struct highlevel_encode_setup {
  110614. void *setup;
  110615. int set_in_stone;
  110616. double base_setting;
  110617. double long_setting;
  110618. double short_setting;
  110619. double impulse_noisetune;
  110620. int managed;
  110621. long bitrate_min;
  110622. long bitrate_av;
  110623. double bitrate_av_damp;
  110624. long bitrate_max;
  110625. long bitrate_reservoir;
  110626. double bitrate_reservoir_bias;
  110627. int impulse_block_p;
  110628. int noise_normalize_p;
  110629. double stereo_point_setting;
  110630. double lowpass_kHz;
  110631. double ath_floating_dB;
  110632. double ath_absolute_dB;
  110633. double amplitude_track_dBpersec;
  110634. double trigger_setting;
  110635. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  110636. } highlevel_encode_setup;
  110637. /*** End of inlined file: highlevel.h ***/
  110638. typedef struct codec_setup_info {
  110639. /* Vorbis supports only short and long blocks, but allows the
  110640. encoder to choose the sizes */
  110641. long blocksizes[2];
  110642. /* modes are the primary means of supporting on-the-fly different
  110643. blocksizes, different channel mappings (LR or M/A),
  110644. different residue backends, etc. Each mode consists of a
  110645. blocksize flag and a mapping (along with the mapping setup */
  110646. int modes;
  110647. int maps;
  110648. int floors;
  110649. int residues;
  110650. int books;
  110651. int psys; /* encode only */
  110652. vorbis_info_mode *mode_param[64];
  110653. int map_type[64];
  110654. vorbis_info_mapping *map_param[64];
  110655. int floor_type[64];
  110656. vorbis_info_floor *floor_param[64];
  110657. int residue_type[64];
  110658. vorbis_info_residue *residue_param[64];
  110659. static_codebook *book_param[256];
  110660. codebook *fullbooks;
  110661. vorbis_info_psy *psy_param[4]; /* encode only */
  110662. vorbis_info_psy_global psy_g_param;
  110663. bitrate_manager_info bi;
  110664. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  110665. highly redundant structure, but
  110666. improves clarity of program flow. */
  110667. int halfrate_flag; /* painless downsample for decode */
  110668. } codec_setup_info;
  110669. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  110670. extern void _vp_global_free(vorbis_look_psy_global *look);
  110671. #endif
  110672. /*** End of inlined file: codec_internal.h ***/
  110673. /*** Start of inlined file: registry.h ***/
  110674. #ifndef _V_REG_H_
  110675. #define _V_REG_H_
  110676. #define VI_TRANSFORMB 1
  110677. #define VI_WINDOWB 1
  110678. #define VI_TIMEB 1
  110679. #define VI_FLOORB 2
  110680. #define VI_RESB 3
  110681. #define VI_MAPB 1
  110682. extern vorbis_func_floor *_floor_P[];
  110683. extern vorbis_func_residue *_residue_P[];
  110684. extern vorbis_func_mapping *_mapping_P[];
  110685. #endif
  110686. /*** End of inlined file: registry.h ***/
  110687. /*** Start of inlined file: scales.h ***/
  110688. #ifndef _V_SCALES_H_
  110689. #define _V_SCALES_H_
  110690. #include <math.h>
  110691. /* 20log10(x) */
  110692. #define VORBIS_IEEE_FLOAT32 1
  110693. #ifdef VORBIS_IEEE_FLOAT32
  110694. static float unitnorm(float x){
  110695. union {
  110696. ogg_uint32_t i;
  110697. float f;
  110698. } ix;
  110699. ix.f = x;
  110700. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  110701. return ix.f;
  110702. }
  110703. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  110704. static float todB(const float *x){
  110705. union {
  110706. ogg_uint32_t i;
  110707. float f;
  110708. } ix;
  110709. ix.f = *x;
  110710. ix.i = ix.i&0x7fffffff;
  110711. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  110712. }
  110713. #define todB_nn(x) todB(x)
  110714. #else
  110715. static float unitnorm(float x){
  110716. if(x<0)return(-1.f);
  110717. return(1.f);
  110718. }
  110719. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  110720. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  110721. #endif
  110722. #define fromdB(x) (exp((x)*.11512925f))
  110723. /* The bark scale equations are approximations, since the original
  110724. table was somewhat hand rolled. The below are chosen to have the
  110725. best possible fit to the rolled tables, thus their somewhat odd
  110726. appearance (these are more accurate and over a longer range than
  110727. the oft-quoted bark equations found in the texts I have). The
  110728. approximations are valid from 0 - 30kHz (nyquist) or so.
  110729. all f in Hz, z in Bark */
  110730. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  110731. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  110732. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  110733. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  110734. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  110735. 0.0 */
  110736. #define toOC(n) (log(n)*1.442695f-5.965784f)
  110737. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  110738. #endif
  110739. /*** End of inlined file: scales.h ***/
  110740. int analysis_noisy=1;
  110741. /* decides between modes, dispatches to the appropriate mapping. */
  110742. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  110743. int ret,i;
  110744. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  110745. vb->glue_bits=0;
  110746. vb->time_bits=0;
  110747. vb->floor_bits=0;
  110748. vb->res_bits=0;
  110749. /* first things first. Make sure encode is ready */
  110750. for(i=0;i<PACKETBLOBS;i++)
  110751. oggpack_reset(vbi->packetblob[i]);
  110752. /* we only have one mapping type (0), and we let the mapping code
  110753. itself figure out what soft mode to use. This allows easier
  110754. bitrate management */
  110755. if((ret=_mapping_P[0]->forward(vb)))
  110756. return(ret);
  110757. if(op){
  110758. if(vorbis_bitrate_managed(vb))
  110759. /* The app is using a bitmanaged mode... but not using the
  110760. bitrate management interface. */
  110761. return(OV_EINVAL);
  110762. op->packet=oggpack_get_buffer(&vb->opb);
  110763. op->bytes=oggpack_bytes(&vb->opb);
  110764. op->b_o_s=0;
  110765. op->e_o_s=vb->eofflag;
  110766. op->granulepos=vb->granulepos;
  110767. op->packetno=vb->sequence; /* for sake of completeness */
  110768. }
  110769. return(0);
  110770. }
  110771. /* there was no great place to put this.... */
  110772. void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  110773. int j;
  110774. FILE *of;
  110775. char buffer[80];
  110776. /* if(i==5870){*/
  110777. sprintf(buffer,"%s_%d.m",base,i);
  110778. of=fopen(buffer,"w");
  110779. if(!of)perror("failed to open data dump file");
  110780. for(j=0;j<n;j++){
  110781. if(bark){
  110782. float b=toBARK((4000.f*j/n)+.25);
  110783. fprintf(of,"%f ",b);
  110784. }else
  110785. if(off!=0)
  110786. fprintf(of,"%f ",(double)(j+off)/8000.);
  110787. else
  110788. fprintf(of,"%f ",(double)j);
  110789. if(dB){
  110790. float val;
  110791. if(v[j]==0.)
  110792. val=-140.;
  110793. else
  110794. val=todB(v+j);
  110795. fprintf(of,"%f\n",val);
  110796. }else{
  110797. fprintf(of,"%f\n",v[j]);
  110798. }
  110799. }
  110800. fclose(of);
  110801. /* } */
  110802. }
  110803. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110804. ogg_int64_t off){
  110805. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  110806. }
  110807. #endif
  110808. /*** End of inlined file: analysis.c ***/
  110809. /*** Start of inlined file: bitrate.c ***/
  110810. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110811. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110812. // tasks..
  110813. #if JUCE_MSVC
  110814. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110815. #endif
  110816. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110817. #if JUCE_USE_OGGVORBIS
  110818. #include <stdlib.h>
  110819. #include <string.h>
  110820. #include <math.h>
  110821. /* compute bitrate tracking setup */
  110822. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  110823. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  110824. bitrate_manager_info *bi=&ci->bi;
  110825. memset(bm,0,sizeof(*bm));
  110826. if(bi && (bi->reservoir_bits>0)){
  110827. long ratesamples=vi->rate;
  110828. int halfsamples=ci->blocksizes[0]>>1;
  110829. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  110830. bm->managed=1;
  110831. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  110832. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  110833. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  110834. bm->avgfloat=PACKETBLOBS/2;
  110835. /* not a necessary fix, but one that leads to a more balanced
  110836. typical initialization */
  110837. {
  110838. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  110839. bm->minmax_reservoir=desired_fill;
  110840. bm->avg_reservoir=desired_fill;
  110841. }
  110842. }
  110843. }
  110844. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  110845. memset(bm,0,sizeof(*bm));
  110846. return;
  110847. }
  110848. int vorbis_bitrate_managed(vorbis_block *vb){
  110849. vorbis_dsp_state *vd=vb->vd;
  110850. private_state *b=(private_state*)vd->backend_state;
  110851. bitrate_manager_state *bm=&b->bms;
  110852. if(bm && bm->managed)return(1);
  110853. return(0);
  110854. }
  110855. /* finish taking in the block we just processed */
  110856. int vorbis_bitrate_addblock(vorbis_block *vb){
  110857. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110858. vorbis_dsp_state *vd=vb->vd;
  110859. private_state *b=(private_state*)vd->backend_state;
  110860. bitrate_manager_state *bm=&b->bms;
  110861. vorbis_info *vi=vd->vi;
  110862. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110863. bitrate_manager_info *bi=&ci->bi;
  110864. int choice=rint(bm->avgfloat);
  110865. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110866. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  110867. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  110868. int samples=ci->blocksizes[vb->W]>>1;
  110869. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  110870. if(!bm->managed){
  110871. /* not a bitrate managed stream, but for API simplicity, we'll
  110872. buffer the packet to keep the code path clean */
  110873. if(bm->vb)return(-1); /* one has been submitted without
  110874. being claimed */
  110875. bm->vb=vb;
  110876. return(0);
  110877. }
  110878. bm->vb=vb;
  110879. /* look ahead for avg floater */
  110880. if(bm->avg_bitsper>0){
  110881. double slew=0.;
  110882. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  110883. double slewlimit= 15./bi->slew_damp;
  110884. /* choosing a new floater:
  110885. if we're over target, we slew down
  110886. if we're under target, we slew up
  110887. choose slew as follows: look through packetblobs of this frame
  110888. and set slew as the first in the appropriate direction that
  110889. gives us the slew we want. This may mean no slew if delta is
  110890. already favorable.
  110891. Then limit slew to slew max */
  110892. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110893. while(choice>0 && this_bits>avg_target_bits &&
  110894. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  110895. choice--;
  110896. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110897. }
  110898. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110899. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  110900. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  110901. choice++;
  110902. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110903. }
  110904. }
  110905. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  110906. if(slew<-slewlimit)slew=-slewlimit;
  110907. if(slew>slewlimit)slew=slewlimit;
  110908. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  110909. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110910. }
  110911. /* enforce min(if used) on the current floater (if used) */
  110912. if(bm->min_bitsper>0){
  110913. /* do we need to force the bitrate up? */
  110914. if(this_bits<min_target_bits){
  110915. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  110916. choice++;
  110917. if(choice>=PACKETBLOBS)break;
  110918. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110919. }
  110920. }
  110921. }
  110922. /* enforce max (if used) on the current floater (if used) */
  110923. if(bm->max_bitsper>0){
  110924. /* do we need to force the bitrate down? */
  110925. if(this_bits>max_target_bits){
  110926. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  110927. choice--;
  110928. if(choice<0)break;
  110929. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110930. }
  110931. }
  110932. }
  110933. /* Choice of packetblobs now made based on floater, and min/max
  110934. requirements. Now boundary check extreme choices */
  110935. if(choice<0){
  110936. /* choosing a smaller packetblob is insufficient to trim bitrate.
  110937. frame will need to be truncated */
  110938. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  110939. bm->choice=choice=0;
  110940. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  110941. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  110942. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110943. }
  110944. }else{
  110945. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  110946. if(choice>=PACKETBLOBS)
  110947. choice=PACKETBLOBS-1;
  110948. bm->choice=choice;
  110949. /* prop up bitrate according to demand. pad this frame out with zeroes */
  110950. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  110951. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  110952. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  110953. }
  110954. /* now we have the final packet and the final packet size. Update statistics */
  110955. /* min and max reservoir */
  110956. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  110957. if(max_target_bits>0 && this_bits>max_target_bits){
  110958. bm->minmax_reservoir+=(this_bits-max_target_bits);
  110959. }else if(min_target_bits>0 && this_bits<min_target_bits){
  110960. bm->minmax_reservoir+=(this_bits-min_target_bits);
  110961. }else{
  110962. /* inbetween; we want to take reservoir toward but not past desired_fill */
  110963. if(bm->minmax_reservoir>desired_fill){
  110964. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  110965. bm->minmax_reservoir+=(this_bits-max_target_bits);
  110966. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  110967. }else{
  110968. bm->minmax_reservoir=desired_fill;
  110969. }
  110970. }else{
  110971. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  110972. bm->minmax_reservoir+=(this_bits-min_target_bits);
  110973. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  110974. }else{
  110975. bm->minmax_reservoir=desired_fill;
  110976. }
  110977. }
  110978. }
  110979. }
  110980. /* avg reservoir */
  110981. if(bm->avg_bitsper>0){
  110982. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  110983. bm->avg_reservoir+=this_bits-avg_target_bits;
  110984. }
  110985. return(0);
  110986. }
  110987. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  110988. private_state *b=(private_state*)vd->backend_state;
  110989. bitrate_manager_state *bm=&b->bms;
  110990. vorbis_block *vb=bm->vb;
  110991. int choice=PACKETBLOBS/2;
  110992. if(!vb)return 0;
  110993. if(op){
  110994. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  110995. if(vorbis_bitrate_managed(vb))
  110996. choice=bm->choice;
  110997. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  110998. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  110999. op->b_o_s=0;
  111000. op->e_o_s=vb->eofflag;
  111001. op->granulepos=vb->granulepos;
  111002. op->packetno=vb->sequence; /* for sake of completeness */
  111003. }
  111004. bm->vb=0;
  111005. return(1);
  111006. }
  111007. #endif
  111008. /*** End of inlined file: bitrate.c ***/
  111009. /*** Start of inlined file: block.c ***/
  111010. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111011. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111012. // tasks..
  111013. #if JUCE_MSVC
  111014. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111015. #endif
  111016. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111017. #if JUCE_USE_OGGVORBIS
  111018. #include <stdio.h>
  111019. #include <stdlib.h>
  111020. #include <string.h>
  111021. /*** Start of inlined file: window.h ***/
  111022. #ifndef _V_WINDOW_
  111023. #define _V_WINDOW_
  111024. extern float *_vorbis_window_get(int n);
  111025. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  111026. int lW,int W,int nW);
  111027. #endif
  111028. /*** End of inlined file: window.h ***/
  111029. /*** Start of inlined file: lpc.h ***/
  111030. #ifndef _V_LPC_H_
  111031. #define _V_LPC_H_
  111032. /* simple linear scale LPC code */
  111033. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  111034. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  111035. float *data,long n);
  111036. #endif
  111037. /*** End of inlined file: lpc.h ***/
  111038. /* pcm accumulator examples (not exhaustive):
  111039. <-------------- lW ---------------->
  111040. <--------------- W ---------------->
  111041. : .....|..... _______________ |
  111042. : .''' | '''_--- | |\ |
  111043. :.....''' |_____--- '''......| | \_______|
  111044. :.................|__________________|_______|__|______|
  111045. |<------ Sl ------>| > Sr < |endW
  111046. |beginSl |endSl | |endSr
  111047. |beginW |endlW |beginSr
  111048. |< lW >|
  111049. <--------------- W ---------------->
  111050. | | .. ______________ |
  111051. | | ' `/ | ---_ |
  111052. |___.'___/`. | ---_____|
  111053. |_______|__|_______|_________________|
  111054. | >|Sl|< |<------ Sr ----->|endW
  111055. | | |endSl |beginSr |endSr
  111056. |beginW | |endlW
  111057. mult[0] |beginSl mult[n]
  111058. <-------------- lW ----------------->
  111059. |<--W-->|
  111060. : .............. ___ | |
  111061. : .''' |`/ \ | |
  111062. :.....''' |/`....\|...|
  111063. :.........................|___|___|___|
  111064. |Sl |Sr |endW
  111065. | | |endSr
  111066. | |beginSr
  111067. | |endSl
  111068. |beginSl
  111069. |beginW
  111070. */
  111071. /* block abstraction setup *********************************************/
  111072. #ifndef WORD_ALIGN
  111073. #define WORD_ALIGN 8
  111074. #endif
  111075. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  111076. int i;
  111077. memset(vb,0,sizeof(*vb));
  111078. vb->vd=v;
  111079. vb->localalloc=0;
  111080. vb->localstore=NULL;
  111081. if(v->analysisp){
  111082. vorbis_block_internal *vbi=(vorbis_block_internal*)
  111083. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  111084. vbi->ampmax=-9999;
  111085. for(i=0;i<PACKETBLOBS;i++){
  111086. if(i==PACKETBLOBS/2){
  111087. vbi->packetblob[i]=&vb->opb;
  111088. }else{
  111089. vbi->packetblob[i]=
  111090. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  111091. }
  111092. oggpack_writeinit(vbi->packetblob[i]);
  111093. }
  111094. }
  111095. return(0);
  111096. }
  111097. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  111098. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  111099. if(bytes+vb->localtop>vb->localalloc){
  111100. /* can't just _ogg_realloc... there are outstanding pointers */
  111101. if(vb->localstore){
  111102. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  111103. vb->totaluse+=vb->localtop;
  111104. link->next=vb->reap;
  111105. link->ptr=vb->localstore;
  111106. vb->reap=link;
  111107. }
  111108. /* highly conservative */
  111109. vb->localalloc=bytes;
  111110. vb->localstore=_ogg_malloc(vb->localalloc);
  111111. vb->localtop=0;
  111112. }
  111113. {
  111114. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  111115. vb->localtop+=bytes;
  111116. return ret;
  111117. }
  111118. }
  111119. /* reap the chain, pull the ripcord */
  111120. void _vorbis_block_ripcord(vorbis_block *vb){
  111121. /* reap the chain */
  111122. struct alloc_chain *reap=vb->reap;
  111123. while(reap){
  111124. struct alloc_chain *next=reap->next;
  111125. _ogg_free(reap->ptr);
  111126. memset(reap,0,sizeof(*reap));
  111127. _ogg_free(reap);
  111128. reap=next;
  111129. }
  111130. /* consolidate storage */
  111131. if(vb->totaluse){
  111132. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  111133. vb->localalloc+=vb->totaluse;
  111134. vb->totaluse=0;
  111135. }
  111136. /* pull the ripcord */
  111137. vb->localtop=0;
  111138. vb->reap=NULL;
  111139. }
  111140. int vorbis_block_clear(vorbis_block *vb){
  111141. int i;
  111142. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  111143. _vorbis_block_ripcord(vb);
  111144. if(vb->localstore)_ogg_free(vb->localstore);
  111145. if(vbi){
  111146. for(i=0;i<PACKETBLOBS;i++){
  111147. oggpack_writeclear(vbi->packetblob[i]);
  111148. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  111149. }
  111150. _ogg_free(vbi);
  111151. }
  111152. memset(vb,0,sizeof(*vb));
  111153. return(0);
  111154. }
  111155. /* Analysis side code, but directly related to blocking. Thus it's
  111156. here and not in analysis.c (which is for analysis transforms only).
  111157. The init is here because some of it is shared */
  111158. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  111159. int i;
  111160. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111161. private_state *b=NULL;
  111162. int hs;
  111163. if(ci==NULL) return 1;
  111164. hs=ci->halfrate_flag;
  111165. memset(v,0,sizeof(*v));
  111166. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  111167. v->vi=vi;
  111168. b->modebits=ilog2(ci->modes);
  111169. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  111170. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  111171. /* MDCT is tranform 0 */
  111172. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  111173. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  111174. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  111175. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  111176. /* Vorbis I uses only window type 0 */
  111177. b->window[0]=ilog2(ci->blocksizes[0])-6;
  111178. b->window[1]=ilog2(ci->blocksizes[1])-6;
  111179. if(encp){ /* encode/decode differ here */
  111180. /* analysis always needs an fft */
  111181. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  111182. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  111183. /* finish the codebooks */
  111184. if(!ci->fullbooks){
  111185. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  111186. for(i=0;i<ci->books;i++)
  111187. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  111188. }
  111189. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  111190. for(i=0;i<ci->psys;i++){
  111191. _vp_psy_init(b->psy+i,
  111192. ci->psy_param[i],
  111193. &ci->psy_g_param,
  111194. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  111195. vi->rate);
  111196. }
  111197. v->analysisp=1;
  111198. }else{
  111199. /* finish the codebooks */
  111200. if(!ci->fullbooks){
  111201. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  111202. for(i=0;i<ci->books;i++){
  111203. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  111204. /* decode codebooks are now standalone after init */
  111205. vorbis_staticbook_destroy(ci->book_param[i]);
  111206. ci->book_param[i]=NULL;
  111207. }
  111208. }
  111209. }
  111210. /* initialize the storage vectors. blocksize[1] is small for encode,
  111211. but the correct size for decode */
  111212. v->pcm_storage=ci->blocksizes[1];
  111213. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  111214. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  111215. {
  111216. int i;
  111217. for(i=0;i<vi->channels;i++)
  111218. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  111219. }
  111220. /* all 1 (large block) or 0 (small block) */
  111221. /* explicitly set for the sake of clarity */
  111222. v->lW=0; /* previous window size */
  111223. v->W=0; /* current window size */
  111224. /* all vector indexes */
  111225. v->centerW=ci->blocksizes[1]/2;
  111226. v->pcm_current=v->centerW;
  111227. /* initialize all the backend lookups */
  111228. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  111229. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  111230. for(i=0;i<ci->floors;i++)
  111231. b->flr[i]=_floor_P[ci->floor_type[i]]->
  111232. look(v,ci->floor_param[i]);
  111233. for(i=0;i<ci->residues;i++)
  111234. b->residue[i]=_residue_P[ci->residue_type[i]]->
  111235. look(v,ci->residue_param[i]);
  111236. return 0;
  111237. }
  111238. /* arbitrary settings and spec-mandated numbers get filled in here */
  111239. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111240. private_state *b=NULL;
  111241. if(_vds_shared_init(v,vi,1))return 1;
  111242. b=(private_state*)v->backend_state;
  111243. b->psy_g_look=_vp_global_look(vi);
  111244. /* Initialize the envelope state storage */
  111245. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  111246. _ve_envelope_init(b->ve,vi);
  111247. vorbis_bitrate_init(vi,&b->bms);
  111248. /* compressed audio packets start after the headers
  111249. with sequence number 3 */
  111250. v->sequence=3;
  111251. return(0);
  111252. }
  111253. void vorbis_dsp_clear(vorbis_dsp_state *v){
  111254. int i;
  111255. if(v){
  111256. vorbis_info *vi=v->vi;
  111257. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  111258. private_state *b=(private_state*)v->backend_state;
  111259. if(b){
  111260. if(b->ve){
  111261. _ve_envelope_clear(b->ve);
  111262. _ogg_free(b->ve);
  111263. }
  111264. if(b->transform[0]){
  111265. mdct_clear((mdct_lookup*) b->transform[0][0]);
  111266. _ogg_free(b->transform[0][0]);
  111267. _ogg_free(b->transform[0]);
  111268. }
  111269. if(b->transform[1]){
  111270. mdct_clear((mdct_lookup*) b->transform[1][0]);
  111271. _ogg_free(b->transform[1][0]);
  111272. _ogg_free(b->transform[1]);
  111273. }
  111274. if(b->flr){
  111275. for(i=0;i<ci->floors;i++)
  111276. _floor_P[ci->floor_type[i]]->
  111277. free_look(b->flr[i]);
  111278. _ogg_free(b->flr);
  111279. }
  111280. if(b->residue){
  111281. for(i=0;i<ci->residues;i++)
  111282. _residue_P[ci->residue_type[i]]->
  111283. free_look(b->residue[i]);
  111284. _ogg_free(b->residue);
  111285. }
  111286. if(b->psy){
  111287. for(i=0;i<ci->psys;i++)
  111288. _vp_psy_clear(b->psy+i);
  111289. _ogg_free(b->psy);
  111290. }
  111291. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  111292. vorbis_bitrate_clear(&b->bms);
  111293. drft_clear(&b->fft_look[0]);
  111294. drft_clear(&b->fft_look[1]);
  111295. }
  111296. if(v->pcm){
  111297. for(i=0;i<vi->channels;i++)
  111298. if(v->pcm[i])_ogg_free(v->pcm[i]);
  111299. _ogg_free(v->pcm);
  111300. if(v->pcmret)_ogg_free(v->pcmret);
  111301. }
  111302. if(b){
  111303. /* free header, header1, header2 */
  111304. if(b->header)_ogg_free(b->header);
  111305. if(b->header1)_ogg_free(b->header1);
  111306. if(b->header2)_ogg_free(b->header2);
  111307. _ogg_free(b);
  111308. }
  111309. memset(v,0,sizeof(*v));
  111310. }
  111311. }
  111312. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  111313. int i;
  111314. vorbis_info *vi=v->vi;
  111315. private_state *b=(private_state*)v->backend_state;
  111316. /* free header, header1, header2 */
  111317. if(b->header)_ogg_free(b->header);b->header=NULL;
  111318. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  111319. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  111320. /* Do we have enough storage space for the requested buffer? If not,
  111321. expand the PCM (and envelope) storage */
  111322. if(v->pcm_current+vals>=v->pcm_storage){
  111323. v->pcm_storage=v->pcm_current+vals*2;
  111324. for(i=0;i<vi->channels;i++){
  111325. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  111326. }
  111327. }
  111328. for(i=0;i<vi->channels;i++)
  111329. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  111330. return(v->pcmret);
  111331. }
  111332. static void _preextrapolate_helper(vorbis_dsp_state *v){
  111333. int i;
  111334. int order=32;
  111335. float *lpc=(float*)alloca(order*sizeof(*lpc));
  111336. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  111337. long j;
  111338. v->preextrapolate=1;
  111339. if(v->pcm_current-v->centerW>order*2){ /* safety */
  111340. for(i=0;i<v->vi->channels;i++){
  111341. /* need to run the extrapolation in reverse! */
  111342. for(j=0;j<v->pcm_current;j++)
  111343. work[j]=v->pcm[i][v->pcm_current-j-1];
  111344. /* prime as above */
  111345. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  111346. /* run the predictor filter */
  111347. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  111348. order,
  111349. work+v->pcm_current-v->centerW,
  111350. v->centerW);
  111351. for(j=0;j<v->pcm_current;j++)
  111352. v->pcm[i][v->pcm_current-j-1]=work[j];
  111353. }
  111354. }
  111355. }
  111356. /* call with val<=0 to set eof */
  111357. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  111358. vorbis_info *vi=v->vi;
  111359. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111360. if(vals<=0){
  111361. int order=32;
  111362. int i;
  111363. float *lpc=(float*) alloca(order*sizeof(*lpc));
  111364. /* if it wasn't done earlier (very short sample) */
  111365. if(!v->preextrapolate)
  111366. _preextrapolate_helper(v);
  111367. /* We're encoding the end of the stream. Just make sure we have
  111368. [at least] a few full blocks of zeroes at the end. */
  111369. /* actually, we don't want zeroes; that could drop a large
  111370. amplitude off a cliff, creating spread spectrum noise that will
  111371. suck to encode. Extrapolate for the sake of cleanliness. */
  111372. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  111373. v->eofflag=v->pcm_current;
  111374. v->pcm_current+=ci->blocksizes[1]*3;
  111375. for(i=0;i<vi->channels;i++){
  111376. if(v->eofflag>order*2){
  111377. /* extrapolate with LPC to fill in */
  111378. long n;
  111379. /* make a predictor filter */
  111380. n=v->eofflag;
  111381. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  111382. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  111383. /* run the predictor filter */
  111384. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  111385. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  111386. }else{
  111387. /* not enough data to extrapolate (unlikely to happen due to
  111388. guarding the overlap, but bulletproof in case that
  111389. assumtion goes away). zeroes will do. */
  111390. memset(v->pcm[i]+v->eofflag,0,
  111391. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  111392. }
  111393. }
  111394. }else{
  111395. if(v->pcm_current+vals>v->pcm_storage)
  111396. return(OV_EINVAL);
  111397. v->pcm_current+=vals;
  111398. /* we may want to reverse extrapolate the beginning of a stream
  111399. too... in case we're beginning on a cliff! */
  111400. /* clumsy, but simple. It only runs once, so simple is good. */
  111401. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  111402. _preextrapolate_helper(v);
  111403. }
  111404. return(0);
  111405. }
  111406. /* do the deltas, envelope shaping, pre-echo and determine the size of
  111407. the next block on which to continue analysis */
  111408. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  111409. int i;
  111410. vorbis_info *vi=v->vi;
  111411. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111412. private_state *b=(private_state*)v->backend_state;
  111413. vorbis_look_psy_global *g=b->psy_g_look;
  111414. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  111415. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  111416. /* check to see if we're started... */
  111417. if(!v->preextrapolate)return(0);
  111418. /* check to see if we're done... */
  111419. if(v->eofflag==-1)return(0);
  111420. /* By our invariant, we have lW, W and centerW set. Search for
  111421. the next boundary so we can determine nW (the next window size)
  111422. which lets us compute the shape of the current block's window */
  111423. /* we do an envelope search even on a single blocksize; we may still
  111424. be throwing more bits at impulses, and envelope search handles
  111425. marking impulses too. */
  111426. {
  111427. long bp=_ve_envelope_search(v);
  111428. if(bp==-1){
  111429. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  111430. full long block */
  111431. v->nW=0;
  111432. }else{
  111433. if(ci->blocksizes[0]==ci->blocksizes[1])
  111434. v->nW=0;
  111435. else
  111436. v->nW=bp;
  111437. }
  111438. }
  111439. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  111440. {
  111441. /* center of next block + next block maximum right side. */
  111442. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  111443. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  111444. although this check is
  111445. less strict that the
  111446. _ve_envelope_search,
  111447. the search is not run
  111448. if we only use one
  111449. block size */
  111450. }
  111451. /* fill in the block. Note that for a short window, lW and nW are *short*
  111452. regardless of actual settings in the stream */
  111453. _vorbis_block_ripcord(vb);
  111454. vb->lW=v->lW;
  111455. vb->W=v->W;
  111456. vb->nW=v->nW;
  111457. if(v->W){
  111458. if(!v->lW || !v->nW){
  111459. vbi->blocktype=BLOCKTYPE_TRANSITION;
  111460. /*fprintf(stderr,"-");*/
  111461. }else{
  111462. vbi->blocktype=BLOCKTYPE_LONG;
  111463. /*fprintf(stderr,"_");*/
  111464. }
  111465. }else{
  111466. if(_ve_envelope_mark(v)){
  111467. vbi->blocktype=BLOCKTYPE_IMPULSE;
  111468. /*fprintf(stderr,"|");*/
  111469. }else{
  111470. vbi->blocktype=BLOCKTYPE_PADDING;
  111471. /*fprintf(stderr,".");*/
  111472. }
  111473. }
  111474. vb->vd=v;
  111475. vb->sequence=v->sequence++;
  111476. vb->granulepos=v->granulepos;
  111477. vb->pcmend=ci->blocksizes[v->W];
  111478. /* copy the vectors; this uses the local storage in vb */
  111479. /* this tracks 'strongest peak' for later psychoacoustics */
  111480. /* moved to the global psy state; clean this mess up */
  111481. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  111482. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  111483. vbi->ampmax=g->ampmax;
  111484. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  111485. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  111486. for(i=0;i<vi->channels;i++){
  111487. vbi->pcmdelay[i]=
  111488. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111489. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111490. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  111491. /* before we added the delay
  111492. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  111493. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  111494. */
  111495. }
  111496. /* handle eof detection: eof==0 means that we've not yet received EOF
  111497. eof>0 marks the last 'real' sample in pcm[]
  111498. eof<0 'no more to do'; doesn't get here */
  111499. if(v->eofflag){
  111500. if(v->centerW>=v->eofflag){
  111501. v->eofflag=-1;
  111502. vb->eofflag=1;
  111503. return(1);
  111504. }
  111505. }
  111506. /* advance storage vectors and clean up */
  111507. {
  111508. int new_centerNext=ci->blocksizes[1]/2;
  111509. int movementW=centerNext-new_centerNext;
  111510. if(movementW>0){
  111511. _ve_envelope_shift(b->ve,movementW);
  111512. v->pcm_current-=movementW;
  111513. for(i=0;i<vi->channels;i++)
  111514. memmove(v->pcm[i],v->pcm[i]+movementW,
  111515. v->pcm_current*sizeof(*v->pcm[i]));
  111516. v->lW=v->W;
  111517. v->W=v->nW;
  111518. v->centerW=new_centerNext;
  111519. if(v->eofflag){
  111520. v->eofflag-=movementW;
  111521. if(v->eofflag<=0)v->eofflag=-1;
  111522. /* do not add padding to end of stream! */
  111523. if(v->centerW>=v->eofflag){
  111524. v->granulepos+=movementW-(v->centerW-v->eofflag);
  111525. }else{
  111526. v->granulepos+=movementW;
  111527. }
  111528. }else{
  111529. v->granulepos+=movementW;
  111530. }
  111531. }
  111532. }
  111533. /* done */
  111534. return(1);
  111535. }
  111536. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  111537. vorbis_info *vi=v->vi;
  111538. codec_setup_info *ci;
  111539. int hs;
  111540. if(!v->backend_state)return -1;
  111541. if(!vi)return -1;
  111542. ci=(codec_setup_info*) vi->codec_setup;
  111543. if(!ci)return -1;
  111544. hs=ci->halfrate_flag;
  111545. v->centerW=ci->blocksizes[1]>>(hs+1);
  111546. v->pcm_current=v->centerW>>hs;
  111547. v->pcm_returned=-1;
  111548. v->granulepos=-1;
  111549. v->sequence=-1;
  111550. v->eofflag=0;
  111551. ((private_state *)(v->backend_state))->sample_count=-1;
  111552. return(0);
  111553. }
  111554. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111555. if(_vds_shared_init(v,vi,0)) return 1;
  111556. vorbis_synthesis_restart(v);
  111557. return 0;
  111558. }
  111559. /* Unlike in analysis, the window is only partially applied for each
  111560. block. The time domain envelope is not yet handled at the point of
  111561. calling (as it relies on the previous block). */
  111562. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  111563. vorbis_info *vi=v->vi;
  111564. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111565. private_state *b=(private_state*)v->backend_state;
  111566. int hs=ci->halfrate_flag;
  111567. int i,j;
  111568. if(!vb)return(OV_EINVAL);
  111569. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  111570. v->lW=v->W;
  111571. v->W=vb->W;
  111572. v->nW=-1;
  111573. if((v->sequence==-1)||
  111574. (v->sequence+1 != vb->sequence)){
  111575. v->granulepos=-1; /* out of sequence; lose count */
  111576. b->sample_count=-1;
  111577. }
  111578. v->sequence=vb->sequence;
  111579. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  111580. was called on block */
  111581. int n=ci->blocksizes[v->W]>>(hs+1);
  111582. int n0=ci->blocksizes[0]>>(hs+1);
  111583. int n1=ci->blocksizes[1]>>(hs+1);
  111584. int thisCenter;
  111585. int prevCenter;
  111586. v->glue_bits+=vb->glue_bits;
  111587. v->time_bits+=vb->time_bits;
  111588. v->floor_bits+=vb->floor_bits;
  111589. v->res_bits+=vb->res_bits;
  111590. if(v->centerW){
  111591. thisCenter=n1;
  111592. prevCenter=0;
  111593. }else{
  111594. thisCenter=0;
  111595. prevCenter=n1;
  111596. }
  111597. /* v->pcm is now used like a two-stage double buffer. We don't want
  111598. to have to constantly shift *or* adjust memory usage. Don't
  111599. accept a new block until the old is shifted out */
  111600. for(j=0;j<vi->channels;j++){
  111601. /* the overlap/add section */
  111602. if(v->lW){
  111603. if(v->W){
  111604. /* large/large */
  111605. float *w=_vorbis_window_get(b->window[1]-hs);
  111606. float *pcm=v->pcm[j]+prevCenter;
  111607. float *p=vb->pcm[j];
  111608. for(i=0;i<n1;i++)
  111609. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  111610. }else{
  111611. /* large/small */
  111612. float *w=_vorbis_window_get(b->window[0]-hs);
  111613. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  111614. float *p=vb->pcm[j];
  111615. for(i=0;i<n0;i++)
  111616. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111617. }
  111618. }else{
  111619. if(v->W){
  111620. /* small/large */
  111621. float *w=_vorbis_window_get(b->window[0]-hs);
  111622. float *pcm=v->pcm[j]+prevCenter;
  111623. float *p=vb->pcm[j]+n1/2-n0/2;
  111624. for(i=0;i<n0;i++)
  111625. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111626. for(;i<n1/2+n0/2;i++)
  111627. pcm[i]=p[i];
  111628. }else{
  111629. /* small/small */
  111630. float *w=_vorbis_window_get(b->window[0]-hs);
  111631. float *pcm=v->pcm[j]+prevCenter;
  111632. float *p=vb->pcm[j];
  111633. for(i=0;i<n0;i++)
  111634. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111635. }
  111636. }
  111637. /* the copy section */
  111638. {
  111639. float *pcm=v->pcm[j]+thisCenter;
  111640. float *p=vb->pcm[j]+n;
  111641. for(i=0;i<n;i++)
  111642. pcm[i]=p[i];
  111643. }
  111644. }
  111645. if(v->centerW)
  111646. v->centerW=0;
  111647. else
  111648. v->centerW=n1;
  111649. /* deal with initial packet state; we do this using the explicit
  111650. pcm_returned==-1 flag otherwise we're sensitive to first block
  111651. being short or long */
  111652. if(v->pcm_returned==-1){
  111653. v->pcm_returned=thisCenter;
  111654. v->pcm_current=thisCenter;
  111655. }else{
  111656. v->pcm_returned=prevCenter;
  111657. v->pcm_current=prevCenter+
  111658. ((ci->blocksizes[v->lW]/4+
  111659. ci->blocksizes[v->W]/4)>>hs);
  111660. }
  111661. }
  111662. /* track the frame number... This is for convenience, but also
  111663. making sure our last packet doesn't end with added padding. If
  111664. the last packet is partial, the number of samples we'll have to
  111665. return will be past the vb->granulepos.
  111666. This is not foolproof! It will be confused if we begin
  111667. decoding at the last page after a seek or hole. In that case,
  111668. we don't have a starting point to judge where the last frame
  111669. is. For this reason, vorbisfile will always try to make sure
  111670. it reads the last two marked pages in proper sequence */
  111671. if(b->sample_count==-1){
  111672. b->sample_count=0;
  111673. }else{
  111674. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111675. }
  111676. if(v->granulepos==-1){
  111677. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  111678. v->granulepos=vb->granulepos;
  111679. /* is this a short page? */
  111680. if(b->sample_count>v->granulepos){
  111681. /* corner case; if this is both the first and last audio page,
  111682. then spec says the end is cut, not beginning */
  111683. if(vb->eofflag){
  111684. /* trim the end */
  111685. /* no preceeding granulepos; assume we started at zero (we'd
  111686. have to in a short single-page stream) */
  111687. /* granulepos could be -1 due to a seek, but that would result
  111688. in a long count, not short count */
  111689. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  111690. }else{
  111691. /* trim the beginning */
  111692. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  111693. if(v->pcm_returned>v->pcm_current)
  111694. v->pcm_returned=v->pcm_current;
  111695. }
  111696. }
  111697. }
  111698. }else{
  111699. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111700. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  111701. if(v->granulepos>vb->granulepos){
  111702. long extra=v->granulepos-vb->granulepos;
  111703. if(extra)
  111704. if(vb->eofflag){
  111705. /* partial last frame. Strip the extra samples off */
  111706. v->pcm_current-=extra>>hs;
  111707. } /* else {Shouldn't happen *unless* the bitstream is out of
  111708. spec. Either way, believe the bitstream } */
  111709. } /* else {Shouldn't happen *unless* the bitstream is out of
  111710. spec. Either way, believe the bitstream } */
  111711. v->granulepos=vb->granulepos;
  111712. }
  111713. }
  111714. /* Update, cleanup */
  111715. if(vb->eofflag)v->eofflag=1;
  111716. return(0);
  111717. }
  111718. /* pcm==NULL indicates we just want the pending samples, no more */
  111719. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  111720. vorbis_info *vi=v->vi;
  111721. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  111722. if(pcm){
  111723. int i;
  111724. for(i=0;i<vi->channels;i++)
  111725. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111726. *pcm=v->pcmret;
  111727. }
  111728. return(v->pcm_current-v->pcm_returned);
  111729. }
  111730. return(0);
  111731. }
  111732. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  111733. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  111734. v->pcm_returned+=n;
  111735. return(0);
  111736. }
  111737. /* intended for use with a specific vorbisfile feature; we want access
  111738. to the [usually synthetic/postextrapolated] buffer and lapping at
  111739. the end of a decode cycle, specifically, a half-short-block worth.
  111740. This funtion works like pcmout above, except it will also expose
  111741. this implicit buffer data not normally decoded. */
  111742. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  111743. vorbis_info *vi=v->vi;
  111744. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  111745. int hs=ci->halfrate_flag;
  111746. int n=ci->blocksizes[v->W]>>(hs+1);
  111747. int n0=ci->blocksizes[0]>>(hs+1);
  111748. int n1=ci->blocksizes[1]>>(hs+1);
  111749. int i,j;
  111750. if(v->pcm_returned<0)return 0;
  111751. /* our returned data ends at pcm_returned; because the synthesis pcm
  111752. buffer is a two-fragment ring, that means our data block may be
  111753. fragmented by buffering, wrapping or a short block not filling
  111754. out a buffer. To simplify things, we unfragment if it's at all
  111755. possibly needed. Otherwise, we'd need to call lapout more than
  111756. once as well as hold additional dsp state. Opt for
  111757. simplicity. */
  111758. /* centerW was advanced by blockin; it would be the center of the
  111759. *next* block */
  111760. if(v->centerW==n1){
  111761. /* the data buffer wraps; swap the halves */
  111762. /* slow, sure, small */
  111763. for(j=0;j<vi->channels;j++){
  111764. float *p=v->pcm[j];
  111765. for(i=0;i<n1;i++){
  111766. float temp=p[i];
  111767. p[i]=p[i+n1];
  111768. p[i+n1]=temp;
  111769. }
  111770. }
  111771. v->pcm_current-=n1;
  111772. v->pcm_returned-=n1;
  111773. v->centerW=0;
  111774. }
  111775. /* solidify buffer into contiguous space */
  111776. if((v->lW^v->W)==1){
  111777. /* long/short or short/long */
  111778. for(j=0;j<vi->channels;j++){
  111779. float *s=v->pcm[j];
  111780. float *d=v->pcm[j]+(n1-n0)/2;
  111781. for(i=(n1+n0)/2-1;i>=0;--i)
  111782. d[i]=s[i];
  111783. }
  111784. v->pcm_returned+=(n1-n0)/2;
  111785. v->pcm_current+=(n1-n0)/2;
  111786. }else{
  111787. if(v->lW==0){
  111788. /* short/short */
  111789. for(j=0;j<vi->channels;j++){
  111790. float *s=v->pcm[j];
  111791. float *d=v->pcm[j]+n1-n0;
  111792. for(i=n0-1;i>=0;--i)
  111793. d[i]=s[i];
  111794. }
  111795. v->pcm_returned+=n1-n0;
  111796. v->pcm_current+=n1-n0;
  111797. }
  111798. }
  111799. if(pcm){
  111800. int i;
  111801. for(i=0;i<vi->channels;i++)
  111802. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111803. *pcm=v->pcmret;
  111804. }
  111805. return(n1+n-v->pcm_returned);
  111806. }
  111807. float *vorbis_window(vorbis_dsp_state *v,int W){
  111808. vorbis_info *vi=v->vi;
  111809. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  111810. int hs=ci->halfrate_flag;
  111811. private_state *b=(private_state*)v->backend_state;
  111812. if(b->window[W]-1<0)return NULL;
  111813. return _vorbis_window_get(b->window[W]-hs);
  111814. }
  111815. #endif
  111816. /*** End of inlined file: block.c ***/
  111817. /*** Start of inlined file: codebook.c ***/
  111818. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111819. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111820. // tasks..
  111821. #if JUCE_MSVC
  111822. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111823. #endif
  111824. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111825. #if JUCE_USE_OGGVORBIS
  111826. #include <stdlib.h>
  111827. #include <string.h>
  111828. #include <math.h>
  111829. /* packs the given codebook into the bitstream **************************/
  111830. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  111831. long i,j;
  111832. int ordered=0;
  111833. /* first the basic parameters */
  111834. oggpack_write(opb,0x564342,24);
  111835. oggpack_write(opb,c->dim,16);
  111836. oggpack_write(opb,c->entries,24);
  111837. /* pack the codewords. There are two packings; length ordered and
  111838. length random. Decide between the two now. */
  111839. for(i=1;i<c->entries;i++)
  111840. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  111841. if(i==c->entries)ordered=1;
  111842. if(ordered){
  111843. /* length ordered. We only need to say how many codewords of
  111844. each length. The actual codewords are generated
  111845. deterministically */
  111846. long count=0;
  111847. oggpack_write(opb,1,1); /* ordered */
  111848. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  111849. for(i=1;i<c->entries;i++){
  111850. long thisx=c->lengthlist[i];
  111851. long last=c->lengthlist[i-1];
  111852. if(thisx>last){
  111853. for(j=last;j<thisx;j++){
  111854. oggpack_write(opb,i-count,_ilog(c->entries-count));
  111855. count=i;
  111856. }
  111857. }
  111858. }
  111859. oggpack_write(opb,i-count,_ilog(c->entries-count));
  111860. }else{
  111861. /* length random. Again, we don't code the codeword itself, just
  111862. the length. This time, though, we have to encode each length */
  111863. oggpack_write(opb,0,1); /* unordered */
  111864. /* algortihmic mapping has use for 'unused entries', which we tag
  111865. here. The algorithmic mapping happens as usual, but the unused
  111866. entry has no codeword. */
  111867. for(i=0;i<c->entries;i++)
  111868. if(c->lengthlist[i]==0)break;
  111869. if(i==c->entries){
  111870. oggpack_write(opb,0,1); /* no unused entries */
  111871. for(i=0;i<c->entries;i++)
  111872. oggpack_write(opb,c->lengthlist[i]-1,5);
  111873. }else{
  111874. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  111875. for(i=0;i<c->entries;i++){
  111876. if(c->lengthlist[i]==0){
  111877. oggpack_write(opb,0,1);
  111878. }else{
  111879. oggpack_write(opb,1,1);
  111880. oggpack_write(opb,c->lengthlist[i]-1,5);
  111881. }
  111882. }
  111883. }
  111884. }
  111885. /* is the entry number the desired return value, or do we have a
  111886. mapping? If we have a mapping, what type? */
  111887. oggpack_write(opb,c->maptype,4);
  111888. switch(c->maptype){
  111889. case 0:
  111890. /* no mapping */
  111891. break;
  111892. case 1:case 2:
  111893. /* implicitly populated value mapping */
  111894. /* explicitly populated value mapping */
  111895. if(!c->quantlist){
  111896. /* no quantlist? error */
  111897. return(-1);
  111898. }
  111899. /* values that define the dequantization */
  111900. oggpack_write(opb,c->q_min,32);
  111901. oggpack_write(opb,c->q_delta,32);
  111902. oggpack_write(opb,c->q_quant-1,4);
  111903. oggpack_write(opb,c->q_sequencep,1);
  111904. {
  111905. int quantvals;
  111906. switch(c->maptype){
  111907. case 1:
  111908. /* a single column of (c->entries/c->dim) quantized values for
  111909. building a full value list algorithmically (square lattice) */
  111910. quantvals=_book_maptype1_quantvals(c);
  111911. break;
  111912. case 2:
  111913. /* every value (c->entries*c->dim total) specified explicitly */
  111914. quantvals=c->entries*c->dim;
  111915. break;
  111916. default: /* NOT_REACHABLE */
  111917. quantvals=-1;
  111918. }
  111919. /* quantized values */
  111920. for(i=0;i<quantvals;i++)
  111921. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  111922. }
  111923. break;
  111924. default:
  111925. /* error case; we don't have any other map types now */
  111926. return(-1);
  111927. }
  111928. return(0);
  111929. }
  111930. /* unpacks a codebook from the packet buffer into the codebook struct,
  111931. readies the codebook auxiliary structures for decode *************/
  111932. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  111933. long i,j;
  111934. memset(s,0,sizeof(*s));
  111935. s->allocedp=1;
  111936. /* make sure alignment is correct */
  111937. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  111938. /* first the basic parameters */
  111939. s->dim=oggpack_read(opb,16);
  111940. s->entries=oggpack_read(opb,24);
  111941. if(s->entries==-1)goto _eofout;
  111942. /* codeword ordering.... length ordered or unordered? */
  111943. switch((int)oggpack_read(opb,1)){
  111944. case 0:
  111945. /* unordered */
  111946. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  111947. /* allocated but unused entries? */
  111948. if(oggpack_read(opb,1)){
  111949. /* yes, unused entries */
  111950. for(i=0;i<s->entries;i++){
  111951. if(oggpack_read(opb,1)){
  111952. long num=oggpack_read(opb,5);
  111953. if(num==-1)goto _eofout;
  111954. s->lengthlist[i]=num+1;
  111955. }else
  111956. s->lengthlist[i]=0;
  111957. }
  111958. }else{
  111959. /* all entries used; no tagging */
  111960. for(i=0;i<s->entries;i++){
  111961. long num=oggpack_read(opb,5);
  111962. if(num==-1)goto _eofout;
  111963. s->lengthlist[i]=num+1;
  111964. }
  111965. }
  111966. break;
  111967. case 1:
  111968. /* ordered */
  111969. {
  111970. long length=oggpack_read(opb,5)+1;
  111971. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  111972. for(i=0;i<s->entries;){
  111973. long num=oggpack_read(opb,_ilog(s->entries-i));
  111974. if(num==-1)goto _eofout;
  111975. for(j=0;j<num && i<s->entries;j++,i++)
  111976. s->lengthlist[i]=length;
  111977. length++;
  111978. }
  111979. }
  111980. break;
  111981. default:
  111982. /* EOF */
  111983. return(-1);
  111984. }
  111985. /* Do we have a mapping to unpack? */
  111986. switch((s->maptype=oggpack_read(opb,4))){
  111987. case 0:
  111988. /* no mapping */
  111989. break;
  111990. case 1: case 2:
  111991. /* implicitly populated value mapping */
  111992. /* explicitly populated value mapping */
  111993. s->q_min=oggpack_read(opb,32);
  111994. s->q_delta=oggpack_read(opb,32);
  111995. s->q_quant=oggpack_read(opb,4)+1;
  111996. s->q_sequencep=oggpack_read(opb,1);
  111997. {
  111998. int quantvals=0;
  111999. switch(s->maptype){
  112000. case 1:
  112001. quantvals=_book_maptype1_quantvals(s);
  112002. break;
  112003. case 2:
  112004. quantvals=s->entries*s->dim;
  112005. break;
  112006. }
  112007. /* quantized values */
  112008. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  112009. for(i=0;i<quantvals;i++)
  112010. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  112011. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  112012. }
  112013. break;
  112014. default:
  112015. goto _errout;
  112016. }
  112017. /* all set */
  112018. return(0);
  112019. _errout:
  112020. _eofout:
  112021. vorbis_staticbook_clear(s);
  112022. return(-1);
  112023. }
  112024. /* returns the number of bits ************************************************/
  112025. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  112026. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  112027. return(book->c->lengthlist[a]);
  112028. }
  112029. /* One the encode side, our vector writers are each designed for a
  112030. specific purpose, and the encoder is not flexible without modification:
  112031. The LSP vector coder uses a single stage nearest-match with no
  112032. interleave, so no step and no error return. This is specced by floor0
  112033. and doesn't change.
  112034. Residue0 encoding interleaves, uses multiple stages, and each stage
  112035. peels of a specific amount of resolution from a lattice (thus we want
  112036. to match by threshold, not nearest match). Residue doesn't *have* to
  112037. be encoded that way, but to change it, one will need to add more
  112038. infrastructure on the encode side (decode side is specced and simpler) */
  112039. /* floor0 LSP (single stage, non interleaved, nearest match) */
  112040. /* returns entry number and *modifies a* to the quantization value *****/
  112041. int vorbis_book_errorv(codebook *book,float *a){
  112042. int dim=book->dim,k;
  112043. int best=_best(book,a,1);
  112044. for(k=0;k<dim;k++)
  112045. a[k]=(book->valuelist+best*dim)[k];
  112046. return(best);
  112047. }
  112048. /* returns the number of bits and *modifies a* to the quantization value *****/
  112049. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  112050. int k,dim=book->dim;
  112051. for(k=0;k<dim;k++)
  112052. a[k]=(book->valuelist+best*dim)[k];
  112053. return(vorbis_book_encode(book,best,b));
  112054. }
  112055. /* the 'eliminate the decode tree' optimization actually requires the
  112056. codewords to be MSb first, not LSb. This is an annoying inelegancy
  112057. (and one of the first places where carefully thought out design
  112058. turned out to be wrong; Vorbis II and future Ogg codecs should go
  112059. to an MSb bitpacker), but not actually the huge hit it appears to
  112060. be. The first-stage decode table catches most words so that
  112061. bitreverse is not in the main execution path. */
  112062. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  112063. int read=book->dec_maxlength;
  112064. long lo,hi;
  112065. long lok = oggpack_look(b,book->dec_firsttablen);
  112066. if (lok >= 0) {
  112067. long entry = book->dec_firsttable[lok];
  112068. if(entry&0x80000000UL){
  112069. lo=(entry>>15)&0x7fff;
  112070. hi=book->used_entries-(entry&0x7fff);
  112071. }else{
  112072. oggpack_adv(b, book->dec_codelengths[entry-1]);
  112073. return(entry-1);
  112074. }
  112075. }else{
  112076. lo=0;
  112077. hi=book->used_entries;
  112078. }
  112079. lok = oggpack_look(b, read);
  112080. while(lok<0 && read>1)
  112081. lok = oggpack_look(b, --read);
  112082. if(lok<0)return -1;
  112083. /* bisect search for the codeword in the ordered list */
  112084. {
  112085. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  112086. while(hi-lo>1){
  112087. long p=(hi-lo)>>1;
  112088. long test=book->codelist[lo+p]>testword;
  112089. lo+=p&(test-1);
  112090. hi-=p&(-test);
  112091. }
  112092. if(book->dec_codelengths[lo]<=read){
  112093. oggpack_adv(b, book->dec_codelengths[lo]);
  112094. return(lo);
  112095. }
  112096. }
  112097. oggpack_adv(b, read);
  112098. return(-1);
  112099. }
  112100. /* Decode side is specced and easier, because we don't need to find
  112101. matches using different criteria; we simply read and map. There are
  112102. two things we need to do 'depending':
  112103. We may need to support interleave. We don't really, but it's
  112104. convenient to do it here rather than rebuild the vector later.
  112105. Cascades may be additive or multiplicitive; this is not inherent in
  112106. the codebook, but set in the code using the codebook. Like
  112107. interleaving, it's easiest to do it here.
  112108. addmul==0 -> declarative (set the value)
  112109. addmul==1 -> additive
  112110. addmul==2 -> multiplicitive */
  112111. /* returns the [original, not compacted] entry number or -1 on eof *********/
  112112. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  112113. long packed_entry=decode_packed_entry_number(book,b);
  112114. if(packed_entry>=0)
  112115. return(book->dec_index[packed_entry]);
  112116. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  112117. return(packed_entry);
  112118. }
  112119. /* returns 0 on OK or -1 on eof *************************************/
  112120. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  112121. int step=n/book->dim;
  112122. long *entry = (long*)alloca(sizeof(*entry)*step);
  112123. float **t = (float**)alloca(sizeof(*t)*step);
  112124. int i,j,o;
  112125. for (i = 0; i < step; i++) {
  112126. entry[i]=decode_packed_entry_number(book,b);
  112127. if(entry[i]==-1)return(-1);
  112128. t[i] = book->valuelist+entry[i]*book->dim;
  112129. }
  112130. for(i=0,o=0;i<book->dim;i++,o+=step)
  112131. for (j=0;j<step;j++)
  112132. a[o+j]+=t[j][i];
  112133. return(0);
  112134. }
  112135. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  112136. int i,j,entry;
  112137. float *t;
  112138. if(book->dim>8){
  112139. for(i=0;i<n;){
  112140. entry = decode_packed_entry_number(book,b);
  112141. if(entry==-1)return(-1);
  112142. t = book->valuelist+entry*book->dim;
  112143. for (j=0;j<book->dim;)
  112144. a[i++]+=t[j++];
  112145. }
  112146. }else{
  112147. for(i=0;i<n;){
  112148. entry = decode_packed_entry_number(book,b);
  112149. if(entry==-1)return(-1);
  112150. t = book->valuelist+entry*book->dim;
  112151. j=0;
  112152. switch((int)book->dim){
  112153. case 8:
  112154. a[i++]+=t[j++];
  112155. case 7:
  112156. a[i++]+=t[j++];
  112157. case 6:
  112158. a[i++]+=t[j++];
  112159. case 5:
  112160. a[i++]+=t[j++];
  112161. case 4:
  112162. a[i++]+=t[j++];
  112163. case 3:
  112164. a[i++]+=t[j++];
  112165. case 2:
  112166. a[i++]+=t[j++];
  112167. case 1:
  112168. a[i++]+=t[j++];
  112169. case 0:
  112170. break;
  112171. }
  112172. }
  112173. }
  112174. return(0);
  112175. }
  112176. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  112177. int i,j,entry;
  112178. float *t;
  112179. for(i=0;i<n;){
  112180. entry = decode_packed_entry_number(book,b);
  112181. if(entry==-1)return(-1);
  112182. t = book->valuelist+entry*book->dim;
  112183. for (j=0;j<book->dim;)
  112184. a[i++]=t[j++];
  112185. }
  112186. return(0);
  112187. }
  112188. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  112189. oggpack_buffer *b,int n){
  112190. long i,j,entry;
  112191. int chptr=0;
  112192. for(i=offset/ch;i<(offset+n)/ch;){
  112193. entry = decode_packed_entry_number(book,b);
  112194. if(entry==-1)return(-1);
  112195. {
  112196. const float *t = book->valuelist+entry*book->dim;
  112197. for (j=0;j<book->dim;j++){
  112198. a[chptr++][i]+=t[j];
  112199. if(chptr==ch){
  112200. chptr=0;
  112201. i++;
  112202. }
  112203. }
  112204. }
  112205. }
  112206. return(0);
  112207. }
  112208. #ifdef _V_SELFTEST
  112209. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  112210. number of vectors through (keeping track of the quantized values),
  112211. and decode using the unpacked book. quantized version of in should
  112212. exactly equal out */
  112213. #include <stdio.h>
  112214. #include "vorbis/book/lsp20_0.vqh"
  112215. #include "vorbis/book/res0a_13.vqh"
  112216. #define TESTSIZE 40
  112217. float test1[TESTSIZE]={
  112218. 0.105939f,
  112219. 0.215373f,
  112220. 0.429117f,
  112221. 0.587974f,
  112222. 0.181173f,
  112223. 0.296583f,
  112224. 0.515707f,
  112225. 0.715261f,
  112226. 0.162327f,
  112227. 0.263834f,
  112228. 0.342876f,
  112229. 0.406025f,
  112230. 0.103571f,
  112231. 0.223561f,
  112232. 0.368513f,
  112233. 0.540313f,
  112234. 0.136672f,
  112235. 0.395882f,
  112236. 0.587183f,
  112237. 0.652476f,
  112238. 0.114338f,
  112239. 0.417300f,
  112240. 0.525486f,
  112241. 0.698679f,
  112242. 0.147492f,
  112243. 0.324481f,
  112244. 0.643089f,
  112245. 0.757582f,
  112246. 0.139556f,
  112247. 0.215795f,
  112248. 0.324559f,
  112249. 0.399387f,
  112250. 0.120236f,
  112251. 0.267420f,
  112252. 0.446940f,
  112253. 0.608760f,
  112254. 0.115587f,
  112255. 0.287234f,
  112256. 0.571081f,
  112257. 0.708603f,
  112258. };
  112259. float test3[TESTSIZE]={
  112260. 0,1,-2,3,4,-5,6,7,8,9,
  112261. 8,-2,7,-1,4,6,8,3,1,-9,
  112262. 10,11,12,13,14,15,26,17,18,19,
  112263. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  112264. static_codebook *testlist[]={&_vq_book_lsp20_0,
  112265. &_vq_book_res0a_13,NULL};
  112266. float *testvec[]={test1,test3};
  112267. int main(){
  112268. oggpack_buffer write;
  112269. oggpack_buffer read;
  112270. long ptr=0,i;
  112271. oggpack_writeinit(&write);
  112272. fprintf(stderr,"Testing codebook abstraction...:\n");
  112273. while(testlist[ptr]){
  112274. codebook c;
  112275. static_codebook s;
  112276. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  112277. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  112278. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  112279. memset(iv,0,sizeof(*iv)*TESTSIZE);
  112280. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  112281. /* pack the codebook, write the testvector */
  112282. oggpack_reset(&write);
  112283. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  112284. we can write */
  112285. vorbis_staticbook_pack(testlist[ptr],&write);
  112286. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  112287. for(i=0;i<TESTSIZE;i+=c.dim){
  112288. int best=_best(&c,qv+i,1);
  112289. vorbis_book_encodev(&c,best,qv+i,&write);
  112290. }
  112291. vorbis_book_clear(&c);
  112292. fprintf(stderr,"OK.\n");
  112293. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  112294. /* transfer the write data to a read buffer and unpack/read */
  112295. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  112296. if(vorbis_staticbook_unpack(&read,&s)){
  112297. fprintf(stderr,"Error unpacking codebook.\n");
  112298. exit(1);
  112299. }
  112300. if(vorbis_book_init_decode(&c,&s)){
  112301. fprintf(stderr,"Error initializing codebook.\n");
  112302. exit(1);
  112303. }
  112304. for(i=0;i<TESTSIZE;i+=c.dim)
  112305. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  112306. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  112307. exit(1);
  112308. }
  112309. for(i=0;i<TESTSIZE;i++)
  112310. if(fabs(qv[i]-iv[i])>.000001){
  112311. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  112312. iv[i],qv[i],i);
  112313. exit(1);
  112314. }
  112315. fprintf(stderr,"OK\n");
  112316. ptr++;
  112317. }
  112318. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  112319. exit(0);
  112320. }
  112321. #endif
  112322. #endif
  112323. /*** End of inlined file: codebook.c ***/
  112324. /*** Start of inlined file: envelope.c ***/
  112325. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112326. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112327. // tasks..
  112328. #if JUCE_MSVC
  112329. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112330. #endif
  112331. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112332. #if JUCE_USE_OGGVORBIS
  112333. #include <stdlib.h>
  112334. #include <string.h>
  112335. #include <stdio.h>
  112336. #include <math.h>
  112337. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  112338. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112339. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112340. int ch=vi->channels;
  112341. int i,j;
  112342. int n=e->winlength=128;
  112343. e->searchstep=64; /* not random */
  112344. e->minenergy=gi->preecho_minenergy;
  112345. e->ch=ch;
  112346. e->storage=128;
  112347. e->cursor=ci->blocksizes[1]/2;
  112348. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  112349. mdct_init(&e->mdct,n);
  112350. for(i=0;i<n;i++){
  112351. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  112352. e->mdct_win[i]*=e->mdct_win[i];
  112353. }
  112354. /* magic follows */
  112355. e->band[0].begin=2; e->band[0].end=4;
  112356. e->band[1].begin=4; e->band[1].end=5;
  112357. e->band[2].begin=6; e->band[2].end=6;
  112358. e->band[3].begin=9; e->band[3].end=8;
  112359. e->band[4].begin=13; e->band[4].end=8;
  112360. e->band[5].begin=17; e->band[5].end=8;
  112361. e->band[6].begin=22; e->band[6].end=8;
  112362. for(j=0;j<VE_BANDS;j++){
  112363. n=e->band[j].end;
  112364. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  112365. for(i=0;i<n;i++){
  112366. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  112367. e->band[j].total+=e->band[j].window[i];
  112368. }
  112369. e->band[j].total=1./e->band[j].total;
  112370. }
  112371. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  112372. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  112373. }
  112374. void _ve_envelope_clear(envelope_lookup *e){
  112375. int i;
  112376. mdct_clear(&e->mdct);
  112377. for(i=0;i<VE_BANDS;i++)
  112378. _ogg_free(e->band[i].window);
  112379. _ogg_free(e->mdct_win);
  112380. _ogg_free(e->filter);
  112381. _ogg_free(e->mark);
  112382. memset(e,0,sizeof(*e));
  112383. }
  112384. /* fairly straight threshhold-by-band based until we find something
  112385. that works better and isn't patented. */
  112386. static int _ve_amp(envelope_lookup *ve,
  112387. vorbis_info_psy_global *gi,
  112388. float *data,
  112389. envelope_band *bands,
  112390. envelope_filter_state *filters,
  112391. long pos){
  112392. long n=ve->winlength;
  112393. int ret=0;
  112394. long i,j;
  112395. float decay;
  112396. /* we want to have a 'minimum bar' for energy, else we're just
  112397. basing blocks on quantization noise that outweighs the signal
  112398. itself (for low power signals) */
  112399. float minV=ve->minenergy;
  112400. float *vec=(float*) alloca(n*sizeof(*vec));
  112401. /* stretch is used to gradually lengthen the number of windows
  112402. considered prevoius-to-potential-trigger */
  112403. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  112404. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  112405. if(penalty<0.f)penalty=0.f;
  112406. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  112407. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  112408. totalshift+pos*ve->searchstep);*/
  112409. /* window and transform */
  112410. for(i=0;i<n;i++)
  112411. vec[i]=data[i]*ve->mdct_win[i];
  112412. mdct_forward(&ve->mdct,vec,vec);
  112413. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  112414. /* near-DC spreading function; this has nothing to do with
  112415. psychoacoustics, just sidelobe leakage and window size */
  112416. {
  112417. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  112418. int ptr=filters->nearptr;
  112419. /* the accumulation is regularly refreshed from scratch to avoid
  112420. floating point creep */
  112421. if(ptr==0){
  112422. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  112423. filters->nearDC_partialacc=temp;
  112424. }else{
  112425. decay=filters->nearDC_acc+=temp;
  112426. filters->nearDC_partialacc+=temp;
  112427. }
  112428. filters->nearDC_acc-=filters->nearDC[ptr];
  112429. filters->nearDC[ptr]=temp;
  112430. decay*=(1./(VE_NEARDC+1));
  112431. filters->nearptr++;
  112432. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  112433. decay=todB(&decay)*.5-15.f;
  112434. }
  112435. /* perform spreading and limiting, also smooth the spectrum. yes,
  112436. the MDCT results in all real coefficients, but it still *behaves*
  112437. like real/imaginary pairs */
  112438. for(i=0;i<n/2;i+=2){
  112439. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  112440. val=todB(&val)*.5f;
  112441. if(val<decay)val=decay;
  112442. if(val<minV)val=minV;
  112443. vec[i>>1]=val;
  112444. decay-=8.;
  112445. }
  112446. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  112447. /* perform preecho/postecho triggering by band */
  112448. for(j=0;j<VE_BANDS;j++){
  112449. float acc=0.;
  112450. float valmax,valmin;
  112451. /* accumulate amplitude */
  112452. for(i=0;i<bands[j].end;i++)
  112453. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  112454. acc*=bands[j].total;
  112455. /* convert amplitude to delta */
  112456. {
  112457. int p,thisx=filters[j].ampptr;
  112458. float postmax,postmin,premax=-99999.f,premin=99999.f;
  112459. p=thisx;
  112460. p--;
  112461. if(p<0)p+=VE_AMP;
  112462. postmax=max(acc,filters[j].ampbuf[p]);
  112463. postmin=min(acc,filters[j].ampbuf[p]);
  112464. for(i=0;i<stretch;i++){
  112465. p--;
  112466. if(p<0)p+=VE_AMP;
  112467. premax=max(premax,filters[j].ampbuf[p]);
  112468. premin=min(premin,filters[j].ampbuf[p]);
  112469. }
  112470. valmin=postmin-premin;
  112471. valmax=postmax-premax;
  112472. /*filters[j].markers[pos]=valmax;*/
  112473. filters[j].ampbuf[thisx]=acc;
  112474. filters[j].ampptr++;
  112475. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  112476. }
  112477. /* look at min/max, decide trigger */
  112478. if(valmax>gi->preecho_thresh[j]+penalty){
  112479. ret|=1;
  112480. ret|=4;
  112481. }
  112482. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  112483. }
  112484. return(ret);
  112485. }
  112486. #if 0
  112487. static int seq=0;
  112488. static ogg_int64_t totalshift=-1024;
  112489. #endif
  112490. long _ve_envelope_search(vorbis_dsp_state *v){
  112491. vorbis_info *vi=v->vi;
  112492. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  112493. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112494. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112495. long i,j;
  112496. int first=ve->current/ve->searchstep;
  112497. int last=v->pcm_current/ve->searchstep-VE_WIN;
  112498. if(first<0)first=0;
  112499. /* make sure we have enough storage to match the PCM */
  112500. if(last+VE_WIN+VE_POST>ve->storage){
  112501. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  112502. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  112503. }
  112504. for(j=first;j<last;j++){
  112505. int ret=0;
  112506. ve->stretch++;
  112507. if(ve->stretch>VE_MAXSTRETCH*2)
  112508. ve->stretch=VE_MAXSTRETCH*2;
  112509. for(i=0;i<ve->ch;i++){
  112510. float *pcm=v->pcm[i]+ve->searchstep*(j);
  112511. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  112512. }
  112513. ve->mark[j+VE_POST]=0;
  112514. if(ret&1){
  112515. ve->mark[j]=1;
  112516. ve->mark[j+1]=1;
  112517. }
  112518. if(ret&2){
  112519. ve->mark[j]=1;
  112520. if(j>0)ve->mark[j-1]=1;
  112521. }
  112522. if(ret&4)ve->stretch=-1;
  112523. }
  112524. ve->current=last*ve->searchstep;
  112525. {
  112526. long centerW=v->centerW;
  112527. long testW=
  112528. centerW+
  112529. ci->blocksizes[v->W]/4+
  112530. ci->blocksizes[1]/2+
  112531. ci->blocksizes[0]/4;
  112532. j=ve->cursor;
  112533. while(j<ve->current-(ve->searchstep)){/* account for postecho
  112534. working back one window */
  112535. if(j>=testW)return(1);
  112536. ve->cursor=j;
  112537. if(ve->mark[j/ve->searchstep]){
  112538. if(j>centerW){
  112539. #if 0
  112540. if(j>ve->curmark){
  112541. float *marker=alloca(v->pcm_current*sizeof(*marker));
  112542. int l,m;
  112543. memset(marker,0,sizeof(*marker)*v->pcm_current);
  112544. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  112545. seq,
  112546. (totalshift+ve->cursor)/44100.,
  112547. (totalshift+j)/44100.);
  112548. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  112549. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  112550. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  112551. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  112552. for(m=0;m<VE_BANDS;m++){
  112553. char buf[80];
  112554. sprintf(buf,"delL%d",m);
  112555. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  112556. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112557. }
  112558. for(m=0;m<VE_BANDS;m++){
  112559. char buf[80];
  112560. sprintf(buf,"delR%d",m);
  112561. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  112562. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112563. }
  112564. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  112565. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  112566. seq++;
  112567. }
  112568. #endif
  112569. ve->curmark=j;
  112570. if(j>=testW)return(1);
  112571. return(0);
  112572. }
  112573. }
  112574. j+=ve->searchstep;
  112575. }
  112576. }
  112577. return(-1);
  112578. }
  112579. int _ve_envelope_mark(vorbis_dsp_state *v){
  112580. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112581. vorbis_info *vi=v->vi;
  112582. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112583. long centerW=v->centerW;
  112584. long beginW=centerW-ci->blocksizes[v->W]/4;
  112585. long endW=centerW+ci->blocksizes[v->W]/4;
  112586. if(v->W){
  112587. beginW-=ci->blocksizes[v->lW]/4;
  112588. endW+=ci->blocksizes[v->nW]/4;
  112589. }else{
  112590. beginW-=ci->blocksizes[0]/4;
  112591. endW+=ci->blocksizes[0]/4;
  112592. }
  112593. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  112594. {
  112595. long first=beginW/ve->searchstep;
  112596. long last=endW/ve->searchstep;
  112597. long i;
  112598. for(i=first;i<last;i++)
  112599. if(ve->mark[i])return(1);
  112600. }
  112601. return(0);
  112602. }
  112603. void _ve_envelope_shift(envelope_lookup *e,long shift){
  112604. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  112605. ahead of ve->current */
  112606. int smallshift=shift/e->searchstep;
  112607. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  112608. #if 0
  112609. for(i=0;i<VE_BANDS*e->ch;i++)
  112610. memmove(e->filter[i].markers,
  112611. e->filter[i].markers+smallshift,
  112612. (1024-smallshift)*sizeof(*(*e->filter).markers));
  112613. totalshift+=shift;
  112614. #endif
  112615. e->current-=shift;
  112616. if(e->curmark>=0)
  112617. e->curmark-=shift;
  112618. e->cursor-=shift;
  112619. }
  112620. #endif
  112621. /*** End of inlined file: envelope.c ***/
  112622. /*** Start of inlined file: floor0.c ***/
  112623. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112624. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112625. // tasks..
  112626. #if JUCE_MSVC
  112627. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112628. #endif
  112629. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112630. #if JUCE_USE_OGGVORBIS
  112631. #include <stdlib.h>
  112632. #include <string.h>
  112633. #include <math.h>
  112634. /*** Start of inlined file: lsp.h ***/
  112635. #ifndef _V_LSP_H_
  112636. #define _V_LSP_H_
  112637. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  112638. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  112639. float *lsp,int m,
  112640. float amp,float ampoffset);
  112641. #endif
  112642. /*** End of inlined file: lsp.h ***/
  112643. #include <stdio.h>
  112644. typedef struct {
  112645. int ln;
  112646. int m;
  112647. int **linearmap;
  112648. int n[2];
  112649. vorbis_info_floor0 *vi;
  112650. long bits;
  112651. long frames;
  112652. } vorbis_look_floor0;
  112653. /***********************************************/
  112654. static void floor0_free_info(vorbis_info_floor *i){
  112655. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  112656. if(info){
  112657. memset(info,0,sizeof(*info));
  112658. _ogg_free(info);
  112659. }
  112660. }
  112661. static void floor0_free_look(vorbis_look_floor *i){
  112662. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112663. if(look){
  112664. if(look->linearmap){
  112665. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  112666. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  112667. _ogg_free(look->linearmap);
  112668. }
  112669. memset(look,0,sizeof(*look));
  112670. _ogg_free(look);
  112671. }
  112672. }
  112673. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112674. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112675. int j;
  112676. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  112677. info->order=oggpack_read(opb,8);
  112678. info->rate=oggpack_read(opb,16);
  112679. info->barkmap=oggpack_read(opb,16);
  112680. info->ampbits=oggpack_read(opb,6);
  112681. info->ampdB=oggpack_read(opb,8);
  112682. info->numbooks=oggpack_read(opb,4)+1;
  112683. if(info->order<1)goto err_out;
  112684. if(info->rate<1)goto err_out;
  112685. if(info->barkmap<1)goto err_out;
  112686. if(info->numbooks<1)goto err_out;
  112687. for(j=0;j<info->numbooks;j++){
  112688. info->books[j]=oggpack_read(opb,8);
  112689. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  112690. }
  112691. return(info);
  112692. err_out:
  112693. floor0_free_info(info);
  112694. return(NULL);
  112695. }
  112696. /* initialize Bark scale and normalization lookups. We could do this
  112697. with static tables, but Vorbis allows a number of possible
  112698. combinations, so it's best to do it computationally.
  112699. The below is authoritative in terms of defining scale mapping.
  112700. Note that the scale depends on the sampling rate as well as the
  112701. linear block and mapping sizes */
  112702. static void floor0_map_lazy_init(vorbis_block *vb,
  112703. vorbis_info_floor *infoX,
  112704. vorbis_look_floor0 *look){
  112705. if(!look->linearmap[vb->W]){
  112706. vorbis_dsp_state *vd=vb->vd;
  112707. vorbis_info *vi=vd->vi;
  112708. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112709. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  112710. int W=vb->W;
  112711. int n=ci->blocksizes[W]/2,j;
  112712. /* we choose a scaling constant so that:
  112713. floor(bark(rate/2-1)*C)=mapped-1
  112714. floor(bark(rate/2)*C)=mapped */
  112715. float scale=look->ln/toBARK(info->rate/2.f);
  112716. /* the mapping from a linear scale to a smaller bark scale is
  112717. straightforward. We do *not* make sure that the linear mapping
  112718. does not skip bark-scale bins; the decoder simply skips them and
  112719. the encoder may do what it wishes in filling them. They're
  112720. necessary in some mapping combinations to keep the scale spacing
  112721. accurate */
  112722. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  112723. for(j=0;j<n;j++){
  112724. int val=floor( toBARK((info->rate/2.f)/n*j)
  112725. *scale); /* bark numbers represent band edges */
  112726. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  112727. look->linearmap[W][j]=val;
  112728. }
  112729. look->linearmap[W][j]=-1;
  112730. look->n[W]=n;
  112731. }
  112732. }
  112733. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  112734. vorbis_info_floor *i){
  112735. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  112736. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  112737. look->m=info->order;
  112738. look->ln=info->barkmap;
  112739. look->vi=info;
  112740. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  112741. return look;
  112742. }
  112743. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  112744. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112745. vorbis_info_floor0 *info=look->vi;
  112746. int j,k;
  112747. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  112748. if(ampraw>0){ /* also handles the -1 out of data case */
  112749. long maxval=(1<<info->ampbits)-1;
  112750. float amp=(float)ampraw/maxval*info->ampdB;
  112751. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  112752. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  112753. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  112754. codebook *b=ci->fullbooks+info->books[booknum];
  112755. float last=0.f;
  112756. /* the additional b->dim is a guard against any possible stack
  112757. smash; b->dim is provably more than we can overflow the
  112758. vector */
  112759. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  112760. for(j=0;j<look->m;j+=b->dim)
  112761. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  112762. for(j=0;j<look->m;){
  112763. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  112764. last=lsp[j-1];
  112765. }
  112766. lsp[look->m]=amp;
  112767. return(lsp);
  112768. }
  112769. }
  112770. eop:
  112771. return(NULL);
  112772. }
  112773. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  112774. void *memo,float *out){
  112775. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112776. vorbis_info_floor0 *info=look->vi;
  112777. floor0_map_lazy_init(vb,info,look);
  112778. if(memo){
  112779. float *lsp=(float *)memo;
  112780. float amp=lsp[look->m];
  112781. /* take the coefficients back to a spectral envelope curve */
  112782. vorbis_lsp_to_curve(out,
  112783. look->linearmap[vb->W],
  112784. look->n[vb->W],
  112785. look->ln,
  112786. lsp,look->m,amp,(float)info->ampdB);
  112787. return(1);
  112788. }
  112789. memset(out,0,sizeof(*out)*look->n[vb->W]);
  112790. return(0);
  112791. }
  112792. /* export hooks */
  112793. vorbis_func_floor floor0_exportbundle={
  112794. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  112795. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  112796. };
  112797. #endif
  112798. /*** End of inlined file: floor0.c ***/
  112799. /*** Start of inlined file: floor1.c ***/
  112800. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112801. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112802. // tasks..
  112803. #if JUCE_MSVC
  112804. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112805. #endif
  112806. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112807. #if JUCE_USE_OGGVORBIS
  112808. #include <stdlib.h>
  112809. #include <string.h>
  112810. #include <math.h>
  112811. #include <stdio.h>
  112812. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  112813. typedef struct {
  112814. int sorted_index[VIF_POSIT+2];
  112815. int forward_index[VIF_POSIT+2];
  112816. int reverse_index[VIF_POSIT+2];
  112817. int hineighbor[VIF_POSIT];
  112818. int loneighbor[VIF_POSIT];
  112819. int posts;
  112820. int n;
  112821. int quant_q;
  112822. vorbis_info_floor1 *vi;
  112823. long phrasebits;
  112824. long postbits;
  112825. long frames;
  112826. } vorbis_look_floor1;
  112827. typedef struct lsfit_acc{
  112828. long x0;
  112829. long x1;
  112830. long xa;
  112831. long ya;
  112832. long x2a;
  112833. long y2a;
  112834. long xya;
  112835. long an;
  112836. } lsfit_acc;
  112837. /***********************************************/
  112838. static void floor1_free_info(vorbis_info_floor *i){
  112839. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  112840. if(info){
  112841. memset(info,0,sizeof(*info));
  112842. _ogg_free(info);
  112843. }
  112844. }
  112845. static void floor1_free_look(vorbis_look_floor *i){
  112846. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  112847. if(look){
  112848. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  112849. (float)look->phrasebits/look->frames,
  112850. (float)look->postbits/look->frames,
  112851. (float)(look->postbits+look->phrasebits)/look->frames);*/
  112852. memset(look,0,sizeof(*look));
  112853. _ogg_free(look);
  112854. }
  112855. }
  112856. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  112857. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  112858. int j,k;
  112859. int count=0;
  112860. int rangebits;
  112861. int maxposit=info->postlist[1];
  112862. int maxclass=-1;
  112863. /* save out partitions */
  112864. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  112865. for(j=0;j<info->partitions;j++){
  112866. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  112867. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  112868. }
  112869. /* save out partition classes */
  112870. for(j=0;j<maxclass+1;j++){
  112871. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  112872. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  112873. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  112874. for(k=0;k<(1<<info->class_subs[j]);k++)
  112875. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  112876. }
  112877. /* save out the post list */
  112878. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  112879. oggpack_write(opb,ilog2(maxposit),4);
  112880. rangebits=ilog2(maxposit);
  112881. for(j=0,k=0;j<info->partitions;j++){
  112882. count+=info->class_dim[info->partitionclass[j]];
  112883. for(;k<count;k++)
  112884. oggpack_write(opb,info->postlist[k+2],rangebits);
  112885. }
  112886. }
  112887. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112888. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112889. int j,k,count=0,maxclass=-1,rangebits;
  112890. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  112891. /* read partitions */
  112892. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  112893. for(j=0;j<info->partitions;j++){
  112894. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  112895. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  112896. }
  112897. /* read partition classes */
  112898. for(j=0;j<maxclass+1;j++){
  112899. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  112900. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  112901. if(info->class_subs[j]<0)
  112902. goto err_out;
  112903. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  112904. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  112905. goto err_out;
  112906. for(k=0;k<(1<<info->class_subs[j]);k++){
  112907. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  112908. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  112909. goto err_out;
  112910. }
  112911. }
  112912. /* read the post list */
  112913. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  112914. rangebits=oggpack_read(opb,4);
  112915. for(j=0,k=0;j<info->partitions;j++){
  112916. count+=info->class_dim[info->partitionclass[j]];
  112917. for(;k<count;k++){
  112918. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  112919. if(t<0 || t>=(1<<rangebits))
  112920. goto err_out;
  112921. }
  112922. }
  112923. info->postlist[0]=0;
  112924. info->postlist[1]=1<<rangebits;
  112925. return(info);
  112926. err_out:
  112927. floor1_free_info(info);
  112928. return(NULL);
  112929. }
  112930. static int icomp(const void *a,const void *b){
  112931. return(**(int **)a-**(int **)b);
  112932. }
  112933. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  112934. vorbis_info_floor *in){
  112935. int *sortpointer[VIF_POSIT+2];
  112936. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  112937. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  112938. int i,j,n=0;
  112939. look->vi=info;
  112940. look->n=info->postlist[1];
  112941. /* we drop each position value in-between already decoded values,
  112942. and use linear interpolation to predict each new value past the
  112943. edges. The positions are read in the order of the position
  112944. list... we precompute the bounding positions in the lookup. Of
  112945. course, the neighbors can change (if a position is declined), but
  112946. this is an initial mapping */
  112947. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  112948. n+=2;
  112949. look->posts=n;
  112950. /* also store a sorted position index */
  112951. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  112952. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  112953. /* points from sort order back to range number */
  112954. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  112955. /* points from range order to sorted position */
  112956. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  112957. /* we actually need the post values too */
  112958. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  112959. /* quantize values to multiplier spec */
  112960. switch(info->mult){
  112961. case 1: /* 1024 -> 256 */
  112962. look->quant_q=256;
  112963. break;
  112964. case 2: /* 1024 -> 128 */
  112965. look->quant_q=128;
  112966. break;
  112967. case 3: /* 1024 -> 86 */
  112968. look->quant_q=86;
  112969. break;
  112970. case 4: /* 1024 -> 64 */
  112971. look->quant_q=64;
  112972. break;
  112973. }
  112974. /* discover our neighbors for decode where we don't use fit flags
  112975. (that would push the neighbors outward) */
  112976. for(i=0;i<n-2;i++){
  112977. int lo=0;
  112978. int hi=1;
  112979. int lx=0;
  112980. int hx=look->n;
  112981. int currentx=info->postlist[i+2];
  112982. for(j=0;j<i+2;j++){
  112983. int x=info->postlist[j];
  112984. if(x>lx && x<currentx){
  112985. lo=j;
  112986. lx=x;
  112987. }
  112988. if(x<hx && x>currentx){
  112989. hi=j;
  112990. hx=x;
  112991. }
  112992. }
  112993. look->loneighbor[i]=lo;
  112994. look->hineighbor[i]=hi;
  112995. }
  112996. return(look);
  112997. }
  112998. static int render_point(int x0,int x1,int y0,int y1,int x){
  112999. y0&=0x7fff; /* mask off flag */
  113000. y1&=0x7fff;
  113001. {
  113002. int dy=y1-y0;
  113003. int adx=x1-x0;
  113004. int ady=abs(dy);
  113005. int err=ady*(x-x0);
  113006. int off=err/adx;
  113007. if(dy<0)return(y0-off);
  113008. return(y0+off);
  113009. }
  113010. }
  113011. static int vorbis_dBquant(const float *x){
  113012. int i= *x*7.3142857f+1023.5f;
  113013. if(i>1023)return(1023);
  113014. if(i<0)return(0);
  113015. return i;
  113016. }
  113017. static float FLOOR1_fromdB_LOOKUP[256]={
  113018. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  113019. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  113020. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  113021. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  113022. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  113023. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  113024. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  113025. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  113026. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  113027. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  113028. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  113029. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  113030. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  113031. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  113032. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  113033. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  113034. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  113035. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  113036. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  113037. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  113038. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  113039. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  113040. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  113041. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  113042. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  113043. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  113044. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  113045. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  113046. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  113047. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  113048. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  113049. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  113050. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  113051. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  113052. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  113053. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  113054. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  113055. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  113056. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  113057. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  113058. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  113059. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  113060. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  113061. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  113062. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  113063. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  113064. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  113065. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  113066. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  113067. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  113068. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  113069. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  113070. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  113071. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  113072. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  113073. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  113074. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  113075. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  113076. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  113077. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  113078. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  113079. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  113080. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  113081. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  113082. };
  113083. static void render_line(int x0,int x1,int y0,int y1,float *d){
  113084. int dy=y1-y0;
  113085. int adx=x1-x0;
  113086. int ady=abs(dy);
  113087. int base=dy/adx;
  113088. int sy=(dy<0?base-1:base+1);
  113089. int x=x0;
  113090. int y=y0;
  113091. int err=0;
  113092. ady-=abs(base*adx);
  113093. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  113094. while(++x<x1){
  113095. err=err+ady;
  113096. if(err>=adx){
  113097. err-=adx;
  113098. y+=sy;
  113099. }else{
  113100. y+=base;
  113101. }
  113102. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  113103. }
  113104. }
  113105. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  113106. int dy=y1-y0;
  113107. int adx=x1-x0;
  113108. int ady=abs(dy);
  113109. int base=dy/adx;
  113110. int sy=(dy<0?base-1:base+1);
  113111. int x=x0;
  113112. int y=y0;
  113113. int err=0;
  113114. ady-=abs(base*adx);
  113115. d[x]=y;
  113116. while(++x<x1){
  113117. err=err+ady;
  113118. if(err>=adx){
  113119. err-=adx;
  113120. y+=sy;
  113121. }else{
  113122. y+=base;
  113123. }
  113124. d[x]=y;
  113125. }
  113126. }
  113127. /* the floor has already been filtered to only include relevant sections */
  113128. static int accumulate_fit(const float *flr,const float *mdct,
  113129. int x0, int x1,lsfit_acc *a,
  113130. int n,vorbis_info_floor1 *info){
  113131. long i;
  113132. 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;
  113133. memset(a,0,sizeof(*a));
  113134. a->x0=x0;
  113135. a->x1=x1;
  113136. if(x1>=n)x1=n-1;
  113137. for(i=x0;i<=x1;i++){
  113138. int quantized=vorbis_dBquant(flr+i);
  113139. if(quantized){
  113140. if(mdct[i]+info->twofitatten>=flr[i]){
  113141. xa += i;
  113142. ya += quantized;
  113143. x2a += i*i;
  113144. y2a += quantized*quantized;
  113145. xya += i*quantized;
  113146. na++;
  113147. }else{
  113148. xb += i;
  113149. yb += quantized;
  113150. x2b += i*i;
  113151. y2b += quantized*quantized;
  113152. xyb += i*quantized;
  113153. nb++;
  113154. }
  113155. }
  113156. }
  113157. xb+=xa;
  113158. yb+=ya;
  113159. x2b+=x2a;
  113160. y2b+=y2a;
  113161. xyb+=xya;
  113162. nb+=na;
  113163. /* weight toward the actually used frequencies if we meet the threshhold */
  113164. {
  113165. int weight=nb*info->twofitweight/(na+1);
  113166. a->xa=xa*weight+xb;
  113167. a->ya=ya*weight+yb;
  113168. a->x2a=x2a*weight+x2b;
  113169. a->y2a=y2a*weight+y2b;
  113170. a->xya=xya*weight+xyb;
  113171. a->an=na*weight+nb;
  113172. }
  113173. return(na);
  113174. }
  113175. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  113176. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  113177. long x0=a[0].x0;
  113178. long x1=a[fits-1].x1;
  113179. for(i=0;i<fits;i++){
  113180. x+=a[i].xa;
  113181. y+=a[i].ya;
  113182. x2+=a[i].x2a;
  113183. y2+=a[i].y2a;
  113184. xy+=a[i].xya;
  113185. an+=a[i].an;
  113186. }
  113187. if(*y0>=0){
  113188. x+= x0;
  113189. y+= *y0;
  113190. x2+= x0 * x0;
  113191. y2+= *y0 * *y0;
  113192. xy+= *y0 * x0;
  113193. an++;
  113194. }
  113195. if(*y1>=0){
  113196. x+= x1;
  113197. y+= *y1;
  113198. x2+= x1 * x1;
  113199. y2+= *y1 * *y1;
  113200. xy+= *y1 * x1;
  113201. an++;
  113202. }
  113203. if(an){
  113204. /* need 64 bit multiplies, which C doesn't give portably as int */
  113205. double fx=x;
  113206. double fy=y;
  113207. double fx2=x2;
  113208. double fxy=xy;
  113209. double denom=1./(an*fx2-fx*fx);
  113210. double a=(fy*fx2-fxy*fx)*denom;
  113211. double b=(an*fxy-fx*fy)*denom;
  113212. *y0=rint(a+b*x0);
  113213. *y1=rint(a+b*x1);
  113214. /* limit to our range! */
  113215. if(*y0>1023)*y0=1023;
  113216. if(*y1>1023)*y1=1023;
  113217. if(*y0<0)*y0=0;
  113218. if(*y1<0)*y1=0;
  113219. }else{
  113220. *y0=0;
  113221. *y1=0;
  113222. }
  113223. }
  113224. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  113225. long y=0;
  113226. int i;
  113227. for(i=0;i<fits && y==0;i++)
  113228. y+=a[i].ya;
  113229. *y0=*y1=y;
  113230. }*/
  113231. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  113232. const float *mdct,
  113233. vorbis_info_floor1 *info){
  113234. int dy=y1-y0;
  113235. int adx=x1-x0;
  113236. int ady=abs(dy);
  113237. int base=dy/adx;
  113238. int sy=(dy<0?base-1:base+1);
  113239. int x=x0;
  113240. int y=y0;
  113241. int err=0;
  113242. int val=vorbis_dBquant(mask+x);
  113243. int mse=0;
  113244. int n=0;
  113245. ady-=abs(base*adx);
  113246. mse=(y-val);
  113247. mse*=mse;
  113248. n++;
  113249. if(mdct[x]+info->twofitatten>=mask[x]){
  113250. if(y+info->maxover<val)return(1);
  113251. if(y-info->maxunder>val)return(1);
  113252. }
  113253. while(++x<x1){
  113254. err=err+ady;
  113255. if(err>=adx){
  113256. err-=adx;
  113257. y+=sy;
  113258. }else{
  113259. y+=base;
  113260. }
  113261. val=vorbis_dBquant(mask+x);
  113262. mse+=((y-val)*(y-val));
  113263. n++;
  113264. if(mdct[x]+info->twofitatten>=mask[x]){
  113265. if(val){
  113266. if(y+info->maxover<val)return(1);
  113267. if(y-info->maxunder>val)return(1);
  113268. }
  113269. }
  113270. }
  113271. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  113272. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  113273. if(mse/n>info->maxerr)return(1);
  113274. return(0);
  113275. }
  113276. static int post_Y(int *A,int *B,int pos){
  113277. if(A[pos]<0)
  113278. return B[pos];
  113279. if(B[pos]<0)
  113280. return A[pos];
  113281. return (A[pos]+B[pos])>>1;
  113282. }
  113283. int *floor1_fit(vorbis_block *vb,void *look_,
  113284. const float *logmdct, /* in */
  113285. const float *logmask){
  113286. long i,j;
  113287. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  113288. vorbis_info_floor1 *info=look->vi;
  113289. long n=look->n;
  113290. long posts=look->posts;
  113291. long nonzero=0;
  113292. lsfit_acc fits[VIF_POSIT+1];
  113293. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  113294. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  113295. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  113296. int hineighbor[VIF_POSIT+2];
  113297. int *output=NULL;
  113298. int memo[VIF_POSIT+2];
  113299. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  113300. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  113301. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  113302. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  113303. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  113304. /* quantize the relevant floor points and collect them into line fit
  113305. structures (one per minimal division) at the same time */
  113306. if(posts==0){
  113307. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  113308. }else{
  113309. for(i=0;i<posts-1;i++)
  113310. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  113311. look->sorted_index[i+1],fits+i,
  113312. n,info);
  113313. }
  113314. if(nonzero){
  113315. /* start by fitting the implicit base case.... */
  113316. int y0=-200;
  113317. int y1=-200;
  113318. fit_line(fits,posts-1,&y0,&y1);
  113319. fit_valueA[0]=y0;
  113320. fit_valueB[0]=y0;
  113321. fit_valueB[1]=y1;
  113322. fit_valueA[1]=y1;
  113323. /* Non degenerate case */
  113324. /* start progressive splitting. This is a greedy, non-optimal
  113325. algorithm, but simple and close enough to the best
  113326. answer. */
  113327. for(i=2;i<posts;i++){
  113328. int sortpos=look->reverse_index[i];
  113329. int ln=loneighbor[sortpos];
  113330. int hn=hineighbor[sortpos];
  113331. /* eliminate repeat searches of a particular range with a memo */
  113332. if(memo[ln]!=hn){
  113333. /* haven't performed this error search yet */
  113334. int lsortpos=look->reverse_index[ln];
  113335. int hsortpos=look->reverse_index[hn];
  113336. memo[ln]=hn;
  113337. {
  113338. /* A note: we want to bound/minimize *local*, not global, error */
  113339. int lx=info->postlist[ln];
  113340. int hx=info->postlist[hn];
  113341. int ly=post_Y(fit_valueA,fit_valueB,ln);
  113342. int hy=post_Y(fit_valueA,fit_valueB,hn);
  113343. if(ly==-1 || hy==-1){
  113344. exit(1);
  113345. }
  113346. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  113347. /* outside error bounds/begin search area. Split it. */
  113348. int ly0=-200;
  113349. int ly1=-200;
  113350. int hy0=-200;
  113351. int hy1=-200;
  113352. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  113353. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  113354. /* store new edge values */
  113355. fit_valueB[ln]=ly0;
  113356. if(ln==0)fit_valueA[ln]=ly0;
  113357. fit_valueA[i]=ly1;
  113358. fit_valueB[i]=hy0;
  113359. fit_valueA[hn]=hy1;
  113360. if(hn==1)fit_valueB[hn]=hy1;
  113361. if(ly1>=0 || hy0>=0){
  113362. /* store new neighbor values */
  113363. for(j=sortpos-1;j>=0;j--)
  113364. if(hineighbor[j]==hn)
  113365. hineighbor[j]=i;
  113366. else
  113367. break;
  113368. for(j=sortpos+1;j<posts;j++)
  113369. if(loneighbor[j]==ln)
  113370. loneighbor[j]=i;
  113371. else
  113372. break;
  113373. }
  113374. }else{
  113375. fit_valueA[i]=-200;
  113376. fit_valueB[i]=-200;
  113377. }
  113378. }
  113379. }
  113380. }
  113381. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113382. output[0]=post_Y(fit_valueA,fit_valueB,0);
  113383. output[1]=post_Y(fit_valueA,fit_valueB,1);
  113384. /* fill in posts marked as not using a fit; we will zero
  113385. back out to 'unused' when encoding them so long as curve
  113386. interpolation doesn't force them into use */
  113387. for(i=2;i<posts;i++){
  113388. int ln=look->loneighbor[i-2];
  113389. int hn=look->hineighbor[i-2];
  113390. int x0=info->postlist[ln];
  113391. int x1=info->postlist[hn];
  113392. int y0=output[ln];
  113393. int y1=output[hn];
  113394. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113395. int vx=post_Y(fit_valueA,fit_valueB,i);
  113396. if(vx>=0 && predicted!=vx){
  113397. output[i]=vx;
  113398. }else{
  113399. output[i]= predicted|0x8000;
  113400. }
  113401. }
  113402. }
  113403. return(output);
  113404. }
  113405. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  113406. int *A,int *B,
  113407. int del){
  113408. long i;
  113409. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  113410. long posts=look->posts;
  113411. int *output=NULL;
  113412. if(A && B){
  113413. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113414. for(i=0;i<posts;i++){
  113415. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  113416. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  113417. }
  113418. }
  113419. return(output);
  113420. }
  113421. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  113422. void*look_,
  113423. int *post,int *ilogmask){
  113424. long i,j;
  113425. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  113426. vorbis_info_floor1 *info=look->vi;
  113427. long posts=look->posts;
  113428. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113429. int out[VIF_POSIT+2];
  113430. static_codebook **sbooks=ci->book_param;
  113431. codebook *books=ci->fullbooks;
  113432. static long seq=0;
  113433. /* quantize values to multiplier spec */
  113434. if(post){
  113435. for(i=0;i<posts;i++){
  113436. int val=post[i]&0x7fff;
  113437. switch(info->mult){
  113438. case 1: /* 1024 -> 256 */
  113439. val>>=2;
  113440. break;
  113441. case 2: /* 1024 -> 128 */
  113442. val>>=3;
  113443. break;
  113444. case 3: /* 1024 -> 86 */
  113445. val/=12;
  113446. break;
  113447. case 4: /* 1024 -> 64 */
  113448. val>>=4;
  113449. break;
  113450. }
  113451. post[i]=val | (post[i]&0x8000);
  113452. }
  113453. out[0]=post[0];
  113454. out[1]=post[1];
  113455. /* find prediction values for each post and subtract them */
  113456. for(i=2;i<posts;i++){
  113457. int ln=look->loneighbor[i-2];
  113458. int hn=look->hineighbor[i-2];
  113459. int x0=info->postlist[ln];
  113460. int x1=info->postlist[hn];
  113461. int y0=post[ln];
  113462. int y1=post[hn];
  113463. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113464. if((post[i]&0x8000) || (predicted==post[i])){
  113465. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  113466. in interpolation */
  113467. out[i]=0;
  113468. }else{
  113469. int headroom=(look->quant_q-predicted<predicted?
  113470. look->quant_q-predicted:predicted);
  113471. int val=post[i]-predicted;
  113472. /* at this point the 'deviation' value is in the range +/- max
  113473. range, but the real, unique range can always be mapped to
  113474. only [0-maxrange). So we want to wrap the deviation into
  113475. this limited range, but do it in the way that least screws
  113476. an essentially gaussian probability distribution. */
  113477. if(val<0)
  113478. if(val<-headroom)
  113479. val=headroom-val-1;
  113480. else
  113481. val=-1-(val<<1);
  113482. else
  113483. if(val>=headroom)
  113484. val= val+headroom;
  113485. else
  113486. val<<=1;
  113487. out[i]=val;
  113488. post[ln]&=0x7fff;
  113489. post[hn]&=0x7fff;
  113490. }
  113491. }
  113492. /* we have everything we need. pack it out */
  113493. /* mark nontrivial floor */
  113494. oggpack_write(opb,1,1);
  113495. /* beginning/end post */
  113496. look->frames++;
  113497. look->postbits+=ilog(look->quant_q-1)*2;
  113498. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  113499. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  113500. /* partition by partition */
  113501. for(i=0,j=2;i<info->partitions;i++){
  113502. int classx=info->partitionclass[i];
  113503. int cdim=info->class_dim[classx];
  113504. int csubbits=info->class_subs[classx];
  113505. int csub=1<<csubbits;
  113506. int bookas[8]={0,0,0,0,0,0,0,0};
  113507. int cval=0;
  113508. int cshift=0;
  113509. int k,l;
  113510. /* generate the partition's first stage cascade value */
  113511. if(csubbits){
  113512. int maxval[8];
  113513. for(k=0;k<csub;k++){
  113514. int booknum=info->class_subbook[classx][k];
  113515. if(booknum<0){
  113516. maxval[k]=1;
  113517. }else{
  113518. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  113519. }
  113520. }
  113521. for(k=0;k<cdim;k++){
  113522. for(l=0;l<csub;l++){
  113523. int val=out[j+k];
  113524. if(val<maxval[l]){
  113525. bookas[k]=l;
  113526. break;
  113527. }
  113528. }
  113529. cval|= bookas[k]<<cshift;
  113530. cshift+=csubbits;
  113531. }
  113532. /* write it */
  113533. look->phrasebits+=
  113534. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  113535. #ifdef TRAIN_FLOOR1
  113536. {
  113537. FILE *of;
  113538. char buffer[80];
  113539. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  113540. vb->pcmend/2,posts-2,class);
  113541. of=fopen(buffer,"a");
  113542. fprintf(of,"%d\n",cval);
  113543. fclose(of);
  113544. }
  113545. #endif
  113546. }
  113547. /* write post values */
  113548. for(k=0;k<cdim;k++){
  113549. int book=info->class_subbook[classx][bookas[k]];
  113550. if(book>=0){
  113551. /* hack to allow training with 'bad' books */
  113552. if(out[j+k]<(books+book)->entries)
  113553. look->postbits+=vorbis_book_encode(books+book,
  113554. out[j+k],opb);
  113555. /*else
  113556. fprintf(stderr,"+!");*/
  113557. #ifdef TRAIN_FLOOR1
  113558. {
  113559. FILE *of;
  113560. char buffer[80];
  113561. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  113562. vb->pcmend/2,posts-2,class,bookas[k]);
  113563. of=fopen(buffer,"a");
  113564. fprintf(of,"%d\n",out[j+k]);
  113565. fclose(of);
  113566. }
  113567. #endif
  113568. }
  113569. }
  113570. j+=cdim;
  113571. }
  113572. {
  113573. /* generate quantized floor equivalent to what we'd unpack in decode */
  113574. /* render the lines */
  113575. int hx=0;
  113576. int lx=0;
  113577. int ly=post[0]*info->mult;
  113578. for(j=1;j<look->posts;j++){
  113579. int current=look->forward_index[j];
  113580. int hy=post[current]&0x7fff;
  113581. if(hy==post[current]){
  113582. hy*=info->mult;
  113583. hx=info->postlist[current];
  113584. render_line0(lx,hx,ly,hy,ilogmask);
  113585. lx=hx;
  113586. ly=hy;
  113587. }
  113588. }
  113589. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  113590. seq++;
  113591. return(1);
  113592. }
  113593. }else{
  113594. oggpack_write(opb,0,1);
  113595. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  113596. seq++;
  113597. return(0);
  113598. }
  113599. }
  113600. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  113601. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113602. vorbis_info_floor1 *info=look->vi;
  113603. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113604. int i,j,k;
  113605. codebook *books=ci->fullbooks;
  113606. /* unpack wrapped/predicted values from stream */
  113607. if(oggpack_read(&vb->opb,1)==1){
  113608. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  113609. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113610. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113611. /* partition by partition */
  113612. for(i=0,j=2;i<info->partitions;i++){
  113613. int classx=info->partitionclass[i];
  113614. int cdim=info->class_dim[classx];
  113615. int csubbits=info->class_subs[classx];
  113616. int csub=1<<csubbits;
  113617. int cval=0;
  113618. /* decode the partition's first stage cascade value */
  113619. if(csubbits){
  113620. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  113621. if(cval==-1)goto eop;
  113622. }
  113623. for(k=0;k<cdim;k++){
  113624. int book=info->class_subbook[classx][cval&(csub-1)];
  113625. cval>>=csubbits;
  113626. if(book>=0){
  113627. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  113628. goto eop;
  113629. }else{
  113630. fit_value[j+k]=0;
  113631. }
  113632. }
  113633. j+=cdim;
  113634. }
  113635. /* unwrap positive values and reconsitute via linear interpolation */
  113636. for(i=2;i<look->posts;i++){
  113637. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  113638. info->postlist[look->hineighbor[i-2]],
  113639. fit_value[look->loneighbor[i-2]],
  113640. fit_value[look->hineighbor[i-2]],
  113641. info->postlist[i]);
  113642. int hiroom=look->quant_q-predicted;
  113643. int loroom=predicted;
  113644. int room=(hiroom<loroom?hiroom:loroom)<<1;
  113645. int val=fit_value[i];
  113646. if(val){
  113647. if(val>=room){
  113648. if(hiroom>loroom){
  113649. val = val-loroom;
  113650. }else{
  113651. val = -1-(val-hiroom);
  113652. }
  113653. }else{
  113654. if(val&1){
  113655. val= -((val+1)>>1);
  113656. }else{
  113657. val>>=1;
  113658. }
  113659. }
  113660. fit_value[i]=val+predicted;
  113661. fit_value[look->loneighbor[i-2]]&=0x7fff;
  113662. fit_value[look->hineighbor[i-2]]&=0x7fff;
  113663. }else{
  113664. fit_value[i]=predicted|0x8000;
  113665. }
  113666. }
  113667. return(fit_value);
  113668. }
  113669. eop:
  113670. return(NULL);
  113671. }
  113672. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  113673. float *out){
  113674. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113675. vorbis_info_floor1 *info=look->vi;
  113676. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113677. int n=ci->blocksizes[vb->W]/2;
  113678. int j;
  113679. if(memo){
  113680. /* render the lines */
  113681. int *fit_value=(int *)memo;
  113682. int hx=0;
  113683. int lx=0;
  113684. int ly=fit_value[0]*info->mult;
  113685. for(j=1;j<look->posts;j++){
  113686. int current=look->forward_index[j];
  113687. int hy=fit_value[current]&0x7fff;
  113688. if(hy==fit_value[current]){
  113689. hy*=info->mult;
  113690. hx=info->postlist[current];
  113691. render_line(lx,hx,ly,hy,out);
  113692. lx=hx;
  113693. ly=hy;
  113694. }
  113695. }
  113696. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  113697. return(1);
  113698. }
  113699. memset(out,0,sizeof(*out)*n);
  113700. return(0);
  113701. }
  113702. /* export hooks */
  113703. vorbis_func_floor floor1_exportbundle={
  113704. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  113705. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  113706. };
  113707. #endif
  113708. /*** End of inlined file: floor1.c ***/
  113709. /*** Start of inlined file: info.c ***/
  113710. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113711. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113712. // tasks..
  113713. #if JUCE_MSVC
  113714. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113715. #endif
  113716. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113717. #if JUCE_USE_OGGVORBIS
  113718. /* general handling of the header and the vorbis_info structure (and
  113719. substructures) */
  113720. #include <stdlib.h>
  113721. #include <string.h>
  113722. #include <ctype.h>
  113723. static void _v_writestring(oggpack_buffer *o, const char *s, int bytes){
  113724. while(bytes--){
  113725. oggpack_write(o,*s++,8);
  113726. }
  113727. }
  113728. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  113729. while(bytes--){
  113730. *buf++=oggpack_read(o,8);
  113731. }
  113732. }
  113733. void vorbis_comment_init(vorbis_comment *vc){
  113734. memset(vc,0,sizeof(*vc));
  113735. }
  113736. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  113737. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  113738. (vc->comments+2)*sizeof(*vc->user_comments));
  113739. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  113740. (vc->comments+2)*sizeof(*vc->comment_lengths));
  113741. vc->comment_lengths[vc->comments]=strlen(comment);
  113742. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  113743. strcpy(vc->user_comments[vc->comments], comment);
  113744. vc->comments++;
  113745. vc->user_comments[vc->comments]=NULL;
  113746. }
  113747. void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, char *contents){
  113748. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  113749. strcpy(comment, tag);
  113750. strcat(comment, "=");
  113751. strcat(comment, contents);
  113752. vorbis_comment_add(vc, comment);
  113753. }
  113754. /* This is more or less the same as strncasecmp - but that doesn't exist
  113755. * everywhere, and this is a fairly trivial function, so we include it */
  113756. static int tagcompare(const char *s1, const char *s2, int n){
  113757. int c=0;
  113758. while(c < n){
  113759. if(toupper(s1[c]) != toupper(s2[c]))
  113760. return !0;
  113761. c++;
  113762. }
  113763. return 0;
  113764. }
  113765. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  113766. long i;
  113767. int found = 0;
  113768. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113769. char *fulltag = (char*)alloca(taglen+ 1);
  113770. strcpy(fulltag, tag);
  113771. strcat(fulltag, "=");
  113772. for(i=0;i<vc->comments;i++){
  113773. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  113774. if(count == found)
  113775. /* We return a pointer to the data, not a copy */
  113776. return vc->user_comments[i] + taglen;
  113777. else
  113778. found++;
  113779. }
  113780. }
  113781. return NULL; /* didn't find anything */
  113782. }
  113783. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  113784. int i,count=0;
  113785. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113786. char *fulltag = (char*)alloca(taglen+1);
  113787. strcpy(fulltag,tag);
  113788. strcat(fulltag, "=");
  113789. for(i=0;i<vc->comments;i++){
  113790. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  113791. count++;
  113792. }
  113793. return count;
  113794. }
  113795. void vorbis_comment_clear(vorbis_comment *vc){
  113796. if(vc){
  113797. long i;
  113798. for(i=0;i<vc->comments;i++)
  113799. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  113800. if(vc->user_comments)_ogg_free(vc->user_comments);
  113801. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  113802. if(vc->vendor)_ogg_free(vc->vendor);
  113803. }
  113804. memset(vc,0,sizeof(*vc));
  113805. }
  113806. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  113807. They may be equal, but short will never ge greater than long */
  113808. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  113809. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  113810. return ci ? ci->blocksizes[zo] : -1;
  113811. }
  113812. /* used by synthesis, which has a full, alloced vi */
  113813. void vorbis_info_init(vorbis_info *vi){
  113814. memset(vi,0,sizeof(*vi));
  113815. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  113816. }
  113817. void vorbis_info_clear(vorbis_info *vi){
  113818. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113819. int i;
  113820. if(ci){
  113821. for(i=0;i<ci->modes;i++)
  113822. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  113823. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  113824. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  113825. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  113826. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  113827. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  113828. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  113829. for(i=0;i<ci->books;i++){
  113830. if(ci->book_param[i]){
  113831. /* knows if the book was not alloced */
  113832. vorbis_staticbook_destroy(ci->book_param[i]);
  113833. }
  113834. if(ci->fullbooks)
  113835. vorbis_book_clear(ci->fullbooks+i);
  113836. }
  113837. if(ci->fullbooks)
  113838. _ogg_free(ci->fullbooks);
  113839. for(i=0;i<ci->psys;i++)
  113840. _vi_psy_free(ci->psy_param[i]);
  113841. _ogg_free(ci);
  113842. }
  113843. memset(vi,0,sizeof(*vi));
  113844. }
  113845. /* Header packing/unpacking ********************************************/
  113846. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  113847. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113848. if(!ci)return(OV_EFAULT);
  113849. vi->version=oggpack_read(opb,32);
  113850. if(vi->version!=0)return(OV_EVERSION);
  113851. vi->channels=oggpack_read(opb,8);
  113852. vi->rate=oggpack_read(opb,32);
  113853. vi->bitrate_upper=oggpack_read(opb,32);
  113854. vi->bitrate_nominal=oggpack_read(opb,32);
  113855. vi->bitrate_lower=oggpack_read(opb,32);
  113856. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  113857. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  113858. if(vi->rate<1)goto err_out;
  113859. if(vi->channels<1)goto err_out;
  113860. if(ci->blocksizes[0]<8)goto err_out;
  113861. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  113862. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  113863. return(0);
  113864. err_out:
  113865. vorbis_info_clear(vi);
  113866. return(OV_EBADHEADER);
  113867. }
  113868. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  113869. int i;
  113870. int vendorlen=oggpack_read(opb,32);
  113871. if(vendorlen<0)goto err_out;
  113872. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  113873. _v_readstring(opb,vc->vendor,vendorlen);
  113874. vc->comments=oggpack_read(opb,32);
  113875. if(vc->comments<0)goto err_out;
  113876. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  113877. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  113878. for(i=0;i<vc->comments;i++){
  113879. int len=oggpack_read(opb,32);
  113880. if(len<0)goto err_out;
  113881. vc->comment_lengths[i]=len;
  113882. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  113883. _v_readstring(opb,vc->user_comments[i],len);
  113884. }
  113885. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  113886. return(0);
  113887. err_out:
  113888. vorbis_comment_clear(vc);
  113889. return(OV_EBADHEADER);
  113890. }
  113891. /* all of the real encoding details are here. The modes, books,
  113892. everything */
  113893. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  113894. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113895. int i;
  113896. if(!ci)return(OV_EFAULT);
  113897. /* codebooks */
  113898. ci->books=oggpack_read(opb,8)+1;
  113899. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  113900. for(i=0;i<ci->books;i++){
  113901. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  113902. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  113903. }
  113904. /* time backend settings; hooks are unused */
  113905. {
  113906. int times=oggpack_read(opb,6)+1;
  113907. for(i=0;i<times;i++){
  113908. int test=oggpack_read(opb,16);
  113909. if(test<0 || test>=VI_TIMEB)goto err_out;
  113910. }
  113911. }
  113912. /* floor backend settings */
  113913. ci->floors=oggpack_read(opb,6)+1;
  113914. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  113915. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  113916. for(i=0;i<ci->floors;i++){
  113917. ci->floor_type[i]=oggpack_read(opb,16);
  113918. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  113919. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  113920. if(!ci->floor_param[i])goto err_out;
  113921. }
  113922. /* residue backend settings */
  113923. ci->residues=oggpack_read(opb,6)+1;
  113924. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  113925. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  113926. for(i=0;i<ci->residues;i++){
  113927. ci->residue_type[i]=oggpack_read(opb,16);
  113928. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  113929. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  113930. if(!ci->residue_param[i])goto err_out;
  113931. }
  113932. /* map backend settings */
  113933. ci->maps=oggpack_read(opb,6)+1;
  113934. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  113935. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  113936. for(i=0;i<ci->maps;i++){
  113937. ci->map_type[i]=oggpack_read(opb,16);
  113938. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  113939. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  113940. if(!ci->map_param[i])goto err_out;
  113941. }
  113942. /* mode settings */
  113943. ci->modes=oggpack_read(opb,6)+1;
  113944. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  113945. for(i=0;i<ci->modes;i++){
  113946. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  113947. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  113948. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  113949. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  113950. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  113951. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  113952. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  113953. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  113954. }
  113955. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  113956. return(0);
  113957. err_out:
  113958. vorbis_info_clear(vi);
  113959. return(OV_EBADHEADER);
  113960. }
  113961. /* The Vorbis header is in three packets; the initial small packet in
  113962. the first page that identifies basic parameters, a second packet
  113963. with bitstream comments and a third packet that holds the
  113964. codebook. */
  113965. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  113966. oggpack_buffer opb;
  113967. if(op){
  113968. oggpack_readinit(&opb,op->packet,op->bytes);
  113969. /* Which of the three types of header is this? */
  113970. /* Also verify header-ness, vorbis */
  113971. {
  113972. char buffer[6];
  113973. int packtype=oggpack_read(&opb,8);
  113974. memset(buffer,0,6);
  113975. _v_readstring(&opb,buffer,6);
  113976. if(memcmp(buffer,"vorbis",6)){
  113977. /* not a vorbis header */
  113978. return(OV_ENOTVORBIS);
  113979. }
  113980. switch(packtype){
  113981. case 0x01: /* least significant *bit* is read first */
  113982. if(!op->b_o_s){
  113983. /* Not the initial packet */
  113984. return(OV_EBADHEADER);
  113985. }
  113986. if(vi->rate!=0){
  113987. /* previously initialized info header */
  113988. return(OV_EBADHEADER);
  113989. }
  113990. return(_vorbis_unpack_info(vi,&opb));
  113991. case 0x03: /* least significant *bit* is read first */
  113992. if(vi->rate==0){
  113993. /* um... we didn't get the initial header */
  113994. return(OV_EBADHEADER);
  113995. }
  113996. return(_vorbis_unpack_comment(vc,&opb));
  113997. case 0x05: /* least significant *bit* is read first */
  113998. if(vi->rate==0 || vc->vendor==NULL){
  113999. /* um... we didn;t get the initial header or comments yet */
  114000. return(OV_EBADHEADER);
  114001. }
  114002. return(_vorbis_unpack_books(vi,&opb));
  114003. default:
  114004. /* Not a valid vorbis header type */
  114005. return(OV_EBADHEADER);
  114006. break;
  114007. }
  114008. }
  114009. }
  114010. return(OV_EBADHEADER);
  114011. }
  114012. /* pack side **********************************************************/
  114013. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  114014. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114015. if(!ci)return(OV_EFAULT);
  114016. /* preamble */
  114017. oggpack_write(opb,0x01,8);
  114018. _v_writestring(opb,"vorbis", 6);
  114019. /* basic information about the stream */
  114020. oggpack_write(opb,0x00,32);
  114021. oggpack_write(opb,vi->channels,8);
  114022. oggpack_write(opb,vi->rate,32);
  114023. oggpack_write(opb,vi->bitrate_upper,32);
  114024. oggpack_write(opb,vi->bitrate_nominal,32);
  114025. oggpack_write(opb,vi->bitrate_lower,32);
  114026. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  114027. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  114028. oggpack_write(opb,1,1);
  114029. return(0);
  114030. }
  114031. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  114032. char temp[]="Xiph.Org libVorbis I 20050304";
  114033. int bytes = strlen(temp);
  114034. /* preamble */
  114035. oggpack_write(opb,0x03,8);
  114036. _v_writestring(opb,"vorbis", 6);
  114037. /* vendor */
  114038. oggpack_write(opb,bytes,32);
  114039. _v_writestring(opb,temp, bytes);
  114040. /* comments */
  114041. oggpack_write(opb,vc->comments,32);
  114042. if(vc->comments){
  114043. int i;
  114044. for(i=0;i<vc->comments;i++){
  114045. if(vc->user_comments[i]){
  114046. oggpack_write(opb,vc->comment_lengths[i],32);
  114047. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  114048. }else{
  114049. oggpack_write(opb,0,32);
  114050. }
  114051. }
  114052. }
  114053. oggpack_write(opb,1,1);
  114054. return(0);
  114055. }
  114056. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  114057. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114058. int i;
  114059. if(!ci)return(OV_EFAULT);
  114060. oggpack_write(opb,0x05,8);
  114061. _v_writestring(opb,"vorbis", 6);
  114062. /* books */
  114063. oggpack_write(opb,ci->books-1,8);
  114064. for(i=0;i<ci->books;i++)
  114065. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  114066. /* times; hook placeholders */
  114067. oggpack_write(opb,0,6);
  114068. oggpack_write(opb,0,16);
  114069. /* floors */
  114070. oggpack_write(opb,ci->floors-1,6);
  114071. for(i=0;i<ci->floors;i++){
  114072. oggpack_write(opb,ci->floor_type[i],16);
  114073. if(_floor_P[ci->floor_type[i]]->pack)
  114074. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  114075. else
  114076. goto err_out;
  114077. }
  114078. /* residues */
  114079. oggpack_write(opb,ci->residues-1,6);
  114080. for(i=0;i<ci->residues;i++){
  114081. oggpack_write(opb,ci->residue_type[i],16);
  114082. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  114083. }
  114084. /* maps */
  114085. oggpack_write(opb,ci->maps-1,6);
  114086. for(i=0;i<ci->maps;i++){
  114087. oggpack_write(opb,ci->map_type[i],16);
  114088. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  114089. }
  114090. /* modes */
  114091. oggpack_write(opb,ci->modes-1,6);
  114092. for(i=0;i<ci->modes;i++){
  114093. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  114094. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  114095. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  114096. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  114097. }
  114098. oggpack_write(opb,1,1);
  114099. return(0);
  114100. err_out:
  114101. return(-1);
  114102. }
  114103. int vorbis_commentheader_out(vorbis_comment *vc,
  114104. ogg_packet *op){
  114105. oggpack_buffer opb;
  114106. oggpack_writeinit(&opb);
  114107. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  114108. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114109. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  114110. op->bytes=oggpack_bytes(&opb);
  114111. op->b_o_s=0;
  114112. op->e_o_s=0;
  114113. op->granulepos=0;
  114114. op->packetno=1;
  114115. return 0;
  114116. }
  114117. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  114118. vorbis_comment *vc,
  114119. ogg_packet *op,
  114120. ogg_packet *op_comm,
  114121. ogg_packet *op_code){
  114122. int ret=OV_EIMPL;
  114123. vorbis_info *vi=v->vi;
  114124. oggpack_buffer opb;
  114125. private_state *b=(private_state*)v->backend_state;
  114126. if(!b){
  114127. ret=OV_EFAULT;
  114128. goto err_out;
  114129. }
  114130. /* first header packet **********************************************/
  114131. oggpack_writeinit(&opb);
  114132. if(_vorbis_pack_info(&opb,vi))goto err_out;
  114133. /* build the packet */
  114134. if(b->header)_ogg_free(b->header);
  114135. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114136. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  114137. op->packet=b->header;
  114138. op->bytes=oggpack_bytes(&opb);
  114139. op->b_o_s=1;
  114140. op->e_o_s=0;
  114141. op->granulepos=0;
  114142. op->packetno=0;
  114143. /* second header packet (comments) **********************************/
  114144. oggpack_reset(&opb);
  114145. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  114146. if(b->header1)_ogg_free(b->header1);
  114147. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114148. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  114149. op_comm->packet=b->header1;
  114150. op_comm->bytes=oggpack_bytes(&opb);
  114151. op_comm->b_o_s=0;
  114152. op_comm->e_o_s=0;
  114153. op_comm->granulepos=0;
  114154. op_comm->packetno=1;
  114155. /* third header packet (modes/codebooks) ****************************/
  114156. oggpack_reset(&opb);
  114157. if(_vorbis_pack_books(&opb,vi))goto err_out;
  114158. if(b->header2)_ogg_free(b->header2);
  114159. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114160. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  114161. op_code->packet=b->header2;
  114162. op_code->bytes=oggpack_bytes(&opb);
  114163. op_code->b_o_s=0;
  114164. op_code->e_o_s=0;
  114165. op_code->granulepos=0;
  114166. op_code->packetno=2;
  114167. oggpack_writeclear(&opb);
  114168. return(0);
  114169. err_out:
  114170. oggpack_writeclear(&opb);
  114171. memset(op,0,sizeof(*op));
  114172. memset(op_comm,0,sizeof(*op_comm));
  114173. memset(op_code,0,sizeof(*op_code));
  114174. if(b->header)_ogg_free(b->header);
  114175. if(b->header1)_ogg_free(b->header1);
  114176. if(b->header2)_ogg_free(b->header2);
  114177. b->header=NULL;
  114178. b->header1=NULL;
  114179. b->header2=NULL;
  114180. return(ret);
  114181. }
  114182. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  114183. if(granulepos>=0)
  114184. return((double)granulepos/v->vi->rate);
  114185. return(-1);
  114186. }
  114187. #endif
  114188. /*** End of inlined file: info.c ***/
  114189. /*** Start of inlined file: lpc.c ***/
  114190. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  114191. are derived from code written by Jutta Degener and Carsten Bormann;
  114192. thus we include their copyright below. The entirety of this file
  114193. is freely redistributable on the condition that both of these
  114194. copyright notices are preserved without modification. */
  114195. /* Preserved Copyright: *********************************************/
  114196. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  114197. Technische Universita"t Berlin
  114198. Any use of this software is permitted provided that this notice is not
  114199. removed and that neither the authors nor the Technische Universita"t
  114200. Berlin are deemed to have made any representations as to the
  114201. suitability of this software for any purpose nor are held responsible
  114202. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  114203. THIS SOFTWARE.
  114204. As a matter of courtesy, the authors request to be informed about uses
  114205. this software has found, about bugs in this software, and about any
  114206. improvements that may be of general interest.
  114207. Berlin, 28.11.1994
  114208. Jutta Degener
  114209. Carsten Bormann
  114210. *********************************************************************/
  114211. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114212. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114213. // tasks..
  114214. #if JUCE_MSVC
  114215. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114216. #endif
  114217. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114218. #if JUCE_USE_OGGVORBIS
  114219. #include <stdlib.h>
  114220. #include <string.h>
  114221. #include <math.h>
  114222. /* Autocorrelation LPC coeff generation algorithm invented by
  114223. N. Levinson in 1947, modified by J. Durbin in 1959. */
  114224. /* Input : n elements of time doamin data
  114225. Output: m lpc coefficients, excitation energy */
  114226. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  114227. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  114228. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  114229. double error;
  114230. int i,j;
  114231. /* autocorrelation, p+1 lag coefficients */
  114232. j=m+1;
  114233. while(j--){
  114234. double d=0; /* double needed for accumulator depth */
  114235. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  114236. aut[j]=d;
  114237. }
  114238. /* Generate lpc coefficients from autocorr values */
  114239. error=aut[0];
  114240. for(i=0;i<m;i++){
  114241. double r= -aut[i+1];
  114242. if(error==0){
  114243. memset(lpci,0,m*sizeof(*lpci));
  114244. return 0;
  114245. }
  114246. /* Sum up this iteration's reflection coefficient; note that in
  114247. Vorbis we don't save it. If anyone wants to recycle this code
  114248. and needs reflection coefficients, save the results of 'r' from
  114249. each iteration. */
  114250. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  114251. r/=error;
  114252. /* Update LPC coefficients and total error */
  114253. lpc[i]=r;
  114254. for(j=0;j<i/2;j++){
  114255. double tmp=lpc[j];
  114256. lpc[j]+=r*lpc[i-1-j];
  114257. lpc[i-1-j]+=r*tmp;
  114258. }
  114259. if(i%2)lpc[j]+=lpc[j]*r;
  114260. error*=1.f-r*r;
  114261. }
  114262. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  114263. /* we need the error value to know how big an impulse to hit the
  114264. filter with later */
  114265. return error;
  114266. }
  114267. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  114268. float *data,long n){
  114269. /* in: coeff[0...m-1] LPC coefficients
  114270. prime[0...m-1] initial values (allocated size of n+m-1)
  114271. out: data[0...n-1] data samples */
  114272. long i,j,o,p;
  114273. float y;
  114274. float *work=(float*)alloca(sizeof(*work)*(m+n));
  114275. if(!prime)
  114276. for(i=0;i<m;i++)
  114277. work[i]=0.f;
  114278. else
  114279. for(i=0;i<m;i++)
  114280. work[i]=prime[i];
  114281. for(i=0;i<n;i++){
  114282. y=0;
  114283. o=i;
  114284. p=m;
  114285. for(j=0;j<m;j++)
  114286. y-=work[o++]*coeff[--p];
  114287. data[i]=work[o]=y;
  114288. }
  114289. }
  114290. #endif
  114291. /*** End of inlined file: lpc.c ***/
  114292. /*** Start of inlined file: lsp.c ***/
  114293. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  114294. an iterative root polisher (CACM algorithm 283). It *is* possible
  114295. to confuse this algorithm into not converging; that should only
  114296. happen with absurdly closely spaced roots (very sharp peaks in the
  114297. LPC f response) which in turn should be impossible in our use of
  114298. the code. If this *does* happen anyway, it's a bug in the floor
  114299. finder; find the cause of the confusion (probably a single bin
  114300. spike or accidental near-float-limit resolution problems) and
  114301. correct it. */
  114302. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114303. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114304. // tasks..
  114305. #if JUCE_MSVC
  114306. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114307. #endif
  114308. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114309. #if JUCE_USE_OGGVORBIS
  114310. #include <math.h>
  114311. #include <string.h>
  114312. #include <stdlib.h>
  114313. /*** Start of inlined file: lookup.h ***/
  114314. #ifndef _V_LOOKUP_H_
  114315. #ifdef FLOAT_LOOKUP
  114316. extern float vorbis_coslook(float a);
  114317. extern float vorbis_invsqlook(float a);
  114318. extern float vorbis_invsq2explook(int a);
  114319. extern float vorbis_fromdBlook(float a);
  114320. #endif
  114321. #ifdef INT_LOOKUP
  114322. extern long vorbis_invsqlook_i(long a,long e);
  114323. extern long vorbis_coslook_i(long a);
  114324. extern float vorbis_fromdBlook_i(long a);
  114325. #endif
  114326. #endif
  114327. /*** End of inlined file: lookup.h ***/
  114328. /* three possible LSP to f curve functions; the exact computation
  114329. (float), a lookup based float implementation, and an integer
  114330. implementation. The float lookup is likely the optimal choice on
  114331. any machine with an FPU. The integer implementation is *not* fixed
  114332. point (due to the need for a large dynamic range and thus a
  114333. seperately tracked exponent) and thus much more complex than the
  114334. relatively simple float implementations. It's mostly for future
  114335. work on a fully fixed point implementation for processors like the
  114336. ARM family. */
  114337. /* undefine both for the 'old' but more precise implementation */
  114338. #define FLOAT_LOOKUP
  114339. #undef INT_LOOKUP
  114340. #ifdef FLOAT_LOOKUP
  114341. /*** Start of inlined file: lookup.c ***/
  114342. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114343. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114344. // tasks..
  114345. #if JUCE_MSVC
  114346. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114347. #endif
  114348. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114349. #if JUCE_USE_OGGVORBIS
  114350. #include <math.h>
  114351. /*** Start of inlined file: lookup.h ***/
  114352. #ifndef _V_LOOKUP_H_
  114353. #ifdef FLOAT_LOOKUP
  114354. extern float vorbis_coslook(float a);
  114355. extern float vorbis_invsqlook(float a);
  114356. extern float vorbis_invsq2explook(int a);
  114357. extern float vorbis_fromdBlook(float a);
  114358. #endif
  114359. #ifdef INT_LOOKUP
  114360. extern long vorbis_invsqlook_i(long a,long e);
  114361. extern long vorbis_coslook_i(long a);
  114362. extern float vorbis_fromdBlook_i(long a);
  114363. #endif
  114364. #endif
  114365. /*** End of inlined file: lookup.h ***/
  114366. /*** Start of inlined file: lookup_data.h ***/
  114367. #ifndef _V_LOOKUP_DATA_H_
  114368. #ifdef FLOAT_LOOKUP
  114369. #define COS_LOOKUP_SZ 128
  114370. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114371. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114372. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114373. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114374. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114375. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114376. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114377. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114378. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114379. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114380. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114381. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114382. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114383. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114384. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114385. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114386. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114387. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114388. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114389. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114390. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114391. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114392. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114393. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114394. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114395. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114396. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114397. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114398. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114399. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114400. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114401. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114402. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114403. -1.0000000000000f,
  114404. };
  114405. #define INVSQ_LOOKUP_SZ 32
  114406. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114407. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114408. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114409. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114410. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114411. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114412. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114413. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114414. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114415. 1.000000000000f,
  114416. };
  114417. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114418. #define INVSQ2EXP_LOOKUP_MAX 32
  114419. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114420. INVSQ2EXP_LOOKUP_MIN+1]={
  114421. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114422. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114423. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114424. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114425. 256.f, 181.019336f, 128.f, 90.50966799f,
  114426. 64.f, 45.254834f, 32.f, 22.627417f,
  114427. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114428. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114429. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114430. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114431. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114432. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114433. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114434. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114435. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114436. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114437. 1.525878906e-05f,
  114438. };
  114439. #endif
  114440. #define FROMdB_LOOKUP_SZ 35
  114441. #define FROMdB2_LOOKUP_SZ 32
  114442. #define FROMdB_SHIFT 5
  114443. #define FROMdB2_SHIFT 3
  114444. #define FROMdB2_MASK 31
  114445. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114446. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114447. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114448. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114449. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114450. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114451. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114452. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114453. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114454. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114455. };
  114456. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114457. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114458. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114459. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114460. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114461. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114462. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114463. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114464. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114465. };
  114466. #ifdef INT_LOOKUP
  114467. #define INVSQ_LOOKUP_I_SHIFT 10
  114468. #define INVSQ_LOOKUP_I_MASK 1023
  114469. static long INVSQ_LOOKUP_I[64+1]={
  114470. 92682l, 91966l, 91267l, 90583l,
  114471. 89915l, 89261l, 88621l, 87995l,
  114472. 87381l, 86781l, 86192l, 85616l,
  114473. 85051l, 84497l, 83953l, 83420l,
  114474. 82897l, 82384l, 81880l, 81385l,
  114475. 80899l, 80422l, 79953l, 79492l,
  114476. 79039l, 78594l, 78156l, 77726l,
  114477. 77302l, 76885l, 76475l, 76072l,
  114478. 75674l, 75283l, 74898l, 74519l,
  114479. 74146l, 73778l, 73415l, 73058l,
  114480. 72706l, 72359l, 72016l, 71679l,
  114481. 71347l, 71019l, 70695l, 70376l,
  114482. 70061l, 69750l, 69444l, 69141l,
  114483. 68842l, 68548l, 68256l, 67969l,
  114484. 67685l, 67405l, 67128l, 66855l,
  114485. 66585l, 66318l, 66054l, 65794l,
  114486. 65536l,
  114487. };
  114488. #define COS_LOOKUP_I_SHIFT 9
  114489. #define COS_LOOKUP_I_MASK 511
  114490. #define COS_LOOKUP_I_SZ 128
  114491. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114492. 16384l, 16379l, 16364l, 16340l,
  114493. 16305l, 16261l, 16207l, 16143l,
  114494. 16069l, 15986l, 15893l, 15791l,
  114495. 15679l, 15557l, 15426l, 15286l,
  114496. 15137l, 14978l, 14811l, 14635l,
  114497. 14449l, 14256l, 14053l, 13842l,
  114498. 13623l, 13395l, 13160l, 12916l,
  114499. 12665l, 12406l, 12140l, 11866l,
  114500. 11585l, 11297l, 11003l, 10702l,
  114501. 10394l, 10080l, 9760l, 9434l,
  114502. 9102l, 8765l, 8423l, 8076l,
  114503. 7723l, 7366l, 7005l, 6639l,
  114504. 6270l, 5897l, 5520l, 5139l,
  114505. 4756l, 4370l, 3981l, 3590l,
  114506. 3196l, 2801l, 2404l, 2006l,
  114507. 1606l, 1205l, 804l, 402l,
  114508. 0l, -401l, -803l, -1204l,
  114509. -1605l, -2005l, -2403l, -2800l,
  114510. -3195l, -3589l, -3980l, -4369l,
  114511. -4755l, -5138l, -5519l, -5896l,
  114512. -6269l, -6638l, -7004l, -7365l,
  114513. -7722l, -8075l, -8422l, -8764l,
  114514. -9101l, -9433l, -9759l, -10079l,
  114515. -10393l, -10701l, -11002l, -11296l,
  114516. -11584l, -11865l, -12139l, -12405l,
  114517. -12664l, -12915l, -13159l, -13394l,
  114518. -13622l, -13841l, -14052l, -14255l,
  114519. -14448l, -14634l, -14810l, -14977l,
  114520. -15136l, -15285l, -15425l, -15556l,
  114521. -15678l, -15790l, -15892l, -15985l,
  114522. -16068l, -16142l, -16206l, -16260l,
  114523. -16304l, -16339l, -16363l, -16378l,
  114524. -16383l,
  114525. };
  114526. #endif
  114527. #endif
  114528. /*** End of inlined file: lookup_data.h ***/
  114529. #ifdef FLOAT_LOOKUP
  114530. /* interpolated lookup based cos function, domain 0 to PI only */
  114531. float vorbis_coslook(float a){
  114532. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114533. int i=vorbis_ftoi(d-.5);
  114534. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114535. }
  114536. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114537. float vorbis_invsqlook(float a){
  114538. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114539. int i=vorbis_ftoi(d-.5f);
  114540. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114541. }
  114542. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114543. float vorbis_invsq2explook(int a){
  114544. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114545. }
  114546. #include <stdio.h>
  114547. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114548. float vorbis_fromdBlook(float a){
  114549. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114550. return (i<0)?1.f:
  114551. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114552. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114553. }
  114554. #endif
  114555. #ifdef INT_LOOKUP
  114556. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114557. 16.16 format
  114558. returns in m.8 format */
  114559. long vorbis_invsqlook_i(long a,long e){
  114560. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114561. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114562. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114563. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114564. d)>>16); /* result 1.16 */
  114565. e+=32;
  114566. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114567. e=(e>>1)-8;
  114568. return(val>>e);
  114569. }
  114570. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114571. /* a is in n.12 format */
  114572. float vorbis_fromdBlook_i(long a){
  114573. int i=(-a)>>(12-FROMdB2_SHIFT);
  114574. return (i<0)?1.f:
  114575. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114576. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114577. }
  114578. /* interpolated lookup based cos function, domain 0 to PI only */
  114579. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114580. long vorbis_coslook_i(long a){
  114581. int i=a>>COS_LOOKUP_I_SHIFT;
  114582. int d=a&COS_LOOKUP_I_MASK;
  114583. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114584. COS_LOOKUP_I_SHIFT);
  114585. }
  114586. #endif
  114587. #endif
  114588. /*** End of inlined file: lookup.c ***/
  114589. /* catch this in the build system; we #include for
  114590. compilers (like gcc) that can't inline across
  114591. modules */
  114592. /* side effect: changes *lsp to cosines of lsp */
  114593. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114594. float amp,float ampoffset){
  114595. int i;
  114596. float wdel=M_PI/ln;
  114597. vorbis_fpu_control fpu;
  114598. (void) fpu; // to avoid an unused variable warning
  114599. vorbis_fpu_setround(&fpu);
  114600. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  114601. i=0;
  114602. while(i<n){
  114603. int k=map[i];
  114604. int qexp;
  114605. float p=.7071067812f;
  114606. float q=.7071067812f;
  114607. float w=vorbis_coslook(wdel*k);
  114608. float *ftmp=lsp;
  114609. int c=m>>1;
  114610. do{
  114611. q*=ftmp[0]-w;
  114612. p*=ftmp[1]-w;
  114613. ftmp+=2;
  114614. }while(--c);
  114615. if(m&1){
  114616. /* odd order filter; slightly assymetric */
  114617. /* the last coefficient */
  114618. q*=ftmp[0]-w;
  114619. q*=q;
  114620. p*=p*(1.f-w*w);
  114621. }else{
  114622. /* even order filter; still symmetric */
  114623. q*=q*(1.f+w);
  114624. p*=p*(1.f-w);
  114625. }
  114626. q=frexp(p+q,&qexp);
  114627. q=vorbis_fromdBlook(amp*
  114628. vorbis_invsqlook(q)*
  114629. vorbis_invsq2explook(qexp+m)-
  114630. ampoffset);
  114631. do{
  114632. curve[i++]*=q;
  114633. }while(map[i]==k);
  114634. }
  114635. vorbis_fpu_restore(fpu);
  114636. }
  114637. #else
  114638. #ifdef INT_LOOKUP
  114639. /*** Start of inlined file: lookup.c ***/
  114640. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114641. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114642. // tasks..
  114643. #if JUCE_MSVC
  114644. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114645. #endif
  114646. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114647. #if JUCE_USE_OGGVORBIS
  114648. #include <math.h>
  114649. /*** Start of inlined file: lookup.h ***/
  114650. #ifndef _V_LOOKUP_H_
  114651. #ifdef FLOAT_LOOKUP
  114652. extern float vorbis_coslook(float a);
  114653. extern float vorbis_invsqlook(float a);
  114654. extern float vorbis_invsq2explook(int a);
  114655. extern float vorbis_fromdBlook(float a);
  114656. #endif
  114657. #ifdef INT_LOOKUP
  114658. extern long vorbis_invsqlook_i(long a,long e);
  114659. extern long vorbis_coslook_i(long a);
  114660. extern float vorbis_fromdBlook_i(long a);
  114661. #endif
  114662. #endif
  114663. /*** End of inlined file: lookup.h ***/
  114664. /*** Start of inlined file: lookup_data.h ***/
  114665. #ifndef _V_LOOKUP_DATA_H_
  114666. #ifdef FLOAT_LOOKUP
  114667. #define COS_LOOKUP_SZ 128
  114668. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114669. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114670. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114671. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114672. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114673. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114674. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114675. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114676. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114677. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114678. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114679. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114680. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114681. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114682. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114683. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114684. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114685. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114686. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114687. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114688. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114689. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114690. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114691. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114692. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114693. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114694. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114695. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114696. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114697. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114698. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114699. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114700. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114701. -1.0000000000000f,
  114702. };
  114703. #define INVSQ_LOOKUP_SZ 32
  114704. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114705. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114706. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114707. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114708. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114709. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114710. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114711. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114712. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114713. 1.000000000000f,
  114714. };
  114715. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114716. #define INVSQ2EXP_LOOKUP_MAX 32
  114717. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114718. INVSQ2EXP_LOOKUP_MIN+1]={
  114719. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114720. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114721. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114722. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114723. 256.f, 181.019336f, 128.f, 90.50966799f,
  114724. 64.f, 45.254834f, 32.f, 22.627417f,
  114725. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114726. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114727. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114728. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114729. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114730. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114731. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114732. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114733. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114734. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114735. 1.525878906e-05f,
  114736. };
  114737. #endif
  114738. #define FROMdB_LOOKUP_SZ 35
  114739. #define FROMdB2_LOOKUP_SZ 32
  114740. #define FROMdB_SHIFT 5
  114741. #define FROMdB2_SHIFT 3
  114742. #define FROMdB2_MASK 31
  114743. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114744. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114745. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114746. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114747. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114748. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114749. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114750. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114751. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114752. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114753. };
  114754. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114755. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114756. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114757. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114758. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114759. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114760. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114761. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114762. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114763. };
  114764. #ifdef INT_LOOKUP
  114765. #define INVSQ_LOOKUP_I_SHIFT 10
  114766. #define INVSQ_LOOKUP_I_MASK 1023
  114767. static long INVSQ_LOOKUP_I[64+1]={
  114768. 92682l, 91966l, 91267l, 90583l,
  114769. 89915l, 89261l, 88621l, 87995l,
  114770. 87381l, 86781l, 86192l, 85616l,
  114771. 85051l, 84497l, 83953l, 83420l,
  114772. 82897l, 82384l, 81880l, 81385l,
  114773. 80899l, 80422l, 79953l, 79492l,
  114774. 79039l, 78594l, 78156l, 77726l,
  114775. 77302l, 76885l, 76475l, 76072l,
  114776. 75674l, 75283l, 74898l, 74519l,
  114777. 74146l, 73778l, 73415l, 73058l,
  114778. 72706l, 72359l, 72016l, 71679l,
  114779. 71347l, 71019l, 70695l, 70376l,
  114780. 70061l, 69750l, 69444l, 69141l,
  114781. 68842l, 68548l, 68256l, 67969l,
  114782. 67685l, 67405l, 67128l, 66855l,
  114783. 66585l, 66318l, 66054l, 65794l,
  114784. 65536l,
  114785. };
  114786. #define COS_LOOKUP_I_SHIFT 9
  114787. #define COS_LOOKUP_I_MASK 511
  114788. #define COS_LOOKUP_I_SZ 128
  114789. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114790. 16384l, 16379l, 16364l, 16340l,
  114791. 16305l, 16261l, 16207l, 16143l,
  114792. 16069l, 15986l, 15893l, 15791l,
  114793. 15679l, 15557l, 15426l, 15286l,
  114794. 15137l, 14978l, 14811l, 14635l,
  114795. 14449l, 14256l, 14053l, 13842l,
  114796. 13623l, 13395l, 13160l, 12916l,
  114797. 12665l, 12406l, 12140l, 11866l,
  114798. 11585l, 11297l, 11003l, 10702l,
  114799. 10394l, 10080l, 9760l, 9434l,
  114800. 9102l, 8765l, 8423l, 8076l,
  114801. 7723l, 7366l, 7005l, 6639l,
  114802. 6270l, 5897l, 5520l, 5139l,
  114803. 4756l, 4370l, 3981l, 3590l,
  114804. 3196l, 2801l, 2404l, 2006l,
  114805. 1606l, 1205l, 804l, 402l,
  114806. 0l, -401l, -803l, -1204l,
  114807. -1605l, -2005l, -2403l, -2800l,
  114808. -3195l, -3589l, -3980l, -4369l,
  114809. -4755l, -5138l, -5519l, -5896l,
  114810. -6269l, -6638l, -7004l, -7365l,
  114811. -7722l, -8075l, -8422l, -8764l,
  114812. -9101l, -9433l, -9759l, -10079l,
  114813. -10393l, -10701l, -11002l, -11296l,
  114814. -11584l, -11865l, -12139l, -12405l,
  114815. -12664l, -12915l, -13159l, -13394l,
  114816. -13622l, -13841l, -14052l, -14255l,
  114817. -14448l, -14634l, -14810l, -14977l,
  114818. -15136l, -15285l, -15425l, -15556l,
  114819. -15678l, -15790l, -15892l, -15985l,
  114820. -16068l, -16142l, -16206l, -16260l,
  114821. -16304l, -16339l, -16363l, -16378l,
  114822. -16383l,
  114823. };
  114824. #endif
  114825. #endif
  114826. /*** End of inlined file: lookup_data.h ***/
  114827. #ifdef FLOAT_LOOKUP
  114828. /* interpolated lookup based cos function, domain 0 to PI only */
  114829. float vorbis_coslook(float a){
  114830. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114831. int i=vorbis_ftoi(d-.5);
  114832. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114833. }
  114834. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114835. float vorbis_invsqlook(float a){
  114836. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114837. int i=vorbis_ftoi(d-.5f);
  114838. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114839. }
  114840. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114841. float vorbis_invsq2explook(int a){
  114842. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114843. }
  114844. #include <stdio.h>
  114845. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114846. float vorbis_fromdBlook(float a){
  114847. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114848. return (i<0)?1.f:
  114849. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114850. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114851. }
  114852. #endif
  114853. #ifdef INT_LOOKUP
  114854. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114855. 16.16 format
  114856. returns in m.8 format */
  114857. long vorbis_invsqlook_i(long a,long e){
  114858. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114859. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114860. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114861. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114862. d)>>16); /* result 1.16 */
  114863. e+=32;
  114864. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114865. e=(e>>1)-8;
  114866. return(val>>e);
  114867. }
  114868. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114869. /* a is in n.12 format */
  114870. float vorbis_fromdBlook_i(long a){
  114871. int i=(-a)>>(12-FROMdB2_SHIFT);
  114872. return (i<0)?1.f:
  114873. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114874. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114875. }
  114876. /* interpolated lookup based cos function, domain 0 to PI only */
  114877. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114878. long vorbis_coslook_i(long a){
  114879. int i=a>>COS_LOOKUP_I_SHIFT;
  114880. int d=a&COS_LOOKUP_I_MASK;
  114881. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114882. COS_LOOKUP_I_SHIFT);
  114883. }
  114884. #endif
  114885. #endif
  114886. /*** End of inlined file: lookup.c ***/
  114887. /* catch this in the build system; we #include for
  114888. compilers (like gcc) that can't inline across
  114889. modules */
  114890. static int MLOOP_1[64]={
  114891. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  114892. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  114893. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114894. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114895. };
  114896. static int MLOOP_2[64]={
  114897. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  114898. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  114899. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114900. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114901. };
  114902. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  114903. /* side effect: changes *lsp to cosines of lsp */
  114904. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114905. float amp,float ampoffset){
  114906. /* 0 <= m < 256 */
  114907. /* set up for using all int later */
  114908. int i;
  114909. int ampoffseti=rint(ampoffset*4096.f);
  114910. int ampi=rint(amp*16.f);
  114911. long *ilsp=alloca(m*sizeof(*ilsp));
  114912. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  114913. i=0;
  114914. while(i<n){
  114915. int j,k=map[i];
  114916. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  114917. unsigned long qi=46341;
  114918. int qexp=0,shift;
  114919. long wi=vorbis_coslook_i(k*65536/ln);
  114920. qi*=labs(ilsp[0]-wi);
  114921. pi*=labs(ilsp[1]-wi);
  114922. for(j=3;j<m;j+=2){
  114923. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114924. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114925. shift=MLOOP_3[(pi|qi)>>16];
  114926. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114927. pi=(pi>>shift)*labs(ilsp[j]-wi);
  114928. qexp+=shift;
  114929. }
  114930. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114931. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114932. shift=MLOOP_3[(pi|qi)>>16];
  114933. /* pi,qi normalized collectively, both tracked using qexp */
  114934. if(m&1){
  114935. /* odd order filter; slightly assymetric */
  114936. /* the last coefficient */
  114937. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114938. pi=(pi>>shift)<<14;
  114939. qexp+=shift;
  114940. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114941. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114942. shift=MLOOP_3[(pi|qi)>>16];
  114943. pi>>=shift;
  114944. qi>>=shift;
  114945. qexp+=shift-14*((m+1)>>1);
  114946. pi=((pi*pi)>>16);
  114947. qi=((qi*qi)>>16);
  114948. qexp=qexp*2+m;
  114949. pi*=(1<<14)-((wi*wi)>>14);
  114950. qi+=pi>>14;
  114951. }else{
  114952. /* even order filter; still symmetric */
  114953. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  114954. worth tracking step by step */
  114955. pi>>=shift;
  114956. qi>>=shift;
  114957. qexp+=shift-7*m;
  114958. pi=((pi*pi)>>16);
  114959. qi=((qi*qi)>>16);
  114960. qexp=qexp*2+m;
  114961. pi*=(1<<14)-wi;
  114962. qi*=(1<<14)+wi;
  114963. qi=(qi+pi)>>14;
  114964. }
  114965. /* we've let the normalization drift because it wasn't important;
  114966. however, for the lookup, things must be normalized again. We
  114967. need at most one right shift or a number of left shifts */
  114968. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  114969. qi>>=1; qexp++;
  114970. }else
  114971. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  114972. qi<<=1; qexp--;
  114973. }
  114974. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  114975. vorbis_invsqlook_i(qi,qexp)-
  114976. /* m.8, m+n<=8 */
  114977. ampoffseti); /* 8.12[0] */
  114978. curve[i]*=amp;
  114979. while(map[++i]==k)curve[i]*=amp;
  114980. }
  114981. }
  114982. #else
  114983. /* old, nonoptimized but simple version for any poor sap who needs to
  114984. figure out what the hell this code does, or wants the other
  114985. fraction of a dB precision */
  114986. /* side effect: changes *lsp to cosines of lsp */
  114987. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114988. float amp,float ampoffset){
  114989. int i;
  114990. float wdel=M_PI/ln;
  114991. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  114992. i=0;
  114993. while(i<n){
  114994. int j,k=map[i];
  114995. float p=.5f;
  114996. float q=.5f;
  114997. float w=2.f*cos(wdel*k);
  114998. for(j=1;j<m;j+=2){
  114999. q *= w-lsp[j-1];
  115000. p *= w-lsp[j];
  115001. }
  115002. if(j==m){
  115003. /* odd order filter; slightly assymetric */
  115004. /* the last coefficient */
  115005. q*=w-lsp[j-1];
  115006. p*=p*(4.f-w*w);
  115007. q*=q;
  115008. }else{
  115009. /* even order filter; still symmetric */
  115010. p*=p*(2.f-w);
  115011. q*=q*(2.f+w);
  115012. }
  115013. q=fromdB(amp/sqrt(p+q)-ampoffset);
  115014. curve[i]*=q;
  115015. while(map[++i]==k)curve[i]*=q;
  115016. }
  115017. }
  115018. #endif
  115019. #endif
  115020. static void cheby(float *g, int ord) {
  115021. int i, j;
  115022. g[0] *= .5f;
  115023. for(i=2; i<= ord; i++) {
  115024. for(j=ord; j >= i; j--) {
  115025. g[j-2] -= g[j];
  115026. g[j] += g[j];
  115027. }
  115028. }
  115029. }
  115030. static int comp(const void *a,const void *b){
  115031. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  115032. }
  115033. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  115034. but there are root sets for which it gets into limit cycles
  115035. (exacerbated by zero suppression) and fails. We can't afford to
  115036. fail, even if the failure is 1 in 100,000,000, so we now use
  115037. Laguerre and later polish with Newton-Raphson (which can then
  115038. afford to fail) */
  115039. #define EPSILON 10e-7
  115040. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  115041. int i,m;
  115042. double lastdelta=0.f;
  115043. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  115044. for(i=0;i<=ord;i++)defl[i]=a[i];
  115045. for(m=ord;m>0;m--){
  115046. double newx=0.f,delta;
  115047. /* iterate a root */
  115048. while(1){
  115049. double p=defl[m],pp=0.f,ppp=0.f,denom;
  115050. /* eval the polynomial and its first two derivatives */
  115051. for(i=m;i>0;i--){
  115052. ppp = newx*ppp + pp;
  115053. pp = newx*pp + p;
  115054. p = newx*p + defl[i-1];
  115055. }
  115056. /* Laguerre's method */
  115057. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  115058. if(denom<0)
  115059. return(-1); /* complex root! The LPC generator handed us a bad filter */
  115060. if(pp>0){
  115061. denom = pp + sqrt(denom);
  115062. if(denom<EPSILON)denom=EPSILON;
  115063. }else{
  115064. denom = pp - sqrt(denom);
  115065. if(denom>-(EPSILON))denom=-(EPSILON);
  115066. }
  115067. delta = m*p/denom;
  115068. newx -= delta;
  115069. if(delta<0.f)delta*=-1;
  115070. if(fabs(delta/newx)<10e-12)break;
  115071. lastdelta=delta;
  115072. }
  115073. r[m-1]=newx;
  115074. /* forward deflation */
  115075. for(i=m;i>0;i--)
  115076. defl[i-1]+=newx*defl[i];
  115077. defl++;
  115078. }
  115079. return(0);
  115080. }
  115081. /* for spit-and-polish only */
  115082. static int Newton_Raphson(float *a,int ord,float *r){
  115083. int i, k, count=0;
  115084. double error=1.f;
  115085. double *root=(double*)alloca(ord*sizeof(*root));
  115086. for(i=0; i<ord;i++) root[i] = r[i];
  115087. while(error>1e-20){
  115088. error=0;
  115089. for(i=0; i<ord; i++) { /* Update each point. */
  115090. double pp=0.,delta;
  115091. double rooti=root[i];
  115092. double p=a[ord];
  115093. for(k=ord-1; k>= 0; k--) {
  115094. pp= pp* rooti + p;
  115095. p = p * rooti + a[k];
  115096. }
  115097. delta = p/pp;
  115098. root[i] -= delta;
  115099. error+= delta*delta;
  115100. }
  115101. if(count>40)return(-1);
  115102. count++;
  115103. }
  115104. /* Replaced the original bubble sort with a real sort. With your
  115105. help, we can eliminate the bubble sort in our lifetime. --Monty */
  115106. for(i=0; i<ord;i++) r[i] = root[i];
  115107. return(0);
  115108. }
  115109. /* Convert lpc coefficients to lsp coefficients */
  115110. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  115111. int order2=(m+1)>>1;
  115112. int g1_order,g2_order;
  115113. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  115114. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  115115. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  115116. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  115117. int i;
  115118. /* even and odd are slightly different base cases */
  115119. g1_order=(m+1)>>1;
  115120. g2_order=(m) >>1;
  115121. /* Compute the lengths of the x polynomials. */
  115122. /* Compute the first half of K & R F1 & F2 polynomials. */
  115123. /* Compute half of the symmetric and antisymmetric polynomials. */
  115124. /* Remove the roots at +1 and -1. */
  115125. g1[g1_order] = 1.f;
  115126. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  115127. g2[g2_order] = 1.f;
  115128. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  115129. if(g1_order>g2_order){
  115130. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  115131. }else{
  115132. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  115133. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  115134. }
  115135. /* Convert into polynomials in cos(alpha) */
  115136. cheby(g1,g1_order);
  115137. cheby(g2,g2_order);
  115138. /* Find the roots of the 2 even polynomials.*/
  115139. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  115140. Laguerre_With_Deflation(g2,g2_order,g2r))
  115141. return(-1);
  115142. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  115143. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  115144. qsort(g1r,g1_order,sizeof(*g1r),comp);
  115145. qsort(g2r,g2_order,sizeof(*g2r),comp);
  115146. for(i=0;i<g1_order;i++)
  115147. lsp[i*2] = acos(g1r[i]);
  115148. for(i=0;i<g2_order;i++)
  115149. lsp[i*2+1] = acos(g2r[i]);
  115150. return(0);
  115151. }
  115152. #endif
  115153. /*** End of inlined file: lsp.c ***/
  115154. /*** Start of inlined file: mapping0.c ***/
  115155. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115156. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115157. // tasks..
  115158. #if JUCE_MSVC
  115159. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115160. #endif
  115161. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115162. #if JUCE_USE_OGGVORBIS
  115163. #include <stdlib.h>
  115164. #include <stdio.h>
  115165. #include <string.h>
  115166. #include <math.h>
  115167. /* simplistic, wasteful way of doing this (unique lookup for each
  115168. mode/submapping); there should be a central repository for
  115169. identical lookups. That will require minor work, so I'm putting it
  115170. off as low priority.
  115171. Why a lookup for each backend in a given mode? Because the
  115172. blocksize is set by the mode, and low backend lookups may require
  115173. parameters from other areas of the mode/mapping */
  115174. static void mapping0_free_info(vorbis_info_mapping *i){
  115175. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  115176. if(info){
  115177. memset(info,0,sizeof(*info));
  115178. _ogg_free(info);
  115179. }
  115180. }
  115181. static int ilog3(unsigned int v){
  115182. int ret=0;
  115183. if(v)--v;
  115184. while(v){
  115185. ret++;
  115186. v>>=1;
  115187. }
  115188. return(ret);
  115189. }
  115190. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  115191. oggpack_buffer *opb){
  115192. int i;
  115193. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  115194. /* another 'we meant to do it this way' hack... up to beta 4, we
  115195. packed 4 binary zeros here to signify one submapping in use. We
  115196. now redefine that to mean four bitflags that indicate use of
  115197. deeper features; bit0:submappings, bit1:coupling,
  115198. bit2,3:reserved. This is backward compatable with all actual uses
  115199. of the beta code. */
  115200. if(info->submaps>1){
  115201. oggpack_write(opb,1,1);
  115202. oggpack_write(opb,info->submaps-1,4);
  115203. }else
  115204. oggpack_write(opb,0,1);
  115205. if(info->coupling_steps>0){
  115206. oggpack_write(opb,1,1);
  115207. oggpack_write(opb,info->coupling_steps-1,8);
  115208. for(i=0;i<info->coupling_steps;i++){
  115209. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  115210. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  115211. }
  115212. }else
  115213. oggpack_write(opb,0,1);
  115214. oggpack_write(opb,0,2); /* 2,3:reserved */
  115215. /* we don't write the channel submappings if we only have one... */
  115216. if(info->submaps>1){
  115217. for(i=0;i<vi->channels;i++)
  115218. oggpack_write(opb,info->chmuxlist[i],4);
  115219. }
  115220. for(i=0;i<info->submaps;i++){
  115221. oggpack_write(opb,0,8); /* time submap unused */
  115222. oggpack_write(opb,info->floorsubmap[i],8);
  115223. oggpack_write(opb,info->residuesubmap[i],8);
  115224. }
  115225. }
  115226. /* also responsible for range checking */
  115227. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  115228. int i;
  115229. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  115230. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115231. memset(info,0,sizeof(*info));
  115232. if(oggpack_read(opb,1))
  115233. info->submaps=oggpack_read(opb,4)+1;
  115234. else
  115235. info->submaps=1;
  115236. if(oggpack_read(opb,1)){
  115237. info->coupling_steps=oggpack_read(opb,8)+1;
  115238. for(i=0;i<info->coupling_steps;i++){
  115239. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  115240. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  115241. if(testM<0 ||
  115242. testA<0 ||
  115243. testM==testA ||
  115244. testM>=vi->channels ||
  115245. testA>=vi->channels) goto err_out;
  115246. }
  115247. }
  115248. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  115249. if(info->submaps>1){
  115250. for(i=0;i<vi->channels;i++){
  115251. info->chmuxlist[i]=oggpack_read(opb,4);
  115252. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  115253. }
  115254. }
  115255. for(i=0;i<info->submaps;i++){
  115256. oggpack_read(opb,8); /* time submap unused */
  115257. info->floorsubmap[i]=oggpack_read(opb,8);
  115258. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  115259. info->residuesubmap[i]=oggpack_read(opb,8);
  115260. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  115261. }
  115262. return info;
  115263. err_out:
  115264. mapping0_free_info(info);
  115265. return(NULL);
  115266. }
  115267. #if 0
  115268. static long seq=0;
  115269. static ogg_int64_t total=0;
  115270. static float FLOOR1_fromdB_LOOKUP[256]={
  115271. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  115272. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  115273. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  115274. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  115275. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  115276. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  115277. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  115278. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  115279. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  115280. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  115281. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  115282. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  115283. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  115284. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  115285. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  115286. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  115287. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  115288. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  115289. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  115290. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  115291. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  115292. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  115293. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  115294. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  115295. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  115296. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  115297. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  115298. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  115299. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  115300. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  115301. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  115302. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  115303. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  115304. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  115305. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  115306. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  115307. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  115308. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  115309. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  115310. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  115311. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  115312. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  115313. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  115314. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  115315. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  115316. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  115317. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  115318. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  115319. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  115320. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  115321. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  115322. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  115323. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  115324. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  115325. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  115326. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  115327. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  115328. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  115329. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  115330. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  115331. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  115332. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  115333. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  115334. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  115335. };
  115336. #endif
  115337. extern int *floor1_fit(vorbis_block *vb,void *look,
  115338. const float *logmdct, /* in */
  115339. const float *logmask);
  115340. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  115341. int *A,int *B,
  115342. int del);
  115343. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  115344. void*look,
  115345. int *post,int *ilogmask);
  115346. static int mapping0_forward(vorbis_block *vb){
  115347. vorbis_dsp_state *vd=vb->vd;
  115348. vorbis_info *vi=vd->vi;
  115349. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115350. private_state *b=(private_state*)vb->vd->backend_state;
  115351. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  115352. int n=vb->pcmend;
  115353. int i,j,k;
  115354. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  115355. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  115356. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  115357. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  115358. float global_ampmax=vbi->ampmax;
  115359. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  115360. int blocktype=vbi->blocktype;
  115361. int modenumber=vb->W;
  115362. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  115363. vorbis_look_psy *psy_look=
  115364. b->psy+blocktype+(vb->W?2:0);
  115365. vb->mode=modenumber;
  115366. for(i=0;i<vi->channels;i++){
  115367. float scale=4.f/n;
  115368. float scale_dB;
  115369. float *pcm =vb->pcm[i];
  115370. float *logfft =pcm;
  115371. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115372. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  115373. todB estimation used on IEEE 754
  115374. compliant machines had a bug that
  115375. returned dB values about a third
  115376. of a decibel too high. The bug
  115377. was harmless because tunings
  115378. implicitly took that into
  115379. account. However, fixing the bug
  115380. in the estimator requires
  115381. changing all the tunings as well.
  115382. For now, it's easier to sync
  115383. things back up here, and
  115384. recalibrate the tunings in the
  115385. next major model upgrade. */
  115386. #if 0
  115387. if(vi->channels==2)
  115388. if(i==0)
  115389. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  115390. else
  115391. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  115392. #endif
  115393. /* window the PCM data */
  115394. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  115395. #if 0
  115396. if(vi->channels==2)
  115397. if(i==0)
  115398. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  115399. else
  115400. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  115401. #endif
  115402. /* transform the PCM data */
  115403. /* only MDCT right now.... */
  115404. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  115405. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  115406. drft_forward(&b->fft_look[vb->W],pcm);
  115407. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  115408. original todB estimation used on
  115409. IEEE 754 compliant machines had a
  115410. bug that returned dB values about
  115411. a third of a decibel too high.
  115412. The bug was harmless because
  115413. tunings implicitly took that into
  115414. account. However, fixing the bug
  115415. in the estimator requires
  115416. changing all the tunings as well.
  115417. For now, it's easier to sync
  115418. things back up here, and
  115419. recalibrate the tunings in the
  115420. next major model upgrade. */
  115421. local_ampmax[i]=logfft[0];
  115422. for(j=1;j<n-1;j+=2){
  115423. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  115424. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  115425. .345 is a hack; the original todB
  115426. estimation used on IEEE 754
  115427. compliant machines had a bug that
  115428. returned dB values about a third
  115429. of a decibel too high. The bug
  115430. was harmless because tunings
  115431. implicitly took that into
  115432. account. However, fixing the bug
  115433. in the estimator requires
  115434. changing all the tunings as well.
  115435. For now, it's easier to sync
  115436. things back up here, and
  115437. recalibrate the tunings in the
  115438. next major model upgrade. */
  115439. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  115440. }
  115441. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  115442. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  115443. #if 0
  115444. if(vi->channels==2){
  115445. if(i==0){
  115446. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  115447. }else{
  115448. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  115449. }
  115450. }
  115451. #endif
  115452. }
  115453. {
  115454. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  115455. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  115456. for(i=0;i<vi->channels;i++){
  115457. /* the encoder setup assumes that all the modes used by any
  115458. specific bitrate tweaking use the same floor */
  115459. int submap=info->chmuxlist[i];
  115460. /* the following makes things clearer to *me* anyway */
  115461. float *mdct =gmdct[i];
  115462. float *logfft =vb->pcm[i];
  115463. float *logmdct =logfft+n/2;
  115464. float *logmask =logfft;
  115465. vb->mode=modenumber;
  115466. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  115467. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  115468. for(j=0;j<n/2;j++)
  115469. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  115470. todB estimation used on IEEE 754
  115471. compliant machines had a bug that
  115472. returned dB values about a third
  115473. of a decibel too high. The bug
  115474. was harmless because tunings
  115475. implicitly took that into
  115476. account. However, fixing the bug
  115477. in the estimator requires
  115478. changing all the tunings as well.
  115479. For now, it's easier to sync
  115480. things back up here, and
  115481. recalibrate the tunings in the
  115482. next major model upgrade. */
  115483. #if 0
  115484. if(vi->channels==2){
  115485. if(i==0)
  115486. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  115487. else
  115488. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  115489. }else{
  115490. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  115491. }
  115492. #endif
  115493. /* first step; noise masking. Not only does 'noise masking'
  115494. give us curves from which we can decide how much resolution
  115495. to give noise parts of the spectrum, it also implicitly hands
  115496. us a tonality estimate (the larger the value in the
  115497. 'noise_depth' vector, the more tonal that area is) */
  115498. _vp_noisemask(psy_look,
  115499. logmdct,
  115500. noise); /* noise does not have by-frequency offset
  115501. bias applied yet */
  115502. #if 0
  115503. if(vi->channels==2){
  115504. if(i==0)
  115505. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  115506. else
  115507. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  115508. }
  115509. #endif
  115510. /* second step: 'all the other crap'; all the stuff that isn't
  115511. computed/fit for bitrate management goes in the second psy
  115512. vector. This includes tone masking, peak limiting and ATH */
  115513. _vp_tonemask(psy_look,
  115514. logfft,
  115515. tone,
  115516. global_ampmax,
  115517. local_ampmax[i]);
  115518. #if 0
  115519. if(vi->channels==2){
  115520. if(i==0)
  115521. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  115522. else
  115523. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  115524. }
  115525. #endif
  115526. /* third step; we offset the noise vectors, overlay tone
  115527. masking. We then do a floor1-specific line fit. If we're
  115528. performing bitrate management, the line fit is performed
  115529. multiple times for up/down tweakage on demand. */
  115530. #if 0
  115531. {
  115532. float aotuv[psy_look->n];
  115533. #endif
  115534. _vp_offset_and_mix(psy_look,
  115535. noise,
  115536. tone,
  115537. 1,
  115538. logmask,
  115539. mdct,
  115540. logmdct);
  115541. #if 0
  115542. if(vi->channels==2){
  115543. if(i==0)
  115544. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  115545. else
  115546. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  115547. }
  115548. }
  115549. #endif
  115550. #if 0
  115551. if(vi->channels==2){
  115552. if(i==0)
  115553. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  115554. else
  115555. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  115556. }
  115557. #endif
  115558. /* this algorithm is hardwired to floor 1 for now; abort out if
  115559. we're *not* floor1. This won't happen unless someone has
  115560. broken the encode setup lib. Guard it anyway. */
  115561. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  115562. floor_posts[i][PACKETBLOBS/2]=
  115563. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115564. logmdct,
  115565. logmask);
  115566. /* are we managing bitrate? If so, perform two more fits for
  115567. later rate tweaking (fits represent hi/lo) */
  115568. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  115569. /* higher rate by way of lower noise curve */
  115570. _vp_offset_and_mix(psy_look,
  115571. noise,
  115572. tone,
  115573. 2,
  115574. logmask,
  115575. mdct,
  115576. logmdct);
  115577. #if 0
  115578. if(vi->channels==2){
  115579. if(i==0)
  115580. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  115581. else
  115582. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  115583. }
  115584. #endif
  115585. floor_posts[i][PACKETBLOBS-1]=
  115586. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115587. logmdct,
  115588. logmask);
  115589. /* lower rate by way of higher noise curve */
  115590. _vp_offset_and_mix(psy_look,
  115591. noise,
  115592. tone,
  115593. 0,
  115594. logmask,
  115595. mdct,
  115596. logmdct);
  115597. #if 0
  115598. if(vi->channels==2)
  115599. if(i==0)
  115600. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  115601. else
  115602. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  115603. #endif
  115604. floor_posts[i][0]=
  115605. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115606. logmdct,
  115607. logmask);
  115608. /* we also interpolate a range of intermediate curves for
  115609. intermediate rates */
  115610. for(k=1;k<PACKETBLOBS/2;k++)
  115611. floor_posts[i][k]=
  115612. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115613. floor_posts[i][0],
  115614. floor_posts[i][PACKETBLOBS/2],
  115615. k*65536/(PACKETBLOBS/2));
  115616. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  115617. floor_posts[i][k]=
  115618. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115619. floor_posts[i][PACKETBLOBS/2],
  115620. floor_posts[i][PACKETBLOBS-1],
  115621. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  115622. }
  115623. }
  115624. }
  115625. vbi->ampmax=global_ampmax;
  115626. /*
  115627. the next phases are performed once for vbr-only and PACKETBLOB
  115628. times for bitrate managed modes.
  115629. 1) encode actual mode being used
  115630. 2) encode the floor for each channel, compute coded mask curve/res
  115631. 3) normalize and couple.
  115632. 4) encode residue
  115633. 5) save packet bytes to the packetblob vector
  115634. */
  115635. /* iterate over the many masking curve fits we've created */
  115636. {
  115637. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  115638. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  115639. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115640. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  115641. float **mag_memo;
  115642. int **mag_sort;
  115643. if(info->coupling_steps){
  115644. mag_memo=_vp_quantize_couple_memo(vb,
  115645. &ci->psy_g_param,
  115646. psy_look,
  115647. info,
  115648. gmdct);
  115649. mag_sort=_vp_quantize_couple_sort(vb,
  115650. psy_look,
  115651. info,
  115652. mag_memo);
  115653. hf_reduction(&ci->psy_g_param,
  115654. psy_look,
  115655. info,
  115656. mag_memo);
  115657. }
  115658. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  115659. if(psy_look->vi->normal_channel_p){
  115660. for(i=0;i<vi->channels;i++){
  115661. float *mdct =gmdct[i];
  115662. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  115663. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  115664. }
  115665. }
  115666. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  115667. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  115668. k++){
  115669. oggpack_buffer *opb=vbi->packetblob[k];
  115670. /* start out our new packet blob with packet type and mode */
  115671. /* Encode the packet type */
  115672. oggpack_write(opb,0,1);
  115673. /* Encode the modenumber */
  115674. /* Encode frame mode, pre,post windowsize, then dispatch */
  115675. oggpack_write(opb,modenumber,b->modebits);
  115676. if(vb->W){
  115677. oggpack_write(opb,vb->lW,1);
  115678. oggpack_write(opb,vb->nW,1);
  115679. }
  115680. /* encode floor, compute masking curve, sep out residue */
  115681. for(i=0;i<vi->channels;i++){
  115682. int submap=info->chmuxlist[i];
  115683. float *mdct =gmdct[i];
  115684. float *res =vb->pcm[i];
  115685. int *ilogmask=ilogmaskch[i]=
  115686. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115687. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  115688. floor_posts[i][k],
  115689. ilogmask);
  115690. #if 0
  115691. {
  115692. char buf[80];
  115693. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  115694. float work[n/2];
  115695. for(j=0;j<n/2;j++)
  115696. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  115697. _analysis_output(buf,seq,work,n/2,1,1,0);
  115698. }
  115699. #endif
  115700. _vp_remove_floor(psy_look,
  115701. mdct,
  115702. ilogmask,
  115703. res,
  115704. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115705. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  115706. #if 0
  115707. {
  115708. char buf[80];
  115709. float work[n/2];
  115710. for(j=0;j<n/2;j++)
  115711. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  115712. sprintf(buf,"resI%c%d",i?'R':'L',k);
  115713. _analysis_output(buf,seq,work,n/2,1,1,0);
  115714. }
  115715. #endif
  115716. }
  115717. /* our iteration is now based on masking curve, not prequant and
  115718. coupling. Only one prequant/coupling step */
  115719. /* quantize/couple */
  115720. /* incomplete implementation that assumes the tree is all depth
  115721. one, or no tree at all */
  115722. if(info->coupling_steps){
  115723. _vp_couple(k,
  115724. &ci->psy_g_param,
  115725. psy_look,
  115726. info,
  115727. vb->pcm,
  115728. mag_memo,
  115729. mag_sort,
  115730. ilogmaskch,
  115731. nonzero,
  115732. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115733. }
  115734. /* classify and encode by submap */
  115735. for(i=0;i<info->submaps;i++){
  115736. int ch_in_bundle=0;
  115737. long **classifications;
  115738. int resnum=info->residuesubmap[i];
  115739. for(j=0;j<vi->channels;j++){
  115740. if(info->chmuxlist[j]==i){
  115741. zerobundle[ch_in_bundle]=0;
  115742. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  115743. res_bundle[ch_in_bundle]=vb->pcm[j];
  115744. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  115745. }
  115746. }
  115747. classifications=_residue_P[ci->residue_type[resnum]]->
  115748. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  115749. _residue_P[ci->residue_type[resnum]]->
  115750. forward(opb,vb,b->residue[resnum],
  115751. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  115752. }
  115753. /* ok, done encoding. Next protopacket. */
  115754. }
  115755. }
  115756. #if 0
  115757. seq++;
  115758. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  115759. #endif
  115760. return(0);
  115761. }
  115762. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  115763. vorbis_dsp_state *vd=vb->vd;
  115764. vorbis_info *vi=vd->vi;
  115765. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  115766. private_state *b=(private_state*)vd->backend_state;
  115767. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  115768. int i,j;
  115769. long n=vb->pcmend=ci->blocksizes[vb->W];
  115770. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  115771. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115772. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  115773. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  115774. /* recover the spectral envelope; store it in the PCM vector for now */
  115775. for(i=0;i<vi->channels;i++){
  115776. int submap=info->chmuxlist[i];
  115777. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115778. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  115779. if(floormemo[i])
  115780. nonzero[i]=1;
  115781. else
  115782. nonzero[i]=0;
  115783. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  115784. }
  115785. /* channel coupling can 'dirty' the nonzero listing */
  115786. for(i=0;i<info->coupling_steps;i++){
  115787. if(nonzero[info->coupling_mag[i]] ||
  115788. nonzero[info->coupling_ang[i]]){
  115789. nonzero[info->coupling_mag[i]]=1;
  115790. nonzero[info->coupling_ang[i]]=1;
  115791. }
  115792. }
  115793. /* recover the residue into our working vectors */
  115794. for(i=0;i<info->submaps;i++){
  115795. int ch_in_bundle=0;
  115796. for(j=0;j<vi->channels;j++){
  115797. if(info->chmuxlist[j]==i){
  115798. if(nonzero[j])
  115799. zerobundle[ch_in_bundle]=1;
  115800. else
  115801. zerobundle[ch_in_bundle]=0;
  115802. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  115803. }
  115804. }
  115805. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  115806. inverse(vb,b->residue[info->residuesubmap[i]],
  115807. pcmbundle,zerobundle,ch_in_bundle);
  115808. }
  115809. /* channel coupling */
  115810. for(i=info->coupling_steps-1;i>=0;i--){
  115811. float *pcmM=vb->pcm[info->coupling_mag[i]];
  115812. float *pcmA=vb->pcm[info->coupling_ang[i]];
  115813. for(j=0;j<n/2;j++){
  115814. float mag=pcmM[j];
  115815. float ang=pcmA[j];
  115816. if(mag>0)
  115817. if(ang>0){
  115818. pcmM[j]=mag;
  115819. pcmA[j]=mag-ang;
  115820. }else{
  115821. pcmA[j]=mag;
  115822. pcmM[j]=mag+ang;
  115823. }
  115824. else
  115825. if(ang>0){
  115826. pcmM[j]=mag;
  115827. pcmA[j]=mag+ang;
  115828. }else{
  115829. pcmA[j]=mag;
  115830. pcmM[j]=mag-ang;
  115831. }
  115832. }
  115833. }
  115834. /* compute and apply spectral envelope */
  115835. for(i=0;i<vi->channels;i++){
  115836. float *pcm=vb->pcm[i];
  115837. int submap=info->chmuxlist[i];
  115838. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115839. inverse2(vb,b->flr[info->floorsubmap[submap]],
  115840. floormemo[i],pcm);
  115841. }
  115842. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  115843. /* only MDCT right now.... */
  115844. for(i=0;i<vi->channels;i++){
  115845. float *pcm=vb->pcm[i];
  115846. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  115847. }
  115848. /* all done! */
  115849. return(0);
  115850. }
  115851. /* export hooks */
  115852. vorbis_func_mapping mapping0_exportbundle={
  115853. &mapping0_pack,
  115854. &mapping0_unpack,
  115855. &mapping0_free_info,
  115856. &mapping0_forward,
  115857. &mapping0_inverse
  115858. };
  115859. #endif
  115860. /*** End of inlined file: mapping0.c ***/
  115861. /*** Start of inlined file: mdct.c ***/
  115862. /* this can also be run as an integer transform by uncommenting a
  115863. define in mdct.h; the integerization is a first pass and although
  115864. it's likely stable for Vorbis, the dynamic range is constrained and
  115865. roundoff isn't done (so it's noisy). Consider it functional, but
  115866. only a starting point. There's no point on a machine with an FPU */
  115867. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115868. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115869. // tasks..
  115870. #if JUCE_MSVC
  115871. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115872. #endif
  115873. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115874. #if JUCE_USE_OGGVORBIS
  115875. #include <stdio.h>
  115876. #include <stdlib.h>
  115877. #include <string.h>
  115878. #include <math.h>
  115879. /* build lookups for trig functions; also pre-figure scaling and
  115880. some window function algebra. */
  115881. void mdct_init(mdct_lookup *lookup,int n){
  115882. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  115883. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  115884. int i;
  115885. int n2=n>>1;
  115886. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  115887. lookup->n=n;
  115888. lookup->trig=T;
  115889. lookup->bitrev=bitrev;
  115890. /* trig lookups... */
  115891. for(i=0;i<n/4;i++){
  115892. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  115893. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  115894. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  115895. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  115896. }
  115897. for(i=0;i<n/8;i++){
  115898. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  115899. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  115900. }
  115901. /* bitreverse lookup... */
  115902. {
  115903. int mask=(1<<(log2n-1))-1,i,j;
  115904. int msb=1<<(log2n-2);
  115905. for(i=0;i<n/8;i++){
  115906. int acc=0;
  115907. for(j=0;msb>>j;j++)
  115908. if((msb>>j)&i)acc|=1<<j;
  115909. bitrev[i*2]=((~acc)&mask)-1;
  115910. bitrev[i*2+1]=acc;
  115911. }
  115912. }
  115913. lookup->scale=FLOAT_CONV(4.f/n);
  115914. }
  115915. /* 8 point butterfly (in place, 4 register) */
  115916. STIN void mdct_butterfly_8(DATA_TYPE *x){
  115917. REG_TYPE r0 = x[6] + x[2];
  115918. REG_TYPE r1 = x[6] - x[2];
  115919. REG_TYPE r2 = x[4] + x[0];
  115920. REG_TYPE r3 = x[4] - x[0];
  115921. x[6] = r0 + r2;
  115922. x[4] = r0 - r2;
  115923. r0 = x[5] - x[1];
  115924. r2 = x[7] - x[3];
  115925. x[0] = r1 + r0;
  115926. x[2] = r1 - r0;
  115927. r0 = x[5] + x[1];
  115928. r1 = x[7] + x[3];
  115929. x[3] = r2 + r3;
  115930. x[1] = r2 - r3;
  115931. x[7] = r1 + r0;
  115932. x[5] = r1 - r0;
  115933. }
  115934. /* 16 point butterfly (in place, 4 register) */
  115935. STIN void mdct_butterfly_16(DATA_TYPE *x){
  115936. REG_TYPE r0 = x[1] - x[9];
  115937. REG_TYPE r1 = x[0] - x[8];
  115938. x[8] += x[0];
  115939. x[9] += x[1];
  115940. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  115941. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  115942. r0 = x[3] - x[11];
  115943. r1 = x[10] - x[2];
  115944. x[10] += x[2];
  115945. x[11] += x[3];
  115946. x[2] = r0;
  115947. x[3] = r1;
  115948. r0 = x[12] - x[4];
  115949. r1 = x[13] - x[5];
  115950. x[12] += x[4];
  115951. x[13] += x[5];
  115952. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  115953. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  115954. r0 = x[14] - x[6];
  115955. r1 = x[15] - x[7];
  115956. x[14] += x[6];
  115957. x[15] += x[7];
  115958. x[6] = r0;
  115959. x[7] = r1;
  115960. mdct_butterfly_8(x);
  115961. mdct_butterfly_8(x+8);
  115962. }
  115963. /* 32 point butterfly (in place, 4 register) */
  115964. STIN void mdct_butterfly_32(DATA_TYPE *x){
  115965. REG_TYPE r0 = x[30] - x[14];
  115966. REG_TYPE r1 = x[31] - x[15];
  115967. x[30] += x[14];
  115968. x[31] += x[15];
  115969. x[14] = r0;
  115970. x[15] = r1;
  115971. r0 = x[28] - x[12];
  115972. r1 = x[29] - x[13];
  115973. x[28] += x[12];
  115974. x[29] += x[13];
  115975. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  115976. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  115977. r0 = x[26] - x[10];
  115978. r1 = x[27] - x[11];
  115979. x[26] += x[10];
  115980. x[27] += x[11];
  115981. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  115982. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  115983. r0 = x[24] - x[8];
  115984. r1 = x[25] - x[9];
  115985. x[24] += x[8];
  115986. x[25] += x[9];
  115987. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  115988. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  115989. r0 = x[22] - x[6];
  115990. r1 = x[7] - x[23];
  115991. x[22] += x[6];
  115992. x[23] += x[7];
  115993. x[6] = r1;
  115994. x[7] = r0;
  115995. r0 = x[4] - x[20];
  115996. r1 = x[5] - x[21];
  115997. x[20] += x[4];
  115998. x[21] += x[5];
  115999. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  116000. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  116001. r0 = x[2] - x[18];
  116002. r1 = x[3] - x[19];
  116003. x[18] += x[2];
  116004. x[19] += x[3];
  116005. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  116006. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  116007. r0 = x[0] - x[16];
  116008. r1 = x[1] - x[17];
  116009. x[16] += x[0];
  116010. x[17] += x[1];
  116011. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  116012. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  116013. mdct_butterfly_16(x);
  116014. mdct_butterfly_16(x+16);
  116015. }
  116016. /* N point first stage butterfly (in place, 2 register) */
  116017. STIN void mdct_butterfly_first(DATA_TYPE *T,
  116018. DATA_TYPE *x,
  116019. int points){
  116020. DATA_TYPE *x1 = x + points - 8;
  116021. DATA_TYPE *x2 = x + (points>>1) - 8;
  116022. REG_TYPE r0;
  116023. REG_TYPE r1;
  116024. do{
  116025. r0 = x1[6] - x2[6];
  116026. r1 = x1[7] - x2[7];
  116027. x1[6] += x2[6];
  116028. x1[7] += x2[7];
  116029. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116030. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116031. r0 = x1[4] - x2[4];
  116032. r1 = x1[5] - x2[5];
  116033. x1[4] += x2[4];
  116034. x1[5] += x2[5];
  116035. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  116036. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  116037. r0 = x1[2] - x2[2];
  116038. r1 = x1[3] - x2[3];
  116039. x1[2] += x2[2];
  116040. x1[3] += x2[3];
  116041. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  116042. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  116043. r0 = x1[0] - x2[0];
  116044. r1 = x1[1] - x2[1];
  116045. x1[0] += x2[0];
  116046. x1[1] += x2[1];
  116047. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  116048. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  116049. x1-=8;
  116050. x2-=8;
  116051. T+=16;
  116052. }while(x2>=x);
  116053. }
  116054. /* N/stage point generic N stage butterfly (in place, 2 register) */
  116055. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  116056. DATA_TYPE *x,
  116057. int points,
  116058. int trigint){
  116059. DATA_TYPE *x1 = x + points - 8;
  116060. DATA_TYPE *x2 = x + (points>>1) - 8;
  116061. REG_TYPE r0;
  116062. REG_TYPE r1;
  116063. do{
  116064. r0 = x1[6] - x2[6];
  116065. r1 = x1[7] - x2[7];
  116066. x1[6] += x2[6];
  116067. x1[7] += x2[7];
  116068. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116069. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116070. T+=trigint;
  116071. r0 = x1[4] - x2[4];
  116072. r1 = x1[5] - x2[5];
  116073. x1[4] += x2[4];
  116074. x1[5] += x2[5];
  116075. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116076. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116077. T+=trigint;
  116078. r0 = x1[2] - x2[2];
  116079. r1 = x1[3] - x2[3];
  116080. x1[2] += x2[2];
  116081. x1[3] += x2[3];
  116082. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116083. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116084. T+=trigint;
  116085. r0 = x1[0] - x2[0];
  116086. r1 = x1[1] - x2[1];
  116087. x1[0] += x2[0];
  116088. x1[1] += x2[1];
  116089. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116090. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116091. T+=trigint;
  116092. x1-=8;
  116093. x2-=8;
  116094. }while(x2>=x);
  116095. }
  116096. STIN void mdct_butterflies(mdct_lookup *init,
  116097. DATA_TYPE *x,
  116098. int points){
  116099. DATA_TYPE *T=init->trig;
  116100. int stages=init->log2n-5;
  116101. int i,j;
  116102. if(--stages>0){
  116103. mdct_butterfly_first(T,x,points);
  116104. }
  116105. for(i=1;--stages>0;i++){
  116106. for(j=0;j<(1<<i);j++)
  116107. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  116108. }
  116109. for(j=0;j<points;j+=32)
  116110. mdct_butterfly_32(x+j);
  116111. }
  116112. void mdct_clear(mdct_lookup *l){
  116113. if(l){
  116114. if(l->trig)_ogg_free(l->trig);
  116115. if(l->bitrev)_ogg_free(l->bitrev);
  116116. memset(l,0,sizeof(*l));
  116117. }
  116118. }
  116119. STIN void mdct_bitreverse(mdct_lookup *init,
  116120. DATA_TYPE *x){
  116121. int n = init->n;
  116122. int *bit = init->bitrev;
  116123. DATA_TYPE *w0 = x;
  116124. DATA_TYPE *w1 = x = w0+(n>>1);
  116125. DATA_TYPE *T = init->trig+n;
  116126. do{
  116127. DATA_TYPE *x0 = x+bit[0];
  116128. DATA_TYPE *x1 = x+bit[1];
  116129. REG_TYPE r0 = x0[1] - x1[1];
  116130. REG_TYPE r1 = x0[0] + x1[0];
  116131. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  116132. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  116133. w1 -= 4;
  116134. r0 = HALVE(x0[1] + x1[1]);
  116135. r1 = HALVE(x0[0] - x1[0]);
  116136. w0[0] = r0 + r2;
  116137. w1[2] = r0 - r2;
  116138. w0[1] = r1 + r3;
  116139. w1[3] = r3 - r1;
  116140. x0 = x+bit[2];
  116141. x1 = x+bit[3];
  116142. r0 = x0[1] - x1[1];
  116143. r1 = x0[0] + x1[0];
  116144. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  116145. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  116146. r0 = HALVE(x0[1] + x1[1]);
  116147. r1 = HALVE(x0[0] - x1[0]);
  116148. w0[2] = r0 + r2;
  116149. w1[0] = r0 - r2;
  116150. w0[3] = r1 + r3;
  116151. w1[1] = r3 - r1;
  116152. T += 4;
  116153. bit += 4;
  116154. w0 += 4;
  116155. }while(w0<w1);
  116156. }
  116157. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  116158. int n=init->n;
  116159. int n2=n>>1;
  116160. int n4=n>>2;
  116161. /* rotate */
  116162. DATA_TYPE *iX = in+n2-7;
  116163. DATA_TYPE *oX = out+n2+n4;
  116164. DATA_TYPE *T = init->trig+n4;
  116165. do{
  116166. oX -= 4;
  116167. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  116168. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  116169. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  116170. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  116171. iX -= 8;
  116172. T += 4;
  116173. }while(iX>=in);
  116174. iX = in+n2-8;
  116175. oX = out+n2+n4;
  116176. T = init->trig+n4;
  116177. do{
  116178. T -= 4;
  116179. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  116180. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  116181. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  116182. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  116183. iX -= 8;
  116184. oX += 4;
  116185. }while(iX>=in);
  116186. mdct_butterflies(init,out+n2,n2);
  116187. mdct_bitreverse(init,out);
  116188. /* roatate + window */
  116189. {
  116190. DATA_TYPE *oX1=out+n2+n4;
  116191. DATA_TYPE *oX2=out+n2+n4;
  116192. DATA_TYPE *iX =out;
  116193. T =init->trig+n2;
  116194. do{
  116195. oX1-=4;
  116196. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  116197. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  116198. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  116199. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  116200. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  116201. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  116202. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  116203. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  116204. oX2+=4;
  116205. iX += 8;
  116206. T += 8;
  116207. }while(iX<oX1);
  116208. iX=out+n2+n4;
  116209. oX1=out+n4;
  116210. oX2=oX1;
  116211. do{
  116212. oX1-=4;
  116213. iX-=4;
  116214. oX2[0] = -(oX1[3] = iX[3]);
  116215. oX2[1] = -(oX1[2] = iX[2]);
  116216. oX2[2] = -(oX1[1] = iX[1]);
  116217. oX2[3] = -(oX1[0] = iX[0]);
  116218. oX2+=4;
  116219. }while(oX2<iX);
  116220. iX=out+n2+n4;
  116221. oX1=out+n2+n4;
  116222. oX2=out+n2;
  116223. do{
  116224. oX1-=4;
  116225. oX1[0]= iX[3];
  116226. oX1[1]= iX[2];
  116227. oX1[2]= iX[1];
  116228. oX1[3]= iX[0];
  116229. iX+=4;
  116230. }while(oX1>oX2);
  116231. }
  116232. }
  116233. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  116234. int n=init->n;
  116235. int n2=n>>1;
  116236. int n4=n>>2;
  116237. int n8=n>>3;
  116238. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  116239. DATA_TYPE *w2=w+n2;
  116240. /* rotate */
  116241. /* window + rotate + step 1 */
  116242. REG_TYPE r0;
  116243. REG_TYPE r1;
  116244. DATA_TYPE *x0=in+n2+n4;
  116245. DATA_TYPE *x1=x0+1;
  116246. DATA_TYPE *T=init->trig+n2;
  116247. int i=0;
  116248. for(i=0;i<n8;i+=2){
  116249. x0 -=4;
  116250. T-=2;
  116251. r0= x0[2] + x1[0];
  116252. r1= x0[0] + x1[2];
  116253. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116254. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116255. x1 +=4;
  116256. }
  116257. x1=in+1;
  116258. for(;i<n2-n8;i+=2){
  116259. T-=2;
  116260. x0 -=4;
  116261. r0= x0[2] - x1[0];
  116262. r1= x0[0] - x1[2];
  116263. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116264. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116265. x1 +=4;
  116266. }
  116267. x0=in+n;
  116268. for(;i<n2;i+=2){
  116269. T-=2;
  116270. x0 -=4;
  116271. r0= -x0[2] - x1[0];
  116272. r1= -x0[0] - x1[2];
  116273. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116274. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116275. x1 +=4;
  116276. }
  116277. mdct_butterflies(init,w+n2,n2);
  116278. mdct_bitreverse(init,w);
  116279. /* roatate + window */
  116280. T=init->trig+n2;
  116281. x0=out+n2;
  116282. for(i=0;i<n4;i++){
  116283. x0--;
  116284. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  116285. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  116286. w+=2;
  116287. T+=2;
  116288. }
  116289. }
  116290. #endif
  116291. /*** End of inlined file: mdct.c ***/
  116292. /*** Start of inlined file: psy.c ***/
  116293. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  116294. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  116295. // tasks..
  116296. #if JUCE_MSVC
  116297. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116298. #endif
  116299. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  116300. #if JUCE_USE_OGGVORBIS
  116301. #include <stdlib.h>
  116302. #include <math.h>
  116303. #include <string.h>
  116304. /*** Start of inlined file: masking.h ***/
  116305. #ifndef _V_MASKING_H_
  116306. #define _V_MASKING_H_
  116307. /* more detailed ATH; the bass if flat to save stressing the floor
  116308. overly for only a bin or two of savings. */
  116309. #define MAX_ATH 88
  116310. static float ATH[]={
  116311. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  116312. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  116313. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  116314. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  116315. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  116316. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  116317. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  116318. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  116319. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  116320. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  116321. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  116322. };
  116323. /* The tone masking curves from Ehmer's and Fielder's papers have been
  116324. replaced by an empirically collected data set. The previously
  116325. published values were, far too often, simply on crack. */
  116326. #define EHMER_OFFSET 16
  116327. #define EHMER_MAX 56
  116328. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  116329. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  116330. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  116331. for collection of these curves) */
  116332. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  116333. /* 62.5 Hz */
  116334. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  116335. -60, -60, -60, -60, -62, -62, -65, -73,
  116336. -69, -68, -68, -67, -70, -70, -72, -74,
  116337. -75, -79, -79, -80, -83, -88, -93, -100,
  116338. -110, -999, -999, -999, -999, -999, -999, -999,
  116339. -999, -999, -999, -999, -999, -999, -999, -999,
  116340. -999, -999, -999, -999, -999, -999, -999, -999},
  116341. { -48, -48, -48, -48, -48, -48, -48, -48,
  116342. -48, -48, -48, -48, -48, -53, -61, -66,
  116343. -66, -68, -67, -70, -76, -76, -72, -73,
  116344. -75, -76, -78, -79, -83, -88, -93, -100,
  116345. -110, -999, -999, -999, -999, -999, -999, -999,
  116346. -999, -999, -999, -999, -999, -999, -999, -999,
  116347. -999, -999, -999, -999, -999, -999, -999, -999},
  116348. { -37, -37, -37, -37, -37, -37, -37, -37,
  116349. -38, -40, -42, -46, -48, -53, -55, -62,
  116350. -65, -58, -56, -56, -61, -60, -65, -67,
  116351. -69, -71, -77, -77, -78, -80, -82, -84,
  116352. -88, -93, -98, -106, -112, -999, -999, -999,
  116353. -999, -999, -999, -999, -999, -999, -999, -999,
  116354. -999, -999, -999, -999, -999, -999, -999, -999},
  116355. { -25, -25, -25, -25, -25, -25, -25, -25,
  116356. -25, -26, -27, -29, -32, -38, -48, -52,
  116357. -52, -50, -48, -48, -51, -52, -54, -60,
  116358. -67, -67, -66, -68, -69, -73, -73, -76,
  116359. -80, -81, -81, -85, -85, -86, -88, -93,
  116360. -100, -110, -999, -999, -999, -999, -999, -999,
  116361. -999, -999, -999, -999, -999, -999, -999, -999},
  116362. { -16, -16, -16, -16, -16, -16, -16, -16,
  116363. -17, -19, -20, -22, -26, -28, -31, -40,
  116364. -47, -39, -39, -40, -42, -43, -47, -51,
  116365. -57, -52, -55, -55, -60, -58, -62, -63,
  116366. -70, -67, -69, -72, -73, -77, -80, -82,
  116367. -83, -87, -90, -94, -98, -104, -115, -999,
  116368. -999, -999, -999, -999, -999, -999, -999, -999},
  116369. { -8, -8, -8, -8, -8, -8, -8, -8,
  116370. -8, -8, -10, -11, -15, -19, -25, -30,
  116371. -34, -31, -30, -31, -29, -32, -35, -42,
  116372. -48, -42, -44, -46, -50, -50, -51, -52,
  116373. -59, -54, -55, -55, -58, -62, -63, -66,
  116374. -72, -73, -76, -75, -78, -80, -80, -81,
  116375. -84, -88, -90, -94, -98, -101, -106, -110}},
  116376. /* 88Hz */
  116377. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  116378. -66, -66, -66, -66, -66, -67, -67, -67,
  116379. -76, -72, -71, -74, -76, -76, -75, -78,
  116380. -79, -79, -81, -83, -86, -89, -93, -97,
  116381. -100, -105, -110, -999, -999, -999, -999, -999,
  116382. -999, -999, -999, -999, -999, -999, -999, -999,
  116383. -999, -999, -999, -999, -999, -999, -999, -999},
  116384. { -47, -47, -47, -47, -47, -47, -47, -47,
  116385. -47, -47, -47, -48, -51, -55, -59, -66,
  116386. -66, -66, -67, -66, -68, -69, -70, -74,
  116387. -79, -77, -77, -78, -80, -81, -82, -84,
  116388. -86, -88, -91, -95, -100, -108, -116, -999,
  116389. -999, -999, -999, -999, -999, -999, -999, -999,
  116390. -999, -999, -999, -999, -999, -999, -999, -999},
  116391. { -36, -36, -36, -36, -36, -36, -36, -36,
  116392. -36, -37, -37, -41, -44, -48, -51, -58,
  116393. -62, -60, -57, -59, -59, -60, -63, -65,
  116394. -72, -71, -70, -72, -74, -77, -76, -78,
  116395. -81, -81, -80, -83, -86, -91, -96, -100,
  116396. -105, -110, -999, -999, -999, -999, -999, -999,
  116397. -999, -999, -999, -999, -999, -999, -999, -999},
  116398. { -28, -28, -28, -28, -28, -28, -28, -28,
  116399. -28, -30, -32, -32, -33, -35, -41, -49,
  116400. -50, -49, -47, -48, -48, -52, -51, -57,
  116401. -65, -61, -59, -61, -64, -69, -70, -74,
  116402. -77, -77, -78, -81, -84, -85, -87, -90,
  116403. -92, -96, -100, -107, -112, -999, -999, -999,
  116404. -999, -999, -999, -999, -999, -999, -999, -999},
  116405. { -19, -19, -19, -19, -19, -19, -19, -19,
  116406. -20, -21, -23, -27, -30, -35, -36, -41,
  116407. -46, -44, -42, -40, -41, -41, -43, -48,
  116408. -55, -53, -52, -53, -56, -59, -58, -60,
  116409. -67, -66, -69, -71, -72, -75, -79, -81,
  116410. -84, -87, -90, -93, -97, -101, -107, -114,
  116411. -999, -999, -999, -999, -999, -999, -999, -999},
  116412. { -9, -9, -9, -9, -9, -9, -9, -9,
  116413. -11, -12, -12, -15, -16, -20, -23, -30,
  116414. -37, -34, -33, -34, -31, -32, -32, -38,
  116415. -47, -44, -41, -40, -47, -49, -46, -46,
  116416. -58, -50, -50, -54, -58, -62, -64, -67,
  116417. -67, -70, -72, -76, -79, -83, -87, -91,
  116418. -96, -100, -104, -110, -999, -999, -999, -999}},
  116419. /* 125 Hz */
  116420. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  116421. -62, -62, -63, -64, -66, -67, -66, -68,
  116422. -75, -72, -76, -75, -76, -78, -79, -82,
  116423. -84, -85, -90, -94, -101, -110, -999, -999,
  116424. -999, -999, -999, -999, -999, -999, -999, -999,
  116425. -999, -999, -999, -999, -999, -999, -999, -999,
  116426. -999, -999, -999, -999, -999, -999, -999, -999},
  116427. { -59, -59, -59, -59, -59, -59, -59, -59,
  116428. -59, -59, -59, -60, -60, -61, -63, -66,
  116429. -71, -68, -70, -70, -71, -72, -72, -75,
  116430. -81, -78, -79, -82, -83, -86, -90, -97,
  116431. -103, -113, -999, -999, -999, -999, -999, -999,
  116432. -999, -999, -999, -999, -999, -999, -999, -999,
  116433. -999, -999, -999, -999, -999, -999, -999, -999},
  116434. { -53, -53, -53, -53, -53, -53, -53, -53,
  116435. -53, -54, -55, -57, -56, -57, -55, -61,
  116436. -65, -60, -60, -62, -63, -63, -66, -68,
  116437. -74, -73, -75, -75, -78, -80, -80, -82,
  116438. -85, -90, -96, -101, -108, -999, -999, -999,
  116439. -999, -999, -999, -999, -999, -999, -999, -999,
  116440. -999, -999, -999, -999, -999, -999, -999, -999},
  116441. { -46, -46, -46, -46, -46, -46, -46, -46,
  116442. -46, -46, -47, -47, -47, -47, -48, -51,
  116443. -57, -51, -49, -50, -51, -53, -54, -59,
  116444. -66, -60, -62, -67, -67, -70, -72, -75,
  116445. -76, -78, -81, -85, -88, -94, -97, -104,
  116446. -112, -999, -999, -999, -999, -999, -999, -999,
  116447. -999, -999, -999, -999, -999, -999, -999, -999},
  116448. { -36, -36, -36, -36, -36, -36, -36, -36,
  116449. -39, -41, -42, -42, -39, -38, -41, -43,
  116450. -52, -44, -40, -39, -37, -37, -40, -47,
  116451. -54, -50, -48, -50, -55, -61, -59, -62,
  116452. -66, -66, -66, -69, -69, -73, -74, -74,
  116453. -75, -77, -79, -82, -87, -91, -95, -100,
  116454. -108, -115, -999, -999, -999, -999, -999, -999},
  116455. { -28, -26, -24, -22, -20, -20, -23, -29,
  116456. -30, -31, -28, -27, -28, -28, -28, -35,
  116457. -40, -33, -32, -29, -30, -30, -30, -37,
  116458. -45, -41, -37, -38, -45, -47, -47, -48,
  116459. -53, -49, -48, -50, -49, -49, -51, -52,
  116460. -58, -56, -57, -56, -60, -61, -62, -70,
  116461. -72, -74, -78, -83, -88, -93, -100, -106}},
  116462. /* 177 Hz */
  116463. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116464. -999, -110, -105, -100, -95, -91, -87, -83,
  116465. -80, -78, -76, -78, -78, -81, -83, -85,
  116466. -86, -85, -86, -87, -90, -97, -107, -999,
  116467. -999, -999, -999, -999, -999, -999, -999, -999,
  116468. -999, -999, -999, -999, -999, -999, -999, -999,
  116469. -999, -999, -999, -999, -999, -999, -999, -999},
  116470. {-999, -999, -999, -110, -105, -100, -95, -90,
  116471. -85, -81, -77, -73, -70, -67, -67, -68,
  116472. -75, -73, -70, -69, -70, -72, -75, -79,
  116473. -84, -83, -84, -86, -88, -89, -89, -93,
  116474. -98, -105, -112, -999, -999, -999, -999, -999,
  116475. -999, -999, -999, -999, -999, -999, -999, -999,
  116476. -999, -999, -999, -999, -999, -999, -999, -999},
  116477. {-105, -100, -95, -90, -85, -80, -76, -71,
  116478. -68, -68, -65, -63, -63, -62, -62, -64,
  116479. -65, -64, -61, -62, -63, -64, -66, -68,
  116480. -73, -73, -74, -75, -76, -81, -83, -85,
  116481. -88, -89, -92, -95, -100, -108, -999, -999,
  116482. -999, -999, -999, -999, -999, -999, -999, -999,
  116483. -999, -999, -999, -999, -999, -999, -999, -999},
  116484. { -80, -75, -71, -68, -65, -63, -62, -61,
  116485. -61, -61, -61, -59, -56, -57, -53, -50,
  116486. -58, -52, -50, -50, -52, -53, -54, -58,
  116487. -67, -63, -67, -68, -72, -75, -78, -80,
  116488. -81, -81, -82, -85, -89, -90, -93, -97,
  116489. -101, -107, -114, -999, -999, -999, -999, -999,
  116490. -999, -999, -999, -999, -999, -999, -999, -999},
  116491. { -65, -61, -59, -57, -56, -55, -55, -56,
  116492. -56, -57, -55, -53, -52, -47, -44, -44,
  116493. -50, -44, -41, -39, -39, -42, -40, -46,
  116494. -51, -49, -50, -53, -54, -63, -60, -61,
  116495. -62, -66, -66, -66, -70, -73, -74, -75,
  116496. -76, -75, -79, -85, -89, -91, -96, -102,
  116497. -110, -999, -999, -999, -999, -999, -999, -999},
  116498. { -52, -50, -49, -49, -48, -48, -48, -49,
  116499. -50, -50, -49, -46, -43, -39, -35, -33,
  116500. -38, -36, -32, -29, -32, -32, -32, -35,
  116501. -44, -39, -38, -38, -46, -50, -45, -46,
  116502. -53, -50, -50, -50, -54, -54, -53, -53,
  116503. -56, -57, -59, -66, -70, -72, -74, -79,
  116504. -83, -85, -90, -97, -114, -999, -999, -999}},
  116505. /* 250 Hz */
  116506. {{-999, -999, -999, -999, -999, -999, -110, -105,
  116507. -100, -95, -90, -86, -80, -75, -75, -79,
  116508. -80, -79, -80, -81, -82, -88, -95, -103,
  116509. -110, -999, -999, -999, -999, -999, -999, -999,
  116510. -999, -999, -999, -999, -999, -999, -999, -999,
  116511. -999, -999, -999, -999, -999, -999, -999, -999,
  116512. -999, -999, -999, -999, -999, -999, -999, -999},
  116513. {-999, -999, -999, -999, -108, -103, -98, -93,
  116514. -88, -83, -79, -78, -75, -71, -67, -68,
  116515. -73, -73, -72, -73, -75, -77, -80, -82,
  116516. -88, -93, -100, -107, -114, -999, -999, -999,
  116517. -999, -999, -999, -999, -999, -999, -999, -999,
  116518. -999, -999, -999, -999, -999, -999, -999, -999,
  116519. -999, -999, -999, -999, -999, -999, -999, -999},
  116520. {-999, -999, -999, -110, -105, -101, -96, -90,
  116521. -86, -81, -77, -73, -69, -66, -61, -62,
  116522. -66, -64, -62, -65, -66, -70, -72, -76,
  116523. -81, -80, -84, -90, -95, -102, -110, -999,
  116524. -999, -999, -999, -999, -999, -999, -999, -999,
  116525. -999, -999, -999, -999, -999, -999, -999, -999,
  116526. -999, -999, -999, -999, -999, -999, -999, -999},
  116527. {-999, -999, -999, -107, -103, -97, -92, -88,
  116528. -83, -79, -74, -70, -66, -59, -53, -58,
  116529. -62, -55, -54, -54, -54, -58, -61, -62,
  116530. -72, -70, -72, -75, -78, -80, -81, -80,
  116531. -83, -83, -88, -93, -100, -107, -115, -999,
  116532. -999, -999, -999, -999, -999, -999, -999, -999,
  116533. -999, -999, -999, -999, -999, -999, -999, -999},
  116534. {-999, -999, -999, -105, -100, -95, -90, -85,
  116535. -80, -75, -70, -66, -62, -56, -48, -44,
  116536. -48, -46, -46, -43, -46, -48, -48, -51,
  116537. -58, -58, -59, -60, -62, -62, -61, -61,
  116538. -65, -64, -65, -68, -70, -74, -75, -78,
  116539. -81, -86, -95, -110, -999, -999, -999, -999,
  116540. -999, -999, -999, -999, -999, -999, -999, -999},
  116541. {-999, -999, -105, -100, -95, -90, -85, -80,
  116542. -75, -70, -65, -61, -55, -49, -39, -33,
  116543. -40, -35, -32, -38, -40, -33, -35, -37,
  116544. -46, -41, -45, -44, -46, -42, -45, -46,
  116545. -52, -50, -50, -50, -54, -54, -55, -57,
  116546. -62, -64, -66, -68, -70, -76, -81, -90,
  116547. -100, -110, -999, -999, -999, -999, -999, -999}},
  116548. /* 354 hz */
  116549. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116550. -105, -98, -90, -85, -82, -83, -80, -78,
  116551. -84, -79, -80, -83, -87, -89, -91, -93,
  116552. -99, -106, -117, -999, -999, -999, -999, -999,
  116553. -999, -999, -999, -999, -999, -999, -999, -999,
  116554. -999, -999, -999, -999, -999, -999, -999, -999,
  116555. -999, -999, -999, -999, -999, -999, -999, -999},
  116556. {-999, -999, -999, -999, -999, -999, -999, -999,
  116557. -105, -98, -90, -85, -80, -75, -70, -68,
  116558. -74, -72, -74, -77, -80, -82, -85, -87,
  116559. -92, -89, -91, -95, -100, -106, -112, -999,
  116560. -999, -999, -999, -999, -999, -999, -999, -999,
  116561. -999, -999, -999, -999, -999, -999, -999, -999,
  116562. -999, -999, -999, -999, -999, -999, -999, -999},
  116563. {-999, -999, -999, -999, -999, -999, -999, -999,
  116564. -105, -98, -90, -83, -75, -71, -63, -64,
  116565. -67, -62, -64, -67, -70, -73, -77, -81,
  116566. -84, -83, -85, -89, -90, -93, -98, -104,
  116567. -109, -114, -999, -999, -999, -999, -999, -999,
  116568. -999, -999, -999, -999, -999, -999, -999, -999,
  116569. -999, -999, -999, -999, -999, -999, -999, -999},
  116570. {-999, -999, -999, -999, -999, -999, -999, -999,
  116571. -103, -96, -88, -81, -75, -68, -58, -54,
  116572. -56, -54, -56, -56, -58, -60, -63, -66,
  116573. -74, -69, -72, -72, -75, -74, -77, -81,
  116574. -81, -82, -84, -87, -93, -96, -99, -104,
  116575. -110, -999, -999, -999, -999, -999, -999, -999,
  116576. -999, -999, -999, -999, -999, -999, -999, -999},
  116577. {-999, -999, -999, -999, -999, -108, -102, -96,
  116578. -91, -85, -80, -74, -68, -60, -51, -46,
  116579. -48, -46, -43, -45, -47, -47, -49, -48,
  116580. -56, -53, -55, -58, -57, -63, -58, -60,
  116581. -66, -64, -67, -70, -70, -74, -77, -84,
  116582. -86, -89, -91, -93, -94, -101, -109, -118,
  116583. -999, -999, -999, -999, -999, -999, -999, -999},
  116584. {-999, -999, -999, -108, -103, -98, -93, -88,
  116585. -83, -78, -73, -68, -60, -53, -44, -35,
  116586. -38, -38, -34, -34, -36, -40, -41, -44,
  116587. -51, -45, -46, -47, -46, -54, -50, -49,
  116588. -50, -50, -50, -51, -54, -57, -58, -60,
  116589. -66, -66, -66, -64, -65, -68, -77, -82,
  116590. -87, -95, -110, -999, -999, -999, -999, -999}},
  116591. /* 500 Hz */
  116592. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116593. -107, -102, -97, -92, -87, -83, -78, -75,
  116594. -82, -79, -83, -85, -89, -92, -95, -98,
  116595. -101, -105, -109, -113, -999, -999, -999, -999,
  116596. -999, -999, -999, -999, -999, -999, -999, -999,
  116597. -999, -999, -999, -999, -999, -999, -999, -999,
  116598. -999, -999, -999, -999, -999, -999, -999, -999},
  116599. {-999, -999, -999, -999, -999, -999, -999, -106,
  116600. -100, -95, -90, -86, -81, -78, -74, -69,
  116601. -74, -74, -76, -79, -83, -84, -86, -89,
  116602. -92, -97, -93, -100, -103, -107, -110, -999,
  116603. -999, -999, -999, -999, -999, -999, -999, -999,
  116604. -999, -999, -999, -999, -999, -999, -999, -999,
  116605. -999, -999, -999, -999, -999, -999, -999, -999},
  116606. {-999, -999, -999, -999, -999, -999, -106, -100,
  116607. -95, -90, -87, -83, -80, -75, -69, -60,
  116608. -66, -66, -68, -70, -74, -78, -79, -81,
  116609. -81, -83, -84, -87, -93, -96, -99, -103,
  116610. -107, -110, -999, -999, -999, -999, -999, -999,
  116611. -999, -999, -999, -999, -999, -999, -999, -999,
  116612. -999, -999, -999, -999, -999, -999, -999, -999},
  116613. {-999, -999, -999, -999, -999, -108, -103, -98,
  116614. -93, -89, -85, -82, -78, -71, -62, -55,
  116615. -58, -58, -54, -54, -55, -59, -61, -62,
  116616. -70, -66, -66, -67, -70, -72, -75, -78,
  116617. -84, -84, -84, -88, -91, -90, -95, -98,
  116618. -102, -103, -106, -110, -999, -999, -999, -999,
  116619. -999, -999, -999, -999, -999, -999, -999, -999},
  116620. {-999, -999, -999, -999, -108, -103, -98, -94,
  116621. -90, -87, -82, -79, -73, -67, -58, -47,
  116622. -50, -45, -41, -45, -48, -44, -44, -49,
  116623. -54, -51, -48, -47, -49, -50, -51, -57,
  116624. -58, -60, -63, -69, -70, -69, -71, -74,
  116625. -78, -82, -90, -95, -101, -105, -110, -999,
  116626. -999, -999, -999, -999, -999, -999, -999, -999},
  116627. {-999, -999, -999, -105, -101, -97, -93, -90,
  116628. -85, -80, -77, -72, -65, -56, -48, -37,
  116629. -40, -36, -34, -40, -50, -47, -38, -41,
  116630. -47, -38, -35, -39, -38, -43, -40, -45,
  116631. -50, -45, -44, -47, -50, -55, -48, -48,
  116632. -52, -66, -70, -76, -82, -90, -97, -105,
  116633. -110, -999, -999, -999, -999, -999, -999, -999}},
  116634. /* 707 Hz */
  116635. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116636. -999, -108, -103, -98, -93, -86, -79, -76,
  116637. -83, -81, -85, -87, -89, -93, -98, -102,
  116638. -107, -112, -999, -999, -999, -999, -999, -999,
  116639. -999, -999, -999, -999, -999, -999, -999, -999,
  116640. -999, -999, -999, -999, -999, -999, -999, -999,
  116641. -999, -999, -999, -999, -999, -999, -999, -999},
  116642. {-999, -999, -999, -999, -999, -999, -999, -999,
  116643. -999, -108, -103, -98, -93, -86, -79, -71,
  116644. -77, -74, -77, -79, -81, -84, -85, -90,
  116645. -92, -93, -92, -98, -101, -108, -112, -999,
  116646. -999, -999, -999, -999, -999, -999, -999, -999,
  116647. -999, -999, -999, -999, -999, -999, -999, -999,
  116648. -999, -999, -999, -999, -999, -999, -999, -999},
  116649. {-999, -999, -999, -999, -999, -999, -999, -999,
  116650. -108, -103, -98, -93, -87, -78, -68, -65,
  116651. -66, -62, -65, -67, -70, -73, -75, -78,
  116652. -82, -82, -83, -84, -91, -93, -98, -102,
  116653. -106, -110, -999, -999, -999, -999, -999, -999,
  116654. -999, -999, -999, -999, -999, -999, -999, -999,
  116655. -999, -999, -999, -999, -999, -999, -999, -999},
  116656. {-999, -999, -999, -999, -999, -999, -999, -999,
  116657. -105, -100, -95, -90, -82, -74, -62, -57,
  116658. -58, -56, -51, -52, -52, -54, -54, -58,
  116659. -66, -59, -60, -63, -66, -69, -73, -79,
  116660. -83, -84, -80, -81, -81, -82, -88, -92,
  116661. -98, -105, -113, -999, -999, -999, -999, -999,
  116662. -999, -999, -999, -999, -999, -999, -999, -999},
  116663. {-999, -999, -999, -999, -999, -999, -999, -107,
  116664. -102, -97, -92, -84, -79, -69, -57, -47,
  116665. -52, -47, -44, -45, -50, -52, -42, -42,
  116666. -53, -43, -43, -48, -51, -56, -55, -52,
  116667. -57, -59, -61, -62, -67, -71, -78, -83,
  116668. -86, -94, -98, -103, -110, -999, -999, -999,
  116669. -999, -999, -999, -999, -999, -999, -999, -999},
  116670. {-999, -999, -999, -999, -999, -999, -105, -100,
  116671. -95, -90, -84, -78, -70, -61, -51, -41,
  116672. -40, -38, -40, -46, -52, -51, -41, -40,
  116673. -46, -40, -38, -38, -41, -46, -41, -46,
  116674. -47, -43, -43, -45, -41, -45, -56, -67,
  116675. -68, -83, -87, -90, -95, -102, -107, -113,
  116676. -999, -999, -999, -999, -999, -999, -999, -999}},
  116677. /* 1000 Hz */
  116678. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116679. -999, -109, -105, -101, -96, -91, -84, -77,
  116680. -82, -82, -85, -89, -94, -100, -106, -110,
  116681. -999, -999, -999, -999, -999, -999, -999, -999,
  116682. -999, -999, -999, -999, -999, -999, -999, -999,
  116683. -999, -999, -999, -999, -999, -999, -999, -999,
  116684. -999, -999, -999, -999, -999, -999, -999, -999},
  116685. {-999, -999, -999, -999, -999, -999, -999, -999,
  116686. -999, -106, -103, -98, -92, -85, -80, -71,
  116687. -75, -72, -76, -80, -84, -86, -89, -93,
  116688. -100, -107, -113, -999, -999, -999, -999, -999,
  116689. -999, -999, -999, -999, -999, -999, -999, -999,
  116690. -999, -999, -999, -999, -999, -999, -999, -999,
  116691. -999, -999, -999, -999, -999, -999, -999, -999},
  116692. {-999, -999, -999, -999, -999, -999, -999, -107,
  116693. -104, -101, -97, -92, -88, -84, -80, -64,
  116694. -66, -63, -64, -66, -69, -73, -77, -83,
  116695. -83, -86, -91, -98, -104, -111, -999, -999,
  116696. -999, -999, -999, -999, -999, -999, -999, -999,
  116697. -999, -999, -999, -999, -999, -999, -999, -999,
  116698. -999, -999, -999, -999, -999, -999, -999, -999},
  116699. {-999, -999, -999, -999, -999, -999, -999, -107,
  116700. -104, -101, -97, -92, -90, -84, -74, -57,
  116701. -58, -52, -55, -54, -50, -52, -50, -52,
  116702. -63, -62, -69, -76, -77, -78, -78, -79,
  116703. -82, -88, -94, -100, -106, -111, -999, -999,
  116704. -999, -999, -999, -999, -999, -999, -999, -999,
  116705. -999, -999, -999, -999, -999, -999, -999, -999},
  116706. {-999, -999, -999, -999, -999, -999, -106, -102,
  116707. -98, -95, -90, -85, -83, -78, -70, -50,
  116708. -50, -41, -44, -49, -47, -50, -50, -44,
  116709. -55, -46, -47, -48, -48, -54, -49, -49,
  116710. -58, -62, -71, -81, -87, -92, -97, -102,
  116711. -108, -114, -999, -999, -999, -999, -999, -999,
  116712. -999, -999, -999, -999, -999, -999, -999, -999},
  116713. {-999, -999, -999, -999, -999, -999, -106, -102,
  116714. -98, -95, -90, -85, -83, -78, -70, -45,
  116715. -43, -41, -47, -50, -51, -50, -49, -45,
  116716. -47, -41, -44, -41, -39, -43, -38, -37,
  116717. -40, -41, -44, -50, -58, -65, -73, -79,
  116718. -85, -92, -97, -101, -105, -109, -113, -999,
  116719. -999, -999, -999, -999, -999, -999, -999, -999}},
  116720. /* 1414 Hz */
  116721. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116722. -999, -999, -999, -107, -100, -95, -87, -81,
  116723. -85, -83, -88, -93, -100, -107, -114, -999,
  116724. -999, -999, -999, -999, -999, -999, -999, -999,
  116725. -999, -999, -999, -999, -999, -999, -999, -999,
  116726. -999, -999, -999, -999, -999, -999, -999, -999,
  116727. -999, -999, -999, -999, -999, -999, -999, -999},
  116728. {-999, -999, -999, -999, -999, -999, -999, -999,
  116729. -999, -999, -107, -101, -95, -88, -83, -76,
  116730. -73, -72, -79, -84, -90, -95, -100, -105,
  116731. -110, -115, -999, -999, -999, -999, -999, -999,
  116732. -999, -999, -999, -999, -999, -999, -999, -999,
  116733. -999, -999, -999, -999, -999, -999, -999, -999,
  116734. -999, -999, -999, -999, -999, -999, -999, -999},
  116735. {-999, -999, -999, -999, -999, -999, -999, -999,
  116736. -999, -999, -104, -98, -92, -87, -81, -70,
  116737. -65, -62, -67, -71, -74, -80, -85, -91,
  116738. -95, -99, -103, -108, -111, -114, -999, -999,
  116739. -999, -999, -999, -999, -999, -999, -999, -999,
  116740. -999, -999, -999, -999, -999, -999, -999, -999,
  116741. -999, -999, -999, -999, -999, -999, -999, -999},
  116742. {-999, -999, -999, -999, -999, -999, -999, -999,
  116743. -999, -999, -103, -97, -90, -85, -76, -60,
  116744. -56, -54, -60, -62, -61, -56, -63, -65,
  116745. -73, -74, -77, -75, -78, -81, -86, -87,
  116746. -88, -91, -94, -98, -103, -110, -999, -999,
  116747. -999, -999, -999, -999, -999, -999, -999, -999,
  116748. -999, -999, -999, -999, -999, -999, -999, -999},
  116749. {-999, -999, -999, -999, -999, -999, -999, -105,
  116750. -100, -97, -92, -86, -81, -79, -70, -57,
  116751. -51, -47, -51, -58, -60, -56, -53, -50,
  116752. -58, -52, -50, -50, -53, -55, -64, -69,
  116753. -71, -85, -82, -78, -81, -85, -95, -102,
  116754. -112, -999, -999, -999, -999, -999, -999, -999,
  116755. -999, -999, -999, -999, -999, -999, -999, -999},
  116756. {-999, -999, -999, -999, -999, -999, -999, -105,
  116757. -100, -97, -92, -85, -83, -79, -72, -49,
  116758. -40, -43, -43, -54, -56, -51, -50, -40,
  116759. -43, -38, -36, -35, -37, -38, -37, -44,
  116760. -54, -60, -57, -60, -70, -75, -84, -92,
  116761. -103, -112, -999, -999, -999, -999, -999, -999,
  116762. -999, -999, -999, -999, -999, -999, -999, -999}},
  116763. /* 2000 Hz */
  116764. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116765. -999, -999, -999, -110, -102, -95, -89, -82,
  116766. -83, -84, -90, -92, -99, -107, -113, -999,
  116767. -999, -999, -999, -999, -999, -999, -999, -999,
  116768. -999, -999, -999, -999, -999, -999, -999, -999,
  116769. -999, -999, -999, -999, -999, -999, -999, -999,
  116770. -999, -999, -999, -999, -999, -999, -999, -999},
  116771. {-999, -999, -999, -999, -999, -999, -999, -999,
  116772. -999, -999, -107, -101, -95, -89, -83, -72,
  116773. -74, -78, -85, -88, -88, -90, -92, -98,
  116774. -105, -111, -999, -999, -999, -999, -999, -999,
  116775. -999, -999, -999, -999, -999, -999, -999, -999,
  116776. -999, -999, -999, -999, -999, -999, -999, -999,
  116777. -999, -999, -999, -999, -999, -999, -999, -999},
  116778. {-999, -999, -999, -999, -999, -999, -999, -999,
  116779. -999, -109, -103, -97, -93, -87, -81, -70,
  116780. -70, -67, -75, -73, -76, -79, -81, -83,
  116781. -88, -89, -97, -103, -110, -999, -999, -999,
  116782. -999, -999, -999, -999, -999, -999, -999, -999,
  116783. -999, -999, -999, -999, -999, -999, -999, -999,
  116784. -999, -999, -999, -999, -999, -999, -999, -999},
  116785. {-999, -999, -999, -999, -999, -999, -999, -999,
  116786. -999, -107, -100, -94, -88, -83, -75, -63,
  116787. -59, -59, -63, -66, -60, -62, -67, -67,
  116788. -77, -76, -81, -88, -86, -92, -96, -102,
  116789. -109, -116, -999, -999, -999, -999, -999, -999,
  116790. -999, -999, -999, -999, -999, -999, -999, -999,
  116791. -999, -999, -999, -999, -999, -999, -999, -999},
  116792. {-999, -999, -999, -999, -999, -999, -999, -999,
  116793. -999, -105, -98, -92, -86, -81, -73, -56,
  116794. -52, -47, -55, -60, -58, -52, -51, -45,
  116795. -49, -50, -53, -54, -61, -71, -70, -69,
  116796. -78, -79, -87, -90, -96, -104, -112, -999,
  116797. -999, -999, -999, -999, -999, -999, -999, -999,
  116798. -999, -999, -999, -999, -999, -999, -999, -999},
  116799. {-999, -999, -999, -999, -999, -999, -999, -999,
  116800. -999, -103, -96, -90, -86, -78, -70, -51,
  116801. -42, -47, -48, -55, -54, -54, -53, -42,
  116802. -35, -28, -33, -38, -37, -44, -47, -49,
  116803. -54, -63, -68, -78, -82, -89, -94, -99,
  116804. -104, -109, -114, -999, -999, -999, -999, -999,
  116805. -999, -999, -999, -999, -999, -999, -999, -999}},
  116806. /* 2828 Hz */
  116807. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116808. -999, -999, -999, -999, -110, -100, -90, -79,
  116809. -85, -81, -82, -82, -89, -94, -99, -103,
  116810. -109, -115, -999, -999, -999, -999, -999, -999,
  116811. -999, -999, -999, -999, -999, -999, -999, -999,
  116812. -999, -999, -999, -999, -999, -999, -999, -999,
  116813. -999, -999, -999, -999, -999, -999, -999, -999},
  116814. {-999, -999, -999, -999, -999, -999, -999, -999,
  116815. -999, -999, -999, -999, -105, -97, -85, -72,
  116816. -74, -70, -70, -70, -76, -85, -91, -93,
  116817. -97, -103, -109, -115, -999, -999, -999, -999,
  116818. -999, -999, -999, -999, -999, -999, -999, -999,
  116819. -999, -999, -999, -999, -999, -999, -999, -999,
  116820. -999, -999, -999, -999, -999, -999, -999, -999},
  116821. {-999, -999, -999, -999, -999, -999, -999, -999,
  116822. -999, -999, -999, -999, -112, -93, -81, -68,
  116823. -62, -60, -60, -57, -63, -70, -77, -82,
  116824. -90, -93, -98, -104, -109, -113, -999, -999,
  116825. -999, -999, -999, -999, -999, -999, -999, -999,
  116826. -999, -999, -999, -999, -999, -999, -999, -999,
  116827. -999, -999, -999, -999, -999, -999, -999, -999},
  116828. {-999, -999, -999, -999, -999, -999, -999, -999,
  116829. -999, -999, -999, -113, -100, -93, -84, -63,
  116830. -58, -48, -53, -54, -52, -52, -57, -64,
  116831. -66, -76, -83, -81, -85, -85, -90, -95,
  116832. -98, -101, -103, -106, -108, -111, -999, -999,
  116833. -999, -999, -999, -999, -999, -999, -999, -999,
  116834. -999, -999, -999, -999, -999, -999, -999, -999},
  116835. {-999, -999, -999, -999, -999, -999, -999, -999,
  116836. -999, -999, -999, -105, -95, -86, -74, -53,
  116837. -50, -38, -43, -49, -43, -42, -39, -39,
  116838. -46, -52, -57, -56, -72, -69, -74, -81,
  116839. -87, -92, -94, -97, -99, -102, -105, -108,
  116840. -999, -999, -999, -999, -999, -999, -999, -999,
  116841. -999, -999, -999, -999, -999, -999, -999, -999},
  116842. {-999, -999, -999, -999, -999, -999, -999, -999,
  116843. -999, -999, -108, -99, -90, -76, -66, -45,
  116844. -43, -41, -44, -47, -43, -47, -40, -30,
  116845. -31, -31, -39, -33, -40, -41, -43, -53,
  116846. -59, -70, -73, -77, -79, -82, -84, -87,
  116847. -999, -999, -999, -999, -999, -999, -999, -999,
  116848. -999, -999, -999, -999, -999, -999, -999, -999}},
  116849. /* 4000 Hz */
  116850. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116851. -999, -999, -999, -999, -999, -110, -91, -76,
  116852. -75, -85, -93, -98, -104, -110, -999, -999,
  116853. -999, -999, -999, -999, -999, -999, -999, -999,
  116854. -999, -999, -999, -999, -999, -999, -999, -999,
  116855. -999, -999, -999, -999, -999, -999, -999, -999,
  116856. -999, -999, -999, -999, -999, -999, -999, -999},
  116857. {-999, -999, -999, -999, -999, -999, -999, -999,
  116858. -999, -999, -999, -999, -999, -110, -91, -70,
  116859. -70, -75, -86, -89, -94, -98, -101, -106,
  116860. -110, -999, -999, -999, -999, -999, -999, -999,
  116861. -999, -999, -999, -999, -999, -999, -999, -999,
  116862. -999, -999, -999, -999, -999, -999, -999, -999,
  116863. -999, -999, -999, -999, -999, -999, -999, -999},
  116864. {-999, -999, -999, -999, -999, -999, -999, -999,
  116865. -999, -999, -999, -999, -110, -95, -80, -60,
  116866. -65, -64, -74, -83, -88, -91, -95, -99,
  116867. -103, -107, -110, -999, -999, -999, -999, -999,
  116868. -999, -999, -999, -999, -999, -999, -999, -999,
  116869. -999, -999, -999, -999, -999, -999, -999, -999,
  116870. -999, -999, -999, -999, -999, -999, -999, -999},
  116871. {-999, -999, -999, -999, -999, -999, -999, -999,
  116872. -999, -999, -999, -999, -110, -95, -80, -58,
  116873. -55, -49, -66, -68, -71, -78, -78, -80,
  116874. -88, -85, -89, -97, -100, -105, -110, -999,
  116875. -999, -999, -999, -999, -999, -999, -999, -999,
  116876. -999, -999, -999, -999, -999, -999, -999, -999,
  116877. -999, -999, -999, -999, -999, -999, -999, -999},
  116878. {-999, -999, -999, -999, -999, -999, -999, -999,
  116879. -999, -999, -999, -999, -110, -95, -80, -53,
  116880. -52, -41, -59, -59, -49, -58, -56, -63,
  116881. -86, -79, -90, -93, -98, -103, -107, -112,
  116882. -999, -999, -999, -999, -999, -999, -999, -999,
  116883. -999, -999, -999, -999, -999, -999, -999, -999,
  116884. -999, -999, -999, -999, -999, -999, -999, -999},
  116885. {-999, -999, -999, -999, -999, -999, -999, -999,
  116886. -999, -999, -999, -110, -97, -91, -73, -45,
  116887. -40, -33, -53, -61, -49, -54, -50, -50,
  116888. -60, -52, -67, -74, -81, -92, -96, -100,
  116889. -105, -110, -999, -999, -999, -999, -999, -999,
  116890. -999, -999, -999, -999, -999, -999, -999, -999,
  116891. -999, -999, -999, -999, -999, -999, -999, -999}},
  116892. /* 5657 Hz */
  116893. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116894. -999, -999, -999, -113, -106, -99, -92, -77,
  116895. -80, -88, -97, -106, -115, -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, -999, -999, -999, -999,
  116899. -999, -999, -999, -999, -999, -999, -999, -999},
  116900. {-999, -999, -999, -999, -999, -999, -999, -999,
  116901. -999, -999, -116, -109, -102, -95, -89, -74,
  116902. -72, -88, -87, -95, -102, -109, -116, -999,
  116903. -999, -999, -999, -999, -999, -999, -999, -999,
  116904. -999, -999, -999, -999, -999, -999, -999, -999,
  116905. -999, -999, -999, -999, -999, -999, -999, -999,
  116906. -999, -999, -999, -999, -999, -999, -999, -999},
  116907. {-999, -999, -999, -999, -999, -999, -999, -999,
  116908. -999, -999, -116, -109, -102, -95, -89, -75,
  116909. -66, -74, -77, -78, -86, -87, -90, -96,
  116910. -105, -115, -999, -999, -999, -999, -999, -999,
  116911. -999, -999, -999, -999, -999, -999, -999, -999,
  116912. -999, -999, -999, -999, -999, -999, -999, -999,
  116913. -999, -999, -999, -999, -999, -999, -999, -999},
  116914. {-999, -999, -999, -999, -999, -999, -999, -999,
  116915. -999, -999, -115, -108, -101, -94, -88, -66,
  116916. -56, -61, -70, -65, -78, -72, -83, -84,
  116917. -93, -98, -105, -110, -999, -999, -999, -999,
  116918. -999, -999, -999, -999, -999, -999, -999, -999,
  116919. -999, -999, -999, -999, -999, -999, -999, -999,
  116920. -999, -999, -999, -999, -999, -999, -999, -999},
  116921. {-999, -999, -999, -999, -999, -999, -999, -999,
  116922. -999, -999, -110, -105, -95, -89, -82, -57,
  116923. -52, -52, -59, -56, -59, -58, -69, -67,
  116924. -88, -82, -82, -89, -94, -100, -108, -999,
  116925. -999, -999, -999, -999, -999, -999, -999, -999,
  116926. -999, -999, -999, -999, -999, -999, -999, -999,
  116927. -999, -999, -999, -999, -999, -999, -999, -999},
  116928. {-999, -999, -999, -999, -999, -999, -999, -999,
  116929. -999, -110, -101, -96, -90, -83, -77, -54,
  116930. -43, -38, -50, -48, -52, -48, -42, -42,
  116931. -51, -52, -53, -59, -65, -71, -78, -85,
  116932. -95, -999, -999, -999, -999, -999, -999, -999,
  116933. -999, -999, -999, -999, -999, -999, -999, -999,
  116934. -999, -999, -999, -999, -999, -999, -999, -999}},
  116935. /* 8000 Hz */
  116936. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116937. -999, -999, -999, -999, -120, -105, -86, -68,
  116938. -78, -79, -90, -100, -110, -999, -999, -999,
  116939. -999, -999, -999, -999, -999, -999, -999, -999,
  116940. -999, -999, -999, -999, -999, -999, -999, -999,
  116941. -999, -999, -999, -999, -999, -999, -999, -999,
  116942. -999, -999, -999, -999, -999, -999, -999, -999},
  116943. {-999, -999, -999, -999, -999, -999, -999, -999,
  116944. -999, -999, -999, -999, -120, -105, -86, -66,
  116945. -73, -77, -88, -96, -105, -115, -999, -999,
  116946. -999, -999, -999, -999, -999, -999, -999, -999,
  116947. -999, -999, -999, -999, -999, -999, -999, -999,
  116948. -999, -999, -999, -999, -999, -999, -999, -999,
  116949. -999, -999, -999, -999, -999, -999, -999, -999},
  116950. {-999, -999, -999, -999, -999, -999, -999, -999,
  116951. -999, -999, -999, -120, -105, -92, -80, -61,
  116952. -64, -68, -80, -87, -92, -100, -110, -999,
  116953. -999, -999, -999, -999, -999, -999, -999, -999,
  116954. -999, -999, -999, -999, -999, -999, -999, -999,
  116955. -999, -999, -999, -999, -999, -999, -999, -999,
  116956. -999, -999, -999, -999, -999, -999, -999, -999},
  116957. {-999, -999, -999, -999, -999, -999, -999, -999,
  116958. -999, -999, -999, -120, -104, -91, -79, -52,
  116959. -60, -54, -64, -69, -77, -80, -82, -84,
  116960. -85, -87, -88, -90, -999, -999, -999, -999,
  116961. -999, -999, -999, -999, -999, -999, -999, -999,
  116962. -999, -999, -999, -999, -999, -999, -999, -999,
  116963. -999, -999, -999, -999, -999, -999, -999, -999},
  116964. {-999, -999, -999, -999, -999, -999, -999, -999,
  116965. -999, -999, -999, -118, -100, -87, -77, -49,
  116966. -50, -44, -58, -61, -61, -67, -65, -62,
  116967. -62, -62, -65, -68, -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, -999, -999, -999, -999},
  116971. {-999, -999, -999, -999, -999, -999, -999, -999,
  116972. -999, -999, -999, -115, -98, -84, -62, -49,
  116973. -44, -38, -46, -49, -49, -46, -39, -37,
  116974. -39, -40, -42, -43, -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, -999, -999, -999, -999, -999}},
  116978. /* 11314 Hz */
  116979. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116980. -999, -999, -999, -999, -999, -110, -88, -74,
  116981. -77, -82, -82, -85, -90, -94, -99, -104,
  116982. -999, -999, -999, -999, -999, -999, -999, -999,
  116983. -999, -999, -999, -999, -999, -999, -999, -999,
  116984. -999, -999, -999, -999, -999, -999, -999, -999,
  116985. -999, -999, -999, -999, -999, -999, -999, -999},
  116986. {-999, -999, -999, -999, -999, -999, -999, -999,
  116987. -999, -999, -999, -999, -999, -110, -88, -66,
  116988. -70, -81, -80, -81, -84, -88, -91, -93,
  116989. -999, -999, -999, -999, -999, -999, -999, -999,
  116990. -999, -999, -999, -999, -999, -999, -999, -999,
  116991. -999, -999, -999, -999, -999, -999, -999, -999,
  116992. -999, -999, -999, -999, -999, -999, -999, -999},
  116993. {-999, -999, -999, -999, -999, -999, -999, -999,
  116994. -999, -999, -999, -999, -999, -110, -88, -61,
  116995. -63, -70, -71, -74, -77, -80, -83, -85,
  116996. -999, -999, -999, -999, -999, -999, -999, -999,
  116997. -999, -999, -999, -999, -999, -999, -999, -999,
  116998. -999, -999, -999, -999, -999, -999, -999, -999,
  116999. -999, -999, -999, -999, -999, -999, -999, -999},
  117000. {-999, -999, -999, -999, -999, -999, -999, -999,
  117001. -999, -999, -999, -999, -999, -110, -86, -62,
  117002. -63, -62, -62, -58, -52, -50, -50, -52,
  117003. -54, -999, -999, -999, -999, -999, -999, -999,
  117004. -999, -999, -999, -999, -999, -999, -999, -999,
  117005. -999, -999, -999, -999, -999, -999, -999, -999,
  117006. -999, -999, -999, -999, -999, -999, -999, -999},
  117007. {-999, -999, -999, -999, -999, -999, -999, -999,
  117008. -999, -999, -999, -999, -118, -108, -84, -53,
  117009. -50, -50, -50, -55, -47, -45, -40, -40,
  117010. -40, -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, -999, -999, -999},
  117014. {-999, -999, -999, -999, -999, -999, -999, -999,
  117015. -999, -999, -999, -999, -118, -100, -73, -43,
  117016. -37, -42, -43, -53, -38, -37, -35, -35,
  117017. -38, -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, -999, -999, -999}},
  117021. /* 16000 Hz */
  117022. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117023. -999, -999, -999, -110, -100, -91, -84, -74,
  117024. -80, -80, -80, -80, -80, -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, -999, -999, -999,
  117028. -999, -999, -999, -999, -999, -999, -999, -999},
  117029. {-999, -999, -999, -999, -999, -999, -999, -999,
  117030. -999, -999, -999, -110, -100, -91, -84, -74,
  117031. -68, -68, -68, -68, -68, -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, -999, -999, -999, -999,
  117035. -999, -999, -999, -999, -999, -999, -999, -999},
  117036. {-999, -999, -999, -999, -999, -999, -999, -999,
  117037. -999, -999, -999, -110, -100, -86, -78, -70,
  117038. -60, -45, -30, -21, -999, -999, -999, -999,
  117039. -999, -999, -999, -999, -999, -999, -999, -999,
  117040. -999, -999, -999, -999, -999, -999, -999, -999,
  117041. -999, -999, -999, -999, -999, -999, -999, -999,
  117042. -999, -999, -999, -999, -999, -999, -999, -999},
  117043. {-999, -999, -999, -999, -999, -999, -999, -999,
  117044. -999, -999, -999, -110, -100, -87, -78, -67,
  117045. -48, -38, -29, -21, -999, -999, -999, -999,
  117046. -999, -999, -999, -999, -999, -999, -999, -999,
  117047. -999, -999, -999, -999, -999, -999, -999, -999,
  117048. -999, -999, -999, -999, -999, -999, -999, -999,
  117049. -999, -999, -999, -999, -999, -999, -999, -999},
  117050. {-999, -999, -999, -999, -999, -999, -999, -999,
  117051. -999, -999, -999, -110, -100, -86, -69, -56,
  117052. -45, -35, -33, -29, -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, -999, -999, -999, -999, -999},
  117057. {-999, -999, -999, -999, -999, -999, -999, -999,
  117058. -999, -999, -999, -110, -100, -83, -71, -48,
  117059. -27, -38, -37, -34, -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, -999, -999, -999, -999, -999}}
  117064. };
  117065. #endif
  117066. /*** End of inlined file: masking.h ***/
  117067. #define NEGINF -9999.f
  117068. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  117069. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  117070. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  117071. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117072. vorbis_info_psy_global *gi=&ci->psy_g_param;
  117073. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  117074. look->channels=vi->channels;
  117075. look->ampmax=-9999.;
  117076. look->gi=gi;
  117077. return(look);
  117078. }
  117079. void _vp_global_free(vorbis_look_psy_global *look){
  117080. if(look){
  117081. memset(look,0,sizeof(*look));
  117082. _ogg_free(look);
  117083. }
  117084. }
  117085. void _vi_gpsy_free(vorbis_info_psy_global *i){
  117086. if(i){
  117087. memset(i,0,sizeof(*i));
  117088. _ogg_free(i);
  117089. }
  117090. }
  117091. void _vi_psy_free(vorbis_info_psy *i){
  117092. if(i){
  117093. memset(i,0,sizeof(*i));
  117094. _ogg_free(i);
  117095. }
  117096. }
  117097. static void min_curve(float *c,
  117098. float *c2){
  117099. int i;
  117100. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  117101. }
  117102. static void max_curve(float *c,
  117103. float *c2){
  117104. int i;
  117105. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  117106. }
  117107. static void attenuate_curve(float *c,float att){
  117108. int i;
  117109. for(i=0;i<EHMER_MAX;i++)
  117110. c[i]+=att;
  117111. }
  117112. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  117113. float center_boost, float center_decay_rate){
  117114. int i,j,k,m;
  117115. float ath[EHMER_MAX];
  117116. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  117117. float athc[P_LEVELS][EHMER_MAX];
  117118. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  117119. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  117120. memset(workc,0,sizeof(workc));
  117121. for(i=0;i<P_BANDS;i++){
  117122. /* we add back in the ATH to avoid low level curves falling off to
  117123. -infinity and unnecessarily cutting off high level curves in the
  117124. curve limiting (last step). */
  117125. /* A half-band's settings must be valid over the whole band, and
  117126. it's better to mask too little than too much */
  117127. int ath_offset=i*4;
  117128. for(j=0;j<EHMER_MAX;j++){
  117129. float min=999.;
  117130. for(k=0;k<4;k++)
  117131. if(j+k+ath_offset<MAX_ATH){
  117132. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  117133. }else{
  117134. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  117135. }
  117136. ath[j]=min;
  117137. }
  117138. /* copy curves into working space, replicate the 50dB curve to 30
  117139. and 40, replicate the 100dB curve to 110 */
  117140. for(j=0;j<6;j++)
  117141. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  117142. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  117143. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  117144. /* apply centered curve boost/decay */
  117145. for(j=0;j<P_LEVELS;j++){
  117146. for(k=0;k<EHMER_MAX;k++){
  117147. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  117148. if(adj<0. && center_boost>0)adj=0.;
  117149. if(adj>0. && center_boost<0)adj=0.;
  117150. workc[i][j][k]+=adj;
  117151. }
  117152. }
  117153. /* normalize curves so the driving amplitude is 0dB */
  117154. /* make temp curves with the ATH overlayed */
  117155. for(j=0;j<P_LEVELS;j++){
  117156. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  117157. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  117158. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  117159. max_curve(athc[j],workc[i][j]);
  117160. }
  117161. /* Now limit the louder curves.
  117162. the idea is this: We don't know what the playback attenuation
  117163. will be; 0dB SL moves every time the user twiddles the volume
  117164. knob. So that means we have to use a single 'most pessimal' curve
  117165. for all masking amplitudes, right? Wrong. The *loudest* sound
  117166. can be in (we assume) a range of ...+100dB] SL. However, sounds
  117167. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  117168. etc... */
  117169. for(j=1;j<P_LEVELS;j++){
  117170. min_curve(athc[j],athc[j-1]);
  117171. min_curve(workc[i][j],athc[j]);
  117172. }
  117173. }
  117174. for(i=0;i<P_BANDS;i++){
  117175. int hi_curve,lo_curve,bin;
  117176. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  117177. /* low frequency curves are measured with greater resolution than
  117178. the MDCT/FFT will actually give us; we want the curve applied
  117179. to the tone data to be pessimistic and thus apply the minimum
  117180. masking possible for a given bin. That means that a single bin
  117181. could span more than one octave and that the curve will be a
  117182. composite of multiple octaves. It also may mean that a single
  117183. bin may span > an eighth of an octave and that the eighth
  117184. octave values may also be composited. */
  117185. /* which octave curves will we be compositing? */
  117186. bin=floor(fromOC(i*.5)/binHz);
  117187. lo_curve= ceil(toOC(bin*binHz+1)*2);
  117188. hi_curve= floor(toOC((bin+1)*binHz)*2);
  117189. if(lo_curve>i)lo_curve=i;
  117190. if(lo_curve<0)lo_curve=0;
  117191. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  117192. for(m=0;m<P_LEVELS;m++){
  117193. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  117194. for(j=0;j<n;j++)brute_buffer[j]=999.;
  117195. /* render the curve into bins, then pull values back into curve.
  117196. The point is that any inherent subsampling aliasing results in
  117197. a safe minimum */
  117198. for(k=lo_curve;k<=hi_curve;k++){
  117199. int l=0;
  117200. for(j=0;j<EHMER_MAX;j++){
  117201. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  117202. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  117203. if(lo_bin<0)lo_bin=0;
  117204. if(lo_bin>n)lo_bin=n;
  117205. if(lo_bin<l)l=lo_bin;
  117206. if(hi_bin<0)hi_bin=0;
  117207. if(hi_bin>n)hi_bin=n;
  117208. for(;l<hi_bin && l<n;l++)
  117209. if(brute_buffer[l]>workc[k][m][j])
  117210. brute_buffer[l]=workc[k][m][j];
  117211. }
  117212. for(;l<n;l++)
  117213. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  117214. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  117215. }
  117216. /* be equally paranoid about being valid up to next half ocatve */
  117217. if(i+1<P_BANDS){
  117218. int l=0;
  117219. k=i+1;
  117220. for(j=0;j<EHMER_MAX;j++){
  117221. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  117222. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  117223. if(lo_bin<0)lo_bin=0;
  117224. if(lo_bin>n)lo_bin=n;
  117225. if(lo_bin<l)l=lo_bin;
  117226. if(hi_bin<0)hi_bin=0;
  117227. if(hi_bin>n)hi_bin=n;
  117228. for(;l<hi_bin && l<n;l++)
  117229. if(brute_buffer[l]>workc[k][m][j])
  117230. brute_buffer[l]=workc[k][m][j];
  117231. }
  117232. for(;l<n;l++)
  117233. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  117234. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  117235. }
  117236. for(j=0;j<EHMER_MAX;j++){
  117237. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  117238. if(bin<0){
  117239. ret[i][m][j+2]=-999.;
  117240. }else{
  117241. if(bin>=n){
  117242. ret[i][m][j+2]=-999.;
  117243. }else{
  117244. ret[i][m][j+2]=brute_buffer[bin];
  117245. }
  117246. }
  117247. }
  117248. /* add fenceposts */
  117249. for(j=0;j<EHMER_OFFSET;j++)
  117250. if(ret[i][m][j+2]>-200.f)break;
  117251. ret[i][m][0]=j;
  117252. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  117253. if(ret[i][m][j+2]>-200.f)
  117254. break;
  117255. ret[i][m][1]=j;
  117256. }
  117257. }
  117258. return(ret);
  117259. }
  117260. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  117261. vorbis_info_psy_global *gi,int n,long rate){
  117262. long i,j,lo=-99,hi=1;
  117263. long maxoc;
  117264. memset(p,0,sizeof(*p));
  117265. p->eighth_octave_lines=gi->eighth_octave_lines;
  117266. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  117267. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  117268. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  117269. p->total_octave_lines=maxoc-p->firstoc+1;
  117270. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  117271. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  117272. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  117273. p->vi=vi;
  117274. p->n=n;
  117275. p->rate=rate;
  117276. /* AoTuV HF weighting */
  117277. p->m_val = 1.;
  117278. if(rate < 26000) p->m_val = 0;
  117279. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  117280. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  117281. /* set up the lookups for a given blocksize and sample rate */
  117282. for(i=0,j=0;i<MAX_ATH-1;i++){
  117283. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  117284. float base=ATH[i];
  117285. if(j<endpos){
  117286. float delta=(ATH[i+1]-base)/(endpos-j);
  117287. for(;j<endpos && j<n;j++){
  117288. p->ath[j]=base+100.;
  117289. base+=delta;
  117290. }
  117291. }
  117292. }
  117293. for(i=0;i<n;i++){
  117294. float bark=toBARK(rate/(2*n)*i);
  117295. for(;lo+vi->noisewindowlomin<i &&
  117296. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  117297. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  117298. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  117299. p->bark[i]=((lo-1)<<16)+(hi-1);
  117300. }
  117301. for(i=0;i<n;i++)
  117302. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  117303. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  117304. vi->tone_centerboost,vi->tone_decay);
  117305. /* set up rolling noise median */
  117306. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  117307. for(i=0;i<P_NOISECURVES;i++)
  117308. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  117309. for(i=0;i<n;i++){
  117310. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  117311. int inthalfoc;
  117312. float del;
  117313. if(halfoc<0)halfoc=0;
  117314. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  117315. inthalfoc=(int)halfoc;
  117316. del=halfoc-inthalfoc;
  117317. for(j=0;j<P_NOISECURVES;j++)
  117318. p->noiseoffset[j][i]=
  117319. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  117320. p->vi->noiseoff[j][inthalfoc+1]*del;
  117321. }
  117322. #if 0
  117323. {
  117324. static int ls=0;
  117325. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  117326. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  117327. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  117328. }
  117329. #endif
  117330. }
  117331. void _vp_psy_clear(vorbis_look_psy *p){
  117332. int i,j;
  117333. if(p){
  117334. if(p->ath)_ogg_free(p->ath);
  117335. if(p->octave)_ogg_free(p->octave);
  117336. if(p->bark)_ogg_free(p->bark);
  117337. if(p->tonecurves){
  117338. for(i=0;i<P_BANDS;i++){
  117339. for(j=0;j<P_LEVELS;j++){
  117340. _ogg_free(p->tonecurves[i][j]);
  117341. }
  117342. _ogg_free(p->tonecurves[i]);
  117343. }
  117344. _ogg_free(p->tonecurves);
  117345. }
  117346. if(p->noiseoffset){
  117347. for(i=0;i<P_NOISECURVES;i++){
  117348. _ogg_free(p->noiseoffset[i]);
  117349. }
  117350. _ogg_free(p->noiseoffset);
  117351. }
  117352. memset(p,0,sizeof(*p));
  117353. }
  117354. }
  117355. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  117356. static void seed_curve(float *seed,
  117357. const float **curves,
  117358. float amp,
  117359. int oc, int n,
  117360. int linesper,float dBoffset){
  117361. int i,post1;
  117362. int seedptr;
  117363. const float *posts,*curve;
  117364. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  117365. choice=max(choice,0);
  117366. choice=min(choice,P_LEVELS-1);
  117367. posts=curves[choice];
  117368. curve=posts+2;
  117369. post1=(int)posts[1];
  117370. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  117371. for(i=posts[0];i<post1;i++){
  117372. if(seedptr>0){
  117373. float lin=amp+curve[i];
  117374. if(seed[seedptr]<lin)seed[seedptr]=lin;
  117375. }
  117376. seedptr+=linesper;
  117377. if(seedptr>=n)break;
  117378. }
  117379. }
  117380. static void seed_loop(vorbis_look_psy *p,
  117381. const float ***curves,
  117382. const float *f,
  117383. const float *flr,
  117384. float *seed,
  117385. float specmax){
  117386. vorbis_info_psy *vi=p->vi;
  117387. long n=p->n,i;
  117388. float dBoffset=vi->max_curve_dB-specmax;
  117389. /* prime the working vector with peak values */
  117390. for(i=0;i<n;i++){
  117391. float max=f[i];
  117392. long oc=p->octave[i];
  117393. while(i+1<n && p->octave[i+1]==oc){
  117394. i++;
  117395. if(f[i]>max)max=f[i];
  117396. }
  117397. if(max+6.f>flr[i]){
  117398. oc=oc>>p->shiftoc;
  117399. if(oc>=P_BANDS)oc=P_BANDS-1;
  117400. if(oc<0)oc=0;
  117401. seed_curve(seed,
  117402. curves[oc],
  117403. max,
  117404. p->octave[i]-p->firstoc,
  117405. p->total_octave_lines,
  117406. p->eighth_octave_lines,
  117407. dBoffset);
  117408. }
  117409. }
  117410. }
  117411. static void seed_chase(float *seeds, int linesper, long n){
  117412. long *posstack=(long*)alloca(n*sizeof(*posstack));
  117413. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  117414. long stack=0;
  117415. long pos=0;
  117416. long i;
  117417. for(i=0;i<n;i++){
  117418. if(stack<2){
  117419. posstack[stack]=i;
  117420. ampstack[stack++]=seeds[i];
  117421. }else{
  117422. while(1){
  117423. if(seeds[i]<ampstack[stack-1]){
  117424. posstack[stack]=i;
  117425. ampstack[stack++]=seeds[i];
  117426. break;
  117427. }else{
  117428. if(i<posstack[stack-1]+linesper){
  117429. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  117430. i<posstack[stack-2]+linesper){
  117431. /* we completely overlap, making stack-1 irrelevant. pop it */
  117432. stack--;
  117433. continue;
  117434. }
  117435. }
  117436. posstack[stack]=i;
  117437. ampstack[stack++]=seeds[i];
  117438. break;
  117439. }
  117440. }
  117441. }
  117442. }
  117443. /* the stack now contains only the positions that are relevant. Scan
  117444. 'em straight through */
  117445. for(i=0;i<stack;i++){
  117446. long endpos;
  117447. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  117448. endpos=posstack[i+1];
  117449. }else{
  117450. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  117451. discarded in short frames */
  117452. }
  117453. if(endpos>n)endpos=n;
  117454. for(;pos<endpos;pos++)
  117455. seeds[pos]=ampstack[i];
  117456. }
  117457. /* there. Linear time. I now remember this was on a problem set I
  117458. had in Grad Skool... I didn't solve it at the time ;-) */
  117459. }
  117460. /* bleaugh, this is more complicated than it needs to be */
  117461. #include<stdio.h>
  117462. static void max_seeds(vorbis_look_psy *p,
  117463. float *seed,
  117464. float *flr){
  117465. long n=p->total_octave_lines;
  117466. int linesper=p->eighth_octave_lines;
  117467. long linpos=0;
  117468. long pos;
  117469. seed_chase(seed,linesper,n); /* for masking */
  117470. pos=p->octave[0]-p->firstoc-(linesper>>1);
  117471. while(linpos+1<p->n){
  117472. float minV=seed[pos];
  117473. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  117474. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  117475. while(pos+1<=end){
  117476. pos++;
  117477. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  117478. minV=seed[pos];
  117479. }
  117480. end=pos+p->firstoc;
  117481. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  117482. if(flr[linpos]<minV)flr[linpos]=minV;
  117483. }
  117484. {
  117485. float minV=seed[p->total_octave_lines-1];
  117486. for(;linpos<p->n;linpos++)
  117487. if(flr[linpos]<minV)flr[linpos]=minV;
  117488. }
  117489. }
  117490. static void bark_noise_hybridmp(int n,const long *b,
  117491. const float *f,
  117492. float *noise,
  117493. const float offset,
  117494. const int fixed){
  117495. float *N=(float*) alloca(n*sizeof(*N));
  117496. float *X=(float*) alloca(n*sizeof(*N));
  117497. float *XX=(float*) alloca(n*sizeof(*N));
  117498. float *Y=(float*) alloca(n*sizeof(*N));
  117499. float *XY=(float*) alloca(n*sizeof(*N));
  117500. float tN, tX, tXX, tY, tXY;
  117501. int i;
  117502. int lo, hi;
  117503. float R, A, B, D;
  117504. float w, x, y;
  117505. tN = tX = tXX = tY = tXY = 0.f;
  117506. y = f[0] + offset;
  117507. if (y < 1.f) y = 1.f;
  117508. w = y * y * .5;
  117509. tN += w;
  117510. tX += w;
  117511. tY += w * y;
  117512. N[0] = tN;
  117513. X[0] = tX;
  117514. XX[0] = tXX;
  117515. Y[0] = tY;
  117516. XY[0] = tXY;
  117517. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  117518. y = f[i] + offset;
  117519. if (y < 1.f) y = 1.f;
  117520. w = y * y;
  117521. tN += w;
  117522. tX += w * x;
  117523. tXX += w * x * x;
  117524. tY += w * y;
  117525. tXY += w * x * y;
  117526. N[i] = tN;
  117527. X[i] = tX;
  117528. XX[i] = tXX;
  117529. Y[i] = tY;
  117530. XY[i] = tXY;
  117531. }
  117532. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117533. lo = b[i] >> 16;
  117534. if( lo>=0 ) break;
  117535. hi = b[i] & 0xffff;
  117536. tN = N[hi] + N[-lo];
  117537. tX = X[hi] - X[-lo];
  117538. tXX = XX[hi] + XX[-lo];
  117539. tY = Y[hi] + Y[-lo];
  117540. tXY = XY[hi] - XY[-lo];
  117541. A = tY * tXX - tX * tXY;
  117542. B = tN * tXY - tX * tY;
  117543. D = tN * tXX - tX * tX;
  117544. R = (A + x * B) / D;
  117545. if (R < 0.f)
  117546. R = 0.f;
  117547. noise[i] = R - offset;
  117548. }
  117549. for ( ;; i++, x += 1.f) {
  117550. lo = b[i] >> 16;
  117551. hi = b[i] & 0xffff;
  117552. if(hi>=n)break;
  117553. tN = N[hi] - N[lo];
  117554. tX = X[hi] - X[lo];
  117555. tXX = XX[hi] - XX[lo];
  117556. tY = Y[hi] - Y[lo];
  117557. tXY = XY[hi] - XY[lo];
  117558. A = tY * tXX - tX * tXY;
  117559. B = tN * tXY - tX * tY;
  117560. D = tN * tXX - tX * tX;
  117561. R = (A + x * B) / D;
  117562. if (R < 0.f) R = 0.f;
  117563. noise[i] = R - offset;
  117564. }
  117565. for ( ; i < n; i++, x += 1.f) {
  117566. R = (A + x * B) / D;
  117567. if (R < 0.f) R = 0.f;
  117568. noise[i] = R - offset;
  117569. }
  117570. if (fixed <= 0) return;
  117571. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117572. hi = i + fixed / 2;
  117573. lo = hi - fixed;
  117574. if(lo>=0)break;
  117575. tN = N[hi] + N[-lo];
  117576. tX = X[hi] - X[-lo];
  117577. tXX = XX[hi] + XX[-lo];
  117578. tY = Y[hi] + Y[-lo];
  117579. tXY = XY[hi] - XY[-lo];
  117580. A = tY * tXX - tX * tXY;
  117581. B = tN * tXY - tX * tY;
  117582. D = tN * tXX - tX * tX;
  117583. R = (A + x * B) / D;
  117584. if (R - offset < noise[i]) noise[i] = R - offset;
  117585. }
  117586. for ( ;; i++, x += 1.f) {
  117587. hi = i + fixed / 2;
  117588. lo = hi - fixed;
  117589. if(hi>=n)break;
  117590. tN = N[hi] - N[lo];
  117591. tX = X[hi] - X[lo];
  117592. tXX = XX[hi] - XX[lo];
  117593. tY = Y[hi] - Y[lo];
  117594. tXY = XY[hi] - XY[lo];
  117595. A = tY * tXX - tX * tXY;
  117596. B = tN * tXY - tX * tY;
  117597. D = tN * tXX - tX * tX;
  117598. R = (A + x * B) / D;
  117599. if (R - offset < noise[i]) noise[i] = R - offset;
  117600. }
  117601. for ( ; i < n; i++, x += 1.f) {
  117602. R = (A + x * B) / D;
  117603. if (R - offset < noise[i]) noise[i] = R - offset;
  117604. }
  117605. }
  117606. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  117607. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  117608. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  117609. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  117610. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  117611. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  117612. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  117613. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  117614. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  117615. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  117616. 973377.F, 913981.F, 858210.F, 805842.F,
  117617. 756669.F, 710497.F, 667142.F, 626433.F,
  117618. 588208.F, 552316.F, 518613.F, 486967.F,
  117619. 457252.F, 429351.F, 403152.F, 378551.F,
  117620. 355452.F, 333762.F, 313396.F, 294273.F,
  117621. 276316.F, 259455.F, 243623.F, 228757.F,
  117622. 214798.F, 201691.F, 189384.F, 177828.F,
  117623. 166977.F, 156788.F, 147221.F, 138237.F,
  117624. 129802.F, 121881.F, 114444.F, 107461.F,
  117625. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  117626. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  117627. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  117628. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  117629. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  117630. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  117631. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  117632. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  117633. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  117634. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  117635. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  117636. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  117637. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  117638. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  117639. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  117640. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  117641. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  117642. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  117643. 1084.32F, 1018.15F, 956.024F, 897.687F,
  117644. 842.910F, 791.475F, 743.179F, 697.830F,
  117645. 655.249F, 615.265F, 577.722F, 542.469F,
  117646. 509.367F, 478.286F, 449.101F, 421.696F,
  117647. 395.964F, 371.803F, 349.115F, 327.812F,
  117648. 307.809F, 289.026F, 271.390F, 254.830F,
  117649. 239.280F, 224.679F, 210.969F, 198.096F,
  117650. 186.008F, 174.658F, 164.000F, 153.993F,
  117651. 144.596F, 135.773F, 127.488F, 119.708F,
  117652. 112.404F, 105.545F, 99.1046F, 93.0572F,
  117653. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  117654. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  117655. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  117656. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  117657. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  117658. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  117659. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  117660. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  117661. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  117662. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  117663. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  117664. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  117665. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  117666. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  117667. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  117668. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  117669. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  117670. 1.20790F, 1.13419F, 1.06499F, 1.F
  117671. };
  117672. void _vp_remove_floor(vorbis_look_psy *p,
  117673. float *mdct,
  117674. int *codedflr,
  117675. float *residue,
  117676. int sliding_lowpass){
  117677. int i,n=p->n;
  117678. if(sliding_lowpass>n)sliding_lowpass=n;
  117679. for(i=0;i<sliding_lowpass;i++){
  117680. residue[i]=
  117681. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  117682. }
  117683. for(;i<n;i++)
  117684. residue[i]=0.;
  117685. }
  117686. void _vp_noisemask(vorbis_look_psy *p,
  117687. float *logmdct,
  117688. float *logmask){
  117689. int i,n=p->n;
  117690. float *work=(float*) alloca(n*sizeof(*work));
  117691. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  117692. 140.,-1);
  117693. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  117694. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  117695. p->vi->noisewindowfixed);
  117696. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  117697. #if 0
  117698. {
  117699. static int seq=0;
  117700. float work2[n];
  117701. for(i=0;i<n;i++){
  117702. work2[i]=logmask[i]+work[i];
  117703. }
  117704. if(seq&1)
  117705. _analysis_output("median2R",seq/2,work,n,1,0,0);
  117706. else
  117707. _analysis_output("median2L",seq/2,work,n,1,0,0);
  117708. if(seq&1)
  117709. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  117710. else
  117711. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  117712. seq++;
  117713. }
  117714. #endif
  117715. for(i=0;i<n;i++){
  117716. int dB=logmask[i]+.5;
  117717. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  117718. if(dB<0)dB=0;
  117719. logmask[i]= work[i]+p->vi->noisecompand[dB];
  117720. }
  117721. }
  117722. void _vp_tonemask(vorbis_look_psy *p,
  117723. float *logfft,
  117724. float *logmask,
  117725. float global_specmax,
  117726. float local_specmax){
  117727. int i,n=p->n;
  117728. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  117729. float att=local_specmax+p->vi->ath_adjatt;
  117730. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  117731. /* set the ATH (floating below localmax, not global max by a
  117732. specified att) */
  117733. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  117734. for(i=0;i<n;i++)
  117735. logmask[i]=p->ath[i]+att;
  117736. /* tone masking */
  117737. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  117738. max_seeds(p,seed,logmask);
  117739. }
  117740. void _vp_offset_and_mix(vorbis_look_psy *p,
  117741. float *noise,
  117742. float *tone,
  117743. int offset_select,
  117744. float *logmask,
  117745. float *mdct,
  117746. float *logmdct){
  117747. int i,n=p->n;
  117748. float de, coeffi, cx;/* AoTuV */
  117749. float toneatt=p->vi->tone_masteratt[offset_select];
  117750. cx = p->m_val;
  117751. for(i=0;i<n;i++){
  117752. float val= noise[i]+p->noiseoffset[offset_select][i];
  117753. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  117754. logmask[i]=max(val,tone[i]+toneatt);
  117755. /* AoTuV */
  117756. /** @ M1 **
  117757. The following codes improve a noise problem.
  117758. A fundamental idea uses the value of masking and carries out
  117759. the relative compensation of the MDCT.
  117760. However, this code is not perfect and all noise problems cannot be solved.
  117761. by Aoyumi @ 2004/04/18
  117762. */
  117763. if(offset_select == 1) {
  117764. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  117765. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  117766. if(val > coeffi){
  117767. /* mdct value is > -17.2 dB below floor */
  117768. de = 1.0-((val-coeffi)*0.005*cx);
  117769. /* pro-rated attenuation:
  117770. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  117771. -0.77 dB boost if mdct value is 0dB (relative to floor)
  117772. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  117773. etc... */
  117774. if(de < 0) de = 0.0001;
  117775. }else
  117776. /* mdct value is <= -17.2 dB below floor */
  117777. de = 1.0-((val-coeffi)*0.0003*cx);
  117778. /* pro-rated attenuation:
  117779. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  117780. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  117781. etc... */
  117782. mdct[i] *= de;
  117783. }
  117784. }
  117785. }
  117786. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  117787. vorbis_info *vi=vd->vi;
  117788. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117789. vorbis_info_psy_global *gi=&ci->psy_g_param;
  117790. int n=ci->blocksizes[vd->W]/2;
  117791. float secs=(float)n/vi->rate;
  117792. amp+=secs*gi->ampmax_att_per_sec;
  117793. if(amp<-9999)amp=-9999;
  117794. return(amp);
  117795. }
  117796. static void couple_lossless(float A, float B,
  117797. float *qA, float *qB){
  117798. int test1=fabs(*qA)>fabs(*qB);
  117799. test1-= fabs(*qA)<fabs(*qB);
  117800. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  117801. if(test1==1){
  117802. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  117803. }else{
  117804. float temp=*qB;
  117805. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  117806. *qA=temp;
  117807. }
  117808. if(*qB>fabs(*qA)*1.9999f){
  117809. *qB= -fabs(*qA)*2.f;
  117810. *qA= -*qA;
  117811. }
  117812. }
  117813. static float hypot_lookup[32]={
  117814. -0.009935, -0.011245, -0.012726, -0.014397,
  117815. -0.016282, -0.018407, -0.020800, -0.023494,
  117816. -0.026522, -0.029923, -0.033737, -0.038010,
  117817. -0.042787, -0.048121, -0.054064, -0.060671,
  117818. -0.068000, -0.076109, -0.085054, -0.094892,
  117819. -0.105675, -0.117451, -0.130260, -0.144134,
  117820. -0.159093, -0.175146, -0.192286, -0.210490,
  117821. -0.229718, -0.249913, -0.271001, -0.292893};
  117822. static void precomputed_couple_point(float premag,
  117823. int floorA,int floorB,
  117824. float *mag, float *ang){
  117825. int test=(floorA>floorB)-1;
  117826. int offset=31-abs(floorA-floorB);
  117827. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  117828. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  117829. *mag=premag*floormag;
  117830. *ang=0.f;
  117831. }
  117832. /* just like below, this is currently set up to only do
  117833. single-step-depth coupling. Otherwise, we'd have to do more
  117834. copying (which will be inevitable later) */
  117835. /* doing the real circular magnitude calculation is audibly superior
  117836. to (A+B)/sqrt(2) */
  117837. static float dipole_hypot(float a, float b){
  117838. if(a>0.){
  117839. if(b>0.)return sqrt(a*a+b*b);
  117840. if(a>-b)return sqrt(a*a-b*b);
  117841. return -sqrt(b*b-a*a);
  117842. }
  117843. if(b<0.)return -sqrt(a*a+b*b);
  117844. if(-a>b)return -sqrt(a*a-b*b);
  117845. return sqrt(b*b-a*a);
  117846. }
  117847. static float round_hypot(float a, float b){
  117848. if(a>0.){
  117849. if(b>0.)return sqrt(a*a+b*b);
  117850. if(a>-b)return sqrt(a*a+b*b);
  117851. return -sqrt(b*b+a*a);
  117852. }
  117853. if(b<0.)return -sqrt(a*a+b*b);
  117854. if(-a>b)return -sqrt(a*a+b*b);
  117855. return sqrt(b*b+a*a);
  117856. }
  117857. /* revert to round hypot for now */
  117858. float **_vp_quantize_couple_memo(vorbis_block *vb,
  117859. vorbis_info_psy_global *g,
  117860. vorbis_look_psy *p,
  117861. vorbis_info_mapping0 *vi,
  117862. float **mdct){
  117863. int i,j,n=p->n;
  117864. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  117865. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  117866. for(i=0;i<vi->coupling_steps;i++){
  117867. float *mdctM=mdct[vi->coupling_mag[i]];
  117868. float *mdctA=mdct[vi->coupling_ang[i]];
  117869. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117870. for(j=0;j<limit;j++)
  117871. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  117872. for(;j<n;j++)
  117873. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  117874. }
  117875. return(ret);
  117876. }
  117877. /* this is for per-channel noise normalization */
  117878. static int apsort(const void *a, const void *b){
  117879. float f1=fabs(**(float**)a);
  117880. float f2=fabs(**(float**)b);
  117881. return (f1<f2)-(f1>f2);
  117882. }
  117883. int **_vp_quantize_couple_sort(vorbis_block *vb,
  117884. vorbis_look_psy *p,
  117885. vorbis_info_mapping0 *vi,
  117886. float **mags){
  117887. if(p->vi->normal_point_p){
  117888. int i,j,k,n=p->n;
  117889. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  117890. int partition=p->vi->normal_partition;
  117891. float **work=(float**) alloca(sizeof(*work)*partition);
  117892. for(i=0;i<vi->coupling_steps;i++){
  117893. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117894. for(j=0;j<n;j+=partition){
  117895. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  117896. qsort(work,partition,sizeof(*work),apsort);
  117897. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  117898. }
  117899. }
  117900. return(ret);
  117901. }
  117902. return(NULL);
  117903. }
  117904. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  117905. float *magnitudes,int *sortedindex){
  117906. int i,j,n=p->n;
  117907. vorbis_info_psy *vi=p->vi;
  117908. int partition=vi->normal_partition;
  117909. float **work=(float**) alloca(sizeof(*work)*partition);
  117910. int start=vi->normal_start;
  117911. for(j=start;j<n;j+=partition){
  117912. if(j+partition>n)partition=n-j;
  117913. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  117914. qsort(work,partition,sizeof(*work),apsort);
  117915. for(i=0;i<partition;i++){
  117916. sortedindex[i+j-start]=work[i]-magnitudes;
  117917. }
  117918. }
  117919. }
  117920. void _vp_noise_normalize(vorbis_look_psy *p,
  117921. float *in,float *out,int *sortedindex){
  117922. int flag=0,i,j=0,n=p->n;
  117923. vorbis_info_psy *vi=p->vi;
  117924. int partition=vi->normal_partition;
  117925. int start=vi->normal_start;
  117926. if(start>n)start=n;
  117927. if(vi->normal_channel_p){
  117928. for(;j<start;j++)
  117929. out[j]=rint(in[j]);
  117930. for(;j+partition<=n;j+=partition){
  117931. float acc=0.;
  117932. int k;
  117933. for(i=j;i<j+partition;i++)
  117934. acc+=in[i]*in[i];
  117935. for(i=0;i<partition;i++){
  117936. k=sortedindex[i+j-start];
  117937. if(in[k]*in[k]>=.25f){
  117938. out[k]=rint(in[k]);
  117939. acc-=in[k]*in[k];
  117940. flag=1;
  117941. }else{
  117942. if(acc<vi->normal_thresh)break;
  117943. out[k]=unitnorm(in[k]);
  117944. acc-=1.;
  117945. }
  117946. }
  117947. for(;i<partition;i++){
  117948. k=sortedindex[i+j-start];
  117949. out[k]=0.;
  117950. }
  117951. }
  117952. }
  117953. for(;j<n;j++)
  117954. out[j]=rint(in[j]);
  117955. }
  117956. void _vp_couple(int blobno,
  117957. vorbis_info_psy_global *g,
  117958. vorbis_look_psy *p,
  117959. vorbis_info_mapping0 *vi,
  117960. float **res,
  117961. float **mag_memo,
  117962. int **mag_sort,
  117963. int **ifloor,
  117964. int *nonzero,
  117965. int sliding_lowpass){
  117966. int i,j,k,n=p->n;
  117967. /* perform any requested channel coupling */
  117968. /* point stereo can only be used in a first stage (in this encoder)
  117969. because of the dependency on floor lookups */
  117970. for(i=0;i<vi->coupling_steps;i++){
  117971. /* once we're doing multistage coupling in which a channel goes
  117972. through more than one coupling step, the floor vector
  117973. magnitudes will also have to be recalculated an propogated
  117974. along with PCM. Right now, we're not (that will wait until 5.1
  117975. most likely), so the code isn't here yet. The memory management
  117976. here is all assuming single depth couplings anyway. */
  117977. /* make sure coupling a zero and a nonzero channel results in two
  117978. nonzero channels. */
  117979. if(nonzero[vi->coupling_mag[i]] ||
  117980. nonzero[vi->coupling_ang[i]]){
  117981. float *rM=res[vi->coupling_mag[i]];
  117982. float *rA=res[vi->coupling_ang[i]];
  117983. float *qM=rM+n;
  117984. float *qA=rA+n;
  117985. int *floorM=ifloor[vi->coupling_mag[i]];
  117986. int *floorA=ifloor[vi->coupling_ang[i]];
  117987. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  117988. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  117989. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  117990. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  117991. int pointlimit=limit;
  117992. nonzero[vi->coupling_mag[i]]=1;
  117993. nonzero[vi->coupling_ang[i]]=1;
  117994. /* The threshold of a stereo is changed with the size of n */
  117995. if(n > 1000)
  117996. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  117997. for(j=0;j<p->n;j+=partition){
  117998. float acc=0.f;
  117999. for(k=0;k<partition;k++){
  118000. int l=k+j;
  118001. if(l<sliding_lowpass){
  118002. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  118003. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  118004. precomputed_couple_point(mag_memo[i][l],
  118005. floorM[l],floorA[l],
  118006. qM+l,qA+l);
  118007. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  118008. }else{
  118009. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  118010. }
  118011. }else{
  118012. qM[l]=0.;
  118013. qA[l]=0.;
  118014. }
  118015. }
  118016. if(p->vi->normal_point_p){
  118017. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  118018. int l=mag_sort[i][j+k];
  118019. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  118020. qM[l]=unitnorm(qM[l]);
  118021. acc-=1.f;
  118022. }
  118023. }
  118024. }
  118025. }
  118026. }
  118027. }
  118028. }
  118029. /* AoTuV */
  118030. /** @ M2 **
  118031. The boost problem by the combination of noise normalization and point stereo is eased.
  118032. However, this is a temporary patch.
  118033. by Aoyumi @ 2004/04/18
  118034. */
  118035. void hf_reduction(vorbis_info_psy_global *g,
  118036. vorbis_look_psy *p,
  118037. vorbis_info_mapping0 *vi,
  118038. float **mdct){
  118039. int i,j,n=p->n, de=0.3*p->m_val;
  118040. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  118041. for(i=0; i<vi->coupling_steps; i++){
  118042. /* for(j=start; j<limit; j++){} // ???*/
  118043. for(j=limit; j<n; j++)
  118044. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  118045. }
  118046. }
  118047. #endif
  118048. /*** End of inlined file: psy.c ***/
  118049. /*** Start of inlined file: registry.c ***/
  118050. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118051. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118052. // tasks..
  118053. #if JUCE_MSVC
  118054. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118055. #endif
  118056. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118057. #if JUCE_USE_OGGVORBIS
  118058. /* seems like major overkill now; the backend numbers will grow into
  118059. the infrastructure soon enough */
  118060. extern vorbis_func_floor floor0_exportbundle;
  118061. extern vorbis_func_floor floor1_exportbundle;
  118062. extern vorbis_func_residue residue0_exportbundle;
  118063. extern vorbis_func_residue residue1_exportbundle;
  118064. extern vorbis_func_residue residue2_exportbundle;
  118065. extern vorbis_func_mapping mapping0_exportbundle;
  118066. vorbis_func_floor *_floor_P[]={
  118067. &floor0_exportbundle,
  118068. &floor1_exportbundle,
  118069. };
  118070. vorbis_func_residue *_residue_P[]={
  118071. &residue0_exportbundle,
  118072. &residue1_exportbundle,
  118073. &residue2_exportbundle,
  118074. };
  118075. vorbis_func_mapping *_mapping_P[]={
  118076. &mapping0_exportbundle,
  118077. };
  118078. #endif
  118079. /*** End of inlined file: registry.c ***/
  118080. /*** Start of inlined file: res0.c ***/
  118081. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  118082. encode/decode loops are coded for clarity and performance is not
  118083. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  118084. it's slow. */
  118085. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118086. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118087. // tasks..
  118088. #if JUCE_MSVC
  118089. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118090. #endif
  118091. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118092. #if JUCE_USE_OGGVORBIS
  118093. #include <stdlib.h>
  118094. #include <string.h>
  118095. #include <math.h>
  118096. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118097. #include <stdio.h>
  118098. #endif
  118099. typedef struct {
  118100. vorbis_info_residue0 *info;
  118101. int parts;
  118102. int stages;
  118103. codebook *fullbooks;
  118104. codebook *phrasebook;
  118105. codebook ***partbooks;
  118106. int partvals;
  118107. int **decodemap;
  118108. long postbits;
  118109. long phrasebits;
  118110. long frames;
  118111. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  118112. int train_seq;
  118113. long *training_data[8][64];
  118114. float training_max[8][64];
  118115. float training_min[8][64];
  118116. float tmin;
  118117. float tmax;
  118118. #endif
  118119. } vorbis_look_residue0;
  118120. void res0_free_info(vorbis_info_residue *i){
  118121. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  118122. if(info){
  118123. memset(info,0,sizeof(*info));
  118124. _ogg_free(info);
  118125. }
  118126. }
  118127. void res0_free_look(vorbis_look_residue *i){
  118128. int j;
  118129. if(i){
  118130. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  118131. #ifdef TRAIN_RES
  118132. {
  118133. int j,k,l;
  118134. for(j=0;j<look->parts;j++){
  118135. /*fprintf(stderr,"partition %d: ",j);*/
  118136. for(k=0;k<8;k++)
  118137. if(look->training_data[k][j]){
  118138. char buffer[80];
  118139. FILE *of;
  118140. codebook *statebook=look->partbooks[j][k];
  118141. /* long and short into the same bucket by current convention */
  118142. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  118143. of=fopen(buffer,"a");
  118144. for(l=0;l<statebook->entries;l++)
  118145. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  118146. fclose(of);
  118147. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  118148. look->training_min[k][j],look->training_max[k][j]);*/
  118149. _ogg_free(look->training_data[k][j]);
  118150. look->training_data[k][j]=NULL;
  118151. }
  118152. /*fprintf(stderr,"\n");*/
  118153. }
  118154. }
  118155. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  118156. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  118157. (float)look->phrasebits/look->frames,
  118158. (float)look->postbits/look->frames,
  118159. (float)(look->postbits+look->phrasebits)/look->frames);*/
  118160. #endif
  118161. /*vorbis_info_residue0 *info=look->info;
  118162. fprintf(stderr,
  118163. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  118164. "(%g/frame) \n",look->frames,look->phrasebits,
  118165. look->resbitsflat,
  118166. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  118167. for(j=0;j<look->parts;j++){
  118168. long acc=0;
  118169. fprintf(stderr,"\t[%d] == ",j);
  118170. for(k=0;k<look->stages;k++)
  118171. if((info->secondstages[j]>>k)&1){
  118172. fprintf(stderr,"%ld,",look->resbits[j][k]);
  118173. acc+=look->resbits[j][k];
  118174. }
  118175. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  118176. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  118177. }
  118178. fprintf(stderr,"\n");*/
  118179. for(j=0;j<look->parts;j++)
  118180. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  118181. _ogg_free(look->partbooks);
  118182. for(j=0;j<look->partvals;j++)
  118183. _ogg_free(look->decodemap[j]);
  118184. _ogg_free(look->decodemap);
  118185. memset(look,0,sizeof(*look));
  118186. _ogg_free(look);
  118187. }
  118188. }
  118189. static int icount(unsigned int v){
  118190. int ret=0;
  118191. while(v){
  118192. ret+=v&1;
  118193. v>>=1;
  118194. }
  118195. return(ret);
  118196. }
  118197. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  118198. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  118199. int j,acc=0;
  118200. oggpack_write(opb,info->begin,24);
  118201. oggpack_write(opb,info->end,24);
  118202. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  118203. code with a partitioned book */
  118204. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  118205. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  118206. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  118207. bitmask of one indicates this partition class has bits to write
  118208. this pass */
  118209. for(j=0;j<info->partitions;j++){
  118210. if(ilog(info->secondstages[j])>3){
  118211. /* yes, this is a minor hack due to not thinking ahead */
  118212. oggpack_write(opb,info->secondstages[j],3);
  118213. oggpack_write(opb,1,1);
  118214. oggpack_write(opb,info->secondstages[j]>>3,5);
  118215. }else
  118216. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  118217. acc+=icount(info->secondstages[j]);
  118218. }
  118219. for(j=0;j<acc;j++)
  118220. oggpack_write(opb,info->booklist[j],8);
  118221. }
  118222. /* vorbis_info is for range checking */
  118223. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  118224. int j,acc=0;
  118225. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  118226. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  118227. info->begin=oggpack_read(opb,24);
  118228. info->end=oggpack_read(opb,24);
  118229. info->grouping=oggpack_read(opb,24)+1;
  118230. info->partitions=oggpack_read(opb,6)+1;
  118231. info->groupbook=oggpack_read(opb,8);
  118232. for(j=0;j<info->partitions;j++){
  118233. int cascade=oggpack_read(opb,3);
  118234. if(oggpack_read(opb,1))
  118235. cascade|=(oggpack_read(opb,5)<<3);
  118236. info->secondstages[j]=cascade;
  118237. acc+=icount(cascade);
  118238. }
  118239. for(j=0;j<acc;j++)
  118240. info->booklist[j]=oggpack_read(opb,8);
  118241. if(info->groupbook>=ci->books)goto errout;
  118242. for(j=0;j<acc;j++)
  118243. if(info->booklist[j]>=ci->books)goto errout;
  118244. return(info);
  118245. errout:
  118246. res0_free_info(info);
  118247. return(NULL);
  118248. }
  118249. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  118250. vorbis_info_residue *vr){
  118251. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  118252. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  118253. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  118254. int j,k,acc=0;
  118255. int dim;
  118256. int maxstage=0;
  118257. look->info=info;
  118258. look->parts=info->partitions;
  118259. look->fullbooks=ci->fullbooks;
  118260. look->phrasebook=ci->fullbooks+info->groupbook;
  118261. dim=look->phrasebook->dim;
  118262. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  118263. for(j=0;j<look->parts;j++){
  118264. int stages=ilog(info->secondstages[j]);
  118265. if(stages){
  118266. if(stages>maxstage)maxstage=stages;
  118267. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  118268. for(k=0;k<stages;k++)
  118269. if(info->secondstages[j]&(1<<k)){
  118270. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  118271. #ifdef TRAIN_RES
  118272. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  118273. sizeof(***look->training_data));
  118274. #endif
  118275. }
  118276. }
  118277. }
  118278. look->partvals=rint(pow((float)look->parts,(float)dim));
  118279. look->stages=maxstage;
  118280. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  118281. for(j=0;j<look->partvals;j++){
  118282. long val=j;
  118283. long mult=look->partvals/look->parts;
  118284. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  118285. for(k=0;k<dim;k++){
  118286. long deco=val/mult;
  118287. val-=deco*mult;
  118288. mult/=look->parts;
  118289. look->decodemap[j][k]=deco;
  118290. }
  118291. }
  118292. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118293. {
  118294. static int train_seq=0;
  118295. look->train_seq=train_seq++;
  118296. }
  118297. #endif
  118298. return(look);
  118299. }
  118300. /* break an abstraction and copy some code for performance purposes */
  118301. static int local_book_besterror(codebook *book,float *a){
  118302. int dim=book->dim,i,k,o;
  118303. int best=0;
  118304. encode_aux_threshmatch *tt=book->c->thresh_tree;
  118305. /* find the quant val of each scalar */
  118306. for(k=0,o=dim;k<dim;++k){
  118307. float val=a[--o];
  118308. i=tt->threshvals>>1;
  118309. if(val<tt->quantthresh[i]){
  118310. if(val<tt->quantthresh[i-1]){
  118311. for(--i;i>0;--i)
  118312. if(val>=tt->quantthresh[i-1])
  118313. break;
  118314. }
  118315. }else{
  118316. for(++i;i<tt->threshvals-1;++i)
  118317. if(val<tt->quantthresh[i])break;
  118318. }
  118319. best=(best*tt->quantvals)+tt->quantmap[i];
  118320. }
  118321. /* regular lattices are easy :-) */
  118322. if(book->c->lengthlist[best]<=0){
  118323. const static_codebook *c=book->c;
  118324. int i,j;
  118325. float bestf=0.f;
  118326. float *e=book->valuelist;
  118327. best=-1;
  118328. for(i=0;i<book->entries;i++){
  118329. if(c->lengthlist[i]>0){
  118330. float thisx=0.f;
  118331. for(j=0;j<dim;j++){
  118332. float val=(e[j]-a[j]);
  118333. thisx+=val*val;
  118334. }
  118335. if(best==-1 || thisx<bestf){
  118336. bestf=thisx;
  118337. best=i;
  118338. }
  118339. }
  118340. e+=dim;
  118341. }
  118342. }
  118343. {
  118344. float *ptr=book->valuelist+best*dim;
  118345. for(i=0;i<dim;i++)
  118346. *a++ -= *ptr++;
  118347. }
  118348. return(best);
  118349. }
  118350. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  118351. codebook *book,long *acc){
  118352. int i,bits=0;
  118353. int dim=book->dim;
  118354. int step=n/dim;
  118355. for(i=0;i<step;i++){
  118356. int entry=local_book_besterror(book,vec+i*dim);
  118357. #ifdef TRAIN_RES
  118358. acc[entry]++;
  118359. #endif
  118360. bits+=vorbis_book_encode(book,entry,opb);
  118361. }
  118362. return(bits);
  118363. }
  118364. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  118365. float **in,int ch){
  118366. long i,j,k;
  118367. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118368. vorbis_info_residue0 *info=look->info;
  118369. /* move all this setup out later */
  118370. int samples_per_partition=info->grouping;
  118371. int possible_partitions=info->partitions;
  118372. int n=info->end-info->begin;
  118373. int partvals=n/samples_per_partition;
  118374. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  118375. float scale=100./samples_per_partition;
  118376. /* we find the partition type for each partition of each
  118377. channel. We'll go back and do the interleaved encoding in a
  118378. bit. For now, clarity */
  118379. for(i=0;i<ch;i++){
  118380. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  118381. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  118382. }
  118383. for(i=0;i<partvals;i++){
  118384. int offset=i*samples_per_partition+info->begin;
  118385. for(j=0;j<ch;j++){
  118386. float max=0.;
  118387. float ent=0.;
  118388. for(k=0;k<samples_per_partition;k++){
  118389. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  118390. ent+=fabs(rint(in[j][offset+k]));
  118391. }
  118392. ent*=scale;
  118393. for(k=0;k<possible_partitions-1;k++)
  118394. if(max<=info->classmetric1[k] &&
  118395. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  118396. break;
  118397. partword[j][i]=k;
  118398. }
  118399. }
  118400. #ifdef TRAIN_RESAUX
  118401. {
  118402. FILE *of;
  118403. char buffer[80];
  118404. for(i=0;i<ch;i++){
  118405. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118406. of=fopen(buffer,"a");
  118407. for(j=0;j<partvals;j++)
  118408. fprintf(of,"%ld, ",partword[i][j]);
  118409. fprintf(of,"\n");
  118410. fclose(of);
  118411. }
  118412. }
  118413. #endif
  118414. look->frames++;
  118415. return(partword);
  118416. }
  118417. /* designed for stereo or other modes where the partition size is an
  118418. integer multiple of the number of channels encoded in the current
  118419. submap */
  118420. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  118421. int ch){
  118422. long i,j,k,l;
  118423. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118424. vorbis_info_residue0 *info=look->info;
  118425. /* move all this setup out later */
  118426. int samples_per_partition=info->grouping;
  118427. int possible_partitions=info->partitions;
  118428. int n=info->end-info->begin;
  118429. int partvals=n/samples_per_partition;
  118430. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  118431. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118432. FILE *of;
  118433. char buffer[80];
  118434. #endif
  118435. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  118436. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  118437. for(i=0,l=info->begin/ch;i<partvals;i++){
  118438. float magmax=0.f;
  118439. float angmax=0.f;
  118440. for(j=0;j<samples_per_partition;j+=ch){
  118441. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  118442. for(k=1;k<ch;k++)
  118443. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  118444. l++;
  118445. }
  118446. for(j=0;j<possible_partitions-1;j++)
  118447. if(magmax<=info->classmetric1[j] &&
  118448. angmax<=info->classmetric2[j])
  118449. break;
  118450. partword[0][i]=j;
  118451. }
  118452. #ifdef TRAIN_RESAUX
  118453. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118454. of=fopen(buffer,"a");
  118455. for(i=0;i<partvals;i++)
  118456. fprintf(of,"%ld, ",partword[0][i]);
  118457. fprintf(of,"\n");
  118458. fclose(of);
  118459. #endif
  118460. look->frames++;
  118461. return(partword);
  118462. }
  118463. static int _01forward(oggpack_buffer *opb,
  118464. vorbis_block *vb,vorbis_look_residue *vl,
  118465. float **in,int ch,
  118466. long **partword,
  118467. int (*encode)(oggpack_buffer *,float *,int,
  118468. codebook *,long *)){
  118469. long i,j,k,s;
  118470. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118471. vorbis_info_residue0 *info=look->info;
  118472. /* move all this setup out later */
  118473. int samples_per_partition=info->grouping;
  118474. int possible_partitions=info->partitions;
  118475. int partitions_per_word=look->phrasebook->dim;
  118476. int n=info->end-info->begin;
  118477. int partvals=n/samples_per_partition;
  118478. long resbits[128];
  118479. long resvals[128];
  118480. #ifdef TRAIN_RES
  118481. for(i=0;i<ch;i++)
  118482. for(j=info->begin;j<info->end;j++){
  118483. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  118484. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  118485. }
  118486. #endif
  118487. memset(resbits,0,sizeof(resbits));
  118488. memset(resvals,0,sizeof(resvals));
  118489. /* we code the partition words for each channel, then the residual
  118490. words for a partition per channel until we've written all the
  118491. residual words for that partition word. Then write the next
  118492. partition channel words... */
  118493. for(s=0;s<look->stages;s++){
  118494. for(i=0;i<partvals;){
  118495. /* first we encode a partition codeword for each channel */
  118496. if(s==0){
  118497. for(j=0;j<ch;j++){
  118498. long val=partword[j][i];
  118499. for(k=1;k<partitions_per_word;k++){
  118500. val*=possible_partitions;
  118501. if(i+k<partvals)
  118502. val+=partword[j][i+k];
  118503. }
  118504. /* training hack */
  118505. if(val<look->phrasebook->entries)
  118506. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  118507. #if 0 /*def TRAIN_RES*/
  118508. else
  118509. fprintf(stderr,"!");
  118510. #endif
  118511. }
  118512. }
  118513. /* now we encode interleaved residual values for the partitions */
  118514. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  118515. long offset=i*samples_per_partition+info->begin;
  118516. for(j=0;j<ch;j++){
  118517. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  118518. if(info->secondstages[partword[j][i]]&(1<<s)){
  118519. codebook *statebook=look->partbooks[partword[j][i]][s];
  118520. if(statebook){
  118521. int ret;
  118522. long *accumulator=NULL;
  118523. #ifdef TRAIN_RES
  118524. accumulator=look->training_data[s][partword[j][i]];
  118525. {
  118526. int l;
  118527. float *samples=in[j]+offset;
  118528. for(l=0;l<samples_per_partition;l++){
  118529. if(samples[l]<look->training_min[s][partword[j][i]])
  118530. look->training_min[s][partword[j][i]]=samples[l];
  118531. if(samples[l]>look->training_max[s][partword[j][i]])
  118532. look->training_max[s][partword[j][i]]=samples[l];
  118533. }
  118534. }
  118535. #endif
  118536. ret=encode(opb,in[j]+offset,samples_per_partition,
  118537. statebook,accumulator);
  118538. look->postbits+=ret;
  118539. resbits[partword[j][i]]+=ret;
  118540. }
  118541. }
  118542. }
  118543. }
  118544. }
  118545. }
  118546. /*{
  118547. long total=0;
  118548. long totalbits=0;
  118549. fprintf(stderr,"%d :: ",vb->mode);
  118550. for(k=0;k<possible_partitions;k++){
  118551. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  118552. total+=resvals[k];
  118553. totalbits+=resbits[k];
  118554. }
  118555. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  118556. }*/
  118557. return(0);
  118558. }
  118559. /* a truncated packet here just means 'stop working'; it's not an error */
  118560. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118561. float **in,int ch,
  118562. long (*decodepart)(codebook *, float *,
  118563. oggpack_buffer *,int)){
  118564. long i,j,k,l,s;
  118565. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118566. vorbis_info_residue0 *info=look->info;
  118567. /* move all this setup out later */
  118568. int samples_per_partition=info->grouping;
  118569. int partitions_per_word=look->phrasebook->dim;
  118570. int n=info->end-info->begin;
  118571. int partvals=n/samples_per_partition;
  118572. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118573. int ***partword=(int***)alloca(ch*sizeof(*partword));
  118574. for(j=0;j<ch;j++)
  118575. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  118576. for(s=0;s<look->stages;s++){
  118577. /* each loop decodes on partition codeword containing
  118578. partitions_pre_word partitions */
  118579. for(i=0,l=0;i<partvals;l++){
  118580. if(s==0){
  118581. /* fetch the partition word for each channel */
  118582. for(j=0;j<ch;j++){
  118583. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118584. if(temp==-1)goto eopbreak;
  118585. partword[j][l]=look->decodemap[temp];
  118586. if(partword[j][l]==NULL)goto errout;
  118587. }
  118588. }
  118589. /* now we decode residual values for the partitions */
  118590. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118591. for(j=0;j<ch;j++){
  118592. long offset=info->begin+i*samples_per_partition;
  118593. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  118594. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  118595. if(stagebook){
  118596. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  118597. samples_per_partition)==-1)goto eopbreak;
  118598. }
  118599. }
  118600. }
  118601. }
  118602. }
  118603. errout:
  118604. eopbreak:
  118605. return(0);
  118606. }
  118607. #if 0
  118608. /* residue 0 and 1 are just slight variants of one another. 0 is
  118609. interleaved, 1 is not */
  118610. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  118611. float **in,int *nonzero,int ch){
  118612. /* we encode only the nonzero parts of a bundle */
  118613. int i,used=0;
  118614. for(i=0;i<ch;i++)
  118615. if(nonzero[i])
  118616. in[used++]=in[i];
  118617. if(used)
  118618. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  118619. return(_01class(vb,vl,in,used));
  118620. else
  118621. return(0);
  118622. }
  118623. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  118624. float **in,float **out,int *nonzero,int ch,
  118625. long **partword){
  118626. /* we encode only the nonzero parts of a bundle */
  118627. int i,j,used=0,n=vb->pcmend/2;
  118628. for(i=0;i<ch;i++)
  118629. if(nonzero[i]){
  118630. if(out)
  118631. for(j=0;j<n;j++)
  118632. out[i][j]+=in[i][j];
  118633. in[used++]=in[i];
  118634. }
  118635. if(used){
  118636. int ret=_01forward(vb,vl,in,used,partword,
  118637. _interleaved_encodepart);
  118638. if(out){
  118639. used=0;
  118640. for(i=0;i<ch;i++)
  118641. if(nonzero[i]){
  118642. for(j=0;j<n;j++)
  118643. out[i][j]-=in[used][j];
  118644. used++;
  118645. }
  118646. }
  118647. return(ret);
  118648. }else{
  118649. return(0);
  118650. }
  118651. }
  118652. #endif
  118653. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118654. float **in,int *nonzero,int ch){
  118655. int i,used=0;
  118656. for(i=0;i<ch;i++)
  118657. if(nonzero[i])
  118658. in[used++]=in[i];
  118659. if(used)
  118660. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  118661. else
  118662. return(0);
  118663. }
  118664. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  118665. float **in,float **out,int *nonzero,int ch,
  118666. long **partword){
  118667. int i,j,used=0,n=vb->pcmend/2;
  118668. for(i=0;i<ch;i++)
  118669. if(nonzero[i]){
  118670. if(out)
  118671. for(j=0;j<n;j++)
  118672. out[i][j]+=in[i][j];
  118673. in[used++]=in[i];
  118674. }
  118675. if(used){
  118676. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  118677. if(out){
  118678. used=0;
  118679. for(i=0;i<ch;i++)
  118680. if(nonzero[i]){
  118681. for(j=0;j<n;j++)
  118682. out[i][j]-=in[used][j];
  118683. used++;
  118684. }
  118685. }
  118686. return(ret);
  118687. }else{
  118688. return(0);
  118689. }
  118690. }
  118691. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  118692. float **in,int *nonzero,int ch){
  118693. int i,used=0;
  118694. for(i=0;i<ch;i++)
  118695. if(nonzero[i])
  118696. in[used++]=in[i];
  118697. if(used)
  118698. return(_01class(vb,vl,in,used));
  118699. else
  118700. return(0);
  118701. }
  118702. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118703. float **in,int *nonzero,int ch){
  118704. int i,used=0;
  118705. for(i=0;i<ch;i++)
  118706. if(nonzero[i])
  118707. in[used++]=in[i];
  118708. if(used)
  118709. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  118710. else
  118711. return(0);
  118712. }
  118713. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  118714. float **in,int *nonzero,int ch){
  118715. int i,used=0;
  118716. for(i=0;i<ch;i++)
  118717. if(nonzero[i])used++;
  118718. if(used)
  118719. return(_2class(vb,vl,in,ch));
  118720. else
  118721. return(0);
  118722. }
  118723. /* res2 is slightly more different; all the channels are interleaved
  118724. into a single vector and encoded. */
  118725. int res2_forward(oggpack_buffer *opb,
  118726. vorbis_block *vb,vorbis_look_residue *vl,
  118727. float **in,float **out,int *nonzero,int ch,
  118728. long **partword){
  118729. long i,j,k,n=vb->pcmend/2,used=0;
  118730. /* don't duplicate the code; use a working vector hack for now and
  118731. reshape ourselves into a single channel res1 */
  118732. /* ugly; reallocs for each coupling pass :-( */
  118733. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  118734. for(i=0;i<ch;i++){
  118735. float *pcm=in[i];
  118736. if(nonzero[i])used++;
  118737. for(j=0,k=i;j<n;j++,k+=ch)
  118738. work[k]=pcm[j];
  118739. }
  118740. if(used){
  118741. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  118742. /* update the sofar vector */
  118743. if(out){
  118744. for(i=0;i<ch;i++){
  118745. float *pcm=in[i];
  118746. float *sofar=out[i];
  118747. for(j=0,k=i;j<n;j++,k+=ch)
  118748. sofar[j]+=pcm[j]-work[k];
  118749. }
  118750. }
  118751. return(ret);
  118752. }else{
  118753. return(0);
  118754. }
  118755. }
  118756. /* duplicate code here as speed is somewhat more important */
  118757. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118758. float **in,int *nonzero,int ch){
  118759. long i,k,l,s;
  118760. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118761. vorbis_info_residue0 *info=look->info;
  118762. /* move all this setup out later */
  118763. int samples_per_partition=info->grouping;
  118764. int partitions_per_word=look->phrasebook->dim;
  118765. int n=info->end-info->begin;
  118766. int partvals=n/samples_per_partition;
  118767. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118768. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  118769. for(i=0;i<ch;i++)if(nonzero[i])break;
  118770. if(i==ch)return(0); /* no nonzero vectors */
  118771. for(s=0;s<look->stages;s++){
  118772. for(i=0,l=0;i<partvals;l++){
  118773. if(s==0){
  118774. /* fetch the partition word */
  118775. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118776. if(temp==-1)goto eopbreak;
  118777. partword[l]=look->decodemap[temp];
  118778. if(partword[l]==NULL)goto errout;
  118779. }
  118780. /* now we decode residual values for the partitions */
  118781. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118782. if(info->secondstages[partword[l][k]]&(1<<s)){
  118783. codebook *stagebook=look->partbooks[partword[l][k]][s];
  118784. if(stagebook){
  118785. if(vorbis_book_decodevv_add(stagebook,in,
  118786. i*samples_per_partition+info->begin,ch,
  118787. &vb->opb,samples_per_partition)==-1)
  118788. goto eopbreak;
  118789. }
  118790. }
  118791. }
  118792. }
  118793. errout:
  118794. eopbreak:
  118795. return(0);
  118796. }
  118797. vorbis_func_residue residue0_exportbundle={
  118798. NULL,
  118799. &res0_unpack,
  118800. &res0_look,
  118801. &res0_free_info,
  118802. &res0_free_look,
  118803. NULL,
  118804. NULL,
  118805. &res0_inverse
  118806. };
  118807. vorbis_func_residue residue1_exportbundle={
  118808. &res0_pack,
  118809. &res0_unpack,
  118810. &res0_look,
  118811. &res0_free_info,
  118812. &res0_free_look,
  118813. &res1_class,
  118814. &res1_forward,
  118815. &res1_inverse
  118816. };
  118817. vorbis_func_residue residue2_exportbundle={
  118818. &res0_pack,
  118819. &res0_unpack,
  118820. &res0_look,
  118821. &res0_free_info,
  118822. &res0_free_look,
  118823. &res2_class,
  118824. &res2_forward,
  118825. &res2_inverse
  118826. };
  118827. #endif
  118828. /*** End of inlined file: res0.c ***/
  118829. /*** Start of inlined file: sharedbook.c ***/
  118830. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118831. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118832. // tasks..
  118833. #if JUCE_MSVC
  118834. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118835. #endif
  118836. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118837. #if JUCE_USE_OGGVORBIS
  118838. #include <stdlib.h>
  118839. #include <math.h>
  118840. #include <string.h>
  118841. /**** pack/unpack helpers ******************************************/
  118842. int _ilog(unsigned int v){
  118843. int ret=0;
  118844. while(v){
  118845. ret++;
  118846. v>>=1;
  118847. }
  118848. return(ret);
  118849. }
  118850. /* 32 bit float (not IEEE; nonnormalized mantissa +
  118851. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  118852. Why not IEEE? It's just not that important here. */
  118853. #define VQ_FEXP 10
  118854. #define VQ_FMAN 21
  118855. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  118856. /* doesn't currently guard under/overflow */
  118857. long _float32_pack(float val){
  118858. int sign=0;
  118859. long exp;
  118860. long mant;
  118861. if(val<0){
  118862. sign=0x80000000;
  118863. val= -val;
  118864. }
  118865. exp= floor(log(val)/log(2.f));
  118866. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  118867. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  118868. return(sign|exp|mant);
  118869. }
  118870. float _float32_unpack(long val){
  118871. double mant=val&0x1fffff;
  118872. int sign=val&0x80000000;
  118873. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  118874. if(sign)mant= -mant;
  118875. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  118876. }
  118877. /* given a list of word lengths, generate a list of codewords. Works
  118878. for length ordered or unordered, always assigns the lowest valued
  118879. codewords first. Extended to handle unused entries (length 0) */
  118880. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  118881. long i,j,count=0;
  118882. ogg_uint32_t marker[33];
  118883. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  118884. memset(marker,0,sizeof(marker));
  118885. for(i=0;i<n;i++){
  118886. long length=l[i];
  118887. if(length>0){
  118888. ogg_uint32_t entry=marker[length];
  118889. /* when we claim a node for an entry, we also claim the nodes
  118890. below it (pruning off the imagined tree that may have dangled
  118891. from it) as well as blocking the use of any nodes directly
  118892. above for leaves */
  118893. /* update ourself */
  118894. if(length<32 && (entry>>length)){
  118895. /* error condition; the lengths must specify an overpopulated tree */
  118896. _ogg_free(r);
  118897. return(NULL);
  118898. }
  118899. r[count++]=entry;
  118900. /* Look to see if the next shorter marker points to the node
  118901. above. if so, update it and repeat. */
  118902. {
  118903. for(j=length;j>0;j--){
  118904. if(marker[j]&1){
  118905. /* have to jump branches */
  118906. if(j==1)
  118907. marker[1]++;
  118908. else
  118909. marker[j]=marker[j-1]<<1;
  118910. break; /* invariant says next upper marker would already
  118911. have been moved if it was on the same path */
  118912. }
  118913. marker[j]++;
  118914. }
  118915. }
  118916. /* prune the tree; the implicit invariant says all the longer
  118917. markers were dangling from our just-taken node. Dangle them
  118918. from our *new* node. */
  118919. for(j=length+1;j<33;j++)
  118920. if((marker[j]>>1) == entry){
  118921. entry=marker[j];
  118922. marker[j]=marker[j-1]<<1;
  118923. }else
  118924. break;
  118925. }else
  118926. if(sparsecount==0)count++;
  118927. }
  118928. /* bitreverse the words because our bitwise packer/unpacker is LSb
  118929. endian */
  118930. for(i=0,count=0;i<n;i++){
  118931. ogg_uint32_t temp=0;
  118932. for(j=0;j<l[i];j++){
  118933. temp<<=1;
  118934. temp|=(r[count]>>j)&1;
  118935. }
  118936. if(sparsecount){
  118937. if(l[i])
  118938. r[count++]=temp;
  118939. }else
  118940. r[count++]=temp;
  118941. }
  118942. return(r);
  118943. }
  118944. /* there might be a straightforward one-line way to do the below
  118945. that's portable and totally safe against roundoff, but I haven't
  118946. thought of it. Therefore, we opt on the side of caution */
  118947. long _book_maptype1_quantvals(const static_codebook *b){
  118948. long vals=floor(pow((float)b->entries,1.f/b->dim));
  118949. /* the above *should* be reliable, but we'll not assume that FP is
  118950. ever reliable when bitstream sync is at stake; verify via integer
  118951. means that vals really is the greatest value of dim for which
  118952. vals^b->bim <= b->entries */
  118953. /* treat the above as an initial guess */
  118954. while(1){
  118955. long acc=1;
  118956. long acc1=1;
  118957. int i;
  118958. for(i=0;i<b->dim;i++){
  118959. acc*=vals;
  118960. acc1*=vals+1;
  118961. }
  118962. if(acc<=b->entries && acc1>b->entries){
  118963. return(vals);
  118964. }else{
  118965. if(acc>b->entries){
  118966. vals--;
  118967. }else{
  118968. vals++;
  118969. }
  118970. }
  118971. }
  118972. }
  118973. /* unpack the quantized list of values for encode/decode ***********/
  118974. /* we need to deal with two map types: in map type 1, the values are
  118975. generated algorithmically (each column of the vector counts through
  118976. the values in the quant vector). in map type 2, all the values came
  118977. in in an explicit list. Both value lists must be unpacked */
  118978. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  118979. long j,k,count=0;
  118980. if(b->maptype==1 || b->maptype==2){
  118981. int quantvals;
  118982. float mindel=_float32_unpack(b->q_min);
  118983. float delta=_float32_unpack(b->q_delta);
  118984. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  118985. /* maptype 1 and 2 both use a quantized value vector, but
  118986. different sizes */
  118987. switch(b->maptype){
  118988. case 1:
  118989. /* most of the time, entries%dimensions == 0, but we need to be
  118990. well defined. We define that the possible vales at each
  118991. scalar is values == entries/dim. If entries%dim != 0, we'll
  118992. have 'too few' values (values*dim<entries), which means that
  118993. we'll have 'left over' entries; left over entries use zeroed
  118994. values (and are wasted). So don't generate codebooks like
  118995. that */
  118996. quantvals=_book_maptype1_quantvals(b);
  118997. for(j=0;j<b->entries;j++){
  118998. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  118999. float last=0.f;
  119000. int indexdiv=1;
  119001. for(k=0;k<b->dim;k++){
  119002. int index= (j/indexdiv)%quantvals;
  119003. float val=b->quantlist[index];
  119004. val=fabs(val)*delta+mindel+last;
  119005. if(b->q_sequencep)last=val;
  119006. if(sparsemap)
  119007. r[sparsemap[count]*b->dim+k]=val;
  119008. else
  119009. r[count*b->dim+k]=val;
  119010. indexdiv*=quantvals;
  119011. }
  119012. count++;
  119013. }
  119014. }
  119015. break;
  119016. case 2:
  119017. for(j=0;j<b->entries;j++){
  119018. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  119019. float last=0.f;
  119020. for(k=0;k<b->dim;k++){
  119021. float val=b->quantlist[j*b->dim+k];
  119022. val=fabs(val)*delta+mindel+last;
  119023. if(b->q_sequencep)last=val;
  119024. if(sparsemap)
  119025. r[sparsemap[count]*b->dim+k]=val;
  119026. else
  119027. r[count*b->dim+k]=val;
  119028. }
  119029. count++;
  119030. }
  119031. }
  119032. break;
  119033. }
  119034. return(r);
  119035. }
  119036. return(NULL);
  119037. }
  119038. void vorbis_staticbook_clear(static_codebook *b){
  119039. if(b->allocedp){
  119040. if(b->quantlist)_ogg_free(b->quantlist);
  119041. if(b->lengthlist)_ogg_free(b->lengthlist);
  119042. if(b->nearest_tree){
  119043. _ogg_free(b->nearest_tree->ptr0);
  119044. _ogg_free(b->nearest_tree->ptr1);
  119045. _ogg_free(b->nearest_tree->p);
  119046. _ogg_free(b->nearest_tree->q);
  119047. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  119048. _ogg_free(b->nearest_tree);
  119049. }
  119050. if(b->thresh_tree){
  119051. _ogg_free(b->thresh_tree->quantthresh);
  119052. _ogg_free(b->thresh_tree->quantmap);
  119053. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  119054. _ogg_free(b->thresh_tree);
  119055. }
  119056. memset(b,0,sizeof(*b));
  119057. }
  119058. }
  119059. void vorbis_staticbook_destroy(static_codebook *b){
  119060. if(b->allocedp){
  119061. vorbis_staticbook_clear(b);
  119062. _ogg_free(b);
  119063. }
  119064. }
  119065. void vorbis_book_clear(codebook *b){
  119066. /* static book is not cleared; we're likely called on the lookup and
  119067. the static codebook belongs to the info struct */
  119068. if(b->valuelist)_ogg_free(b->valuelist);
  119069. if(b->codelist)_ogg_free(b->codelist);
  119070. if(b->dec_index)_ogg_free(b->dec_index);
  119071. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  119072. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  119073. memset(b,0,sizeof(*b));
  119074. }
  119075. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  119076. memset(c,0,sizeof(*c));
  119077. c->c=s;
  119078. c->entries=s->entries;
  119079. c->used_entries=s->entries;
  119080. c->dim=s->dim;
  119081. c->codelist=_make_words(s->lengthlist,s->entries,0);
  119082. c->valuelist=_book_unquantize(s,s->entries,NULL);
  119083. return(0);
  119084. }
  119085. static int sort32a(const void *a,const void *b){
  119086. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  119087. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  119088. }
  119089. /* decode codebook arrangement is more heavily optimized than encode */
  119090. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  119091. int i,j,n=0,tabn;
  119092. int *sortindex;
  119093. memset(c,0,sizeof(*c));
  119094. /* count actually used entries */
  119095. for(i=0;i<s->entries;i++)
  119096. if(s->lengthlist[i]>0)
  119097. n++;
  119098. c->entries=s->entries;
  119099. c->used_entries=n;
  119100. c->dim=s->dim;
  119101. /* two different remappings go on here.
  119102. First, we collapse the likely sparse codebook down only to
  119103. actually represented values/words. This collapsing needs to be
  119104. indexed as map-valueless books are used to encode original entry
  119105. positions as integers.
  119106. Second, we reorder all vectors, including the entry index above,
  119107. by sorted bitreversed codeword to allow treeless decode. */
  119108. {
  119109. /* perform sort */
  119110. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  119111. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  119112. if(codes==NULL)goto err_out;
  119113. for(i=0;i<n;i++){
  119114. codes[i]=ogg_bitreverse(codes[i]);
  119115. codep[i]=codes+i;
  119116. }
  119117. qsort(codep,n,sizeof(*codep),sort32a);
  119118. sortindex=(int*)alloca(n*sizeof(*sortindex));
  119119. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  119120. /* the index is a reverse index */
  119121. for(i=0;i<n;i++){
  119122. int position=codep[i]-codes;
  119123. sortindex[position]=i;
  119124. }
  119125. for(i=0;i<n;i++)
  119126. c->codelist[sortindex[i]]=codes[i];
  119127. _ogg_free(codes);
  119128. }
  119129. c->valuelist=_book_unquantize(s,n,sortindex);
  119130. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  119131. for(n=0,i=0;i<s->entries;i++)
  119132. if(s->lengthlist[i]>0)
  119133. c->dec_index[sortindex[n++]]=i;
  119134. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  119135. for(n=0,i=0;i<s->entries;i++)
  119136. if(s->lengthlist[i]>0)
  119137. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  119138. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  119139. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  119140. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  119141. tabn=1<<c->dec_firsttablen;
  119142. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  119143. c->dec_maxlength=0;
  119144. for(i=0;i<n;i++){
  119145. if(c->dec_maxlength<c->dec_codelengths[i])
  119146. c->dec_maxlength=c->dec_codelengths[i];
  119147. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  119148. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  119149. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  119150. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  119151. }
  119152. }
  119153. /* now fill in 'unused' entries in the firsttable with hi/lo search
  119154. hints for the non-direct-hits */
  119155. {
  119156. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  119157. long lo=0,hi=0;
  119158. for(i=0;i<tabn;i++){
  119159. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  119160. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  119161. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  119162. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  119163. /* we only actually have 15 bits per hint to play with here.
  119164. In order to overflow gracefully (nothing breaks, efficiency
  119165. just drops), encode as the difference from the extremes. */
  119166. {
  119167. unsigned long loval=lo;
  119168. unsigned long hival=n-hi;
  119169. if(loval>0x7fff)loval=0x7fff;
  119170. if(hival>0x7fff)hival=0x7fff;
  119171. c->dec_firsttable[ogg_bitreverse(word)]=
  119172. 0x80000000UL | (loval<<15) | hival;
  119173. }
  119174. }
  119175. }
  119176. }
  119177. return(0);
  119178. err_out:
  119179. vorbis_book_clear(c);
  119180. return(-1);
  119181. }
  119182. static float _dist(int el,float *ref, float *b,int step){
  119183. int i;
  119184. float acc=0.f;
  119185. for(i=0;i<el;i++){
  119186. float val=(ref[i]-b[i*step]);
  119187. acc+=val*val;
  119188. }
  119189. return(acc);
  119190. }
  119191. int _best(codebook *book, float *a, int step){
  119192. encode_aux_threshmatch *tt=book->c->thresh_tree;
  119193. #if 0
  119194. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  119195. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  119196. #endif
  119197. int dim=book->dim;
  119198. int k,o;
  119199. /*int savebest=-1;
  119200. float saverr;*/
  119201. /* do we have a threshhold encode hint? */
  119202. if(tt){
  119203. int index=0,i;
  119204. /* find the quant val of each scalar */
  119205. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  119206. i=tt->threshvals>>1;
  119207. if(a[o]<tt->quantthresh[i]){
  119208. for(;i>0;i--)
  119209. if(a[o]>=tt->quantthresh[i-1])
  119210. break;
  119211. }else{
  119212. for(i++;i<tt->threshvals-1;i++)
  119213. if(a[o]<tt->quantthresh[i])break;
  119214. }
  119215. index=(index*tt->quantvals)+tt->quantmap[i];
  119216. }
  119217. /* regular lattices are easy :-) */
  119218. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  119219. use a decision tree after all
  119220. and fall through*/
  119221. return(index);
  119222. }
  119223. #if 0
  119224. /* do we have a pigeonhole encode hint? */
  119225. if(pt){
  119226. const static_codebook *c=book->c;
  119227. int i,besti=-1;
  119228. float best=0.f;
  119229. int entry=0;
  119230. /* dealing with sequentialness is a pain in the ass */
  119231. if(c->q_sequencep){
  119232. int pv;
  119233. long mul=1;
  119234. float qlast=0;
  119235. for(k=0,o=0;k<dim;k++,o+=step){
  119236. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  119237. if(pv<0 || pv>=pt->mapentries)break;
  119238. entry+=pt->pigeonmap[pv]*mul;
  119239. mul*=pt->quantvals;
  119240. qlast+=pv*pt->del+pt->min;
  119241. }
  119242. }else{
  119243. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  119244. int pv=(int)((a[o]-pt->min)/pt->del);
  119245. if(pv<0 || pv>=pt->mapentries)break;
  119246. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  119247. }
  119248. }
  119249. /* must be within the pigeonholable range; if we quant outside (or
  119250. in an entry that we define no list for), brute force it */
  119251. if(k==dim && pt->fitlength[entry]){
  119252. /* search the abbreviated list */
  119253. long *list=pt->fitlist+pt->fitmap[entry];
  119254. for(i=0;i<pt->fitlength[entry];i++){
  119255. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  119256. if(besti==-1 || this<best){
  119257. best=this;
  119258. besti=list[i];
  119259. }
  119260. }
  119261. return(besti);
  119262. }
  119263. }
  119264. if(nt){
  119265. /* optimized using the decision tree */
  119266. while(1){
  119267. float c=0.f;
  119268. float *p=book->valuelist+nt->p[ptr];
  119269. float *q=book->valuelist+nt->q[ptr];
  119270. for(k=0,o=0;k<dim;k++,o+=step)
  119271. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  119272. if(c>0.f) /* in A */
  119273. ptr= -nt->ptr0[ptr];
  119274. else /* in B */
  119275. ptr= -nt->ptr1[ptr];
  119276. if(ptr<=0)break;
  119277. }
  119278. return(-ptr);
  119279. }
  119280. #endif
  119281. /* brute force it! */
  119282. {
  119283. const static_codebook *c=book->c;
  119284. int i,besti=-1;
  119285. float best=0.f;
  119286. float *e=book->valuelist;
  119287. for(i=0;i<book->entries;i++){
  119288. if(c->lengthlist[i]>0){
  119289. float thisx=_dist(dim,e,a,step);
  119290. if(besti==-1 || thisx<best){
  119291. best=thisx;
  119292. besti=i;
  119293. }
  119294. }
  119295. e+=dim;
  119296. }
  119297. /*if(savebest!=-1 && savebest!=besti){
  119298. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  119299. "original:");
  119300. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  119301. fprintf(stderr,"\n"
  119302. "pigeonhole (entry %d, err %g):",savebest,saverr);
  119303. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  119304. (book->valuelist+savebest*dim)[i]);
  119305. fprintf(stderr,"\n"
  119306. "bruteforce (entry %d, err %g):",besti,best);
  119307. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  119308. (book->valuelist+besti*dim)[i]);
  119309. fprintf(stderr,"\n");
  119310. }*/
  119311. return(besti);
  119312. }
  119313. }
  119314. long vorbis_book_codeword(codebook *book,int entry){
  119315. if(book->c) /* only use with encode; decode optimizations are
  119316. allowed to break this */
  119317. return book->codelist[entry];
  119318. return -1;
  119319. }
  119320. long vorbis_book_codelen(codebook *book,int entry){
  119321. if(book->c) /* only use with encode; decode optimizations are
  119322. allowed to break this */
  119323. return book->c->lengthlist[entry];
  119324. return -1;
  119325. }
  119326. #ifdef _V_SELFTEST
  119327. /* Unit tests of the dequantizer; this stuff will be OK
  119328. cross-platform, I simply want to be sure that special mapping cases
  119329. actually work properly; a bug could go unnoticed for a while */
  119330. #include <stdio.h>
  119331. /* cases:
  119332. no mapping
  119333. full, explicit mapping
  119334. algorithmic mapping
  119335. nonsequential
  119336. sequential
  119337. */
  119338. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  119339. static long partial_quantlist1[]={0,7,2};
  119340. /* no mapping */
  119341. static_codebook test1={
  119342. 4,16,
  119343. NULL,
  119344. 0,
  119345. 0,0,0,0,
  119346. NULL,
  119347. NULL,NULL
  119348. };
  119349. static float *test1_result=NULL;
  119350. /* linear, full mapping, nonsequential */
  119351. static_codebook test2={
  119352. 4,3,
  119353. NULL,
  119354. 2,
  119355. -533200896,1611661312,4,0,
  119356. full_quantlist1,
  119357. NULL,NULL
  119358. };
  119359. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  119360. /* linear, full mapping, sequential */
  119361. static_codebook test3={
  119362. 4,3,
  119363. NULL,
  119364. 2,
  119365. -533200896,1611661312,4,1,
  119366. full_quantlist1,
  119367. NULL,NULL
  119368. };
  119369. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  119370. /* linear, algorithmic mapping, nonsequential */
  119371. static_codebook test4={
  119372. 3,27,
  119373. NULL,
  119374. 1,
  119375. -533200896,1611661312,4,0,
  119376. partial_quantlist1,
  119377. NULL,NULL
  119378. };
  119379. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  119380. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  119381. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  119382. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  119383. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  119384. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  119385. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  119386. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  119387. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  119388. /* linear, algorithmic mapping, sequential */
  119389. static_codebook test5={
  119390. 3,27,
  119391. NULL,
  119392. 1,
  119393. -533200896,1611661312,4,1,
  119394. partial_quantlist1,
  119395. NULL,NULL
  119396. };
  119397. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  119398. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  119399. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  119400. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  119401. -3, 1, 5, 4, 8,12, -1, 3, 7,
  119402. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  119403. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  119404. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  119405. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  119406. void run_test(static_codebook *b,float *comp){
  119407. float *out=_book_unquantize(b,b->entries,NULL);
  119408. int i;
  119409. if(comp){
  119410. if(!out){
  119411. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  119412. exit(1);
  119413. }
  119414. for(i=0;i<b->entries*b->dim;i++)
  119415. if(fabs(out[i]-comp[i])>.0001){
  119416. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  119417. "position %d, %g != %g\n",i,out[i],comp[i]);
  119418. exit(1);
  119419. }
  119420. }else{
  119421. if(out){
  119422. fprintf(stderr,"_book_unquantize returned a value array: \n"
  119423. " correct result should have been NULL\n");
  119424. exit(1);
  119425. }
  119426. }
  119427. }
  119428. int main(){
  119429. /* run the nine dequant tests, and compare to the hand-rolled results */
  119430. fprintf(stderr,"Dequant test 1... ");
  119431. run_test(&test1,test1_result);
  119432. fprintf(stderr,"OK\nDequant test 2... ");
  119433. run_test(&test2,test2_result);
  119434. fprintf(stderr,"OK\nDequant test 3... ");
  119435. run_test(&test3,test3_result);
  119436. fprintf(stderr,"OK\nDequant test 4... ");
  119437. run_test(&test4,test4_result);
  119438. fprintf(stderr,"OK\nDequant test 5... ");
  119439. run_test(&test5,test5_result);
  119440. fprintf(stderr,"OK\n\n");
  119441. return(0);
  119442. }
  119443. #endif
  119444. #endif
  119445. /*** End of inlined file: sharedbook.c ***/
  119446. /*** Start of inlined file: smallft.c ***/
  119447. /* FFT implementation from OggSquish, minus cosine transforms,
  119448. * minus all but radix 2/4 case. In Vorbis we only need this
  119449. * cut-down version.
  119450. *
  119451. * To do more than just power-of-two sized vectors, see the full
  119452. * version I wrote for NetLib.
  119453. *
  119454. * Note that the packing is a little strange; rather than the FFT r/i
  119455. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  119456. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  119457. * FORTRAN version
  119458. */
  119459. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119460. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119461. // tasks..
  119462. #if JUCE_MSVC
  119463. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119464. #endif
  119465. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119466. #if JUCE_USE_OGGVORBIS
  119467. #include <stdlib.h>
  119468. #include <string.h>
  119469. #include <math.h>
  119470. static void drfti1(int n, float *wa, int *ifac){
  119471. static int ntryh[4] = { 4,2,3,5 };
  119472. static float tpi = 6.28318530717958648f;
  119473. float arg,argh,argld,fi;
  119474. int ntry=0,i,j=-1;
  119475. int k1, l1, l2, ib;
  119476. int ld, ii, ip, is, nq, nr;
  119477. int ido, ipm, nfm1;
  119478. int nl=n;
  119479. int nf=0;
  119480. L101:
  119481. j++;
  119482. if (j < 4)
  119483. ntry=ntryh[j];
  119484. else
  119485. ntry+=2;
  119486. L104:
  119487. nq=nl/ntry;
  119488. nr=nl-ntry*nq;
  119489. if (nr!=0) goto L101;
  119490. nf++;
  119491. ifac[nf+1]=ntry;
  119492. nl=nq;
  119493. if(ntry!=2)goto L107;
  119494. if(nf==1)goto L107;
  119495. for (i=1;i<nf;i++){
  119496. ib=nf-i+1;
  119497. ifac[ib+1]=ifac[ib];
  119498. }
  119499. ifac[2] = 2;
  119500. L107:
  119501. if(nl!=1)goto L104;
  119502. ifac[0]=n;
  119503. ifac[1]=nf;
  119504. argh=tpi/n;
  119505. is=0;
  119506. nfm1=nf-1;
  119507. l1=1;
  119508. if(nfm1==0)return;
  119509. for (k1=0;k1<nfm1;k1++){
  119510. ip=ifac[k1+2];
  119511. ld=0;
  119512. l2=l1*ip;
  119513. ido=n/l2;
  119514. ipm=ip-1;
  119515. for (j=0;j<ipm;j++){
  119516. ld+=l1;
  119517. i=is;
  119518. argld=(float)ld*argh;
  119519. fi=0.f;
  119520. for (ii=2;ii<ido;ii+=2){
  119521. fi+=1.f;
  119522. arg=fi*argld;
  119523. wa[i++]=cos(arg);
  119524. wa[i++]=sin(arg);
  119525. }
  119526. is+=ido;
  119527. }
  119528. l1=l2;
  119529. }
  119530. }
  119531. static void fdrffti(int n, float *wsave, int *ifac){
  119532. if (n == 1) return;
  119533. drfti1(n, wsave+n, ifac);
  119534. }
  119535. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  119536. int i,k;
  119537. float ti2,tr2;
  119538. int t0,t1,t2,t3,t4,t5,t6;
  119539. t1=0;
  119540. t0=(t2=l1*ido);
  119541. t3=ido<<1;
  119542. for(k=0;k<l1;k++){
  119543. ch[t1<<1]=cc[t1]+cc[t2];
  119544. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  119545. t1+=ido;
  119546. t2+=ido;
  119547. }
  119548. if(ido<2)return;
  119549. if(ido==2)goto L105;
  119550. t1=0;
  119551. t2=t0;
  119552. for(k=0;k<l1;k++){
  119553. t3=t2;
  119554. t4=(t1<<1)+(ido<<1);
  119555. t5=t1;
  119556. t6=t1+t1;
  119557. for(i=2;i<ido;i+=2){
  119558. t3+=2;
  119559. t4-=2;
  119560. t5+=2;
  119561. t6+=2;
  119562. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119563. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119564. ch[t6]=cc[t5]+ti2;
  119565. ch[t4]=ti2-cc[t5];
  119566. ch[t6-1]=cc[t5-1]+tr2;
  119567. ch[t4-1]=cc[t5-1]-tr2;
  119568. }
  119569. t1+=ido;
  119570. t2+=ido;
  119571. }
  119572. if(ido%2==1)return;
  119573. L105:
  119574. t3=(t2=(t1=ido)-1);
  119575. t2+=t0;
  119576. for(k=0;k<l1;k++){
  119577. ch[t1]=-cc[t2];
  119578. ch[t1-1]=cc[t3];
  119579. t1+=ido<<1;
  119580. t2+=ido;
  119581. t3+=ido;
  119582. }
  119583. }
  119584. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  119585. float *wa2,float *wa3){
  119586. static float hsqt2 = .70710678118654752f;
  119587. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119588. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119589. t0=l1*ido;
  119590. t1=t0;
  119591. t4=t1<<1;
  119592. t2=t1+(t1<<1);
  119593. t3=0;
  119594. for(k=0;k<l1;k++){
  119595. tr1=cc[t1]+cc[t2];
  119596. tr2=cc[t3]+cc[t4];
  119597. ch[t5=t3<<2]=tr1+tr2;
  119598. ch[(ido<<2)+t5-1]=tr2-tr1;
  119599. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  119600. ch[t5]=cc[t2]-cc[t1];
  119601. t1+=ido;
  119602. t2+=ido;
  119603. t3+=ido;
  119604. t4+=ido;
  119605. }
  119606. if(ido<2)return;
  119607. if(ido==2)goto L105;
  119608. t1=0;
  119609. for(k=0;k<l1;k++){
  119610. t2=t1;
  119611. t4=t1<<2;
  119612. t5=(t6=ido<<1)+t4;
  119613. for(i=2;i<ido;i+=2){
  119614. t3=(t2+=2);
  119615. t4+=2;
  119616. t5-=2;
  119617. t3+=t0;
  119618. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119619. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119620. t3+=t0;
  119621. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  119622. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  119623. t3+=t0;
  119624. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  119625. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  119626. tr1=cr2+cr4;
  119627. tr4=cr4-cr2;
  119628. ti1=ci2+ci4;
  119629. ti4=ci2-ci4;
  119630. ti2=cc[t2]+ci3;
  119631. ti3=cc[t2]-ci3;
  119632. tr2=cc[t2-1]+cr3;
  119633. tr3=cc[t2-1]-cr3;
  119634. ch[t4-1]=tr1+tr2;
  119635. ch[t4]=ti1+ti2;
  119636. ch[t5-1]=tr3-ti4;
  119637. ch[t5]=tr4-ti3;
  119638. ch[t4+t6-1]=ti4+tr3;
  119639. ch[t4+t6]=tr4+ti3;
  119640. ch[t5+t6-1]=tr2-tr1;
  119641. ch[t5+t6]=ti1-ti2;
  119642. }
  119643. t1+=ido;
  119644. }
  119645. if(ido&1)return;
  119646. L105:
  119647. t2=(t1=t0+ido-1)+(t0<<1);
  119648. t3=ido<<2;
  119649. t4=ido;
  119650. t5=ido<<1;
  119651. t6=ido;
  119652. for(k=0;k<l1;k++){
  119653. ti1=-hsqt2*(cc[t1]+cc[t2]);
  119654. tr1=hsqt2*(cc[t1]-cc[t2]);
  119655. ch[t4-1]=tr1+cc[t6-1];
  119656. ch[t4+t5-1]=cc[t6-1]-tr1;
  119657. ch[t4]=ti1-cc[t1+t0];
  119658. ch[t4+t5]=ti1+cc[t1+t0];
  119659. t1+=ido;
  119660. t2+=ido;
  119661. t4+=t3;
  119662. t6+=ido;
  119663. }
  119664. }
  119665. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  119666. float *c2,float *ch,float *ch2,float *wa){
  119667. static float tpi=6.283185307179586f;
  119668. int idij,ipph,i,j,k,l,ic,ik,is;
  119669. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119670. float dc2,ai1,ai2,ar1,ar2,ds2;
  119671. int nbd;
  119672. float dcp,arg,dsp,ar1h,ar2h;
  119673. int idp2,ipp2;
  119674. arg=tpi/(float)ip;
  119675. dcp=cos(arg);
  119676. dsp=sin(arg);
  119677. ipph=(ip+1)>>1;
  119678. ipp2=ip;
  119679. idp2=ido;
  119680. nbd=(ido-1)>>1;
  119681. t0=l1*ido;
  119682. t10=ip*ido;
  119683. if(ido==1)goto L119;
  119684. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  119685. t1=0;
  119686. for(j=1;j<ip;j++){
  119687. t1+=t0;
  119688. t2=t1;
  119689. for(k=0;k<l1;k++){
  119690. ch[t2]=c1[t2];
  119691. t2+=ido;
  119692. }
  119693. }
  119694. is=-ido;
  119695. t1=0;
  119696. if(nbd>l1){
  119697. for(j=1;j<ip;j++){
  119698. t1+=t0;
  119699. is+=ido;
  119700. t2= -ido+t1;
  119701. for(k=0;k<l1;k++){
  119702. idij=is-1;
  119703. t2+=ido;
  119704. t3=t2;
  119705. for(i=2;i<ido;i+=2){
  119706. idij+=2;
  119707. t3+=2;
  119708. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119709. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119710. }
  119711. }
  119712. }
  119713. }else{
  119714. for(j=1;j<ip;j++){
  119715. is+=ido;
  119716. idij=is-1;
  119717. t1+=t0;
  119718. t2=t1;
  119719. for(i=2;i<ido;i+=2){
  119720. idij+=2;
  119721. t2+=2;
  119722. t3=t2;
  119723. for(k=0;k<l1;k++){
  119724. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119725. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119726. t3+=ido;
  119727. }
  119728. }
  119729. }
  119730. }
  119731. t1=0;
  119732. t2=ipp2*t0;
  119733. if(nbd<l1){
  119734. for(j=1;j<ipph;j++){
  119735. t1+=t0;
  119736. t2-=t0;
  119737. t3=t1;
  119738. t4=t2;
  119739. for(i=2;i<ido;i+=2){
  119740. t3+=2;
  119741. t4+=2;
  119742. t5=t3-ido;
  119743. t6=t4-ido;
  119744. for(k=0;k<l1;k++){
  119745. t5+=ido;
  119746. t6+=ido;
  119747. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119748. c1[t6-1]=ch[t5]-ch[t6];
  119749. c1[t5]=ch[t5]+ch[t6];
  119750. c1[t6]=ch[t6-1]-ch[t5-1];
  119751. }
  119752. }
  119753. }
  119754. }else{
  119755. for(j=1;j<ipph;j++){
  119756. t1+=t0;
  119757. t2-=t0;
  119758. t3=t1;
  119759. t4=t2;
  119760. for(k=0;k<l1;k++){
  119761. t5=t3;
  119762. t6=t4;
  119763. for(i=2;i<ido;i+=2){
  119764. t5+=2;
  119765. t6+=2;
  119766. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119767. c1[t6-1]=ch[t5]-ch[t6];
  119768. c1[t5]=ch[t5]+ch[t6];
  119769. c1[t6]=ch[t6-1]-ch[t5-1];
  119770. }
  119771. t3+=ido;
  119772. t4+=ido;
  119773. }
  119774. }
  119775. }
  119776. L119:
  119777. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  119778. t1=0;
  119779. t2=ipp2*idl1;
  119780. for(j=1;j<ipph;j++){
  119781. t1+=t0;
  119782. t2-=t0;
  119783. t3=t1-ido;
  119784. t4=t2-ido;
  119785. for(k=0;k<l1;k++){
  119786. t3+=ido;
  119787. t4+=ido;
  119788. c1[t3]=ch[t3]+ch[t4];
  119789. c1[t4]=ch[t4]-ch[t3];
  119790. }
  119791. }
  119792. ar1=1.f;
  119793. ai1=0.f;
  119794. t1=0;
  119795. t2=ipp2*idl1;
  119796. t3=(ip-1)*idl1;
  119797. for(l=1;l<ipph;l++){
  119798. t1+=idl1;
  119799. t2-=idl1;
  119800. ar1h=dcp*ar1-dsp*ai1;
  119801. ai1=dcp*ai1+dsp*ar1;
  119802. ar1=ar1h;
  119803. t4=t1;
  119804. t5=t2;
  119805. t6=t3;
  119806. t7=idl1;
  119807. for(ik=0;ik<idl1;ik++){
  119808. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  119809. ch2[t5++]=ai1*c2[t6++];
  119810. }
  119811. dc2=ar1;
  119812. ds2=ai1;
  119813. ar2=ar1;
  119814. ai2=ai1;
  119815. t4=idl1;
  119816. t5=(ipp2-1)*idl1;
  119817. for(j=2;j<ipph;j++){
  119818. t4+=idl1;
  119819. t5-=idl1;
  119820. ar2h=dc2*ar2-ds2*ai2;
  119821. ai2=dc2*ai2+ds2*ar2;
  119822. ar2=ar2h;
  119823. t6=t1;
  119824. t7=t2;
  119825. t8=t4;
  119826. t9=t5;
  119827. for(ik=0;ik<idl1;ik++){
  119828. ch2[t6++]+=ar2*c2[t8++];
  119829. ch2[t7++]+=ai2*c2[t9++];
  119830. }
  119831. }
  119832. }
  119833. t1=0;
  119834. for(j=1;j<ipph;j++){
  119835. t1+=idl1;
  119836. t2=t1;
  119837. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  119838. }
  119839. if(ido<l1)goto L132;
  119840. t1=0;
  119841. t2=0;
  119842. for(k=0;k<l1;k++){
  119843. t3=t1;
  119844. t4=t2;
  119845. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  119846. t1+=ido;
  119847. t2+=t10;
  119848. }
  119849. goto L135;
  119850. L132:
  119851. for(i=0;i<ido;i++){
  119852. t1=i;
  119853. t2=i;
  119854. for(k=0;k<l1;k++){
  119855. cc[t2]=ch[t1];
  119856. t1+=ido;
  119857. t2+=t10;
  119858. }
  119859. }
  119860. L135:
  119861. t1=0;
  119862. t2=ido<<1;
  119863. t3=0;
  119864. t4=ipp2*t0;
  119865. for(j=1;j<ipph;j++){
  119866. t1+=t2;
  119867. t3+=t0;
  119868. t4-=t0;
  119869. t5=t1;
  119870. t6=t3;
  119871. t7=t4;
  119872. for(k=0;k<l1;k++){
  119873. cc[t5-1]=ch[t6];
  119874. cc[t5]=ch[t7];
  119875. t5+=t10;
  119876. t6+=ido;
  119877. t7+=ido;
  119878. }
  119879. }
  119880. if(ido==1)return;
  119881. if(nbd<l1)goto L141;
  119882. t1=-ido;
  119883. t3=0;
  119884. t4=0;
  119885. t5=ipp2*t0;
  119886. for(j=1;j<ipph;j++){
  119887. t1+=t2;
  119888. t3+=t2;
  119889. t4+=t0;
  119890. t5-=t0;
  119891. t6=t1;
  119892. t7=t3;
  119893. t8=t4;
  119894. t9=t5;
  119895. for(k=0;k<l1;k++){
  119896. for(i=2;i<ido;i+=2){
  119897. ic=idp2-i;
  119898. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  119899. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  119900. cc[i+t7]=ch[i+t8]+ch[i+t9];
  119901. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  119902. }
  119903. t6+=t10;
  119904. t7+=t10;
  119905. t8+=ido;
  119906. t9+=ido;
  119907. }
  119908. }
  119909. return;
  119910. L141:
  119911. t1=-ido;
  119912. t3=0;
  119913. t4=0;
  119914. t5=ipp2*t0;
  119915. for(j=1;j<ipph;j++){
  119916. t1+=t2;
  119917. t3+=t2;
  119918. t4+=t0;
  119919. t5-=t0;
  119920. for(i=2;i<ido;i+=2){
  119921. t6=idp2+t1-i;
  119922. t7=i+t3;
  119923. t8=i+t4;
  119924. t9=i+t5;
  119925. for(k=0;k<l1;k++){
  119926. cc[t7-1]=ch[t8-1]+ch[t9-1];
  119927. cc[t6-1]=ch[t8-1]-ch[t9-1];
  119928. cc[t7]=ch[t8]+ch[t9];
  119929. cc[t6]=ch[t9]-ch[t8];
  119930. t6+=t10;
  119931. t7+=t10;
  119932. t8+=ido;
  119933. t9+=ido;
  119934. }
  119935. }
  119936. }
  119937. }
  119938. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  119939. int i,k1,l1,l2;
  119940. int na,kh,nf;
  119941. int ip,iw,ido,idl1,ix2,ix3;
  119942. nf=ifac[1];
  119943. na=1;
  119944. l2=n;
  119945. iw=n;
  119946. for(k1=0;k1<nf;k1++){
  119947. kh=nf-k1;
  119948. ip=ifac[kh+1];
  119949. l1=l2/ip;
  119950. ido=n/l2;
  119951. idl1=ido*l1;
  119952. iw-=(ip-1)*ido;
  119953. na=1-na;
  119954. if(ip!=4)goto L102;
  119955. ix2=iw+ido;
  119956. ix3=ix2+ido;
  119957. if(na!=0)
  119958. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119959. else
  119960. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  119961. goto L110;
  119962. L102:
  119963. if(ip!=2)goto L104;
  119964. if(na!=0)goto L103;
  119965. dradf2(ido,l1,c,ch,wa+iw-1);
  119966. goto L110;
  119967. L103:
  119968. dradf2(ido,l1,ch,c,wa+iw-1);
  119969. goto L110;
  119970. L104:
  119971. if(ido==1)na=1-na;
  119972. if(na!=0)goto L109;
  119973. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  119974. na=1;
  119975. goto L110;
  119976. L109:
  119977. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  119978. na=0;
  119979. L110:
  119980. l2=l1;
  119981. }
  119982. if(na==1)return;
  119983. for(i=0;i<n;i++)c[i]=ch[i];
  119984. }
  119985. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  119986. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119987. float ti2,tr2;
  119988. t0=l1*ido;
  119989. t1=0;
  119990. t2=0;
  119991. t3=(ido<<1)-1;
  119992. for(k=0;k<l1;k++){
  119993. ch[t1]=cc[t2]+cc[t3+t2];
  119994. ch[t1+t0]=cc[t2]-cc[t3+t2];
  119995. t2=(t1+=ido)<<1;
  119996. }
  119997. if(ido<2)return;
  119998. if(ido==2)goto L105;
  119999. t1=0;
  120000. t2=0;
  120001. for(k=0;k<l1;k++){
  120002. t3=t1;
  120003. t5=(t4=t2)+(ido<<1);
  120004. t6=t0+t1;
  120005. for(i=2;i<ido;i+=2){
  120006. t3+=2;
  120007. t4+=2;
  120008. t5-=2;
  120009. t6+=2;
  120010. ch[t3-1]=cc[t4-1]+cc[t5-1];
  120011. tr2=cc[t4-1]-cc[t5-1];
  120012. ch[t3]=cc[t4]-cc[t5];
  120013. ti2=cc[t4]+cc[t5];
  120014. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  120015. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  120016. }
  120017. t2=(t1+=ido)<<1;
  120018. }
  120019. if(ido%2==1)return;
  120020. L105:
  120021. t1=ido-1;
  120022. t2=ido-1;
  120023. for(k=0;k<l1;k++){
  120024. ch[t1]=cc[t2]+cc[t2];
  120025. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  120026. t1+=ido;
  120027. t2+=ido<<1;
  120028. }
  120029. }
  120030. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  120031. float *wa2){
  120032. static float taur = -.5f;
  120033. static float taui = .8660254037844386f;
  120034. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  120035. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  120036. t0=l1*ido;
  120037. t1=0;
  120038. t2=t0<<1;
  120039. t3=ido<<1;
  120040. t4=ido+(ido<<1);
  120041. t5=0;
  120042. for(k=0;k<l1;k++){
  120043. tr2=cc[t3-1]+cc[t3-1];
  120044. cr2=cc[t5]+(taur*tr2);
  120045. ch[t1]=cc[t5]+tr2;
  120046. ci3=taui*(cc[t3]+cc[t3]);
  120047. ch[t1+t0]=cr2-ci3;
  120048. ch[t1+t2]=cr2+ci3;
  120049. t1+=ido;
  120050. t3+=t4;
  120051. t5+=t4;
  120052. }
  120053. if(ido==1)return;
  120054. t1=0;
  120055. t3=ido<<1;
  120056. for(k=0;k<l1;k++){
  120057. t7=t1+(t1<<1);
  120058. t6=(t5=t7+t3);
  120059. t8=t1;
  120060. t10=(t9=t1+t0)+t0;
  120061. for(i=2;i<ido;i+=2){
  120062. t5+=2;
  120063. t6-=2;
  120064. t7+=2;
  120065. t8+=2;
  120066. t9+=2;
  120067. t10+=2;
  120068. tr2=cc[t5-1]+cc[t6-1];
  120069. cr2=cc[t7-1]+(taur*tr2);
  120070. ch[t8-1]=cc[t7-1]+tr2;
  120071. ti2=cc[t5]-cc[t6];
  120072. ci2=cc[t7]+(taur*ti2);
  120073. ch[t8]=cc[t7]+ti2;
  120074. cr3=taui*(cc[t5-1]-cc[t6-1]);
  120075. ci3=taui*(cc[t5]+cc[t6]);
  120076. dr2=cr2-ci3;
  120077. dr3=cr2+ci3;
  120078. di2=ci2+cr3;
  120079. di3=ci2-cr3;
  120080. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  120081. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  120082. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  120083. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  120084. }
  120085. t1+=ido;
  120086. }
  120087. }
  120088. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  120089. float *wa2,float *wa3){
  120090. static float sqrt2=1.414213562373095f;
  120091. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  120092. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  120093. t0=l1*ido;
  120094. t1=0;
  120095. t2=ido<<2;
  120096. t3=0;
  120097. t6=ido<<1;
  120098. for(k=0;k<l1;k++){
  120099. t4=t3+t6;
  120100. t5=t1;
  120101. tr3=cc[t4-1]+cc[t4-1];
  120102. tr4=cc[t4]+cc[t4];
  120103. tr1=cc[t3]-cc[(t4+=t6)-1];
  120104. tr2=cc[t3]+cc[t4-1];
  120105. ch[t5]=tr2+tr3;
  120106. ch[t5+=t0]=tr1-tr4;
  120107. ch[t5+=t0]=tr2-tr3;
  120108. ch[t5+=t0]=tr1+tr4;
  120109. t1+=ido;
  120110. t3+=t2;
  120111. }
  120112. if(ido<2)return;
  120113. if(ido==2)goto L105;
  120114. t1=0;
  120115. for(k=0;k<l1;k++){
  120116. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  120117. t7=t1;
  120118. for(i=2;i<ido;i+=2){
  120119. t2+=2;
  120120. t3+=2;
  120121. t4-=2;
  120122. t5-=2;
  120123. t7+=2;
  120124. ti1=cc[t2]+cc[t5];
  120125. ti2=cc[t2]-cc[t5];
  120126. ti3=cc[t3]-cc[t4];
  120127. tr4=cc[t3]+cc[t4];
  120128. tr1=cc[t2-1]-cc[t5-1];
  120129. tr2=cc[t2-1]+cc[t5-1];
  120130. ti4=cc[t3-1]-cc[t4-1];
  120131. tr3=cc[t3-1]+cc[t4-1];
  120132. ch[t7-1]=tr2+tr3;
  120133. cr3=tr2-tr3;
  120134. ch[t7]=ti2+ti3;
  120135. ci3=ti2-ti3;
  120136. cr2=tr1-tr4;
  120137. cr4=tr1+tr4;
  120138. ci2=ti1+ti4;
  120139. ci4=ti1-ti4;
  120140. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  120141. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  120142. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  120143. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  120144. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  120145. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  120146. }
  120147. t1+=ido;
  120148. }
  120149. if(ido%2 == 1)return;
  120150. L105:
  120151. t1=ido;
  120152. t2=ido<<2;
  120153. t3=ido-1;
  120154. t4=ido+(ido<<1);
  120155. for(k=0;k<l1;k++){
  120156. t5=t3;
  120157. ti1=cc[t1]+cc[t4];
  120158. ti2=cc[t4]-cc[t1];
  120159. tr1=cc[t1-1]-cc[t4-1];
  120160. tr2=cc[t1-1]+cc[t4-1];
  120161. ch[t5]=tr2+tr2;
  120162. ch[t5+=t0]=sqrt2*(tr1-ti1);
  120163. ch[t5+=t0]=ti2+ti2;
  120164. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  120165. t3+=ido;
  120166. t1+=t2;
  120167. t4+=t2;
  120168. }
  120169. }
  120170. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  120171. float *c2,float *ch,float *ch2,float *wa){
  120172. static float tpi=6.283185307179586f;
  120173. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  120174. t11,t12;
  120175. float dc2,ai1,ai2,ar1,ar2,ds2;
  120176. int nbd;
  120177. float dcp,arg,dsp,ar1h,ar2h;
  120178. int ipp2;
  120179. t10=ip*ido;
  120180. t0=l1*ido;
  120181. arg=tpi/(float)ip;
  120182. dcp=cos(arg);
  120183. dsp=sin(arg);
  120184. nbd=(ido-1)>>1;
  120185. ipp2=ip;
  120186. ipph=(ip+1)>>1;
  120187. if(ido<l1)goto L103;
  120188. t1=0;
  120189. t2=0;
  120190. for(k=0;k<l1;k++){
  120191. t3=t1;
  120192. t4=t2;
  120193. for(i=0;i<ido;i++){
  120194. ch[t3]=cc[t4];
  120195. t3++;
  120196. t4++;
  120197. }
  120198. t1+=ido;
  120199. t2+=t10;
  120200. }
  120201. goto L106;
  120202. L103:
  120203. t1=0;
  120204. for(i=0;i<ido;i++){
  120205. t2=t1;
  120206. t3=t1;
  120207. for(k=0;k<l1;k++){
  120208. ch[t2]=cc[t3];
  120209. t2+=ido;
  120210. t3+=t10;
  120211. }
  120212. t1++;
  120213. }
  120214. L106:
  120215. t1=0;
  120216. t2=ipp2*t0;
  120217. t7=(t5=ido<<1);
  120218. for(j=1;j<ipph;j++){
  120219. t1+=t0;
  120220. t2-=t0;
  120221. t3=t1;
  120222. t4=t2;
  120223. t6=t5;
  120224. for(k=0;k<l1;k++){
  120225. ch[t3]=cc[t6-1]+cc[t6-1];
  120226. ch[t4]=cc[t6]+cc[t6];
  120227. t3+=ido;
  120228. t4+=ido;
  120229. t6+=t10;
  120230. }
  120231. t5+=t7;
  120232. }
  120233. if (ido == 1)goto L116;
  120234. if(nbd<l1)goto L112;
  120235. t1=0;
  120236. t2=ipp2*t0;
  120237. t7=0;
  120238. for(j=1;j<ipph;j++){
  120239. t1+=t0;
  120240. t2-=t0;
  120241. t3=t1;
  120242. t4=t2;
  120243. t7+=(ido<<1);
  120244. t8=t7;
  120245. for(k=0;k<l1;k++){
  120246. t5=t3;
  120247. t6=t4;
  120248. t9=t8;
  120249. t11=t8;
  120250. for(i=2;i<ido;i+=2){
  120251. t5+=2;
  120252. t6+=2;
  120253. t9+=2;
  120254. t11-=2;
  120255. ch[t5-1]=cc[t9-1]+cc[t11-1];
  120256. ch[t6-1]=cc[t9-1]-cc[t11-1];
  120257. ch[t5]=cc[t9]-cc[t11];
  120258. ch[t6]=cc[t9]+cc[t11];
  120259. }
  120260. t3+=ido;
  120261. t4+=ido;
  120262. t8+=t10;
  120263. }
  120264. }
  120265. goto L116;
  120266. L112:
  120267. t1=0;
  120268. t2=ipp2*t0;
  120269. t7=0;
  120270. for(j=1;j<ipph;j++){
  120271. t1+=t0;
  120272. t2-=t0;
  120273. t3=t1;
  120274. t4=t2;
  120275. t7+=(ido<<1);
  120276. t8=t7;
  120277. t9=t7;
  120278. for(i=2;i<ido;i+=2){
  120279. t3+=2;
  120280. t4+=2;
  120281. t8+=2;
  120282. t9-=2;
  120283. t5=t3;
  120284. t6=t4;
  120285. t11=t8;
  120286. t12=t9;
  120287. for(k=0;k<l1;k++){
  120288. ch[t5-1]=cc[t11-1]+cc[t12-1];
  120289. ch[t6-1]=cc[t11-1]-cc[t12-1];
  120290. ch[t5]=cc[t11]-cc[t12];
  120291. ch[t6]=cc[t11]+cc[t12];
  120292. t5+=ido;
  120293. t6+=ido;
  120294. t11+=t10;
  120295. t12+=t10;
  120296. }
  120297. }
  120298. }
  120299. L116:
  120300. ar1=1.f;
  120301. ai1=0.f;
  120302. t1=0;
  120303. t9=(t2=ipp2*idl1);
  120304. t3=(ip-1)*idl1;
  120305. for(l=1;l<ipph;l++){
  120306. t1+=idl1;
  120307. t2-=idl1;
  120308. ar1h=dcp*ar1-dsp*ai1;
  120309. ai1=dcp*ai1+dsp*ar1;
  120310. ar1=ar1h;
  120311. t4=t1;
  120312. t5=t2;
  120313. t6=0;
  120314. t7=idl1;
  120315. t8=t3;
  120316. for(ik=0;ik<idl1;ik++){
  120317. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  120318. c2[t5++]=ai1*ch2[t8++];
  120319. }
  120320. dc2=ar1;
  120321. ds2=ai1;
  120322. ar2=ar1;
  120323. ai2=ai1;
  120324. t6=idl1;
  120325. t7=t9-idl1;
  120326. for(j=2;j<ipph;j++){
  120327. t6+=idl1;
  120328. t7-=idl1;
  120329. ar2h=dc2*ar2-ds2*ai2;
  120330. ai2=dc2*ai2+ds2*ar2;
  120331. ar2=ar2h;
  120332. t4=t1;
  120333. t5=t2;
  120334. t11=t6;
  120335. t12=t7;
  120336. for(ik=0;ik<idl1;ik++){
  120337. c2[t4++]+=ar2*ch2[t11++];
  120338. c2[t5++]+=ai2*ch2[t12++];
  120339. }
  120340. }
  120341. }
  120342. t1=0;
  120343. for(j=1;j<ipph;j++){
  120344. t1+=idl1;
  120345. t2=t1;
  120346. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  120347. }
  120348. t1=0;
  120349. t2=ipp2*t0;
  120350. for(j=1;j<ipph;j++){
  120351. t1+=t0;
  120352. t2-=t0;
  120353. t3=t1;
  120354. t4=t2;
  120355. for(k=0;k<l1;k++){
  120356. ch[t3]=c1[t3]-c1[t4];
  120357. ch[t4]=c1[t3]+c1[t4];
  120358. t3+=ido;
  120359. t4+=ido;
  120360. }
  120361. }
  120362. if(ido==1)goto L132;
  120363. if(nbd<l1)goto L128;
  120364. t1=0;
  120365. t2=ipp2*t0;
  120366. for(j=1;j<ipph;j++){
  120367. t1+=t0;
  120368. t2-=t0;
  120369. t3=t1;
  120370. t4=t2;
  120371. for(k=0;k<l1;k++){
  120372. t5=t3;
  120373. t6=t4;
  120374. for(i=2;i<ido;i+=2){
  120375. t5+=2;
  120376. t6+=2;
  120377. ch[t5-1]=c1[t5-1]-c1[t6];
  120378. ch[t6-1]=c1[t5-1]+c1[t6];
  120379. ch[t5]=c1[t5]+c1[t6-1];
  120380. ch[t6]=c1[t5]-c1[t6-1];
  120381. }
  120382. t3+=ido;
  120383. t4+=ido;
  120384. }
  120385. }
  120386. goto L132;
  120387. L128:
  120388. t1=0;
  120389. t2=ipp2*t0;
  120390. for(j=1;j<ipph;j++){
  120391. t1+=t0;
  120392. t2-=t0;
  120393. t3=t1;
  120394. t4=t2;
  120395. for(i=2;i<ido;i+=2){
  120396. t3+=2;
  120397. t4+=2;
  120398. t5=t3;
  120399. t6=t4;
  120400. for(k=0;k<l1;k++){
  120401. ch[t5-1]=c1[t5-1]-c1[t6];
  120402. ch[t6-1]=c1[t5-1]+c1[t6];
  120403. ch[t5]=c1[t5]+c1[t6-1];
  120404. ch[t6]=c1[t5]-c1[t6-1];
  120405. t5+=ido;
  120406. t6+=ido;
  120407. }
  120408. }
  120409. }
  120410. L132:
  120411. if(ido==1)return;
  120412. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  120413. t1=0;
  120414. for(j=1;j<ip;j++){
  120415. t2=(t1+=t0);
  120416. for(k=0;k<l1;k++){
  120417. c1[t2]=ch[t2];
  120418. t2+=ido;
  120419. }
  120420. }
  120421. if(nbd>l1)goto L139;
  120422. is= -ido-1;
  120423. t1=0;
  120424. for(j=1;j<ip;j++){
  120425. is+=ido;
  120426. t1+=t0;
  120427. idij=is;
  120428. t2=t1;
  120429. for(i=2;i<ido;i+=2){
  120430. t2+=2;
  120431. idij+=2;
  120432. t3=t2;
  120433. for(k=0;k<l1;k++){
  120434. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120435. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120436. t3+=ido;
  120437. }
  120438. }
  120439. }
  120440. return;
  120441. L139:
  120442. is= -ido-1;
  120443. t1=0;
  120444. for(j=1;j<ip;j++){
  120445. is+=ido;
  120446. t1+=t0;
  120447. t2=t1;
  120448. for(k=0;k<l1;k++){
  120449. idij=is;
  120450. t3=t2;
  120451. for(i=2;i<ido;i+=2){
  120452. idij+=2;
  120453. t3+=2;
  120454. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120455. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120456. }
  120457. t2+=ido;
  120458. }
  120459. }
  120460. }
  120461. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  120462. int i,k1,l1,l2;
  120463. int na;
  120464. int nf,ip,iw,ix2,ix3,ido,idl1;
  120465. nf=ifac[1];
  120466. na=0;
  120467. l1=1;
  120468. iw=1;
  120469. for(k1=0;k1<nf;k1++){
  120470. ip=ifac[k1 + 2];
  120471. l2=ip*l1;
  120472. ido=n/l2;
  120473. idl1=ido*l1;
  120474. if(ip!=4)goto L103;
  120475. ix2=iw+ido;
  120476. ix3=ix2+ido;
  120477. if(na!=0)
  120478. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120479. else
  120480. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120481. na=1-na;
  120482. goto L115;
  120483. L103:
  120484. if(ip!=2)goto L106;
  120485. if(na!=0)
  120486. dradb2(ido,l1,ch,c,wa+iw-1);
  120487. else
  120488. dradb2(ido,l1,c,ch,wa+iw-1);
  120489. na=1-na;
  120490. goto L115;
  120491. L106:
  120492. if(ip!=3)goto L109;
  120493. ix2=iw+ido;
  120494. if(na!=0)
  120495. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  120496. else
  120497. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  120498. na=1-na;
  120499. goto L115;
  120500. L109:
  120501. /* The radix five case can be translated later..... */
  120502. /* if(ip!=5)goto L112;
  120503. ix2=iw+ido;
  120504. ix3=ix2+ido;
  120505. ix4=ix3+ido;
  120506. if(na!=0)
  120507. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120508. else
  120509. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120510. na=1-na;
  120511. goto L115;
  120512. L112:*/
  120513. if(na!=0)
  120514. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  120515. else
  120516. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  120517. if(ido==1)na=1-na;
  120518. L115:
  120519. l1=l2;
  120520. iw+=(ip-1)*ido;
  120521. }
  120522. if(na==0)return;
  120523. for(i=0;i<n;i++)c[i]=ch[i];
  120524. }
  120525. void drft_forward(drft_lookup *l,float *data){
  120526. if(l->n==1)return;
  120527. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120528. }
  120529. void drft_backward(drft_lookup *l,float *data){
  120530. if (l->n==1)return;
  120531. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120532. }
  120533. void drft_init(drft_lookup *l,int n){
  120534. l->n=n;
  120535. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  120536. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  120537. fdrffti(n, l->trigcache, l->splitcache);
  120538. }
  120539. void drft_clear(drft_lookup *l){
  120540. if(l){
  120541. if(l->trigcache)_ogg_free(l->trigcache);
  120542. if(l->splitcache)_ogg_free(l->splitcache);
  120543. memset(l,0,sizeof(*l));
  120544. }
  120545. }
  120546. #endif
  120547. /*** End of inlined file: smallft.c ***/
  120548. /*** Start of inlined file: synthesis.c ***/
  120549. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120550. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120551. // tasks..
  120552. #if JUCE_MSVC
  120553. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120554. #endif
  120555. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120556. #if JUCE_USE_OGGVORBIS
  120557. #include <stdio.h>
  120558. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  120559. vorbis_dsp_state *vd=vb->vd;
  120560. private_state *b=(private_state*)vd->backend_state;
  120561. vorbis_info *vi=vd->vi;
  120562. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  120563. oggpack_buffer *opb=&vb->opb;
  120564. int type,mode,i;
  120565. /* first things first. Make sure decode is ready */
  120566. _vorbis_block_ripcord(vb);
  120567. oggpack_readinit(opb,op->packet,op->bytes);
  120568. /* Check the packet type */
  120569. if(oggpack_read(opb,1)!=0){
  120570. /* Oops. This is not an audio data packet */
  120571. return(OV_ENOTAUDIO);
  120572. }
  120573. /* read our mode and pre/post windowsize */
  120574. mode=oggpack_read(opb,b->modebits);
  120575. if(mode==-1)return(OV_EBADPACKET);
  120576. vb->mode=mode;
  120577. vb->W=ci->mode_param[mode]->blockflag;
  120578. if(vb->W){
  120579. /* this doesn;t get mapped through mode selection as it's used
  120580. only for window selection */
  120581. vb->lW=oggpack_read(opb,1);
  120582. vb->nW=oggpack_read(opb,1);
  120583. if(vb->nW==-1) return(OV_EBADPACKET);
  120584. }else{
  120585. vb->lW=0;
  120586. vb->nW=0;
  120587. }
  120588. /* more setup */
  120589. vb->granulepos=op->granulepos;
  120590. vb->sequence=op->packetno;
  120591. vb->eofflag=op->e_o_s;
  120592. /* alloc pcm passback storage */
  120593. vb->pcmend=ci->blocksizes[vb->W];
  120594. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  120595. for(i=0;i<vi->channels;i++)
  120596. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  120597. /* unpack_header enforces range checking */
  120598. type=ci->map_type[ci->mode_param[mode]->mapping];
  120599. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  120600. mapping]));
  120601. }
  120602. /* used to track pcm position without actually performing decode.
  120603. Useful for sequential 'fast forward' */
  120604. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  120605. vorbis_dsp_state *vd=vb->vd;
  120606. private_state *b=(private_state*)vd->backend_state;
  120607. vorbis_info *vi=vd->vi;
  120608. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120609. oggpack_buffer *opb=&vb->opb;
  120610. int mode;
  120611. /* first things first. Make sure decode is ready */
  120612. _vorbis_block_ripcord(vb);
  120613. oggpack_readinit(opb,op->packet,op->bytes);
  120614. /* Check the packet type */
  120615. if(oggpack_read(opb,1)!=0){
  120616. /* Oops. This is not an audio data packet */
  120617. return(OV_ENOTAUDIO);
  120618. }
  120619. /* read our mode and pre/post windowsize */
  120620. mode=oggpack_read(opb,b->modebits);
  120621. if(mode==-1)return(OV_EBADPACKET);
  120622. vb->mode=mode;
  120623. vb->W=ci->mode_param[mode]->blockflag;
  120624. if(vb->W){
  120625. vb->lW=oggpack_read(opb,1);
  120626. vb->nW=oggpack_read(opb,1);
  120627. if(vb->nW==-1) return(OV_EBADPACKET);
  120628. }else{
  120629. vb->lW=0;
  120630. vb->nW=0;
  120631. }
  120632. /* more setup */
  120633. vb->granulepos=op->granulepos;
  120634. vb->sequence=op->packetno;
  120635. vb->eofflag=op->e_o_s;
  120636. /* no pcm */
  120637. vb->pcmend=0;
  120638. vb->pcm=NULL;
  120639. return(0);
  120640. }
  120641. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  120642. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120643. oggpack_buffer opb;
  120644. int mode;
  120645. oggpack_readinit(&opb,op->packet,op->bytes);
  120646. /* Check the packet type */
  120647. if(oggpack_read(&opb,1)!=0){
  120648. /* Oops. This is not an audio data packet */
  120649. return(OV_ENOTAUDIO);
  120650. }
  120651. {
  120652. int modebits=0;
  120653. int v=ci->modes;
  120654. while(v>1){
  120655. modebits++;
  120656. v>>=1;
  120657. }
  120658. /* read our mode and pre/post windowsize */
  120659. mode=oggpack_read(&opb,modebits);
  120660. }
  120661. if(mode==-1)return(OV_EBADPACKET);
  120662. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  120663. }
  120664. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  120665. /* set / clear half-sample-rate mode */
  120666. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120667. /* right now, our MDCT can't handle < 64 sample windows. */
  120668. if(ci->blocksizes[0]<=64 && flag)return -1;
  120669. ci->halfrate_flag=(flag?1:0);
  120670. return 0;
  120671. }
  120672. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  120673. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120674. return ci->halfrate_flag;
  120675. }
  120676. #endif
  120677. /*** End of inlined file: synthesis.c ***/
  120678. /*** Start of inlined file: vorbisenc.c ***/
  120679. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120680. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120681. // tasks..
  120682. #if JUCE_MSVC
  120683. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120684. #endif
  120685. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120686. #if JUCE_USE_OGGVORBIS
  120687. #include <stdlib.h>
  120688. #include <string.h>
  120689. #include <math.h>
  120690. /* careful with this; it's using static array sizing to make managing
  120691. all the modes a little less annoying. If we use a residue backend
  120692. with > 12 partition types, or a different division of iteration,
  120693. this needs to be updated. */
  120694. typedef struct {
  120695. static_codebook *books[12][3];
  120696. } static_bookblock;
  120697. typedef struct {
  120698. int res_type;
  120699. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  120700. vorbis_info_residue0 *res;
  120701. static_codebook *book_aux;
  120702. static_codebook *book_aux_managed;
  120703. static_bookblock *books_base;
  120704. static_bookblock *books_base_managed;
  120705. } vorbis_residue_template;
  120706. typedef struct {
  120707. vorbis_info_mapping0 *map;
  120708. vorbis_residue_template *res;
  120709. } vorbis_mapping_template;
  120710. typedef struct vp_adjblock{
  120711. int block[P_BANDS];
  120712. } vp_adjblock;
  120713. typedef struct {
  120714. int data[NOISE_COMPAND_LEVELS];
  120715. } compandblock;
  120716. /* high level configuration information for setting things up
  120717. step-by-step with the detailed vorbis_encode_ctl interface.
  120718. There's a fair amount of redundancy such that interactive setup
  120719. does not directly deal with any vorbis_info or codec_setup_info
  120720. initialization; it's all stored (until full init) in this highlevel
  120721. setup, then flushed out to the real codec setup structs later. */
  120722. typedef struct {
  120723. int att[P_NOISECURVES];
  120724. float boost;
  120725. float decay;
  120726. } att3;
  120727. typedef struct { int data[P_NOISECURVES]; } adj3;
  120728. typedef struct {
  120729. int pre[PACKETBLOBS];
  120730. int post[PACKETBLOBS];
  120731. float kHz[PACKETBLOBS];
  120732. float lowpasskHz[PACKETBLOBS];
  120733. } adj_stereo;
  120734. typedef struct {
  120735. int lo;
  120736. int hi;
  120737. int fixed;
  120738. } noiseguard;
  120739. typedef struct {
  120740. int data[P_NOISECURVES][17];
  120741. } noise3;
  120742. typedef struct {
  120743. int mappings;
  120744. double *rate_mapping;
  120745. double *quality_mapping;
  120746. int coupling_restriction;
  120747. long samplerate_min_restriction;
  120748. long samplerate_max_restriction;
  120749. int *blocksize_short;
  120750. int *blocksize_long;
  120751. att3 *psy_tone_masteratt;
  120752. int *psy_tone_0dB;
  120753. int *psy_tone_dBsuppress;
  120754. vp_adjblock *psy_tone_adj_impulse;
  120755. vp_adjblock *psy_tone_adj_long;
  120756. vp_adjblock *psy_tone_adj_other;
  120757. noiseguard *psy_noiseguards;
  120758. noise3 *psy_noise_bias_impulse;
  120759. noise3 *psy_noise_bias_padding;
  120760. noise3 *psy_noise_bias_trans;
  120761. noise3 *psy_noise_bias_long;
  120762. int *psy_noise_dBsuppress;
  120763. compandblock *psy_noise_compand;
  120764. double *psy_noise_compand_short_mapping;
  120765. double *psy_noise_compand_long_mapping;
  120766. int *psy_noise_normal_start[2];
  120767. int *psy_noise_normal_partition[2];
  120768. double *psy_noise_normal_thresh;
  120769. int *psy_ath_float;
  120770. int *psy_ath_abs;
  120771. double *psy_lowpass;
  120772. vorbis_info_psy_global *global_params;
  120773. double *global_mapping;
  120774. adj_stereo *stereo_modes;
  120775. static_codebook ***floor_books;
  120776. vorbis_info_floor1 *floor_params;
  120777. int *floor_short_mapping;
  120778. int *floor_long_mapping;
  120779. vorbis_mapping_template *maps;
  120780. } ve_setup_data_template;
  120781. /* a few static coder conventions */
  120782. static vorbis_info_mode _mode_template[2]={
  120783. {0,0,0,0},
  120784. {1,0,0,1}
  120785. };
  120786. static vorbis_info_mapping0 _map_nominal[2]={
  120787. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  120788. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  120789. };
  120790. /*** Start of inlined file: setup_44.h ***/
  120791. /*** Start of inlined file: floor_all.h ***/
  120792. /*** Start of inlined file: floor_books.h ***/
  120793. static long _huff_lengthlist_line_256x7_0sub1[] = {
  120794. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  120795. };
  120796. static static_codebook _huff_book_line_256x7_0sub1 = {
  120797. 1, 9,
  120798. _huff_lengthlist_line_256x7_0sub1,
  120799. 0, 0, 0, 0, 0,
  120800. NULL,
  120801. NULL,
  120802. NULL,
  120803. NULL,
  120804. 0
  120805. };
  120806. static long _huff_lengthlist_line_256x7_0sub2[] = {
  120807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  120808. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  120809. };
  120810. static static_codebook _huff_book_line_256x7_0sub2 = {
  120811. 1, 25,
  120812. _huff_lengthlist_line_256x7_0sub2,
  120813. 0, 0, 0, 0, 0,
  120814. NULL,
  120815. NULL,
  120816. NULL,
  120817. NULL,
  120818. 0
  120819. };
  120820. static long _huff_lengthlist_line_256x7_0sub3[] = {
  120821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  120823. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  120824. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  120825. };
  120826. static static_codebook _huff_book_line_256x7_0sub3 = {
  120827. 1, 64,
  120828. _huff_lengthlist_line_256x7_0sub3,
  120829. 0, 0, 0, 0, 0,
  120830. NULL,
  120831. NULL,
  120832. NULL,
  120833. NULL,
  120834. 0
  120835. };
  120836. static long _huff_lengthlist_line_256x7_1sub1[] = {
  120837. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  120838. };
  120839. static static_codebook _huff_book_line_256x7_1sub1 = {
  120840. 1, 9,
  120841. _huff_lengthlist_line_256x7_1sub1,
  120842. 0, 0, 0, 0, 0,
  120843. NULL,
  120844. NULL,
  120845. NULL,
  120846. NULL,
  120847. 0
  120848. };
  120849. static long _huff_lengthlist_line_256x7_1sub2[] = {
  120850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  120851. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  120852. };
  120853. static static_codebook _huff_book_line_256x7_1sub2 = {
  120854. 1, 25,
  120855. _huff_lengthlist_line_256x7_1sub2,
  120856. 0, 0, 0, 0, 0,
  120857. NULL,
  120858. NULL,
  120859. NULL,
  120860. NULL,
  120861. 0
  120862. };
  120863. static long _huff_lengthlist_line_256x7_1sub3[] = {
  120864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  120866. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  120867. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  120868. };
  120869. static static_codebook _huff_book_line_256x7_1sub3 = {
  120870. 1, 64,
  120871. _huff_lengthlist_line_256x7_1sub3,
  120872. 0, 0, 0, 0, 0,
  120873. NULL,
  120874. NULL,
  120875. NULL,
  120876. NULL,
  120877. 0
  120878. };
  120879. static long _huff_lengthlist_line_256x7_class0[] = {
  120880. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  120881. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  120882. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  120883. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  120884. };
  120885. static static_codebook _huff_book_line_256x7_class0 = {
  120886. 1, 64,
  120887. _huff_lengthlist_line_256x7_class0,
  120888. 0, 0, 0, 0, 0,
  120889. NULL,
  120890. NULL,
  120891. NULL,
  120892. NULL,
  120893. 0
  120894. };
  120895. static long _huff_lengthlist_line_256x7_class1[] = {
  120896. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  120897. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  120898. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  120899. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  120900. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  120901. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  120902. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  120903. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  120904. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  120905. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  120906. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  120907. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  120908. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120909. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120910. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  120911. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  120912. };
  120913. static static_codebook _huff_book_line_256x7_class1 = {
  120914. 1, 256,
  120915. _huff_lengthlist_line_256x7_class1,
  120916. 0, 0, 0, 0, 0,
  120917. NULL,
  120918. NULL,
  120919. NULL,
  120920. NULL,
  120921. 0
  120922. };
  120923. static long _huff_lengthlist_line_512x17_0sub0[] = {
  120924. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  120925. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  120926. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  120927. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  120928. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  120929. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  120930. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  120931. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  120932. };
  120933. static static_codebook _huff_book_line_512x17_0sub0 = {
  120934. 1, 128,
  120935. _huff_lengthlist_line_512x17_0sub0,
  120936. 0, 0, 0, 0, 0,
  120937. NULL,
  120938. NULL,
  120939. NULL,
  120940. NULL,
  120941. 0
  120942. };
  120943. static long _huff_lengthlist_line_512x17_1sub0[] = {
  120944. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  120945. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  120946. };
  120947. static static_codebook _huff_book_line_512x17_1sub0 = {
  120948. 1, 32,
  120949. _huff_lengthlist_line_512x17_1sub0,
  120950. 0, 0, 0, 0, 0,
  120951. NULL,
  120952. NULL,
  120953. NULL,
  120954. NULL,
  120955. 0
  120956. };
  120957. static long _huff_lengthlist_line_512x17_1sub1[] = {
  120958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120960. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  120961. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  120962. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  120963. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  120964. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  120965. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  120966. };
  120967. static static_codebook _huff_book_line_512x17_1sub1 = {
  120968. 1, 128,
  120969. _huff_lengthlist_line_512x17_1sub1,
  120970. 0, 0, 0, 0, 0,
  120971. NULL,
  120972. NULL,
  120973. NULL,
  120974. NULL,
  120975. 0
  120976. };
  120977. static long _huff_lengthlist_line_512x17_2sub1[] = {
  120978. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  120979. 5, 3,
  120980. };
  120981. static static_codebook _huff_book_line_512x17_2sub1 = {
  120982. 1, 18,
  120983. _huff_lengthlist_line_512x17_2sub1,
  120984. 0, 0, 0, 0, 0,
  120985. NULL,
  120986. NULL,
  120987. NULL,
  120988. NULL,
  120989. 0
  120990. };
  120991. static long _huff_lengthlist_line_512x17_2sub2[] = {
  120992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120993. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  120994. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  120995. 9, 8,
  120996. };
  120997. static static_codebook _huff_book_line_512x17_2sub2 = {
  120998. 1, 50,
  120999. _huff_lengthlist_line_512x17_2sub2,
  121000. 0, 0, 0, 0, 0,
  121001. NULL,
  121002. NULL,
  121003. NULL,
  121004. NULL,
  121005. 0
  121006. };
  121007. static long _huff_lengthlist_line_512x17_2sub3[] = {
  121008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121011. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  121012. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  121013. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121014. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121015. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121016. };
  121017. static static_codebook _huff_book_line_512x17_2sub3 = {
  121018. 1, 128,
  121019. _huff_lengthlist_line_512x17_2sub3,
  121020. 0, 0, 0, 0, 0,
  121021. NULL,
  121022. NULL,
  121023. NULL,
  121024. NULL,
  121025. 0
  121026. };
  121027. static long _huff_lengthlist_line_512x17_3sub1[] = {
  121028. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  121029. 5, 5,
  121030. };
  121031. static static_codebook _huff_book_line_512x17_3sub1 = {
  121032. 1, 18,
  121033. _huff_lengthlist_line_512x17_3sub1,
  121034. 0, 0, 0, 0, 0,
  121035. NULL,
  121036. NULL,
  121037. NULL,
  121038. NULL,
  121039. 0
  121040. };
  121041. static long _huff_lengthlist_line_512x17_3sub2[] = {
  121042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121043. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  121044. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  121045. 11,14,
  121046. };
  121047. static static_codebook _huff_book_line_512x17_3sub2 = {
  121048. 1, 50,
  121049. _huff_lengthlist_line_512x17_3sub2,
  121050. 0, 0, 0, 0, 0,
  121051. NULL,
  121052. NULL,
  121053. NULL,
  121054. NULL,
  121055. 0
  121056. };
  121057. static long _huff_lengthlist_line_512x17_3sub3[] = {
  121058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121061. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  121062. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121063. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121064. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121065. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121066. };
  121067. static static_codebook _huff_book_line_512x17_3sub3 = {
  121068. 1, 128,
  121069. _huff_lengthlist_line_512x17_3sub3,
  121070. 0, 0, 0, 0, 0,
  121071. NULL,
  121072. NULL,
  121073. NULL,
  121074. NULL,
  121075. 0
  121076. };
  121077. static long _huff_lengthlist_line_512x17_class1[] = {
  121078. 1, 2, 3, 6, 5, 4, 7, 7,
  121079. };
  121080. static static_codebook _huff_book_line_512x17_class1 = {
  121081. 1, 8,
  121082. _huff_lengthlist_line_512x17_class1,
  121083. 0, 0, 0, 0, 0,
  121084. NULL,
  121085. NULL,
  121086. NULL,
  121087. NULL,
  121088. 0
  121089. };
  121090. static long _huff_lengthlist_line_512x17_class2[] = {
  121091. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  121092. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  121093. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  121094. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  121095. };
  121096. static static_codebook _huff_book_line_512x17_class2 = {
  121097. 1, 64,
  121098. _huff_lengthlist_line_512x17_class2,
  121099. 0, 0, 0, 0, 0,
  121100. NULL,
  121101. NULL,
  121102. NULL,
  121103. NULL,
  121104. 0
  121105. };
  121106. static long _huff_lengthlist_line_512x17_class3[] = {
  121107. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  121108. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  121109. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  121110. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  121111. };
  121112. static static_codebook _huff_book_line_512x17_class3 = {
  121113. 1, 64,
  121114. _huff_lengthlist_line_512x17_class3,
  121115. 0, 0, 0, 0, 0,
  121116. NULL,
  121117. NULL,
  121118. NULL,
  121119. NULL,
  121120. 0
  121121. };
  121122. static long _huff_lengthlist_line_128x4_class0[] = {
  121123. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  121124. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  121125. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  121126. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  121127. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  121128. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  121129. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  121130. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  121131. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  121132. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  121133. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  121134. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  121135. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  121136. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  121137. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  121138. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  121139. };
  121140. static static_codebook _huff_book_line_128x4_class0 = {
  121141. 1, 256,
  121142. _huff_lengthlist_line_128x4_class0,
  121143. 0, 0, 0, 0, 0,
  121144. NULL,
  121145. NULL,
  121146. NULL,
  121147. NULL,
  121148. 0
  121149. };
  121150. static long _huff_lengthlist_line_128x4_0sub0[] = {
  121151. 2, 2, 2, 2,
  121152. };
  121153. static static_codebook _huff_book_line_128x4_0sub0 = {
  121154. 1, 4,
  121155. _huff_lengthlist_line_128x4_0sub0,
  121156. 0, 0, 0, 0, 0,
  121157. NULL,
  121158. NULL,
  121159. NULL,
  121160. NULL,
  121161. 0
  121162. };
  121163. static long _huff_lengthlist_line_128x4_0sub1[] = {
  121164. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  121165. };
  121166. static static_codebook _huff_book_line_128x4_0sub1 = {
  121167. 1, 10,
  121168. _huff_lengthlist_line_128x4_0sub1,
  121169. 0, 0, 0, 0, 0,
  121170. NULL,
  121171. NULL,
  121172. NULL,
  121173. NULL,
  121174. 0
  121175. };
  121176. static long _huff_lengthlist_line_128x4_0sub2[] = {
  121177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  121178. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  121179. };
  121180. static static_codebook _huff_book_line_128x4_0sub2 = {
  121181. 1, 25,
  121182. _huff_lengthlist_line_128x4_0sub2,
  121183. 0, 0, 0, 0, 0,
  121184. NULL,
  121185. NULL,
  121186. NULL,
  121187. NULL,
  121188. 0
  121189. };
  121190. static long _huff_lengthlist_line_128x4_0sub3[] = {
  121191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  121193. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  121194. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  121195. };
  121196. static static_codebook _huff_book_line_128x4_0sub3 = {
  121197. 1, 64,
  121198. _huff_lengthlist_line_128x4_0sub3,
  121199. 0, 0, 0, 0, 0,
  121200. NULL,
  121201. NULL,
  121202. NULL,
  121203. NULL,
  121204. 0
  121205. };
  121206. static long _huff_lengthlist_line_256x4_class0[] = {
  121207. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  121208. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  121209. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  121210. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  121211. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  121212. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  121213. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  121214. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  121215. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  121216. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  121217. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  121218. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  121219. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  121220. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  121221. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  121222. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  121223. };
  121224. static static_codebook _huff_book_line_256x4_class0 = {
  121225. 1, 256,
  121226. _huff_lengthlist_line_256x4_class0,
  121227. 0, 0, 0, 0, 0,
  121228. NULL,
  121229. NULL,
  121230. NULL,
  121231. NULL,
  121232. 0
  121233. };
  121234. static long _huff_lengthlist_line_256x4_0sub0[] = {
  121235. 2, 2, 2, 2,
  121236. };
  121237. static static_codebook _huff_book_line_256x4_0sub0 = {
  121238. 1, 4,
  121239. _huff_lengthlist_line_256x4_0sub0,
  121240. 0, 0, 0, 0, 0,
  121241. NULL,
  121242. NULL,
  121243. NULL,
  121244. NULL,
  121245. 0
  121246. };
  121247. static long _huff_lengthlist_line_256x4_0sub1[] = {
  121248. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  121249. };
  121250. static static_codebook _huff_book_line_256x4_0sub1 = {
  121251. 1, 10,
  121252. _huff_lengthlist_line_256x4_0sub1,
  121253. 0, 0, 0, 0, 0,
  121254. NULL,
  121255. NULL,
  121256. NULL,
  121257. NULL,
  121258. 0
  121259. };
  121260. static long _huff_lengthlist_line_256x4_0sub2[] = {
  121261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  121262. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  121263. };
  121264. static static_codebook _huff_book_line_256x4_0sub2 = {
  121265. 1, 25,
  121266. _huff_lengthlist_line_256x4_0sub2,
  121267. 0, 0, 0, 0, 0,
  121268. NULL,
  121269. NULL,
  121270. NULL,
  121271. NULL,
  121272. 0
  121273. };
  121274. static long _huff_lengthlist_line_256x4_0sub3[] = {
  121275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  121277. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  121278. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  121279. };
  121280. static static_codebook _huff_book_line_256x4_0sub3 = {
  121281. 1, 64,
  121282. _huff_lengthlist_line_256x4_0sub3,
  121283. 0, 0, 0, 0, 0,
  121284. NULL,
  121285. NULL,
  121286. NULL,
  121287. NULL,
  121288. 0
  121289. };
  121290. static long _huff_lengthlist_line_128x7_class0[] = {
  121291. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  121292. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  121293. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  121294. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  121295. };
  121296. static static_codebook _huff_book_line_128x7_class0 = {
  121297. 1, 64,
  121298. _huff_lengthlist_line_128x7_class0,
  121299. 0, 0, 0, 0, 0,
  121300. NULL,
  121301. NULL,
  121302. NULL,
  121303. NULL,
  121304. 0
  121305. };
  121306. static long _huff_lengthlist_line_128x7_class1[] = {
  121307. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  121308. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  121309. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  121310. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121311. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  121312. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  121313. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  121314. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  121315. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  121316. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  121317. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  121318. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  121319. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  121320. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  121321. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  121322. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  121323. };
  121324. static static_codebook _huff_book_line_128x7_class1 = {
  121325. 1, 256,
  121326. _huff_lengthlist_line_128x7_class1,
  121327. 0, 0, 0, 0, 0,
  121328. NULL,
  121329. NULL,
  121330. NULL,
  121331. NULL,
  121332. 0
  121333. };
  121334. static long _huff_lengthlist_line_128x7_0sub1[] = {
  121335. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  121336. };
  121337. static static_codebook _huff_book_line_128x7_0sub1 = {
  121338. 1, 9,
  121339. _huff_lengthlist_line_128x7_0sub1,
  121340. 0, 0, 0, 0, 0,
  121341. NULL,
  121342. NULL,
  121343. NULL,
  121344. NULL,
  121345. 0
  121346. };
  121347. static long _huff_lengthlist_line_128x7_0sub2[] = {
  121348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  121349. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  121350. };
  121351. static static_codebook _huff_book_line_128x7_0sub2 = {
  121352. 1, 25,
  121353. _huff_lengthlist_line_128x7_0sub2,
  121354. 0, 0, 0, 0, 0,
  121355. NULL,
  121356. NULL,
  121357. NULL,
  121358. NULL,
  121359. 0
  121360. };
  121361. static long _huff_lengthlist_line_128x7_0sub3[] = {
  121362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  121364. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121365. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  121366. };
  121367. static static_codebook _huff_book_line_128x7_0sub3 = {
  121368. 1, 64,
  121369. _huff_lengthlist_line_128x7_0sub3,
  121370. 0, 0, 0, 0, 0,
  121371. NULL,
  121372. NULL,
  121373. NULL,
  121374. NULL,
  121375. 0
  121376. };
  121377. static long _huff_lengthlist_line_128x7_1sub1[] = {
  121378. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  121379. };
  121380. static static_codebook _huff_book_line_128x7_1sub1 = {
  121381. 1, 9,
  121382. _huff_lengthlist_line_128x7_1sub1,
  121383. 0, 0, 0, 0, 0,
  121384. NULL,
  121385. NULL,
  121386. NULL,
  121387. NULL,
  121388. 0
  121389. };
  121390. static long _huff_lengthlist_line_128x7_1sub2[] = {
  121391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  121392. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  121393. };
  121394. static static_codebook _huff_book_line_128x7_1sub2 = {
  121395. 1, 25,
  121396. _huff_lengthlist_line_128x7_1sub2,
  121397. 0, 0, 0, 0, 0,
  121398. NULL,
  121399. NULL,
  121400. NULL,
  121401. NULL,
  121402. 0
  121403. };
  121404. static long _huff_lengthlist_line_128x7_1sub3[] = {
  121405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  121407. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  121408. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  121409. };
  121410. static static_codebook _huff_book_line_128x7_1sub3 = {
  121411. 1, 64,
  121412. _huff_lengthlist_line_128x7_1sub3,
  121413. 0, 0, 0, 0, 0,
  121414. NULL,
  121415. NULL,
  121416. NULL,
  121417. NULL,
  121418. 0
  121419. };
  121420. static long _huff_lengthlist_line_128x11_class1[] = {
  121421. 1, 6, 3, 7, 2, 4, 5, 7,
  121422. };
  121423. static static_codebook _huff_book_line_128x11_class1 = {
  121424. 1, 8,
  121425. _huff_lengthlist_line_128x11_class1,
  121426. 0, 0, 0, 0, 0,
  121427. NULL,
  121428. NULL,
  121429. NULL,
  121430. NULL,
  121431. 0
  121432. };
  121433. static long _huff_lengthlist_line_128x11_class2[] = {
  121434. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  121435. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  121436. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  121437. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  121438. };
  121439. static static_codebook _huff_book_line_128x11_class2 = {
  121440. 1, 64,
  121441. _huff_lengthlist_line_128x11_class2,
  121442. 0, 0, 0, 0, 0,
  121443. NULL,
  121444. NULL,
  121445. NULL,
  121446. NULL,
  121447. 0
  121448. };
  121449. static long _huff_lengthlist_line_128x11_class3[] = {
  121450. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  121451. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  121452. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  121453. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  121454. };
  121455. static static_codebook _huff_book_line_128x11_class3 = {
  121456. 1, 64,
  121457. _huff_lengthlist_line_128x11_class3,
  121458. 0, 0, 0, 0, 0,
  121459. NULL,
  121460. NULL,
  121461. NULL,
  121462. NULL,
  121463. 0
  121464. };
  121465. static long _huff_lengthlist_line_128x11_0sub0[] = {
  121466. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121467. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  121468. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  121469. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  121470. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  121471. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  121472. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  121473. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121474. };
  121475. static static_codebook _huff_book_line_128x11_0sub0 = {
  121476. 1, 128,
  121477. _huff_lengthlist_line_128x11_0sub0,
  121478. 0, 0, 0, 0, 0,
  121479. NULL,
  121480. NULL,
  121481. NULL,
  121482. NULL,
  121483. 0
  121484. };
  121485. static long _huff_lengthlist_line_128x11_1sub0[] = {
  121486. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  121487. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  121488. };
  121489. static static_codebook _huff_book_line_128x11_1sub0 = {
  121490. 1, 32,
  121491. _huff_lengthlist_line_128x11_1sub0,
  121492. 0, 0, 0, 0, 0,
  121493. NULL,
  121494. NULL,
  121495. NULL,
  121496. NULL,
  121497. 0
  121498. };
  121499. static long _huff_lengthlist_line_128x11_1sub1[] = {
  121500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121502. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121503. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  121504. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  121505. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  121506. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  121507. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  121508. };
  121509. static static_codebook _huff_book_line_128x11_1sub1 = {
  121510. 1, 128,
  121511. _huff_lengthlist_line_128x11_1sub1,
  121512. 0, 0, 0, 0, 0,
  121513. NULL,
  121514. NULL,
  121515. NULL,
  121516. NULL,
  121517. 0
  121518. };
  121519. static long _huff_lengthlist_line_128x11_2sub1[] = {
  121520. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  121521. 5, 5,
  121522. };
  121523. static static_codebook _huff_book_line_128x11_2sub1 = {
  121524. 1, 18,
  121525. _huff_lengthlist_line_128x11_2sub1,
  121526. 0, 0, 0, 0, 0,
  121527. NULL,
  121528. NULL,
  121529. NULL,
  121530. NULL,
  121531. 0
  121532. };
  121533. static long _huff_lengthlist_line_128x11_2sub2[] = {
  121534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121535. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  121536. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  121537. 8,11,
  121538. };
  121539. static static_codebook _huff_book_line_128x11_2sub2 = {
  121540. 1, 50,
  121541. _huff_lengthlist_line_128x11_2sub2,
  121542. 0, 0, 0, 0, 0,
  121543. NULL,
  121544. NULL,
  121545. NULL,
  121546. NULL,
  121547. 0
  121548. };
  121549. static long _huff_lengthlist_line_128x11_2sub3[] = {
  121550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121553. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  121554. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121555. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121556. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121557. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121558. };
  121559. static static_codebook _huff_book_line_128x11_2sub3 = {
  121560. 1, 128,
  121561. _huff_lengthlist_line_128x11_2sub3,
  121562. 0, 0, 0, 0, 0,
  121563. NULL,
  121564. NULL,
  121565. NULL,
  121566. NULL,
  121567. 0
  121568. };
  121569. static long _huff_lengthlist_line_128x11_3sub1[] = {
  121570. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  121571. 5, 4,
  121572. };
  121573. static static_codebook _huff_book_line_128x11_3sub1 = {
  121574. 1, 18,
  121575. _huff_lengthlist_line_128x11_3sub1,
  121576. 0, 0, 0, 0, 0,
  121577. NULL,
  121578. NULL,
  121579. NULL,
  121580. NULL,
  121581. 0
  121582. };
  121583. static long _huff_lengthlist_line_128x11_3sub2[] = {
  121584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121585. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  121586. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  121587. 12, 6,
  121588. };
  121589. static static_codebook _huff_book_line_128x11_3sub2 = {
  121590. 1, 50,
  121591. _huff_lengthlist_line_128x11_3sub2,
  121592. 0, 0, 0, 0, 0,
  121593. NULL,
  121594. NULL,
  121595. NULL,
  121596. NULL,
  121597. 0
  121598. };
  121599. static long _huff_lengthlist_line_128x11_3sub3[] = {
  121600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121603. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  121604. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  121605. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121606. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121607. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  121608. };
  121609. static static_codebook _huff_book_line_128x11_3sub3 = {
  121610. 1, 128,
  121611. _huff_lengthlist_line_128x11_3sub3,
  121612. 0, 0, 0, 0, 0,
  121613. NULL,
  121614. NULL,
  121615. NULL,
  121616. NULL,
  121617. 0
  121618. };
  121619. static long _huff_lengthlist_line_128x17_class1[] = {
  121620. 1, 3, 4, 7, 2, 5, 6, 7,
  121621. };
  121622. static static_codebook _huff_book_line_128x17_class1 = {
  121623. 1, 8,
  121624. _huff_lengthlist_line_128x17_class1,
  121625. 0, 0, 0, 0, 0,
  121626. NULL,
  121627. NULL,
  121628. NULL,
  121629. NULL,
  121630. 0
  121631. };
  121632. static long _huff_lengthlist_line_128x17_class2[] = {
  121633. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  121634. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  121635. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  121636. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  121637. };
  121638. static static_codebook _huff_book_line_128x17_class2 = {
  121639. 1, 64,
  121640. _huff_lengthlist_line_128x17_class2,
  121641. 0, 0, 0, 0, 0,
  121642. NULL,
  121643. NULL,
  121644. NULL,
  121645. NULL,
  121646. 0
  121647. };
  121648. static long _huff_lengthlist_line_128x17_class3[] = {
  121649. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  121650. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  121651. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  121652. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  121653. };
  121654. static static_codebook _huff_book_line_128x17_class3 = {
  121655. 1, 64,
  121656. _huff_lengthlist_line_128x17_class3,
  121657. 0, 0, 0, 0, 0,
  121658. NULL,
  121659. NULL,
  121660. NULL,
  121661. NULL,
  121662. 0
  121663. };
  121664. static long _huff_lengthlist_line_128x17_0sub0[] = {
  121665. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121666. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  121667. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  121668. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  121669. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  121670. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  121671. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  121672. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121673. };
  121674. static static_codebook _huff_book_line_128x17_0sub0 = {
  121675. 1, 128,
  121676. _huff_lengthlist_line_128x17_0sub0,
  121677. 0, 0, 0, 0, 0,
  121678. NULL,
  121679. NULL,
  121680. NULL,
  121681. NULL,
  121682. 0
  121683. };
  121684. static long _huff_lengthlist_line_128x17_1sub0[] = {
  121685. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121686. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  121687. };
  121688. static static_codebook _huff_book_line_128x17_1sub0 = {
  121689. 1, 32,
  121690. _huff_lengthlist_line_128x17_1sub0,
  121691. 0, 0, 0, 0, 0,
  121692. NULL,
  121693. NULL,
  121694. NULL,
  121695. NULL,
  121696. 0
  121697. };
  121698. static long _huff_lengthlist_line_128x17_1sub1[] = {
  121699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121701. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  121702. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  121703. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  121704. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  121705. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  121706. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  121707. };
  121708. static static_codebook _huff_book_line_128x17_1sub1 = {
  121709. 1, 128,
  121710. _huff_lengthlist_line_128x17_1sub1,
  121711. 0, 0, 0, 0, 0,
  121712. NULL,
  121713. NULL,
  121714. NULL,
  121715. NULL,
  121716. 0
  121717. };
  121718. static long _huff_lengthlist_line_128x17_2sub1[] = {
  121719. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  121720. 9, 4,
  121721. };
  121722. static static_codebook _huff_book_line_128x17_2sub1 = {
  121723. 1, 18,
  121724. _huff_lengthlist_line_128x17_2sub1,
  121725. 0, 0, 0, 0, 0,
  121726. NULL,
  121727. NULL,
  121728. NULL,
  121729. NULL,
  121730. 0
  121731. };
  121732. static long _huff_lengthlist_line_128x17_2sub2[] = {
  121733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121734. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  121735. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  121736. 13,13,
  121737. };
  121738. static static_codebook _huff_book_line_128x17_2sub2 = {
  121739. 1, 50,
  121740. _huff_lengthlist_line_128x17_2sub2,
  121741. 0, 0, 0, 0, 0,
  121742. NULL,
  121743. NULL,
  121744. NULL,
  121745. NULL,
  121746. 0
  121747. };
  121748. static long _huff_lengthlist_line_128x17_2sub3[] = {
  121749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121752. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121753. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  121754. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121755. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121756. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121757. };
  121758. static static_codebook _huff_book_line_128x17_2sub3 = {
  121759. 1, 128,
  121760. _huff_lengthlist_line_128x17_2sub3,
  121761. 0, 0, 0, 0, 0,
  121762. NULL,
  121763. NULL,
  121764. NULL,
  121765. NULL,
  121766. 0
  121767. };
  121768. static long _huff_lengthlist_line_128x17_3sub1[] = {
  121769. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  121770. 6, 4,
  121771. };
  121772. static static_codebook _huff_book_line_128x17_3sub1 = {
  121773. 1, 18,
  121774. _huff_lengthlist_line_128x17_3sub1,
  121775. 0, 0, 0, 0, 0,
  121776. NULL,
  121777. NULL,
  121778. NULL,
  121779. NULL,
  121780. 0
  121781. };
  121782. static long _huff_lengthlist_line_128x17_3sub2[] = {
  121783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121784. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121785. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  121786. 10, 8,
  121787. };
  121788. static static_codebook _huff_book_line_128x17_3sub2 = {
  121789. 1, 50,
  121790. _huff_lengthlist_line_128x17_3sub2,
  121791. 0, 0, 0, 0, 0,
  121792. NULL,
  121793. NULL,
  121794. NULL,
  121795. NULL,
  121796. 0
  121797. };
  121798. static long _huff_lengthlist_line_128x17_3sub3[] = {
  121799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121802. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  121803. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  121804. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121805. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121806. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  121807. };
  121808. static static_codebook _huff_book_line_128x17_3sub3 = {
  121809. 1, 128,
  121810. _huff_lengthlist_line_128x17_3sub3,
  121811. 0, 0, 0, 0, 0,
  121812. NULL,
  121813. NULL,
  121814. NULL,
  121815. NULL,
  121816. 0
  121817. };
  121818. static long _huff_lengthlist_line_1024x27_class1[] = {
  121819. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  121820. };
  121821. static static_codebook _huff_book_line_1024x27_class1 = {
  121822. 1, 16,
  121823. _huff_lengthlist_line_1024x27_class1,
  121824. 0, 0, 0, 0, 0,
  121825. NULL,
  121826. NULL,
  121827. NULL,
  121828. NULL,
  121829. 0
  121830. };
  121831. static long _huff_lengthlist_line_1024x27_class2[] = {
  121832. 1, 4, 2, 6, 3, 7, 5, 7,
  121833. };
  121834. static static_codebook _huff_book_line_1024x27_class2 = {
  121835. 1, 8,
  121836. _huff_lengthlist_line_1024x27_class2,
  121837. 0, 0, 0, 0, 0,
  121838. NULL,
  121839. NULL,
  121840. NULL,
  121841. NULL,
  121842. 0
  121843. };
  121844. static long _huff_lengthlist_line_1024x27_class3[] = {
  121845. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  121846. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  121847. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  121848. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  121849. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  121850. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  121851. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  121852. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  121853. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  121854. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  121855. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  121856. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121857. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  121858. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  121859. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  121860. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121861. };
  121862. static static_codebook _huff_book_line_1024x27_class3 = {
  121863. 1, 256,
  121864. _huff_lengthlist_line_1024x27_class3,
  121865. 0, 0, 0, 0, 0,
  121866. NULL,
  121867. NULL,
  121868. NULL,
  121869. NULL,
  121870. 0
  121871. };
  121872. static long _huff_lengthlist_line_1024x27_class4[] = {
  121873. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  121874. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  121875. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  121876. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  121877. };
  121878. static static_codebook _huff_book_line_1024x27_class4 = {
  121879. 1, 64,
  121880. _huff_lengthlist_line_1024x27_class4,
  121881. 0, 0, 0, 0, 0,
  121882. NULL,
  121883. NULL,
  121884. NULL,
  121885. NULL,
  121886. 0
  121887. };
  121888. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  121889. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121890. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  121891. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  121892. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  121893. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  121894. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  121895. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  121896. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  121897. };
  121898. static static_codebook _huff_book_line_1024x27_0sub0 = {
  121899. 1, 128,
  121900. _huff_lengthlist_line_1024x27_0sub0,
  121901. 0, 0, 0, 0, 0,
  121902. NULL,
  121903. NULL,
  121904. NULL,
  121905. NULL,
  121906. 0
  121907. };
  121908. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  121909. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  121910. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  121911. };
  121912. static static_codebook _huff_book_line_1024x27_1sub0 = {
  121913. 1, 32,
  121914. _huff_lengthlist_line_1024x27_1sub0,
  121915. 0, 0, 0, 0, 0,
  121916. NULL,
  121917. NULL,
  121918. NULL,
  121919. NULL,
  121920. 0
  121921. };
  121922. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  121923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121925. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  121926. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  121927. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  121928. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  121929. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  121930. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  121931. };
  121932. static static_codebook _huff_book_line_1024x27_1sub1 = {
  121933. 1, 128,
  121934. _huff_lengthlist_line_1024x27_1sub1,
  121935. 0, 0, 0, 0, 0,
  121936. NULL,
  121937. NULL,
  121938. NULL,
  121939. NULL,
  121940. 0
  121941. };
  121942. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  121943. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121944. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  121945. };
  121946. static static_codebook _huff_book_line_1024x27_2sub0 = {
  121947. 1, 32,
  121948. _huff_lengthlist_line_1024x27_2sub0,
  121949. 0, 0, 0, 0, 0,
  121950. NULL,
  121951. NULL,
  121952. NULL,
  121953. NULL,
  121954. 0
  121955. };
  121956. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  121957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121959. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  121960. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  121961. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  121962. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  121963. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  121964. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  121965. };
  121966. static static_codebook _huff_book_line_1024x27_2sub1 = {
  121967. 1, 128,
  121968. _huff_lengthlist_line_1024x27_2sub1,
  121969. 0, 0, 0, 0, 0,
  121970. NULL,
  121971. NULL,
  121972. NULL,
  121973. NULL,
  121974. 0
  121975. };
  121976. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  121977. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  121978. 5, 5,
  121979. };
  121980. static static_codebook _huff_book_line_1024x27_3sub1 = {
  121981. 1, 18,
  121982. _huff_lengthlist_line_1024x27_3sub1,
  121983. 0, 0, 0, 0, 0,
  121984. NULL,
  121985. NULL,
  121986. NULL,
  121987. NULL,
  121988. 0
  121989. };
  121990. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  121991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121992. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  121993. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  121994. 9,11,
  121995. };
  121996. static static_codebook _huff_book_line_1024x27_3sub2 = {
  121997. 1, 50,
  121998. _huff_lengthlist_line_1024x27_3sub2,
  121999. 0, 0, 0, 0, 0,
  122000. NULL,
  122001. NULL,
  122002. NULL,
  122003. NULL,
  122004. 0
  122005. };
  122006. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  122007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122010. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  122011. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  122012. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122013. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122014. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122015. };
  122016. static static_codebook _huff_book_line_1024x27_3sub3 = {
  122017. 1, 128,
  122018. _huff_lengthlist_line_1024x27_3sub3,
  122019. 0, 0, 0, 0, 0,
  122020. NULL,
  122021. NULL,
  122022. NULL,
  122023. NULL,
  122024. 0
  122025. };
  122026. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  122027. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  122028. 5, 4,
  122029. };
  122030. static static_codebook _huff_book_line_1024x27_4sub1 = {
  122031. 1, 18,
  122032. _huff_lengthlist_line_1024x27_4sub1,
  122033. 0, 0, 0, 0, 0,
  122034. NULL,
  122035. NULL,
  122036. NULL,
  122037. NULL,
  122038. 0
  122039. };
  122040. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  122041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122042. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  122043. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  122044. 9,12,
  122045. };
  122046. static static_codebook _huff_book_line_1024x27_4sub2 = {
  122047. 1, 50,
  122048. _huff_lengthlist_line_1024x27_4sub2,
  122049. 0, 0, 0, 0, 0,
  122050. NULL,
  122051. NULL,
  122052. NULL,
  122053. NULL,
  122054. 0
  122055. };
  122056. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  122057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122060. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  122061. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  122062. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122063. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122064. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  122065. };
  122066. static static_codebook _huff_book_line_1024x27_4sub3 = {
  122067. 1, 128,
  122068. _huff_lengthlist_line_1024x27_4sub3,
  122069. 0, 0, 0, 0, 0,
  122070. NULL,
  122071. NULL,
  122072. NULL,
  122073. NULL,
  122074. 0
  122075. };
  122076. static long _huff_lengthlist_line_2048x27_class1[] = {
  122077. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  122078. };
  122079. static static_codebook _huff_book_line_2048x27_class1 = {
  122080. 1, 16,
  122081. _huff_lengthlist_line_2048x27_class1,
  122082. 0, 0, 0, 0, 0,
  122083. NULL,
  122084. NULL,
  122085. NULL,
  122086. NULL,
  122087. 0
  122088. };
  122089. static long _huff_lengthlist_line_2048x27_class2[] = {
  122090. 1, 2, 3, 6, 4, 7, 5, 7,
  122091. };
  122092. static static_codebook _huff_book_line_2048x27_class2 = {
  122093. 1, 8,
  122094. _huff_lengthlist_line_2048x27_class2,
  122095. 0, 0, 0, 0, 0,
  122096. NULL,
  122097. NULL,
  122098. NULL,
  122099. NULL,
  122100. 0
  122101. };
  122102. static long _huff_lengthlist_line_2048x27_class3[] = {
  122103. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  122104. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  122105. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  122106. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  122107. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  122108. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  122109. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  122110. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  122111. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  122112. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  122113. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  122114. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122115. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  122116. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  122117. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122118. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122119. };
  122120. static static_codebook _huff_book_line_2048x27_class3 = {
  122121. 1, 256,
  122122. _huff_lengthlist_line_2048x27_class3,
  122123. 0, 0, 0, 0, 0,
  122124. NULL,
  122125. NULL,
  122126. NULL,
  122127. NULL,
  122128. 0
  122129. };
  122130. static long _huff_lengthlist_line_2048x27_class4[] = {
  122131. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  122132. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  122133. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  122134. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  122135. };
  122136. static static_codebook _huff_book_line_2048x27_class4 = {
  122137. 1, 64,
  122138. _huff_lengthlist_line_2048x27_class4,
  122139. 0, 0, 0, 0, 0,
  122140. NULL,
  122141. NULL,
  122142. NULL,
  122143. NULL,
  122144. 0
  122145. };
  122146. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  122147. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  122148. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  122149. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  122150. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  122151. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  122152. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  122153. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  122154. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  122155. };
  122156. static static_codebook _huff_book_line_2048x27_0sub0 = {
  122157. 1, 128,
  122158. _huff_lengthlist_line_2048x27_0sub0,
  122159. 0, 0, 0, 0, 0,
  122160. NULL,
  122161. NULL,
  122162. NULL,
  122163. NULL,
  122164. 0
  122165. };
  122166. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  122167. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  122168. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  122169. };
  122170. static static_codebook _huff_book_line_2048x27_1sub0 = {
  122171. 1, 32,
  122172. _huff_lengthlist_line_2048x27_1sub0,
  122173. 0, 0, 0, 0, 0,
  122174. NULL,
  122175. NULL,
  122176. NULL,
  122177. NULL,
  122178. 0
  122179. };
  122180. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  122181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122183. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  122184. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  122185. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  122186. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  122187. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  122188. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  122189. };
  122190. static static_codebook _huff_book_line_2048x27_1sub1 = {
  122191. 1, 128,
  122192. _huff_lengthlist_line_2048x27_1sub1,
  122193. 0, 0, 0, 0, 0,
  122194. NULL,
  122195. NULL,
  122196. NULL,
  122197. NULL,
  122198. 0
  122199. };
  122200. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  122201. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  122202. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  122203. };
  122204. static static_codebook _huff_book_line_2048x27_2sub0 = {
  122205. 1, 32,
  122206. _huff_lengthlist_line_2048x27_2sub0,
  122207. 0, 0, 0, 0, 0,
  122208. NULL,
  122209. NULL,
  122210. NULL,
  122211. NULL,
  122212. 0
  122213. };
  122214. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  122215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122217. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  122218. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  122219. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  122220. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  122221. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  122222. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122223. };
  122224. static static_codebook _huff_book_line_2048x27_2sub1 = {
  122225. 1, 128,
  122226. _huff_lengthlist_line_2048x27_2sub1,
  122227. 0, 0, 0, 0, 0,
  122228. NULL,
  122229. NULL,
  122230. NULL,
  122231. NULL,
  122232. 0
  122233. };
  122234. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  122235. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  122236. 5, 5,
  122237. };
  122238. static static_codebook _huff_book_line_2048x27_3sub1 = {
  122239. 1, 18,
  122240. _huff_lengthlist_line_2048x27_3sub1,
  122241. 0, 0, 0, 0, 0,
  122242. NULL,
  122243. NULL,
  122244. NULL,
  122245. NULL,
  122246. 0
  122247. };
  122248. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  122249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122250. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  122251. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  122252. 10,12,
  122253. };
  122254. static static_codebook _huff_book_line_2048x27_3sub2 = {
  122255. 1, 50,
  122256. _huff_lengthlist_line_2048x27_3sub2,
  122257. 0, 0, 0, 0, 0,
  122258. NULL,
  122259. NULL,
  122260. NULL,
  122261. NULL,
  122262. 0
  122263. };
  122264. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  122265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122268. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  122269. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122270. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122271. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122272. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122273. };
  122274. static static_codebook _huff_book_line_2048x27_3sub3 = {
  122275. 1, 128,
  122276. _huff_lengthlist_line_2048x27_3sub3,
  122277. 0, 0, 0, 0, 0,
  122278. NULL,
  122279. NULL,
  122280. NULL,
  122281. NULL,
  122282. 0
  122283. };
  122284. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  122285. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  122286. 4, 5,
  122287. };
  122288. static static_codebook _huff_book_line_2048x27_4sub1 = {
  122289. 1, 18,
  122290. _huff_lengthlist_line_2048x27_4sub1,
  122291. 0, 0, 0, 0, 0,
  122292. NULL,
  122293. NULL,
  122294. NULL,
  122295. NULL,
  122296. 0
  122297. };
  122298. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  122299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122300. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  122301. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  122302. 10,10,
  122303. };
  122304. static static_codebook _huff_book_line_2048x27_4sub2 = {
  122305. 1, 50,
  122306. _huff_lengthlist_line_2048x27_4sub2,
  122307. 0, 0, 0, 0, 0,
  122308. NULL,
  122309. NULL,
  122310. NULL,
  122311. NULL,
  122312. 0
  122313. };
  122314. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  122315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122318. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  122319. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  122320. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122321. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122322. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  122323. };
  122324. static static_codebook _huff_book_line_2048x27_4sub3 = {
  122325. 1, 128,
  122326. _huff_lengthlist_line_2048x27_4sub3,
  122327. 0, 0, 0, 0, 0,
  122328. NULL,
  122329. NULL,
  122330. NULL,
  122331. NULL,
  122332. 0
  122333. };
  122334. static long _huff_lengthlist_line_256x4low_class0[] = {
  122335. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  122336. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  122337. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  122338. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  122339. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  122340. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  122341. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  122342. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  122343. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  122344. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  122345. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  122346. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  122347. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  122348. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  122349. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  122350. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  122351. };
  122352. static static_codebook _huff_book_line_256x4low_class0 = {
  122353. 1, 256,
  122354. _huff_lengthlist_line_256x4low_class0,
  122355. 0, 0, 0, 0, 0,
  122356. NULL,
  122357. NULL,
  122358. NULL,
  122359. NULL,
  122360. 0
  122361. };
  122362. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  122363. 1, 3, 2, 3,
  122364. };
  122365. static static_codebook _huff_book_line_256x4low_0sub0 = {
  122366. 1, 4,
  122367. _huff_lengthlist_line_256x4low_0sub0,
  122368. 0, 0, 0, 0, 0,
  122369. NULL,
  122370. NULL,
  122371. NULL,
  122372. NULL,
  122373. 0
  122374. };
  122375. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  122376. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  122377. };
  122378. static static_codebook _huff_book_line_256x4low_0sub1 = {
  122379. 1, 10,
  122380. _huff_lengthlist_line_256x4low_0sub1,
  122381. 0, 0, 0, 0, 0,
  122382. NULL,
  122383. NULL,
  122384. NULL,
  122385. NULL,
  122386. 0
  122387. };
  122388. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  122389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  122390. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  122391. };
  122392. static static_codebook _huff_book_line_256x4low_0sub2 = {
  122393. 1, 25,
  122394. _huff_lengthlist_line_256x4low_0sub2,
  122395. 0, 0, 0, 0, 0,
  122396. NULL,
  122397. NULL,
  122398. NULL,
  122399. NULL,
  122400. 0
  122401. };
  122402. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  122403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 4, 3, 5, 4,
  122405. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  122406. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  122407. };
  122408. static static_codebook _huff_book_line_256x4low_0sub3 = {
  122409. 1, 64,
  122410. _huff_lengthlist_line_256x4low_0sub3,
  122411. 0, 0, 0, 0, 0,
  122412. NULL,
  122413. NULL,
  122414. NULL,
  122415. NULL,
  122416. 0
  122417. };
  122418. /*** End of inlined file: floor_books.h ***/
  122419. static static_codebook *_floor_128x4_books[]={
  122420. &_huff_book_line_128x4_class0,
  122421. &_huff_book_line_128x4_0sub0,
  122422. &_huff_book_line_128x4_0sub1,
  122423. &_huff_book_line_128x4_0sub2,
  122424. &_huff_book_line_128x4_0sub3,
  122425. };
  122426. static static_codebook *_floor_256x4_books[]={
  122427. &_huff_book_line_256x4_class0,
  122428. &_huff_book_line_256x4_0sub0,
  122429. &_huff_book_line_256x4_0sub1,
  122430. &_huff_book_line_256x4_0sub2,
  122431. &_huff_book_line_256x4_0sub3,
  122432. };
  122433. static static_codebook *_floor_128x7_books[]={
  122434. &_huff_book_line_128x7_class0,
  122435. &_huff_book_line_128x7_class1,
  122436. &_huff_book_line_128x7_0sub1,
  122437. &_huff_book_line_128x7_0sub2,
  122438. &_huff_book_line_128x7_0sub3,
  122439. &_huff_book_line_128x7_1sub1,
  122440. &_huff_book_line_128x7_1sub2,
  122441. &_huff_book_line_128x7_1sub3,
  122442. };
  122443. static static_codebook *_floor_256x7_books[]={
  122444. &_huff_book_line_256x7_class0,
  122445. &_huff_book_line_256x7_class1,
  122446. &_huff_book_line_256x7_0sub1,
  122447. &_huff_book_line_256x7_0sub2,
  122448. &_huff_book_line_256x7_0sub3,
  122449. &_huff_book_line_256x7_1sub1,
  122450. &_huff_book_line_256x7_1sub2,
  122451. &_huff_book_line_256x7_1sub3,
  122452. };
  122453. static static_codebook *_floor_128x11_books[]={
  122454. &_huff_book_line_128x11_class1,
  122455. &_huff_book_line_128x11_class2,
  122456. &_huff_book_line_128x11_class3,
  122457. &_huff_book_line_128x11_0sub0,
  122458. &_huff_book_line_128x11_1sub0,
  122459. &_huff_book_line_128x11_1sub1,
  122460. &_huff_book_line_128x11_2sub1,
  122461. &_huff_book_line_128x11_2sub2,
  122462. &_huff_book_line_128x11_2sub3,
  122463. &_huff_book_line_128x11_3sub1,
  122464. &_huff_book_line_128x11_3sub2,
  122465. &_huff_book_line_128x11_3sub3,
  122466. };
  122467. static static_codebook *_floor_128x17_books[]={
  122468. &_huff_book_line_128x17_class1,
  122469. &_huff_book_line_128x17_class2,
  122470. &_huff_book_line_128x17_class3,
  122471. &_huff_book_line_128x17_0sub0,
  122472. &_huff_book_line_128x17_1sub0,
  122473. &_huff_book_line_128x17_1sub1,
  122474. &_huff_book_line_128x17_2sub1,
  122475. &_huff_book_line_128x17_2sub2,
  122476. &_huff_book_line_128x17_2sub3,
  122477. &_huff_book_line_128x17_3sub1,
  122478. &_huff_book_line_128x17_3sub2,
  122479. &_huff_book_line_128x17_3sub3,
  122480. };
  122481. static static_codebook *_floor_256x4low_books[]={
  122482. &_huff_book_line_256x4low_class0,
  122483. &_huff_book_line_256x4low_0sub0,
  122484. &_huff_book_line_256x4low_0sub1,
  122485. &_huff_book_line_256x4low_0sub2,
  122486. &_huff_book_line_256x4low_0sub3,
  122487. };
  122488. static static_codebook *_floor_1024x27_books[]={
  122489. &_huff_book_line_1024x27_class1,
  122490. &_huff_book_line_1024x27_class2,
  122491. &_huff_book_line_1024x27_class3,
  122492. &_huff_book_line_1024x27_class4,
  122493. &_huff_book_line_1024x27_0sub0,
  122494. &_huff_book_line_1024x27_1sub0,
  122495. &_huff_book_line_1024x27_1sub1,
  122496. &_huff_book_line_1024x27_2sub0,
  122497. &_huff_book_line_1024x27_2sub1,
  122498. &_huff_book_line_1024x27_3sub1,
  122499. &_huff_book_line_1024x27_3sub2,
  122500. &_huff_book_line_1024x27_3sub3,
  122501. &_huff_book_line_1024x27_4sub1,
  122502. &_huff_book_line_1024x27_4sub2,
  122503. &_huff_book_line_1024x27_4sub3,
  122504. };
  122505. static static_codebook *_floor_2048x27_books[]={
  122506. &_huff_book_line_2048x27_class1,
  122507. &_huff_book_line_2048x27_class2,
  122508. &_huff_book_line_2048x27_class3,
  122509. &_huff_book_line_2048x27_class4,
  122510. &_huff_book_line_2048x27_0sub0,
  122511. &_huff_book_line_2048x27_1sub0,
  122512. &_huff_book_line_2048x27_1sub1,
  122513. &_huff_book_line_2048x27_2sub0,
  122514. &_huff_book_line_2048x27_2sub1,
  122515. &_huff_book_line_2048x27_3sub1,
  122516. &_huff_book_line_2048x27_3sub2,
  122517. &_huff_book_line_2048x27_3sub3,
  122518. &_huff_book_line_2048x27_4sub1,
  122519. &_huff_book_line_2048x27_4sub2,
  122520. &_huff_book_line_2048x27_4sub3,
  122521. };
  122522. static static_codebook *_floor_512x17_books[]={
  122523. &_huff_book_line_512x17_class1,
  122524. &_huff_book_line_512x17_class2,
  122525. &_huff_book_line_512x17_class3,
  122526. &_huff_book_line_512x17_0sub0,
  122527. &_huff_book_line_512x17_1sub0,
  122528. &_huff_book_line_512x17_1sub1,
  122529. &_huff_book_line_512x17_2sub1,
  122530. &_huff_book_line_512x17_2sub2,
  122531. &_huff_book_line_512x17_2sub3,
  122532. &_huff_book_line_512x17_3sub1,
  122533. &_huff_book_line_512x17_3sub2,
  122534. &_huff_book_line_512x17_3sub3,
  122535. };
  122536. static static_codebook **_floor_books[10]={
  122537. _floor_128x4_books,
  122538. _floor_256x4_books,
  122539. _floor_128x7_books,
  122540. _floor_256x7_books,
  122541. _floor_128x11_books,
  122542. _floor_128x17_books,
  122543. _floor_256x4low_books,
  122544. _floor_1024x27_books,
  122545. _floor_2048x27_books,
  122546. _floor_512x17_books,
  122547. };
  122548. static vorbis_info_floor1 _floor[10]={
  122549. /* 128 x 4 */
  122550. {
  122551. 1,{0},{4},{2},{0},
  122552. {{1,2,3,4}},
  122553. 4,{0,128, 33,8,16,70},
  122554. 60,30,500, 1.,18., -1
  122555. },
  122556. /* 256 x 4 */
  122557. {
  122558. 1,{0},{4},{2},{0},
  122559. {{1,2,3,4}},
  122560. 4,{0,256, 66,16,32,140},
  122561. 60,30,500, 1.,18., -1
  122562. },
  122563. /* 128 x 7 */
  122564. {
  122565. 2,{0,1},{3,4},{2,2},{0,1},
  122566. {{-1,2,3,4},{-1,5,6,7}},
  122567. 4,{0,128, 14,4,58, 2,8,28,90},
  122568. 60,30,500, 1.,18., -1
  122569. },
  122570. /* 256 x 7 */
  122571. {
  122572. 2,{0,1},{3,4},{2,2},{0,1},
  122573. {{-1,2,3,4},{-1,5,6,7}},
  122574. 4,{0,256, 28,8,116, 4,16,56,180},
  122575. 60,30,500, 1.,18., -1
  122576. },
  122577. /* 128 x 11 */
  122578. {
  122579. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122580. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122581. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  122582. 60,30,500, 1,18., -1
  122583. },
  122584. /* 128 x 17 */
  122585. {
  122586. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122587. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122588. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  122589. 60,30,500, 1,18., -1
  122590. },
  122591. /* 256 x 4 (low bitrate version) */
  122592. {
  122593. 1,{0},{4},{2},{0},
  122594. {{1,2,3,4}},
  122595. 4,{0,256, 66,16,32,140},
  122596. 60,30,500, 1.,18., -1
  122597. },
  122598. /* 1024 x 27 */
  122599. {
  122600. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122601. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122602. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  122603. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  122604. 60,30,500, 3,18., -1 /* lowpass */
  122605. },
  122606. /* 2048 x 27 */
  122607. {
  122608. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122609. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122610. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  122611. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  122612. 60,30,500, 3,18., -1 /* lowpass */
  122613. },
  122614. /* 512 x 17 */
  122615. {
  122616. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122617. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122618. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  122619. 7,23,39, 55,79,110, 156,232,360},
  122620. 60,30,500, 1,18., -1 /* lowpass! */
  122621. },
  122622. };
  122623. /*** End of inlined file: floor_all.h ***/
  122624. /*** Start of inlined file: residue_44.h ***/
  122625. /*** Start of inlined file: res_books_stereo.h ***/
  122626. static long _vq_quantlist__16c0_s_p1_0[] = {
  122627. 1,
  122628. 0,
  122629. 2,
  122630. };
  122631. static long _vq_lengthlist__16c0_s_p1_0[] = {
  122632. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122633. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122637. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  122638. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122642. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122643. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  122678. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0,
  122683. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 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, 7,10,10, 0, 0,
  122688. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122723. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122724. 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122729. 0, 0, 0, 0, 0, 9,10,12, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122734. 0, 0, 0, 0, 0, 0, 9,12, 9, 0, 0, 0, 0, 0, 0, 0,
  122735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122910. 0, 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,
  123043. };
  123044. static float _vq_quantthresh__16c0_s_p1_0[] = {
  123045. -0.5, 0.5,
  123046. };
  123047. static long _vq_quantmap__16c0_s_p1_0[] = {
  123048. 1, 0, 2,
  123049. };
  123050. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  123051. _vq_quantthresh__16c0_s_p1_0,
  123052. _vq_quantmap__16c0_s_p1_0,
  123053. 3,
  123054. 3
  123055. };
  123056. static static_codebook _16c0_s_p1_0 = {
  123057. 8, 6561,
  123058. _vq_lengthlist__16c0_s_p1_0,
  123059. 1, -535822336, 1611661312, 2, 0,
  123060. _vq_quantlist__16c0_s_p1_0,
  123061. NULL,
  123062. &_vq_auxt__16c0_s_p1_0,
  123063. NULL,
  123064. 0
  123065. };
  123066. static long _vq_quantlist__16c0_s_p2_0[] = {
  123067. 2,
  123068. 1,
  123069. 3,
  123070. 0,
  123071. 4,
  123072. };
  123073. static long _vq_lengthlist__16c0_s_p2_0[] = {
  123074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123113. 0,
  123114. };
  123115. static float _vq_quantthresh__16c0_s_p2_0[] = {
  123116. -1.5, -0.5, 0.5, 1.5,
  123117. };
  123118. static long _vq_quantmap__16c0_s_p2_0[] = {
  123119. 3, 1, 0, 2, 4,
  123120. };
  123121. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  123122. _vq_quantthresh__16c0_s_p2_0,
  123123. _vq_quantmap__16c0_s_p2_0,
  123124. 5,
  123125. 5
  123126. };
  123127. static static_codebook _16c0_s_p2_0 = {
  123128. 4, 625,
  123129. _vq_lengthlist__16c0_s_p2_0,
  123130. 1, -533725184, 1611661312, 3, 0,
  123131. _vq_quantlist__16c0_s_p2_0,
  123132. NULL,
  123133. &_vq_auxt__16c0_s_p2_0,
  123134. NULL,
  123135. 0
  123136. };
  123137. static long _vq_quantlist__16c0_s_p3_0[] = {
  123138. 2,
  123139. 1,
  123140. 3,
  123141. 0,
  123142. 4,
  123143. };
  123144. static long _vq_lengthlist__16c0_s_p3_0[] = {
  123145. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  123147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123148. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  123150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123151. 0, 0, 0, 0, 6, 6, 6, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  123152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123184. 0,
  123185. };
  123186. static float _vq_quantthresh__16c0_s_p3_0[] = {
  123187. -1.5, -0.5, 0.5, 1.5,
  123188. };
  123189. static long _vq_quantmap__16c0_s_p3_0[] = {
  123190. 3, 1, 0, 2, 4,
  123191. };
  123192. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  123193. _vq_quantthresh__16c0_s_p3_0,
  123194. _vq_quantmap__16c0_s_p3_0,
  123195. 5,
  123196. 5
  123197. };
  123198. static static_codebook _16c0_s_p3_0 = {
  123199. 4, 625,
  123200. _vq_lengthlist__16c0_s_p3_0,
  123201. 1, -533725184, 1611661312, 3, 0,
  123202. _vq_quantlist__16c0_s_p3_0,
  123203. NULL,
  123204. &_vq_auxt__16c0_s_p3_0,
  123205. NULL,
  123206. 0
  123207. };
  123208. static long _vq_quantlist__16c0_s_p4_0[] = {
  123209. 4,
  123210. 3,
  123211. 5,
  123212. 2,
  123213. 6,
  123214. 1,
  123215. 7,
  123216. 0,
  123217. 8,
  123218. };
  123219. static long _vq_lengthlist__16c0_s_p4_0[] = {
  123220. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  123221. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  123222. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  123223. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  123224. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123225. 0,
  123226. };
  123227. static float _vq_quantthresh__16c0_s_p4_0[] = {
  123228. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123229. };
  123230. static long _vq_quantmap__16c0_s_p4_0[] = {
  123231. 7, 5, 3, 1, 0, 2, 4, 6,
  123232. 8,
  123233. };
  123234. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  123235. _vq_quantthresh__16c0_s_p4_0,
  123236. _vq_quantmap__16c0_s_p4_0,
  123237. 9,
  123238. 9
  123239. };
  123240. static static_codebook _16c0_s_p4_0 = {
  123241. 2, 81,
  123242. _vq_lengthlist__16c0_s_p4_0,
  123243. 1, -531628032, 1611661312, 4, 0,
  123244. _vq_quantlist__16c0_s_p4_0,
  123245. NULL,
  123246. &_vq_auxt__16c0_s_p4_0,
  123247. NULL,
  123248. 0
  123249. };
  123250. static long _vq_quantlist__16c0_s_p5_0[] = {
  123251. 4,
  123252. 3,
  123253. 5,
  123254. 2,
  123255. 6,
  123256. 1,
  123257. 7,
  123258. 0,
  123259. 8,
  123260. };
  123261. static long _vq_lengthlist__16c0_s_p5_0[] = {
  123262. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  123263. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  123264. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  123265. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  123266. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  123267. 10,
  123268. };
  123269. static float _vq_quantthresh__16c0_s_p5_0[] = {
  123270. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123271. };
  123272. static long _vq_quantmap__16c0_s_p5_0[] = {
  123273. 7, 5, 3, 1, 0, 2, 4, 6,
  123274. 8,
  123275. };
  123276. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  123277. _vq_quantthresh__16c0_s_p5_0,
  123278. _vq_quantmap__16c0_s_p5_0,
  123279. 9,
  123280. 9
  123281. };
  123282. static static_codebook _16c0_s_p5_0 = {
  123283. 2, 81,
  123284. _vq_lengthlist__16c0_s_p5_0,
  123285. 1, -531628032, 1611661312, 4, 0,
  123286. _vq_quantlist__16c0_s_p5_0,
  123287. NULL,
  123288. &_vq_auxt__16c0_s_p5_0,
  123289. NULL,
  123290. 0
  123291. };
  123292. static long _vq_quantlist__16c0_s_p6_0[] = {
  123293. 8,
  123294. 7,
  123295. 9,
  123296. 6,
  123297. 10,
  123298. 5,
  123299. 11,
  123300. 4,
  123301. 12,
  123302. 3,
  123303. 13,
  123304. 2,
  123305. 14,
  123306. 1,
  123307. 15,
  123308. 0,
  123309. 16,
  123310. };
  123311. static long _vq_lengthlist__16c0_s_p6_0[] = {
  123312. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  123313. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  123314. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  123315. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  123316. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  123317. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  123318. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  123319. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  123320. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  123321. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  123322. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  123323. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  123324. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  123325. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  123326. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  123327. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  123328. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  123329. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  123330. 14,
  123331. };
  123332. static float _vq_quantthresh__16c0_s_p6_0[] = {
  123333. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123334. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123335. };
  123336. static long _vq_quantmap__16c0_s_p6_0[] = {
  123337. 15, 13, 11, 9, 7, 5, 3, 1,
  123338. 0, 2, 4, 6, 8, 10, 12, 14,
  123339. 16,
  123340. };
  123341. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  123342. _vq_quantthresh__16c0_s_p6_0,
  123343. _vq_quantmap__16c0_s_p6_0,
  123344. 17,
  123345. 17
  123346. };
  123347. static static_codebook _16c0_s_p6_0 = {
  123348. 2, 289,
  123349. _vq_lengthlist__16c0_s_p6_0,
  123350. 1, -529530880, 1611661312, 5, 0,
  123351. _vq_quantlist__16c0_s_p6_0,
  123352. NULL,
  123353. &_vq_auxt__16c0_s_p6_0,
  123354. NULL,
  123355. 0
  123356. };
  123357. static long _vq_quantlist__16c0_s_p7_0[] = {
  123358. 1,
  123359. 0,
  123360. 2,
  123361. };
  123362. static long _vq_lengthlist__16c0_s_p7_0[] = {
  123363. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  123364. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  123365. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  123366. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  123367. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  123368. 13,
  123369. };
  123370. static float _vq_quantthresh__16c0_s_p7_0[] = {
  123371. -5.5, 5.5,
  123372. };
  123373. static long _vq_quantmap__16c0_s_p7_0[] = {
  123374. 1, 0, 2,
  123375. };
  123376. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  123377. _vq_quantthresh__16c0_s_p7_0,
  123378. _vq_quantmap__16c0_s_p7_0,
  123379. 3,
  123380. 3
  123381. };
  123382. static static_codebook _16c0_s_p7_0 = {
  123383. 4, 81,
  123384. _vq_lengthlist__16c0_s_p7_0,
  123385. 1, -529137664, 1618345984, 2, 0,
  123386. _vq_quantlist__16c0_s_p7_0,
  123387. NULL,
  123388. &_vq_auxt__16c0_s_p7_0,
  123389. NULL,
  123390. 0
  123391. };
  123392. static long _vq_quantlist__16c0_s_p7_1[] = {
  123393. 5,
  123394. 4,
  123395. 6,
  123396. 3,
  123397. 7,
  123398. 2,
  123399. 8,
  123400. 1,
  123401. 9,
  123402. 0,
  123403. 10,
  123404. };
  123405. static long _vq_lengthlist__16c0_s_p7_1[] = {
  123406. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  123407. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  123408. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  123409. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  123410. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  123411. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  123412. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  123413. 11,11,11, 9, 9, 9, 9,10,10,
  123414. };
  123415. static float _vq_quantthresh__16c0_s_p7_1[] = {
  123416. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123417. 3.5, 4.5,
  123418. };
  123419. static long _vq_quantmap__16c0_s_p7_1[] = {
  123420. 9, 7, 5, 3, 1, 0, 2, 4,
  123421. 6, 8, 10,
  123422. };
  123423. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  123424. _vq_quantthresh__16c0_s_p7_1,
  123425. _vq_quantmap__16c0_s_p7_1,
  123426. 11,
  123427. 11
  123428. };
  123429. static static_codebook _16c0_s_p7_1 = {
  123430. 2, 121,
  123431. _vq_lengthlist__16c0_s_p7_1,
  123432. 1, -531365888, 1611661312, 4, 0,
  123433. _vq_quantlist__16c0_s_p7_1,
  123434. NULL,
  123435. &_vq_auxt__16c0_s_p7_1,
  123436. NULL,
  123437. 0
  123438. };
  123439. static long _vq_quantlist__16c0_s_p8_0[] = {
  123440. 6,
  123441. 5,
  123442. 7,
  123443. 4,
  123444. 8,
  123445. 3,
  123446. 9,
  123447. 2,
  123448. 10,
  123449. 1,
  123450. 11,
  123451. 0,
  123452. 12,
  123453. };
  123454. static long _vq_lengthlist__16c0_s_p8_0[] = {
  123455. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  123456. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  123457. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  123458. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  123459. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  123460. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  123461. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  123462. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  123463. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  123464. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  123465. 0,12,13,13,12,13,14,14,14,
  123466. };
  123467. static float _vq_quantthresh__16c0_s_p8_0[] = {
  123468. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123469. 12.5, 17.5, 22.5, 27.5,
  123470. };
  123471. static long _vq_quantmap__16c0_s_p8_0[] = {
  123472. 11, 9, 7, 5, 3, 1, 0, 2,
  123473. 4, 6, 8, 10, 12,
  123474. };
  123475. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  123476. _vq_quantthresh__16c0_s_p8_0,
  123477. _vq_quantmap__16c0_s_p8_0,
  123478. 13,
  123479. 13
  123480. };
  123481. static static_codebook _16c0_s_p8_0 = {
  123482. 2, 169,
  123483. _vq_lengthlist__16c0_s_p8_0,
  123484. 1, -526516224, 1616117760, 4, 0,
  123485. _vq_quantlist__16c0_s_p8_0,
  123486. NULL,
  123487. &_vq_auxt__16c0_s_p8_0,
  123488. NULL,
  123489. 0
  123490. };
  123491. static long _vq_quantlist__16c0_s_p8_1[] = {
  123492. 2,
  123493. 1,
  123494. 3,
  123495. 0,
  123496. 4,
  123497. };
  123498. static long _vq_lengthlist__16c0_s_p8_1[] = {
  123499. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  123500. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  123501. };
  123502. static float _vq_quantthresh__16c0_s_p8_1[] = {
  123503. -1.5, -0.5, 0.5, 1.5,
  123504. };
  123505. static long _vq_quantmap__16c0_s_p8_1[] = {
  123506. 3, 1, 0, 2, 4,
  123507. };
  123508. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  123509. _vq_quantthresh__16c0_s_p8_1,
  123510. _vq_quantmap__16c0_s_p8_1,
  123511. 5,
  123512. 5
  123513. };
  123514. static static_codebook _16c0_s_p8_1 = {
  123515. 2, 25,
  123516. _vq_lengthlist__16c0_s_p8_1,
  123517. 1, -533725184, 1611661312, 3, 0,
  123518. _vq_quantlist__16c0_s_p8_1,
  123519. NULL,
  123520. &_vq_auxt__16c0_s_p8_1,
  123521. NULL,
  123522. 0
  123523. };
  123524. static long _vq_quantlist__16c0_s_p9_0[] = {
  123525. 1,
  123526. 0,
  123527. 2,
  123528. };
  123529. static long _vq_lengthlist__16c0_s_p9_0[] = {
  123530. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123531. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123532. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123533. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123534. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123535. 7,
  123536. };
  123537. static float _vq_quantthresh__16c0_s_p9_0[] = {
  123538. -157.5, 157.5,
  123539. };
  123540. static long _vq_quantmap__16c0_s_p9_0[] = {
  123541. 1, 0, 2,
  123542. };
  123543. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  123544. _vq_quantthresh__16c0_s_p9_0,
  123545. _vq_quantmap__16c0_s_p9_0,
  123546. 3,
  123547. 3
  123548. };
  123549. static static_codebook _16c0_s_p9_0 = {
  123550. 4, 81,
  123551. _vq_lengthlist__16c0_s_p9_0,
  123552. 1, -518803456, 1628680192, 2, 0,
  123553. _vq_quantlist__16c0_s_p9_0,
  123554. NULL,
  123555. &_vq_auxt__16c0_s_p9_0,
  123556. NULL,
  123557. 0
  123558. };
  123559. static long _vq_quantlist__16c0_s_p9_1[] = {
  123560. 7,
  123561. 6,
  123562. 8,
  123563. 5,
  123564. 9,
  123565. 4,
  123566. 10,
  123567. 3,
  123568. 11,
  123569. 2,
  123570. 12,
  123571. 1,
  123572. 13,
  123573. 0,
  123574. 14,
  123575. };
  123576. static long _vq_lengthlist__16c0_s_p9_1[] = {
  123577. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  123578. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  123579. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  123580. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  123581. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123582. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123583. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123584. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123585. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123586. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123587. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123588. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123589. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123590. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123591. 10,
  123592. };
  123593. static float _vq_quantthresh__16c0_s_p9_1[] = {
  123594. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  123595. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  123596. };
  123597. static long _vq_quantmap__16c0_s_p9_1[] = {
  123598. 13, 11, 9, 7, 5, 3, 1, 0,
  123599. 2, 4, 6, 8, 10, 12, 14,
  123600. };
  123601. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  123602. _vq_quantthresh__16c0_s_p9_1,
  123603. _vq_quantmap__16c0_s_p9_1,
  123604. 15,
  123605. 15
  123606. };
  123607. static static_codebook _16c0_s_p9_1 = {
  123608. 2, 225,
  123609. _vq_lengthlist__16c0_s_p9_1,
  123610. 1, -520986624, 1620377600, 4, 0,
  123611. _vq_quantlist__16c0_s_p9_1,
  123612. NULL,
  123613. &_vq_auxt__16c0_s_p9_1,
  123614. NULL,
  123615. 0
  123616. };
  123617. static long _vq_quantlist__16c0_s_p9_2[] = {
  123618. 10,
  123619. 9,
  123620. 11,
  123621. 8,
  123622. 12,
  123623. 7,
  123624. 13,
  123625. 6,
  123626. 14,
  123627. 5,
  123628. 15,
  123629. 4,
  123630. 16,
  123631. 3,
  123632. 17,
  123633. 2,
  123634. 18,
  123635. 1,
  123636. 19,
  123637. 0,
  123638. 20,
  123639. };
  123640. static long _vq_lengthlist__16c0_s_p9_2[] = {
  123641. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  123642. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  123643. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  123644. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  123645. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  123646. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  123647. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  123648. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  123649. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  123650. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  123651. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  123652. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  123653. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  123654. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  123655. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  123656. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  123657. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  123658. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  123659. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  123660. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  123661. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  123662. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  123663. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  123664. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  123665. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  123666. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  123667. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  123668. 10,11,10,10,11, 9,10,10,10,
  123669. };
  123670. static float _vq_quantthresh__16c0_s_p9_2[] = {
  123671. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  123672. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  123673. 6.5, 7.5, 8.5, 9.5,
  123674. };
  123675. static long _vq_quantmap__16c0_s_p9_2[] = {
  123676. 19, 17, 15, 13, 11, 9, 7, 5,
  123677. 3, 1, 0, 2, 4, 6, 8, 10,
  123678. 12, 14, 16, 18, 20,
  123679. };
  123680. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  123681. _vq_quantthresh__16c0_s_p9_2,
  123682. _vq_quantmap__16c0_s_p9_2,
  123683. 21,
  123684. 21
  123685. };
  123686. static static_codebook _16c0_s_p9_2 = {
  123687. 2, 441,
  123688. _vq_lengthlist__16c0_s_p9_2,
  123689. 1, -529268736, 1611661312, 5, 0,
  123690. _vq_quantlist__16c0_s_p9_2,
  123691. NULL,
  123692. &_vq_auxt__16c0_s_p9_2,
  123693. NULL,
  123694. 0
  123695. };
  123696. static long _huff_lengthlist__16c0_s_single[] = {
  123697. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  123698. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  123699. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  123700. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  123701. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  123702. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  123703. 16,16,18,18,
  123704. };
  123705. static static_codebook _huff_book__16c0_s_single = {
  123706. 2, 100,
  123707. _huff_lengthlist__16c0_s_single,
  123708. 0, 0, 0, 0, 0,
  123709. NULL,
  123710. NULL,
  123711. NULL,
  123712. NULL,
  123713. 0
  123714. };
  123715. static long _huff_lengthlist__16c1_s_long[] = {
  123716. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  123717. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  123718. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  123719. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  123720. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  123721. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  123722. 12,11,11,13,
  123723. };
  123724. static static_codebook _huff_book__16c1_s_long = {
  123725. 2, 100,
  123726. _huff_lengthlist__16c1_s_long,
  123727. 0, 0, 0, 0, 0,
  123728. NULL,
  123729. NULL,
  123730. NULL,
  123731. NULL,
  123732. 0
  123733. };
  123734. static long _vq_quantlist__16c1_s_p1_0[] = {
  123735. 1,
  123736. 0,
  123737. 2,
  123738. };
  123739. static long _vq_lengthlist__16c1_s_p1_0[] = {
  123740. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  123741. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123745. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123746. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123750. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  123751. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  123786. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  123791. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 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, 7, 9, 9, 0, 0,
  123796. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  123797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123831. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123832. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  123837. 0, 0, 0, 0, 0, 8, 9,11, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  123842. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  123843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124035. 0, 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,
  124151. };
  124152. static float _vq_quantthresh__16c1_s_p1_0[] = {
  124153. -0.5, 0.5,
  124154. };
  124155. static long _vq_quantmap__16c1_s_p1_0[] = {
  124156. 1, 0, 2,
  124157. };
  124158. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  124159. _vq_quantthresh__16c1_s_p1_0,
  124160. _vq_quantmap__16c1_s_p1_0,
  124161. 3,
  124162. 3
  124163. };
  124164. static static_codebook _16c1_s_p1_0 = {
  124165. 8, 6561,
  124166. _vq_lengthlist__16c1_s_p1_0,
  124167. 1, -535822336, 1611661312, 2, 0,
  124168. _vq_quantlist__16c1_s_p1_0,
  124169. NULL,
  124170. &_vq_auxt__16c1_s_p1_0,
  124171. NULL,
  124172. 0
  124173. };
  124174. static long _vq_quantlist__16c1_s_p2_0[] = {
  124175. 2,
  124176. 1,
  124177. 3,
  124178. 0,
  124179. 4,
  124180. };
  124181. static long _vq_lengthlist__16c1_s_p2_0[] = {
  124182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124221. 0,
  124222. };
  124223. static float _vq_quantthresh__16c1_s_p2_0[] = {
  124224. -1.5, -0.5, 0.5, 1.5,
  124225. };
  124226. static long _vq_quantmap__16c1_s_p2_0[] = {
  124227. 3, 1, 0, 2, 4,
  124228. };
  124229. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  124230. _vq_quantthresh__16c1_s_p2_0,
  124231. _vq_quantmap__16c1_s_p2_0,
  124232. 5,
  124233. 5
  124234. };
  124235. static static_codebook _16c1_s_p2_0 = {
  124236. 4, 625,
  124237. _vq_lengthlist__16c1_s_p2_0,
  124238. 1, -533725184, 1611661312, 3, 0,
  124239. _vq_quantlist__16c1_s_p2_0,
  124240. NULL,
  124241. &_vq_auxt__16c1_s_p2_0,
  124242. NULL,
  124243. 0
  124244. };
  124245. static long _vq_quantlist__16c1_s_p3_0[] = {
  124246. 2,
  124247. 1,
  124248. 3,
  124249. 0,
  124250. 4,
  124251. };
  124252. static long _vq_lengthlist__16c1_s_p3_0[] = {
  124253. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  124255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124256. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  124258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124259. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  124260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124292. 0,
  124293. };
  124294. static float _vq_quantthresh__16c1_s_p3_0[] = {
  124295. -1.5, -0.5, 0.5, 1.5,
  124296. };
  124297. static long _vq_quantmap__16c1_s_p3_0[] = {
  124298. 3, 1, 0, 2, 4,
  124299. };
  124300. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  124301. _vq_quantthresh__16c1_s_p3_0,
  124302. _vq_quantmap__16c1_s_p3_0,
  124303. 5,
  124304. 5
  124305. };
  124306. static static_codebook _16c1_s_p3_0 = {
  124307. 4, 625,
  124308. _vq_lengthlist__16c1_s_p3_0,
  124309. 1, -533725184, 1611661312, 3, 0,
  124310. _vq_quantlist__16c1_s_p3_0,
  124311. NULL,
  124312. &_vq_auxt__16c1_s_p3_0,
  124313. NULL,
  124314. 0
  124315. };
  124316. static long _vq_quantlist__16c1_s_p4_0[] = {
  124317. 4,
  124318. 3,
  124319. 5,
  124320. 2,
  124321. 6,
  124322. 1,
  124323. 7,
  124324. 0,
  124325. 8,
  124326. };
  124327. static long _vq_lengthlist__16c1_s_p4_0[] = {
  124328. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  124329. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  124330. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  124331. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  124332. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124333. 0,
  124334. };
  124335. static float _vq_quantthresh__16c1_s_p4_0[] = {
  124336. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124337. };
  124338. static long _vq_quantmap__16c1_s_p4_0[] = {
  124339. 7, 5, 3, 1, 0, 2, 4, 6,
  124340. 8,
  124341. };
  124342. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  124343. _vq_quantthresh__16c1_s_p4_0,
  124344. _vq_quantmap__16c1_s_p4_0,
  124345. 9,
  124346. 9
  124347. };
  124348. static static_codebook _16c1_s_p4_0 = {
  124349. 2, 81,
  124350. _vq_lengthlist__16c1_s_p4_0,
  124351. 1, -531628032, 1611661312, 4, 0,
  124352. _vq_quantlist__16c1_s_p4_0,
  124353. NULL,
  124354. &_vq_auxt__16c1_s_p4_0,
  124355. NULL,
  124356. 0
  124357. };
  124358. static long _vq_quantlist__16c1_s_p5_0[] = {
  124359. 4,
  124360. 3,
  124361. 5,
  124362. 2,
  124363. 6,
  124364. 1,
  124365. 7,
  124366. 0,
  124367. 8,
  124368. };
  124369. static long _vq_lengthlist__16c1_s_p5_0[] = {
  124370. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  124371. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  124372. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  124373. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  124374. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  124375. 10,
  124376. };
  124377. static float _vq_quantthresh__16c1_s_p5_0[] = {
  124378. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124379. };
  124380. static long _vq_quantmap__16c1_s_p5_0[] = {
  124381. 7, 5, 3, 1, 0, 2, 4, 6,
  124382. 8,
  124383. };
  124384. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  124385. _vq_quantthresh__16c1_s_p5_0,
  124386. _vq_quantmap__16c1_s_p5_0,
  124387. 9,
  124388. 9
  124389. };
  124390. static static_codebook _16c1_s_p5_0 = {
  124391. 2, 81,
  124392. _vq_lengthlist__16c1_s_p5_0,
  124393. 1, -531628032, 1611661312, 4, 0,
  124394. _vq_quantlist__16c1_s_p5_0,
  124395. NULL,
  124396. &_vq_auxt__16c1_s_p5_0,
  124397. NULL,
  124398. 0
  124399. };
  124400. static long _vq_quantlist__16c1_s_p6_0[] = {
  124401. 8,
  124402. 7,
  124403. 9,
  124404. 6,
  124405. 10,
  124406. 5,
  124407. 11,
  124408. 4,
  124409. 12,
  124410. 3,
  124411. 13,
  124412. 2,
  124413. 14,
  124414. 1,
  124415. 15,
  124416. 0,
  124417. 16,
  124418. };
  124419. static long _vq_lengthlist__16c1_s_p6_0[] = {
  124420. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  124421. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  124422. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  124423. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  124424. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  124425. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  124426. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  124427. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  124428. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  124429. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  124430. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  124431. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  124432. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  124433. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  124434. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  124435. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  124436. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  124437. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  124438. 14,
  124439. };
  124440. static float _vq_quantthresh__16c1_s_p6_0[] = {
  124441. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124442. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124443. };
  124444. static long _vq_quantmap__16c1_s_p6_0[] = {
  124445. 15, 13, 11, 9, 7, 5, 3, 1,
  124446. 0, 2, 4, 6, 8, 10, 12, 14,
  124447. 16,
  124448. };
  124449. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  124450. _vq_quantthresh__16c1_s_p6_0,
  124451. _vq_quantmap__16c1_s_p6_0,
  124452. 17,
  124453. 17
  124454. };
  124455. static static_codebook _16c1_s_p6_0 = {
  124456. 2, 289,
  124457. _vq_lengthlist__16c1_s_p6_0,
  124458. 1, -529530880, 1611661312, 5, 0,
  124459. _vq_quantlist__16c1_s_p6_0,
  124460. NULL,
  124461. &_vq_auxt__16c1_s_p6_0,
  124462. NULL,
  124463. 0
  124464. };
  124465. static long _vq_quantlist__16c1_s_p7_0[] = {
  124466. 1,
  124467. 0,
  124468. 2,
  124469. };
  124470. static long _vq_lengthlist__16c1_s_p7_0[] = {
  124471. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  124472. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  124473. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  124474. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  124475. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  124476. 11,
  124477. };
  124478. static float _vq_quantthresh__16c1_s_p7_0[] = {
  124479. -5.5, 5.5,
  124480. };
  124481. static long _vq_quantmap__16c1_s_p7_0[] = {
  124482. 1, 0, 2,
  124483. };
  124484. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  124485. _vq_quantthresh__16c1_s_p7_0,
  124486. _vq_quantmap__16c1_s_p7_0,
  124487. 3,
  124488. 3
  124489. };
  124490. static static_codebook _16c1_s_p7_0 = {
  124491. 4, 81,
  124492. _vq_lengthlist__16c1_s_p7_0,
  124493. 1, -529137664, 1618345984, 2, 0,
  124494. _vq_quantlist__16c1_s_p7_0,
  124495. NULL,
  124496. &_vq_auxt__16c1_s_p7_0,
  124497. NULL,
  124498. 0
  124499. };
  124500. static long _vq_quantlist__16c1_s_p7_1[] = {
  124501. 5,
  124502. 4,
  124503. 6,
  124504. 3,
  124505. 7,
  124506. 2,
  124507. 8,
  124508. 1,
  124509. 9,
  124510. 0,
  124511. 10,
  124512. };
  124513. static long _vq_lengthlist__16c1_s_p7_1[] = {
  124514. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  124515. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  124516. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  124517. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  124518. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  124519. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  124520. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  124521. 10,10,10, 8, 8, 8, 8, 9, 9,
  124522. };
  124523. static float _vq_quantthresh__16c1_s_p7_1[] = {
  124524. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124525. 3.5, 4.5,
  124526. };
  124527. static long _vq_quantmap__16c1_s_p7_1[] = {
  124528. 9, 7, 5, 3, 1, 0, 2, 4,
  124529. 6, 8, 10,
  124530. };
  124531. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  124532. _vq_quantthresh__16c1_s_p7_1,
  124533. _vq_quantmap__16c1_s_p7_1,
  124534. 11,
  124535. 11
  124536. };
  124537. static static_codebook _16c1_s_p7_1 = {
  124538. 2, 121,
  124539. _vq_lengthlist__16c1_s_p7_1,
  124540. 1, -531365888, 1611661312, 4, 0,
  124541. _vq_quantlist__16c1_s_p7_1,
  124542. NULL,
  124543. &_vq_auxt__16c1_s_p7_1,
  124544. NULL,
  124545. 0
  124546. };
  124547. static long _vq_quantlist__16c1_s_p8_0[] = {
  124548. 6,
  124549. 5,
  124550. 7,
  124551. 4,
  124552. 8,
  124553. 3,
  124554. 9,
  124555. 2,
  124556. 10,
  124557. 1,
  124558. 11,
  124559. 0,
  124560. 12,
  124561. };
  124562. static long _vq_lengthlist__16c1_s_p8_0[] = {
  124563. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  124564. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  124565. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  124566. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  124567. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  124568. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  124569. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  124570. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  124571. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  124572. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  124573. 0,12,12,12,12,13,13,14,15,
  124574. };
  124575. static float _vq_quantthresh__16c1_s_p8_0[] = {
  124576. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124577. 12.5, 17.5, 22.5, 27.5,
  124578. };
  124579. static long _vq_quantmap__16c1_s_p8_0[] = {
  124580. 11, 9, 7, 5, 3, 1, 0, 2,
  124581. 4, 6, 8, 10, 12,
  124582. };
  124583. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  124584. _vq_quantthresh__16c1_s_p8_0,
  124585. _vq_quantmap__16c1_s_p8_0,
  124586. 13,
  124587. 13
  124588. };
  124589. static static_codebook _16c1_s_p8_0 = {
  124590. 2, 169,
  124591. _vq_lengthlist__16c1_s_p8_0,
  124592. 1, -526516224, 1616117760, 4, 0,
  124593. _vq_quantlist__16c1_s_p8_0,
  124594. NULL,
  124595. &_vq_auxt__16c1_s_p8_0,
  124596. NULL,
  124597. 0
  124598. };
  124599. static long _vq_quantlist__16c1_s_p8_1[] = {
  124600. 2,
  124601. 1,
  124602. 3,
  124603. 0,
  124604. 4,
  124605. };
  124606. static long _vq_lengthlist__16c1_s_p8_1[] = {
  124607. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124608. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124609. };
  124610. static float _vq_quantthresh__16c1_s_p8_1[] = {
  124611. -1.5, -0.5, 0.5, 1.5,
  124612. };
  124613. static long _vq_quantmap__16c1_s_p8_1[] = {
  124614. 3, 1, 0, 2, 4,
  124615. };
  124616. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  124617. _vq_quantthresh__16c1_s_p8_1,
  124618. _vq_quantmap__16c1_s_p8_1,
  124619. 5,
  124620. 5
  124621. };
  124622. static static_codebook _16c1_s_p8_1 = {
  124623. 2, 25,
  124624. _vq_lengthlist__16c1_s_p8_1,
  124625. 1, -533725184, 1611661312, 3, 0,
  124626. _vq_quantlist__16c1_s_p8_1,
  124627. NULL,
  124628. &_vq_auxt__16c1_s_p8_1,
  124629. NULL,
  124630. 0
  124631. };
  124632. static long _vq_quantlist__16c1_s_p9_0[] = {
  124633. 6,
  124634. 5,
  124635. 7,
  124636. 4,
  124637. 8,
  124638. 3,
  124639. 9,
  124640. 2,
  124641. 10,
  124642. 1,
  124643. 11,
  124644. 0,
  124645. 12,
  124646. };
  124647. static long _vq_lengthlist__16c1_s_p9_0[] = {
  124648. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124649. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124650. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124651. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124652. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124653. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124654. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124655. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124656. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124657. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124658. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124659. };
  124660. static float _vq_quantthresh__16c1_s_p9_0[] = {
  124661. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  124662. 787.5, 1102.5, 1417.5, 1732.5,
  124663. };
  124664. static long _vq_quantmap__16c1_s_p9_0[] = {
  124665. 11, 9, 7, 5, 3, 1, 0, 2,
  124666. 4, 6, 8, 10, 12,
  124667. };
  124668. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  124669. _vq_quantthresh__16c1_s_p9_0,
  124670. _vq_quantmap__16c1_s_p9_0,
  124671. 13,
  124672. 13
  124673. };
  124674. static static_codebook _16c1_s_p9_0 = {
  124675. 2, 169,
  124676. _vq_lengthlist__16c1_s_p9_0,
  124677. 1, -513964032, 1628680192, 4, 0,
  124678. _vq_quantlist__16c1_s_p9_0,
  124679. NULL,
  124680. &_vq_auxt__16c1_s_p9_0,
  124681. NULL,
  124682. 0
  124683. };
  124684. static long _vq_quantlist__16c1_s_p9_1[] = {
  124685. 7,
  124686. 6,
  124687. 8,
  124688. 5,
  124689. 9,
  124690. 4,
  124691. 10,
  124692. 3,
  124693. 11,
  124694. 2,
  124695. 12,
  124696. 1,
  124697. 13,
  124698. 0,
  124699. 14,
  124700. };
  124701. static long _vq_lengthlist__16c1_s_p9_1[] = {
  124702. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  124703. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  124704. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  124705. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  124706. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  124707. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  124708. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  124709. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124710. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124711. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124712. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124713. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124714. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  124715. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124716. 13,
  124717. };
  124718. static float _vq_quantthresh__16c1_s_p9_1[] = {
  124719. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124720. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124721. };
  124722. static long _vq_quantmap__16c1_s_p9_1[] = {
  124723. 13, 11, 9, 7, 5, 3, 1, 0,
  124724. 2, 4, 6, 8, 10, 12, 14,
  124725. };
  124726. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  124727. _vq_quantthresh__16c1_s_p9_1,
  124728. _vq_quantmap__16c1_s_p9_1,
  124729. 15,
  124730. 15
  124731. };
  124732. static static_codebook _16c1_s_p9_1 = {
  124733. 2, 225,
  124734. _vq_lengthlist__16c1_s_p9_1,
  124735. 1, -520986624, 1620377600, 4, 0,
  124736. _vq_quantlist__16c1_s_p9_1,
  124737. NULL,
  124738. &_vq_auxt__16c1_s_p9_1,
  124739. NULL,
  124740. 0
  124741. };
  124742. static long _vq_quantlist__16c1_s_p9_2[] = {
  124743. 10,
  124744. 9,
  124745. 11,
  124746. 8,
  124747. 12,
  124748. 7,
  124749. 13,
  124750. 6,
  124751. 14,
  124752. 5,
  124753. 15,
  124754. 4,
  124755. 16,
  124756. 3,
  124757. 17,
  124758. 2,
  124759. 18,
  124760. 1,
  124761. 19,
  124762. 0,
  124763. 20,
  124764. };
  124765. static long _vq_lengthlist__16c1_s_p9_2[] = {
  124766. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  124767. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  124768. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  124769. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  124770. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  124771. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  124772. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  124773. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  124774. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  124775. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  124776. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  124777. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  124778. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  124779. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  124780. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  124781. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  124782. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  124783. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  124784. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  124785. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  124786. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  124787. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  124788. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  124789. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  124790. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  124791. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  124792. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  124793. 11,11,11,11,12,11,11,12,11,
  124794. };
  124795. static float _vq_quantthresh__16c1_s_p9_2[] = {
  124796. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  124797. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  124798. 6.5, 7.5, 8.5, 9.5,
  124799. };
  124800. static long _vq_quantmap__16c1_s_p9_2[] = {
  124801. 19, 17, 15, 13, 11, 9, 7, 5,
  124802. 3, 1, 0, 2, 4, 6, 8, 10,
  124803. 12, 14, 16, 18, 20,
  124804. };
  124805. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  124806. _vq_quantthresh__16c1_s_p9_2,
  124807. _vq_quantmap__16c1_s_p9_2,
  124808. 21,
  124809. 21
  124810. };
  124811. static static_codebook _16c1_s_p9_2 = {
  124812. 2, 441,
  124813. _vq_lengthlist__16c1_s_p9_2,
  124814. 1, -529268736, 1611661312, 5, 0,
  124815. _vq_quantlist__16c1_s_p9_2,
  124816. NULL,
  124817. &_vq_auxt__16c1_s_p9_2,
  124818. NULL,
  124819. 0
  124820. };
  124821. static long _huff_lengthlist__16c1_s_short[] = {
  124822. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  124823. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  124824. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  124825. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  124826. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  124827. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  124828. 9, 9,10,13,
  124829. };
  124830. static static_codebook _huff_book__16c1_s_short = {
  124831. 2, 100,
  124832. _huff_lengthlist__16c1_s_short,
  124833. 0, 0, 0, 0, 0,
  124834. NULL,
  124835. NULL,
  124836. NULL,
  124837. NULL,
  124838. 0
  124839. };
  124840. static long _huff_lengthlist__16c2_s_long[] = {
  124841. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  124842. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  124843. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  124844. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  124845. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  124846. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  124847. 14,14,16,18,
  124848. };
  124849. static static_codebook _huff_book__16c2_s_long = {
  124850. 2, 100,
  124851. _huff_lengthlist__16c2_s_long,
  124852. 0, 0, 0, 0, 0,
  124853. NULL,
  124854. NULL,
  124855. NULL,
  124856. NULL,
  124857. 0
  124858. };
  124859. static long _vq_quantlist__16c2_s_p1_0[] = {
  124860. 1,
  124861. 0,
  124862. 2,
  124863. };
  124864. static long _vq_lengthlist__16c2_s_p1_0[] = {
  124865. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  124866. 0, 0, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124870. 0,
  124871. };
  124872. static float _vq_quantthresh__16c2_s_p1_0[] = {
  124873. -0.5, 0.5,
  124874. };
  124875. static long _vq_quantmap__16c2_s_p1_0[] = {
  124876. 1, 0, 2,
  124877. };
  124878. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  124879. _vq_quantthresh__16c2_s_p1_0,
  124880. _vq_quantmap__16c2_s_p1_0,
  124881. 3,
  124882. 3
  124883. };
  124884. static static_codebook _16c2_s_p1_0 = {
  124885. 4, 81,
  124886. _vq_lengthlist__16c2_s_p1_0,
  124887. 1, -535822336, 1611661312, 2, 0,
  124888. _vq_quantlist__16c2_s_p1_0,
  124889. NULL,
  124890. &_vq_auxt__16c2_s_p1_0,
  124891. NULL,
  124892. 0
  124893. };
  124894. static long _vq_quantlist__16c2_s_p2_0[] = {
  124895. 2,
  124896. 1,
  124897. 3,
  124898. 0,
  124899. 4,
  124900. };
  124901. static long _vq_lengthlist__16c2_s_p2_0[] = {
  124902. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  124903. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  124904. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  124905. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  124906. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  124907. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  124908. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  124909. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  124910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124914. 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8,11,11, 0, 0, 0,
  124915. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  124916. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  124917. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  124918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124922. 0, 0, 0, 0, 0, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  124923. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  124924. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  124925. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124930. 0, 0, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  124931. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  124932. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  124933. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8,
  124938. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  124939. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  124940. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  124941. 13,
  124942. };
  124943. static float _vq_quantthresh__16c2_s_p2_0[] = {
  124944. -1.5, -0.5, 0.5, 1.5,
  124945. };
  124946. static long _vq_quantmap__16c2_s_p2_0[] = {
  124947. 3, 1, 0, 2, 4,
  124948. };
  124949. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  124950. _vq_quantthresh__16c2_s_p2_0,
  124951. _vq_quantmap__16c2_s_p2_0,
  124952. 5,
  124953. 5
  124954. };
  124955. static static_codebook _16c2_s_p2_0 = {
  124956. 4, 625,
  124957. _vq_lengthlist__16c2_s_p2_0,
  124958. 1, -533725184, 1611661312, 3, 0,
  124959. _vq_quantlist__16c2_s_p2_0,
  124960. NULL,
  124961. &_vq_auxt__16c2_s_p2_0,
  124962. NULL,
  124963. 0
  124964. };
  124965. static long _vq_quantlist__16c2_s_p3_0[] = {
  124966. 4,
  124967. 3,
  124968. 5,
  124969. 2,
  124970. 6,
  124971. 1,
  124972. 7,
  124973. 0,
  124974. 8,
  124975. };
  124976. static long _vq_lengthlist__16c2_s_p3_0[] = {
  124977. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  124978. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  124979. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  124980. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  124981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124982. 0,
  124983. };
  124984. static float _vq_quantthresh__16c2_s_p3_0[] = {
  124985. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124986. };
  124987. static long _vq_quantmap__16c2_s_p3_0[] = {
  124988. 7, 5, 3, 1, 0, 2, 4, 6,
  124989. 8,
  124990. };
  124991. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  124992. _vq_quantthresh__16c2_s_p3_0,
  124993. _vq_quantmap__16c2_s_p3_0,
  124994. 9,
  124995. 9
  124996. };
  124997. static static_codebook _16c2_s_p3_0 = {
  124998. 2, 81,
  124999. _vq_lengthlist__16c2_s_p3_0,
  125000. 1, -531628032, 1611661312, 4, 0,
  125001. _vq_quantlist__16c2_s_p3_0,
  125002. NULL,
  125003. &_vq_auxt__16c2_s_p3_0,
  125004. NULL,
  125005. 0
  125006. };
  125007. static long _vq_quantlist__16c2_s_p4_0[] = {
  125008. 8,
  125009. 7,
  125010. 9,
  125011. 6,
  125012. 10,
  125013. 5,
  125014. 11,
  125015. 4,
  125016. 12,
  125017. 3,
  125018. 13,
  125019. 2,
  125020. 14,
  125021. 1,
  125022. 15,
  125023. 0,
  125024. 16,
  125025. };
  125026. static long _vq_lengthlist__16c2_s_p4_0[] = {
  125027. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  125028. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  125029. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  125030. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  125031. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  125032. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  125033. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  125034. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  125035. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  125036. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  125037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125045. 0,
  125046. };
  125047. static float _vq_quantthresh__16c2_s_p4_0[] = {
  125048. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125049. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125050. };
  125051. static long _vq_quantmap__16c2_s_p4_0[] = {
  125052. 15, 13, 11, 9, 7, 5, 3, 1,
  125053. 0, 2, 4, 6, 8, 10, 12, 14,
  125054. 16,
  125055. };
  125056. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  125057. _vq_quantthresh__16c2_s_p4_0,
  125058. _vq_quantmap__16c2_s_p4_0,
  125059. 17,
  125060. 17
  125061. };
  125062. static static_codebook _16c2_s_p4_0 = {
  125063. 2, 289,
  125064. _vq_lengthlist__16c2_s_p4_0,
  125065. 1, -529530880, 1611661312, 5, 0,
  125066. _vq_quantlist__16c2_s_p4_0,
  125067. NULL,
  125068. &_vq_auxt__16c2_s_p4_0,
  125069. NULL,
  125070. 0
  125071. };
  125072. static long _vq_quantlist__16c2_s_p5_0[] = {
  125073. 1,
  125074. 0,
  125075. 2,
  125076. };
  125077. static long _vq_lengthlist__16c2_s_p5_0[] = {
  125078. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  125079. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  125080. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  125081. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  125082. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  125083. 12,
  125084. };
  125085. static float _vq_quantthresh__16c2_s_p5_0[] = {
  125086. -5.5, 5.5,
  125087. };
  125088. static long _vq_quantmap__16c2_s_p5_0[] = {
  125089. 1, 0, 2,
  125090. };
  125091. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  125092. _vq_quantthresh__16c2_s_p5_0,
  125093. _vq_quantmap__16c2_s_p5_0,
  125094. 3,
  125095. 3
  125096. };
  125097. static static_codebook _16c2_s_p5_0 = {
  125098. 4, 81,
  125099. _vq_lengthlist__16c2_s_p5_0,
  125100. 1, -529137664, 1618345984, 2, 0,
  125101. _vq_quantlist__16c2_s_p5_0,
  125102. NULL,
  125103. &_vq_auxt__16c2_s_p5_0,
  125104. NULL,
  125105. 0
  125106. };
  125107. static long _vq_quantlist__16c2_s_p5_1[] = {
  125108. 5,
  125109. 4,
  125110. 6,
  125111. 3,
  125112. 7,
  125113. 2,
  125114. 8,
  125115. 1,
  125116. 9,
  125117. 0,
  125118. 10,
  125119. };
  125120. static long _vq_lengthlist__16c2_s_p5_1[] = {
  125121. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  125122. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  125123. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  125124. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  125125. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  125126. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  125127. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  125128. 11,11,11, 7, 7, 8, 8, 8, 8,
  125129. };
  125130. static float _vq_quantthresh__16c2_s_p5_1[] = {
  125131. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125132. 3.5, 4.5,
  125133. };
  125134. static long _vq_quantmap__16c2_s_p5_1[] = {
  125135. 9, 7, 5, 3, 1, 0, 2, 4,
  125136. 6, 8, 10,
  125137. };
  125138. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  125139. _vq_quantthresh__16c2_s_p5_1,
  125140. _vq_quantmap__16c2_s_p5_1,
  125141. 11,
  125142. 11
  125143. };
  125144. static static_codebook _16c2_s_p5_1 = {
  125145. 2, 121,
  125146. _vq_lengthlist__16c2_s_p5_1,
  125147. 1, -531365888, 1611661312, 4, 0,
  125148. _vq_quantlist__16c2_s_p5_1,
  125149. NULL,
  125150. &_vq_auxt__16c2_s_p5_1,
  125151. NULL,
  125152. 0
  125153. };
  125154. static long _vq_quantlist__16c2_s_p6_0[] = {
  125155. 6,
  125156. 5,
  125157. 7,
  125158. 4,
  125159. 8,
  125160. 3,
  125161. 9,
  125162. 2,
  125163. 10,
  125164. 1,
  125165. 11,
  125166. 0,
  125167. 12,
  125168. };
  125169. static long _vq_lengthlist__16c2_s_p6_0[] = {
  125170. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  125171. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  125172. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  125173. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  125174. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  125175. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  125176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125180. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125181. };
  125182. static float _vq_quantthresh__16c2_s_p6_0[] = {
  125183. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  125184. 12.5, 17.5, 22.5, 27.5,
  125185. };
  125186. static long _vq_quantmap__16c2_s_p6_0[] = {
  125187. 11, 9, 7, 5, 3, 1, 0, 2,
  125188. 4, 6, 8, 10, 12,
  125189. };
  125190. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  125191. _vq_quantthresh__16c2_s_p6_0,
  125192. _vq_quantmap__16c2_s_p6_0,
  125193. 13,
  125194. 13
  125195. };
  125196. static static_codebook _16c2_s_p6_0 = {
  125197. 2, 169,
  125198. _vq_lengthlist__16c2_s_p6_0,
  125199. 1, -526516224, 1616117760, 4, 0,
  125200. _vq_quantlist__16c2_s_p6_0,
  125201. NULL,
  125202. &_vq_auxt__16c2_s_p6_0,
  125203. NULL,
  125204. 0
  125205. };
  125206. static long _vq_quantlist__16c2_s_p6_1[] = {
  125207. 2,
  125208. 1,
  125209. 3,
  125210. 0,
  125211. 4,
  125212. };
  125213. static long _vq_lengthlist__16c2_s_p6_1[] = {
  125214. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  125215. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  125216. };
  125217. static float _vq_quantthresh__16c2_s_p6_1[] = {
  125218. -1.5, -0.5, 0.5, 1.5,
  125219. };
  125220. static long _vq_quantmap__16c2_s_p6_1[] = {
  125221. 3, 1, 0, 2, 4,
  125222. };
  125223. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  125224. _vq_quantthresh__16c2_s_p6_1,
  125225. _vq_quantmap__16c2_s_p6_1,
  125226. 5,
  125227. 5
  125228. };
  125229. static static_codebook _16c2_s_p6_1 = {
  125230. 2, 25,
  125231. _vq_lengthlist__16c2_s_p6_1,
  125232. 1, -533725184, 1611661312, 3, 0,
  125233. _vq_quantlist__16c2_s_p6_1,
  125234. NULL,
  125235. &_vq_auxt__16c2_s_p6_1,
  125236. NULL,
  125237. 0
  125238. };
  125239. static long _vq_quantlist__16c2_s_p7_0[] = {
  125240. 6,
  125241. 5,
  125242. 7,
  125243. 4,
  125244. 8,
  125245. 3,
  125246. 9,
  125247. 2,
  125248. 10,
  125249. 1,
  125250. 11,
  125251. 0,
  125252. 12,
  125253. };
  125254. static long _vq_lengthlist__16c2_s_p7_0[] = {
  125255. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  125256. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  125257. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  125258. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  125259. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  125260. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  125261. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  125262. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  125263. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  125264. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  125265. 18,13,14,13,13,14,13,15,14,
  125266. };
  125267. static float _vq_quantthresh__16c2_s_p7_0[] = {
  125268. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  125269. 27.5, 38.5, 49.5, 60.5,
  125270. };
  125271. static long _vq_quantmap__16c2_s_p7_0[] = {
  125272. 11, 9, 7, 5, 3, 1, 0, 2,
  125273. 4, 6, 8, 10, 12,
  125274. };
  125275. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  125276. _vq_quantthresh__16c2_s_p7_0,
  125277. _vq_quantmap__16c2_s_p7_0,
  125278. 13,
  125279. 13
  125280. };
  125281. static static_codebook _16c2_s_p7_0 = {
  125282. 2, 169,
  125283. _vq_lengthlist__16c2_s_p7_0,
  125284. 1, -523206656, 1618345984, 4, 0,
  125285. _vq_quantlist__16c2_s_p7_0,
  125286. NULL,
  125287. &_vq_auxt__16c2_s_p7_0,
  125288. NULL,
  125289. 0
  125290. };
  125291. static long _vq_quantlist__16c2_s_p7_1[] = {
  125292. 5,
  125293. 4,
  125294. 6,
  125295. 3,
  125296. 7,
  125297. 2,
  125298. 8,
  125299. 1,
  125300. 9,
  125301. 0,
  125302. 10,
  125303. };
  125304. static long _vq_lengthlist__16c2_s_p7_1[] = {
  125305. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  125306. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  125307. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  125308. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  125309. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  125310. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  125311. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  125312. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  125313. };
  125314. static float _vq_quantthresh__16c2_s_p7_1[] = {
  125315. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125316. 3.5, 4.5,
  125317. };
  125318. static long _vq_quantmap__16c2_s_p7_1[] = {
  125319. 9, 7, 5, 3, 1, 0, 2, 4,
  125320. 6, 8, 10,
  125321. };
  125322. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  125323. _vq_quantthresh__16c2_s_p7_1,
  125324. _vq_quantmap__16c2_s_p7_1,
  125325. 11,
  125326. 11
  125327. };
  125328. static static_codebook _16c2_s_p7_1 = {
  125329. 2, 121,
  125330. _vq_lengthlist__16c2_s_p7_1,
  125331. 1, -531365888, 1611661312, 4, 0,
  125332. _vq_quantlist__16c2_s_p7_1,
  125333. NULL,
  125334. &_vq_auxt__16c2_s_p7_1,
  125335. NULL,
  125336. 0
  125337. };
  125338. static long _vq_quantlist__16c2_s_p8_0[] = {
  125339. 7,
  125340. 6,
  125341. 8,
  125342. 5,
  125343. 9,
  125344. 4,
  125345. 10,
  125346. 3,
  125347. 11,
  125348. 2,
  125349. 12,
  125350. 1,
  125351. 13,
  125352. 0,
  125353. 14,
  125354. };
  125355. static long _vq_lengthlist__16c2_s_p8_0[] = {
  125356. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  125357. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  125358. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  125359. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  125360. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  125361. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  125362. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  125363. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  125364. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  125365. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  125366. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  125367. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  125368. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  125369. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  125370. 13,
  125371. };
  125372. static float _vq_quantthresh__16c2_s_p8_0[] = {
  125373. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  125374. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  125375. };
  125376. static long _vq_quantmap__16c2_s_p8_0[] = {
  125377. 13, 11, 9, 7, 5, 3, 1, 0,
  125378. 2, 4, 6, 8, 10, 12, 14,
  125379. };
  125380. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  125381. _vq_quantthresh__16c2_s_p8_0,
  125382. _vq_quantmap__16c2_s_p8_0,
  125383. 15,
  125384. 15
  125385. };
  125386. static static_codebook _16c2_s_p8_0 = {
  125387. 2, 225,
  125388. _vq_lengthlist__16c2_s_p8_0,
  125389. 1, -520986624, 1620377600, 4, 0,
  125390. _vq_quantlist__16c2_s_p8_0,
  125391. NULL,
  125392. &_vq_auxt__16c2_s_p8_0,
  125393. NULL,
  125394. 0
  125395. };
  125396. static long _vq_quantlist__16c2_s_p8_1[] = {
  125397. 10,
  125398. 9,
  125399. 11,
  125400. 8,
  125401. 12,
  125402. 7,
  125403. 13,
  125404. 6,
  125405. 14,
  125406. 5,
  125407. 15,
  125408. 4,
  125409. 16,
  125410. 3,
  125411. 17,
  125412. 2,
  125413. 18,
  125414. 1,
  125415. 19,
  125416. 0,
  125417. 20,
  125418. };
  125419. static long _vq_lengthlist__16c2_s_p8_1[] = {
  125420. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  125421. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  125422. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  125423. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  125424. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  125425. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  125426. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  125427. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  125428. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  125429. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  125430. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  125431. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  125432. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  125433. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  125434. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  125435. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  125436. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  125437. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  125438. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  125439. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  125440. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  125441. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  125442. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  125443. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  125444. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  125445. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  125446. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  125447. 10,11,10,10,10,10,10,10,10,
  125448. };
  125449. static float _vq_quantthresh__16c2_s_p8_1[] = {
  125450. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  125451. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  125452. 6.5, 7.5, 8.5, 9.5,
  125453. };
  125454. static long _vq_quantmap__16c2_s_p8_1[] = {
  125455. 19, 17, 15, 13, 11, 9, 7, 5,
  125456. 3, 1, 0, 2, 4, 6, 8, 10,
  125457. 12, 14, 16, 18, 20,
  125458. };
  125459. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  125460. _vq_quantthresh__16c2_s_p8_1,
  125461. _vq_quantmap__16c2_s_p8_1,
  125462. 21,
  125463. 21
  125464. };
  125465. static static_codebook _16c2_s_p8_1 = {
  125466. 2, 441,
  125467. _vq_lengthlist__16c2_s_p8_1,
  125468. 1, -529268736, 1611661312, 5, 0,
  125469. _vq_quantlist__16c2_s_p8_1,
  125470. NULL,
  125471. &_vq_auxt__16c2_s_p8_1,
  125472. NULL,
  125473. 0
  125474. };
  125475. static long _vq_quantlist__16c2_s_p9_0[] = {
  125476. 6,
  125477. 5,
  125478. 7,
  125479. 4,
  125480. 8,
  125481. 3,
  125482. 9,
  125483. 2,
  125484. 10,
  125485. 1,
  125486. 11,
  125487. 0,
  125488. 12,
  125489. };
  125490. static long _vq_lengthlist__16c2_s_p9_0[] = {
  125491. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125492. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125493. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125494. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125495. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125496. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125497. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125498. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125499. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125500. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125501. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125502. };
  125503. static float _vq_quantthresh__16c2_s_p9_0[] = {
  125504. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  125505. 2327.5, 3258.5, 4189.5, 5120.5,
  125506. };
  125507. static long _vq_quantmap__16c2_s_p9_0[] = {
  125508. 11, 9, 7, 5, 3, 1, 0, 2,
  125509. 4, 6, 8, 10, 12,
  125510. };
  125511. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  125512. _vq_quantthresh__16c2_s_p9_0,
  125513. _vq_quantmap__16c2_s_p9_0,
  125514. 13,
  125515. 13
  125516. };
  125517. static static_codebook _16c2_s_p9_0 = {
  125518. 2, 169,
  125519. _vq_lengthlist__16c2_s_p9_0,
  125520. 1, -510275072, 1631393792, 4, 0,
  125521. _vq_quantlist__16c2_s_p9_0,
  125522. NULL,
  125523. &_vq_auxt__16c2_s_p9_0,
  125524. NULL,
  125525. 0
  125526. };
  125527. static long _vq_quantlist__16c2_s_p9_1[] = {
  125528. 8,
  125529. 7,
  125530. 9,
  125531. 6,
  125532. 10,
  125533. 5,
  125534. 11,
  125535. 4,
  125536. 12,
  125537. 3,
  125538. 13,
  125539. 2,
  125540. 14,
  125541. 1,
  125542. 15,
  125543. 0,
  125544. 16,
  125545. };
  125546. static long _vq_lengthlist__16c2_s_p9_1[] = {
  125547. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  125548. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  125549. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  125550. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  125551. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  125552. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  125553. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  125554. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  125555. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  125556. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  125557. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125558. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125559. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125560. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125561. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125562. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  125563. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  125564. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125565. 10,
  125566. };
  125567. static float _vq_quantthresh__16c2_s_p9_1[] = {
  125568. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  125569. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  125570. };
  125571. static long _vq_quantmap__16c2_s_p9_1[] = {
  125572. 15, 13, 11, 9, 7, 5, 3, 1,
  125573. 0, 2, 4, 6, 8, 10, 12, 14,
  125574. 16,
  125575. };
  125576. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  125577. _vq_quantthresh__16c2_s_p9_1,
  125578. _vq_quantmap__16c2_s_p9_1,
  125579. 17,
  125580. 17
  125581. };
  125582. static static_codebook _16c2_s_p9_1 = {
  125583. 2, 289,
  125584. _vq_lengthlist__16c2_s_p9_1,
  125585. 1, -518488064, 1622704128, 5, 0,
  125586. _vq_quantlist__16c2_s_p9_1,
  125587. NULL,
  125588. &_vq_auxt__16c2_s_p9_1,
  125589. NULL,
  125590. 0
  125591. };
  125592. static long _vq_quantlist__16c2_s_p9_2[] = {
  125593. 13,
  125594. 12,
  125595. 14,
  125596. 11,
  125597. 15,
  125598. 10,
  125599. 16,
  125600. 9,
  125601. 17,
  125602. 8,
  125603. 18,
  125604. 7,
  125605. 19,
  125606. 6,
  125607. 20,
  125608. 5,
  125609. 21,
  125610. 4,
  125611. 22,
  125612. 3,
  125613. 23,
  125614. 2,
  125615. 24,
  125616. 1,
  125617. 25,
  125618. 0,
  125619. 26,
  125620. };
  125621. static long _vq_lengthlist__16c2_s_p9_2[] = {
  125622. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  125623. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  125624. };
  125625. static float _vq_quantthresh__16c2_s_p9_2[] = {
  125626. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  125627. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125628. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  125629. 11.5, 12.5,
  125630. };
  125631. static long _vq_quantmap__16c2_s_p9_2[] = {
  125632. 25, 23, 21, 19, 17, 15, 13, 11,
  125633. 9, 7, 5, 3, 1, 0, 2, 4,
  125634. 6, 8, 10, 12, 14, 16, 18, 20,
  125635. 22, 24, 26,
  125636. };
  125637. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  125638. _vq_quantthresh__16c2_s_p9_2,
  125639. _vq_quantmap__16c2_s_p9_2,
  125640. 27,
  125641. 27
  125642. };
  125643. static static_codebook _16c2_s_p9_2 = {
  125644. 1, 27,
  125645. _vq_lengthlist__16c2_s_p9_2,
  125646. 1, -528875520, 1611661312, 5, 0,
  125647. _vq_quantlist__16c2_s_p9_2,
  125648. NULL,
  125649. &_vq_auxt__16c2_s_p9_2,
  125650. NULL,
  125651. 0
  125652. };
  125653. static long _huff_lengthlist__16c2_s_short[] = {
  125654. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  125655. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  125656. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  125657. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  125658. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  125659. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  125660. 15,12,14,14,
  125661. };
  125662. static static_codebook _huff_book__16c2_s_short = {
  125663. 2, 100,
  125664. _huff_lengthlist__16c2_s_short,
  125665. 0, 0, 0, 0, 0,
  125666. NULL,
  125667. NULL,
  125668. NULL,
  125669. NULL,
  125670. 0
  125671. };
  125672. static long _vq_quantlist__8c0_s_p1_0[] = {
  125673. 1,
  125674. 0,
  125675. 2,
  125676. };
  125677. static long _vq_lengthlist__8c0_s_p1_0[] = {
  125678. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  125679. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125683. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  125684. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125688. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  125689. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125705. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125710. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125715. 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0,
  125724. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7,10, 9, 0, 0, 0,
  125729. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 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, 7, 9,10, 0, 0,
  125734. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  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, 0, 0, 0, 0, 0, 0, 0,
  125750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  125755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  125760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125763. 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125770. 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  125775. 0, 0, 0, 0, 0, 9,10,11, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125780. 0, 0, 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 0,
  125781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  126089. };
  126090. static float _vq_quantthresh__8c0_s_p1_0[] = {
  126091. -0.5, 0.5,
  126092. };
  126093. static long _vq_quantmap__8c0_s_p1_0[] = {
  126094. 1, 0, 2,
  126095. };
  126096. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  126097. _vq_quantthresh__8c0_s_p1_0,
  126098. _vq_quantmap__8c0_s_p1_0,
  126099. 3,
  126100. 3
  126101. };
  126102. static static_codebook _8c0_s_p1_0 = {
  126103. 8, 6561,
  126104. _vq_lengthlist__8c0_s_p1_0,
  126105. 1, -535822336, 1611661312, 2, 0,
  126106. _vq_quantlist__8c0_s_p1_0,
  126107. NULL,
  126108. &_vq_auxt__8c0_s_p1_0,
  126109. NULL,
  126110. 0
  126111. };
  126112. static long _vq_quantlist__8c0_s_p2_0[] = {
  126113. 2,
  126114. 1,
  126115. 3,
  126116. 0,
  126117. 4,
  126118. };
  126119. static long _vq_lengthlist__8c0_s_p2_0[] = {
  126120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126159. 0,
  126160. };
  126161. static float _vq_quantthresh__8c0_s_p2_0[] = {
  126162. -1.5, -0.5, 0.5, 1.5,
  126163. };
  126164. static long _vq_quantmap__8c0_s_p2_0[] = {
  126165. 3, 1, 0, 2, 4,
  126166. };
  126167. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  126168. _vq_quantthresh__8c0_s_p2_0,
  126169. _vq_quantmap__8c0_s_p2_0,
  126170. 5,
  126171. 5
  126172. };
  126173. static static_codebook _8c0_s_p2_0 = {
  126174. 4, 625,
  126175. _vq_lengthlist__8c0_s_p2_0,
  126176. 1, -533725184, 1611661312, 3, 0,
  126177. _vq_quantlist__8c0_s_p2_0,
  126178. NULL,
  126179. &_vq_auxt__8c0_s_p2_0,
  126180. NULL,
  126181. 0
  126182. };
  126183. static long _vq_quantlist__8c0_s_p3_0[] = {
  126184. 2,
  126185. 1,
  126186. 3,
  126187. 0,
  126188. 4,
  126189. };
  126190. static long _vq_lengthlist__8c0_s_p3_0[] = {
  126191. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  126193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126194. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  126196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126197. 0, 0, 0, 0, 6, 7, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  126198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126230. 0,
  126231. };
  126232. static float _vq_quantthresh__8c0_s_p3_0[] = {
  126233. -1.5, -0.5, 0.5, 1.5,
  126234. };
  126235. static long _vq_quantmap__8c0_s_p3_0[] = {
  126236. 3, 1, 0, 2, 4,
  126237. };
  126238. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  126239. _vq_quantthresh__8c0_s_p3_0,
  126240. _vq_quantmap__8c0_s_p3_0,
  126241. 5,
  126242. 5
  126243. };
  126244. static static_codebook _8c0_s_p3_0 = {
  126245. 4, 625,
  126246. _vq_lengthlist__8c0_s_p3_0,
  126247. 1, -533725184, 1611661312, 3, 0,
  126248. _vq_quantlist__8c0_s_p3_0,
  126249. NULL,
  126250. &_vq_auxt__8c0_s_p3_0,
  126251. NULL,
  126252. 0
  126253. };
  126254. static long _vq_quantlist__8c0_s_p4_0[] = {
  126255. 4,
  126256. 3,
  126257. 5,
  126258. 2,
  126259. 6,
  126260. 1,
  126261. 7,
  126262. 0,
  126263. 8,
  126264. };
  126265. static long _vq_lengthlist__8c0_s_p4_0[] = {
  126266. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  126267. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  126268. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  126269. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  126270. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126271. 0,
  126272. };
  126273. static float _vq_quantthresh__8c0_s_p4_0[] = {
  126274. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126275. };
  126276. static long _vq_quantmap__8c0_s_p4_0[] = {
  126277. 7, 5, 3, 1, 0, 2, 4, 6,
  126278. 8,
  126279. };
  126280. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  126281. _vq_quantthresh__8c0_s_p4_0,
  126282. _vq_quantmap__8c0_s_p4_0,
  126283. 9,
  126284. 9
  126285. };
  126286. static static_codebook _8c0_s_p4_0 = {
  126287. 2, 81,
  126288. _vq_lengthlist__8c0_s_p4_0,
  126289. 1, -531628032, 1611661312, 4, 0,
  126290. _vq_quantlist__8c0_s_p4_0,
  126291. NULL,
  126292. &_vq_auxt__8c0_s_p4_0,
  126293. NULL,
  126294. 0
  126295. };
  126296. static long _vq_quantlist__8c0_s_p5_0[] = {
  126297. 4,
  126298. 3,
  126299. 5,
  126300. 2,
  126301. 6,
  126302. 1,
  126303. 7,
  126304. 0,
  126305. 8,
  126306. };
  126307. static long _vq_lengthlist__8c0_s_p5_0[] = {
  126308. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  126309. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  126310. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  126311. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  126312. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  126313. 10,
  126314. };
  126315. static float _vq_quantthresh__8c0_s_p5_0[] = {
  126316. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126317. };
  126318. static long _vq_quantmap__8c0_s_p5_0[] = {
  126319. 7, 5, 3, 1, 0, 2, 4, 6,
  126320. 8,
  126321. };
  126322. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  126323. _vq_quantthresh__8c0_s_p5_0,
  126324. _vq_quantmap__8c0_s_p5_0,
  126325. 9,
  126326. 9
  126327. };
  126328. static static_codebook _8c0_s_p5_0 = {
  126329. 2, 81,
  126330. _vq_lengthlist__8c0_s_p5_0,
  126331. 1, -531628032, 1611661312, 4, 0,
  126332. _vq_quantlist__8c0_s_p5_0,
  126333. NULL,
  126334. &_vq_auxt__8c0_s_p5_0,
  126335. NULL,
  126336. 0
  126337. };
  126338. static long _vq_quantlist__8c0_s_p6_0[] = {
  126339. 8,
  126340. 7,
  126341. 9,
  126342. 6,
  126343. 10,
  126344. 5,
  126345. 11,
  126346. 4,
  126347. 12,
  126348. 3,
  126349. 13,
  126350. 2,
  126351. 14,
  126352. 1,
  126353. 15,
  126354. 0,
  126355. 16,
  126356. };
  126357. static long _vq_lengthlist__8c0_s_p6_0[] = {
  126358. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  126359. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  126360. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  126361. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  126362. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  126363. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  126364. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  126365. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  126366. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  126367. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  126368. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  126369. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  126370. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  126371. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  126372. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  126373. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  126374. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  126375. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  126376. 14,
  126377. };
  126378. static float _vq_quantthresh__8c0_s_p6_0[] = {
  126379. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126380. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126381. };
  126382. static long _vq_quantmap__8c0_s_p6_0[] = {
  126383. 15, 13, 11, 9, 7, 5, 3, 1,
  126384. 0, 2, 4, 6, 8, 10, 12, 14,
  126385. 16,
  126386. };
  126387. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  126388. _vq_quantthresh__8c0_s_p6_0,
  126389. _vq_quantmap__8c0_s_p6_0,
  126390. 17,
  126391. 17
  126392. };
  126393. static static_codebook _8c0_s_p6_0 = {
  126394. 2, 289,
  126395. _vq_lengthlist__8c0_s_p6_0,
  126396. 1, -529530880, 1611661312, 5, 0,
  126397. _vq_quantlist__8c0_s_p6_0,
  126398. NULL,
  126399. &_vq_auxt__8c0_s_p6_0,
  126400. NULL,
  126401. 0
  126402. };
  126403. static long _vq_quantlist__8c0_s_p7_0[] = {
  126404. 1,
  126405. 0,
  126406. 2,
  126407. };
  126408. static long _vq_lengthlist__8c0_s_p7_0[] = {
  126409. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  126410. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  126411. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  126412. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  126413. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  126414. 10,
  126415. };
  126416. static float _vq_quantthresh__8c0_s_p7_0[] = {
  126417. -5.5, 5.5,
  126418. };
  126419. static long _vq_quantmap__8c0_s_p7_0[] = {
  126420. 1, 0, 2,
  126421. };
  126422. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  126423. _vq_quantthresh__8c0_s_p7_0,
  126424. _vq_quantmap__8c0_s_p7_0,
  126425. 3,
  126426. 3
  126427. };
  126428. static static_codebook _8c0_s_p7_0 = {
  126429. 4, 81,
  126430. _vq_lengthlist__8c0_s_p7_0,
  126431. 1, -529137664, 1618345984, 2, 0,
  126432. _vq_quantlist__8c0_s_p7_0,
  126433. NULL,
  126434. &_vq_auxt__8c0_s_p7_0,
  126435. NULL,
  126436. 0
  126437. };
  126438. static long _vq_quantlist__8c0_s_p7_1[] = {
  126439. 5,
  126440. 4,
  126441. 6,
  126442. 3,
  126443. 7,
  126444. 2,
  126445. 8,
  126446. 1,
  126447. 9,
  126448. 0,
  126449. 10,
  126450. };
  126451. static long _vq_lengthlist__8c0_s_p7_1[] = {
  126452. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  126453. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  126454. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  126455. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  126456. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  126457. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  126458. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  126459. 10,10,10, 9, 9, 9,10,10,10,
  126460. };
  126461. static float _vq_quantthresh__8c0_s_p7_1[] = {
  126462. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126463. 3.5, 4.5,
  126464. };
  126465. static long _vq_quantmap__8c0_s_p7_1[] = {
  126466. 9, 7, 5, 3, 1, 0, 2, 4,
  126467. 6, 8, 10,
  126468. };
  126469. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  126470. _vq_quantthresh__8c0_s_p7_1,
  126471. _vq_quantmap__8c0_s_p7_1,
  126472. 11,
  126473. 11
  126474. };
  126475. static static_codebook _8c0_s_p7_1 = {
  126476. 2, 121,
  126477. _vq_lengthlist__8c0_s_p7_1,
  126478. 1, -531365888, 1611661312, 4, 0,
  126479. _vq_quantlist__8c0_s_p7_1,
  126480. NULL,
  126481. &_vq_auxt__8c0_s_p7_1,
  126482. NULL,
  126483. 0
  126484. };
  126485. static long _vq_quantlist__8c0_s_p8_0[] = {
  126486. 6,
  126487. 5,
  126488. 7,
  126489. 4,
  126490. 8,
  126491. 3,
  126492. 9,
  126493. 2,
  126494. 10,
  126495. 1,
  126496. 11,
  126497. 0,
  126498. 12,
  126499. };
  126500. static long _vq_lengthlist__8c0_s_p8_0[] = {
  126501. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  126502. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  126503. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  126504. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  126505. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  126506. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  126507. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  126508. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  126509. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  126510. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  126511. 0, 0,13,13,11,13,13,11,12,
  126512. };
  126513. static float _vq_quantthresh__8c0_s_p8_0[] = {
  126514. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126515. 12.5, 17.5, 22.5, 27.5,
  126516. };
  126517. static long _vq_quantmap__8c0_s_p8_0[] = {
  126518. 11, 9, 7, 5, 3, 1, 0, 2,
  126519. 4, 6, 8, 10, 12,
  126520. };
  126521. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  126522. _vq_quantthresh__8c0_s_p8_0,
  126523. _vq_quantmap__8c0_s_p8_0,
  126524. 13,
  126525. 13
  126526. };
  126527. static static_codebook _8c0_s_p8_0 = {
  126528. 2, 169,
  126529. _vq_lengthlist__8c0_s_p8_0,
  126530. 1, -526516224, 1616117760, 4, 0,
  126531. _vq_quantlist__8c0_s_p8_0,
  126532. NULL,
  126533. &_vq_auxt__8c0_s_p8_0,
  126534. NULL,
  126535. 0
  126536. };
  126537. static long _vq_quantlist__8c0_s_p8_1[] = {
  126538. 2,
  126539. 1,
  126540. 3,
  126541. 0,
  126542. 4,
  126543. };
  126544. static long _vq_lengthlist__8c0_s_p8_1[] = {
  126545. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  126546. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  126547. };
  126548. static float _vq_quantthresh__8c0_s_p8_1[] = {
  126549. -1.5, -0.5, 0.5, 1.5,
  126550. };
  126551. static long _vq_quantmap__8c0_s_p8_1[] = {
  126552. 3, 1, 0, 2, 4,
  126553. };
  126554. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  126555. _vq_quantthresh__8c0_s_p8_1,
  126556. _vq_quantmap__8c0_s_p8_1,
  126557. 5,
  126558. 5
  126559. };
  126560. static static_codebook _8c0_s_p8_1 = {
  126561. 2, 25,
  126562. _vq_lengthlist__8c0_s_p8_1,
  126563. 1, -533725184, 1611661312, 3, 0,
  126564. _vq_quantlist__8c0_s_p8_1,
  126565. NULL,
  126566. &_vq_auxt__8c0_s_p8_1,
  126567. NULL,
  126568. 0
  126569. };
  126570. static long _vq_quantlist__8c0_s_p9_0[] = {
  126571. 1,
  126572. 0,
  126573. 2,
  126574. };
  126575. static long _vq_lengthlist__8c0_s_p9_0[] = {
  126576. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126577. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126578. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126579. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126580. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126581. 7,
  126582. };
  126583. static float _vq_quantthresh__8c0_s_p9_0[] = {
  126584. -157.5, 157.5,
  126585. };
  126586. static long _vq_quantmap__8c0_s_p9_0[] = {
  126587. 1, 0, 2,
  126588. };
  126589. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  126590. _vq_quantthresh__8c0_s_p9_0,
  126591. _vq_quantmap__8c0_s_p9_0,
  126592. 3,
  126593. 3
  126594. };
  126595. static static_codebook _8c0_s_p9_0 = {
  126596. 4, 81,
  126597. _vq_lengthlist__8c0_s_p9_0,
  126598. 1, -518803456, 1628680192, 2, 0,
  126599. _vq_quantlist__8c0_s_p9_0,
  126600. NULL,
  126601. &_vq_auxt__8c0_s_p9_0,
  126602. NULL,
  126603. 0
  126604. };
  126605. static long _vq_quantlist__8c0_s_p9_1[] = {
  126606. 7,
  126607. 6,
  126608. 8,
  126609. 5,
  126610. 9,
  126611. 4,
  126612. 10,
  126613. 3,
  126614. 11,
  126615. 2,
  126616. 12,
  126617. 1,
  126618. 13,
  126619. 0,
  126620. 14,
  126621. };
  126622. static long _vq_lengthlist__8c0_s_p9_1[] = {
  126623. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  126624. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  126625. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  126626. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  126627. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126628. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126629. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126630. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126631. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126632. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126633. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126634. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126635. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126636. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126637. 11,
  126638. };
  126639. static float _vq_quantthresh__8c0_s_p9_1[] = {
  126640. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126641. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126642. };
  126643. static long _vq_quantmap__8c0_s_p9_1[] = {
  126644. 13, 11, 9, 7, 5, 3, 1, 0,
  126645. 2, 4, 6, 8, 10, 12, 14,
  126646. };
  126647. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  126648. _vq_quantthresh__8c0_s_p9_1,
  126649. _vq_quantmap__8c0_s_p9_1,
  126650. 15,
  126651. 15
  126652. };
  126653. static static_codebook _8c0_s_p9_1 = {
  126654. 2, 225,
  126655. _vq_lengthlist__8c0_s_p9_1,
  126656. 1, -520986624, 1620377600, 4, 0,
  126657. _vq_quantlist__8c0_s_p9_1,
  126658. NULL,
  126659. &_vq_auxt__8c0_s_p9_1,
  126660. NULL,
  126661. 0
  126662. };
  126663. static long _vq_quantlist__8c0_s_p9_2[] = {
  126664. 10,
  126665. 9,
  126666. 11,
  126667. 8,
  126668. 12,
  126669. 7,
  126670. 13,
  126671. 6,
  126672. 14,
  126673. 5,
  126674. 15,
  126675. 4,
  126676. 16,
  126677. 3,
  126678. 17,
  126679. 2,
  126680. 18,
  126681. 1,
  126682. 19,
  126683. 0,
  126684. 20,
  126685. };
  126686. static long _vq_lengthlist__8c0_s_p9_2[] = {
  126687. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  126688. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  126689. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  126690. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  126691. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  126692. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  126693. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  126694. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  126695. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  126696. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  126697. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  126698. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  126699. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  126700. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  126701. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  126702. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  126703. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  126704. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  126705. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  126706. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  126707. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  126708. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  126709. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  126710. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  126711. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  126712. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  126713. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  126714. 10,11, 9,11,10, 9,10, 9,10,
  126715. };
  126716. static float _vq_quantthresh__8c0_s_p9_2[] = {
  126717. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126718. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126719. 6.5, 7.5, 8.5, 9.5,
  126720. };
  126721. static long _vq_quantmap__8c0_s_p9_2[] = {
  126722. 19, 17, 15, 13, 11, 9, 7, 5,
  126723. 3, 1, 0, 2, 4, 6, 8, 10,
  126724. 12, 14, 16, 18, 20,
  126725. };
  126726. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  126727. _vq_quantthresh__8c0_s_p9_2,
  126728. _vq_quantmap__8c0_s_p9_2,
  126729. 21,
  126730. 21
  126731. };
  126732. static static_codebook _8c0_s_p9_2 = {
  126733. 2, 441,
  126734. _vq_lengthlist__8c0_s_p9_2,
  126735. 1, -529268736, 1611661312, 5, 0,
  126736. _vq_quantlist__8c0_s_p9_2,
  126737. NULL,
  126738. &_vq_auxt__8c0_s_p9_2,
  126739. NULL,
  126740. 0
  126741. };
  126742. static long _huff_lengthlist__8c0_s_single[] = {
  126743. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  126744. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  126745. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  126746. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  126747. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  126748. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  126749. 17,16,17,17,
  126750. };
  126751. static static_codebook _huff_book__8c0_s_single = {
  126752. 2, 100,
  126753. _huff_lengthlist__8c0_s_single,
  126754. 0, 0, 0, 0, 0,
  126755. NULL,
  126756. NULL,
  126757. NULL,
  126758. NULL,
  126759. 0
  126760. };
  126761. static long _vq_quantlist__8c1_s_p1_0[] = {
  126762. 1,
  126763. 0,
  126764. 2,
  126765. };
  126766. static long _vq_lengthlist__8c1_s_p1_0[] = {
  126767. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  126768. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126772. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  126773. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126777. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  126778. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126794. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126799. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126804. 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0,
  126813. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  126818. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  126823. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 0, 0, 0, 0, 0, 0, 0,
  126839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  126844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  126849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126852. 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  126859. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  126864. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  126869. 0, 0, 0, 0, 0, 0, 8,10, 8, 0, 0, 0, 0, 0, 0, 0,
  126870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  127178. };
  127179. static float _vq_quantthresh__8c1_s_p1_0[] = {
  127180. -0.5, 0.5,
  127181. };
  127182. static long _vq_quantmap__8c1_s_p1_0[] = {
  127183. 1, 0, 2,
  127184. };
  127185. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  127186. _vq_quantthresh__8c1_s_p1_0,
  127187. _vq_quantmap__8c1_s_p1_0,
  127188. 3,
  127189. 3
  127190. };
  127191. static static_codebook _8c1_s_p1_0 = {
  127192. 8, 6561,
  127193. _vq_lengthlist__8c1_s_p1_0,
  127194. 1, -535822336, 1611661312, 2, 0,
  127195. _vq_quantlist__8c1_s_p1_0,
  127196. NULL,
  127197. &_vq_auxt__8c1_s_p1_0,
  127198. NULL,
  127199. 0
  127200. };
  127201. static long _vq_quantlist__8c1_s_p2_0[] = {
  127202. 2,
  127203. 1,
  127204. 3,
  127205. 0,
  127206. 4,
  127207. };
  127208. static long _vq_lengthlist__8c1_s_p2_0[] = {
  127209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127248. 0,
  127249. };
  127250. static float _vq_quantthresh__8c1_s_p2_0[] = {
  127251. -1.5, -0.5, 0.5, 1.5,
  127252. };
  127253. static long _vq_quantmap__8c1_s_p2_0[] = {
  127254. 3, 1, 0, 2, 4,
  127255. };
  127256. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  127257. _vq_quantthresh__8c1_s_p2_0,
  127258. _vq_quantmap__8c1_s_p2_0,
  127259. 5,
  127260. 5
  127261. };
  127262. static static_codebook _8c1_s_p2_0 = {
  127263. 4, 625,
  127264. _vq_lengthlist__8c1_s_p2_0,
  127265. 1, -533725184, 1611661312, 3, 0,
  127266. _vq_quantlist__8c1_s_p2_0,
  127267. NULL,
  127268. &_vq_auxt__8c1_s_p2_0,
  127269. NULL,
  127270. 0
  127271. };
  127272. static long _vq_quantlist__8c1_s_p3_0[] = {
  127273. 2,
  127274. 1,
  127275. 3,
  127276. 0,
  127277. 4,
  127278. };
  127279. static long _vq_lengthlist__8c1_s_p3_0[] = {
  127280. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  127282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127283. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  127285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127286. 0, 0, 0, 0, 6, 6, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  127287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127319. 0,
  127320. };
  127321. static float _vq_quantthresh__8c1_s_p3_0[] = {
  127322. -1.5, -0.5, 0.5, 1.5,
  127323. };
  127324. static long _vq_quantmap__8c1_s_p3_0[] = {
  127325. 3, 1, 0, 2, 4,
  127326. };
  127327. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  127328. _vq_quantthresh__8c1_s_p3_0,
  127329. _vq_quantmap__8c1_s_p3_0,
  127330. 5,
  127331. 5
  127332. };
  127333. static static_codebook _8c1_s_p3_0 = {
  127334. 4, 625,
  127335. _vq_lengthlist__8c1_s_p3_0,
  127336. 1, -533725184, 1611661312, 3, 0,
  127337. _vq_quantlist__8c1_s_p3_0,
  127338. NULL,
  127339. &_vq_auxt__8c1_s_p3_0,
  127340. NULL,
  127341. 0
  127342. };
  127343. static long _vq_quantlist__8c1_s_p4_0[] = {
  127344. 4,
  127345. 3,
  127346. 5,
  127347. 2,
  127348. 6,
  127349. 1,
  127350. 7,
  127351. 0,
  127352. 8,
  127353. };
  127354. static long _vq_lengthlist__8c1_s_p4_0[] = {
  127355. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  127356. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  127357. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  127358. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  127359. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127360. 0,
  127361. };
  127362. static float _vq_quantthresh__8c1_s_p4_0[] = {
  127363. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127364. };
  127365. static long _vq_quantmap__8c1_s_p4_0[] = {
  127366. 7, 5, 3, 1, 0, 2, 4, 6,
  127367. 8,
  127368. };
  127369. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  127370. _vq_quantthresh__8c1_s_p4_0,
  127371. _vq_quantmap__8c1_s_p4_0,
  127372. 9,
  127373. 9
  127374. };
  127375. static static_codebook _8c1_s_p4_0 = {
  127376. 2, 81,
  127377. _vq_lengthlist__8c1_s_p4_0,
  127378. 1, -531628032, 1611661312, 4, 0,
  127379. _vq_quantlist__8c1_s_p4_0,
  127380. NULL,
  127381. &_vq_auxt__8c1_s_p4_0,
  127382. NULL,
  127383. 0
  127384. };
  127385. static long _vq_quantlist__8c1_s_p5_0[] = {
  127386. 4,
  127387. 3,
  127388. 5,
  127389. 2,
  127390. 6,
  127391. 1,
  127392. 7,
  127393. 0,
  127394. 8,
  127395. };
  127396. static long _vq_lengthlist__8c1_s_p5_0[] = {
  127397. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  127398. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  127399. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  127400. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  127401. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  127402. 10,
  127403. };
  127404. static float _vq_quantthresh__8c1_s_p5_0[] = {
  127405. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127406. };
  127407. static long _vq_quantmap__8c1_s_p5_0[] = {
  127408. 7, 5, 3, 1, 0, 2, 4, 6,
  127409. 8,
  127410. };
  127411. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  127412. _vq_quantthresh__8c1_s_p5_0,
  127413. _vq_quantmap__8c1_s_p5_0,
  127414. 9,
  127415. 9
  127416. };
  127417. static static_codebook _8c1_s_p5_0 = {
  127418. 2, 81,
  127419. _vq_lengthlist__8c1_s_p5_0,
  127420. 1, -531628032, 1611661312, 4, 0,
  127421. _vq_quantlist__8c1_s_p5_0,
  127422. NULL,
  127423. &_vq_auxt__8c1_s_p5_0,
  127424. NULL,
  127425. 0
  127426. };
  127427. static long _vq_quantlist__8c1_s_p6_0[] = {
  127428. 8,
  127429. 7,
  127430. 9,
  127431. 6,
  127432. 10,
  127433. 5,
  127434. 11,
  127435. 4,
  127436. 12,
  127437. 3,
  127438. 13,
  127439. 2,
  127440. 14,
  127441. 1,
  127442. 15,
  127443. 0,
  127444. 16,
  127445. };
  127446. static long _vq_lengthlist__8c1_s_p6_0[] = {
  127447. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  127448. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  127449. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127450. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  127451. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  127452. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  127453. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  127454. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  127455. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  127456. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  127457. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  127458. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  127459. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  127460. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  127461. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  127462. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  127463. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  127464. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  127465. 14,
  127466. };
  127467. static float _vq_quantthresh__8c1_s_p6_0[] = {
  127468. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127469. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127470. };
  127471. static long _vq_quantmap__8c1_s_p6_0[] = {
  127472. 15, 13, 11, 9, 7, 5, 3, 1,
  127473. 0, 2, 4, 6, 8, 10, 12, 14,
  127474. 16,
  127475. };
  127476. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  127477. _vq_quantthresh__8c1_s_p6_0,
  127478. _vq_quantmap__8c1_s_p6_0,
  127479. 17,
  127480. 17
  127481. };
  127482. static static_codebook _8c1_s_p6_0 = {
  127483. 2, 289,
  127484. _vq_lengthlist__8c1_s_p6_0,
  127485. 1, -529530880, 1611661312, 5, 0,
  127486. _vq_quantlist__8c1_s_p6_0,
  127487. NULL,
  127488. &_vq_auxt__8c1_s_p6_0,
  127489. NULL,
  127490. 0
  127491. };
  127492. static long _vq_quantlist__8c1_s_p7_0[] = {
  127493. 1,
  127494. 0,
  127495. 2,
  127496. };
  127497. static long _vq_lengthlist__8c1_s_p7_0[] = {
  127498. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  127499. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  127500. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  127501. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  127502. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  127503. 9,
  127504. };
  127505. static float _vq_quantthresh__8c1_s_p7_0[] = {
  127506. -5.5, 5.5,
  127507. };
  127508. static long _vq_quantmap__8c1_s_p7_0[] = {
  127509. 1, 0, 2,
  127510. };
  127511. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  127512. _vq_quantthresh__8c1_s_p7_0,
  127513. _vq_quantmap__8c1_s_p7_0,
  127514. 3,
  127515. 3
  127516. };
  127517. static static_codebook _8c1_s_p7_0 = {
  127518. 4, 81,
  127519. _vq_lengthlist__8c1_s_p7_0,
  127520. 1, -529137664, 1618345984, 2, 0,
  127521. _vq_quantlist__8c1_s_p7_0,
  127522. NULL,
  127523. &_vq_auxt__8c1_s_p7_0,
  127524. NULL,
  127525. 0
  127526. };
  127527. static long _vq_quantlist__8c1_s_p7_1[] = {
  127528. 5,
  127529. 4,
  127530. 6,
  127531. 3,
  127532. 7,
  127533. 2,
  127534. 8,
  127535. 1,
  127536. 9,
  127537. 0,
  127538. 10,
  127539. };
  127540. static long _vq_lengthlist__8c1_s_p7_1[] = {
  127541. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  127542. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  127543. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  127544. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  127545. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  127546. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  127547. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  127548. 10,10,10, 8, 8, 8, 8, 8, 8,
  127549. };
  127550. static float _vq_quantthresh__8c1_s_p7_1[] = {
  127551. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127552. 3.5, 4.5,
  127553. };
  127554. static long _vq_quantmap__8c1_s_p7_1[] = {
  127555. 9, 7, 5, 3, 1, 0, 2, 4,
  127556. 6, 8, 10,
  127557. };
  127558. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  127559. _vq_quantthresh__8c1_s_p7_1,
  127560. _vq_quantmap__8c1_s_p7_1,
  127561. 11,
  127562. 11
  127563. };
  127564. static static_codebook _8c1_s_p7_1 = {
  127565. 2, 121,
  127566. _vq_lengthlist__8c1_s_p7_1,
  127567. 1, -531365888, 1611661312, 4, 0,
  127568. _vq_quantlist__8c1_s_p7_1,
  127569. NULL,
  127570. &_vq_auxt__8c1_s_p7_1,
  127571. NULL,
  127572. 0
  127573. };
  127574. static long _vq_quantlist__8c1_s_p8_0[] = {
  127575. 6,
  127576. 5,
  127577. 7,
  127578. 4,
  127579. 8,
  127580. 3,
  127581. 9,
  127582. 2,
  127583. 10,
  127584. 1,
  127585. 11,
  127586. 0,
  127587. 12,
  127588. };
  127589. static long _vq_lengthlist__8c1_s_p8_0[] = {
  127590. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  127591. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  127592. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127593. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127594. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  127595. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  127596. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  127597. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  127598. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  127599. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  127600. 0,12,12,11,10,12,11,13,12,
  127601. };
  127602. static float _vq_quantthresh__8c1_s_p8_0[] = {
  127603. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127604. 12.5, 17.5, 22.5, 27.5,
  127605. };
  127606. static long _vq_quantmap__8c1_s_p8_0[] = {
  127607. 11, 9, 7, 5, 3, 1, 0, 2,
  127608. 4, 6, 8, 10, 12,
  127609. };
  127610. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  127611. _vq_quantthresh__8c1_s_p8_0,
  127612. _vq_quantmap__8c1_s_p8_0,
  127613. 13,
  127614. 13
  127615. };
  127616. static static_codebook _8c1_s_p8_0 = {
  127617. 2, 169,
  127618. _vq_lengthlist__8c1_s_p8_0,
  127619. 1, -526516224, 1616117760, 4, 0,
  127620. _vq_quantlist__8c1_s_p8_0,
  127621. NULL,
  127622. &_vq_auxt__8c1_s_p8_0,
  127623. NULL,
  127624. 0
  127625. };
  127626. static long _vq_quantlist__8c1_s_p8_1[] = {
  127627. 2,
  127628. 1,
  127629. 3,
  127630. 0,
  127631. 4,
  127632. };
  127633. static long _vq_lengthlist__8c1_s_p8_1[] = {
  127634. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  127635. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  127636. };
  127637. static float _vq_quantthresh__8c1_s_p8_1[] = {
  127638. -1.5, -0.5, 0.5, 1.5,
  127639. };
  127640. static long _vq_quantmap__8c1_s_p8_1[] = {
  127641. 3, 1, 0, 2, 4,
  127642. };
  127643. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  127644. _vq_quantthresh__8c1_s_p8_1,
  127645. _vq_quantmap__8c1_s_p8_1,
  127646. 5,
  127647. 5
  127648. };
  127649. static static_codebook _8c1_s_p8_1 = {
  127650. 2, 25,
  127651. _vq_lengthlist__8c1_s_p8_1,
  127652. 1, -533725184, 1611661312, 3, 0,
  127653. _vq_quantlist__8c1_s_p8_1,
  127654. NULL,
  127655. &_vq_auxt__8c1_s_p8_1,
  127656. NULL,
  127657. 0
  127658. };
  127659. static long _vq_quantlist__8c1_s_p9_0[] = {
  127660. 6,
  127661. 5,
  127662. 7,
  127663. 4,
  127664. 8,
  127665. 3,
  127666. 9,
  127667. 2,
  127668. 10,
  127669. 1,
  127670. 11,
  127671. 0,
  127672. 12,
  127673. };
  127674. static long _vq_lengthlist__8c1_s_p9_0[] = {
  127675. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  127676. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  127677. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127678. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127679. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127680. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127681. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127682. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127683. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127684. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127685. 10,10,10,10,10, 9, 9, 9, 9,
  127686. };
  127687. static float _vq_quantthresh__8c1_s_p9_0[] = {
  127688. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  127689. 787.5, 1102.5, 1417.5, 1732.5,
  127690. };
  127691. static long _vq_quantmap__8c1_s_p9_0[] = {
  127692. 11, 9, 7, 5, 3, 1, 0, 2,
  127693. 4, 6, 8, 10, 12,
  127694. };
  127695. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  127696. _vq_quantthresh__8c1_s_p9_0,
  127697. _vq_quantmap__8c1_s_p9_0,
  127698. 13,
  127699. 13
  127700. };
  127701. static static_codebook _8c1_s_p9_0 = {
  127702. 2, 169,
  127703. _vq_lengthlist__8c1_s_p9_0,
  127704. 1, -513964032, 1628680192, 4, 0,
  127705. _vq_quantlist__8c1_s_p9_0,
  127706. NULL,
  127707. &_vq_auxt__8c1_s_p9_0,
  127708. NULL,
  127709. 0
  127710. };
  127711. static long _vq_quantlist__8c1_s_p9_1[] = {
  127712. 7,
  127713. 6,
  127714. 8,
  127715. 5,
  127716. 9,
  127717. 4,
  127718. 10,
  127719. 3,
  127720. 11,
  127721. 2,
  127722. 12,
  127723. 1,
  127724. 13,
  127725. 0,
  127726. 14,
  127727. };
  127728. static long _vq_lengthlist__8c1_s_p9_1[] = {
  127729. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  127730. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  127731. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  127732. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  127733. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  127734. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  127735. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  127736. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  127737. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  127738. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  127739. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  127740. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  127741. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  127742. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  127743. 15,
  127744. };
  127745. static float _vq_quantthresh__8c1_s_p9_1[] = {
  127746. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  127747. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  127748. };
  127749. static long _vq_quantmap__8c1_s_p9_1[] = {
  127750. 13, 11, 9, 7, 5, 3, 1, 0,
  127751. 2, 4, 6, 8, 10, 12, 14,
  127752. };
  127753. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  127754. _vq_quantthresh__8c1_s_p9_1,
  127755. _vq_quantmap__8c1_s_p9_1,
  127756. 15,
  127757. 15
  127758. };
  127759. static static_codebook _8c1_s_p9_1 = {
  127760. 2, 225,
  127761. _vq_lengthlist__8c1_s_p9_1,
  127762. 1, -520986624, 1620377600, 4, 0,
  127763. _vq_quantlist__8c1_s_p9_1,
  127764. NULL,
  127765. &_vq_auxt__8c1_s_p9_1,
  127766. NULL,
  127767. 0
  127768. };
  127769. static long _vq_quantlist__8c1_s_p9_2[] = {
  127770. 10,
  127771. 9,
  127772. 11,
  127773. 8,
  127774. 12,
  127775. 7,
  127776. 13,
  127777. 6,
  127778. 14,
  127779. 5,
  127780. 15,
  127781. 4,
  127782. 16,
  127783. 3,
  127784. 17,
  127785. 2,
  127786. 18,
  127787. 1,
  127788. 19,
  127789. 0,
  127790. 20,
  127791. };
  127792. static long _vq_lengthlist__8c1_s_p9_2[] = {
  127793. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  127794. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  127795. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  127796. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  127797. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  127798. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  127799. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  127800. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  127801. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  127802. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  127803. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  127804. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  127805. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  127806. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  127807. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  127808. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  127809. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127810. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  127811. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  127812. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  127813. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127814. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  127815. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  127816. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  127817. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  127818. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  127819. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  127820. 10,10,10,10,10,10,10,10,10,
  127821. };
  127822. static float _vq_quantthresh__8c1_s_p9_2[] = {
  127823. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  127824. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  127825. 6.5, 7.5, 8.5, 9.5,
  127826. };
  127827. static long _vq_quantmap__8c1_s_p9_2[] = {
  127828. 19, 17, 15, 13, 11, 9, 7, 5,
  127829. 3, 1, 0, 2, 4, 6, 8, 10,
  127830. 12, 14, 16, 18, 20,
  127831. };
  127832. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  127833. _vq_quantthresh__8c1_s_p9_2,
  127834. _vq_quantmap__8c1_s_p9_2,
  127835. 21,
  127836. 21
  127837. };
  127838. static static_codebook _8c1_s_p9_2 = {
  127839. 2, 441,
  127840. _vq_lengthlist__8c1_s_p9_2,
  127841. 1, -529268736, 1611661312, 5, 0,
  127842. _vq_quantlist__8c1_s_p9_2,
  127843. NULL,
  127844. &_vq_auxt__8c1_s_p9_2,
  127845. NULL,
  127846. 0
  127847. };
  127848. static long _huff_lengthlist__8c1_s_single[] = {
  127849. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  127850. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  127851. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  127852. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  127853. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  127854. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  127855. 9, 7, 7, 8,
  127856. };
  127857. static static_codebook _huff_book__8c1_s_single = {
  127858. 2, 100,
  127859. _huff_lengthlist__8c1_s_single,
  127860. 0, 0, 0, 0, 0,
  127861. NULL,
  127862. NULL,
  127863. NULL,
  127864. NULL,
  127865. 0
  127866. };
  127867. static long _huff_lengthlist__44c2_s_long[] = {
  127868. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  127869. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  127870. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  127871. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  127872. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  127873. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  127874. 10, 8, 8, 9,
  127875. };
  127876. static static_codebook _huff_book__44c2_s_long = {
  127877. 2, 100,
  127878. _huff_lengthlist__44c2_s_long,
  127879. 0, 0, 0, 0, 0,
  127880. NULL,
  127881. NULL,
  127882. NULL,
  127883. NULL,
  127884. 0
  127885. };
  127886. static long _vq_quantlist__44c2_s_p1_0[] = {
  127887. 1,
  127888. 0,
  127889. 2,
  127890. };
  127891. static long _vq_lengthlist__44c2_s_p1_0[] = {
  127892. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  127893. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127897. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  127898. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127902. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  127903. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127919. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127924. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127929. 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0,
  127938. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  127943. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  127948. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 0, 0, 0, 0, 0, 0, 0,
  127964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  127969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  127974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127977. 0, 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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  127984. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  127989. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  127994. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  127995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  128303. };
  128304. static float _vq_quantthresh__44c2_s_p1_0[] = {
  128305. -0.5, 0.5,
  128306. };
  128307. static long _vq_quantmap__44c2_s_p1_0[] = {
  128308. 1, 0, 2,
  128309. };
  128310. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  128311. _vq_quantthresh__44c2_s_p1_0,
  128312. _vq_quantmap__44c2_s_p1_0,
  128313. 3,
  128314. 3
  128315. };
  128316. static static_codebook _44c2_s_p1_0 = {
  128317. 8, 6561,
  128318. _vq_lengthlist__44c2_s_p1_0,
  128319. 1, -535822336, 1611661312, 2, 0,
  128320. _vq_quantlist__44c2_s_p1_0,
  128321. NULL,
  128322. &_vq_auxt__44c2_s_p1_0,
  128323. NULL,
  128324. 0
  128325. };
  128326. static long _vq_quantlist__44c2_s_p2_0[] = {
  128327. 2,
  128328. 1,
  128329. 3,
  128330. 0,
  128331. 4,
  128332. };
  128333. static long _vq_lengthlist__44c2_s_p2_0[] = {
  128334. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  128335. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  128336. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  128337. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  128338. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128343. 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  128344. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  128345. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  128346. 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128351. 0, 0, 0, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  128352. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  128353. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0,
  128354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128359. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  128360. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  128361. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 0, 0, 0, 0, 0,
  128362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128373. 0,
  128374. };
  128375. static float _vq_quantthresh__44c2_s_p2_0[] = {
  128376. -1.5, -0.5, 0.5, 1.5,
  128377. };
  128378. static long _vq_quantmap__44c2_s_p2_0[] = {
  128379. 3, 1, 0, 2, 4,
  128380. };
  128381. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  128382. _vq_quantthresh__44c2_s_p2_0,
  128383. _vq_quantmap__44c2_s_p2_0,
  128384. 5,
  128385. 5
  128386. };
  128387. static static_codebook _44c2_s_p2_0 = {
  128388. 4, 625,
  128389. _vq_lengthlist__44c2_s_p2_0,
  128390. 1, -533725184, 1611661312, 3, 0,
  128391. _vq_quantlist__44c2_s_p2_0,
  128392. NULL,
  128393. &_vq_auxt__44c2_s_p2_0,
  128394. NULL,
  128395. 0
  128396. };
  128397. static long _vq_quantlist__44c2_s_p3_0[] = {
  128398. 2,
  128399. 1,
  128400. 3,
  128401. 0,
  128402. 4,
  128403. };
  128404. static long _vq_lengthlist__44c2_s_p3_0[] = {
  128405. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  128407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128408. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  128410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128411. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  128412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128444. 0,
  128445. };
  128446. static float _vq_quantthresh__44c2_s_p3_0[] = {
  128447. -1.5, -0.5, 0.5, 1.5,
  128448. };
  128449. static long _vq_quantmap__44c2_s_p3_0[] = {
  128450. 3, 1, 0, 2, 4,
  128451. };
  128452. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  128453. _vq_quantthresh__44c2_s_p3_0,
  128454. _vq_quantmap__44c2_s_p3_0,
  128455. 5,
  128456. 5
  128457. };
  128458. static static_codebook _44c2_s_p3_0 = {
  128459. 4, 625,
  128460. _vq_lengthlist__44c2_s_p3_0,
  128461. 1, -533725184, 1611661312, 3, 0,
  128462. _vq_quantlist__44c2_s_p3_0,
  128463. NULL,
  128464. &_vq_auxt__44c2_s_p3_0,
  128465. NULL,
  128466. 0
  128467. };
  128468. static long _vq_quantlist__44c2_s_p4_0[] = {
  128469. 4,
  128470. 3,
  128471. 5,
  128472. 2,
  128473. 6,
  128474. 1,
  128475. 7,
  128476. 0,
  128477. 8,
  128478. };
  128479. static long _vq_lengthlist__44c2_s_p4_0[] = {
  128480. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  128481. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  128482. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  128483. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  128484. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128485. 0,
  128486. };
  128487. static float _vq_quantthresh__44c2_s_p4_0[] = {
  128488. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128489. };
  128490. static long _vq_quantmap__44c2_s_p4_0[] = {
  128491. 7, 5, 3, 1, 0, 2, 4, 6,
  128492. 8,
  128493. };
  128494. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  128495. _vq_quantthresh__44c2_s_p4_0,
  128496. _vq_quantmap__44c2_s_p4_0,
  128497. 9,
  128498. 9
  128499. };
  128500. static static_codebook _44c2_s_p4_0 = {
  128501. 2, 81,
  128502. _vq_lengthlist__44c2_s_p4_0,
  128503. 1, -531628032, 1611661312, 4, 0,
  128504. _vq_quantlist__44c2_s_p4_0,
  128505. NULL,
  128506. &_vq_auxt__44c2_s_p4_0,
  128507. NULL,
  128508. 0
  128509. };
  128510. static long _vq_quantlist__44c2_s_p5_0[] = {
  128511. 4,
  128512. 3,
  128513. 5,
  128514. 2,
  128515. 6,
  128516. 1,
  128517. 7,
  128518. 0,
  128519. 8,
  128520. };
  128521. static long _vq_lengthlist__44c2_s_p5_0[] = {
  128522. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  128523. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  128524. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  128525. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  128526. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  128527. 11,
  128528. };
  128529. static float _vq_quantthresh__44c2_s_p5_0[] = {
  128530. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128531. };
  128532. static long _vq_quantmap__44c2_s_p5_0[] = {
  128533. 7, 5, 3, 1, 0, 2, 4, 6,
  128534. 8,
  128535. };
  128536. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  128537. _vq_quantthresh__44c2_s_p5_0,
  128538. _vq_quantmap__44c2_s_p5_0,
  128539. 9,
  128540. 9
  128541. };
  128542. static static_codebook _44c2_s_p5_0 = {
  128543. 2, 81,
  128544. _vq_lengthlist__44c2_s_p5_0,
  128545. 1, -531628032, 1611661312, 4, 0,
  128546. _vq_quantlist__44c2_s_p5_0,
  128547. NULL,
  128548. &_vq_auxt__44c2_s_p5_0,
  128549. NULL,
  128550. 0
  128551. };
  128552. static long _vq_quantlist__44c2_s_p6_0[] = {
  128553. 8,
  128554. 7,
  128555. 9,
  128556. 6,
  128557. 10,
  128558. 5,
  128559. 11,
  128560. 4,
  128561. 12,
  128562. 3,
  128563. 13,
  128564. 2,
  128565. 14,
  128566. 1,
  128567. 15,
  128568. 0,
  128569. 16,
  128570. };
  128571. static long _vq_lengthlist__44c2_s_p6_0[] = {
  128572. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  128573. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  128574. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  128575. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  128576. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  128577. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  128578. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  128579. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  128580. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  128581. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  128582. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  128583. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  128584. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  128585. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  128586. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  128587. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  128588. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  128589. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  128590. 14,
  128591. };
  128592. static float _vq_quantthresh__44c2_s_p6_0[] = {
  128593. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128594. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128595. };
  128596. static long _vq_quantmap__44c2_s_p6_0[] = {
  128597. 15, 13, 11, 9, 7, 5, 3, 1,
  128598. 0, 2, 4, 6, 8, 10, 12, 14,
  128599. 16,
  128600. };
  128601. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  128602. _vq_quantthresh__44c2_s_p6_0,
  128603. _vq_quantmap__44c2_s_p6_0,
  128604. 17,
  128605. 17
  128606. };
  128607. static static_codebook _44c2_s_p6_0 = {
  128608. 2, 289,
  128609. _vq_lengthlist__44c2_s_p6_0,
  128610. 1, -529530880, 1611661312, 5, 0,
  128611. _vq_quantlist__44c2_s_p6_0,
  128612. NULL,
  128613. &_vq_auxt__44c2_s_p6_0,
  128614. NULL,
  128615. 0
  128616. };
  128617. static long _vq_quantlist__44c2_s_p7_0[] = {
  128618. 1,
  128619. 0,
  128620. 2,
  128621. };
  128622. static long _vq_lengthlist__44c2_s_p7_0[] = {
  128623. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  128624. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  128625. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  128626. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  128627. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  128628. 11,
  128629. };
  128630. static float _vq_quantthresh__44c2_s_p7_0[] = {
  128631. -5.5, 5.5,
  128632. };
  128633. static long _vq_quantmap__44c2_s_p7_0[] = {
  128634. 1, 0, 2,
  128635. };
  128636. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  128637. _vq_quantthresh__44c2_s_p7_0,
  128638. _vq_quantmap__44c2_s_p7_0,
  128639. 3,
  128640. 3
  128641. };
  128642. static static_codebook _44c2_s_p7_0 = {
  128643. 4, 81,
  128644. _vq_lengthlist__44c2_s_p7_0,
  128645. 1, -529137664, 1618345984, 2, 0,
  128646. _vq_quantlist__44c2_s_p7_0,
  128647. NULL,
  128648. &_vq_auxt__44c2_s_p7_0,
  128649. NULL,
  128650. 0
  128651. };
  128652. static long _vq_quantlist__44c2_s_p7_1[] = {
  128653. 5,
  128654. 4,
  128655. 6,
  128656. 3,
  128657. 7,
  128658. 2,
  128659. 8,
  128660. 1,
  128661. 9,
  128662. 0,
  128663. 10,
  128664. };
  128665. static long _vq_lengthlist__44c2_s_p7_1[] = {
  128666. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  128667. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  128668. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  128669. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  128670. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  128671. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  128672. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  128673. 10,10,10, 8, 8, 8, 8, 8, 8,
  128674. };
  128675. static float _vq_quantthresh__44c2_s_p7_1[] = {
  128676. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128677. 3.5, 4.5,
  128678. };
  128679. static long _vq_quantmap__44c2_s_p7_1[] = {
  128680. 9, 7, 5, 3, 1, 0, 2, 4,
  128681. 6, 8, 10,
  128682. };
  128683. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  128684. _vq_quantthresh__44c2_s_p7_1,
  128685. _vq_quantmap__44c2_s_p7_1,
  128686. 11,
  128687. 11
  128688. };
  128689. static static_codebook _44c2_s_p7_1 = {
  128690. 2, 121,
  128691. _vq_lengthlist__44c2_s_p7_1,
  128692. 1, -531365888, 1611661312, 4, 0,
  128693. _vq_quantlist__44c2_s_p7_1,
  128694. NULL,
  128695. &_vq_auxt__44c2_s_p7_1,
  128696. NULL,
  128697. 0
  128698. };
  128699. static long _vq_quantlist__44c2_s_p8_0[] = {
  128700. 6,
  128701. 5,
  128702. 7,
  128703. 4,
  128704. 8,
  128705. 3,
  128706. 9,
  128707. 2,
  128708. 10,
  128709. 1,
  128710. 11,
  128711. 0,
  128712. 12,
  128713. };
  128714. static long _vq_lengthlist__44c2_s_p8_0[] = {
  128715. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  128716. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  128717. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  128718. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  128719. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  128720. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  128721. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  128722. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  128723. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  128724. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  128725. 0,12,12,12,12,13,12,14,14,
  128726. };
  128727. static float _vq_quantthresh__44c2_s_p8_0[] = {
  128728. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128729. 12.5, 17.5, 22.5, 27.5,
  128730. };
  128731. static long _vq_quantmap__44c2_s_p8_0[] = {
  128732. 11, 9, 7, 5, 3, 1, 0, 2,
  128733. 4, 6, 8, 10, 12,
  128734. };
  128735. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  128736. _vq_quantthresh__44c2_s_p8_0,
  128737. _vq_quantmap__44c2_s_p8_0,
  128738. 13,
  128739. 13
  128740. };
  128741. static static_codebook _44c2_s_p8_0 = {
  128742. 2, 169,
  128743. _vq_lengthlist__44c2_s_p8_0,
  128744. 1, -526516224, 1616117760, 4, 0,
  128745. _vq_quantlist__44c2_s_p8_0,
  128746. NULL,
  128747. &_vq_auxt__44c2_s_p8_0,
  128748. NULL,
  128749. 0
  128750. };
  128751. static long _vq_quantlist__44c2_s_p8_1[] = {
  128752. 2,
  128753. 1,
  128754. 3,
  128755. 0,
  128756. 4,
  128757. };
  128758. static long _vq_lengthlist__44c2_s_p8_1[] = {
  128759. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  128760. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  128761. };
  128762. static float _vq_quantthresh__44c2_s_p8_1[] = {
  128763. -1.5, -0.5, 0.5, 1.5,
  128764. };
  128765. static long _vq_quantmap__44c2_s_p8_1[] = {
  128766. 3, 1, 0, 2, 4,
  128767. };
  128768. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  128769. _vq_quantthresh__44c2_s_p8_1,
  128770. _vq_quantmap__44c2_s_p8_1,
  128771. 5,
  128772. 5
  128773. };
  128774. static static_codebook _44c2_s_p8_1 = {
  128775. 2, 25,
  128776. _vq_lengthlist__44c2_s_p8_1,
  128777. 1, -533725184, 1611661312, 3, 0,
  128778. _vq_quantlist__44c2_s_p8_1,
  128779. NULL,
  128780. &_vq_auxt__44c2_s_p8_1,
  128781. NULL,
  128782. 0
  128783. };
  128784. static long _vq_quantlist__44c2_s_p9_0[] = {
  128785. 6,
  128786. 5,
  128787. 7,
  128788. 4,
  128789. 8,
  128790. 3,
  128791. 9,
  128792. 2,
  128793. 10,
  128794. 1,
  128795. 11,
  128796. 0,
  128797. 12,
  128798. };
  128799. static long _vq_lengthlist__44c2_s_p9_0[] = {
  128800. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  128801. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  128802. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128803. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  128804. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128805. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128806. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128807. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128808. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128809. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128810. 11,11,11,11,11,11,11,11,11,
  128811. };
  128812. static float _vq_quantthresh__44c2_s_p9_0[] = {
  128813. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  128814. 552.5, 773.5, 994.5, 1215.5,
  128815. };
  128816. static long _vq_quantmap__44c2_s_p9_0[] = {
  128817. 11, 9, 7, 5, 3, 1, 0, 2,
  128818. 4, 6, 8, 10, 12,
  128819. };
  128820. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  128821. _vq_quantthresh__44c2_s_p9_0,
  128822. _vq_quantmap__44c2_s_p9_0,
  128823. 13,
  128824. 13
  128825. };
  128826. static static_codebook _44c2_s_p9_0 = {
  128827. 2, 169,
  128828. _vq_lengthlist__44c2_s_p9_0,
  128829. 1, -514541568, 1627103232, 4, 0,
  128830. _vq_quantlist__44c2_s_p9_0,
  128831. NULL,
  128832. &_vq_auxt__44c2_s_p9_0,
  128833. NULL,
  128834. 0
  128835. };
  128836. static long _vq_quantlist__44c2_s_p9_1[] = {
  128837. 6,
  128838. 5,
  128839. 7,
  128840. 4,
  128841. 8,
  128842. 3,
  128843. 9,
  128844. 2,
  128845. 10,
  128846. 1,
  128847. 11,
  128848. 0,
  128849. 12,
  128850. };
  128851. static long _vq_lengthlist__44c2_s_p9_1[] = {
  128852. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  128853. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  128854. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  128855. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  128856. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  128857. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  128858. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  128859. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  128860. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  128861. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  128862. 17,13,12,12,10,13,11,14,14,
  128863. };
  128864. static float _vq_quantthresh__44c2_s_p9_1[] = {
  128865. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  128866. 42.5, 59.5, 76.5, 93.5,
  128867. };
  128868. static long _vq_quantmap__44c2_s_p9_1[] = {
  128869. 11, 9, 7, 5, 3, 1, 0, 2,
  128870. 4, 6, 8, 10, 12,
  128871. };
  128872. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  128873. _vq_quantthresh__44c2_s_p9_1,
  128874. _vq_quantmap__44c2_s_p9_1,
  128875. 13,
  128876. 13
  128877. };
  128878. static static_codebook _44c2_s_p9_1 = {
  128879. 2, 169,
  128880. _vq_lengthlist__44c2_s_p9_1,
  128881. 1, -522616832, 1620115456, 4, 0,
  128882. _vq_quantlist__44c2_s_p9_1,
  128883. NULL,
  128884. &_vq_auxt__44c2_s_p9_1,
  128885. NULL,
  128886. 0
  128887. };
  128888. static long _vq_quantlist__44c2_s_p9_2[] = {
  128889. 8,
  128890. 7,
  128891. 9,
  128892. 6,
  128893. 10,
  128894. 5,
  128895. 11,
  128896. 4,
  128897. 12,
  128898. 3,
  128899. 13,
  128900. 2,
  128901. 14,
  128902. 1,
  128903. 15,
  128904. 0,
  128905. 16,
  128906. };
  128907. static long _vq_lengthlist__44c2_s_p9_2[] = {
  128908. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  128909. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  128910. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  128911. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  128912. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  128913. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  128914. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  128915. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  128916. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  128917. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  128918. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  128919. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  128920. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  128921. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  128922. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  128923. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  128924. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  128925. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  128926. 10,
  128927. };
  128928. static float _vq_quantthresh__44c2_s_p9_2[] = {
  128929. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128930. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128931. };
  128932. static long _vq_quantmap__44c2_s_p9_2[] = {
  128933. 15, 13, 11, 9, 7, 5, 3, 1,
  128934. 0, 2, 4, 6, 8, 10, 12, 14,
  128935. 16,
  128936. };
  128937. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  128938. _vq_quantthresh__44c2_s_p9_2,
  128939. _vq_quantmap__44c2_s_p9_2,
  128940. 17,
  128941. 17
  128942. };
  128943. static static_codebook _44c2_s_p9_2 = {
  128944. 2, 289,
  128945. _vq_lengthlist__44c2_s_p9_2,
  128946. 1, -529530880, 1611661312, 5, 0,
  128947. _vq_quantlist__44c2_s_p9_2,
  128948. NULL,
  128949. &_vq_auxt__44c2_s_p9_2,
  128950. NULL,
  128951. 0
  128952. };
  128953. static long _huff_lengthlist__44c2_s_short[] = {
  128954. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  128955. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  128956. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  128957. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  128958. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  128959. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  128960. 6, 8, 9,12,
  128961. };
  128962. static static_codebook _huff_book__44c2_s_short = {
  128963. 2, 100,
  128964. _huff_lengthlist__44c2_s_short,
  128965. 0, 0, 0, 0, 0,
  128966. NULL,
  128967. NULL,
  128968. NULL,
  128969. NULL,
  128970. 0
  128971. };
  128972. static long _huff_lengthlist__44c3_s_long[] = {
  128973. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  128974. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  128975. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  128976. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  128977. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  128978. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  128979. 9, 8, 8, 8,
  128980. };
  128981. static static_codebook _huff_book__44c3_s_long = {
  128982. 2, 100,
  128983. _huff_lengthlist__44c3_s_long,
  128984. 0, 0, 0, 0, 0,
  128985. NULL,
  128986. NULL,
  128987. NULL,
  128988. NULL,
  128989. 0
  128990. };
  128991. static long _vq_quantlist__44c3_s_p1_0[] = {
  128992. 1,
  128993. 0,
  128994. 2,
  128995. };
  128996. static long _vq_lengthlist__44c3_s_p1_0[] = {
  128997. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  128998. 0, 0, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129002. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129003. 0, 0, 0, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129007. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  129008. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129029. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129034. 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0,
  129043. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  129048. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  129053. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 0, 0, 0, 0, 0, 0, 0,
  129069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  129074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  129079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129082. 0, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129089. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129094. 0, 0, 0, 0, 0, 7, 8, 9, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129099. 0, 0, 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 0,
  129100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129132. 0, 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,
  129408. };
  129409. static float _vq_quantthresh__44c3_s_p1_0[] = {
  129410. -0.5, 0.5,
  129411. };
  129412. static long _vq_quantmap__44c3_s_p1_0[] = {
  129413. 1, 0, 2,
  129414. };
  129415. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  129416. _vq_quantthresh__44c3_s_p1_0,
  129417. _vq_quantmap__44c3_s_p1_0,
  129418. 3,
  129419. 3
  129420. };
  129421. static static_codebook _44c3_s_p1_0 = {
  129422. 8, 6561,
  129423. _vq_lengthlist__44c3_s_p1_0,
  129424. 1, -535822336, 1611661312, 2, 0,
  129425. _vq_quantlist__44c3_s_p1_0,
  129426. NULL,
  129427. &_vq_auxt__44c3_s_p1_0,
  129428. NULL,
  129429. 0
  129430. };
  129431. static long _vq_quantlist__44c3_s_p2_0[] = {
  129432. 2,
  129433. 1,
  129434. 3,
  129435. 0,
  129436. 4,
  129437. };
  129438. static long _vq_lengthlist__44c3_s_p2_0[] = {
  129439. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  129440. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  129441. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129442. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  129443. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129448. 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  129449. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  129450. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  129451. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129456. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  129457. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  129458. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  129459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129464. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  129465. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  129466. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129478. 0,
  129479. };
  129480. static float _vq_quantthresh__44c3_s_p2_0[] = {
  129481. -1.5, -0.5, 0.5, 1.5,
  129482. };
  129483. static long _vq_quantmap__44c3_s_p2_0[] = {
  129484. 3, 1, 0, 2, 4,
  129485. };
  129486. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  129487. _vq_quantthresh__44c3_s_p2_0,
  129488. _vq_quantmap__44c3_s_p2_0,
  129489. 5,
  129490. 5
  129491. };
  129492. static static_codebook _44c3_s_p2_0 = {
  129493. 4, 625,
  129494. _vq_lengthlist__44c3_s_p2_0,
  129495. 1, -533725184, 1611661312, 3, 0,
  129496. _vq_quantlist__44c3_s_p2_0,
  129497. NULL,
  129498. &_vq_auxt__44c3_s_p2_0,
  129499. NULL,
  129500. 0
  129501. };
  129502. static long _vq_quantlist__44c3_s_p3_0[] = {
  129503. 2,
  129504. 1,
  129505. 3,
  129506. 0,
  129507. 4,
  129508. };
  129509. static long _vq_lengthlist__44c3_s_p3_0[] = {
  129510. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  129512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129513. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  129515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129516. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  129517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129549. 0,
  129550. };
  129551. static float _vq_quantthresh__44c3_s_p3_0[] = {
  129552. -1.5, -0.5, 0.5, 1.5,
  129553. };
  129554. static long _vq_quantmap__44c3_s_p3_0[] = {
  129555. 3, 1, 0, 2, 4,
  129556. };
  129557. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  129558. _vq_quantthresh__44c3_s_p3_0,
  129559. _vq_quantmap__44c3_s_p3_0,
  129560. 5,
  129561. 5
  129562. };
  129563. static static_codebook _44c3_s_p3_0 = {
  129564. 4, 625,
  129565. _vq_lengthlist__44c3_s_p3_0,
  129566. 1, -533725184, 1611661312, 3, 0,
  129567. _vq_quantlist__44c3_s_p3_0,
  129568. NULL,
  129569. &_vq_auxt__44c3_s_p3_0,
  129570. NULL,
  129571. 0
  129572. };
  129573. static long _vq_quantlist__44c3_s_p4_0[] = {
  129574. 4,
  129575. 3,
  129576. 5,
  129577. 2,
  129578. 6,
  129579. 1,
  129580. 7,
  129581. 0,
  129582. 8,
  129583. };
  129584. static long _vq_lengthlist__44c3_s_p4_0[] = {
  129585. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  129586. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  129587. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  129588. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  129589. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129590. 0,
  129591. };
  129592. static float _vq_quantthresh__44c3_s_p4_0[] = {
  129593. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129594. };
  129595. static long _vq_quantmap__44c3_s_p4_0[] = {
  129596. 7, 5, 3, 1, 0, 2, 4, 6,
  129597. 8,
  129598. };
  129599. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  129600. _vq_quantthresh__44c3_s_p4_0,
  129601. _vq_quantmap__44c3_s_p4_0,
  129602. 9,
  129603. 9
  129604. };
  129605. static static_codebook _44c3_s_p4_0 = {
  129606. 2, 81,
  129607. _vq_lengthlist__44c3_s_p4_0,
  129608. 1, -531628032, 1611661312, 4, 0,
  129609. _vq_quantlist__44c3_s_p4_0,
  129610. NULL,
  129611. &_vq_auxt__44c3_s_p4_0,
  129612. NULL,
  129613. 0
  129614. };
  129615. static long _vq_quantlist__44c3_s_p5_0[] = {
  129616. 4,
  129617. 3,
  129618. 5,
  129619. 2,
  129620. 6,
  129621. 1,
  129622. 7,
  129623. 0,
  129624. 8,
  129625. };
  129626. static long _vq_lengthlist__44c3_s_p5_0[] = {
  129627. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  129628. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  129629. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  129630. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  129631. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  129632. 11,
  129633. };
  129634. static float _vq_quantthresh__44c3_s_p5_0[] = {
  129635. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129636. };
  129637. static long _vq_quantmap__44c3_s_p5_0[] = {
  129638. 7, 5, 3, 1, 0, 2, 4, 6,
  129639. 8,
  129640. };
  129641. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  129642. _vq_quantthresh__44c3_s_p5_0,
  129643. _vq_quantmap__44c3_s_p5_0,
  129644. 9,
  129645. 9
  129646. };
  129647. static static_codebook _44c3_s_p5_0 = {
  129648. 2, 81,
  129649. _vq_lengthlist__44c3_s_p5_0,
  129650. 1, -531628032, 1611661312, 4, 0,
  129651. _vq_quantlist__44c3_s_p5_0,
  129652. NULL,
  129653. &_vq_auxt__44c3_s_p5_0,
  129654. NULL,
  129655. 0
  129656. };
  129657. static long _vq_quantlist__44c3_s_p6_0[] = {
  129658. 8,
  129659. 7,
  129660. 9,
  129661. 6,
  129662. 10,
  129663. 5,
  129664. 11,
  129665. 4,
  129666. 12,
  129667. 3,
  129668. 13,
  129669. 2,
  129670. 14,
  129671. 1,
  129672. 15,
  129673. 0,
  129674. 16,
  129675. };
  129676. static long _vq_lengthlist__44c3_s_p6_0[] = {
  129677. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  129678. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  129679. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  129680. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  129681. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  129682. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129683. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  129684. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  129685. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  129686. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  129687. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  129688. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  129689. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  129690. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  129691. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  129692. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  129693. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  129694. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  129695. 13,
  129696. };
  129697. static float _vq_quantthresh__44c3_s_p6_0[] = {
  129698. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129699. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129700. };
  129701. static long _vq_quantmap__44c3_s_p6_0[] = {
  129702. 15, 13, 11, 9, 7, 5, 3, 1,
  129703. 0, 2, 4, 6, 8, 10, 12, 14,
  129704. 16,
  129705. };
  129706. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  129707. _vq_quantthresh__44c3_s_p6_0,
  129708. _vq_quantmap__44c3_s_p6_0,
  129709. 17,
  129710. 17
  129711. };
  129712. static static_codebook _44c3_s_p6_0 = {
  129713. 2, 289,
  129714. _vq_lengthlist__44c3_s_p6_0,
  129715. 1, -529530880, 1611661312, 5, 0,
  129716. _vq_quantlist__44c3_s_p6_0,
  129717. NULL,
  129718. &_vq_auxt__44c3_s_p6_0,
  129719. NULL,
  129720. 0
  129721. };
  129722. static long _vq_quantlist__44c3_s_p7_0[] = {
  129723. 1,
  129724. 0,
  129725. 2,
  129726. };
  129727. static long _vq_lengthlist__44c3_s_p7_0[] = {
  129728. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  129729. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  129730. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  129731. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  129732. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  129733. 10,
  129734. };
  129735. static float _vq_quantthresh__44c3_s_p7_0[] = {
  129736. -5.5, 5.5,
  129737. };
  129738. static long _vq_quantmap__44c3_s_p7_0[] = {
  129739. 1, 0, 2,
  129740. };
  129741. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  129742. _vq_quantthresh__44c3_s_p7_0,
  129743. _vq_quantmap__44c3_s_p7_0,
  129744. 3,
  129745. 3
  129746. };
  129747. static static_codebook _44c3_s_p7_0 = {
  129748. 4, 81,
  129749. _vq_lengthlist__44c3_s_p7_0,
  129750. 1, -529137664, 1618345984, 2, 0,
  129751. _vq_quantlist__44c3_s_p7_0,
  129752. NULL,
  129753. &_vq_auxt__44c3_s_p7_0,
  129754. NULL,
  129755. 0
  129756. };
  129757. static long _vq_quantlist__44c3_s_p7_1[] = {
  129758. 5,
  129759. 4,
  129760. 6,
  129761. 3,
  129762. 7,
  129763. 2,
  129764. 8,
  129765. 1,
  129766. 9,
  129767. 0,
  129768. 10,
  129769. };
  129770. static long _vq_lengthlist__44c3_s_p7_1[] = {
  129771. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  129772. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  129773. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  129774. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  129775. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  129776. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  129777. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  129778. 10,10,10, 8, 8, 8, 8, 8, 8,
  129779. };
  129780. static float _vq_quantthresh__44c3_s_p7_1[] = {
  129781. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129782. 3.5, 4.5,
  129783. };
  129784. static long _vq_quantmap__44c3_s_p7_1[] = {
  129785. 9, 7, 5, 3, 1, 0, 2, 4,
  129786. 6, 8, 10,
  129787. };
  129788. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  129789. _vq_quantthresh__44c3_s_p7_1,
  129790. _vq_quantmap__44c3_s_p7_1,
  129791. 11,
  129792. 11
  129793. };
  129794. static static_codebook _44c3_s_p7_1 = {
  129795. 2, 121,
  129796. _vq_lengthlist__44c3_s_p7_1,
  129797. 1, -531365888, 1611661312, 4, 0,
  129798. _vq_quantlist__44c3_s_p7_1,
  129799. NULL,
  129800. &_vq_auxt__44c3_s_p7_1,
  129801. NULL,
  129802. 0
  129803. };
  129804. static long _vq_quantlist__44c3_s_p8_0[] = {
  129805. 6,
  129806. 5,
  129807. 7,
  129808. 4,
  129809. 8,
  129810. 3,
  129811. 9,
  129812. 2,
  129813. 10,
  129814. 1,
  129815. 11,
  129816. 0,
  129817. 12,
  129818. };
  129819. static long _vq_lengthlist__44c3_s_p8_0[] = {
  129820. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  129821. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  129822. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129823. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  129824. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  129825. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  129826. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  129827. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  129828. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  129829. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  129830. 0,13,13,12,12,13,12,14,13,
  129831. };
  129832. static float _vq_quantthresh__44c3_s_p8_0[] = {
  129833. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129834. 12.5, 17.5, 22.5, 27.5,
  129835. };
  129836. static long _vq_quantmap__44c3_s_p8_0[] = {
  129837. 11, 9, 7, 5, 3, 1, 0, 2,
  129838. 4, 6, 8, 10, 12,
  129839. };
  129840. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  129841. _vq_quantthresh__44c3_s_p8_0,
  129842. _vq_quantmap__44c3_s_p8_0,
  129843. 13,
  129844. 13
  129845. };
  129846. static static_codebook _44c3_s_p8_0 = {
  129847. 2, 169,
  129848. _vq_lengthlist__44c3_s_p8_0,
  129849. 1, -526516224, 1616117760, 4, 0,
  129850. _vq_quantlist__44c3_s_p8_0,
  129851. NULL,
  129852. &_vq_auxt__44c3_s_p8_0,
  129853. NULL,
  129854. 0
  129855. };
  129856. static long _vq_quantlist__44c3_s_p8_1[] = {
  129857. 2,
  129858. 1,
  129859. 3,
  129860. 0,
  129861. 4,
  129862. };
  129863. static long _vq_lengthlist__44c3_s_p8_1[] = {
  129864. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  129865. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  129866. };
  129867. static float _vq_quantthresh__44c3_s_p8_1[] = {
  129868. -1.5, -0.5, 0.5, 1.5,
  129869. };
  129870. static long _vq_quantmap__44c3_s_p8_1[] = {
  129871. 3, 1, 0, 2, 4,
  129872. };
  129873. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  129874. _vq_quantthresh__44c3_s_p8_1,
  129875. _vq_quantmap__44c3_s_p8_1,
  129876. 5,
  129877. 5
  129878. };
  129879. static static_codebook _44c3_s_p8_1 = {
  129880. 2, 25,
  129881. _vq_lengthlist__44c3_s_p8_1,
  129882. 1, -533725184, 1611661312, 3, 0,
  129883. _vq_quantlist__44c3_s_p8_1,
  129884. NULL,
  129885. &_vq_auxt__44c3_s_p8_1,
  129886. NULL,
  129887. 0
  129888. };
  129889. static long _vq_quantlist__44c3_s_p9_0[] = {
  129890. 6,
  129891. 5,
  129892. 7,
  129893. 4,
  129894. 8,
  129895. 3,
  129896. 9,
  129897. 2,
  129898. 10,
  129899. 1,
  129900. 11,
  129901. 0,
  129902. 12,
  129903. };
  129904. static long _vq_lengthlist__44c3_s_p9_0[] = {
  129905. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  129906. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  129907. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129908. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  129909. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129910. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129911. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129912. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  129913. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  129914. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129915. 11,11,11,11,11,11,11,11,11,
  129916. };
  129917. static float _vq_quantthresh__44c3_s_p9_0[] = {
  129918. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  129919. 637.5, 892.5, 1147.5, 1402.5,
  129920. };
  129921. static long _vq_quantmap__44c3_s_p9_0[] = {
  129922. 11, 9, 7, 5, 3, 1, 0, 2,
  129923. 4, 6, 8, 10, 12,
  129924. };
  129925. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  129926. _vq_quantthresh__44c3_s_p9_0,
  129927. _vq_quantmap__44c3_s_p9_0,
  129928. 13,
  129929. 13
  129930. };
  129931. static static_codebook _44c3_s_p9_0 = {
  129932. 2, 169,
  129933. _vq_lengthlist__44c3_s_p9_0,
  129934. 1, -514332672, 1627381760, 4, 0,
  129935. _vq_quantlist__44c3_s_p9_0,
  129936. NULL,
  129937. &_vq_auxt__44c3_s_p9_0,
  129938. NULL,
  129939. 0
  129940. };
  129941. static long _vq_quantlist__44c3_s_p9_1[] = {
  129942. 7,
  129943. 6,
  129944. 8,
  129945. 5,
  129946. 9,
  129947. 4,
  129948. 10,
  129949. 3,
  129950. 11,
  129951. 2,
  129952. 12,
  129953. 1,
  129954. 13,
  129955. 0,
  129956. 14,
  129957. };
  129958. static long _vq_lengthlist__44c3_s_p9_1[] = {
  129959. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  129960. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  129961. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  129962. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  129963. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  129964. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  129965. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  129966. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  129967. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  129968. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  129969. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  129970. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  129971. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  129972. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  129973. 15,
  129974. };
  129975. static float _vq_quantthresh__44c3_s_p9_1[] = {
  129976. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  129977. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  129978. };
  129979. static long _vq_quantmap__44c3_s_p9_1[] = {
  129980. 13, 11, 9, 7, 5, 3, 1, 0,
  129981. 2, 4, 6, 8, 10, 12, 14,
  129982. };
  129983. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  129984. _vq_quantthresh__44c3_s_p9_1,
  129985. _vq_quantmap__44c3_s_p9_1,
  129986. 15,
  129987. 15
  129988. };
  129989. static static_codebook _44c3_s_p9_1 = {
  129990. 2, 225,
  129991. _vq_lengthlist__44c3_s_p9_1,
  129992. 1, -522338304, 1620115456, 4, 0,
  129993. _vq_quantlist__44c3_s_p9_1,
  129994. NULL,
  129995. &_vq_auxt__44c3_s_p9_1,
  129996. NULL,
  129997. 0
  129998. };
  129999. static long _vq_quantlist__44c3_s_p9_2[] = {
  130000. 8,
  130001. 7,
  130002. 9,
  130003. 6,
  130004. 10,
  130005. 5,
  130006. 11,
  130007. 4,
  130008. 12,
  130009. 3,
  130010. 13,
  130011. 2,
  130012. 14,
  130013. 1,
  130014. 15,
  130015. 0,
  130016. 16,
  130017. };
  130018. static long _vq_lengthlist__44c3_s_p9_2[] = {
  130019. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  130020. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  130021. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  130022. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  130023. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  130024. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  130025. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  130026. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  130027. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  130028. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  130029. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  130030. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  130031. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  130032. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  130033. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  130034. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  130035. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  130036. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  130037. 10,
  130038. };
  130039. static float _vq_quantthresh__44c3_s_p9_2[] = {
  130040. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130041. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130042. };
  130043. static long _vq_quantmap__44c3_s_p9_2[] = {
  130044. 15, 13, 11, 9, 7, 5, 3, 1,
  130045. 0, 2, 4, 6, 8, 10, 12, 14,
  130046. 16,
  130047. };
  130048. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  130049. _vq_quantthresh__44c3_s_p9_2,
  130050. _vq_quantmap__44c3_s_p9_2,
  130051. 17,
  130052. 17
  130053. };
  130054. static static_codebook _44c3_s_p9_2 = {
  130055. 2, 289,
  130056. _vq_lengthlist__44c3_s_p9_2,
  130057. 1, -529530880, 1611661312, 5, 0,
  130058. _vq_quantlist__44c3_s_p9_2,
  130059. NULL,
  130060. &_vq_auxt__44c3_s_p9_2,
  130061. NULL,
  130062. 0
  130063. };
  130064. static long _huff_lengthlist__44c3_s_short[] = {
  130065. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  130066. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  130067. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  130068. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  130069. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  130070. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  130071. 6, 8, 9,11,
  130072. };
  130073. static static_codebook _huff_book__44c3_s_short = {
  130074. 2, 100,
  130075. _huff_lengthlist__44c3_s_short,
  130076. 0, 0, 0, 0, 0,
  130077. NULL,
  130078. NULL,
  130079. NULL,
  130080. NULL,
  130081. 0
  130082. };
  130083. static long _huff_lengthlist__44c4_s_long[] = {
  130084. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  130085. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  130086. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  130087. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  130088. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  130089. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  130090. 9, 8, 7, 7,
  130091. };
  130092. static static_codebook _huff_book__44c4_s_long = {
  130093. 2, 100,
  130094. _huff_lengthlist__44c4_s_long,
  130095. 0, 0, 0, 0, 0,
  130096. NULL,
  130097. NULL,
  130098. NULL,
  130099. NULL,
  130100. 0
  130101. };
  130102. static long _vq_quantlist__44c4_s_p1_0[] = {
  130103. 1,
  130104. 0,
  130105. 2,
  130106. };
  130107. static long _vq_lengthlist__44c4_s_p1_0[] = {
  130108. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  130109. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130113. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  130114. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130118. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  130119. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130135. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130140. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130145. 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0,
  130154. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  130159. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  130164. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 0, 0, 0, 0, 0, 0, 0,
  130180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  130185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  130190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130193. 0, 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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  130200. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  130205. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  130210. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  130211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  130519. };
  130520. static float _vq_quantthresh__44c4_s_p1_0[] = {
  130521. -0.5, 0.5,
  130522. };
  130523. static long _vq_quantmap__44c4_s_p1_0[] = {
  130524. 1, 0, 2,
  130525. };
  130526. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  130527. _vq_quantthresh__44c4_s_p1_0,
  130528. _vq_quantmap__44c4_s_p1_0,
  130529. 3,
  130530. 3
  130531. };
  130532. static static_codebook _44c4_s_p1_0 = {
  130533. 8, 6561,
  130534. _vq_lengthlist__44c4_s_p1_0,
  130535. 1, -535822336, 1611661312, 2, 0,
  130536. _vq_quantlist__44c4_s_p1_0,
  130537. NULL,
  130538. &_vq_auxt__44c4_s_p1_0,
  130539. NULL,
  130540. 0
  130541. };
  130542. static long _vq_quantlist__44c4_s_p2_0[] = {
  130543. 2,
  130544. 1,
  130545. 3,
  130546. 0,
  130547. 4,
  130548. };
  130549. static long _vq_lengthlist__44c4_s_p2_0[] = {
  130550. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  130551. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  130552. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130553. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  130554. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130559. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  130560. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  130561. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  130562. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130567. 0, 0, 0, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  130568. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  130569. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 0, 0,
  130570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130575. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  130576. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  130577. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130589. 0,
  130590. };
  130591. static float _vq_quantthresh__44c4_s_p2_0[] = {
  130592. -1.5, -0.5, 0.5, 1.5,
  130593. };
  130594. static long _vq_quantmap__44c4_s_p2_0[] = {
  130595. 3, 1, 0, 2, 4,
  130596. };
  130597. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  130598. _vq_quantthresh__44c4_s_p2_0,
  130599. _vq_quantmap__44c4_s_p2_0,
  130600. 5,
  130601. 5
  130602. };
  130603. static static_codebook _44c4_s_p2_0 = {
  130604. 4, 625,
  130605. _vq_lengthlist__44c4_s_p2_0,
  130606. 1, -533725184, 1611661312, 3, 0,
  130607. _vq_quantlist__44c4_s_p2_0,
  130608. NULL,
  130609. &_vq_auxt__44c4_s_p2_0,
  130610. NULL,
  130611. 0
  130612. };
  130613. static long _vq_quantlist__44c4_s_p3_0[] = {
  130614. 2,
  130615. 1,
  130616. 3,
  130617. 0,
  130618. 4,
  130619. };
  130620. static long _vq_lengthlist__44c4_s_p3_0[] = {
  130621. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  130623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130624. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  130626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130627. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  130628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130660. 0,
  130661. };
  130662. static float _vq_quantthresh__44c4_s_p3_0[] = {
  130663. -1.5, -0.5, 0.5, 1.5,
  130664. };
  130665. static long _vq_quantmap__44c4_s_p3_0[] = {
  130666. 3, 1, 0, 2, 4,
  130667. };
  130668. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  130669. _vq_quantthresh__44c4_s_p3_0,
  130670. _vq_quantmap__44c4_s_p3_0,
  130671. 5,
  130672. 5
  130673. };
  130674. static static_codebook _44c4_s_p3_0 = {
  130675. 4, 625,
  130676. _vq_lengthlist__44c4_s_p3_0,
  130677. 1, -533725184, 1611661312, 3, 0,
  130678. _vq_quantlist__44c4_s_p3_0,
  130679. NULL,
  130680. &_vq_auxt__44c4_s_p3_0,
  130681. NULL,
  130682. 0
  130683. };
  130684. static long _vq_quantlist__44c4_s_p4_0[] = {
  130685. 4,
  130686. 3,
  130687. 5,
  130688. 2,
  130689. 6,
  130690. 1,
  130691. 7,
  130692. 0,
  130693. 8,
  130694. };
  130695. static long _vq_lengthlist__44c4_s_p4_0[] = {
  130696. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  130697. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  130698. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  130699. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  130700. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130701. 0,
  130702. };
  130703. static float _vq_quantthresh__44c4_s_p4_0[] = {
  130704. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130705. };
  130706. static long _vq_quantmap__44c4_s_p4_0[] = {
  130707. 7, 5, 3, 1, 0, 2, 4, 6,
  130708. 8,
  130709. };
  130710. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  130711. _vq_quantthresh__44c4_s_p4_0,
  130712. _vq_quantmap__44c4_s_p4_0,
  130713. 9,
  130714. 9
  130715. };
  130716. static static_codebook _44c4_s_p4_0 = {
  130717. 2, 81,
  130718. _vq_lengthlist__44c4_s_p4_0,
  130719. 1, -531628032, 1611661312, 4, 0,
  130720. _vq_quantlist__44c4_s_p4_0,
  130721. NULL,
  130722. &_vq_auxt__44c4_s_p4_0,
  130723. NULL,
  130724. 0
  130725. };
  130726. static long _vq_quantlist__44c4_s_p5_0[] = {
  130727. 4,
  130728. 3,
  130729. 5,
  130730. 2,
  130731. 6,
  130732. 1,
  130733. 7,
  130734. 0,
  130735. 8,
  130736. };
  130737. static long _vq_lengthlist__44c4_s_p5_0[] = {
  130738. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  130739. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  130740. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  130741. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  130742. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  130743. 10,
  130744. };
  130745. static float _vq_quantthresh__44c4_s_p5_0[] = {
  130746. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130747. };
  130748. static long _vq_quantmap__44c4_s_p5_0[] = {
  130749. 7, 5, 3, 1, 0, 2, 4, 6,
  130750. 8,
  130751. };
  130752. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  130753. _vq_quantthresh__44c4_s_p5_0,
  130754. _vq_quantmap__44c4_s_p5_0,
  130755. 9,
  130756. 9
  130757. };
  130758. static static_codebook _44c4_s_p5_0 = {
  130759. 2, 81,
  130760. _vq_lengthlist__44c4_s_p5_0,
  130761. 1, -531628032, 1611661312, 4, 0,
  130762. _vq_quantlist__44c4_s_p5_0,
  130763. NULL,
  130764. &_vq_auxt__44c4_s_p5_0,
  130765. NULL,
  130766. 0
  130767. };
  130768. static long _vq_quantlist__44c4_s_p6_0[] = {
  130769. 8,
  130770. 7,
  130771. 9,
  130772. 6,
  130773. 10,
  130774. 5,
  130775. 11,
  130776. 4,
  130777. 12,
  130778. 3,
  130779. 13,
  130780. 2,
  130781. 14,
  130782. 1,
  130783. 15,
  130784. 0,
  130785. 16,
  130786. };
  130787. static long _vq_lengthlist__44c4_s_p6_0[] = {
  130788. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  130789. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  130790. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  130791. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  130792. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  130793. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130794. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  130795. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  130796. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  130797. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  130798. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  130799. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  130800. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  130801. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  130802. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  130803. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  130804. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  130805. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  130806. 13,
  130807. };
  130808. static float _vq_quantthresh__44c4_s_p6_0[] = {
  130809. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130810. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130811. };
  130812. static long _vq_quantmap__44c4_s_p6_0[] = {
  130813. 15, 13, 11, 9, 7, 5, 3, 1,
  130814. 0, 2, 4, 6, 8, 10, 12, 14,
  130815. 16,
  130816. };
  130817. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  130818. _vq_quantthresh__44c4_s_p6_0,
  130819. _vq_quantmap__44c4_s_p6_0,
  130820. 17,
  130821. 17
  130822. };
  130823. static static_codebook _44c4_s_p6_0 = {
  130824. 2, 289,
  130825. _vq_lengthlist__44c4_s_p6_0,
  130826. 1, -529530880, 1611661312, 5, 0,
  130827. _vq_quantlist__44c4_s_p6_0,
  130828. NULL,
  130829. &_vq_auxt__44c4_s_p6_0,
  130830. NULL,
  130831. 0
  130832. };
  130833. static long _vq_quantlist__44c4_s_p7_0[] = {
  130834. 1,
  130835. 0,
  130836. 2,
  130837. };
  130838. static long _vq_lengthlist__44c4_s_p7_0[] = {
  130839. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  130840. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  130841. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  130842. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  130843. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  130844. 10,
  130845. };
  130846. static float _vq_quantthresh__44c4_s_p7_0[] = {
  130847. -5.5, 5.5,
  130848. };
  130849. static long _vq_quantmap__44c4_s_p7_0[] = {
  130850. 1, 0, 2,
  130851. };
  130852. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  130853. _vq_quantthresh__44c4_s_p7_0,
  130854. _vq_quantmap__44c4_s_p7_0,
  130855. 3,
  130856. 3
  130857. };
  130858. static static_codebook _44c4_s_p7_0 = {
  130859. 4, 81,
  130860. _vq_lengthlist__44c4_s_p7_0,
  130861. 1, -529137664, 1618345984, 2, 0,
  130862. _vq_quantlist__44c4_s_p7_0,
  130863. NULL,
  130864. &_vq_auxt__44c4_s_p7_0,
  130865. NULL,
  130866. 0
  130867. };
  130868. static long _vq_quantlist__44c4_s_p7_1[] = {
  130869. 5,
  130870. 4,
  130871. 6,
  130872. 3,
  130873. 7,
  130874. 2,
  130875. 8,
  130876. 1,
  130877. 9,
  130878. 0,
  130879. 10,
  130880. };
  130881. static long _vq_lengthlist__44c4_s_p7_1[] = {
  130882. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  130883. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  130884. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  130885. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  130886. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  130887. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  130888. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  130889. 10,10,10, 8, 8, 8, 8, 9, 9,
  130890. };
  130891. static float _vq_quantthresh__44c4_s_p7_1[] = {
  130892. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130893. 3.5, 4.5,
  130894. };
  130895. static long _vq_quantmap__44c4_s_p7_1[] = {
  130896. 9, 7, 5, 3, 1, 0, 2, 4,
  130897. 6, 8, 10,
  130898. };
  130899. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  130900. _vq_quantthresh__44c4_s_p7_1,
  130901. _vq_quantmap__44c4_s_p7_1,
  130902. 11,
  130903. 11
  130904. };
  130905. static static_codebook _44c4_s_p7_1 = {
  130906. 2, 121,
  130907. _vq_lengthlist__44c4_s_p7_1,
  130908. 1, -531365888, 1611661312, 4, 0,
  130909. _vq_quantlist__44c4_s_p7_1,
  130910. NULL,
  130911. &_vq_auxt__44c4_s_p7_1,
  130912. NULL,
  130913. 0
  130914. };
  130915. static long _vq_quantlist__44c4_s_p8_0[] = {
  130916. 6,
  130917. 5,
  130918. 7,
  130919. 4,
  130920. 8,
  130921. 3,
  130922. 9,
  130923. 2,
  130924. 10,
  130925. 1,
  130926. 11,
  130927. 0,
  130928. 12,
  130929. };
  130930. static long _vq_lengthlist__44c4_s_p8_0[] = {
  130931. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  130932. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  130933. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130934. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  130935. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  130936. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  130937. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  130938. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  130939. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  130940. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  130941. 0,13,12,12,12,12,12,13,13,
  130942. };
  130943. static float _vq_quantthresh__44c4_s_p8_0[] = {
  130944. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130945. 12.5, 17.5, 22.5, 27.5,
  130946. };
  130947. static long _vq_quantmap__44c4_s_p8_0[] = {
  130948. 11, 9, 7, 5, 3, 1, 0, 2,
  130949. 4, 6, 8, 10, 12,
  130950. };
  130951. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  130952. _vq_quantthresh__44c4_s_p8_0,
  130953. _vq_quantmap__44c4_s_p8_0,
  130954. 13,
  130955. 13
  130956. };
  130957. static static_codebook _44c4_s_p8_0 = {
  130958. 2, 169,
  130959. _vq_lengthlist__44c4_s_p8_0,
  130960. 1, -526516224, 1616117760, 4, 0,
  130961. _vq_quantlist__44c4_s_p8_0,
  130962. NULL,
  130963. &_vq_auxt__44c4_s_p8_0,
  130964. NULL,
  130965. 0
  130966. };
  130967. static long _vq_quantlist__44c4_s_p8_1[] = {
  130968. 2,
  130969. 1,
  130970. 3,
  130971. 0,
  130972. 4,
  130973. };
  130974. static long _vq_lengthlist__44c4_s_p8_1[] = {
  130975. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  130976. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  130977. };
  130978. static float _vq_quantthresh__44c4_s_p8_1[] = {
  130979. -1.5, -0.5, 0.5, 1.5,
  130980. };
  130981. static long _vq_quantmap__44c4_s_p8_1[] = {
  130982. 3, 1, 0, 2, 4,
  130983. };
  130984. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  130985. _vq_quantthresh__44c4_s_p8_1,
  130986. _vq_quantmap__44c4_s_p8_1,
  130987. 5,
  130988. 5
  130989. };
  130990. static static_codebook _44c4_s_p8_1 = {
  130991. 2, 25,
  130992. _vq_lengthlist__44c4_s_p8_1,
  130993. 1, -533725184, 1611661312, 3, 0,
  130994. _vq_quantlist__44c4_s_p8_1,
  130995. NULL,
  130996. &_vq_auxt__44c4_s_p8_1,
  130997. NULL,
  130998. 0
  130999. };
  131000. static long _vq_quantlist__44c4_s_p9_0[] = {
  131001. 6,
  131002. 5,
  131003. 7,
  131004. 4,
  131005. 8,
  131006. 3,
  131007. 9,
  131008. 2,
  131009. 10,
  131010. 1,
  131011. 11,
  131012. 0,
  131013. 12,
  131014. };
  131015. static long _vq_lengthlist__44c4_s_p9_0[] = {
  131016. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  131017. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  131018. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131019. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131020. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131021. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131022. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131023. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131024. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131025. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131026. 12,12,12,12,12,12,12,12,12,
  131027. };
  131028. static float _vq_quantthresh__44c4_s_p9_0[] = {
  131029. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  131030. 787.5, 1102.5, 1417.5, 1732.5,
  131031. };
  131032. static long _vq_quantmap__44c4_s_p9_0[] = {
  131033. 11, 9, 7, 5, 3, 1, 0, 2,
  131034. 4, 6, 8, 10, 12,
  131035. };
  131036. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  131037. _vq_quantthresh__44c4_s_p9_0,
  131038. _vq_quantmap__44c4_s_p9_0,
  131039. 13,
  131040. 13
  131041. };
  131042. static static_codebook _44c4_s_p9_0 = {
  131043. 2, 169,
  131044. _vq_lengthlist__44c4_s_p9_0,
  131045. 1, -513964032, 1628680192, 4, 0,
  131046. _vq_quantlist__44c4_s_p9_0,
  131047. NULL,
  131048. &_vq_auxt__44c4_s_p9_0,
  131049. NULL,
  131050. 0
  131051. };
  131052. static long _vq_quantlist__44c4_s_p9_1[] = {
  131053. 7,
  131054. 6,
  131055. 8,
  131056. 5,
  131057. 9,
  131058. 4,
  131059. 10,
  131060. 3,
  131061. 11,
  131062. 2,
  131063. 12,
  131064. 1,
  131065. 13,
  131066. 0,
  131067. 14,
  131068. };
  131069. static long _vq_lengthlist__44c4_s_p9_1[] = {
  131070. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  131071. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  131072. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  131073. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  131074. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  131075. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  131076. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  131077. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  131078. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  131079. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  131080. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  131081. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  131082. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  131083. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  131084. 15,
  131085. };
  131086. static float _vq_quantthresh__44c4_s_p9_1[] = {
  131087. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  131088. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  131089. };
  131090. static long _vq_quantmap__44c4_s_p9_1[] = {
  131091. 13, 11, 9, 7, 5, 3, 1, 0,
  131092. 2, 4, 6, 8, 10, 12, 14,
  131093. };
  131094. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  131095. _vq_quantthresh__44c4_s_p9_1,
  131096. _vq_quantmap__44c4_s_p9_1,
  131097. 15,
  131098. 15
  131099. };
  131100. static static_codebook _44c4_s_p9_1 = {
  131101. 2, 225,
  131102. _vq_lengthlist__44c4_s_p9_1,
  131103. 1, -520986624, 1620377600, 4, 0,
  131104. _vq_quantlist__44c4_s_p9_1,
  131105. NULL,
  131106. &_vq_auxt__44c4_s_p9_1,
  131107. NULL,
  131108. 0
  131109. };
  131110. static long _vq_quantlist__44c4_s_p9_2[] = {
  131111. 10,
  131112. 9,
  131113. 11,
  131114. 8,
  131115. 12,
  131116. 7,
  131117. 13,
  131118. 6,
  131119. 14,
  131120. 5,
  131121. 15,
  131122. 4,
  131123. 16,
  131124. 3,
  131125. 17,
  131126. 2,
  131127. 18,
  131128. 1,
  131129. 19,
  131130. 0,
  131131. 20,
  131132. };
  131133. static long _vq_lengthlist__44c4_s_p9_2[] = {
  131134. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  131135. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  131136. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  131137. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  131138. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  131139. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  131140. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  131141. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  131142. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  131143. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  131144. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  131145. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  131146. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  131147. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  131148. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  131149. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  131150. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  131151. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131152. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  131153. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  131154. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131155. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  131156. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  131157. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  131158. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  131159. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  131160. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  131161. 10,10,10,10,10,10,10,10,10,
  131162. };
  131163. static float _vq_quantthresh__44c4_s_p9_2[] = {
  131164. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131165. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131166. 6.5, 7.5, 8.5, 9.5,
  131167. };
  131168. static long _vq_quantmap__44c4_s_p9_2[] = {
  131169. 19, 17, 15, 13, 11, 9, 7, 5,
  131170. 3, 1, 0, 2, 4, 6, 8, 10,
  131171. 12, 14, 16, 18, 20,
  131172. };
  131173. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  131174. _vq_quantthresh__44c4_s_p9_2,
  131175. _vq_quantmap__44c4_s_p9_2,
  131176. 21,
  131177. 21
  131178. };
  131179. static static_codebook _44c4_s_p9_2 = {
  131180. 2, 441,
  131181. _vq_lengthlist__44c4_s_p9_2,
  131182. 1, -529268736, 1611661312, 5, 0,
  131183. _vq_quantlist__44c4_s_p9_2,
  131184. NULL,
  131185. &_vq_auxt__44c4_s_p9_2,
  131186. NULL,
  131187. 0
  131188. };
  131189. static long _huff_lengthlist__44c4_s_short[] = {
  131190. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  131191. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  131192. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  131193. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  131194. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  131195. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  131196. 7, 9,12,17,
  131197. };
  131198. static static_codebook _huff_book__44c4_s_short = {
  131199. 2, 100,
  131200. _huff_lengthlist__44c4_s_short,
  131201. 0, 0, 0, 0, 0,
  131202. NULL,
  131203. NULL,
  131204. NULL,
  131205. NULL,
  131206. 0
  131207. };
  131208. static long _huff_lengthlist__44c5_s_long[] = {
  131209. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  131210. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  131211. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  131212. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  131213. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  131214. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  131215. 9, 8, 7, 7,
  131216. };
  131217. static static_codebook _huff_book__44c5_s_long = {
  131218. 2, 100,
  131219. _huff_lengthlist__44c5_s_long,
  131220. 0, 0, 0, 0, 0,
  131221. NULL,
  131222. NULL,
  131223. NULL,
  131224. NULL,
  131225. 0
  131226. };
  131227. static long _vq_quantlist__44c5_s_p1_0[] = {
  131228. 1,
  131229. 0,
  131230. 2,
  131231. };
  131232. static long _vq_lengthlist__44c5_s_p1_0[] = {
  131233. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  131234. 0, 0, 4, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131238. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131239. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131243. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  131244. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131260. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131265. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131270. 0, 0, 0, 0, 0, 0, 0, 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, 4, 7, 7, 0, 0, 0, 0,
  131279. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  131284. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  131289. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  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, 0, 0, 0, 0, 0, 0, 0,
  131305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  131310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  131315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131318. 0, 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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131325. 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  131330. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  131335. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  131336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  131644. };
  131645. static float _vq_quantthresh__44c5_s_p1_0[] = {
  131646. -0.5, 0.5,
  131647. };
  131648. static long _vq_quantmap__44c5_s_p1_0[] = {
  131649. 1, 0, 2,
  131650. };
  131651. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  131652. _vq_quantthresh__44c5_s_p1_0,
  131653. _vq_quantmap__44c5_s_p1_0,
  131654. 3,
  131655. 3
  131656. };
  131657. static static_codebook _44c5_s_p1_0 = {
  131658. 8, 6561,
  131659. _vq_lengthlist__44c5_s_p1_0,
  131660. 1, -535822336, 1611661312, 2, 0,
  131661. _vq_quantlist__44c5_s_p1_0,
  131662. NULL,
  131663. &_vq_auxt__44c5_s_p1_0,
  131664. NULL,
  131665. 0
  131666. };
  131667. static long _vq_quantlist__44c5_s_p2_0[] = {
  131668. 2,
  131669. 1,
  131670. 3,
  131671. 0,
  131672. 4,
  131673. };
  131674. static long _vq_lengthlist__44c5_s_p2_0[] = {
  131675. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  131676. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  131677. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  131678. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  131679. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131684. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  131685. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  131686. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  131687. 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131692. 0, 0, 0, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  131693. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  131694. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 0, 0,
  131695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131700. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  131701. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  131702. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 0, 0, 0, 0, 0,
  131703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131714. 0,
  131715. };
  131716. static float _vq_quantthresh__44c5_s_p2_0[] = {
  131717. -1.5, -0.5, 0.5, 1.5,
  131718. };
  131719. static long _vq_quantmap__44c5_s_p2_0[] = {
  131720. 3, 1, 0, 2, 4,
  131721. };
  131722. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  131723. _vq_quantthresh__44c5_s_p2_0,
  131724. _vq_quantmap__44c5_s_p2_0,
  131725. 5,
  131726. 5
  131727. };
  131728. static static_codebook _44c5_s_p2_0 = {
  131729. 4, 625,
  131730. _vq_lengthlist__44c5_s_p2_0,
  131731. 1, -533725184, 1611661312, 3, 0,
  131732. _vq_quantlist__44c5_s_p2_0,
  131733. NULL,
  131734. &_vq_auxt__44c5_s_p2_0,
  131735. NULL,
  131736. 0
  131737. };
  131738. static long _vq_quantlist__44c5_s_p3_0[] = {
  131739. 2,
  131740. 1,
  131741. 3,
  131742. 0,
  131743. 4,
  131744. };
  131745. static long _vq_lengthlist__44c5_s_p3_0[] = {
  131746. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  131748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131749. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  131751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131752. 0, 0, 0, 0, 5, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  131753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131785. 0,
  131786. };
  131787. static float _vq_quantthresh__44c5_s_p3_0[] = {
  131788. -1.5, -0.5, 0.5, 1.5,
  131789. };
  131790. static long _vq_quantmap__44c5_s_p3_0[] = {
  131791. 3, 1, 0, 2, 4,
  131792. };
  131793. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  131794. _vq_quantthresh__44c5_s_p3_0,
  131795. _vq_quantmap__44c5_s_p3_0,
  131796. 5,
  131797. 5
  131798. };
  131799. static static_codebook _44c5_s_p3_0 = {
  131800. 4, 625,
  131801. _vq_lengthlist__44c5_s_p3_0,
  131802. 1, -533725184, 1611661312, 3, 0,
  131803. _vq_quantlist__44c5_s_p3_0,
  131804. NULL,
  131805. &_vq_auxt__44c5_s_p3_0,
  131806. NULL,
  131807. 0
  131808. };
  131809. static long _vq_quantlist__44c5_s_p4_0[] = {
  131810. 4,
  131811. 3,
  131812. 5,
  131813. 2,
  131814. 6,
  131815. 1,
  131816. 7,
  131817. 0,
  131818. 8,
  131819. };
  131820. static long _vq_lengthlist__44c5_s_p4_0[] = {
  131821. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  131822. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  131823. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  131824. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  131825. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131826. 0,
  131827. };
  131828. static float _vq_quantthresh__44c5_s_p4_0[] = {
  131829. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131830. };
  131831. static long _vq_quantmap__44c5_s_p4_0[] = {
  131832. 7, 5, 3, 1, 0, 2, 4, 6,
  131833. 8,
  131834. };
  131835. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  131836. _vq_quantthresh__44c5_s_p4_0,
  131837. _vq_quantmap__44c5_s_p4_0,
  131838. 9,
  131839. 9
  131840. };
  131841. static static_codebook _44c5_s_p4_0 = {
  131842. 2, 81,
  131843. _vq_lengthlist__44c5_s_p4_0,
  131844. 1, -531628032, 1611661312, 4, 0,
  131845. _vq_quantlist__44c5_s_p4_0,
  131846. NULL,
  131847. &_vq_auxt__44c5_s_p4_0,
  131848. NULL,
  131849. 0
  131850. };
  131851. static long _vq_quantlist__44c5_s_p5_0[] = {
  131852. 4,
  131853. 3,
  131854. 5,
  131855. 2,
  131856. 6,
  131857. 1,
  131858. 7,
  131859. 0,
  131860. 8,
  131861. };
  131862. static long _vq_lengthlist__44c5_s_p5_0[] = {
  131863. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  131864. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  131865. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  131866. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  131867. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  131868. 10,
  131869. };
  131870. static float _vq_quantthresh__44c5_s_p5_0[] = {
  131871. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131872. };
  131873. static long _vq_quantmap__44c5_s_p5_0[] = {
  131874. 7, 5, 3, 1, 0, 2, 4, 6,
  131875. 8,
  131876. };
  131877. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  131878. _vq_quantthresh__44c5_s_p5_0,
  131879. _vq_quantmap__44c5_s_p5_0,
  131880. 9,
  131881. 9
  131882. };
  131883. static static_codebook _44c5_s_p5_0 = {
  131884. 2, 81,
  131885. _vq_lengthlist__44c5_s_p5_0,
  131886. 1, -531628032, 1611661312, 4, 0,
  131887. _vq_quantlist__44c5_s_p5_0,
  131888. NULL,
  131889. &_vq_auxt__44c5_s_p5_0,
  131890. NULL,
  131891. 0
  131892. };
  131893. static long _vq_quantlist__44c5_s_p6_0[] = {
  131894. 8,
  131895. 7,
  131896. 9,
  131897. 6,
  131898. 10,
  131899. 5,
  131900. 11,
  131901. 4,
  131902. 12,
  131903. 3,
  131904. 13,
  131905. 2,
  131906. 14,
  131907. 1,
  131908. 15,
  131909. 0,
  131910. 16,
  131911. };
  131912. static long _vq_lengthlist__44c5_s_p6_0[] = {
  131913. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  131914. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  131915. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  131916. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  131917. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  131918. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  131919. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  131920. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  131921. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  131922. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  131923. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  131924. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  131925. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  131926. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  131927. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  131928. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  131929. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  131930. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  131931. 13,
  131932. };
  131933. static float _vq_quantthresh__44c5_s_p6_0[] = {
  131934. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131935. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131936. };
  131937. static long _vq_quantmap__44c5_s_p6_0[] = {
  131938. 15, 13, 11, 9, 7, 5, 3, 1,
  131939. 0, 2, 4, 6, 8, 10, 12, 14,
  131940. 16,
  131941. };
  131942. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  131943. _vq_quantthresh__44c5_s_p6_0,
  131944. _vq_quantmap__44c5_s_p6_0,
  131945. 17,
  131946. 17
  131947. };
  131948. static static_codebook _44c5_s_p6_0 = {
  131949. 2, 289,
  131950. _vq_lengthlist__44c5_s_p6_0,
  131951. 1, -529530880, 1611661312, 5, 0,
  131952. _vq_quantlist__44c5_s_p6_0,
  131953. NULL,
  131954. &_vq_auxt__44c5_s_p6_0,
  131955. NULL,
  131956. 0
  131957. };
  131958. static long _vq_quantlist__44c5_s_p7_0[] = {
  131959. 1,
  131960. 0,
  131961. 2,
  131962. };
  131963. static long _vq_lengthlist__44c5_s_p7_0[] = {
  131964. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  131965. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  131966. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  131967. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  131968. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  131969. 10,
  131970. };
  131971. static float _vq_quantthresh__44c5_s_p7_0[] = {
  131972. -5.5, 5.5,
  131973. };
  131974. static long _vq_quantmap__44c5_s_p7_0[] = {
  131975. 1, 0, 2,
  131976. };
  131977. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  131978. _vq_quantthresh__44c5_s_p7_0,
  131979. _vq_quantmap__44c5_s_p7_0,
  131980. 3,
  131981. 3
  131982. };
  131983. static static_codebook _44c5_s_p7_0 = {
  131984. 4, 81,
  131985. _vq_lengthlist__44c5_s_p7_0,
  131986. 1, -529137664, 1618345984, 2, 0,
  131987. _vq_quantlist__44c5_s_p7_0,
  131988. NULL,
  131989. &_vq_auxt__44c5_s_p7_0,
  131990. NULL,
  131991. 0
  131992. };
  131993. static long _vq_quantlist__44c5_s_p7_1[] = {
  131994. 5,
  131995. 4,
  131996. 6,
  131997. 3,
  131998. 7,
  131999. 2,
  132000. 8,
  132001. 1,
  132002. 9,
  132003. 0,
  132004. 10,
  132005. };
  132006. static long _vq_lengthlist__44c5_s_p7_1[] = {
  132007. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  132008. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  132009. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  132010. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  132011. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  132012. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  132013. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  132014. 10,10,10, 8, 8, 8, 8, 8, 8,
  132015. };
  132016. static float _vq_quantthresh__44c5_s_p7_1[] = {
  132017. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132018. 3.5, 4.5,
  132019. };
  132020. static long _vq_quantmap__44c5_s_p7_1[] = {
  132021. 9, 7, 5, 3, 1, 0, 2, 4,
  132022. 6, 8, 10,
  132023. };
  132024. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  132025. _vq_quantthresh__44c5_s_p7_1,
  132026. _vq_quantmap__44c5_s_p7_1,
  132027. 11,
  132028. 11
  132029. };
  132030. static static_codebook _44c5_s_p7_1 = {
  132031. 2, 121,
  132032. _vq_lengthlist__44c5_s_p7_1,
  132033. 1, -531365888, 1611661312, 4, 0,
  132034. _vq_quantlist__44c5_s_p7_1,
  132035. NULL,
  132036. &_vq_auxt__44c5_s_p7_1,
  132037. NULL,
  132038. 0
  132039. };
  132040. static long _vq_quantlist__44c5_s_p8_0[] = {
  132041. 6,
  132042. 5,
  132043. 7,
  132044. 4,
  132045. 8,
  132046. 3,
  132047. 9,
  132048. 2,
  132049. 10,
  132050. 1,
  132051. 11,
  132052. 0,
  132053. 12,
  132054. };
  132055. static long _vq_lengthlist__44c5_s_p8_0[] = {
  132056. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  132057. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  132058. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  132059. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  132060. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  132061. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  132062. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  132063. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  132064. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  132065. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  132066. 0,12,12,12,12,12,12,13,13,
  132067. };
  132068. static float _vq_quantthresh__44c5_s_p8_0[] = {
  132069. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132070. 12.5, 17.5, 22.5, 27.5,
  132071. };
  132072. static long _vq_quantmap__44c5_s_p8_0[] = {
  132073. 11, 9, 7, 5, 3, 1, 0, 2,
  132074. 4, 6, 8, 10, 12,
  132075. };
  132076. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  132077. _vq_quantthresh__44c5_s_p8_0,
  132078. _vq_quantmap__44c5_s_p8_0,
  132079. 13,
  132080. 13
  132081. };
  132082. static static_codebook _44c5_s_p8_0 = {
  132083. 2, 169,
  132084. _vq_lengthlist__44c5_s_p8_0,
  132085. 1, -526516224, 1616117760, 4, 0,
  132086. _vq_quantlist__44c5_s_p8_0,
  132087. NULL,
  132088. &_vq_auxt__44c5_s_p8_0,
  132089. NULL,
  132090. 0
  132091. };
  132092. static long _vq_quantlist__44c5_s_p8_1[] = {
  132093. 2,
  132094. 1,
  132095. 3,
  132096. 0,
  132097. 4,
  132098. };
  132099. static long _vq_lengthlist__44c5_s_p8_1[] = {
  132100. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  132101. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132102. };
  132103. static float _vq_quantthresh__44c5_s_p8_1[] = {
  132104. -1.5, -0.5, 0.5, 1.5,
  132105. };
  132106. static long _vq_quantmap__44c5_s_p8_1[] = {
  132107. 3, 1, 0, 2, 4,
  132108. };
  132109. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  132110. _vq_quantthresh__44c5_s_p8_1,
  132111. _vq_quantmap__44c5_s_p8_1,
  132112. 5,
  132113. 5
  132114. };
  132115. static static_codebook _44c5_s_p8_1 = {
  132116. 2, 25,
  132117. _vq_lengthlist__44c5_s_p8_1,
  132118. 1, -533725184, 1611661312, 3, 0,
  132119. _vq_quantlist__44c5_s_p8_1,
  132120. NULL,
  132121. &_vq_auxt__44c5_s_p8_1,
  132122. NULL,
  132123. 0
  132124. };
  132125. static long _vq_quantlist__44c5_s_p9_0[] = {
  132126. 7,
  132127. 6,
  132128. 8,
  132129. 5,
  132130. 9,
  132131. 4,
  132132. 10,
  132133. 3,
  132134. 11,
  132135. 2,
  132136. 12,
  132137. 1,
  132138. 13,
  132139. 0,
  132140. 14,
  132141. };
  132142. static long _vq_lengthlist__44c5_s_p9_0[] = {
  132143. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  132144. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  132145. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132146. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132147. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132148. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132149. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132150. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132151. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132152. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132153. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132154. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132155. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132156. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  132157. 12,
  132158. };
  132159. static float _vq_quantthresh__44c5_s_p9_0[] = {
  132160. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  132161. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  132162. };
  132163. static long _vq_quantmap__44c5_s_p9_0[] = {
  132164. 13, 11, 9, 7, 5, 3, 1, 0,
  132165. 2, 4, 6, 8, 10, 12, 14,
  132166. };
  132167. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  132168. _vq_quantthresh__44c5_s_p9_0,
  132169. _vq_quantmap__44c5_s_p9_0,
  132170. 15,
  132171. 15
  132172. };
  132173. static static_codebook _44c5_s_p9_0 = {
  132174. 2, 225,
  132175. _vq_lengthlist__44c5_s_p9_0,
  132176. 1, -512522752, 1628852224, 4, 0,
  132177. _vq_quantlist__44c5_s_p9_0,
  132178. NULL,
  132179. &_vq_auxt__44c5_s_p9_0,
  132180. NULL,
  132181. 0
  132182. };
  132183. static long _vq_quantlist__44c5_s_p9_1[] = {
  132184. 8,
  132185. 7,
  132186. 9,
  132187. 6,
  132188. 10,
  132189. 5,
  132190. 11,
  132191. 4,
  132192. 12,
  132193. 3,
  132194. 13,
  132195. 2,
  132196. 14,
  132197. 1,
  132198. 15,
  132199. 0,
  132200. 16,
  132201. };
  132202. static long _vq_lengthlist__44c5_s_p9_1[] = {
  132203. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  132204. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  132205. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  132206. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  132207. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  132208. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  132209. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  132210. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  132211. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  132212. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  132213. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  132214. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  132215. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  132216. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  132217. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  132218. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  132219. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  132220. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  132221. 15,
  132222. };
  132223. static float _vq_quantthresh__44c5_s_p9_1[] = {
  132224. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  132225. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  132226. };
  132227. static long _vq_quantmap__44c5_s_p9_1[] = {
  132228. 15, 13, 11, 9, 7, 5, 3, 1,
  132229. 0, 2, 4, 6, 8, 10, 12, 14,
  132230. 16,
  132231. };
  132232. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  132233. _vq_quantthresh__44c5_s_p9_1,
  132234. _vq_quantmap__44c5_s_p9_1,
  132235. 17,
  132236. 17
  132237. };
  132238. static static_codebook _44c5_s_p9_1 = {
  132239. 2, 289,
  132240. _vq_lengthlist__44c5_s_p9_1,
  132241. 1, -520814592, 1620377600, 5, 0,
  132242. _vq_quantlist__44c5_s_p9_1,
  132243. NULL,
  132244. &_vq_auxt__44c5_s_p9_1,
  132245. NULL,
  132246. 0
  132247. };
  132248. static long _vq_quantlist__44c5_s_p9_2[] = {
  132249. 10,
  132250. 9,
  132251. 11,
  132252. 8,
  132253. 12,
  132254. 7,
  132255. 13,
  132256. 6,
  132257. 14,
  132258. 5,
  132259. 15,
  132260. 4,
  132261. 16,
  132262. 3,
  132263. 17,
  132264. 2,
  132265. 18,
  132266. 1,
  132267. 19,
  132268. 0,
  132269. 20,
  132270. };
  132271. static long _vq_lengthlist__44c5_s_p9_2[] = {
  132272. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  132273. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  132274. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  132275. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  132276. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  132277. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  132278. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  132279. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  132280. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  132281. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132282. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  132283. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  132284. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  132285. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  132286. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  132287. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  132288. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  132289. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  132290. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  132291. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  132292. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132293. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  132294. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  132295. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  132296. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  132297. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  132298. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  132299. 10,10,10,10,10,10,10,10,10,
  132300. };
  132301. static float _vq_quantthresh__44c5_s_p9_2[] = {
  132302. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132303. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132304. 6.5, 7.5, 8.5, 9.5,
  132305. };
  132306. static long _vq_quantmap__44c5_s_p9_2[] = {
  132307. 19, 17, 15, 13, 11, 9, 7, 5,
  132308. 3, 1, 0, 2, 4, 6, 8, 10,
  132309. 12, 14, 16, 18, 20,
  132310. };
  132311. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  132312. _vq_quantthresh__44c5_s_p9_2,
  132313. _vq_quantmap__44c5_s_p9_2,
  132314. 21,
  132315. 21
  132316. };
  132317. static static_codebook _44c5_s_p9_2 = {
  132318. 2, 441,
  132319. _vq_lengthlist__44c5_s_p9_2,
  132320. 1, -529268736, 1611661312, 5, 0,
  132321. _vq_quantlist__44c5_s_p9_2,
  132322. NULL,
  132323. &_vq_auxt__44c5_s_p9_2,
  132324. NULL,
  132325. 0
  132326. };
  132327. static long _huff_lengthlist__44c5_s_short[] = {
  132328. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  132329. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  132330. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  132331. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  132332. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  132333. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  132334. 6, 8,11,16,
  132335. };
  132336. static static_codebook _huff_book__44c5_s_short = {
  132337. 2, 100,
  132338. _huff_lengthlist__44c5_s_short,
  132339. 0, 0, 0, 0, 0,
  132340. NULL,
  132341. NULL,
  132342. NULL,
  132343. NULL,
  132344. 0
  132345. };
  132346. static long _huff_lengthlist__44c6_s_long[] = {
  132347. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  132348. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  132349. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  132350. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  132351. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  132352. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  132353. 11,10,10,12,
  132354. };
  132355. static static_codebook _huff_book__44c6_s_long = {
  132356. 2, 100,
  132357. _huff_lengthlist__44c6_s_long,
  132358. 0, 0, 0, 0, 0,
  132359. NULL,
  132360. NULL,
  132361. NULL,
  132362. NULL,
  132363. 0
  132364. };
  132365. static long _vq_quantlist__44c6_s_p1_0[] = {
  132366. 1,
  132367. 0,
  132368. 2,
  132369. };
  132370. static long _vq_lengthlist__44c6_s_p1_0[] = {
  132371. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  132372. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  132373. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  132374. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  132375. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  132376. 8,
  132377. };
  132378. static float _vq_quantthresh__44c6_s_p1_0[] = {
  132379. -0.5, 0.5,
  132380. };
  132381. static long _vq_quantmap__44c6_s_p1_0[] = {
  132382. 1, 0, 2,
  132383. };
  132384. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  132385. _vq_quantthresh__44c6_s_p1_0,
  132386. _vq_quantmap__44c6_s_p1_0,
  132387. 3,
  132388. 3
  132389. };
  132390. static static_codebook _44c6_s_p1_0 = {
  132391. 4, 81,
  132392. _vq_lengthlist__44c6_s_p1_0,
  132393. 1, -535822336, 1611661312, 2, 0,
  132394. _vq_quantlist__44c6_s_p1_0,
  132395. NULL,
  132396. &_vq_auxt__44c6_s_p1_0,
  132397. NULL,
  132398. 0
  132399. };
  132400. static long _vq_quantlist__44c6_s_p2_0[] = {
  132401. 2,
  132402. 1,
  132403. 3,
  132404. 0,
  132405. 4,
  132406. };
  132407. static long _vq_lengthlist__44c6_s_p2_0[] = {
  132408. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  132409. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  132410. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  132411. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  132412. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  132413. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  132414. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  132415. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  132416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132417. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  132418. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  132419. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  132420. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  132421. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  132422. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  132423. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  132424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132425. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  132426. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  132427. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  132428. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  132429. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  132430. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  132431. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132433. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  132434. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  132435. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  132436. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  132437. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  132438. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  132439. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  132444. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  132445. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  132446. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  132447. 13,
  132448. };
  132449. static float _vq_quantthresh__44c6_s_p2_0[] = {
  132450. -1.5, -0.5, 0.5, 1.5,
  132451. };
  132452. static long _vq_quantmap__44c6_s_p2_0[] = {
  132453. 3, 1, 0, 2, 4,
  132454. };
  132455. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  132456. _vq_quantthresh__44c6_s_p2_0,
  132457. _vq_quantmap__44c6_s_p2_0,
  132458. 5,
  132459. 5
  132460. };
  132461. static static_codebook _44c6_s_p2_0 = {
  132462. 4, 625,
  132463. _vq_lengthlist__44c6_s_p2_0,
  132464. 1, -533725184, 1611661312, 3, 0,
  132465. _vq_quantlist__44c6_s_p2_0,
  132466. NULL,
  132467. &_vq_auxt__44c6_s_p2_0,
  132468. NULL,
  132469. 0
  132470. };
  132471. static long _vq_quantlist__44c6_s_p3_0[] = {
  132472. 4,
  132473. 3,
  132474. 5,
  132475. 2,
  132476. 6,
  132477. 1,
  132478. 7,
  132479. 0,
  132480. 8,
  132481. };
  132482. static long _vq_lengthlist__44c6_s_p3_0[] = {
  132483. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132484. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  132485. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  132486. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  132487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132488. 0,
  132489. };
  132490. static float _vq_quantthresh__44c6_s_p3_0[] = {
  132491. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132492. };
  132493. static long _vq_quantmap__44c6_s_p3_0[] = {
  132494. 7, 5, 3, 1, 0, 2, 4, 6,
  132495. 8,
  132496. };
  132497. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  132498. _vq_quantthresh__44c6_s_p3_0,
  132499. _vq_quantmap__44c6_s_p3_0,
  132500. 9,
  132501. 9
  132502. };
  132503. static static_codebook _44c6_s_p3_0 = {
  132504. 2, 81,
  132505. _vq_lengthlist__44c6_s_p3_0,
  132506. 1, -531628032, 1611661312, 4, 0,
  132507. _vq_quantlist__44c6_s_p3_0,
  132508. NULL,
  132509. &_vq_auxt__44c6_s_p3_0,
  132510. NULL,
  132511. 0
  132512. };
  132513. static long _vq_quantlist__44c6_s_p4_0[] = {
  132514. 8,
  132515. 7,
  132516. 9,
  132517. 6,
  132518. 10,
  132519. 5,
  132520. 11,
  132521. 4,
  132522. 12,
  132523. 3,
  132524. 13,
  132525. 2,
  132526. 14,
  132527. 1,
  132528. 15,
  132529. 0,
  132530. 16,
  132531. };
  132532. static long _vq_lengthlist__44c6_s_p4_0[] = {
  132533. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  132534. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  132535. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  132536. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132537. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132538. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  132539. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  132540. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  132541. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  132542. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  132543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132551. 0,
  132552. };
  132553. static float _vq_quantthresh__44c6_s_p4_0[] = {
  132554. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132555. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132556. };
  132557. static long _vq_quantmap__44c6_s_p4_0[] = {
  132558. 15, 13, 11, 9, 7, 5, 3, 1,
  132559. 0, 2, 4, 6, 8, 10, 12, 14,
  132560. 16,
  132561. };
  132562. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  132563. _vq_quantthresh__44c6_s_p4_0,
  132564. _vq_quantmap__44c6_s_p4_0,
  132565. 17,
  132566. 17
  132567. };
  132568. static static_codebook _44c6_s_p4_0 = {
  132569. 2, 289,
  132570. _vq_lengthlist__44c6_s_p4_0,
  132571. 1, -529530880, 1611661312, 5, 0,
  132572. _vq_quantlist__44c6_s_p4_0,
  132573. NULL,
  132574. &_vq_auxt__44c6_s_p4_0,
  132575. NULL,
  132576. 0
  132577. };
  132578. static long _vq_quantlist__44c6_s_p5_0[] = {
  132579. 1,
  132580. 0,
  132581. 2,
  132582. };
  132583. static long _vq_lengthlist__44c6_s_p5_0[] = {
  132584. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  132585. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  132586. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  132587. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  132588. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  132589. 12,
  132590. };
  132591. static float _vq_quantthresh__44c6_s_p5_0[] = {
  132592. -5.5, 5.5,
  132593. };
  132594. static long _vq_quantmap__44c6_s_p5_0[] = {
  132595. 1, 0, 2,
  132596. };
  132597. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  132598. _vq_quantthresh__44c6_s_p5_0,
  132599. _vq_quantmap__44c6_s_p5_0,
  132600. 3,
  132601. 3
  132602. };
  132603. static static_codebook _44c6_s_p5_0 = {
  132604. 4, 81,
  132605. _vq_lengthlist__44c6_s_p5_0,
  132606. 1, -529137664, 1618345984, 2, 0,
  132607. _vq_quantlist__44c6_s_p5_0,
  132608. NULL,
  132609. &_vq_auxt__44c6_s_p5_0,
  132610. NULL,
  132611. 0
  132612. };
  132613. static long _vq_quantlist__44c6_s_p5_1[] = {
  132614. 5,
  132615. 4,
  132616. 6,
  132617. 3,
  132618. 7,
  132619. 2,
  132620. 8,
  132621. 1,
  132622. 9,
  132623. 0,
  132624. 10,
  132625. };
  132626. static long _vq_lengthlist__44c6_s_p5_1[] = {
  132627. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  132628. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  132629. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  132630. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  132631. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  132632. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  132633. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  132634. 11,10,10, 7, 7, 8, 8, 8, 8,
  132635. };
  132636. static float _vq_quantthresh__44c6_s_p5_1[] = {
  132637. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132638. 3.5, 4.5,
  132639. };
  132640. static long _vq_quantmap__44c6_s_p5_1[] = {
  132641. 9, 7, 5, 3, 1, 0, 2, 4,
  132642. 6, 8, 10,
  132643. };
  132644. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  132645. _vq_quantthresh__44c6_s_p5_1,
  132646. _vq_quantmap__44c6_s_p5_1,
  132647. 11,
  132648. 11
  132649. };
  132650. static static_codebook _44c6_s_p5_1 = {
  132651. 2, 121,
  132652. _vq_lengthlist__44c6_s_p5_1,
  132653. 1, -531365888, 1611661312, 4, 0,
  132654. _vq_quantlist__44c6_s_p5_1,
  132655. NULL,
  132656. &_vq_auxt__44c6_s_p5_1,
  132657. NULL,
  132658. 0
  132659. };
  132660. static long _vq_quantlist__44c6_s_p6_0[] = {
  132661. 6,
  132662. 5,
  132663. 7,
  132664. 4,
  132665. 8,
  132666. 3,
  132667. 9,
  132668. 2,
  132669. 10,
  132670. 1,
  132671. 11,
  132672. 0,
  132673. 12,
  132674. };
  132675. static long _vq_lengthlist__44c6_s_p6_0[] = {
  132676. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  132677. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  132678. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  132679. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132680. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  132681. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  132682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132686. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132687. };
  132688. static float _vq_quantthresh__44c6_s_p6_0[] = {
  132689. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132690. 12.5, 17.5, 22.5, 27.5,
  132691. };
  132692. static long _vq_quantmap__44c6_s_p6_0[] = {
  132693. 11, 9, 7, 5, 3, 1, 0, 2,
  132694. 4, 6, 8, 10, 12,
  132695. };
  132696. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  132697. _vq_quantthresh__44c6_s_p6_0,
  132698. _vq_quantmap__44c6_s_p6_0,
  132699. 13,
  132700. 13
  132701. };
  132702. static static_codebook _44c6_s_p6_0 = {
  132703. 2, 169,
  132704. _vq_lengthlist__44c6_s_p6_0,
  132705. 1, -526516224, 1616117760, 4, 0,
  132706. _vq_quantlist__44c6_s_p6_0,
  132707. NULL,
  132708. &_vq_auxt__44c6_s_p6_0,
  132709. NULL,
  132710. 0
  132711. };
  132712. static long _vq_quantlist__44c6_s_p6_1[] = {
  132713. 2,
  132714. 1,
  132715. 3,
  132716. 0,
  132717. 4,
  132718. };
  132719. static long _vq_lengthlist__44c6_s_p6_1[] = {
  132720. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  132721. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132722. };
  132723. static float _vq_quantthresh__44c6_s_p6_1[] = {
  132724. -1.5, -0.5, 0.5, 1.5,
  132725. };
  132726. static long _vq_quantmap__44c6_s_p6_1[] = {
  132727. 3, 1, 0, 2, 4,
  132728. };
  132729. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  132730. _vq_quantthresh__44c6_s_p6_1,
  132731. _vq_quantmap__44c6_s_p6_1,
  132732. 5,
  132733. 5
  132734. };
  132735. static static_codebook _44c6_s_p6_1 = {
  132736. 2, 25,
  132737. _vq_lengthlist__44c6_s_p6_1,
  132738. 1, -533725184, 1611661312, 3, 0,
  132739. _vq_quantlist__44c6_s_p6_1,
  132740. NULL,
  132741. &_vq_auxt__44c6_s_p6_1,
  132742. NULL,
  132743. 0
  132744. };
  132745. static long _vq_quantlist__44c6_s_p7_0[] = {
  132746. 6,
  132747. 5,
  132748. 7,
  132749. 4,
  132750. 8,
  132751. 3,
  132752. 9,
  132753. 2,
  132754. 10,
  132755. 1,
  132756. 11,
  132757. 0,
  132758. 12,
  132759. };
  132760. static long _vq_lengthlist__44c6_s_p7_0[] = {
  132761. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  132762. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  132763. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  132764. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132765. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  132766. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  132767. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  132768. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  132769. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  132770. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  132771. 20,13,13,13,13,13,13,14,14,
  132772. };
  132773. static float _vq_quantthresh__44c6_s_p7_0[] = {
  132774. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  132775. 27.5, 38.5, 49.5, 60.5,
  132776. };
  132777. static long _vq_quantmap__44c6_s_p7_0[] = {
  132778. 11, 9, 7, 5, 3, 1, 0, 2,
  132779. 4, 6, 8, 10, 12,
  132780. };
  132781. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  132782. _vq_quantthresh__44c6_s_p7_0,
  132783. _vq_quantmap__44c6_s_p7_0,
  132784. 13,
  132785. 13
  132786. };
  132787. static static_codebook _44c6_s_p7_0 = {
  132788. 2, 169,
  132789. _vq_lengthlist__44c6_s_p7_0,
  132790. 1, -523206656, 1618345984, 4, 0,
  132791. _vq_quantlist__44c6_s_p7_0,
  132792. NULL,
  132793. &_vq_auxt__44c6_s_p7_0,
  132794. NULL,
  132795. 0
  132796. };
  132797. static long _vq_quantlist__44c6_s_p7_1[] = {
  132798. 5,
  132799. 4,
  132800. 6,
  132801. 3,
  132802. 7,
  132803. 2,
  132804. 8,
  132805. 1,
  132806. 9,
  132807. 0,
  132808. 10,
  132809. };
  132810. static long _vq_lengthlist__44c6_s_p7_1[] = {
  132811. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  132812. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  132813. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  132814. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  132815. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  132816. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  132817. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  132818. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  132819. };
  132820. static float _vq_quantthresh__44c6_s_p7_1[] = {
  132821. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132822. 3.5, 4.5,
  132823. };
  132824. static long _vq_quantmap__44c6_s_p7_1[] = {
  132825. 9, 7, 5, 3, 1, 0, 2, 4,
  132826. 6, 8, 10,
  132827. };
  132828. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  132829. _vq_quantthresh__44c6_s_p7_1,
  132830. _vq_quantmap__44c6_s_p7_1,
  132831. 11,
  132832. 11
  132833. };
  132834. static static_codebook _44c6_s_p7_1 = {
  132835. 2, 121,
  132836. _vq_lengthlist__44c6_s_p7_1,
  132837. 1, -531365888, 1611661312, 4, 0,
  132838. _vq_quantlist__44c6_s_p7_1,
  132839. NULL,
  132840. &_vq_auxt__44c6_s_p7_1,
  132841. NULL,
  132842. 0
  132843. };
  132844. static long _vq_quantlist__44c6_s_p8_0[] = {
  132845. 7,
  132846. 6,
  132847. 8,
  132848. 5,
  132849. 9,
  132850. 4,
  132851. 10,
  132852. 3,
  132853. 11,
  132854. 2,
  132855. 12,
  132856. 1,
  132857. 13,
  132858. 0,
  132859. 14,
  132860. };
  132861. static long _vq_lengthlist__44c6_s_p8_0[] = {
  132862. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  132863. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  132864. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  132865. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  132866. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  132867. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  132868. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  132869. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  132870. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  132871. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  132872. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  132873. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  132874. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  132875. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  132876. 14,
  132877. };
  132878. static float _vq_quantthresh__44c6_s_p8_0[] = {
  132879. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  132880. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  132881. };
  132882. static long _vq_quantmap__44c6_s_p8_0[] = {
  132883. 13, 11, 9, 7, 5, 3, 1, 0,
  132884. 2, 4, 6, 8, 10, 12, 14,
  132885. };
  132886. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  132887. _vq_quantthresh__44c6_s_p8_0,
  132888. _vq_quantmap__44c6_s_p8_0,
  132889. 15,
  132890. 15
  132891. };
  132892. static static_codebook _44c6_s_p8_0 = {
  132893. 2, 225,
  132894. _vq_lengthlist__44c6_s_p8_0,
  132895. 1, -520986624, 1620377600, 4, 0,
  132896. _vq_quantlist__44c6_s_p8_0,
  132897. NULL,
  132898. &_vq_auxt__44c6_s_p8_0,
  132899. NULL,
  132900. 0
  132901. };
  132902. static long _vq_quantlist__44c6_s_p8_1[] = {
  132903. 10,
  132904. 9,
  132905. 11,
  132906. 8,
  132907. 12,
  132908. 7,
  132909. 13,
  132910. 6,
  132911. 14,
  132912. 5,
  132913. 15,
  132914. 4,
  132915. 16,
  132916. 3,
  132917. 17,
  132918. 2,
  132919. 18,
  132920. 1,
  132921. 19,
  132922. 0,
  132923. 20,
  132924. };
  132925. static long _vq_lengthlist__44c6_s_p8_1[] = {
  132926. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  132927. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  132928. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  132929. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  132930. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132931. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  132932. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  132933. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  132934. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132935. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132936. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  132937. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  132938. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  132939. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  132940. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  132941. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  132942. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  132943. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  132944. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  132945. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  132946. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  132947. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  132948. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  132949. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  132950. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  132951. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  132952. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  132953. 10,10,10,10,10,10,10,10,10,
  132954. };
  132955. static float _vq_quantthresh__44c6_s_p8_1[] = {
  132956. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132957. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132958. 6.5, 7.5, 8.5, 9.5,
  132959. };
  132960. static long _vq_quantmap__44c6_s_p8_1[] = {
  132961. 19, 17, 15, 13, 11, 9, 7, 5,
  132962. 3, 1, 0, 2, 4, 6, 8, 10,
  132963. 12, 14, 16, 18, 20,
  132964. };
  132965. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  132966. _vq_quantthresh__44c6_s_p8_1,
  132967. _vq_quantmap__44c6_s_p8_1,
  132968. 21,
  132969. 21
  132970. };
  132971. static static_codebook _44c6_s_p8_1 = {
  132972. 2, 441,
  132973. _vq_lengthlist__44c6_s_p8_1,
  132974. 1, -529268736, 1611661312, 5, 0,
  132975. _vq_quantlist__44c6_s_p8_1,
  132976. NULL,
  132977. &_vq_auxt__44c6_s_p8_1,
  132978. NULL,
  132979. 0
  132980. };
  132981. static long _vq_quantlist__44c6_s_p9_0[] = {
  132982. 6,
  132983. 5,
  132984. 7,
  132985. 4,
  132986. 8,
  132987. 3,
  132988. 9,
  132989. 2,
  132990. 10,
  132991. 1,
  132992. 11,
  132993. 0,
  132994. 12,
  132995. };
  132996. static long _vq_lengthlist__44c6_s_p9_0[] = {
  132997. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  132998. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  132999. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133000. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  133001. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133002. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133003. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133004. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133005. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133006. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133007. 10,10,10,10,10,10,10,10,10,
  133008. };
  133009. static float _vq_quantthresh__44c6_s_p9_0[] = {
  133010. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  133011. 1592.5, 2229.5, 2866.5, 3503.5,
  133012. };
  133013. static long _vq_quantmap__44c6_s_p9_0[] = {
  133014. 11, 9, 7, 5, 3, 1, 0, 2,
  133015. 4, 6, 8, 10, 12,
  133016. };
  133017. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  133018. _vq_quantthresh__44c6_s_p9_0,
  133019. _vq_quantmap__44c6_s_p9_0,
  133020. 13,
  133021. 13
  133022. };
  133023. static static_codebook _44c6_s_p9_0 = {
  133024. 2, 169,
  133025. _vq_lengthlist__44c6_s_p9_0,
  133026. 1, -511845376, 1630791680, 4, 0,
  133027. _vq_quantlist__44c6_s_p9_0,
  133028. NULL,
  133029. &_vq_auxt__44c6_s_p9_0,
  133030. NULL,
  133031. 0
  133032. };
  133033. static long _vq_quantlist__44c6_s_p9_1[] = {
  133034. 6,
  133035. 5,
  133036. 7,
  133037. 4,
  133038. 8,
  133039. 3,
  133040. 9,
  133041. 2,
  133042. 10,
  133043. 1,
  133044. 11,
  133045. 0,
  133046. 12,
  133047. };
  133048. static long _vq_lengthlist__44c6_s_p9_1[] = {
  133049. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  133050. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  133051. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  133052. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  133053. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  133054. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  133055. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  133056. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  133057. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  133058. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  133059. 15,12,10,11,11,13,11,12,13,
  133060. };
  133061. static float _vq_quantthresh__44c6_s_p9_1[] = {
  133062. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  133063. 122.5, 171.5, 220.5, 269.5,
  133064. };
  133065. static long _vq_quantmap__44c6_s_p9_1[] = {
  133066. 11, 9, 7, 5, 3, 1, 0, 2,
  133067. 4, 6, 8, 10, 12,
  133068. };
  133069. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  133070. _vq_quantthresh__44c6_s_p9_1,
  133071. _vq_quantmap__44c6_s_p9_1,
  133072. 13,
  133073. 13
  133074. };
  133075. static static_codebook _44c6_s_p9_1 = {
  133076. 2, 169,
  133077. _vq_lengthlist__44c6_s_p9_1,
  133078. 1, -518889472, 1622704128, 4, 0,
  133079. _vq_quantlist__44c6_s_p9_1,
  133080. NULL,
  133081. &_vq_auxt__44c6_s_p9_1,
  133082. NULL,
  133083. 0
  133084. };
  133085. static long _vq_quantlist__44c6_s_p9_2[] = {
  133086. 24,
  133087. 23,
  133088. 25,
  133089. 22,
  133090. 26,
  133091. 21,
  133092. 27,
  133093. 20,
  133094. 28,
  133095. 19,
  133096. 29,
  133097. 18,
  133098. 30,
  133099. 17,
  133100. 31,
  133101. 16,
  133102. 32,
  133103. 15,
  133104. 33,
  133105. 14,
  133106. 34,
  133107. 13,
  133108. 35,
  133109. 12,
  133110. 36,
  133111. 11,
  133112. 37,
  133113. 10,
  133114. 38,
  133115. 9,
  133116. 39,
  133117. 8,
  133118. 40,
  133119. 7,
  133120. 41,
  133121. 6,
  133122. 42,
  133123. 5,
  133124. 43,
  133125. 4,
  133126. 44,
  133127. 3,
  133128. 45,
  133129. 2,
  133130. 46,
  133131. 1,
  133132. 47,
  133133. 0,
  133134. 48,
  133135. };
  133136. static long _vq_lengthlist__44c6_s_p9_2[] = {
  133137. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  133138. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133139. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133140. 7,
  133141. };
  133142. static float _vq_quantthresh__44c6_s_p9_2[] = {
  133143. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  133144. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133145. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133146. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133147. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133148. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133149. };
  133150. static long _vq_quantmap__44c6_s_p9_2[] = {
  133151. 47, 45, 43, 41, 39, 37, 35, 33,
  133152. 31, 29, 27, 25, 23, 21, 19, 17,
  133153. 15, 13, 11, 9, 7, 5, 3, 1,
  133154. 0, 2, 4, 6, 8, 10, 12, 14,
  133155. 16, 18, 20, 22, 24, 26, 28, 30,
  133156. 32, 34, 36, 38, 40, 42, 44, 46,
  133157. 48,
  133158. };
  133159. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  133160. _vq_quantthresh__44c6_s_p9_2,
  133161. _vq_quantmap__44c6_s_p9_2,
  133162. 49,
  133163. 49
  133164. };
  133165. static static_codebook _44c6_s_p9_2 = {
  133166. 1, 49,
  133167. _vq_lengthlist__44c6_s_p9_2,
  133168. 1, -526909440, 1611661312, 6, 0,
  133169. _vq_quantlist__44c6_s_p9_2,
  133170. NULL,
  133171. &_vq_auxt__44c6_s_p9_2,
  133172. NULL,
  133173. 0
  133174. };
  133175. static long _huff_lengthlist__44c6_s_short[] = {
  133176. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  133177. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  133178. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  133179. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  133180. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  133181. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  133182. 9,10,17,18,
  133183. };
  133184. static static_codebook _huff_book__44c6_s_short = {
  133185. 2, 100,
  133186. _huff_lengthlist__44c6_s_short,
  133187. 0, 0, 0, 0, 0,
  133188. NULL,
  133189. NULL,
  133190. NULL,
  133191. NULL,
  133192. 0
  133193. };
  133194. static long _huff_lengthlist__44c7_s_long[] = {
  133195. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  133196. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  133197. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  133198. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  133199. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  133200. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  133201. 11,10,10,12,
  133202. };
  133203. static static_codebook _huff_book__44c7_s_long = {
  133204. 2, 100,
  133205. _huff_lengthlist__44c7_s_long,
  133206. 0, 0, 0, 0, 0,
  133207. NULL,
  133208. NULL,
  133209. NULL,
  133210. NULL,
  133211. 0
  133212. };
  133213. static long _vq_quantlist__44c7_s_p1_0[] = {
  133214. 1,
  133215. 0,
  133216. 2,
  133217. };
  133218. static long _vq_lengthlist__44c7_s_p1_0[] = {
  133219. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  133220. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  133221. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  133222. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  133223. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  133224. 8,
  133225. };
  133226. static float _vq_quantthresh__44c7_s_p1_0[] = {
  133227. -0.5, 0.5,
  133228. };
  133229. static long _vq_quantmap__44c7_s_p1_0[] = {
  133230. 1, 0, 2,
  133231. };
  133232. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  133233. _vq_quantthresh__44c7_s_p1_0,
  133234. _vq_quantmap__44c7_s_p1_0,
  133235. 3,
  133236. 3
  133237. };
  133238. static static_codebook _44c7_s_p1_0 = {
  133239. 4, 81,
  133240. _vq_lengthlist__44c7_s_p1_0,
  133241. 1, -535822336, 1611661312, 2, 0,
  133242. _vq_quantlist__44c7_s_p1_0,
  133243. NULL,
  133244. &_vq_auxt__44c7_s_p1_0,
  133245. NULL,
  133246. 0
  133247. };
  133248. static long _vq_quantlist__44c7_s_p2_0[] = {
  133249. 2,
  133250. 1,
  133251. 3,
  133252. 0,
  133253. 4,
  133254. };
  133255. static long _vq_lengthlist__44c7_s_p2_0[] = {
  133256. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  133257. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  133258. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  133259. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  133260. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  133261. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  133262. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  133263. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  133264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133265. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  133266. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  133267. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  133268. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  133269. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  133270. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  133271. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  133272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133273. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  133274. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  133275. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  133276. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  133277. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  133278. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  133279. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133281. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  133282. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  133283. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  133284. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  133285. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  133286. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  133287. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  133292. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  133293. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  133294. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  133295. 13,
  133296. };
  133297. static float _vq_quantthresh__44c7_s_p2_0[] = {
  133298. -1.5, -0.5, 0.5, 1.5,
  133299. };
  133300. static long _vq_quantmap__44c7_s_p2_0[] = {
  133301. 3, 1, 0, 2, 4,
  133302. };
  133303. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  133304. _vq_quantthresh__44c7_s_p2_0,
  133305. _vq_quantmap__44c7_s_p2_0,
  133306. 5,
  133307. 5
  133308. };
  133309. static static_codebook _44c7_s_p2_0 = {
  133310. 4, 625,
  133311. _vq_lengthlist__44c7_s_p2_0,
  133312. 1, -533725184, 1611661312, 3, 0,
  133313. _vq_quantlist__44c7_s_p2_0,
  133314. NULL,
  133315. &_vq_auxt__44c7_s_p2_0,
  133316. NULL,
  133317. 0
  133318. };
  133319. static long _vq_quantlist__44c7_s_p3_0[] = {
  133320. 4,
  133321. 3,
  133322. 5,
  133323. 2,
  133324. 6,
  133325. 1,
  133326. 7,
  133327. 0,
  133328. 8,
  133329. };
  133330. static long _vq_lengthlist__44c7_s_p3_0[] = {
  133331. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  133332. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  133333. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  133334. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  133335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133336. 0,
  133337. };
  133338. static float _vq_quantthresh__44c7_s_p3_0[] = {
  133339. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133340. };
  133341. static long _vq_quantmap__44c7_s_p3_0[] = {
  133342. 7, 5, 3, 1, 0, 2, 4, 6,
  133343. 8,
  133344. };
  133345. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  133346. _vq_quantthresh__44c7_s_p3_0,
  133347. _vq_quantmap__44c7_s_p3_0,
  133348. 9,
  133349. 9
  133350. };
  133351. static static_codebook _44c7_s_p3_0 = {
  133352. 2, 81,
  133353. _vq_lengthlist__44c7_s_p3_0,
  133354. 1, -531628032, 1611661312, 4, 0,
  133355. _vq_quantlist__44c7_s_p3_0,
  133356. NULL,
  133357. &_vq_auxt__44c7_s_p3_0,
  133358. NULL,
  133359. 0
  133360. };
  133361. static long _vq_quantlist__44c7_s_p4_0[] = {
  133362. 8,
  133363. 7,
  133364. 9,
  133365. 6,
  133366. 10,
  133367. 5,
  133368. 11,
  133369. 4,
  133370. 12,
  133371. 3,
  133372. 13,
  133373. 2,
  133374. 14,
  133375. 1,
  133376. 15,
  133377. 0,
  133378. 16,
  133379. };
  133380. static long _vq_lengthlist__44c7_s_p4_0[] = {
  133381. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  133382. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  133383. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  133384. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  133385. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  133386. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  133387. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  133388. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  133389. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  133390. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  133391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133399. 0,
  133400. };
  133401. static float _vq_quantthresh__44c7_s_p4_0[] = {
  133402. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133403. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133404. };
  133405. static long _vq_quantmap__44c7_s_p4_0[] = {
  133406. 15, 13, 11, 9, 7, 5, 3, 1,
  133407. 0, 2, 4, 6, 8, 10, 12, 14,
  133408. 16,
  133409. };
  133410. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  133411. _vq_quantthresh__44c7_s_p4_0,
  133412. _vq_quantmap__44c7_s_p4_0,
  133413. 17,
  133414. 17
  133415. };
  133416. static static_codebook _44c7_s_p4_0 = {
  133417. 2, 289,
  133418. _vq_lengthlist__44c7_s_p4_0,
  133419. 1, -529530880, 1611661312, 5, 0,
  133420. _vq_quantlist__44c7_s_p4_0,
  133421. NULL,
  133422. &_vq_auxt__44c7_s_p4_0,
  133423. NULL,
  133424. 0
  133425. };
  133426. static long _vq_quantlist__44c7_s_p5_0[] = {
  133427. 1,
  133428. 0,
  133429. 2,
  133430. };
  133431. static long _vq_lengthlist__44c7_s_p5_0[] = {
  133432. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  133433. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  133434. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  133435. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  133436. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  133437. 12,
  133438. };
  133439. static float _vq_quantthresh__44c7_s_p5_0[] = {
  133440. -5.5, 5.5,
  133441. };
  133442. static long _vq_quantmap__44c7_s_p5_0[] = {
  133443. 1, 0, 2,
  133444. };
  133445. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  133446. _vq_quantthresh__44c7_s_p5_0,
  133447. _vq_quantmap__44c7_s_p5_0,
  133448. 3,
  133449. 3
  133450. };
  133451. static static_codebook _44c7_s_p5_0 = {
  133452. 4, 81,
  133453. _vq_lengthlist__44c7_s_p5_0,
  133454. 1, -529137664, 1618345984, 2, 0,
  133455. _vq_quantlist__44c7_s_p5_0,
  133456. NULL,
  133457. &_vq_auxt__44c7_s_p5_0,
  133458. NULL,
  133459. 0
  133460. };
  133461. static long _vq_quantlist__44c7_s_p5_1[] = {
  133462. 5,
  133463. 4,
  133464. 6,
  133465. 3,
  133466. 7,
  133467. 2,
  133468. 8,
  133469. 1,
  133470. 9,
  133471. 0,
  133472. 10,
  133473. };
  133474. static long _vq_lengthlist__44c7_s_p5_1[] = {
  133475. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  133476. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  133477. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  133478. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  133479. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  133480. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  133481. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  133482. 11,11,11, 7, 7, 8, 8, 8, 8,
  133483. };
  133484. static float _vq_quantthresh__44c7_s_p5_1[] = {
  133485. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133486. 3.5, 4.5,
  133487. };
  133488. static long _vq_quantmap__44c7_s_p5_1[] = {
  133489. 9, 7, 5, 3, 1, 0, 2, 4,
  133490. 6, 8, 10,
  133491. };
  133492. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  133493. _vq_quantthresh__44c7_s_p5_1,
  133494. _vq_quantmap__44c7_s_p5_1,
  133495. 11,
  133496. 11
  133497. };
  133498. static static_codebook _44c7_s_p5_1 = {
  133499. 2, 121,
  133500. _vq_lengthlist__44c7_s_p5_1,
  133501. 1, -531365888, 1611661312, 4, 0,
  133502. _vq_quantlist__44c7_s_p5_1,
  133503. NULL,
  133504. &_vq_auxt__44c7_s_p5_1,
  133505. NULL,
  133506. 0
  133507. };
  133508. static long _vq_quantlist__44c7_s_p6_0[] = {
  133509. 6,
  133510. 5,
  133511. 7,
  133512. 4,
  133513. 8,
  133514. 3,
  133515. 9,
  133516. 2,
  133517. 10,
  133518. 1,
  133519. 11,
  133520. 0,
  133521. 12,
  133522. };
  133523. static long _vq_lengthlist__44c7_s_p6_0[] = {
  133524. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  133525. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  133526. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  133527. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  133528. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  133529. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  133530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133534. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133535. };
  133536. static float _vq_quantthresh__44c7_s_p6_0[] = {
  133537. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133538. 12.5, 17.5, 22.5, 27.5,
  133539. };
  133540. static long _vq_quantmap__44c7_s_p6_0[] = {
  133541. 11, 9, 7, 5, 3, 1, 0, 2,
  133542. 4, 6, 8, 10, 12,
  133543. };
  133544. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  133545. _vq_quantthresh__44c7_s_p6_0,
  133546. _vq_quantmap__44c7_s_p6_0,
  133547. 13,
  133548. 13
  133549. };
  133550. static static_codebook _44c7_s_p6_0 = {
  133551. 2, 169,
  133552. _vq_lengthlist__44c7_s_p6_0,
  133553. 1, -526516224, 1616117760, 4, 0,
  133554. _vq_quantlist__44c7_s_p6_0,
  133555. NULL,
  133556. &_vq_auxt__44c7_s_p6_0,
  133557. NULL,
  133558. 0
  133559. };
  133560. static long _vq_quantlist__44c7_s_p6_1[] = {
  133561. 2,
  133562. 1,
  133563. 3,
  133564. 0,
  133565. 4,
  133566. };
  133567. static long _vq_lengthlist__44c7_s_p6_1[] = {
  133568. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  133569. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  133570. };
  133571. static float _vq_quantthresh__44c7_s_p6_1[] = {
  133572. -1.5, -0.5, 0.5, 1.5,
  133573. };
  133574. static long _vq_quantmap__44c7_s_p6_1[] = {
  133575. 3, 1, 0, 2, 4,
  133576. };
  133577. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  133578. _vq_quantthresh__44c7_s_p6_1,
  133579. _vq_quantmap__44c7_s_p6_1,
  133580. 5,
  133581. 5
  133582. };
  133583. static static_codebook _44c7_s_p6_1 = {
  133584. 2, 25,
  133585. _vq_lengthlist__44c7_s_p6_1,
  133586. 1, -533725184, 1611661312, 3, 0,
  133587. _vq_quantlist__44c7_s_p6_1,
  133588. NULL,
  133589. &_vq_auxt__44c7_s_p6_1,
  133590. NULL,
  133591. 0
  133592. };
  133593. static long _vq_quantlist__44c7_s_p7_0[] = {
  133594. 6,
  133595. 5,
  133596. 7,
  133597. 4,
  133598. 8,
  133599. 3,
  133600. 9,
  133601. 2,
  133602. 10,
  133603. 1,
  133604. 11,
  133605. 0,
  133606. 12,
  133607. };
  133608. static long _vq_lengthlist__44c7_s_p7_0[] = {
  133609. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  133610. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  133611. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  133612. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  133613. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  133614. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  133615. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  133616. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  133617. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  133618. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  133619. 19,13,13,13,13,14,14,15,15,
  133620. };
  133621. static float _vq_quantthresh__44c7_s_p7_0[] = {
  133622. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  133623. 27.5, 38.5, 49.5, 60.5,
  133624. };
  133625. static long _vq_quantmap__44c7_s_p7_0[] = {
  133626. 11, 9, 7, 5, 3, 1, 0, 2,
  133627. 4, 6, 8, 10, 12,
  133628. };
  133629. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  133630. _vq_quantthresh__44c7_s_p7_0,
  133631. _vq_quantmap__44c7_s_p7_0,
  133632. 13,
  133633. 13
  133634. };
  133635. static static_codebook _44c7_s_p7_0 = {
  133636. 2, 169,
  133637. _vq_lengthlist__44c7_s_p7_0,
  133638. 1, -523206656, 1618345984, 4, 0,
  133639. _vq_quantlist__44c7_s_p7_0,
  133640. NULL,
  133641. &_vq_auxt__44c7_s_p7_0,
  133642. NULL,
  133643. 0
  133644. };
  133645. static long _vq_quantlist__44c7_s_p7_1[] = {
  133646. 5,
  133647. 4,
  133648. 6,
  133649. 3,
  133650. 7,
  133651. 2,
  133652. 8,
  133653. 1,
  133654. 9,
  133655. 0,
  133656. 10,
  133657. };
  133658. static long _vq_lengthlist__44c7_s_p7_1[] = {
  133659. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  133660. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  133661. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  133662. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133663. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  133664. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  133665. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  133666. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133667. };
  133668. static float _vq_quantthresh__44c7_s_p7_1[] = {
  133669. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133670. 3.5, 4.5,
  133671. };
  133672. static long _vq_quantmap__44c7_s_p7_1[] = {
  133673. 9, 7, 5, 3, 1, 0, 2, 4,
  133674. 6, 8, 10,
  133675. };
  133676. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  133677. _vq_quantthresh__44c7_s_p7_1,
  133678. _vq_quantmap__44c7_s_p7_1,
  133679. 11,
  133680. 11
  133681. };
  133682. static static_codebook _44c7_s_p7_1 = {
  133683. 2, 121,
  133684. _vq_lengthlist__44c7_s_p7_1,
  133685. 1, -531365888, 1611661312, 4, 0,
  133686. _vq_quantlist__44c7_s_p7_1,
  133687. NULL,
  133688. &_vq_auxt__44c7_s_p7_1,
  133689. NULL,
  133690. 0
  133691. };
  133692. static long _vq_quantlist__44c7_s_p8_0[] = {
  133693. 7,
  133694. 6,
  133695. 8,
  133696. 5,
  133697. 9,
  133698. 4,
  133699. 10,
  133700. 3,
  133701. 11,
  133702. 2,
  133703. 12,
  133704. 1,
  133705. 13,
  133706. 0,
  133707. 14,
  133708. };
  133709. static long _vq_lengthlist__44c7_s_p8_0[] = {
  133710. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  133711. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  133712. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  133713. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  133714. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  133715. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  133716. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  133717. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  133718. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  133719. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  133720. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  133721. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  133722. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  133723. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  133724. 14,
  133725. };
  133726. static float _vq_quantthresh__44c7_s_p8_0[] = {
  133727. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133728. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133729. };
  133730. static long _vq_quantmap__44c7_s_p8_0[] = {
  133731. 13, 11, 9, 7, 5, 3, 1, 0,
  133732. 2, 4, 6, 8, 10, 12, 14,
  133733. };
  133734. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  133735. _vq_quantthresh__44c7_s_p8_0,
  133736. _vq_quantmap__44c7_s_p8_0,
  133737. 15,
  133738. 15
  133739. };
  133740. static static_codebook _44c7_s_p8_0 = {
  133741. 2, 225,
  133742. _vq_lengthlist__44c7_s_p8_0,
  133743. 1, -520986624, 1620377600, 4, 0,
  133744. _vq_quantlist__44c7_s_p8_0,
  133745. NULL,
  133746. &_vq_auxt__44c7_s_p8_0,
  133747. NULL,
  133748. 0
  133749. };
  133750. static long _vq_quantlist__44c7_s_p8_1[] = {
  133751. 10,
  133752. 9,
  133753. 11,
  133754. 8,
  133755. 12,
  133756. 7,
  133757. 13,
  133758. 6,
  133759. 14,
  133760. 5,
  133761. 15,
  133762. 4,
  133763. 16,
  133764. 3,
  133765. 17,
  133766. 2,
  133767. 18,
  133768. 1,
  133769. 19,
  133770. 0,
  133771. 20,
  133772. };
  133773. static long _vq_lengthlist__44c7_s_p8_1[] = {
  133774. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  133775. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  133776. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  133777. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  133778. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133779. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  133780. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  133781. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  133782. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133783. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133784. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  133785. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  133786. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  133787. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  133788. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  133789. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  133790. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  133791. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  133792. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  133793. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  133794. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  133795. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  133796. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  133797. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  133798. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  133799. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  133800. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  133801. 10,10,10,10,10,10,10,10,10,
  133802. };
  133803. static float _vq_quantthresh__44c7_s_p8_1[] = {
  133804. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  133805. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  133806. 6.5, 7.5, 8.5, 9.5,
  133807. };
  133808. static long _vq_quantmap__44c7_s_p8_1[] = {
  133809. 19, 17, 15, 13, 11, 9, 7, 5,
  133810. 3, 1, 0, 2, 4, 6, 8, 10,
  133811. 12, 14, 16, 18, 20,
  133812. };
  133813. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  133814. _vq_quantthresh__44c7_s_p8_1,
  133815. _vq_quantmap__44c7_s_p8_1,
  133816. 21,
  133817. 21
  133818. };
  133819. static static_codebook _44c7_s_p8_1 = {
  133820. 2, 441,
  133821. _vq_lengthlist__44c7_s_p8_1,
  133822. 1, -529268736, 1611661312, 5, 0,
  133823. _vq_quantlist__44c7_s_p8_1,
  133824. NULL,
  133825. &_vq_auxt__44c7_s_p8_1,
  133826. NULL,
  133827. 0
  133828. };
  133829. static long _vq_quantlist__44c7_s_p9_0[] = {
  133830. 6,
  133831. 5,
  133832. 7,
  133833. 4,
  133834. 8,
  133835. 3,
  133836. 9,
  133837. 2,
  133838. 10,
  133839. 1,
  133840. 11,
  133841. 0,
  133842. 12,
  133843. };
  133844. static long _vq_lengthlist__44c7_s_p9_0[] = {
  133845. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  133846. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  133847. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133848. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133849. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133850. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133851. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133852. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133853. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133854. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133855. 11,11,11,11,11,11,11,11,11,
  133856. };
  133857. static float _vq_quantthresh__44c7_s_p9_0[] = {
  133858. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  133859. 1592.5, 2229.5, 2866.5, 3503.5,
  133860. };
  133861. static long _vq_quantmap__44c7_s_p9_0[] = {
  133862. 11, 9, 7, 5, 3, 1, 0, 2,
  133863. 4, 6, 8, 10, 12,
  133864. };
  133865. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  133866. _vq_quantthresh__44c7_s_p9_0,
  133867. _vq_quantmap__44c7_s_p9_0,
  133868. 13,
  133869. 13
  133870. };
  133871. static static_codebook _44c7_s_p9_0 = {
  133872. 2, 169,
  133873. _vq_lengthlist__44c7_s_p9_0,
  133874. 1, -511845376, 1630791680, 4, 0,
  133875. _vq_quantlist__44c7_s_p9_0,
  133876. NULL,
  133877. &_vq_auxt__44c7_s_p9_0,
  133878. NULL,
  133879. 0
  133880. };
  133881. static long _vq_quantlist__44c7_s_p9_1[] = {
  133882. 6,
  133883. 5,
  133884. 7,
  133885. 4,
  133886. 8,
  133887. 3,
  133888. 9,
  133889. 2,
  133890. 10,
  133891. 1,
  133892. 11,
  133893. 0,
  133894. 12,
  133895. };
  133896. static long _vq_lengthlist__44c7_s_p9_1[] = {
  133897. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  133898. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  133899. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  133900. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  133901. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  133902. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  133903. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  133904. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  133905. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  133906. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  133907. 15,11,11,10,10,12,12,12,12,
  133908. };
  133909. static float _vq_quantthresh__44c7_s_p9_1[] = {
  133910. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  133911. 122.5, 171.5, 220.5, 269.5,
  133912. };
  133913. static long _vq_quantmap__44c7_s_p9_1[] = {
  133914. 11, 9, 7, 5, 3, 1, 0, 2,
  133915. 4, 6, 8, 10, 12,
  133916. };
  133917. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  133918. _vq_quantthresh__44c7_s_p9_1,
  133919. _vq_quantmap__44c7_s_p9_1,
  133920. 13,
  133921. 13
  133922. };
  133923. static static_codebook _44c7_s_p9_1 = {
  133924. 2, 169,
  133925. _vq_lengthlist__44c7_s_p9_1,
  133926. 1, -518889472, 1622704128, 4, 0,
  133927. _vq_quantlist__44c7_s_p9_1,
  133928. NULL,
  133929. &_vq_auxt__44c7_s_p9_1,
  133930. NULL,
  133931. 0
  133932. };
  133933. static long _vq_quantlist__44c7_s_p9_2[] = {
  133934. 24,
  133935. 23,
  133936. 25,
  133937. 22,
  133938. 26,
  133939. 21,
  133940. 27,
  133941. 20,
  133942. 28,
  133943. 19,
  133944. 29,
  133945. 18,
  133946. 30,
  133947. 17,
  133948. 31,
  133949. 16,
  133950. 32,
  133951. 15,
  133952. 33,
  133953. 14,
  133954. 34,
  133955. 13,
  133956. 35,
  133957. 12,
  133958. 36,
  133959. 11,
  133960. 37,
  133961. 10,
  133962. 38,
  133963. 9,
  133964. 39,
  133965. 8,
  133966. 40,
  133967. 7,
  133968. 41,
  133969. 6,
  133970. 42,
  133971. 5,
  133972. 43,
  133973. 4,
  133974. 44,
  133975. 3,
  133976. 45,
  133977. 2,
  133978. 46,
  133979. 1,
  133980. 47,
  133981. 0,
  133982. 48,
  133983. };
  133984. static long _vq_lengthlist__44c7_s_p9_2[] = {
  133985. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  133986. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133987. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133988. 7,
  133989. };
  133990. static float _vq_quantthresh__44c7_s_p9_2[] = {
  133991. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  133992. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133993. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133994. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133995. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133996. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133997. };
  133998. static long _vq_quantmap__44c7_s_p9_2[] = {
  133999. 47, 45, 43, 41, 39, 37, 35, 33,
  134000. 31, 29, 27, 25, 23, 21, 19, 17,
  134001. 15, 13, 11, 9, 7, 5, 3, 1,
  134002. 0, 2, 4, 6, 8, 10, 12, 14,
  134003. 16, 18, 20, 22, 24, 26, 28, 30,
  134004. 32, 34, 36, 38, 40, 42, 44, 46,
  134005. 48,
  134006. };
  134007. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  134008. _vq_quantthresh__44c7_s_p9_2,
  134009. _vq_quantmap__44c7_s_p9_2,
  134010. 49,
  134011. 49
  134012. };
  134013. static static_codebook _44c7_s_p9_2 = {
  134014. 1, 49,
  134015. _vq_lengthlist__44c7_s_p9_2,
  134016. 1, -526909440, 1611661312, 6, 0,
  134017. _vq_quantlist__44c7_s_p9_2,
  134018. NULL,
  134019. &_vq_auxt__44c7_s_p9_2,
  134020. NULL,
  134021. 0
  134022. };
  134023. static long _huff_lengthlist__44c7_s_short[] = {
  134024. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  134025. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  134026. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  134027. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  134028. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  134029. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  134030. 10, 9,11,14,
  134031. };
  134032. static static_codebook _huff_book__44c7_s_short = {
  134033. 2, 100,
  134034. _huff_lengthlist__44c7_s_short,
  134035. 0, 0, 0, 0, 0,
  134036. NULL,
  134037. NULL,
  134038. NULL,
  134039. NULL,
  134040. 0
  134041. };
  134042. static long _huff_lengthlist__44c8_s_long[] = {
  134043. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  134044. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  134045. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  134046. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  134047. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  134048. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  134049. 11, 9, 9,10,
  134050. };
  134051. static static_codebook _huff_book__44c8_s_long = {
  134052. 2, 100,
  134053. _huff_lengthlist__44c8_s_long,
  134054. 0, 0, 0, 0, 0,
  134055. NULL,
  134056. NULL,
  134057. NULL,
  134058. NULL,
  134059. 0
  134060. };
  134061. static long _vq_quantlist__44c8_s_p1_0[] = {
  134062. 1,
  134063. 0,
  134064. 2,
  134065. };
  134066. static long _vq_lengthlist__44c8_s_p1_0[] = {
  134067. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  134068. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  134069. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  134070. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  134071. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  134072. 8,
  134073. };
  134074. static float _vq_quantthresh__44c8_s_p1_0[] = {
  134075. -0.5, 0.5,
  134076. };
  134077. static long _vq_quantmap__44c8_s_p1_0[] = {
  134078. 1, 0, 2,
  134079. };
  134080. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  134081. _vq_quantthresh__44c8_s_p1_0,
  134082. _vq_quantmap__44c8_s_p1_0,
  134083. 3,
  134084. 3
  134085. };
  134086. static static_codebook _44c8_s_p1_0 = {
  134087. 4, 81,
  134088. _vq_lengthlist__44c8_s_p1_0,
  134089. 1, -535822336, 1611661312, 2, 0,
  134090. _vq_quantlist__44c8_s_p1_0,
  134091. NULL,
  134092. &_vq_auxt__44c8_s_p1_0,
  134093. NULL,
  134094. 0
  134095. };
  134096. static long _vq_quantlist__44c8_s_p2_0[] = {
  134097. 2,
  134098. 1,
  134099. 3,
  134100. 0,
  134101. 4,
  134102. };
  134103. static long _vq_lengthlist__44c8_s_p2_0[] = {
  134104. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  134105. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  134106. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  134107. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  134108. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  134109. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  134110. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  134111. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  134112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134113. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  134114. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  134115. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  134116. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  134117. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  134118. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  134119. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  134120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134121. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  134122. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  134123. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  134124. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  134125. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  134126. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  134127. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134129. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  134130. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  134131. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  134132. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  134133. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  134134. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  134135. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  134140. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  134141. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  134142. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  134143. 13,
  134144. };
  134145. static float _vq_quantthresh__44c8_s_p2_0[] = {
  134146. -1.5, -0.5, 0.5, 1.5,
  134147. };
  134148. static long _vq_quantmap__44c8_s_p2_0[] = {
  134149. 3, 1, 0, 2, 4,
  134150. };
  134151. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  134152. _vq_quantthresh__44c8_s_p2_0,
  134153. _vq_quantmap__44c8_s_p2_0,
  134154. 5,
  134155. 5
  134156. };
  134157. static static_codebook _44c8_s_p2_0 = {
  134158. 4, 625,
  134159. _vq_lengthlist__44c8_s_p2_0,
  134160. 1, -533725184, 1611661312, 3, 0,
  134161. _vq_quantlist__44c8_s_p2_0,
  134162. NULL,
  134163. &_vq_auxt__44c8_s_p2_0,
  134164. NULL,
  134165. 0
  134166. };
  134167. static long _vq_quantlist__44c8_s_p3_0[] = {
  134168. 4,
  134169. 3,
  134170. 5,
  134171. 2,
  134172. 6,
  134173. 1,
  134174. 7,
  134175. 0,
  134176. 8,
  134177. };
  134178. static long _vq_lengthlist__44c8_s_p3_0[] = {
  134179. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  134180. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  134181. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  134182. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  134183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134184. 0,
  134185. };
  134186. static float _vq_quantthresh__44c8_s_p3_0[] = {
  134187. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134188. };
  134189. static long _vq_quantmap__44c8_s_p3_0[] = {
  134190. 7, 5, 3, 1, 0, 2, 4, 6,
  134191. 8,
  134192. };
  134193. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  134194. _vq_quantthresh__44c8_s_p3_0,
  134195. _vq_quantmap__44c8_s_p3_0,
  134196. 9,
  134197. 9
  134198. };
  134199. static static_codebook _44c8_s_p3_0 = {
  134200. 2, 81,
  134201. _vq_lengthlist__44c8_s_p3_0,
  134202. 1, -531628032, 1611661312, 4, 0,
  134203. _vq_quantlist__44c8_s_p3_0,
  134204. NULL,
  134205. &_vq_auxt__44c8_s_p3_0,
  134206. NULL,
  134207. 0
  134208. };
  134209. static long _vq_quantlist__44c8_s_p4_0[] = {
  134210. 8,
  134211. 7,
  134212. 9,
  134213. 6,
  134214. 10,
  134215. 5,
  134216. 11,
  134217. 4,
  134218. 12,
  134219. 3,
  134220. 13,
  134221. 2,
  134222. 14,
  134223. 1,
  134224. 15,
  134225. 0,
  134226. 16,
  134227. };
  134228. static long _vq_lengthlist__44c8_s_p4_0[] = {
  134229. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  134230. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  134231. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  134232. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  134233. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  134234. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  134235. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  134236. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  134237. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  134238. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  134239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134247. 0,
  134248. };
  134249. static float _vq_quantthresh__44c8_s_p4_0[] = {
  134250. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134251. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134252. };
  134253. static long _vq_quantmap__44c8_s_p4_0[] = {
  134254. 15, 13, 11, 9, 7, 5, 3, 1,
  134255. 0, 2, 4, 6, 8, 10, 12, 14,
  134256. 16,
  134257. };
  134258. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  134259. _vq_quantthresh__44c8_s_p4_0,
  134260. _vq_quantmap__44c8_s_p4_0,
  134261. 17,
  134262. 17
  134263. };
  134264. static static_codebook _44c8_s_p4_0 = {
  134265. 2, 289,
  134266. _vq_lengthlist__44c8_s_p4_0,
  134267. 1, -529530880, 1611661312, 5, 0,
  134268. _vq_quantlist__44c8_s_p4_0,
  134269. NULL,
  134270. &_vq_auxt__44c8_s_p4_0,
  134271. NULL,
  134272. 0
  134273. };
  134274. static long _vq_quantlist__44c8_s_p5_0[] = {
  134275. 1,
  134276. 0,
  134277. 2,
  134278. };
  134279. static long _vq_lengthlist__44c8_s_p5_0[] = {
  134280. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  134281. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  134282. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  134283. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  134284. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  134285. 12,
  134286. };
  134287. static float _vq_quantthresh__44c8_s_p5_0[] = {
  134288. -5.5, 5.5,
  134289. };
  134290. static long _vq_quantmap__44c8_s_p5_0[] = {
  134291. 1, 0, 2,
  134292. };
  134293. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  134294. _vq_quantthresh__44c8_s_p5_0,
  134295. _vq_quantmap__44c8_s_p5_0,
  134296. 3,
  134297. 3
  134298. };
  134299. static static_codebook _44c8_s_p5_0 = {
  134300. 4, 81,
  134301. _vq_lengthlist__44c8_s_p5_0,
  134302. 1, -529137664, 1618345984, 2, 0,
  134303. _vq_quantlist__44c8_s_p5_0,
  134304. NULL,
  134305. &_vq_auxt__44c8_s_p5_0,
  134306. NULL,
  134307. 0
  134308. };
  134309. static long _vq_quantlist__44c8_s_p5_1[] = {
  134310. 5,
  134311. 4,
  134312. 6,
  134313. 3,
  134314. 7,
  134315. 2,
  134316. 8,
  134317. 1,
  134318. 9,
  134319. 0,
  134320. 10,
  134321. };
  134322. static long _vq_lengthlist__44c8_s_p5_1[] = {
  134323. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  134324. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  134325. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  134326. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  134327. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  134328. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  134329. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  134330. 11,11,11, 7, 7, 7, 7, 8, 8,
  134331. };
  134332. static float _vq_quantthresh__44c8_s_p5_1[] = {
  134333. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134334. 3.5, 4.5,
  134335. };
  134336. static long _vq_quantmap__44c8_s_p5_1[] = {
  134337. 9, 7, 5, 3, 1, 0, 2, 4,
  134338. 6, 8, 10,
  134339. };
  134340. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  134341. _vq_quantthresh__44c8_s_p5_1,
  134342. _vq_quantmap__44c8_s_p5_1,
  134343. 11,
  134344. 11
  134345. };
  134346. static static_codebook _44c8_s_p5_1 = {
  134347. 2, 121,
  134348. _vq_lengthlist__44c8_s_p5_1,
  134349. 1, -531365888, 1611661312, 4, 0,
  134350. _vq_quantlist__44c8_s_p5_1,
  134351. NULL,
  134352. &_vq_auxt__44c8_s_p5_1,
  134353. NULL,
  134354. 0
  134355. };
  134356. static long _vq_quantlist__44c8_s_p6_0[] = {
  134357. 6,
  134358. 5,
  134359. 7,
  134360. 4,
  134361. 8,
  134362. 3,
  134363. 9,
  134364. 2,
  134365. 10,
  134366. 1,
  134367. 11,
  134368. 0,
  134369. 12,
  134370. };
  134371. static long _vq_lengthlist__44c8_s_p6_0[] = {
  134372. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  134373. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  134374. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  134375. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  134376. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  134377. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  134378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134382. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134383. };
  134384. static float _vq_quantthresh__44c8_s_p6_0[] = {
  134385. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134386. 12.5, 17.5, 22.5, 27.5,
  134387. };
  134388. static long _vq_quantmap__44c8_s_p6_0[] = {
  134389. 11, 9, 7, 5, 3, 1, 0, 2,
  134390. 4, 6, 8, 10, 12,
  134391. };
  134392. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  134393. _vq_quantthresh__44c8_s_p6_0,
  134394. _vq_quantmap__44c8_s_p6_0,
  134395. 13,
  134396. 13
  134397. };
  134398. static static_codebook _44c8_s_p6_0 = {
  134399. 2, 169,
  134400. _vq_lengthlist__44c8_s_p6_0,
  134401. 1, -526516224, 1616117760, 4, 0,
  134402. _vq_quantlist__44c8_s_p6_0,
  134403. NULL,
  134404. &_vq_auxt__44c8_s_p6_0,
  134405. NULL,
  134406. 0
  134407. };
  134408. static long _vq_quantlist__44c8_s_p6_1[] = {
  134409. 2,
  134410. 1,
  134411. 3,
  134412. 0,
  134413. 4,
  134414. };
  134415. static long _vq_lengthlist__44c8_s_p6_1[] = {
  134416. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  134417. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  134418. };
  134419. static float _vq_quantthresh__44c8_s_p6_1[] = {
  134420. -1.5, -0.5, 0.5, 1.5,
  134421. };
  134422. static long _vq_quantmap__44c8_s_p6_1[] = {
  134423. 3, 1, 0, 2, 4,
  134424. };
  134425. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  134426. _vq_quantthresh__44c8_s_p6_1,
  134427. _vq_quantmap__44c8_s_p6_1,
  134428. 5,
  134429. 5
  134430. };
  134431. static static_codebook _44c8_s_p6_1 = {
  134432. 2, 25,
  134433. _vq_lengthlist__44c8_s_p6_1,
  134434. 1, -533725184, 1611661312, 3, 0,
  134435. _vq_quantlist__44c8_s_p6_1,
  134436. NULL,
  134437. &_vq_auxt__44c8_s_p6_1,
  134438. NULL,
  134439. 0
  134440. };
  134441. static long _vq_quantlist__44c8_s_p7_0[] = {
  134442. 6,
  134443. 5,
  134444. 7,
  134445. 4,
  134446. 8,
  134447. 3,
  134448. 9,
  134449. 2,
  134450. 10,
  134451. 1,
  134452. 11,
  134453. 0,
  134454. 12,
  134455. };
  134456. static long _vq_lengthlist__44c8_s_p7_0[] = {
  134457. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  134458. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  134459. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  134460. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  134461. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  134462. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  134463. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  134464. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  134465. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  134466. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  134467. 20,13,13,13,13,14,13,15,15,
  134468. };
  134469. static float _vq_quantthresh__44c8_s_p7_0[] = {
  134470. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  134471. 27.5, 38.5, 49.5, 60.5,
  134472. };
  134473. static long _vq_quantmap__44c8_s_p7_0[] = {
  134474. 11, 9, 7, 5, 3, 1, 0, 2,
  134475. 4, 6, 8, 10, 12,
  134476. };
  134477. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  134478. _vq_quantthresh__44c8_s_p7_0,
  134479. _vq_quantmap__44c8_s_p7_0,
  134480. 13,
  134481. 13
  134482. };
  134483. static static_codebook _44c8_s_p7_0 = {
  134484. 2, 169,
  134485. _vq_lengthlist__44c8_s_p7_0,
  134486. 1, -523206656, 1618345984, 4, 0,
  134487. _vq_quantlist__44c8_s_p7_0,
  134488. NULL,
  134489. &_vq_auxt__44c8_s_p7_0,
  134490. NULL,
  134491. 0
  134492. };
  134493. static long _vq_quantlist__44c8_s_p7_1[] = {
  134494. 5,
  134495. 4,
  134496. 6,
  134497. 3,
  134498. 7,
  134499. 2,
  134500. 8,
  134501. 1,
  134502. 9,
  134503. 0,
  134504. 10,
  134505. };
  134506. static long _vq_lengthlist__44c8_s_p7_1[] = {
  134507. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  134508. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  134509. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  134510. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134511. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  134512. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  134513. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  134514. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134515. };
  134516. static float _vq_quantthresh__44c8_s_p7_1[] = {
  134517. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134518. 3.5, 4.5,
  134519. };
  134520. static long _vq_quantmap__44c8_s_p7_1[] = {
  134521. 9, 7, 5, 3, 1, 0, 2, 4,
  134522. 6, 8, 10,
  134523. };
  134524. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  134525. _vq_quantthresh__44c8_s_p7_1,
  134526. _vq_quantmap__44c8_s_p7_1,
  134527. 11,
  134528. 11
  134529. };
  134530. static static_codebook _44c8_s_p7_1 = {
  134531. 2, 121,
  134532. _vq_lengthlist__44c8_s_p7_1,
  134533. 1, -531365888, 1611661312, 4, 0,
  134534. _vq_quantlist__44c8_s_p7_1,
  134535. NULL,
  134536. &_vq_auxt__44c8_s_p7_1,
  134537. NULL,
  134538. 0
  134539. };
  134540. static long _vq_quantlist__44c8_s_p8_0[] = {
  134541. 7,
  134542. 6,
  134543. 8,
  134544. 5,
  134545. 9,
  134546. 4,
  134547. 10,
  134548. 3,
  134549. 11,
  134550. 2,
  134551. 12,
  134552. 1,
  134553. 13,
  134554. 0,
  134555. 14,
  134556. };
  134557. static long _vq_lengthlist__44c8_s_p8_0[] = {
  134558. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  134559. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  134560. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  134561. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  134562. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  134563. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  134564. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  134565. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  134566. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  134567. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  134568. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  134569. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  134570. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  134571. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  134572. 15,
  134573. };
  134574. static float _vq_quantthresh__44c8_s_p8_0[] = {
  134575. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  134576. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  134577. };
  134578. static long _vq_quantmap__44c8_s_p8_0[] = {
  134579. 13, 11, 9, 7, 5, 3, 1, 0,
  134580. 2, 4, 6, 8, 10, 12, 14,
  134581. };
  134582. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  134583. _vq_quantthresh__44c8_s_p8_0,
  134584. _vq_quantmap__44c8_s_p8_0,
  134585. 15,
  134586. 15
  134587. };
  134588. static static_codebook _44c8_s_p8_0 = {
  134589. 2, 225,
  134590. _vq_lengthlist__44c8_s_p8_0,
  134591. 1, -520986624, 1620377600, 4, 0,
  134592. _vq_quantlist__44c8_s_p8_0,
  134593. NULL,
  134594. &_vq_auxt__44c8_s_p8_0,
  134595. NULL,
  134596. 0
  134597. };
  134598. static long _vq_quantlist__44c8_s_p8_1[] = {
  134599. 10,
  134600. 9,
  134601. 11,
  134602. 8,
  134603. 12,
  134604. 7,
  134605. 13,
  134606. 6,
  134607. 14,
  134608. 5,
  134609. 15,
  134610. 4,
  134611. 16,
  134612. 3,
  134613. 17,
  134614. 2,
  134615. 18,
  134616. 1,
  134617. 19,
  134618. 0,
  134619. 20,
  134620. };
  134621. static long _vq_lengthlist__44c8_s_p8_1[] = {
  134622. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  134623. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  134624. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  134625. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  134626. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134627. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  134628. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  134629. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  134630. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134631. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134632. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  134633. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  134634. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  134635. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134636. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  134637. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  134638. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  134639. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  134640. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  134641. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  134642. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  134643. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  134644. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134645. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  134646. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  134647. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  134648. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134649. 10, 9, 9,10,10, 9,10, 9, 9,
  134650. };
  134651. static float _vq_quantthresh__44c8_s_p8_1[] = {
  134652. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  134653. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  134654. 6.5, 7.5, 8.5, 9.5,
  134655. };
  134656. static long _vq_quantmap__44c8_s_p8_1[] = {
  134657. 19, 17, 15, 13, 11, 9, 7, 5,
  134658. 3, 1, 0, 2, 4, 6, 8, 10,
  134659. 12, 14, 16, 18, 20,
  134660. };
  134661. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  134662. _vq_quantthresh__44c8_s_p8_1,
  134663. _vq_quantmap__44c8_s_p8_1,
  134664. 21,
  134665. 21
  134666. };
  134667. static static_codebook _44c8_s_p8_1 = {
  134668. 2, 441,
  134669. _vq_lengthlist__44c8_s_p8_1,
  134670. 1, -529268736, 1611661312, 5, 0,
  134671. _vq_quantlist__44c8_s_p8_1,
  134672. NULL,
  134673. &_vq_auxt__44c8_s_p8_1,
  134674. NULL,
  134675. 0
  134676. };
  134677. static long _vq_quantlist__44c8_s_p9_0[] = {
  134678. 8,
  134679. 7,
  134680. 9,
  134681. 6,
  134682. 10,
  134683. 5,
  134684. 11,
  134685. 4,
  134686. 12,
  134687. 3,
  134688. 13,
  134689. 2,
  134690. 14,
  134691. 1,
  134692. 15,
  134693. 0,
  134694. 16,
  134695. };
  134696. static long _vq_lengthlist__44c8_s_p9_0[] = {
  134697. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134698. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  134699. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  134700. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134701. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134702. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134703. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134704. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134705. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134706. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134707. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134708. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134709. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134710. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134711. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134712. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134713. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134714. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134715. 10,
  134716. };
  134717. static float _vq_quantthresh__44c8_s_p9_0[] = {
  134718. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  134719. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  134720. };
  134721. static long _vq_quantmap__44c8_s_p9_0[] = {
  134722. 15, 13, 11, 9, 7, 5, 3, 1,
  134723. 0, 2, 4, 6, 8, 10, 12, 14,
  134724. 16,
  134725. };
  134726. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  134727. _vq_quantthresh__44c8_s_p9_0,
  134728. _vq_quantmap__44c8_s_p9_0,
  134729. 17,
  134730. 17
  134731. };
  134732. static static_codebook _44c8_s_p9_0 = {
  134733. 2, 289,
  134734. _vq_lengthlist__44c8_s_p9_0,
  134735. 1, -509798400, 1631393792, 5, 0,
  134736. _vq_quantlist__44c8_s_p9_0,
  134737. NULL,
  134738. &_vq_auxt__44c8_s_p9_0,
  134739. NULL,
  134740. 0
  134741. };
  134742. static long _vq_quantlist__44c8_s_p9_1[] = {
  134743. 9,
  134744. 8,
  134745. 10,
  134746. 7,
  134747. 11,
  134748. 6,
  134749. 12,
  134750. 5,
  134751. 13,
  134752. 4,
  134753. 14,
  134754. 3,
  134755. 15,
  134756. 2,
  134757. 16,
  134758. 1,
  134759. 17,
  134760. 0,
  134761. 18,
  134762. };
  134763. static long _vq_lengthlist__44c8_s_p9_1[] = {
  134764. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  134765. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  134766. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  134767. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  134768. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  134769. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  134770. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  134771. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  134772. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  134773. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  134774. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  134775. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  134776. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  134777. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  134778. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  134779. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  134780. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  134781. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  134782. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  134783. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  134784. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  134785. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  134786. 14,13,13,14,14,15,14,15,14,
  134787. };
  134788. static float _vq_quantthresh__44c8_s_p9_1[] = {
  134789. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  134790. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  134791. 367.5, 416.5,
  134792. };
  134793. static long _vq_quantmap__44c8_s_p9_1[] = {
  134794. 17, 15, 13, 11, 9, 7, 5, 3,
  134795. 1, 0, 2, 4, 6, 8, 10, 12,
  134796. 14, 16, 18,
  134797. };
  134798. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  134799. _vq_quantthresh__44c8_s_p9_1,
  134800. _vq_quantmap__44c8_s_p9_1,
  134801. 19,
  134802. 19
  134803. };
  134804. static static_codebook _44c8_s_p9_1 = {
  134805. 2, 361,
  134806. _vq_lengthlist__44c8_s_p9_1,
  134807. 1, -518287360, 1622704128, 5, 0,
  134808. _vq_quantlist__44c8_s_p9_1,
  134809. NULL,
  134810. &_vq_auxt__44c8_s_p9_1,
  134811. NULL,
  134812. 0
  134813. };
  134814. static long _vq_quantlist__44c8_s_p9_2[] = {
  134815. 24,
  134816. 23,
  134817. 25,
  134818. 22,
  134819. 26,
  134820. 21,
  134821. 27,
  134822. 20,
  134823. 28,
  134824. 19,
  134825. 29,
  134826. 18,
  134827. 30,
  134828. 17,
  134829. 31,
  134830. 16,
  134831. 32,
  134832. 15,
  134833. 33,
  134834. 14,
  134835. 34,
  134836. 13,
  134837. 35,
  134838. 12,
  134839. 36,
  134840. 11,
  134841. 37,
  134842. 10,
  134843. 38,
  134844. 9,
  134845. 39,
  134846. 8,
  134847. 40,
  134848. 7,
  134849. 41,
  134850. 6,
  134851. 42,
  134852. 5,
  134853. 43,
  134854. 4,
  134855. 44,
  134856. 3,
  134857. 45,
  134858. 2,
  134859. 46,
  134860. 1,
  134861. 47,
  134862. 0,
  134863. 48,
  134864. };
  134865. static long _vq_lengthlist__44c8_s_p9_2[] = {
  134866. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  134867. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134868. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134869. 7,
  134870. };
  134871. static float _vq_quantthresh__44c8_s_p9_2[] = {
  134872. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  134873. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  134874. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134875. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134876. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  134877. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  134878. };
  134879. static long _vq_quantmap__44c8_s_p9_2[] = {
  134880. 47, 45, 43, 41, 39, 37, 35, 33,
  134881. 31, 29, 27, 25, 23, 21, 19, 17,
  134882. 15, 13, 11, 9, 7, 5, 3, 1,
  134883. 0, 2, 4, 6, 8, 10, 12, 14,
  134884. 16, 18, 20, 22, 24, 26, 28, 30,
  134885. 32, 34, 36, 38, 40, 42, 44, 46,
  134886. 48,
  134887. };
  134888. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  134889. _vq_quantthresh__44c8_s_p9_2,
  134890. _vq_quantmap__44c8_s_p9_2,
  134891. 49,
  134892. 49
  134893. };
  134894. static static_codebook _44c8_s_p9_2 = {
  134895. 1, 49,
  134896. _vq_lengthlist__44c8_s_p9_2,
  134897. 1, -526909440, 1611661312, 6, 0,
  134898. _vq_quantlist__44c8_s_p9_2,
  134899. NULL,
  134900. &_vq_auxt__44c8_s_p9_2,
  134901. NULL,
  134902. 0
  134903. };
  134904. static long _huff_lengthlist__44c8_s_short[] = {
  134905. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  134906. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  134907. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  134908. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  134909. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  134910. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  134911. 10, 9,11,14,
  134912. };
  134913. static static_codebook _huff_book__44c8_s_short = {
  134914. 2, 100,
  134915. _huff_lengthlist__44c8_s_short,
  134916. 0, 0, 0, 0, 0,
  134917. NULL,
  134918. NULL,
  134919. NULL,
  134920. NULL,
  134921. 0
  134922. };
  134923. static long _huff_lengthlist__44c9_s_long[] = {
  134924. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  134925. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  134926. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  134927. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  134928. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  134929. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  134930. 10, 9, 8, 9,
  134931. };
  134932. static static_codebook _huff_book__44c9_s_long = {
  134933. 2, 100,
  134934. _huff_lengthlist__44c9_s_long,
  134935. 0, 0, 0, 0, 0,
  134936. NULL,
  134937. NULL,
  134938. NULL,
  134939. NULL,
  134940. 0
  134941. };
  134942. static long _vq_quantlist__44c9_s_p1_0[] = {
  134943. 1,
  134944. 0,
  134945. 2,
  134946. };
  134947. static long _vq_lengthlist__44c9_s_p1_0[] = {
  134948. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  134949. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  134950. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  134951. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  134952. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  134953. 7,
  134954. };
  134955. static float _vq_quantthresh__44c9_s_p1_0[] = {
  134956. -0.5, 0.5,
  134957. };
  134958. static long _vq_quantmap__44c9_s_p1_0[] = {
  134959. 1, 0, 2,
  134960. };
  134961. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  134962. _vq_quantthresh__44c9_s_p1_0,
  134963. _vq_quantmap__44c9_s_p1_0,
  134964. 3,
  134965. 3
  134966. };
  134967. static static_codebook _44c9_s_p1_0 = {
  134968. 4, 81,
  134969. _vq_lengthlist__44c9_s_p1_0,
  134970. 1, -535822336, 1611661312, 2, 0,
  134971. _vq_quantlist__44c9_s_p1_0,
  134972. NULL,
  134973. &_vq_auxt__44c9_s_p1_0,
  134974. NULL,
  134975. 0
  134976. };
  134977. static long _vq_quantlist__44c9_s_p2_0[] = {
  134978. 2,
  134979. 1,
  134980. 3,
  134981. 0,
  134982. 4,
  134983. };
  134984. static long _vq_lengthlist__44c9_s_p2_0[] = {
  134985. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  134986. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  134987. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  134988. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  134989. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  134990. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  134991. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  134992. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  134993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134994. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  134995. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  134996. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  134997. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  134998. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  134999. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  135000. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  135001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135002. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  135003. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  135004. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  135005. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  135006. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  135007. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  135008. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135010. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  135011. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  135012. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  135013. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  135014. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  135015. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  135016. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  135021. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  135022. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  135023. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  135024. 12,
  135025. };
  135026. static float _vq_quantthresh__44c9_s_p2_0[] = {
  135027. -1.5, -0.5, 0.5, 1.5,
  135028. };
  135029. static long _vq_quantmap__44c9_s_p2_0[] = {
  135030. 3, 1, 0, 2, 4,
  135031. };
  135032. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  135033. _vq_quantthresh__44c9_s_p2_0,
  135034. _vq_quantmap__44c9_s_p2_0,
  135035. 5,
  135036. 5
  135037. };
  135038. static static_codebook _44c9_s_p2_0 = {
  135039. 4, 625,
  135040. _vq_lengthlist__44c9_s_p2_0,
  135041. 1, -533725184, 1611661312, 3, 0,
  135042. _vq_quantlist__44c9_s_p2_0,
  135043. NULL,
  135044. &_vq_auxt__44c9_s_p2_0,
  135045. NULL,
  135046. 0
  135047. };
  135048. static long _vq_quantlist__44c9_s_p3_0[] = {
  135049. 4,
  135050. 3,
  135051. 5,
  135052. 2,
  135053. 6,
  135054. 1,
  135055. 7,
  135056. 0,
  135057. 8,
  135058. };
  135059. static long _vq_lengthlist__44c9_s_p3_0[] = {
  135060. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  135061. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  135062. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  135063. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  135064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135065. 0,
  135066. };
  135067. static float _vq_quantthresh__44c9_s_p3_0[] = {
  135068. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135069. };
  135070. static long _vq_quantmap__44c9_s_p3_0[] = {
  135071. 7, 5, 3, 1, 0, 2, 4, 6,
  135072. 8,
  135073. };
  135074. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  135075. _vq_quantthresh__44c9_s_p3_0,
  135076. _vq_quantmap__44c9_s_p3_0,
  135077. 9,
  135078. 9
  135079. };
  135080. static static_codebook _44c9_s_p3_0 = {
  135081. 2, 81,
  135082. _vq_lengthlist__44c9_s_p3_0,
  135083. 1, -531628032, 1611661312, 4, 0,
  135084. _vq_quantlist__44c9_s_p3_0,
  135085. NULL,
  135086. &_vq_auxt__44c9_s_p3_0,
  135087. NULL,
  135088. 0
  135089. };
  135090. static long _vq_quantlist__44c9_s_p4_0[] = {
  135091. 8,
  135092. 7,
  135093. 9,
  135094. 6,
  135095. 10,
  135096. 5,
  135097. 11,
  135098. 4,
  135099. 12,
  135100. 3,
  135101. 13,
  135102. 2,
  135103. 14,
  135104. 1,
  135105. 15,
  135106. 0,
  135107. 16,
  135108. };
  135109. static long _vq_lengthlist__44c9_s_p4_0[] = {
  135110. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  135111. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  135112. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  135113. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  135114. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  135115. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  135116. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  135117. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  135118. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  135119. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  135120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135128. 0,
  135129. };
  135130. static float _vq_quantthresh__44c9_s_p4_0[] = {
  135131. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135132. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135133. };
  135134. static long _vq_quantmap__44c9_s_p4_0[] = {
  135135. 15, 13, 11, 9, 7, 5, 3, 1,
  135136. 0, 2, 4, 6, 8, 10, 12, 14,
  135137. 16,
  135138. };
  135139. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  135140. _vq_quantthresh__44c9_s_p4_0,
  135141. _vq_quantmap__44c9_s_p4_0,
  135142. 17,
  135143. 17
  135144. };
  135145. static static_codebook _44c9_s_p4_0 = {
  135146. 2, 289,
  135147. _vq_lengthlist__44c9_s_p4_0,
  135148. 1, -529530880, 1611661312, 5, 0,
  135149. _vq_quantlist__44c9_s_p4_0,
  135150. NULL,
  135151. &_vq_auxt__44c9_s_p4_0,
  135152. NULL,
  135153. 0
  135154. };
  135155. static long _vq_quantlist__44c9_s_p5_0[] = {
  135156. 1,
  135157. 0,
  135158. 2,
  135159. };
  135160. static long _vq_lengthlist__44c9_s_p5_0[] = {
  135161. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  135162. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  135163. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  135164. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  135165. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  135166. 12,
  135167. };
  135168. static float _vq_quantthresh__44c9_s_p5_0[] = {
  135169. -5.5, 5.5,
  135170. };
  135171. static long _vq_quantmap__44c9_s_p5_0[] = {
  135172. 1, 0, 2,
  135173. };
  135174. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  135175. _vq_quantthresh__44c9_s_p5_0,
  135176. _vq_quantmap__44c9_s_p5_0,
  135177. 3,
  135178. 3
  135179. };
  135180. static static_codebook _44c9_s_p5_0 = {
  135181. 4, 81,
  135182. _vq_lengthlist__44c9_s_p5_0,
  135183. 1, -529137664, 1618345984, 2, 0,
  135184. _vq_quantlist__44c9_s_p5_0,
  135185. NULL,
  135186. &_vq_auxt__44c9_s_p5_0,
  135187. NULL,
  135188. 0
  135189. };
  135190. static long _vq_quantlist__44c9_s_p5_1[] = {
  135191. 5,
  135192. 4,
  135193. 6,
  135194. 3,
  135195. 7,
  135196. 2,
  135197. 8,
  135198. 1,
  135199. 9,
  135200. 0,
  135201. 10,
  135202. };
  135203. static long _vq_lengthlist__44c9_s_p5_1[] = {
  135204. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  135205. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  135206. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  135207. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  135208. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  135209. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  135210. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  135211. 11,11,11, 7, 7, 7, 7, 7, 7,
  135212. };
  135213. static float _vq_quantthresh__44c9_s_p5_1[] = {
  135214. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135215. 3.5, 4.5,
  135216. };
  135217. static long _vq_quantmap__44c9_s_p5_1[] = {
  135218. 9, 7, 5, 3, 1, 0, 2, 4,
  135219. 6, 8, 10,
  135220. };
  135221. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  135222. _vq_quantthresh__44c9_s_p5_1,
  135223. _vq_quantmap__44c9_s_p5_1,
  135224. 11,
  135225. 11
  135226. };
  135227. static static_codebook _44c9_s_p5_1 = {
  135228. 2, 121,
  135229. _vq_lengthlist__44c9_s_p5_1,
  135230. 1, -531365888, 1611661312, 4, 0,
  135231. _vq_quantlist__44c9_s_p5_1,
  135232. NULL,
  135233. &_vq_auxt__44c9_s_p5_1,
  135234. NULL,
  135235. 0
  135236. };
  135237. static long _vq_quantlist__44c9_s_p6_0[] = {
  135238. 6,
  135239. 5,
  135240. 7,
  135241. 4,
  135242. 8,
  135243. 3,
  135244. 9,
  135245. 2,
  135246. 10,
  135247. 1,
  135248. 11,
  135249. 0,
  135250. 12,
  135251. };
  135252. static long _vq_lengthlist__44c9_s_p6_0[] = {
  135253. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  135254. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  135255. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  135256. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  135257. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  135258. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  135259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135263. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135264. };
  135265. static float _vq_quantthresh__44c9_s_p6_0[] = {
  135266. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  135267. 12.5, 17.5, 22.5, 27.5,
  135268. };
  135269. static long _vq_quantmap__44c9_s_p6_0[] = {
  135270. 11, 9, 7, 5, 3, 1, 0, 2,
  135271. 4, 6, 8, 10, 12,
  135272. };
  135273. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  135274. _vq_quantthresh__44c9_s_p6_0,
  135275. _vq_quantmap__44c9_s_p6_0,
  135276. 13,
  135277. 13
  135278. };
  135279. static static_codebook _44c9_s_p6_0 = {
  135280. 2, 169,
  135281. _vq_lengthlist__44c9_s_p6_0,
  135282. 1, -526516224, 1616117760, 4, 0,
  135283. _vq_quantlist__44c9_s_p6_0,
  135284. NULL,
  135285. &_vq_auxt__44c9_s_p6_0,
  135286. NULL,
  135287. 0
  135288. };
  135289. static long _vq_quantlist__44c9_s_p6_1[] = {
  135290. 2,
  135291. 1,
  135292. 3,
  135293. 0,
  135294. 4,
  135295. };
  135296. static long _vq_lengthlist__44c9_s_p6_1[] = {
  135297. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  135298. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  135299. };
  135300. static float _vq_quantthresh__44c9_s_p6_1[] = {
  135301. -1.5, -0.5, 0.5, 1.5,
  135302. };
  135303. static long _vq_quantmap__44c9_s_p6_1[] = {
  135304. 3, 1, 0, 2, 4,
  135305. };
  135306. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  135307. _vq_quantthresh__44c9_s_p6_1,
  135308. _vq_quantmap__44c9_s_p6_1,
  135309. 5,
  135310. 5
  135311. };
  135312. static static_codebook _44c9_s_p6_1 = {
  135313. 2, 25,
  135314. _vq_lengthlist__44c9_s_p6_1,
  135315. 1, -533725184, 1611661312, 3, 0,
  135316. _vq_quantlist__44c9_s_p6_1,
  135317. NULL,
  135318. &_vq_auxt__44c9_s_p6_1,
  135319. NULL,
  135320. 0
  135321. };
  135322. static long _vq_quantlist__44c9_s_p7_0[] = {
  135323. 6,
  135324. 5,
  135325. 7,
  135326. 4,
  135327. 8,
  135328. 3,
  135329. 9,
  135330. 2,
  135331. 10,
  135332. 1,
  135333. 11,
  135334. 0,
  135335. 12,
  135336. };
  135337. static long _vq_lengthlist__44c9_s_p7_0[] = {
  135338. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  135339. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  135340. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  135341. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  135342. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  135343. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  135344. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  135345. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  135346. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  135347. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  135348. 19,12,12,12,12,13,13,14,14,
  135349. };
  135350. static float _vq_quantthresh__44c9_s_p7_0[] = {
  135351. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  135352. 27.5, 38.5, 49.5, 60.5,
  135353. };
  135354. static long _vq_quantmap__44c9_s_p7_0[] = {
  135355. 11, 9, 7, 5, 3, 1, 0, 2,
  135356. 4, 6, 8, 10, 12,
  135357. };
  135358. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  135359. _vq_quantthresh__44c9_s_p7_0,
  135360. _vq_quantmap__44c9_s_p7_0,
  135361. 13,
  135362. 13
  135363. };
  135364. static static_codebook _44c9_s_p7_0 = {
  135365. 2, 169,
  135366. _vq_lengthlist__44c9_s_p7_0,
  135367. 1, -523206656, 1618345984, 4, 0,
  135368. _vq_quantlist__44c9_s_p7_0,
  135369. NULL,
  135370. &_vq_auxt__44c9_s_p7_0,
  135371. NULL,
  135372. 0
  135373. };
  135374. static long _vq_quantlist__44c9_s_p7_1[] = {
  135375. 5,
  135376. 4,
  135377. 6,
  135378. 3,
  135379. 7,
  135380. 2,
  135381. 8,
  135382. 1,
  135383. 9,
  135384. 0,
  135385. 10,
  135386. };
  135387. static long _vq_lengthlist__44c9_s_p7_1[] = {
  135388. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  135389. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135390. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  135391. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135392. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  135393. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  135394. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  135395. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135396. };
  135397. static float _vq_quantthresh__44c9_s_p7_1[] = {
  135398. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135399. 3.5, 4.5,
  135400. };
  135401. static long _vq_quantmap__44c9_s_p7_1[] = {
  135402. 9, 7, 5, 3, 1, 0, 2, 4,
  135403. 6, 8, 10,
  135404. };
  135405. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  135406. _vq_quantthresh__44c9_s_p7_1,
  135407. _vq_quantmap__44c9_s_p7_1,
  135408. 11,
  135409. 11
  135410. };
  135411. static static_codebook _44c9_s_p7_1 = {
  135412. 2, 121,
  135413. _vq_lengthlist__44c9_s_p7_1,
  135414. 1, -531365888, 1611661312, 4, 0,
  135415. _vq_quantlist__44c9_s_p7_1,
  135416. NULL,
  135417. &_vq_auxt__44c9_s_p7_1,
  135418. NULL,
  135419. 0
  135420. };
  135421. static long _vq_quantlist__44c9_s_p8_0[] = {
  135422. 7,
  135423. 6,
  135424. 8,
  135425. 5,
  135426. 9,
  135427. 4,
  135428. 10,
  135429. 3,
  135430. 11,
  135431. 2,
  135432. 12,
  135433. 1,
  135434. 13,
  135435. 0,
  135436. 14,
  135437. };
  135438. static long _vq_lengthlist__44c9_s_p8_0[] = {
  135439. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  135440. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  135441. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  135442. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  135443. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  135444. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  135445. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  135446. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  135447. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  135448. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  135449. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  135450. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  135451. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  135452. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  135453. 14,
  135454. };
  135455. static float _vq_quantthresh__44c9_s_p8_0[] = {
  135456. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  135457. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  135458. };
  135459. static long _vq_quantmap__44c9_s_p8_0[] = {
  135460. 13, 11, 9, 7, 5, 3, 1, 0,
  135461. 2, 4, 6, 8, 10, 12, 14,
  135462. };
  135463. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  135464. _vq_quantthresh__44c9_s_p8_0,
  135465. _vq_quantmap__44c9_s_p8_0,
  135466. 15,
  135467. 15
  135468. };
  135469. static static_codebook _44c9_s_p8_0 = {
  135470. 2, 225,
  135471. _vq_lengthlist__44c9_s_p8_0,
  135472. 1, -520986624, 1620377600, 4, 0,
  135473. _vq_quantlist__44c9_s_p8_0,
  135474. NULL,
  135475. &_vq_auxt__44c9_s_p8_0,
  135476. NULL,
  135477. 0
  135478. };
  135479. static long _vq_quantlist__44c9_s_p8_1[] = {
  135480. 10,
  135481. 9,
  135482. 11,
  135483. 8,
  135484. 12,
  135485. 7,
  135486. 13,
  135487. 6,
  135488. 14,
  135489. 5,
  135490. 15,
  135491. 4,
  135492. 16,
  135493. 3,
  135494. 17,
  135495. 2,
  135496. 18,
  135497. 1,
  135498. 19,
  135499. 0,
  135500. 20,
  135501. };
  135502. static long _vq_lengthlist__44c9_s_p8_1[] = {
  135503. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  135504. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  135505. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  135506. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  135507. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135508. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  135509. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  135510. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  135511. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135512. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135513. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  135514. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  135515. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135516. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135517. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  135518. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  135519. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  135520. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  135521. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  135522. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135523. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  135524. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  135525. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  135526. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135527. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  135528. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  135529. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  135530. 9, 9, 9,10, 9, 9, 9, 9, 9,
  135531. };
  135532. static float _vq_quantthresh__44c9_s_p8_1[] = {
  135533. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  135534. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  135535. 6.5, 7.5, 8.5, 9.5,
  135536. };
  135537. static long _vq_quantmap__44c9_s_p8_1[] = {
  135538. 19, 17, 15, 13, 11, 9, 7, 5,
  135539. 3, 1, 0, 2, 4, 6, 8, 10,
  135540. 12, 14, 16, 18, 20,
  135541. };
  135542. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  135543. _vq_quantthresh__44c9_s_p8_1,
  135544. _vq_quantmap__44c9_s_p8_1,
  135545. 21,
  135546. 21
  135547. };
  135548. static static_codebook _44c9_s_p8_1 = {
  135549. 2, 441,
  135550. _vq_lengthlist__44c9_s_p8_1,
  135551. 1, -529268736, 1611661312, 5, 0,
  135552. _vq_quantlist__44c9_s_p8_1,
  135553. NULL,
  135554. &_vq_auxt__44c9_s_p8_1,
  135555. NULL,
  135556. 0
  135557. };
  135558. static long _vq_quantlist__44c9_s_p9_0[] = {
  135559. 9,
  135560. 8,
  135561. 10,
  135562. 7,
  135563. 11,
  135564. 6,
  135565. 12,
  135566. 5,
  135567. 13,
  135568. 4,
  135569. 14,
  135570. 3,
  135571. 15,
  135572. 2,
  135573. 16,
  135574. 1,
  135575. 17,
  135576. 0,
  135577. 18,
  135578. };
  135579. static long _vq_lengthlist__44c9_s_p9_0[] = {
  135580. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135581. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  135582. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  135583. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  135584. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135585. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135586. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135587. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135588. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135589. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135590. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135591. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135592. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135593. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135594. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135595. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135596. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  135597. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135598. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135599. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135600. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135601. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135602. 11,11,11,11,11,11,11,11,11,
  135603. };
  135604. static float _vq_quantthresh__44c9_s_p9_0[] = {
  135605. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  135606. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  135607. 6982.5, 7913.5,
  135608. };
  135609. static long _vq_quantmap__44c9_s_p9_0[] = {
  135610. 17, 15, 13, 11, 9, 7, 5, 3,
  135611. 1, 0, 2, 4, 6, 8, 10, 12,
  135612. 14, 16, 18,
  135613. };
  135614. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  135615. _vq_quantthresh__44c9_s_p9_0,
  135616. _vq_quantmap__44c9_s_p9_0,
  135617. 19,
  135618. 19
  135619. };
  135620. static static_codebook _44c9_s_p9_0 = {
  135621. 2, 361,
  135622. _vq_lengthlist__44c9_s_p9_0,
  135623. 1, -508535424, 1631393792, 5, 0,
  135624. _vq_quantlist__44c9_s_p9_0,
  135625. NULL,
  135626. &_vq_auxt__44c9_s_p9_0,
  135627. NULL,
  135628. 0
  135629. };
  135630. static long _vq_quantlist__44c9_s_p9_1[] = {
  135631. 9,
  135632. 8,
  135633. 10,
  135634. 7,
  135635. 11,
  135636. 6,
  135637. 12,
  135638. 5,
  135639. 13,
  135640. 4,
  135641. 14,
  135642. 3,
  135643. 15,
  135644. 2,
  135645. 16,
  135646. 1,
  135647. 17,
  135648. 0,
  135649. 18,
  135650. };
  135651. static long _vq_lengthlist__44c9_s_p9_1[] = {
  135652. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  135653. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  135654. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  135655. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  135656. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  135657. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  135658. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  135659. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  135660. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  135661. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  135662. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  135663. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  135664. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  135665. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  135666. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  135667. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  135668. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  135669. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  135670. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  135671. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  135672. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  135673. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  135674. 13,13,13,14,13,14,15,15,15,
  135675. };
  135676. static float _vq_quantthresh__44c9_s_p9_1[] = {
  135677. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  135678. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  135679. 367.5, 416.5,
  135680. };
  135681. static long _vq_quantmap__44c9_s_p9_1[] = {
  135682. 17, 15, 13, 11, 9, 7, 5, 3,
  135683. 1, 0, 2, 4, 6, 8, 10, 12,
  135684. 14, 16, 18,
  135685. };
  135686. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  135687. _vq_quantthresh__44c9_s_p9_1,
  135688. _vq_quantmap__44c9_s_p9_1,
  135689. 19,
  135690. 19
  135691. };
  135692. static static_codebook _44c9_s_p9_1 = {
  135693. 2, 361,
  135694. _vq_lengthlist__44c9_s_p9_1,
  135695. 1, -518287360, 1622704128, 5, 0,
  135696. _vq_quantlist__44c9_s_p9_1,
  135697. NULL,
  135698. &_vq_auxt__44c9_s_p9_1,
  135699. NULL,
  135700. 0
  135701. };
  135702. static long _vq_quantlist__44c9_s_p9_2[] = {
  135703. 24,
  135704. 23,
  135705. 25,
  135706. 22,
  135707. 26,
  135708. 21,
  135709. 27,
  135710. 20,
  135711. 28,
  135712. 19,
  135713. 29,
  135714. 18,
  135715. 30,
  135716. 17,
  135717. 31,
  135718. 16,
  135719. 32,
  135720. 15,
  135721. 33,
  135722. 14,
  135723. 34,
  135724. 13,
  135725. 35,
  135726. 12,
  135727. 36,
  135728. 11,
  135729. 37,
  135730. 10,
  135731. 38,
  135732. 9,
  135733. 39,
  135734. 8,
  135735. 40,
  135736. 7,
  135737. 41,
  135738. 6,
  135739. 42,
  135740. 5,
  135741. 43,
  135742. 4,
  135743. 44,
  135744. 3,
  135745. 45,
  135746. 2,
  135747. 46,
  135748. 1,
  135749. 47,
  135750. 0,
  135751. 48,
  135752. };
  135753. static long _vq_lengthlist__44c9_s_p9_2[] = {
  135754. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  135755. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135756. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135757. 7,
  135758. };
  135759. static float _vq_quantthresh__44c9_s_p9_2[] = {
  135760. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  135761. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  135762. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135763. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135764. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  135765. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  135766. };
  135767. static long _vq_quantmap__44c9_s_p9_2[] = {
  135768. 47, 45, 43, 41, 39, 37, 35, 33,
  135769. 31, 29, 27, 25, 23, 21, 19, 17,
  135770. 15, 13, 11, 9, 7, 5, 3, 1,
  135771. 0, 2, 4, 6, 8, 10, 12, 14,
  135772. 16, 18, 20, 22, 24, 26, 28, 30,
  135773. 32, 34, 36, 38, 40, 42, 44, 46,
  135774. 48,
  135775. };
  135776. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  135777. _vq_quantthresh__44c9_s_p9_2,
  135778. _vq_quantmap__44c9_s_p9_2,
  135779. 49,
  135780. 49
  135781. };
  135782. static static_codebook _44c9_s_p9_2 = {
  135783. 1, 49,
  135784. _vq_lengthlist__44c9_s_p9_2,
  135785. 1, -526909440, 1611661312, 6, 0,
  135786. _vq_quantlist__44c9_s_p9_2,
  135787. NULL,
  135788. &_vq_auxt__44c9_s_p9_2,
  135789. NULL,
  135790. 0
  135791. };
  135792. static long _huff_lengthlist__44c9_s_short[] = {
  135793. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  135794. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  135795. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  135796. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  135797. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  135798. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  135799. 9, 8,10,13,
  135800. };
  135801. static static_codebook _huff_book__44c9_s_short = {
  135802. 2, 100,
  135803. _huff_lengthlist__44c9_s_short,
  135804. 0, 0, 0, 0, 0,
  135805. NULL,
  135806. NULL,
  135807. NULL,
  135808. NULL,
  135809. 0
  135810. };
  135811. static long _huff_lengthlist__44c0_s_long[] = {
  135812. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  135813. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  135814. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  135815. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  135816. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  135817. 12,
  135818. };
  135819. static static_codebook _huff_book__44c0_s_long = {
  135820. 2, 81,
  135821. _huff_lengthlist__44c0_s_long,
  135822. 0, 0, 0, 0, 0,
  135823. NULL,
  135824. NULL,
  135825. NULL,
  135826. NULL,
  135827. 0
  135828. };
  135829. static long _vq_quantlist__44c0_s_p1_0[] = {
  135830. 1,
  135831. 0,
  135832. 2,
  135833. };
  135834. static long _vq_lengthlist__44c0_s_p1_0[] = {
  135835. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135836. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135840. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  135841. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135845. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135846. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  135881. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  135886. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 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, 7, 9, 9, 0, 0,
  135891. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  135892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135926. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  135927. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  135932. 0, 0, 0, 0, 0, 9, 9,11, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  135937. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  135938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136115. 0, 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,
  136246. };
  136247. static float _vq_quantthresh__44c0_s_p1_0[] = {
  136248. -0.5, 0.5,
  136249. };
  136250. static long _vq_quantmap__44c0_s_p1_0[] = {
  136251. 1, 0, 2,
  136252. };
  136253. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  136254. _vq_quantthresh__44c0_s_p1_0,
  136255. _vq_quantmap__44c0_s_p1_0,
  136256. 3,
  136257. 3
  136258. };
  136259. static static_codebook _44c0_s_p1_0 = {
  136260. 8, 6561,
  136261. _vq_lengthlist__44c0_s_p1_0,
  136262. 1, -535822336, 1611661312, 2, 0,
  136263. _vq_quantlist__44c0_s_p1_0,
  136264. NULL,
  136265. &_vq_auxt__44c0_s_p1_0,
  136266. NULL,
  136267. 0
  136268. };
  136269. static long _vq_quantlist__44c0_s_p2_0[] = {
  136270. 2,
  136271. 1,
  136272. 3,
  136273. 0,
  136274. 4,
  136275. };
  136276. static long _vq_lengthlist__44c0_s_p2_0[] = {
  136277. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  136279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136280. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  136282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136283. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  136284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136316. 0,
  136317. };
  136318. static float _vq_quantthresh__44c0_s_p2_0[] = {
  136319. -1.5, -0.5, 0.5, 1.5,
  136320. };
  136321. static long _vq_quantmap__44c0_s_p2_0[] = {
  136322. 3, 1, 0, 2, 4,
  136323. };
  136324. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  136325. _vq_quantthresh__44c0_s_p2_0,
  136326. _vq_quantmap__44c0_s_p2_0,
  136327. 5,
  136328. 5
  136329. };
  136330. static static_codebook _44c0_s_p2_0 = {
  136331. 4, 625,
  136332. _vq_lengthlist__44c0_s_p2_0,
  136333. 1, -533725184, 1611661312, 3, 0,
  136334. _vq_quantlist__44c0_s_p2_0,
  136335. NULL,
  136336. &_vq_auxt__44c0_s_p2_0,
  136337. NULL,
  136338. 0
  136339. };
  136340. static long _vq_quantlist__44c0_s_p3_0[] = {
  136341. 4,
  136342. 3,
  136343. 5,
  136344. 2,
  136345. 6,
  136346. 1,
  136347. 7,
  136348. 0,
  136349. 8,
  136350. };
  136351. static long _vq_lengthlist__44c0_s_p3_0[] = {
  136352. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  136353. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  136354. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  136355. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  136356. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136357. 0,
  136358. };
  136359. static float _vq_quantthresh__44c0_s_p3_0[] = {
  136360. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136361. };
  136362. static long _vq_quantmap__44c0_s_p3_0[] = {
  136363. 7, 5, 3, 1, 0, 2, 4, 6,
  136364. 8,
  136365. };
  136366. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  136367. _vq_quantthresh__44c0_s_p3_0,
  136368. _vq_quantmap__44c0_s_p3_0,
  136369. 9,
  136370. 9
  136371. };
  136372. static static_codebook _44c0_s_p3_0 = {
  136373. 2, 81,
  136374. _vq_lengthlist__44c0_s_p3_0,
  136375. 1, -531628032, 1611661312, 4, 0,
  136376. _vq_quantlist__44c0_s_p3_0,
  136377. NULL,
  136378. &_vq_auxt__44c0_s_p3_0,
  136379. NULL,
  136380. 0
  136381. };
  136382. static long _vq_quantlist__44c0_s_p4_0[] = {
  136383. 4,
  136384. 3,
  136385. 5,
  136386. 2,
  136387. 6,
  136388. 1,
  136389. 7,
  136390. 0,
  136391. 8,
  136392. };
  136393. static long _vq_lengthlist__44c0_s_p4_0[] = {
  136394. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  136395. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  136396. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  136397. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  136398. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  136399. 10,
  136400. };
  136401. static float _vq_quantthresh__44c0_s_p4_0[] = {
  136402. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136403. };
  136404. static long _vq_quantmap__44c0_s_p4_0[] = {
  136405. 7, 5, 3, 1, 0, 2, 4, 6,
  136406. 8,
  136407. };
  136408. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  136409. _vq_quantthresh__44c0_s_p4_0,
  136410. _vq_quantmap__44c0_s_p4_0,
  136411. 9,
  136412. 9
  136413. };
  136414. static static_codebook _44c0_s_p4_0 = {
  136415. 2, 81,
  136416. _vq_lengthlist__44c0_s_p4_0,
  136417. 1, -531628032, 1611661312, 4, 0,
  136418. _vq_quantlist__44c0_s_p4_0,
  136419. NULL,
  136420. &_vq_auxt__44c0_s_p4_0,
  136421. NULL,
  136422. 0
  136423. };
  136424. static long _vq_quantlist__44c0_s_p5_0[] = {
  136425. 8,
  136426. 7,
  136427. 9,
  136428. 6,
  136429. 10,
  136430. 5,
  136431. 11,
  136432. 4,
  136433. 12,
  136434. 3,
  136435. 13,
  136436. 2,
  136437. 14,
  136438. 1,
  136439. 15,
  136440. 0,
  136441. 16,
  136442. };
  136443. static long _vq_lengthlist__44c0_s_p5_0[] = {
  136444. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  136445. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  136446. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  136447. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  136448. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  136449. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  136450. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  136451. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  136452. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  136453. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  136454. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  136455. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  136456. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  136457. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  136458. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  136459. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  136460. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  136461. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  136462. 14,
  136463. };
  136464. static float _vq_quantthresh__44c0_s_p5_0[] = {
  136465. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136466. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136467. };
  136468. static long _vq_quantmap__44c0_s_p5_0[] = {
  136469. 15, 13, 11, 9, 7, 5, 3, 1,
  136470. 0, 2, 4, 6, 8, 10, 12, 14,
  136471. 16,
  136472. };
  136473. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  136474. _vq_quantthresh__44c0_s_p5_0,
  136475. _vq_quantmap__44c0_s_p5_0,
  136476. 17,
  136477. 17
  136478. };
  136479. static static_codebook _44c0_s_p5_0 = {
  136480. 2, 289,
  136481. _vq_lengthlist__44c0_s_p5_0,
  136482. 1, -529530880, 1611661312, 5, 0,
  136483. _vq_quantlist__44c0_s_p5_0,
  136484. NULL,
  136485. &_vq_auxt__44c0_s_p5_0,
  136486. NULL,
  136487. 0
  136488. };
  136489. static long _vq_quantlist__44c0_s_p6_0[] = {
  136490. 1,
  136491. 0,
  136492. 2,
  136493. };
  136494. static long _vq_lengthlist__44c0_s_p6_0[] = {
  136495. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  136496. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  136497. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  136498. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  136499. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  136500. 10,
  136501. };
  136502. static float _vq_quantthresh__44c0_s_p6_0[] = {
  136503. -5.5, 5.5,
  136504. };
  136505. static long _vq_quantmap__44c0_s_p6_0[] = {
  136506. 1, 0, 2,
  136507. };
  136508. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  136509. _vq_quantthresh__44c0_s_p6_0,
  136510. _vq_quantmap__44c0_s_p6_0,
  136511. 3,
  136512. 3
  136513. };
  136514. static static_codebook _44c0_s_p6_0 = {
  136515. 4, 81,
  136516. _vq_lengthlist__44c0_s_p6_0,
  136517. 1, -529137664, 1618345984, 2, 0,
  136518. _vq_quantlist__44c0_s_p6_0,
  136519. NULL,
  136520. &_vq_auxt__44c0_s_p6_0,
  136521. NULL,
  136522. 0
  136523. };
  136524. static long _vq_quantlist__44c0_s_p6_1[] = {
  136525. 5,
  136526. 4,
  136527. 6,
  136528. 3,
  136529. 7,
  136530. 2,
  136531. 8,
  136532. 1,
  136533. 9,
  136534. 0,
  136535. 10,
  136536. };
  136537. static long _vq_lengthlist__44c0_s_p6_1[] = {
  136538. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  136539. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  136540. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  136541. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  136542. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  136543. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  136544. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  136545. 10,10,10, 8, 8, 8, 8, 8, 8,
  136546. };
  136547. static float _vq_quantthresh__44c0_s_p6_1[] = {
  136548. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  136549. 3.5, 4.5,
  136550. };
  136551. static long _vq_quantmap__44c0_s_p6_1[] = {
  136552. 9, 7, 5, 3, 1, 0, 2, 4,
  136553. 6, 8, 10,
  136554. };
  136555. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  136556. _vq_quantthresh__44c0_s_p6_1,
  136557. _vq_quantmap__44c0_s_p6_1,
  136558. 11,
  136559. 11
  136560. };
  136561. static static_codebook _44c0_s_p6_1 = {
  136562. 2, 121,
  136563. _vq_lengthlist__44c0_s_p6_1,
  136564. 1, -531365888, 1611661312, 4, 0,
  136565. _vq_quantlist__44c0_s_p6_1,
  136566. NULL,
  136567. &_vq_auxt__44c0_s_p6_1,
  136568. NULL,
  136569. 0
  136570. };
  136571. static long _vq_quantlist__44c0_s_p7_0[] = {
  136572. 6,
  136573. 5,
  136574. 7,
  136575. 4,
  136576. 8,
  136577. 3,
  136578. 9,
  136579. 2,
  136580. 10,
  136581. 1,
  136582. 11,
  136583. 0,
  136584. 12,
  136585. };
  136586. static long _vq_lengthlist__44c0_s_p7_0[] = {
  136587. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  136588. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  136589. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  136590. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  136591. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  136592. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  136593. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  136594. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  136595. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  136596. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  136597. 0,12,12,11,11,12,12,13,13,
  136598. };
  136599. static float _vq_quantthresh__44c0_s_p7_0[] = {
  136600. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136601. 12.5, 17.5, 22.5, 27.5,
  136602. };
  136603. static long _vq_quantmap__44c0_s_p7_0[] = {
  136604. 11, 9, 7, 5, 3, 1, 0, 2,
  136605. 4, 6, 8, 10, 12,
  136606. };
  136607. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  136608. _vq_quantthresh__44c0_s_p7_0,
  136609. _vq_quantmap__44c0_s_p7_0,
  136610. 13,
  136611. 13
  136612. };
  136613. static static_codebook _44c0_s_p7_0 = {
  136614. 2, 169,
  136615. _vq_lengthlist__44c0_s_p7_0,
  136616. 1, -526516224, 1616117760, 4, 0,
  136617. _vq_quantlist__44c0_s_p7_0,
  136618. NULL,
  136619. &_vq_auxt__44c0_s_p7_0,
  136620. NULL,
  136621. 0
  136622. };
  136623. static long _vq_quantlist__44c0_s_p7_1[] = {
  136624. 2,
  136625. 1,
  136626. 3,
  136627. 0,
  136628. 4,
  136629. };
  136630. static long _vq_lengthlist__44c0_s_p7_1[] = {
  136631. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  136632. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  136633. };
  136634. static float _vq_quantthresh__44c0_s_p7_1[] = {
  136635. -1.5, -0.5, 0.5, 1.5,
  136636. };
  136637. static long _vq_quantmap__44c0_s_p7_1[] = {
  136638. 3, 1, 0, 2, 4,
  136639. };
  136640. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  136641. _vq_quantthresh__44c0_s_p7_1,
  136642. _vq_quantmap__44c0_s_p7_1,
  136643. 5,
  136644. 5
  136645. };
  136646. static static_codebook _44c0_s_p7_1 = {
  136647. 2, 25,
  136648. _vq_lengthlist__44c0_s_p7_1,
  136649. 1, -533725184, 1611661312, 3, 0,
  136650. _vq_quantlist__44c0_s_p7_1,
  136651. NULL,
  136652. &_vq_auxt__44c0_s_p7_1,
  136653. NULL,
  136654. 0
  136655. };
  136656. static long _vq_quantlist__44c0_s_p8_0[] = {
  136657. 2,
  136658. 1,
  136659. 3,
  136660. 0,
  136661. 4,
  136662. };
  136663. static long _vq_lengthlist__44c0_s_p8_0[] = {
  136664. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  136665. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136666. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136667. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136668. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136669. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136670. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136671. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  136672. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136673. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136674. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136675. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136676. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  136677. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136678. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136679. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  136680. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136681. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136682. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136683. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136684. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136685. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136686. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136687. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136688. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136689. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136690. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136691. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136692. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136693. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136694. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136695. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136696. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136697. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136698. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136699. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136700. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136701. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136702. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136703. 11,
  136704. };
  136705. static float _vq_quantthresh__44c0_s_p8_0[] = {
  136706. -331.5, -110.5, 110.5, 331.5,
  136707. };
  136708. static long _vq_quantmap__44c0_s_p8_0[] = {
  136709. 3, 1, 0, 2, 4,
  136710. };
  136711. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  136712. _vq_quantthresh__44c0_s_p8_0,
  136713. _vq_quantmap__44c0_s_p8_0,
  136714. 5,
  136715. 5
  136716. };
  136717. static static_codebook _44c0_s_p8_0 = {
  136718. 4, 625,
  136719. _vq_lengthlist__44c0_s_p8_0,
  136720. 1, -518283264, 1627103232, 3, 0,
  136721. _vq_quantlist__44c0_s_p8_0,
  136722. NULL,
  136723. &_vq_auxt__44c0_s_p8_0,
  136724. NULL,
  136725. 0
  136726. };
  136727. static long _vq_quantlist__44c0_s_p8_1[] = {
  136728. 6,
  136729. 5,
  136730. 7,
  136731. 4,
  136732. 8,
  136733. 3,
  136734. 9,
  136735. 2,
  136736. 10,
  136737. 1,
  136738. 11,
  136739. 0,
  136740. 12,
  136741. };
  136742. static long _vq_lengthlist__44c0_s_p8_1[] = {
  136743. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  136744. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  136745. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  136746. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  136747. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  136748. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  136749. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  136750. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  136751. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  136752. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  136753. 16,13,13,12,12,14,14,15,13,
  136754. };
  136755. static float _vq_quantthresh__44c0_s_p8_1[] = {
  136756. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  136757. 42.5, 59.5, 76.5, 93.5,
  136758. };
  136759. static long _vq_quantmap__44c0_s_p8_1[] = {
  136760. 11, 9, 7, 5, 3, 1, 0, 2,
  136761. 4, 6, 8, 10, 12,
  136762. };
  136763. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  136764. _vq_quantthresh__44c0_s_p8_1,
  136765. _vq_quantmap__44c0_s_p8_1,
  136766. 13,
  136767. 13
  136768. };
  136769. static static_codebook _44c0_s_p8_1 = {
  136770. 2, 169,
  136771. _vq_lengthlist__44c0_s_p8_1,
  136772. 1, -522616832, 1620115456, 4, 0,
  136773. _vq_quantlist__44c0_s_p8_1,
  136774. NULL,
  136775. &_vq_auxt__44c0_s_p8_1,
  136776. NULL,
  136777. 0
  136778. };
  136779. static long _vq_quantlist__44c0_s_p8_2[] = {
  136780. 8,
  136781. 7,
  136782. 9,
  136783. 6,
  136784. 10,
  136785. 5,
  136786. 11,
  136787. 4,
  136788. 12,
  136789. 3,
  136790. 13,
  136791. 2,
  136792. 14,
  136793. 1,
  136794. 15,
  136795. 0,
  136796. 16,
  136797. };
  136798. static long _vq_lengthlist__44c0_s_p8_2[] = {
  136799. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  136800. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  136801. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  136802. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  136803. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  136804. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  136805. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  136806. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  136807. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  136808. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  136809. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  136810. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  136811. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  136812. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  136813. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  136814. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  136815. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  136816. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  136817. 10,
  136818. };
  136819. static float _vq_quantthresh__44c0_s_p8_2[] = {
  136820. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136821. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136822. };
  136823. static long _vq_quantmap__44c0_s_p8_2[] = {
  136824. 15, 13, 11, 9, 7, 5, 3, 1,
  136825. 0, 2, 4, 6, 8, 10, 12, 14,
  136826. 16,
  136827. };
  136828. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  136829. _vq_quantthresh__44c0_s_p8_2,
  136830. _vq_quantmap__44c0_s_p8_2,
  136831. 17,
  136832. 17
  136833. };
  136834. static static_codebook _44c0_s_p8_2 = {
  136835. 2, 289,
  136836. _vq_lengthlist__44c0_s_p8_2,
  136837. 1, -529530880, 1611661312, 5, 0,
  136838. _vq_quantlist__44c0_s_p8_2,
  136839. NULL,
  136840. &_vq_auxt__44c0_s_p8_2,
  136841. NULL,
  136842. 0
  136843. };
  136844. static long _huff_lengthlist__44c0_s_short[] = {
  136845. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  136846. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  136847. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  136848. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  136849. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  136850. 12,
  136851. };
  136852. static static_codebook _huff_book__44c0_s_short = {
  136853. 2, 81,
  136854. _huff_lengthlist__44c0_s_short,
  136855. 0, 0, 0, 0, 0,
  136856. NULL,
  136857. NULL,
  136858. NULL,
  136859. NULL,
  136860. 0
  136861. };
  136862. static long _huff_lengthlist__44c0_sm_long[] = {
  136863. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  136864. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  136865. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  136866. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  136867. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  136868. 13,
  136869. };
  136870. static static_codebook _huff_book__44c0_sm_long = {
  136871. 2, 81,
  136872. _huff_lengthlist__44c0_sm_long,
  136873. 0, 0, 0, 0, 0,
  136874. NULL,
  136875. NULL,
  136876. NULL,
  136877. NULL,
  136878. 0
  136879. };
  136880. static long _vq_quantlist__44c0_sm_p1_0[] = {
  136881. 1,
  136882. 0,
  136883. 2,
  136884. };
  136885. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  136886. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  136887. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136891. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136892. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136896. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  136897. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  136932. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  136937. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  136942. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  136943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136977. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136978. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  136983. 0, 0, 0, 0, 0, 9, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  136988. 0, 0, 0, 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 0,
  136989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137166. 0, 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,
  137297. };
  137298. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  137299. -0.5, 0.5,
  137300. };
  137301. static long _vq_quantmap__44c0_sm_p1_0[] = {
  137302. 1, 0, 2,
  137303. };
  137304. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  137305. _vq_quantthresh__44c0_sm_p1_0,
  137306. _vq_quantmap__44c0_sm_p1_0,
  137307. 3,
  137308. 3
  137309. };
  137310. static static_codebook _44c0_sm_p1_0 = {
  137311. 8, 6561,
  137312. _vq_lengthlist__44c0_sm_p1_0,
  137313. 1, -535822336, 1611661312, 2, 0,
  137314. _vq_quantlist__44c0_sm_p1_0,
  137315. NULL,
  137316. &_vq_auxt__44c0_sm_p1_0,
  137317. NULL,
  137318. 0
  137319. };
  137320. static long _vq_quantlist__44c0_sm_p2_0[] = {
  137321. 2,
  137322. 1,
  137323. 3,
  137324. 0,
  137325. 4,
  137326. };
  137327. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  137328. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  137330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137331. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  137333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137334. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  137335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137341. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137343. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137367. 0,
  137368. };
  137369. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  137370. -1.5, -0.5, 0.5, 1.5,
  137371. };
  137372. static long _vq_quantmap__44c0_sm_p2_0[] = {
  137373. 3, 1, 0, 2, 4,
  137374. };
  137375. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  137376. _vq_quantthresh__44c0_sm_p2_0,
  137377. _vq_quantmap__44c0_sm_p2_0,
  137378. 5,
  137379. 5
  137380. };
  137381. static static_codebook _44c0_sm_p2_0 = {
  137382. 4, 625,
  137383. _vq_lengthlist__44c0_sm_p2_0,
  137384. 1, -533725184, 1611661312, 3, 0,
  137385. _vq_quantlist__44c0_sm_p2_0,
  137386. NULL,
  137387. &_vq_auxt__44c0_sm_p2_0,
  137388. NULL,
  137389. 0
  137390. };
  137391. static long _vq_quantlist__44c0_sm_p3_0[] = {
  137392. 4,
  137393. 3,
  137394. 5,
  137395. 2,
  137396. 6,
  137397. 1,
  137398. 7,
  137399. 0,
  137400. 8,
  137401. };
  137402. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  137403. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  137404. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  137405. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  137406. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  137407. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137408. 0,
  137409. };
  137410. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  137411. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137412. };
  137413. static long _vq_quantmap__44c0_sm_p3_0[] = {
  137414. 7, 5, 3, 1, 0, 2, 4, 6,
  137415. 8,
  137416. };
  137417. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  137418. _vq_quantthresh__44c0_sm_p3_0,
  137419. _vq_quantmap__44c0_sm_p3_0,
  137420. 9,
  137421. 9
  137422. };
  137423. static static_codebook _44c0_sm_p3_0 = {
  137424. 2, 81,
  137425. _vq_lengthlist__44c0_sm_p3_0,
  137426. 1, -531628032, 1611661312, 4, 0,
  137427. _vq_quantlist__44c0_sm_p3_0,
  137428. NULL,
  137429. &_vq_auxt__44c0_sm_p3_0,
  137430. NULL,
  137431. 0
  137432. };
  137433. static long _vq_quantlist__44c0_sm_p4_0[] = {
  137434. 4,
  137435. 3,
  137436. 5,
  137437. 2,
  137438. 6,
  137439. 1,
  137440. 7,
  137441. 0,
  137442. 8,
  137443. };
  137444. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  137445. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  137446. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  137447. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  137448. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  137449. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  137450. 11,
  137451. };
  137452. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  137453. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137454. };
  137455. static long _vq_quantmap__44c0_sm_p4_0[] = {
  137456. 7, 5, 3, 1, 0, 2, 4, 6,
  137457. 8,
  137458. };
  137459. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  137460. _vq_quantthresh__44c0_sm_p4_0,
  137461. _vq_quantmap__44c0_sm_p4_0,
  137462. 9,
  137463. 9
  137464. };
  137465. static static_codebook _44c0_sm_p4_0 = {
  137466. 2, 81,
  137467. _vq_lengthlist__44c0_sm_p4_0,
  137468. 1, -531628032, 1611661312, 4, 0,
  137469. _vq_quantlist__44c0_sm_p4_0,
  137470. NULL,
  137471. &_vq_auxt__44c0_sm_p4_0,
  137472. NULL,
  137473. 0
  137474. };
  137475. static long _vq_quantlist__44c0_sm_p5_0[] = {
  137476. 8,
  137477. 7,
  137478. 9,
  137479. 6,
  137480. 10,
  137481. 5,
  137482. 11,
  137483. 4,
  137484. 12,
  137485. 3,
  137486. 13,
  137487. 2,
  137488. 14,
  137489. 1,
  137490. 15,
  137491. 0,
  137492. 16,
  137493. };
  137494. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  137495. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  137496. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  137497. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  137498. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  137499. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  137500. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  137501. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  137502. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  137503. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  137504. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  137505. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  137506. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  137507. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  137508. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  137509. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  137510. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  137511. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  137512. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  137513. 14,
  137514. };
  137515. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  137516. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137517. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137518. };
  137519. static long _vq_quantmap__44c0_sm_p5_0[] = {
  137520. 15, 13, 11, 9, 7, 5, 3, 1,
  137521. 0, 2, 4, 6, 8, 10, 12, 14,
  137522. 16,
  137523. };
  137524. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  137525. _vq_quantthresh__44c0_sm_p5_0,
  137526. _vq_quantmap__44c0_sm_p5_0,
  137527. 17,
  137528. 17
  137529. };
  137530. static static_codebook _44c0_sm_p5_0 = {
  137531. 2, 289,
  137532. _vq_lengthlist__44c0_sm_p5_0,
  137533. 1, -529530880, 1611661312, 5, 0,
  137534. _vq_quantlist__44c0_sm_p5_0,
  137535. NULL,
  137536. &_vq_auxt__44c0_sm_p5_0,
  137537. NULL,
  137538. 0
  137539. };
  137540. static long _vq_quantlist__44c0_sm_p6_0[] = {
  137541. 1,
  137542. 0,
  137543. 2,
  137544. };
  137545. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  137546. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  137547. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  137548. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  137549. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  137550. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  137551. 11,
  137552. };
  137553. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  137554. -5.5, 5.5,
  137555. };
  137556. static long _vq_quantmap__44c0_sm_p6_0[] = {
  137557. 1, 0, 2,
  137558. };
  137559. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  137560. _vq_quantthresh__44c0_sm_p6_0,
  137561. _vq_quantmap__44c0_sm_p6_0,
  137562. 3,
  137563. 3
  137564. };
  137565. static static_codebook _44c0_sm_p6_0 = {
  137566. 4, 81,
  137567. _vq_lengthlist__44c0_sm_p6_0,
  137568. 1, -529137664, 1618345984, 2, 0,
  137569. _vq_quantlist__44c0_sm_p6_0,
  137570. NULL,
  137571. &_vq_auxt__44c0_sm_p6_0,
  137572. NULL,
  137573. 0
  137574. };
  137575. static long _vq_quantlist__44c0_sm_p6_1[] = {
  137576. 5,
  137577. 4,
  137578. 6,
  137579. 3,
  137580. 7,
  137581. 2,
  137582. 8,
  137583. 1,
  137584. 9,
  137585. 0,
  137586. 10,
  137587. };
  137588. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  137589. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  137590. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  137591. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  137592. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  137593. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  137594. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  137595. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  137596. 10,10,10, 8, 8, 8, 8, 8, 8,
  137597. };
  137598. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  137599. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137600. 3.5, 4.5,
  137601. };
  137602. static long _vq_quantmap__44c0_sm_p6_1[] = {
  137603. 9, 7, 5, 3, 1, 0, 2, 4,
  137604. 6, 8, 10,
  137605. };
  137606. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  137607. _vq_quantthresh__44c0_sm_p6_1,
  137608. _vq_quantmap__44c0_sm_p6_1,
  137609. 11,
  137610. 11
  137611. };
  137612. static static_codebook _44c0_sm_p6_1 = {
  137613. 2, 121,
  137614. _vq_lengthlist__44c0_sm_p6_1,
  137615. 1, -531365888, 1611661312, 4, 0,
  137616. _vq_quantlist__44c0_sm_p6_1,
  137617. NULL,
  137618. &_vq_auxt__44c0_sm_p6_1,
  137619. NULL,
  137620. 0
  137621. };
  137622. static long _vq_quantlist__44c0_sm_p7_0[] = {
  137623. 6,
  137624. 5,
  137625. 7,
  137626. 4,
  137627. 8,
  137628. 3,
  137629. 9,
  137630. 2,
  137631. 10,
  137632. 1,
  137633. 11,
  137634. 0,
  137635. 12,
  137636. };
  137637. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  137638. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  137639. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  137640. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  137641. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  137642. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  137643. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  137644. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  137645. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  137646. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  137647. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  137648. 0,12,12,11,11,13,12,14,14,
  137649. };
  137650. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  137651. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137652. 12.5, 17.5, 22.5, 27.5,
  137653. };
  137654. static long _vq_quantmap__44c0_sm_p7_0[] = {
  137655. 11, 9, 7, 5, 3, 1, 0, 2,
  137656. 4, 6, 8, 10, 12,
  137657. };
  137658. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  137659. _vq_quantthresh__44c0_sm_p7_0,
  137660. _vq_quantmap__44c0_sm_p7_0,
  137661. 13,
  137662. 13
  137663. };
  137664. static static_codebook _44c0_sm_p7_0 = {
  137665. 2, 169,
  137666. _vq_lengthlist__44c0_sm_p7_0,
  137667. 1, -526516224, 1616117760, 4, 0,
  137668. _vq_quantlist__44c0_sm_p7_0,
  137669. NULL,
  137670. &_vq_auxt__44c0_sm_p7_0,
  137671. NULL,
  137672. 0
  137673. };
  137674. static long _vq_quantlist__44c0_sm_p7_1[] = {
  137675. 2,
  137676. 1,
  137677. 3,
  137678. 0,
  137679. 4,
  137680. };
  137681. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  137682. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  137683. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  137684. };
  137685. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  137686. -1.5, -0.5, 0.5, 1.5,
  137687. };
  137688. static long _vq_quantmap__44c0_sm_p7_1[] = {
  137689. 3, 1, 0, 2, 4,
  137690. };
  137691. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  137692. _vq_quantthresh__44c0_sm_p7_1,
  137693. _vq_quantmap__44c0_sm_p7_1,
  137694. 5,
  137695. 5
  137696. };
  137697. static static_codebook _44c0_sm_p7_1 = {
  137698. 2, 25,
  137699. _vq_lengthlist__44c0_sm_p7_1,
  137700. 1, -533725184, 1611661312, 3, 0,
  137701. _vq_quantlist__44c0_sm_p7_1,
  137702. NULL,
  137703. &_vq_auxt__44c0_sm_p7_1,
  137704. NULL,
  137705. 0
  137706. };
  137707. static long _vq_quantlist__44c0_sm_p8_0[] = {
  137708. 4,
  137709. 3,
  137710. 5,
  137711. 2,
  137712. 6,
  137713. 1,
  137714. 7,
  137715. 0,
  137716. 8,
  137717. };
  137718. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  137719. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  137720. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  137721. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137722. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137723. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137724. 12,
  137725. };
  137726. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  137727. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  137728. };
  137729. static long _vq_quantmap__44c0_sm_p8_0[] = {
  137730. 7, 5, 3, 1, 0, 2, 4, 6,
  137731. 8,
  137732. };
  137733. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  137734. _vq_quantthresh__44c0_sm_p8_0,
  137735. _vq_quantmap__44c0_sm_p8_0,
  137736. 9,
  137737. 9
  137738. };
  137739. static static_codebook _44c0_sm_p8_0 = {
  137740. 2, 81,
  137741. _vq_lengthlist__44c0_sm_p8_0,
  137742. 1, -516186112, 1627103232, 4, 0,
  137743. _vq_quantlist__44c0_sm_p8_0,
  137744. NULL,
  137745. &_vq_auxt__44c0_sm_p8_0,
  137746. NULL,
  137747. 0
  137748. };
  137749. static long _vq_quantlist__44c0_sm_p8_1[] = {
  137750. 6,
  137751. 5,
  137752. 7,
  137753. 4,
  137754. 8,
  137755. 3,
  137756. 9,
  137757. 2,
  137758. 10,
  137759. 1,
  137760. 11,
  137761. 0,
  137762. 12,
  137763. };
  137764. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  137765. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  137766. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  137767. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  137768. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  137769. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  137770. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  137771. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  137772. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  137773. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  137774. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  137775. 20,13,13,12,12,16,13,15,13,
  137776. };
  137777. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  137778. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  137779. 42.5, 59.5, 76.5, 93.5,
  137780. };
  137781. static long _vq_quantmap__44c0_sm_p8_1[] = {
  137782. 11, 9, 7, 5, 3, 1, 0, 2,
  137783. 4, 6, 8, 10, 12,
  137784. };
  137785. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  137786. _vq_quantthresh__44c0_sm_p8_1,
  137787. _vq_quantmap__44c0_sm_p8_1,
  137788. 13,
  137789. 13
  137790. };
  137791. static static_codebook _44c0_sm_p8_1 = {
  137792. 2, 169,
  137793. _vq_lengthlist__44c0_sm_p8_1,
  137794. 1, -522616832, 1620115456, 4, 0,
  137795. _vq_quantlist__44c0_sm_p8_1,
  137796. NULL,
  137797. &_vq_auxt__44c0_sm_p8_1,
  137798. NULL,
  137799. 0
  137800. };
  137801. static long _vq_quantlist__44c0_sm_p8_2[] = {
  137802. 8,
  137803. 7,
  137804. 9,
  137805. 6,
  137806. 10,
  137807. 5,
  137808. 11,
  137809. 4,
  137810. 12,
  137811. 3,
  137812. 13,
  137813. 2,
  137814. 14,
  137815. 1,
  137816. 15,
  137817. 0,
  137818. 16,
  137819. };
  137820. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  137821. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  137822. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  137823. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  137824. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  137825. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  137826. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  137827. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  137828. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  137829. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  137830. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  137831. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  137832. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  137833. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  137834. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  137835. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  137836. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  137837. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  137838. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  137839. 9,
  137840. };
  137841. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  137842. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137843. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137844. };
  137845. static long _vq_quantmap__44c0_sm_p8_2[] = {
  137846. 15, 13, 11, 9, 7, 5, 3, 1,
  137847. 0, 2, 4, 6, 8, 10, 12, 14,
  137848. 16,
  137849. };
  137850. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  137851. _vq_quantthresh__44c0_sm_p8_2,
  137852. _vq_quantmap__44c0_sm_p8_2,
  137853. 17,
  137854. 17
  137855. };
  137856. static static_codebook _44c0_sm_p8_2 = {
  137857. 2, 289,
  137858. _vq_lengthlist__44c0_sm_p8_2,
  137859. 1, -529530880, 1611661312, 5, 0,
  137860. _vq_quantlist__44c0_sm_p8_2,
  137861. NULL,
  137862. &_vq_auxt__44c0_sm_p8_2,
  137863. NULL,
  137864. 0
  137865. };
  137866. static long _huff_lengthlist__44c0_sm_short[] = {
  137867. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  137868. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  137869. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  137870. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  137871. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  137872. 12,
  137873. };
  137874. static static_codebook _huff_book__44c0_sm_short = {
  137875. 2, 81,
  137876. _huff_lengthlist__44c0_sm_short,
  137877. 0, 0, 0, 0, 0,
  137878. NULL,
  137879. NULL,
  137880. NULL,
  137881. NULL,
  137882. 0
  137883. };
  137884. static long _huff_lengthlist__44c1_s_long[] = {
  137885. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  137886. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  137887. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  137888. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  137889. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  137890. 11,
  137891. };
  137892. static static_codebook _huff_book__44c1_s_long = {
  137893. 2, 81,
  137894. _huff_lengthlist__44c1_s_long,
  137895. 0, 0, 0, 0, 0,
  137896. NULL,
  137897. NULL,
  137898. NULL,
  137899. NULL,
  137900. 0
  137901. };
  137902. static long _vq_quantlist__44c1_s_p1_0[] = {
  137903. 1,
  137904. 0,
  137905. 2,
  137906. };
  137907. static long _vq_lengthlist__44c1_s_p1_0[] = {
  137908. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  137909. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137913. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  137914. 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137918. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  137919. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137935. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137940. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137945. 0, 0, 0, 0, 0, 0, 0, 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, 4, 7, 7, 0, 0, 0, 0,
  137954. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  137959. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  137964. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 0, 0, 0, 0, 0, 0, 0,
  137980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  137985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  137990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137993. 0, 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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  138000. 0, 0, 0, 0, 7, 8, 9, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  138005. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  138010. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  138011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  138319. };
  138320. static float _vq_quantthresh__44c1_s_p1_0[] = {
  138321. -0.5, 0.5,
  138322. };
  138323. static long _vq_quantmap__44c1_s_p1_0[] = {
  138324. 1, 0, 2,
  138325. };
  138326. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  138327. _vq_quantthresh__44c1_s_p1_0,
  138328. _vq_quantmap__44c1_s_p1_0,
  138329. 3,
  138330. 3
  138331. };
  138332. static static_codebook _44c1_s_p1_0 = {
  138333. 8, 6561,
  138334. _vq_lengthlist__44c1_s_p1_0,
  138335. 1, -535822336, 1611661312, 2, 0,
  138336. _vq_quantlist__44c1_s_p1_0,
  138337. NULL,
  138338. &_vq_auxt__44c1_s_p1_0,
  138339. NULL,
  138340. 0
  138341. };
  138342. static long _vq_quantlist__44c1_s_p2_0[] = {
  138343. 2,
  138344. 1,
  138345. 3,
  138346. 0,
  138347. 4,
  138348. };
  138349. static long _vq_lengthlist__44c1_s_p2_0[] = {
  138350. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  138352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138353. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  138355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138356. 0, 0, 0, 0, 6, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  138357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138389. 0,
  138390. };
  138391. static float _vq_quantthresh__44c1_s_p2_0[] = {
  138392. -1.5, -0.5, 0.5, 1.5,
  138393. };
  138394. static long _vq_quantmap__44c1_s_p2_0[] = {
  138395. 3, 1, 0, 2, 4,
  138396. };
  138397. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  138398. _vq_quantthresh__44c1_s_p2_0,
  138399. _vq_quantmap__44c1_s_p2_0,
  138400. 5,
  138401. 5
  138402. };
  138403. static static_codebook _44c1_s_p2_0 = {
  138404. 4, 625,
  138405. _vq_lengthlist__44c1_s_p2_0,
  138406. 1, -533725184, 1611661312, 3, 0,
  138407. _vq_quantlist__44c1_s_p2_0,
  138408. NULL,
  138409. &_vq_auxt__44c1_s_p2_0,
  138410. NULL,
  138411. 0
  138412. };
  138413. static long _vq_quantlist__44c1_s_p3_0[] = {
  138414. 4,
  138415. 3,
  138416. 5,
  138417. 2,
  138418. 6,
  138419. 1,
  138420. 7,
  138421. 0,
  138422. 8,
  138423. };
  138424. static long _vq_lengthlist__44c1_s_p3_0[] = {
  138425. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  138426. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  138427. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  138428. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  138429. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138430. 0,
  138431. };
  138432. static float _vq_quantthresh__44c1_s_p3_0[] = {
  138433. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138434. };
  138435. static long _vq_quantmap__44c1_s_p3_0[] = {
  138436. 7, 5, 3, 1, 0, 2, 4, 6,
  138437. 8,
  138438. };
  138439. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  138440. _vq_quantthresh__44c1_s_p3_0,
  138441. _vq_quantmap__44c1_s_p3_0,
  138442. 9,
  138443. 9
  138444. };
  138445. static static_codebook _44c1_s_p3_0 = {
  138446. 2, 81,
  138447. _vq_lengthlist__44c1_s_p3_0,
  138448. 1, -531628032, 1611661312, 4, 0,
  138449. _vq_quantlist__44c1_s_p3_0,
  138450. NULL,
  138451. &_vq_auxt__44c1_s_p3_0,
  138452. NULL,
  138453. 0
  138454. };
  138455. static long _vq_quantlist__44c1_s_p4_0[] = {
  138456. 4,
  138457. 3,
  138458. 5,
  138459. 2,
  138460. 6,
  138461. 1,
  138462. 7,
  138463. 0,
  138464. 8,
  138465. };
  138466. static long _vq_lengthlist__44c1_s_p4_0[] = {
  138467. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  138468. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  138469. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  138470. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  138471. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  138472. 11,
  138473. };
  138474. static float _vq_quantthresh__44c1_s_p4_0[] = {
  138475. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138476. };
  138477. static long _vq_quantmap__44c1_s_p4_0[] = {
  138478. 7, 5, 3, 1, 0, 2, 4, 6,
  138479. 8,
  138480. };
  138481. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  138482. _vq_quantthresh__44c1_s_p4_0,
  138483. _vq_quantmap__44c1_s_p4_0,
  138484. 9,
  138485. 9
  138486. };
  138487. static static_codebook _44c1_s_p4_0 = {
  138488. 2, 81,
  138489. _vq_lengthlist__44c1_s_p4_0,
  138490. 1, -531628032, 1611661312, 4, 0,
  138491. _vq_quantlist__44c1_s_p4_0,
  138492. NULL,
  138493. &_vq_auxt__44c1_s_p4_0,
  138494. NULL,
  138495. 0
  138496. };
  138497. static long _vq_quantlist__44c1_s_p5_0[] = {
  138498. 8,
  138499. 7,
  138500. 9,
  138501. 6,
  138502. 10,
  138503. 5,
  138504. 11,
  138505. 4,
  138506. 12,
  138507. 3,
  138508. 13,
  138509. 2,
  138510. 14,
  138511. 1,
  138512. 15,
  138513. 0,
  138514. 16,
  138515. };
  138516. static long _vq_lengthlist__44c1_s_p5_0[] = {
  138517. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  138518. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  138519. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  138520. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  138521. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  138522. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  138523. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  138524. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  138525. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  138526. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  138527. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  138528. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  138529. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  138530. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  138531. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  138532. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  138533. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  138534. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  138535. 14,
  138536. };
  138537. static float _vq_quantthresh__44c1_s_p5_0[] = {
  138538. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138539. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138540. };
  138541. static long _vq_quantmap__44c1_s_p5_0[] = {
  138542. 15, 13, 11, 9, 7, 5, 3, 1,
  138543. 0, 2, 4, 6, 8, 10, 12, 14,
  138544. 16,
  138545. };
  138546. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  138547. _vq_quantthresh__44c1_s_p5_0,
  138548. _vq_quantmap__44c1_s_p5_0,
  138549. 17,
  138550. 17
  138551. };
  138552. static static_codebook _44c1_s_p5_0 = {
  138553. 2, 289,
  138554. _vq_lengthlist__44c1_s_p5_0,
  138555. 1, -529530880, 1611661312, 5, 0,
  138556. _vq_quantlist__44c1_s_p5_0,
  138557. NULL,
  138558. &_vq_auxt__44c1_s_p5_0,
  138559. NULL,
  138560. 0
  138561. };
  138562. static long _vq_quantlist__44c1_s_p6_0[] = {
  138563. 1,
  138564. 0,
  138565. 2,
  138566. };
  138567. static long _vq_lengthlist__44c1_s_p6_0[] = {
  138568. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  138569. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  138570. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  138571. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  138572. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  138573. 11,
  138574. };
  138575. static float _vq_quantthresh__44c1_s_p6_0[] = {
  138576. -5.5, 5.5,
  138577. };
  138578. static long _vq_quantmap__44c1_s_p6_0[] = {
  138579. 1, 0, 2,
  138580. };
  138581. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  138582. _vq_quantthresh__44c1_s_p6_0,
  138583. _vq_quantmap__44c1_s_p6_0,
  138584. 3,
  138585. 3
  138586. };
  138587. static static_codebook _44c1_s_p6_0 = {
  138588. 4, 81,
  138589. _vq_lengthlist__44c1_s_p6_0,
  138590. 1, -529137664, 1618345984, 2, 0,
  138591. _vq_quantlist__44c1_s_p6_0,
  138592. NULL,
  138593. &_vq_auxt__44c1_s_p6_0,
  138594. NULL,
  138595. 0
  138596. };
  138597. static long _vq_quantlist__44c1_s_p6_1[] = {
  138598. 5,
  138599. 4,
  138600. 6,
  138601. 3,
  138602. 7,
  138603. 2,
  138604. 8,
  138605. 1,
  138606. 9,
  138607. 0,
  138608. 10,
  138609. };
  138610. static long _vq_lengthlist__44c1_s_p6_1[] = {
  138611. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  138612. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  138613. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  138614. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  138615. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  138616. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  138617. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  138618. 10,10,10, 8, 8, 8, 8, 8, 8,
  138619. };
  138620. static float _vq_quantthresh__44c1_s_p6_1[] = {
  138621. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138622. 3.5, 4.5,
  138623. };
  138624. static long _vq_quantmap__44c1_s_p6_1[] = {
  138625. 9, 7, 5, 3, 1, 0, 2, 4,
  138626. 6, 8, 10,
  138627. };
  138628. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  138629. _vq_quantthresh__44c1_s_p6_1,
  138630. _vq_quantmap__44c1_s_p6_1,
  138631. 11,
  138632. 11
  138633. };
  138634. static static_codebook _44c1_s_p6_1 = {
  138635. 2, 121,
  138636. _vq_lengthlist__44c1_s_p6_1,
  138637. 1, -531365888, 1611661312, 4, 0,
  138638. _vq_quantlist__44c1_s_p6_1,
  138639. NULL,
  138640. &_vq_auxt__44c1_s_p6_1,
  138641. NULL,
  138642. 0
  138643. };
  138644. static long _vq_quantlist__44c1_s_p7_0[] = {
  138645. 6,
  138646. 5,
  138647. 7,
  138648. 4,
  138649. 8,
  138650. 3,
  138651. 9,
  138652. 2,
  138653. 10,
  138654. 1,
  138655. 11,
  138656. 0,
  138657. 12,
  138658. };
  138659. static long _vq_lengthlist__44c1_s_p7_0[] = {
  138660. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  138661. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  138662. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  138663. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  138664. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  138665. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  138666. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  138667. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  138668. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  138669. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  138670. 0,12,11,11,11,13,10,14,13,
  138671. };
  138672. static float _vq_quantthresh__44c1_s_p7_0[] = {
  138673. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138674. 12.5, 17.5, 22.5, 27.5,
  138675. };
  138676. static long _vq_quantmap__44c1_s_p7_0[] = {
  138677. 11, 9, 7, 5, 3, 1, 0, 2,
  138678. 4, 6, 8, 10, 12,
  138679. };
  138680. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  138681. _vq_quantthresh__44c1_s_p7_0,
  138682. _vq_quantmap__44c1_s_p7_0,
  138683. 13,
  138684. 13
  138685. };
  138686. static static_codebook _44c1_s_p7_0 = {
  138687. 2, 169,
  138688. _vq_lengthlist__44c1_s_p7_0,
  138689. 1, -526516224, 1616117760, 4, 0,
  138690. _vq_quantlist__44c1_s_p7_0,
  138691. NULL,
  138692. &_vq_auxt__44c1_s_p7_0,
  138693. NULL,
  138694. 0
  138695. };
  138696. static long _vq_quantlist__44c1_s_p7_1[] = {
  138697. 2,
  138698. 1,
  138699. 3,
  138700. 0,
  138701. 4,
  138702. };
  138703. static long _vq_lengthlist__44c1_s_p7_1[] = {
  138704. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  138705. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  138706. };
  138707. static float _vq_quantthresh__44c1_s_p7_1[] = {
  138708. -1.5, -0.5, 0.5, 1.5,
  138709. };
  138710. static long _vq_quantmap__44c1_s_p7_1[] = {
  138711. 3, 1, 0, 2, 4,
  138712. };
  138713. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  138714. _vq_quantthresh__44c1_s_p7_1,
  138715. _vq_quantmap__44c1_s_p7_1,
  138716. 5,
  138717. 5
  138718. };
  138719. static static_codebook _44c1_s_p7_1 = {
  138720. 2, 25,
  138721. _vq_lengthlist__44c1_s_p7_1,
  138722. 1, -533725184, 1611661312, 3, 0,
  138723. _vq_quantlist__44c1_s_p7_1,
  138724. NULL,
  138725. &_vq_auxt__44c1_s_p7_1,
  138726. NULL,
  138727. 0
  138728. };
  138729. static long _vq_quantlist__44c1_s_p8_0[] = {
  138730. 6,
  138731. 5,
  138732. 7,
  138733. 4,
  138734. 8,
  138735. 3,
  138736. 9,
  138737. 2,
  138738. 10,
  138739. 1,
  138740. 11,
  138741. 0,
  138742. 12,
  138743. };
  138744. static long _vq_lengthlist__44c1_s_p8_0[] = {
  138745. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  138746. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  138747. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138748. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138749. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138750. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138751. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138752. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138753. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138754. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138755. 10,10,10,10,10,10,10,10,10,
  138756. };
  138757. static float _vq_quantthresh__44c1_s_p8_0[] = {
  138758. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  138759. 552.5, 773.5, 994.5, 1215.5,
  138760. };
  138761. static long _vq_quantmap__44c1_s_p8_0[] = {
  138762. 11, 9, 7, 5, 3, 1, 0, 2,
  138763. 4, 6, 8, 10, 12,
  138764. };
  138765. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  138766. _vq_quantthresh__44c1_s_p8_0,
  138767. _vq_quantmap__44c1_s_p8_0,
  138768. 13,
  138769. 13
  138770. };
  138771. static static_codebook _44c1_s_p8_0 = {
  138772. 2, 169,
  138773. _vq_lengthlist__44c1_s_p8_0,
  138774. 1, -514541568, 1627103232, 4, 0,
  138775. _vq_quantlist__44c1_s_p8_0,
  138776. NULL,
  138777. &_vq_auxt__44c1_s_p8_0,
  138778. NULL,
  138779. 0
  138780. };
  138781. static long _vq_quantlist__44c1_s_p8_1[] = {
  138782. 6,
  138783. 5,
  138784. 7,
  138785. 4,
  138786. 8,
  138787. 3,
  138788. 9,
  138789. 2,
  138790. 10,
  138791. 1,
  138792. 11,
  138793. 0,
  138794. 12,
  138795. };
  138796. static long _vq_lengthlist__44c1_s_p8_1[] = {
  138797. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  138798. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  138799. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  138800. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  138801. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  138802. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  138803. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  138804. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  138805. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  138806. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  138807. 16,13,12,12,11,14,12,15,13,
  138808. };
  138809. static float _vq_quantthresh__44c1_s_p8_1[] = {
  138810. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  138811. 42.5, 59.5, 76.5, 93.5,
  138812. };
  138813. static long _vq_quantmap__44c1_s_p8_1[] = {
  138814. 11, 9, 7, 5, 3, 1, 0, 2,
  138815. 4, 6, 8, 10, 12,
  138816. };
  138817. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  138818. _vq_quantthresh__44c1_s_p8_1,
  138819. _vq_quantmap__44c1_s_p8_1,
  138820. 13,
  138821. 13
  138822. };
  138823. static static_codebook _44c1_s_p8_1 = {
  138824. 2, 169,
  138825. _vq_lengthlist__44c1_s_p8_1,
  138826. 1, -522616832, 1620115456, 4, 0,
  138827. _vq_quantlist__44c1_s_p8_1,
  138828. NULL,
  138829. &_vq_auxt__44c1_s_p8_1,
  138830. NULL,
  138831. 0
  138832. };
  138833. static long _vq_quantlist__44c1_s_p8_2[] = {
  138834. 8,
  138835. 7,
  138836. 9,
  138837. 6,
  138838. 10,
  138839. 5,
  138840. 11,
  138841. 4,
  138842. 12,
  138843. 3,
  138844. 13,
  138845. 2,
  138846. 14,
  138847. 1,
  138848. 15,
  138849. 0,
  138850. 16,
  138851. };
  138852. static long _vq_lengthlist__44c1_s_p8_2[] = {
  138853. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  138854. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  138855. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  138856. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  138857. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  138858. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  138859. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  138860. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  138861. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  138862. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  138863. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  138864. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  138865. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  138866. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  138867. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  138868. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  138869. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  138870. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  138871. 9,
  138872. };
  138873. static float _vq_quantthresh__44c1_s_p8_2[] = {
  138874. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138875. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138876. };
  138877. static long _vq_quantmap__44c1_s_p8_2[] = {
  138878. 15, 13, 11, 9, 7, 5, 3, 1,
  138879. 0, 2, 4, 6, 8, 10, 12, 14,
  138880. 16,
  138881. };
  138882. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  138883. _vq_quantthresh__44c1_s_p8_2,
  138884. _vq_quantmap__44c1_s_p8_2,
  138885. 17,
  138886. 17
  138887. };
  138888. static static_codebook _44c1_s_p8_2 = {
  138889. 2, 289,
  138890. _vq_lengthlist__44c1_s_p8_2,
  138891. 1, -529530880, 1611661312, 5, 0,
  138892. _vq_quantlist__44c1_s_p8_2,
  138893. NULL,
  138894. &_vq_auxt__44c1_s_p8_2,
  138895. NULL,
  138896. 0
  138897. };
  138898. static long _huff_lengthlist__44c1_s_short[] = {
  138899. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  138900. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  138901. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  138902. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  138903. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  138904. 11,
  138905. };
  138906. static static_codebook _huff_book__44c1_s_short = {
  138907. 2, 81,
  138908. _huff_lengthlist__44c1_s_short,
  138909. 0, 0, 0, 0, 0,
  138910. NULL,
  138911. NULL,
  138912. NULL,
  138913. NULL,
  138914. 0
  138915. };
  138916. static long _huff_lengthlist__44c1_sm_long[] = {
  138917. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  138918. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  138919. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  138920. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  138921. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  138922. 11,
  138923. };
  138924. static static_codebook _huff_book__44c1_sm_long = {
  138925. 2, 81,
  138926. _huff_lengthlist__44c1_sm_long,
  138927. 0, 0, 0, 0, 0,
  138928. NULL,
  138929. NULL,
  138930. NULL,
  138931. NULL,
  138932. 0
  138933. };
  138934. static long _vq_quantlist__44c1_sm_p1_0[] = {
  138935. 1,
  138936. 0,
  138937. 2,
  138938. };
  138939. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  138940. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  138941. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138945. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  138946. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138950. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  138951. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138967. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138972. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138977. 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 7, 0, 0, 0, 0,
  138986. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  138991. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  138996. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 0, 0, 0, 0, 0, 0, 0,
  139012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  139017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  139022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139025. 0, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  139032. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  139037. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  139042. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  139043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  139351. };
  139352. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  139353. -0.5, 0.5,
  139354. };
  139355. static long _vq_quantmap__44c1_sm_p1_0[] = {
  139356. 1, 0, 2,
  139357. };
  139358. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  139359. _vq_quantthresh__44c1_sm_p1_0,
  139360. _vq_quantmap__44c1_sm_p1_0,
  139361. 3,
  139362. 3
  139363. };
  139364. static static_codebook _44c1_sm_p1_0 = {
  139365. 8, 6561,
  139366. _vq_lengthlist__44c1_sm_p1_0,
  139367. 1, -535822336, 1611661312, 2, 0,
  139368. _vq_quantlist__44c1_sm_p1_0,
  139369. NULL,
  139370. &_vq_auxt__44c1_sm_p1_0,
  139371. NULL,
  139372. 0
  139373. };
  139374. static long _vq_quantlist__44c1_sm_p2_0[] = {
  139375. 2,
  139376. 1,
  139377. 3,
  139378. 0,
  139379. 4,
  139380. };
  139381. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  139382. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  139384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139385. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  139387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139388. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  139389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139421. 0,
  139422. };
  139423. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  139424. -1.5, -0.5, 0.5, 1.5,
  139425. };
  139426. static long _vq_quantmap__44c1_sm_p2_0[] = {
  139427. 3, 1, 0, 2, 4,
  139428. };
  139429. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  139430. _vq_quantthresh__44c1_sm_p2_0,
  139431. _vq_quantmap__44c1_sm_p2_0,
  139432. 5,
  139433. 5
  139434. };
  139435. static static_codebook _44c1_sm_p2_0 = {
  139436. 4, 625,
  139437. _vq_lengthlist__44c1_sm_p2_0,
  139438. 1, -533725184, 1611661312, 3, 0,
  139439. _vq_quantlist__44c1_sm_p2_0,
  139440. NULL,
  139441. &_vq_auxt__44c1_sm_p2_0,
  139442. NULL,
  139443. 0
  139444. };
  139445. static long _vq_quantlist__44c1_sm_p3_0[] = {
  139446. 4,
  139447. 3,
  139448. 5,
  139449. 2,
  139450. 6,
  139451. 1,
  139452. 7,
  139453. 0,
  139454. 8,
  139455. };
  139456. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  139457. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  139458. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  139459. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  139460. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  139461. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139462. 0,
  139463. };
  139464. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  139465. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139466. };
  139467. static long _vq_quantmap__44c1_sm_p3_0[] = {
  139468. 7, 5, 3, 1, 0, 2, 4, 6,
  139469. 8,
  139470. };
  139471. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  139472. _vq_quantthresh__44c1_sm_p3_0,
  139473. _vq_quantmap__44c1_sm_p3_0,
  139474. 9,
  139475. 9
  139476. };
  139477. static static_codebook _44c1_sm_p3_0 = {
  139478. 2, 81,
  139479. _vq_lengthlist__44c1_sm_p3_0,
  139480. 1, -531628032, 1611661312, 4, 0,
  139481. _vq_quantlist__44c1_sm_p3_0,
  139482. NULL,
  139483. &_vq_auxt__44c1_sm_p3_0,
  139484. NULL,
  139485. 0
  139486. };
  139487. static long _vq_quantlist__44c1_sm_p4_0[] = {
  139488. 4,
  139489. 3,
  139490. 5,
  139491. 2,
  139492. 6,
  139493. 1,
  139494. 7,
  139495. 0,
  139496. 8,
  139497. };
  139498. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  139499. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  139500. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  139501. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  139502. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  139503. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  139504. 11,
  139505. };
  139506. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  139507. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139508. };
  139509. static long _vq_quantmap__44c1_sm_p4_0[] = {
  139510. 7, 5, 3, 1, 0, 2, 4, 6,
  139511. 8,
  139512. };
  139513. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  139514. _vq_quantthresh__44c1_sm_p4_0,
  139515. _vq_quantmap__44c1_sm_p4_0,
  139516. 9,
  139517. 9
  139518. };
  139519. static static_codebook _44c1_sm_p4_0 = {
  139520. 2, 81,
  139521. _vq_lengthlist__44c1_sm_p4_0,
  139522. 1, -531628032, 1611661312, 4, 0,
  139523. _vq_quantlist__44c1_sm_p4_0,
  139524. NULL,
  139525. &_vq_auxt__44c1_sm_p4_0,
  139526. NULL,
  139527. 0
  139528. };
  139529. static long _vq_quantlist__44c1_sm_p5_0[] = {
  139530. 8,
  139531. 7,
  139532. 9,
  139533. 6,
  139534. 10,
  139535. 5,
  139536. 11,
  139537. 4,
  139538. 12,
  139539. 3,
  139540. 13,
  139541. 2,
  139542. 14,
  139543. 1,
  139544. 15,
  139545. 0,
  139546. 16,
  139547. };
  139548. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  139549. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  139550. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  139551. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  139552. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  139553. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  139554. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  139555. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  139556. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  139557. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  139558. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  139559. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  139560. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  139561. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  139562. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  139563. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  139564. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  139565. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  139566. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  139567. 14,
  139568. };
  139569. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  139570. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139571. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139572. };
  139573. static long _vq_quantmap__44c1_sm_p5_0[] = {
  139574. 15, 13, 11, 9, 7, 5, 3, 1,
  139575. 0, 2, 4, 6, 8, 10, 12, 14,
  139576. 16,
  139577. };
  139578. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  139579. _vq_quantthresh__44c1_sm_p5_0,
  139580. _vq_quantmap__44c1_sm_p5_0,
  139581. 17,
  139582. 17
  139583. };
  139584. static static_codebook _44c1_sm_p5_0 = {
  139585. 2, 289,
  139586. _vq_lengthlist__44c1_sm_p5_0,
  139587. 1, -529530880, 1611661312, 5, 0,
  139588. _vq_quantlist__44c1_sm_p5_0,
  139589. NULL,
  139590. &_vq_auxt__44c1_sm_p5_0,
  139591. NULL,
  139592. 0
  139593. };
  139594. static long _vq_quantlist__44c1_sm_p6_0[] = {
  139595. 1,
  139596. 0,
  139597. 2,
  139598. };
  139599. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  139600. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  139601. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  139602. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  139603. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  139604. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  139605. 11,
  139606. };
  139607. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  139608. -5.5, 5.5,
  139609. };
  139610. static long _vq_quantmap__44c1_sm_p6_0[] = {
  139611. 1, 0, 2,
  139612. };
  139613. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  139614. _vq_quantthresh__44c1_sm_p6_0,
  139615. _vq_quantmap__44c1_sm_p6_0,
  139616. 3,
  139617. 3
  139618. };
  139619. static static_codebook _44c1_sm_p6_0 = {
  139620. 4, 81,
  139621. _vq_lengthlist__44c1_sm_p6_0,
  139622. 1, -529137664, 1618345984, 2, 0,
  139623. _vq_quantlist__44c1_sm_p6_0,
  139624. NULL,
  139625. &_vq_auxt__44c1_sm_p6_0,
  139626. NULL,
  139627. 0
  139628. };
  139629. static long _vq_quantlist__44c1_sm_p6_1[] = {
  139630. 5,
  139631. 4,
  139632. 6,
  139633. 3,
  139634. 7,
  139635. 2,
  139636. 8,
  139637. 1,
  139638. 9,
  139639. 0,
  139640. 10,
  139641. };
  139642. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  139643. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  139644. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  139645. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  139646. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  139647. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  139648. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  139649. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  139650. 10,10,10, 8, 8, 8, 8, 8, 8,
  139651. };
  139652. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  139653. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139654. 3.5, 4.5,
  139655. };
  139656. static long _vq_quantmap__44c1_sm_p6_1[] = {
  139657. 9, 7, 5, 3, 1, 0, 2, 4,
  139658. 6, 8, 10,
  139659. };
  139660. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  139661. _vq_quantthresh__44c1_sm_p6_1,
  139662. _vq_quantmap__44c1_sm_p6_1,
  139663. 11,
  139664. 11
  139665. };
  139666. static static_codebook _44c1_sm_p6_1 = {
  139667. 2, 121,
  139668. _vq_lengthlist__44c1_sm_p6_1,
  139669. 1, -531365888, 1611661312, 4, 0,
  139670. _vq_quantlist__44c1_sm_p6_1,
  139671. NULL,
  139672. &_vq_auxt__44c1_sm_p6_1,
  139673. NULL,
  139674. 0
  139675. };
  139676. static long _vq_quantlist__44c1_sm_p7_0[] = {
  139677. 6,
  139678. 5,
  139679. 7,
  139680. 4,
  139681. 8,
  139682. 3,
  139683. 9,
  139684. 2,
  139685. 10,
  139686. 1,
  139687. 11,
  139688. 0,
  139689. 12,
  139690. };
  139691. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  139692. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  139693. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  139694. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  139695. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  139696. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  139697. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  139698. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  139699. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  139700. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  139701. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  139702. 0,12,12,11,11,13,12,14,13,
  139703. };
  139704. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  139705. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  139706. 12.5, 17.5, 22.5, 27.5,
  139707. };
  139708. static long _vq_quantmap__44c1_sm_p7_0[] = {
  139709. 11, 9, 7, 5, 3, 1, 0, 2,
  139710. 4, 6, 8, 10, 12,
  139711. };
  139712. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  139713. _vq_quantthresh__44c1_sm_p7_0,
  139714. _vq_quantmap__44c1_sm_p7_0,
  139715. 13,
  139716. 13
  139717. };
  139718. static static_codebook _44c1_sm_p7_0 = {
  139719. 2, 169,
  139720. _vq_lengthlist__44c1_sm_p7_0,
  139721. 1, -526516224, 1616117760, 4, 0,
  139722. _vq_quantlist__44c1_sm_p7_0,
  139723. NULL,
  139724. &_vq_auxt__44c1_sm_p7_0,
  139725. NULL,
  139726. 0
  139727. };
  139728. static long _vq_quantlist__44c1_sm_p7_1[] = {
  139729. 2,
  139730. 1,
  139731. 3,
  139732. 0,
  139733. 4,
  139734. };
  139735. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  139736. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  139737. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  139738. };
  139739. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  139740. -1.5, -0.5, 0.5, 1.5,
  139741. };
  139742. static long _vq_quantmap__44c1_sm_p7_1[] = {
  139743. 3, 1, 0, 2, 4,
  139744. };
  139745. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  139746. _vq_quantthresh__44c1_sm_p7_1,
  139747. _vq_quantmap__44c1_sm_p7_1,
  139748. 5,
  139749. 5
  139750. };
  139751. static static_codebook _44c1_sm_p7_1 = {
  139752. 2, 25,
  139753. _vq_lengthlist__44c1_sm_p7_1,
  139754. 1, -533725184, 1611661312, 3, 0,
  139755. _vq_quantlist__44c1_sm_p7_1,
  139756. NULL,
  139757. &_vq_auxt__44c1_sm_p7_1,
  139758. NULL,
  139759. 0
  139760. };
  139761. static long _vq_quantlist__44c1_sm_p8_0[] = {
  139762. 6,
  139763. 5,
  139764. 7,
  139765. 4,
  139766. 8,
  139767. 3,
  139768. 9,
  139769. 2,
  139770. 10,
  139771. 1,
  139772. 11,
  139773. 0,
  139774. 12,
  139775. };
  139776. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  139777. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  139778. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  139779. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139780. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139781. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139782. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139783. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139784. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139785. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139786. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  139787. 13,13,13,13,13,13,13,13,13,
  139788. };
  139789. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  139790. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  139791. 552.5, 773.5, 994.5, 1215.5,
  139792. };
  139793. static long _vq_quantmap__44c1_sm_p8_0[] = {
  139794. 11, 9, 7, 5, 3, 1, 0, 2,
  139795. 4, 6, 8, 10, 12,
  139796. };
  139797. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  139798. _vq_quantthresh__44c1_sm_p8_0,
  139799. _vq_quantmap__44c1_sm_p8_0,
  139800. 13,
  139801. 13
  139802. };
  139803. static static_codebook _44c1_sm_p8_0 = {
  139804. 2, 169,
  139805. _vq_lengthlist__44c1_sm_p8_0,
  139806. 1, -514541568, 1627103232, 4, 0,
  139807. _vq_quantlist__44c1_sm_p8_0,
  139808. NULL,
  139809. &_vq_auxt__44c1_sm_p8_0,
  139810. NULL,
  139811. 0
  139812. };
  139813. static long _vq_quantlist__44c1_sm_p8_1[] = {
  139814. 6,
  139815. 5,
  139816. 7,
  139817. 4,
  139818. 8,
  139819. 3,
  139820. 9,
  139821. 2,
  139822. 10,
  139823. 1,
  139824. 11,
  139825. 0,
  139826. 12,
  139827. };
  139828. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  139829. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  139830. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  139831. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  139832. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  139833. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  139834. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  139835. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  139836. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  139837. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  139838. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  139839. 20,13,12,12,12,14,12,14,13,
  139840. };
  139841. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  139842. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  139843. 42.5, 59.5, 76.5, 93.5,
  139844. };
  139845. static long _vq_quantmap__44c1_sm_p8_1[] = {
  139846. 11, 9, 7, 5, 3, 1, 0, 2,
  139847. 4, 6, 8, 10, 12,
  139848. };
  139849. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  139850. _vq_quantthresh__44c1_sm_p8_1,
  139851. _vq_quantmap__44c1_sm_p8_1,
  139852. 13,
  139853. 13
  139854. };
  139855. static static_codebook _44c1_sm_p8_1 = {
  139856. 2, 169,
  139857. _vq_lengthlist__44c1_sm_p8_1,
  139858. 1, -522616832, 1620115456, 4, 0,
  139859. _vq_quantlist__44c1_sm_p8_1,
  139860. NULL,
  139861. &_vq_auxt__44c1_sm_p8_1,
  139862. NULL,
  139863. 0
  139864. };
  139865. static long _vq_quantlist__44c1_sm_p8_2[] = {
  139866. 8,
  139867. 7,
  139868. 9,
  139869. 6,
  139870. 10,
  139871. 5,
  139872. 11,
  139873. 4,
  139874. 12,
  139875. 3,
  139876. 13,
  139877. 2,
  139878. 14,
  139879. 1,
  139880. 15,
  139881. 0,
  139882. 16,
  139883. };
  139884. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  139885. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  139886. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  139887. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  139888. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  139889. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  139890. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  139891. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  139892. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  139893. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  139894. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  139895. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  139896. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  139897. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  139898. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  139899. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  139900. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  139901. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  139902. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  139903. 9,
  139904. };
  139905. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  139906. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139907. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139908. };
  139909. static long _vq_quantmap__44c1_sm_p8_2[] = {
  139910. 15, 13, 11, 9, 7, 5, 3, 1,
  139911. 0, 2, 4, 6, 8, 10, 12, 14,
  139912. 16,
  139913. };
  139914. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  139915. _vq_quantthresh__44c1_sm_p8_2,
  139916. _vq_quantmap__44c1_sm_p8_2,
  139917. 17,
  139918. 17
  139919. };
  139920. static static_codebook _44c1_sm_p8_2 = {
  139921. 2, 289,
  139922. _vq_lengthlist__44c1_sm_p8_2,
  139923. 1, -529530880, 1611661312, 5, 0,
  139924. _vq_quantlist__44c1_sm_p8_2,
  139925. NULL,
  139926. &_vq_auxt__44c1_sm_p8_2,
  139927. NULL,
  139928. 0
  139929. };
  139930. static long _huff_lengthlist__44c1_sm_short[] = {
  139931. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  139932. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  139933. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  139934. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  139935. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  139936. 11,
  139937. };
  139938. static static_codebook _huff_book__44c1_sm_short = {
  139939. 2, 81,
  139940. _huff_lengthlist__44c1_sm_short,
  139941. 0, 0, 0, 0, 0,
  139942. NULL,
  139943. NULL,
  139944. NULL,
  139945. NULL,
  139946. 0
  139947. };
  139948. static long _huff_lengthlist__44cn1_s_long[] = {
  139949. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  139950. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  139951. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  139952. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  139953. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  139954. 20,
  139955. };
  139956. static static_codebook _huff_book__44cn1_s_long = {
  139957. 2, 81,
  139958. _huff_lengthlist__44cn1_s_long,
  139959. 0, 0, 0, 0, 0,
  139960. NULL,
  139961. NULL,
  139962. NULL,
  139963. NULL,
  139964. 0
  139965. };
  139966. static long _vq_quantlist__44cn1_s_p1_0[] = {
  139967. 1,
  139968. 0,
  139969. 2,
  139970. };
  139971. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  139972. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  139973. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139977. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  139978. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139982. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  139983. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139999. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140004. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140009. 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0,
  140018. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 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, 7,10,10, 0, 0, 0,
  140023. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 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, 7,10,10, 0, 0,
  140028. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  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, 0, 0, 0, 0, 0, 0, 0,
  140044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  140049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  140054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140057. 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  140064. 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  140069. 0, 0, 0, 0, 0, 9, 9,11, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  140074. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  140075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  140383. };
  140384. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  140385. -0.5, 0.5,
  140386. };
  140387. static long _vq_quantmap__44cn1_s_p1_0[] = {
  140388. 1, 0, 2,
  140389. };
  140390. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  140391. _vq_quantthresh__44cn1_s_p1_0,
  140392. _vq_quantmap__44cn1_s_p1_0,
  140393. 3,
  140394. 3
  140395. };
  140396. static static_codebook _44cn1_s_p1_0 = {
  140397. 8, 6561,
  140398. _vq_lengthlist__44cn1_s_p1_0,
  140399. 1, -535822336, 1611661312, 2, 0,
  140400. _vq_quantlist__44cn1_s_p1_0,
  140401. NULL,
  140402. &_vq_auxt__44cn1_s_p1_0,
  140403. NULL,
  140404. 0
  140405. };
  140406. static long _vq_quantlist__44cn1_s_p2_0[] = {
  140407. 2,
  140408. 1,
  140409. 3,
  140410. 0,
  140411. 4,
  140412. };
  140413. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  140414. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  140416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140417. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  140419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140420. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  140421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140453. 0,
  140454. };
  140455. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  140456. -1.5, -0.5, 0.5, 1.5,
  140457. };
  140458. static long _vq_quantmap__44cn1_s_p2_0[] = {
  140459. 3, 1, 0, 2, 4,
  140460. };
  140461. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  140462. _vq_quantthresh__44cn1_s_p2_0,
  140463. _vq_quantmap__44cn1_s_p2_0,
  140464. 5,
  140465. 5
  140466. };
  140467. static static_codebook _44cn1_s_p2_0 = {
  140468. 4, 625,
  140469. _vq_lengthlist__44cn1_s_p2_0,
  140470. 1, -533725184, 1611661312, 3, 0,
  140471. _vq_quantlist__44cn1_s_p2_0,
  140472. NULL,
  140473. &_vq_auxt__44cn1_s_p2_0,
  140474. NULL,
  140475. 0
  140476. };
  140477. static long _vq_quantlist__44cn1_s_p3_0[] = {
  140478. 4,
  140479. 3,
  140480. 5,
  140481. 2,
  140482. 6,
  140483. 1,
  140484. 7,
  140485. 0,
  140486. 8,
  140487. };
  140488. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  140489. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  140490. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  140491. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  140492. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  140493. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140494. 0,
  140495. };
  140496. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  140497. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140498. };
  140499. static long _vq_quantmap__44cn1_s_p3_0[] = {
  140500. 7, 5, 3, 1, 0, 2, 4, 6,
  140501. 8,
  140502. };
  140503. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  140504. _vq_quantthresh__44cn1_s_p3_0,
  140505. _vq_quantmap__44cn1_s_p3_0,
  140506. 9,
  140507. 9
  140508. };
  140509. static static_codebook _44cn1_s_p3_0 = {
  140510. 2, 81,
  140511. _vq_lengthlist__44cn1_s_p3_0,
  140512. 1, -531628032, 1611661312, 4, 0,
  140513. _vq_quantlist__44cn1_s_p3_0,
  140514. NULL,
  140515. &_vq_auxt__44cn1_s_p3_0,
  140516. NULL,
  140517. 0
  140518. };
  140519. static long _vq_quantlist__44cn1_s_p4_0[] = {
  140520. 4,
  140521. 3,
  140522. 5,
  140523. 2,
  140524. 6,
  140525. 1,
  140526. 7,
  140527. 0,
  140528. 8,
  140529. };
  140530. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  140531. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  140532. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  140533. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  140534. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  140535. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  140536. 11,
  140537. };
  140538. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  140539. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140540. };
  140541. static long _vq_quantmap__44cn1_s_p4_0[] = {
  140542. 7, 5, 3, 1, 0, 2, 4, 6,
  140543. 8,
  140544. };
  140545. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  140546. _vq_quantthresh__44cn1_s_p4_0,
  140547. _vq_quantmap__44cn1_s_p4_0,
  140548. 9,
  140549. 9
  140550. };
  140551. static static_codebook _44cn1_s_p4_0 = {
  140552. 2, 81,
  140553. _vq_lengthlist__44cn1_s_p4_0,
  140554. 1, -531628032, 1611661312, 4, 0,
  140555. _vq_quantlist__44cn1_s_p4_0,
  140556. NULL,
  140557. &_vq_auxt__44cn1_s_p4_0,
  140558. NULL,
  140559. 0
  140560. };
  140561. static long _vq_quantlist__44cn1_s_p5_0[] = {
  140562. 8,
  140563. 7,
  140564. 9,
  140565. 6,
  140566. 10,
  140567. 5,
  140568. 11,
  140569. 4,
  140570. 12,
  140571. 3,
  140572. 13,
  140573. 2,
  140574. 14,
  140575. 1,
  140576. 15,
  140577. 0,
  140578. 16,
  140579. };
  140580. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  140581. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  140582. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  140583. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  140584. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  140585. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  140586. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  140587. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  140588. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  140589. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  140590. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  140591. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  140592. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  140593. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  140594. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  140595. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  140596. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  140597. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  140598. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  140599. 14,
  140600. };
  140601. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  140602. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140603. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140604. };
  140605. static long _vq_quantmap__44cn1_s_p5_0[] = {
  140606. 15, 13, 11, 9, 7, 5, 3, 1,
  140607. 0, 2, 4, 6, 8, 10, 12, 14,
  140608. 16,
  140609. };
  140610. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  140611. _vq_quantthresh__44cn1_s_p5_0,
  140612. _vq_quantmap__44cn1_s_p5_0,
  140613. 17,
  140614. 17
  140615. };
  140616. static static_codebook _44cn1_s_p5_0 = {
  140617. 2, 289,
  140618. _vq_lengthlist__44cn1_s_p5_0,
  140619. 1, -529530880, 1611661312, 5, 0,
  140620. _vq_quantlist__44cn1_s_p5_0,
  140621. NULL,
  140622. &_vq_auxt__44cn1_s_p5_0,
  140623. NULL,
  140624. 0
  140625. };
  140626. static long _vq_quantlist__44cn1_s_p6_0[] = {
  140627. 1,
  140628. 0,
  140629. 2,
  140630. };
  140631. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  140632. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  140633. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  140634. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  140635. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  140636. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  140637. 10,
  140638. };
  140639. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  140640. -5.5, 5.5,
  140641. };
  140642. static long _vq_quantmap__44cn1_s_p6_0[] = {
  140643. 1, 0, 2,
  140644. };
  140645. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  140646. _vq_quantthresh__44cn1_s_p6_0,
  140647. _vq_quantmap__44cn1_s_p6_0,
  140648. 3,
  140649. 3
  140650. };
  140651. static static_codebook _44cn1_s_p6_0 = {
  140652. 4, 81,
  140653. _vq_lengthlist__44cn1_s_p6_0,
  140654. 1, -529137664, 1618345984, 2, 0,
  140655. _vq_quantlist__44cn1_s_p6_0,
  140656. NULL,
  140657. &_vq_auxt__44cn1_s_p6_0,
  140658. NULL,
  140659. 0
  140660. };
  140661. static long _vq_quantlist__44cn1_s_p6_1[] = {
  140662. 5,
  140663. 4,
  140664. 6,
  140665. 3,
  140666. 7,
  140667. 2,
  140668. 8,
  140669. 1,
  140670. 9,
  140671. 0,
  140672. 10,
  140673. };
  140674. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  140675. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  140676. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  140677. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  140678. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  140679. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  140680. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  140681. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  140682. 10,10,10, 9, 9, 9, 9, 9, 9,
  140683. };
  140684. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  140685. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140686. 3.5, 4.5,
  140687. };
  140688. static long _vq_quantmap__44cn1_s_p6_1[] = {
  140689. 9, 7, 5, 3, 1, 0, 2, 4,
  140690. 6, 8, 10,
  140691. };
  140692. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  140693. _vq_quantthresh__44cn1_s_p6_1,
  140694. _vq_quantmap__44cn1_s_p6_1,
  140695. 11,
  140696. 11
  140697. };
  140698. static static_codebook _44cn1_s_p6_1 = {
  140699. 2, 121,
  140700. _vq_lengthlist__44cn1_s_p6_1,
  140701. 1, -531365888, 1611661312, 4, 0,
  140702. _vq_quantlist__44cn1_s_p6_1,
  140703. NULL,
  140704. &_vq_auxt__44cn1_s_p6_1,
  140705. NULL,
  140706. 0
  140707. };
  140708. static long _vq_quantlist__44cn1_s_p7_0[] = {
  140709. 6,
  140710. 5,
  140711. 7,
  140712. 4,
  140713. 8,
  140714. 3,
  140715. 9,
  140716. 2,
  140717. 10,
  140718. 1,
  140719. 11,
  140720. 0,
  140721. 12,
  140722. };
  140723. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  140724. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  140725. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  140726. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  140727. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  140728. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  140729. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  140730. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  140731. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  140732. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  140733. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  140734. 0,13,13,12,12,13,13,13,14,
  140735. };
  140736. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  140737. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140738. 12.5, 17.5, 22.5, 27.5,
  140739. };
  140740. static long _vq_quantmap__44cn1_s_p7_0[] = {
  140741. 11, 9, 7, 5, 3, 1, 0, 2,
  140742. 4, 6, 8, 10, 12,
  140743. };
  140744. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  140745. _vq_quantthresh__44cn1_s_p7_0,
  140746. _vq_quantmap__44cn1_s_p7_0,
  140747. 13,
  140748. 13
  140749. };
  140750. static static_codebook _44cn1_s_p7_0 = {
  140751. 2, 169,
  140752. _vq_lengthlist__44cn1_s_p7_0,
  140753. 1, -526516224, 1616117760, 4, 0,
  140754. _vq_quantlist__44cn1_s_p7_0,
  140755. NULL,
  140756. &_vq_auxt__44cn1_s_p7_0,
  140757. NULL,
  140758. 0
  140759. };
  140760. static long _vq_quantlist__44cn1_s_p7_1[] = {
  140761. 2,
  140762. 1,
  140763. 3,
  140764. 0,
  140765. 4,
  140766. };
  140767. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  140768. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  140769. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  140770. };
  140771. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  140772. -1.5, -0.5, 0.5, 1.5,
  140773. };
  140774. static long _vq_quantmap__44cn1_s_p7_1[] = {
  140775. 3, 1, 0, 2, 4,
  140776. };
  140777. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  140778. _vq_quantthresh__44cn1_s_p7_1,
  140779. _vq_quantmap__44cn1_s_p7_1,
  140780. 5,
  140781. 5
  140782. };
  140783. static static_codebook _44cn1_s_p7_1 = {
  140784. 2, 25,
  140785. _vq_lengthlist__44cn1_s_p7_1,
  140786. 1, -533725184, 1611661312, 3, 0,
  140787. _vq_quantlist__44cn1_s_p7_1,
  140788. NULL,
  140789. &_vq_auxt__44cn1_s_p7_1,
  140790. NULL,
  140791. 0
  140792. };
  140793. static long _vq_quantlist__44cn1_s_p8_0[] = {
  140794. 2,
  140795. 1,
  140796. 3,
  140797. 0,
  140798. 4,
  140799. };
  140800. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  140801. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  140802. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  140803. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140804. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  140805. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140806. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140807. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140808. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  140809. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140810. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  140811. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  140812. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140813. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140814. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140815. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140816. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  140817. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140818. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140819. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140820. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140821. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140822. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140823. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140824. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140825. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140826. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140827. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140828. 11,11,11,11,11,11,11,11,11,11,11,11,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,11,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,12,12,12,12,12,12,12,12,12,
  140835. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140836. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140837. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140838. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140839. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  140840. 12,
  140841. };
  140842. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  140843. -331.5, -110.5, 110.5, 331.5,
  140844. };
  140845. static long _vq_quantmap__44cn1_s_p8_0[] = {
  140846. 3, 1, 0, 2, 4,
  140847. };
  140848. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  140849. _vq_quantthresh__44cn1_s_p8_0,
  140850. _vq_quantmap__44cn1_s_p8_0,
  140851. 5,
  140852. 5
  140853. };
  140854. static static_codebook _44cn1_s_p8_0 = {
  140855. 4, 625,
  140856. _vq_lengthlist__44cn1_s_p8_0,
  140857. 1, -518283264, 1627103232, 3, 0,
  140858. _vq_quantlist__44cn1_s_p8_0,
  140859. NULL,
  140860. &_vq_auxt__44cn1_s_p8_0,
  140861. NULL,
  140862. 0
  140863. };
  140864. static long _vq_quantlist__44cn1_s_p8_1[] = {
  140865. 6,
  140866. 5,
  140867. 7,
  140868. 4,
  140869. 8,
  140870. 3,
  140871. 9,
  140872. 2,
  140873. 10,
  140874. 1,
  140875. 11,
  140876. 0,
  140877. 12,
  140878. };
  140879. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  140880. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  140881. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  140882. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  140883. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  140884. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  140885. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  140886. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  140887. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  140888. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  140889. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  140890. 15,12,12,11,11,14,12,13,14,
  140891. };
  140892. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  140893. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  140894. 42.5, 59.5, 76.5, 93.5,
  140895. };
  140896. static long _vq_quantmap__44cn1_s_p8_1[] = {
  140897. 11, 9, 7, 5, 3, 1, 0, 2,
  140898. 4, 6, 8, 10, 12,
  140899. };
  140900. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  140901. _vq_quantthresh__44cn1_s_p8_1,
  140902. _vq_quantmap__44cn1_s_p8_1,
  140903. 13,
  140904. 13
  140905. };
  140906. static static_codebook _44cn1_s_p8_1 = {
  140907. 2, 169,
  140908. _vq_lengthlist__44cn1_s_p8_1,
  140909. 1, -522616832, 1620115456, 4, 0,
  140910. _vq_quantlist__44cn1_s_p8_1,
  140911. NULL,
  140912. &_vq_auxt__44cn1_s_p8_1,
  140913. NULL,
  140914. 0
  140915. };
  140916. static long _vq_quantlist__44cn1_s_p8_2[] = {
  140917. 8,
  140918. 7,
  140919. 9,
  140920. 6,
  140921. 10,
  140922. 5,
  140923. 11,
  140924. 4,
  140925. 12,
  140926. 3,
  140927. 13,
  140928. 2,
  140929. 14,
  140930. 1,
  140931. 15,
  140932. 0,
  140933. 16,
  140934. };
  140935. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  140936. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  140937. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  140938. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  140939. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  140940. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  140941. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  140942. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  140943. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  140944. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  140945. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  140946. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  140947. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  140948. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  140949. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  140950. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  140951. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  140952. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  140953. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  140954. 9,
  140955. };
  140956. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  140957. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140958. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140959. };
  140960. static long _vq_quantmap__44cn1_s_p8_2[] = {
  140961. 15, 13, 11, 9, 7, 5, 3, 1,
  140962. 0, 2, 4, 6, 8, 10, 12, 14,
  140963. 16,
  140964. };
  140965. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  140966. _vq_quantthresh__44cn1_s_p8_2,
  140967. _vq_quantmap__44cn1_s_p8_2,
  140968. 17,
  140969. 17
  140970. };
  140971. static static_codebook _44cn1_s_p8_2 = {
  140972. 2, 289,
  140973. _vq_lengthlist__44cn1_s_p8_2,
  140974. 1, -529530880, 1611661312, 5, 0,
  140975. _vq_quantlist__44cn1_s_p8_2,
  140976. NULL,
  140977. &_vq_auxt__44cn1_s_p8_2,
  140978. NULL,
  140979. 0
  140980. };
  140981. static long _huff_lengthlist__44cn1_s_short[] = {
  140982. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  140983. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  140984. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  140985. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  140986. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  140987. 10,
  140988. };
  140989. static static_codebook _huff_book__44cn1_s_short = {
  140990. 2, 81,
  140991. _huff_lengthlist__44cn1_s_short,
  140992. 0, 0, 0, 0, 0,
  140993. NULL,
  140994. NULL,
  140995. NULL,
  140996. NULL,
  140997. 0
  140998. };
  140999. static long _huff_lengthlist__44cn1_sm_long[] = {
  141000. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  141001. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  141002. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  141003. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  141004. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  141005. 17,
  141006. };
  141007. static static_codebook _huff_book__44cn1_sm_long = {
  141008. 2, 81,
  141009. _huff_lengthlist__44cn1_sm_long,
  141010. 0, 0, 0, 0, 0,
  141011. NULL,
  141012. NULL,
  141013. NULL,
  141014. NULL,
  141015. 0
  141016. };
  141017. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  141018. 1,
  141019. 0,
  141020. 2,
  141021. };
  141022. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  141023. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  141024. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141028. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  141029. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141033. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  141034. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141050. 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141055. 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141060. 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0,
  141069. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7,10, 9, 0, 0, 0,
  141074. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  141079. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 0, 0, 0, 0, 0, 0, 0,
  141095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  141100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  141105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141108. 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  141115. 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  141120. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  141125. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  141126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  141434. };
  141435. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  141436. -0.5, 0.5,
  141437. };
  141438. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  141439. 1, 0, 2,
  141440. };
  141441. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  141442. _vq_quantthresh__44cn1_sm_p1_0,
  141443. _vq_quantmap__44cn1_sm_p1_0,
  141444. 3,
  141445. 3
  141446. };
  141447. static static_codebook _44cn1_sm_p1_0 = {
  141448. 8, 6561,
  141449. _vq_lengthlist__44cn1_sm_p1_0,
  141450. 1, -535822336, 1611661312, 2, 0,
  141451. _vq_quantlist__44cn1_sm_p1_0,
  141452. NULL,
  141453. &_vq_auxt__44cn1_sm_p1_0,
  141454. NULL,
  141455. 0
  141456. };
  141457. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  141458. 2,
  141459. 1,
  141460. 3,
  141461. 0,
  141462. 4,
  141463. };
  141464. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  141465. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  141467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141468. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  141470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141471. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  141472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141504. 0,
  141505. };
  141506. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  141507. -1.5, -0.5, 0.5, 1.5,
  141508. };
  141509. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  141510. 3, 1, 0, 2, 4,
  141511. };
  141512. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  141513. _vq_quantthresh__44cn1_sm_p2_0,
  141514. _vq_quantmap__44cn1_sm_p2_0,
  141515. 5,
  141516. 5
  141517. };
  141518. static static_codebook _44cn1_sm_p2_0 = {
  141519. 4, 625,
  141520. _vq_lengthlist__44cn1_sm_p2_0,
  141521. 1, -533725184, 1611661312, 3, 0,
  141522. _vq_quantlist__44cn1_sm_p2_0,
  141523. NULL,
  141524. &_vq_auxt__44cn1_sm_p2_0,
  141525. NULL,
  141526. 0
  141527. };
  141528. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  141529. 4,
  141530. 3,
  141531. 5,
  141532. 2,
  141533. 6,
  141534. 1,
  141535. 7,
  141536. 0,
  141537. 8,
  141538. };
  141539. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  141540. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  141541. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  141542. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  141543. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  141544. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141545. 0,
  141546. };
  141547. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  141548. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141549. };
  141550. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  141551. 7, 5, 3, 1, 0, 2, 4, 6,
  141552. 8,
  141553. };
  141554. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  141555. _vq_quantthresh__44cn1_sm_p3_0,
  141556. _vq_quantmap__44cn1_sm_p3_0,
  141557. 9,
  141558. 9
  141559. };
  141560. static static_codebook _44cn1_sm_p3_0 = {
  141561. 2, 81,
  141562. _vq_lengthlist__44cn1_sm_p3_0,
  141563. 1, -531628032, 1611661312, 4, 0,
  141564. _vq_quantlist__44cn1_sm_p3_0,
  141565. NULL,
  141566. &_vq_auxt__44cn1_sm_p3_0,
  141567. NULL,
  141568. 0
  141569. };
  141570. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  141571. 4,
  141572. 3,
  141573. 5,
  141574. 2,
  141575. 6,
  141576. 1,
  141577. 7,
  141578. 0,
  141579. 8,
  141580. };
  141581. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  141582. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  141583. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  141584. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  141585. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  141586. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  141587. 11,
  141588. };
  141589. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  141590. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141591. };
  141592. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  141593. 7, 5, 3, 1, 0, 2, 4, 6,
  141594. 8,
  141595. };
  141596. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  141597. _vq_quantthresh__44cn1_sm_p4_0,
  141598. _vq_quantmap__44cn1_sm_p4_0,
  141599. 9,
  141600. 9
  141601. };
  141602. static static_codebook _44cn1_sm_p4_0 = {
  141603. 2, 81,
  141604. _vq_lengthlist__44cn1_sm_p4_0,
  141605. 1, -531628032, 1611661312, 4, 0,
  141606. _vq_quantlist__44cn1_sm_p4_0,
  141607. NULL,
  141608. &_vq_auxt__44cn1_sm_p4_0,
  141609. NULL,
  141610. 0
  141611. };
  141612. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  141613. 8,
  141614. 7,
  141615. 9,
  141616. 6,
  141617. 10,
  141618. 5,
  141619. 11,
  141620. 4,
  141621. 12,
  141622. 3,
  141623. 13,
  141624. 2,
  141625. 14,
  141626. 1,
  141627. 15,
  141628. 0,
  141629. 16,
  141630. };
  141631. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  141632. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  141633. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  141634. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  141635. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  141636. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  141637. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  141638. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  141639. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  141640. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  141641. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  141642. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  141643. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  141644. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  141645. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  141646. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  141647. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  141648. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  141649. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  141650. 14,
  141651. };
  141652. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  141653. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141654. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141655. };
  141656. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  141657. 15, 13, 11, 9, 7, 5, 3, 1,
  141658. 0, 2, 4, 6, 8, 10, 12, 14,
  141659. 16,
  141660. };
  141661. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  141662. _vq_quantthresh__44cn1_sm_p5_0,
  141663. _vq_quantmap__44cn1_sm_p5_0,
  141664. 17,
  141665. 17
  141666. };
  141667. static static_codebook _44cn1_sm_p5_0 = {
  141668. 2, 289,
  141669. _vq_lengthlist__44cn1_sm_p5_0,
  141670. 1, -529530880, 1611661312, 5, 0,
  141671. _vq_quantlist__44cn1_sm_p5_0,
  141672. NULL,
  141673. &_vq_auxt__44cn1_sm_p5_0,
  141674. NULL,
  141675. 0
  141676. };
  141677. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  141678. 1,
  141679. 0,
  141680. 2,
  141681. };
  141682. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  141683. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  141684. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  141685. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  141686. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  141687. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  141688. 10,
  141689. };
  141690. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  141691. -5.5, 5.5,
  141692. };
  141693. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  141694. 1, 0, 2,
  141695. };
  141696. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  141697. _vq_quantthresh__44cn1_sm_p6_0,
  141698. _vq_quantmap__44cn1_sm_p6_0,
  141699. 3,
  141700. 3
  141701. };
  141702. static static_codebook _44cn1_sm_p6_0 = {
  141703. 4, 81,
  141704. _vq_lengthlist__44cn1_sm_p6_0,
  141705. 1, -529137664, 1618345984, 2, 0,
  141706. _vq_quantlist__44cn1_sm_p6_0,
  141707. NULL,
  141708. &_vq_auxt__44cn1_sm_p6_0,
  141709. NULL,
  141710. 0
  141711. };
  141712. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  141713. 5,
  141714. 4,
  141715. 6,
  141716. 3,
  141717. 7,
  141718. 2,
  141719. 8,
  141720. 1,
  141721. 9,
  141722. 0,
  141723. 10,
  141724. };
  141725. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  141726. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  141727. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  141728. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  141729. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  141730. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  141731. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  141732. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  141733. 10,10,10, 8, 9, 8, 8, 9, 8,
  141734. };
  141735. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  141736. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141737. 3.5, 4.5,
  141738. };
  141739. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  141740. 9, 7, 5, 3, 1, 0, 2, 4,
  141741. 6, 8, 10,
  141742. };
  141743. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  141744. _vq_quantthresh__44cn1_sm_p6_1,
  141745. _vq_quantmap__44cn1_sm_p6_1,
  141746. 11,
  141747. 11
  141748. };
  141749. static static_codebook _44cn1_sm_p6_1 = {
  141750. 2, 121,
  141751. _vq_lengthlist__44cn1_sm_p6_1,
  141752. 1, -531365888, 1611661312, 4, 0,
  141753. _vq_quantlist__44cn1_sm_p6_1,
  141754. NULL,
  141755. &_vq_auxt__44cn1_sm_p6_1,
  141756. NULL,
  141757. 0
  141758. };
  141759. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  141760. 6,
  141761. 5,
  141762. 7,
  141763. 4,
  141764. 8,
  141765. 3,
  141766. 9,
  141767. 2,
  141768. 10,
  141769. 1,
  141770. 11,
  141771. 0,
  141772. 12,
  141773. };
  141774. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  141775. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  141776. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  141777. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  141778. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  141779. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  141780. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  141781. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  141782. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  141783. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  141784. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  141785. 0,13,12,12,12,13,13,13,14,
  141786. };
  141787. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  141788. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141789. 12.5, 17.5, 22.5, 27.5,
  141790. };
  141791. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  141792. 11, 9, 7, 5, 3, 1, 0, 2,
  141793. 4, 6, 8, 10, 12,
  141794. };
  141795. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  141796. _vq_quantthresh__44cn1_sm_p7_0,
  141797. _vq_quantmap__44cn1_sm_p7_0,
  141798. 13,
  141799. 13
  141800. };
  141801. static static_codebook _44cn1_sm_p7_0 = {
  141802. 2, 169,
  141803. _vq_lengthlist__44cn1_sm_p7_0,
  141804. 1, -526516224, 1616117760, 4, 0,
  141805. _vq_quantlist__44cn1_sm_p7_0,
  141806. NULL,
  141807. &_vq_auxt__44cn1_sm_p7_0,
  141808. NULL,
  141809. 0
  141810. };
  141811. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  141812. 2,
  141813. 1,
  141814. 3,
  141815. 0,
  141816. 4,
  141817. };
  141818. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  141819. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  141820. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  141821. };
  141822. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  141823. -1.5, -0.5, 0.5, 1.5,
  141824. };
  141825. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  141826. 3, 1, 0, 2, 4,
  141827. };
  141828. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  141829. _vq_quantthresh__44cn1_sm_p7_1,
  141830. _vq_quantmap__44cn1_sm_p7_1,
  141831. 5,
  141832. 5
  141833. };
  141834. static static_codebook _44cn1_sm_p7_1 = {
  141835. 2, 25,
  141836. _vq_lengthlist__44cn1_sm_p7_1,
  141837. 1, -533725184, 1611661312, 3, 0,
  141838. _vq_quantlist__44cn1_sm_p7_1,
  141839. NULL,
  141840. &_vq_auxt__44cn1_sm_p7_1,
  141841. NULL,
  141842. 0
  141843. };
  141844. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  141845. 4,
  141846. 3,
  141847. 5,
  141848. 2,
  141849. 6,
  141850. 1,
  141851. 7,
  141852. 0,
  141853. 8,
  141854. };
  141855. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  141856. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  141857. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  141858. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  141859. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  141860. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  141861. 14,
  141862. };
  141863. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  141864. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  141865. };
  141866. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  141867. 7, 5, 3, 1, 0, 2, 4, 6,
  141868. 8,
  141869. };
  141870. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  141871. _vq_quantthresh__44cn1_sm_p8_0,
  141872. _vq_quantmap__44cn1_sm_p8_0,
  141873. 9,
  141874. 9
  141875. };
  141876. static static_codebook _44cn1_sm_p8_0 = {
  141877. 2, 81,
  141878. _vq_lengthlist__44cn1_sm_p8_0,
  141879. 1, -516186112, 1627103232, 4, 0,
  141880. _vq_quantlist__44cn1_sm_p8_0,
  141881. NULL,
  141882. &_vq_auxt__44cn1_sm_p8_0,
  141883. NULL,
  141884. 0
  141885. };
  141886. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  141887. 6,
  141888. 5,
  141889. 7,
  141890. 4,
  141891. 8,
  141892. 3,
  141893. 9,
  141894. 2,
  141895. 10,
  141896. 1,
  141897. 11,
  141898. 0,
  141899. 12,
  141900. };
  141901. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  141902. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  141903. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  141904. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  141905. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  141906. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  141907. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  141908. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  141909. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  141910. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  141911. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  141912. 17,12,12,11,10,13,11,13,13,
  141913. };
  141914. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  141915. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  141916. 42.5, 59.5, 76.5, 93.5,
  141917. };
  141918. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  141919. 11, 9, 7, 5, 3, 1, 0, 2,
  141920. 4, 6, 8, 10, 12,
  141921. };
  141922. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  141923. _vq_quantthresh__44cn1_sm_p8_1,
  141924. _vq_quantmap__44cn1_sm_p8_1,
  141925. 13,
  141926. 13
  141927. };
  141928. static static_codebook _44cn1_sm_p8_1 = {
  141929. 2, 169,
  141930. _vq_lengthlist__44cn1_sm_p8_1,
  141931. 1, -522616832, 1620115456, 4, 0,
  141932. _vq_quantlist__44cn1_sm_p8_1,
  141933. NULL,
  141934. &_vq_auxt__44cn1_sm_p8_1,
  141935. NULL,
  141936. 0
  141937. };
  141938. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  141939. 8,
  141940. 7,
  141941. 9,
  141942. 6,
  141943. 10,
  141944. 5,
  141945. 11,
  141946. 4,
  141947. 12,
  141948. 3,
  141949. 13,
  141950. 2,
  141951. 14,
  141952. 1,
  141953. 15,
  141954. 0,
  141955. 16,
  141956. };
  141957. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  141958. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  141959. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  141960. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  141961. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  141962. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  141963. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  141964. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  141965. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  141966. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  141967. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  141968. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  141969. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  141970. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  141971. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  141972. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  141973. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  141974. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  141975. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  141976. 9,
  141977. };
  141978. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  141979. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141980. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141981. };
  141982. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  141983. 15, 13, 11, 9, 7, 5, 3, 1,
  141984. 0, 2, 4, 6, 8, 10, 12, 14,
  141985. 16,
  141986. };
  141987. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  141988. _vq_quantthresh__44cn1_sm_p8_2,
  141989. _vq_quantmap__44cn1_sm_p8_2,
  141990. 17,
  141991. 17
  141992. };
  141993. static static_codebook _44cn1_sm_p8_2 = {
  141994. 2, 289,
  141995. _vq_lengthlist__44cn1_sm_p8_2,
  141996. 1, -529530880, 1611661312, 5, 0,
  141997. _vq_quantlist__44cn1_sm_p8_2,
  141998. NULL,
  141999. &_vq_auxt__44cn1_sm_p8_2,
  142000. NULL,
  142001. 0
  142002. };
  142003. static long _huff_lengthlist__44cn1_sm_short[] = {
  142004. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  142005. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  142006. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  142007. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  142008. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  142009. 9,
  142010. };
  142011. static static_codebook _huff_book__44cn1_sm_short = {
  142012. 2, 81,
  142013. _huff_lengthlist__44cn1_sm_short,
  142014. 0, 0, 0, 0, 0,
  142015. NULL,
  142016. NULL,
  142017. NULL,
  142018. NULL,
  142019. 0
  142020. };
  142021. /*** End of inlined file: res_books_stereo.h ***/
  142022. /***** residue backends *********************************************/
  142023. static vorbis_info_residue0 _residue_44_low={
  142024. 0,-1, -1, 9,-1,
  142025. /* 0 1 2 3 4 5 6 7 */
  142026. {0},
  142027. {-1},
  142028. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  142029. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  142030. };
  142031. static vorbis_info_residue0 _residue_44_mid={
  142032. 0,-1, -1, 10,-1,
  142033. /* 0 1 2 3 4 5 6 7 8 */
  142034. {0},
  142035. {-1},
  142036. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  142037. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  142038. };
  142039. static vorbis_info_residue0 _residue_44_high={
  142040. 0,-1, -1, 10,-1,
  142041. /* 0 1 2 3 4 5 6 7 8 */
  142042. {0},
  142043. {-1},
  142044. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  142045. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  142046. };
  142047. static static_bookblock _resbook_44s_n1={
  142048. {
  142049. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  142050. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  142051. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  142052. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  142053. }
  142054. };
  142055. static static_bookblock _resbook_44sm_n1={
  142056. {
  142057. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  142058. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  142059. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  142060. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  142061. }
  142062. };
  142063. static static_bookblock _resbook_44s_0={
  142064. {
  142065. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  142066. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  142067. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  142068. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  142069. }
  142070. };
  142071. static static_bookblock _resbook_44sm_0={
  142072. {
  142073. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  142074. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  142075. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  142076. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  142077. }
  142078. };
  142079. static static_bookblock _resbook_44s_1={
  142080. {
  142081. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  142082. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  142083. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  142084. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  142085. }
  142086. };
  142087. static static_bookblock _resbook_44sm_1={
  142088. {
  142089. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  142090. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  142091. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  142092. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  142093. }
  142094. };
  142095. static static_bookblock _resbook_44s_2={
  142096. {
  142097. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  142098. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  142099. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  142100. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  142101. }
  142102. };
  142103. static static_bookblock _resbook_44s_3={
  142104. {
  142105. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  142106. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  142107. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  142108. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  142109. }
  142110. };
  142111. static static_bookblock _resbook_44s_4={
  142112. {
  142113. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  142114. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  142115. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  142116. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  142117. }
  142118. };
  142119. static static_bookblock _resbook_44s_5={
  142120. {
  142121. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  142122. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  142123. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  142124. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  142125. }
  142126. };
  142127. static static_bookblock _resbook_44s_6={
  142128. {
  142129. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  142130. {0,0,&_44c6_s_p4_0},
  142131. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  142132. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  142133. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  142134. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  142135. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  142136. }
  142137. };
  142138. static static_bookblock _resbook_44s_7={
  142139. {
  142140. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  142141. {0,0,&_44c7_s_p4_0},
  142142. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  142143. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  142144. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  142145. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  142146. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  142147. }
  142148. };
  142149. static static_bookblock _resbook_44s_8={
  142150. {
  142151. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  142152. {0,0,&_44c8_s_p4_0},
  142153. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  142154. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  142155. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  142156. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  142157. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  142158. }
  142159. };
  142160. static static_bookblock _resbook_44s_9={
  142161. {
  142162. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  142163. {0,0,&_44c9_s_p4_0},
  142164. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  142165. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  142166. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  142167. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  142168. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  142169. }
  142170. };
  142171. static vorbis_residue_template _res_44s_n1[]={
  142172. {2,0, &_residue_44_low,
  142173. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  142174. &_resbook_44s_n1,&_resbook_44sm_n1},
  142175. {2,0, &_residue_44_low,
  142176. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  142177. &_resbook_44s_n1,&_resbook_44sm_n1}
  142178. };
  142179. static vorbis_residue_template _res_44s_0[]={
  142180. {2,0, &_residue_44_low,
  142181. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  142182. &_resbook_44s_0,&_resbook_44sm_0},
  142183. {2,0, &_residue_44_low,
  142184. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  142185. &_resbook_44s_0,&_resbook_44sm_0}
  142186. };
  142187. static vorbis_residue_template _res_44s_1[]={
  142188. {2,0, &_residue_44_low,
  142189. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  142190. &_resbook_44s_1,&_resbook_44sm_1},
  142191. {2,0, &_residue_44_low,
  142192. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  142193. &_resbook_44s_1,&_resbook_44sm_1}
  142194. };
  142195. static vorbis_residue_template _res_44s_2[]={
  142196. {2,0, &_residue_44_mid,
  142197. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  142198. &_resbook_44s_2,&_resbook_44s_2},
  142199. {2,0, &_residue_44_mid,
  142200. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  142201. &_resbook_44s_2,&_resbook_44s_2}
  142202. };
  142203. static vorbis_residue_template _res_44s_3[]={
  142204. {2,0, &_residue_44_mid,
  142205. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  142206. &_resbook_44s_3,&_resbook_44s_3},
  142207. {2,0, &_residue_44_mid,
  142208. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  142209. &_resbook_44s_3,&_resbook_44s_3}
  142210. };
  142211. static vorbis_residue_template _res_44s_4[]={
  142212. {2,0, &_residue_44_mid,
  142213. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  142214. &_resbook_44s_4,&_resbook_44s_4},
  142215. {2,0, &_residue_44_mid,
  142216. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  142217. &_resbook_44s_4,&_resbook_44s_4}
  142218. };
  142219. static vorbis_residue_template _res_44s_5[]={
  142220. {2,0, &_residue_44_mid,
  142221. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  142222. &_resbook_44s_5,&_resbook_44s_5},
  142223. {2,0, &_residue_44_mid,
  142224. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  142225. &_resbook_44s_5,&_resbook_44s_5}
  142226. };
  142227. static vorbis_residue_template _res_44s_6[]={
  142228. {2,0, &_residue_44_high,
  142229. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  142230. &_resbook_44s_6,&_resbook_44s_6},
  142231. {2,0, &_residue_44_high,
  142232. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  142233. &_resbook_44s_6,&_resbook_44s_6}
  142234. };
  142235. static vorbis_residue_template _res_44s_7[]={
  142236. {2,0, &_residue_44_high,
  142237. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  142238. &_resbook_44s_7,&_resbook_44s_7},
  142239. {2,0, &_residue_44_high,
  142240. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  142241. &_resbook_44s_7,&_resbook_44s_7}
  142242. };
  142243. static vorbis_residue_template _res_44s_8[]={
  142244. {2,0, &_residue_44_high,
  142245. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  142246. &_resbook_44s_8,&_resbook_44s_8},
  142247. {2,0, &_residue_44_high,
  142248. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  142249. &_resbook_44s_8,&_resbook_44s_8}
  142250. };
  142251. static vorbis_residue_template _res_44s_9[]={
  142252. {2,0, &_residue_44_high,
  142253. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  142254. &_resbook_44s_9,&_resbook_44s_9},
  142255. {2,0, &_residue_44_high,
  142256. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  142257. &_resbook_44s_9,&_resbook_44s_9}
  142258. };
  142259. static vorbis_mapping_template _mapres_template_44_stereo[]={
  142260. { _map_nominal, _res_44s_n1 }, /* -1 */
  142261. { _map_nominal, _res_44s_0 }, /* 0 */
  142262. { _map_nominal, _res_44s_1 }, /* 1 */
  142263. { _map_nominal, _res_44s_2 }, /* 2 */
  142264. { _map_nominal, _res_44s_3 }, /* 3 */
  142265. { _map_nominal, _res_44s_4 }, /* 4 */
  142266. { _map_nominal, _res_44s_5 }, /* 5 */
  142267. { _map_nominal, _res_44s_6 }, /* 6 */
  142268. { _map_nominal, _res_44s_7 }, /* 7 */
  142269. { _map_nominal, _res_44s_8 }, /* 8 */
  142270. { _map_nominal, _res_44s_9 }, /* 9 */
  142271. };
  142272. /*** End of inlined file: residue_44.h ***/
  142273. /*** Start of inlined file: psych_44.h ***/
  142274. /* preecho trigger settings *****************************************/
  142275. static vorbis_info_psy_global _psy_global_44[5]={
  142276. {8, /* lines per eighth octave */
  142277. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  142278. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  142279. -6.f,
  142280. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142281. },
  142282. {8, /* lines per eighth octave */
  142283. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  142284. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  142285. -6.f,
  142286. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142287. },
  142288. {8, /* lines per eighth octave */
  142289. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  142290. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  142291. -6.f,
  142292. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142293. },
  142294. {8, /* lines per eighth octave */
  142295. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  142296. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  142297. -6.f,
  142298. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142299. },
  142300. {8, /* lines per eighth octave */
  142301. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  142302. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  142303. -6.f,
  142304. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142305. },
  142306. };
  142307. /* noise compander lookups * low, mid, high quality ****************/
  142308. static compandblock _psy_compand_44[6]={
  142309. /* sub-mode Z short */
  142310. {{
  142311. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142312. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142313. 16,17,18,19,20,21,22, 23, /* 23dB */
  142314. 24,25,26,27,28,29,30, 31, /* 31dB */
  142315. 32,33,34,35,36,37,38, 39, /* 39dB */
  142316. }},
  142317. /* mode_Z nominal short */
  142318. {{
  142319. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  142320. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  142321. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  142322. 15,16,17,17,17,18,18, 19, /* 31dB */
  142323. 19,19,20,21,22,23,24, 25, /* 39dB */
  142324. }},
  142325. /* mode A short */
  142326. {{
  142327. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  142328. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  142329. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142330. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142331. 11,12,13,14,15,16,17, 18, /* 39dB */
  142332. }},
  142333. /* sub-mode Z long */
  142334. {{
  142335. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142336. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142337. 16,17,18,19,20,21,22, 23, /* 23dB */
  142338. 24,25,26,27,28,29,30, 31, /* 31dB */
  142339. 32,33,34,35,36,37,38, 39, /* 39dB */
  142340. }},
  142341. /* mode_Z nominal long */
  142342. {{
  142343. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142344. 8, 9,10,11,12,12,13, 13, /* 15dB */
  142345. 13,14,14,14,15,15,15, 15, /* 23dB */
  142346. 16,16,17,17,17,18,18, 19, /* 31dB */
  142347. 19,19,20,21,22,23,24, 25, /* 39dB */
  142348. }},
  142349. /* mode A long */
  142350. {{
  142351. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142352. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  142353. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142354. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142355. 11,12,13,14,15,16,17, 18, /* 39dB */
  142356. }}
  142357. };
  142358. /* tonal masking curve level adjustments *************************/
  142359. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  142360. /* 63 125 250 500 1 2 4 8 16 */
  142361. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  142362. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142363. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  142364. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142365. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  142366. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142367. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  142368. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142369. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  142370. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  142371. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142372. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142373. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142374. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142375. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142376. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142377. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142378. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142379. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142380. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142381. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142382. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142383. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142384. };
  142385. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  142386. /* 63 125 250 500 1 2 4 8 16 */
  142387. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  142388. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142389. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  142390. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142391. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  142392. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142393. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  142394. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142395. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  142396. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 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. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 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. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 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. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 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. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 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. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 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. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 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. /* noise bias (transition block) */
  142412. static noise3 _psy_noisebias_trans[12]={
  142413. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142414. /* -1 */
  142415. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142416. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142417. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142418. /* 0
  142419. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142420. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  142421. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142422. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142423. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  142424. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142425. /* 1
  142426. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142427. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142428. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142429. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142430. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142431. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142432. /* 2
  142433. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142434. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142435. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  142436. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142437. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142438. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  142439. /* 3
  142440. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142441. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142442. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142443. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142444. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142445. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142446. /* 4
  142447. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142448. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142449. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142450. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142451. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142452. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142453. /* 5
  142454. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142455. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142456. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  142457. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142458. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142459. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  142460. /* 6
  142461. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142462. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142463. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142464. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142465. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142466. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142467. /* 7
  142468. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142469. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  142470. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  142471. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142472. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142473. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142474. /* 8
  142475. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142476. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142477. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142478. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142479. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142480. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142481. /* 9
  142482. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142483. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142484. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142485. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142486. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  142487. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  142488. /* 10 */
  142489. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  142490. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  142491. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142492. };
  142493. /* noise bias (long block) */
  142494. static noise3 _psy_noisebias_long[12]={
  142495. /*63 125 250 500 1k 2k 4k 8k 16k*/
  142496. /* -1 */
  142497. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  142498. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  142499. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142500. /* 0 */
  142501. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142502. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  142503. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142504. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142505. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  142506. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142507. /* 1 */
  142508. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142509. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142510. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142511. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142512. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142513. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142514. /* 2 */
  142515. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142516. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142517. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142518. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142519. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142520. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142521. /* 3 */
  142522. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142523. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142524. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142525. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142526. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142527. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  142528. /* 4 */
  142529. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142530. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142531. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142532. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142533. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142534. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  142535. /* 5 */
  142536. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142537. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142538. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  142539. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142540. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142541. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  142542. /* 6 */
  142543. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142544. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142545. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142546. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142547. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142548. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  142549. /* 7 */
  142550. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142551. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  142552. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142553. /* 8 */
  142554. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  142555. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  142556. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142557. /* 9 */
  142558. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142559. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  142560. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142561. /* 10 */
  142562. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  142563. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  142564. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142565. };
  142566. /* noise bias (impulse block) */
  142567. static noise3 _psy_noisebias_impulse[12]={
  142568. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142569. /* -1 */
  142570. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142571. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142572. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142573. /* 0 */
  142574. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142575. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  142576. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  142577. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142578. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  142579. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142580. /* 1 */
  142581. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142582. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  142583. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  142584. /* 2 */
  142585. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142586. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142587. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142588. /* 3 */
  142589. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142590. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142591. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142592. /* 4 */
  142593. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142594. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142595. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142596. /* 5 */
  142597. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142598. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  142599. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  142600. /* 6
  142601. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142602. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  142603. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  142604. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142605. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  142606. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  142607. /* 7 */
  142608. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142609. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  142610. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  142611. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142612. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  142613. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142614. /* 8 */
  142615. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142616. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  142617. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142618. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142619. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  142620. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142621. /* 9 */
  142622. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142623. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  142624. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142625. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142626. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  142627. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142628. /* 10 */
  142629. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  142630. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  142631. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142632. };
  142633. /* noise bias (padding block) */
  142634. static noise3 _psy_noisebias_padding[12]={
  142635. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142636. /* -1 */
  142637. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142638. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142639. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142640. /* 0 */
  142641. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142642. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  142643. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  142644. /* 1 */
  142645. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142646. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142647. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  142648. /* 2 */
  142649. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142650. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142651. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  142652. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142653. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142654. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142655. /* 3 */
  142656. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142657. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142658. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142659. /* 4 */
  142660. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142661. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  142662. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142663. /* 5 */
  142664. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142665. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  142666. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  142667. /* 6 */
  142668. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142669. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  142670. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  142671. /* 7 */
  142672. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142673. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  142674. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  142675. /* 8 */
  142676. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  142677. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  142678. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  142679. /* 9 */
  142680. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  142681. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  142682. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  142683. /* 10 */
  142684. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  142685. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  142686. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142687. };
  142688. static noiseguard _psy_noiseguards_44[4]={
  142689. {3,3,15},
  142690. {3,3,15},
  142691. {10,10,100},
  142692. {10,10,100},
  142693. };
  142694. static int _psy_tone_suppress[12]={
  142695. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  142696. };
  142697. static int _psy_tone_0dB[12]={
  142698. 90,90,95,95,95,95,105,105,105,105,105,105,
  142699. };
  142700. static int _psy_noise_suppress[12]={
  142701. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  142702. };
  142703. static vorbis_info_psy _psy_info_template={
  142704. /* blockflag */
  142705. -1,
  142706. /* ath_adjatt, ath_maxatt */
  142707. -140.,-140.,
  142708. /* tonemask att boost/decay,suppr,curves */
  142709. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  142710. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  142711. 1, -0.f, .5f, .5f, 0,0,0,
  142712. /* noiseoffset*3, noisecompand, max_curve_dB */
  142713. {{-1},{-1},{-1}},{-1},105.f,
  142714. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  142715. 0,0,-1,-1,0.,
  142716. };
  142717. /* ath ****************/
  142718. static int _psy_ath_floater[12]={
  142719. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  142720. };
  142721. static int _psy_ath_abs[12]={
  142722. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  142723. };
  142724. /* stereo setup. These don't map directly to quality level, there's
  142725. an additional indirection as several of the below may be used in a
  142726. single bitmanaged stream
  142727. ****************/
  142728. /* various stereo possibilities */
  142729. /* stereo mode by base quality level */
  142730. static adj_stereo _psy_stereo_modes_44[12]={
  142731. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  142732. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142733. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142734. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  142735. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142736. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  142737. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142738. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142739. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  142740. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142741. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  142742. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142743. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142744. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142745. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  142746. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  142747. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142748. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142749. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142750. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  142751. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  142752. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  142753. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142754. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142755. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  142756. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142757. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142758. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142759. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  142760. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  142761. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142762. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  142763. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142764. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  142765. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142766. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  142767. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  142768. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142769. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  142770. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142771. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142772. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142773. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142774. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142775. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142776. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  142777. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142778. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  142779. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142780. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142781. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142782. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142783. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142784. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142785. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142786. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142787. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  142788. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142789. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142790. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142791. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142792. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142793. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142794. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142795. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142796. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  142797. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142798. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142799. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  142800. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142801. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142802. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142803. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  142804. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142805. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  142806. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142807. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142808. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142809. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142810. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  142811. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142812. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142813. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  142814. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142815. };
  142816. /* tone master attenuation by base quality mode and bitrate tweak */
  142817. static att3 _psy_tone_masteratt_44[12]={
  142818. {{ 35, 21, 9}, 0, 0}, /* -1 */
  142819. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  142820. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  142821. {{ 25, 12, 2}, 0, 0}, /* 1 */
  142822. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  142823. {{ 20, 9, -3}, 0, 0}, /* 2 */
  142824. {{ 20, 9, -4}, 0, 0}, /* 3 */
  142825. {{ 20, 9, -4}, 0, 0}, /* 4 */
  142826. {{ 20, 6, -6}, 0, 0}, /* 5 */
  142827. {{ 20, 3, -10}, 0, 0}, /* 6 */
  142828. {{ 18, 1, -14}, 0, 0}, /* 7 */
  142829. {{ 18, 0, -16}, 0, 0}, /* 8 */
  142830. {{ 18, -2, -16}, 0, 0}, /* 9 */
  142831. {{ 12, -2, -20}, 0, 0}, /* 10 */
  142832. };
  142833. /* lowpass by mode **************/
  142834. static double _psy_lowpass_44[12]={
  142835. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  142836. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  142837. };
  142838. /* noise normalization **********/
  142839. static int _noise_start_short_44[11]={
  142840. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  142841. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  142842. };
  142843. static int _noise_start_long_44[11]={
  142844. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  142845. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  142846. };
  142847. static int _noise_part_short_44[11]={
  142848. 8,8,8,8,8,8,8,8,8,8,8
  142849. };
  142850. static int _noise_part_long_44[11]={
  142851. 32,32,32,32,32,32,32,32,32,32,32
  142852. };
  142853. static double _noise_thresh_44[11]={
  142854. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  142855. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  142856. };
  142857. static double _noise_thresh_5only[2]={
  142858. .5,.5,
  142859. };
  142860. /*** End of inlined file: psych_44.h ***/
  142861. static double rate_mapping_44_stereo[12]={
  142862. 22500.,32000.,40000.,48000.,56000.,64000.,
  142863. 80000.,96000.,112000.,128000.,160000.,250001.
  142864. };
  142865. static double quality_mapping_44[12]={
  142866. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  142867. };
  142868. static int blocksize_short_44[11]={
  142869. 512,256,256,256,256,256,256,256,256,256,256
  142870. };
  142871. static int blocksize_long_44[11]={
  142872. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  142873. };
  142874. static double _psy_compand_short_mapping[12]={
  142875. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  142876. };
  142877. static double _psy_compand_long_mapping[12]={
  142878. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  142879. };
  142880. static double _global_mapping_44[12]={
  142881. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  142882. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  142883. };
  142884. static int _floor_short_mapping_44[11]={
  142885. 1,0,0,2,2,4,5,5,5,5,5
  142886. };
  142887. static int _floor_long_mapping_44[11]={
  142888. 8,7,7,7,7,7,7,7,7,7,7
  142889. };
  142890. ve_setup_data_template ve_setup_44_stereo={
  142891. 11,
  142892. rate_mapping_44_stereo,
  142893. quality_mapping_44,
  142894. 2,
  142895. 40000,
  142896. 50000,
  142897. blocksize_short_44,
  142898. blocksize_long_44,
  142899. _psy_tone_masteratt_44,
  142900. _psy_tone_0dB,
  142901. _psy_tone_suppress,
  142902. _vp_tonemask_adj_otherblock,
  142903. _vp_tonemask_adj_longblock,
  142904. _vp_tonemask_adj_otherblock,
  142905. _psy_noiseguards_44,
  142906. _psy_noisebias_impulse,
  142907. _psy_noisebias_padding,
  142908. _psy_noisebias_trans,
  142909. _psy_noisebias_long,
  142910. _psy_noise_suppress,
  142911. _psy_compand_44,
  142912. _psy_compand_short_mapping,
  142913. _psy_compand_long_mapping,
  142914. {_noise_start_short_44,_noise_start_long_44},
  142915. {_noise_part_short_44,_noise_part_long_44},
  142916. _noise_thresh_44,
  142917. _psy_ath_floater,
  142918. _psy_ath_abs,
  142919. _psy_lowpass_44,
  142920. _psy_global_44,
  142921. _global_mapping_44,
  142922. _psy_stereo_modes_44,
  142923. _floor_books,
  142924. _floor,
  142925. _floor_short_mapping_44,
  142926. _floor_long_mapping_44,
  142927. _mapres_template_44_stereo
  142928. };
  142929. /*** End of inlined file: setup_44.h ***/
  142930. /*** Start of inlined file: setup_44u.h ***/
  142931. /*** Start of inlined file: residue_44u.h ***/
  142932. /*** Start of inlined file: res_books_uncoupled.h ***/
  142933. static long _vq_quantlist__16u0__p1_0[] = {
  142934. 1,
  142935. 0,
  142936. 2,
  142937. };
  142938. static long _vq_lengthlist__16u0__p1_0[] = {
  142939. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  142940. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  142941. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  142942. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  142943. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  142944. 12,
  142945. };
  142946. static float _vq_quantthresh__16u0__p1_0[] = {
  142947. -0.5, 0.5,
  142948. };
  142949. static long _vq_quantmap__16u0__p1_0[] = {
  142950. 1, 0, 2,
  142951. };
  142952. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  142953. _vq_quantthresh__16u0__p1_0,
  142954. _vq_quantmap__16u0__p1_0,
  142955. 3,
  142956. 3
  142957. };
  142958. static static_codebook _16u0__p1_0 = {
  142959. 4, 81,
  142960. _vq_lengthlist__16u0__p1_0,
  142961. 1, -535822336, 1611661312, 2, 0,
  142962. _vq_quantlist__16u0__p1_0,
  142963. NULL,
  142964. &_vq_auxt__16u0__p1_0,
  142965. NULL,
  142966. 0
  142967. };
  142968. static long _vq_quantlist__16u0__p2_0[] = {
  142969. 1,
  142970. 0,
  142971. 2,
  142972. };
  142973. static long _vq_lengthlist__16u0__p2_0[] = {
  142974. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  142975. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  142976. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  142977. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  142978. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  142979. 8,
  142980. };
  142981. static float _vq_quantthresh__16u0__p2_0[] = {
  142982. -0.5, 0.5,
  142983. };
  142984. static long _vq_quantmap__16u0__p2_0[] = {
  142985. 1, 0, 2,
  142986. };
  142987. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  142988. _vq_quantthresh__16u0__p2_0,
  142989. _vq_quantmap__16u0__p2_0,
  142990. 3,
  142991. 3
  142992. };
  142993. static static_codebook _16u0__p2_0 = {
  142994. 4, 81,
  142995. _vq_lengthlist__16u0__p2_0,
  142996. 1, -535822336, 1611661312, 2, 0,
  142997. _vq_quantlist__16u0__p2_0,
  142998. NULL,
  142999. &_vq_auxt__16u0__p2_0,
  143000. NULL,
  143001. 0
  143002. };
  143003. static long _vq_quantlist__16u0__p3_0[] = {
  143004. 2,
  143005. 1,
  143006. 3,
  143007. 0,
  143008. 4,
  143009. };
  143010. static long _vq_lengthlist__16u0__p3_0[] = {
  143011. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  143012. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  143013. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  143014. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  143015. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  143016. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  143017. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  143018. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  143019. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  143020. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  143021. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  143022. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  143023. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  143024. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  143025. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  143026. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  143027. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  143028. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  143029. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  143030. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  143031. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  143032. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  143033. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  143034. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  143035. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  143036. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  143037. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  143038. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  143039. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  143040. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  143041. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  143042. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  143043. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  143044. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  143045. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  143046. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  143047. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  143048. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  143049. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  143050. 18,
  143051. };
  143052. static float _vq_quantthresh__16u0__p3_0[] = {
  143053. -1.5, -0.5, 0.5, 1.5,
  143054. };
  143055. static long _vq_quantmap__16u0__p3_0[] = {
  143056. 3, 1, 0, 2, 4,
  143057. };
  143058. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  143059. _vq_quantthresh__16u0__p3_0,
  143060. _vq_quantmap__16u0__p3_0,
  143061. 5,
  143062. 5
  143063. };
  143064. static static_codebook _16u0__p3_0 = {
  143065. 4, 625,
  143066. _vq_lengthlist__16u0__p3_0,
  143067. 1, -533725184, 1611661312, 3, 0,
  143068. _vq_quantlist__16u0__p3_0,
  143069. NULL,
  143070. &_vq_auxt__16u0__p3_0,
  143071. NULL,
  143072. 0
  143073. };
  143074. static long _vq_quantlist__16u0__p4_0[] = {
  143075. 2,
  143076. 1,
  143077. 3,
  143078. 0,
  143079. 4,
  143080. };
  143081. static long _vq_lengthlist__16u0__p4_0[] = {
  143082. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  143083. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  143084. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  143085. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  143086. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  143087. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  143088. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  143089. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  143090. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  143091. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  143092. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  143093. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  143094. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  143095. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  143096. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  143097. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  143098. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  143099. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  143100. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  143101. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  143102. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  143103. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  143104. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  143105. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  143106. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  143107. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  143108. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  143109. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  143110. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  143111. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  143112. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  143113. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  143114. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  143115. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  143116. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  143117. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  143118. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  143119. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  143120. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  143121. 11,
  143122. };
  143123. static float _vq_quantthresh__16u0__p4_0[] = {
  143124. -1.5, -0.5, 0.5, 1.5,
  143125. };
  143126. static long _vq_quantmap__16u0__p4_0[] = {
  143127. 3, 1, 0, 2, 4,
  143128. };
  143129. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  143130. _vq_quantthresh__16u0__p4_0,
  143131. _vq_quantmap__16u0__p4_0,
  143132. 5,
  143133. 5
  143134. };
  143135. static static_codebook _16u0__p4_0 = {
  143136. 4, 625,
  143137. _vq_lengthlist__16u0__p4_0,
  143138. 1, -533725184, 1611661312, 3, 0,
  143139. _vq_quantlist__16u0__p4_0,
  143140. NULL,
  143141. &_vq_auxt__16u0__p4_0,
  143142. NULL,
  143143. 0
  143144. };
  143145. static long _vq_quantlist__16u0__p5_0[] = {
  143146. 4,
  143147. 3,
  143148. 5,
  143149. 2,
  143150. 6,
  143151. 1,
  143152. 7,
  143153. 0,
  143154. 8,
  143155. };
  143156. static long _vq_lengthlist__16u0__p5_0[] = {
  143157. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143158. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  143159. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  143160. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  143161. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  143162. 12,
  143163. };
  143164. static float _vq_quantthresh__16u0__p5_0[] = {
  143165. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143166. };
  143167. static long _vq_quantmap__16u0__p5_0[] = {
  143168. 7, 5, 3, 1, 0, 2, 4, 6,
  143169. 8,
  143170. };
  143171. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  143172. _vq_quantthresh__16u0__p5_0,
  143173. _vq_quantmap__16u0__p5_0,
  143174. 9,
  143175. 9
  143176. };
  143177. static static_codebook _16u0__p5_0 = {
  143178. 2, 81,
  143179. _vq_lengthlist__16u0__p5_0,
  143180. 1, -531628032, 1611661312, 4, 0,
  143181. _vq_quantlist__16u0__p5_0,
  143182. NULL,
  143183. &_vq_auxt__16u0__p5_0,
  143184. NULL,
  143185. 0
  143186. };
  143187. static long _vq_quantlist__16u0__p6_0[] = {
  143188. 6,
  143189. 5,
  143190. 7,
  143191. 4,
  143192. 8,
  143193. 3,
  143194. 9,
  143195. 2,
  143196. 10,
  143197. 1,
  143198. 11,
  143199. 0,
  143200. 12,
  143201. };
  143202. static long _vq_lengthlist__16u0__p6_0[] = {
  143203. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  143204. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  143205. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  143206. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  143207. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  143208. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  143209. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  143210. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  143211. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  143212. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  143213. 18, 0,19, 0, 0, 0, 0, 0, 0,
  143214. };
  143215. static float _vq_quantthresh__16u0__p6_0[] = {
  143216. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143217. 12.5, 17.5, 22.5, 27.5,
  143218. };
  143219. static long _vq_quantmap__16u0__p6_0[] = {
  143220. 11, 9, 7, 5, 3, 1, 0, 2,
  143221. 4, 6, 8, 10, 12,
  143222. };
  143223. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  143224. _vq_quantthresh__16u0__p6_0,
  143225. _vq_quantmap__16u0__p6_0,
  143226. 13,
  143227. 13
  143228. };
  143229. static static_codebook _16u0__p6_0 = {
  143230. 2, 169,
  143231. _vq_lengthlist__16u0__p6_0,
  143232. 1, -526516224, 1616117760, 4, 0,
  143233. _vq_quantlist__16u0__p6_0,
  143234. NULL,
  143235. &_vq_auxt__16u0__p6_0,
  143236. NULL,
  143237. 0
  143238. };
  143239. static long _vq_quantlist__16u0__p6_1[] = {
  143240. 2,
  143241. 1,
  143242. 3,
  143243. 0,
  143244. 4,
  143245. };
  143246. static long _vq_lengthlist__16u0__p6_1[] = {
  143247. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  143248. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  143249. };
  143250. static float _vq_quantthresh__16u0__p6_1[] = {
  143251. -1.5, -0.5, 0.5, 1.5,
  143252. };
  143253. static long _vq_quantmap__16u0__p6_1[] = {
  143254. 3, 1, 0, 2, 4,
  143255. };
  143256. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  143257. _vq_quantthresh__16u0__p6_1,
  143258. _vq_quantmap__16u0__p6_1,
  143259. 5,
  143260. 5
  143261. };
  143262. static static_codebook _16u0__p6_1 = {
  143263. 2, 25,
  143264. _vq_lengthlist__16u0__p6_1,
  143265. 1, -533725184, 1611661312, 3, 0,
  143266. _vq_quantlist__16u0__p6_1,
  143267. NULL,
  143268. &_vq_auxt__16u0__p6_1,
  143269. NULL,
  143270. 0
  143271. };
  143272. static long _vq_quantlist__16u0__p7_0[] = {
  143273. 1,
  143274. 0,
  143275. 2,
  143276. };
  143277. static long _vq_lengthlist__16u0__p7_0[] = {
  143278. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143279. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143280. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143281. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143282. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143283. 7,
  143284. };
  143285. static float _vq_quantthresh__16u0__p7_0[] = {
  143286. -157.5, 157.5,
  143287. };
  143288. static long _vq_quantmap__16u0__p7_0[] = {
  143289. 1, 0, 2,
  143290. };
  143291. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  143292. _vq_quantthresh__16u0__p7_0,
  143293. _vq_quantmap__16u0__p7_0,
  143294. 3,
  143295. 3
  143296. };
  143297. static static_codebook _16u0__p7_0 = {
  143298. 4, 81,
  143299. _vq_lengthlist__16u0__p7_0,
  143300. 1, -518803456, 1628680192, 2, 0,
  143301. _vq_quantlist__16u0__p7_0,
  143302. NULL,
  143303. &_vq_auxt__16u0__p7_0,
  143304. NULL,
  143305. 0
  143306. };
  143307. static long _vq_quantlist__16u0__p7_1[] = {
  143308. 7,
  143309. 6,
  143310. 8,
  143311. 5,
  143312. 9,
  143313. 4,
  143314. 10,
  143315. 3,
  143316. 11,
  143317. 2,
  143318. 12,
  143319. 1,
  143320. 13,
  143321. 0,
  143322. 14,
  143323. };
  143324. static long _vq_lengthlist__16u0__p7_1[] = {
  143325. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  143326. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  143327. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  143328. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  143329. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  143330. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  143331. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143332. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143333. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143334. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143335. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143336. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143337. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143338. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143339. 10,
  143340. };
  143341. static float _vq_quantthresh__16u0__p7_1[] = {
  143342. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  143343. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  143344. };
  143345. static long _vq_quantmap__16u0__p7_1[] = {
  143346. 13, 11, 9, 7, 5, 3, 1, 0,
  143347. 2, 4, 6, 8, 10, 12, 14,
  143348. };
  143349. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  143350. _vq_quantthresh__16u0__p7_1,
  143351. _vq_quantmap__16u0__p7_1,
  143352. 15,
  143353. 15
  143354. };
  143355. static static_codebook _16u0__p7_1 = {
  143356. 2, 225,
  143357. _vq_lengthlist__16u0__p7_1,
  143358. 1, -520986624, 1620377600, 4, 0,
  143359. _vq_quantlist__16u0__p7_1,
  143360. NULL,
  143361. &_vq_auxt__16u0__p7_1,
  143362. NULL,
  143363. 0
  143364. };
  143365. static long _vq_quantlist__16u0__p7_2[] = {
  143366. 10,
  143367. 9,
  143368. 11,
  143369. 8,
  143370. 12,
  143371. 7,
  143372. 13,
  143373. 6,
  143374. 14,
  143375. 5,
  143376. 15,
  143377. 4,
  143378. 16,
  143379. 3,
  143380. 17,
  143381. 2,
  143382. 18,
  143383. 1,
  143384. 19,
  143385. 0,
  143386. 20,
  143387. };
  143388. static long _vq_lengthlist__16u0__p7_2[] = {
  143389. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  143390. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  143391. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  143392. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  143393. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  143394. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  143395. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  143396. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  143397. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  143398. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  143399. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  143400. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  143401. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  143402. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  143403. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  143404. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  143405. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  143406. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  143407. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  143408. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  143409. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  143410. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  143411. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  143412. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  143413. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  143414. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  143415. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  143416. 10,10,12,11,10,11,11,11,10,
  143417. };
  143418. static float _vq_quantthresh__16u0__p7_2[] = {
  143419. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  143420. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  143421. 6.5, 7.5, 8.5, 9.5,
  143422. };
  143423. static long _vq_quantmap__16u0__p7_2[] = {
  143424. 19, 17, 15, 13, 11, 9, 7, 5,
  143425. 3, 1, 0, 2, 4, 6, 8, 10,
  143426. 12, 14, 16, 18, 20,
  143427. };
  143428. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  143429. _vq_quantthresh__16u0__p7_2,
  143430. _vq_quantmap__16u0__p7_2,
  143431. 21,
  143432. 21
  143433. };
  143434. static static_codebook _16u0__p7_2 = {
  143435. 2, 441,
  143436. _vq_lengthlist__16u0__p7_2,
  143437. 1, -529268736, 1611661312, 5, 0,
  143438. _vq_quantlist__16u0__p7_2,
  143439. NULL,
  143440. &_vq_auxt__16u0__p7_2,
  143441. NULL,
  143442. 0
  143443. };
  143444. static long _huff_lengthlist__16u0__single[] = {
  143445. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  143446. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  143447. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  143448. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  143449. };
  143450. static static_codebook _huff_book__16u0__single = {
  143451. 2, 64,
  143452. _huff_lengthlist__16u0__single,
  143453. 0, 0, 0, 0, 0,
  143454. NULL,
  143455. NULL,
  143456. NULL,
  143457. NULL,
  143458. 0
  143459. };
  143460. static long _huff_lengthlist__16u1__long[] = {
  143461. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  143462. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  143463. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  143464. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  143465. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  143466. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  143467. 16,13,16,18,
  143468. };
  143469. static static_codebook _huff_book__16u1__long = {
  143470. 2, 100,
  143471. _huff_lengthlist__16u1__long,
  143472. 0, 0, 0, 0, 0,
  143473. NULL,
  143474. NULL,
  143475. NULL,
  143476. NULL,
  143477. 0
  143478. };
  143479. static long _vq_quantlist__16u1__p1_0[] = {
  143480. 1,
  143481. 0,
  143482. 2,
  143483. };
  143484. static long _vq_lengthlist__16u1__p1_0[] = {
  143485. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  143486. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  143487. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  143488. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  143489. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  143490. 11,
  143491. };
  143492. static float _vq_quantthresh__16u1__p1_0[] = {
  143493. -0.5, 0.5,
  143494. };
  143495. static long _vq_quantmap__16u1__p1_0[] = {
  143496. 1, 0, 2,
  143497. };
  143498. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  143499. _vq_quantthresh__16u1__p1_0,
  143500. _vq_quantmap__16u1__p1_0,
  143501. 3,
  143502. 3
  143503. };
  143504. static static_codebook _16u1__p1_0 = {
  143505. 4, 81,
  143506. _vq_lengthlist__16u1__p1_0,
  143507. 1, -535822336, 1611661312, 2, 0,
  143508. _vq_quantlist__16u1__p1_0,
  143509. NULL,
  143510. &_vq_auxt__16u1__p1_0,
  143511. NULL,
  143512. 0
  143513. };
  143514. static long _vq_quantlist__16u1__p2_0[] = {
  143515. 1,
  143516. 0,
  143517. 2,
  143518. };
  143519. static long _vq_lengthlist__16u1__p2_0[] = {
  143520. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  143521. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  143522. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  143523. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  143524. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  143525. 8,
  143526. };
  143527. static float _vq_quantthresh__16u1__p2_0[] = {
  143528. -0.5, 0.5,
  143529. };
  143530. static long _vq_quantmap__16u1__p2_0[] = {
  143531. 1, 0, 2,
  143532. };
  143533. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  143534. _vq_quantthresh__16u1__p2_0,
  143535. _vq_quantmap__16u1__p2_0,
  143536. 3,
  143537. 3
  143538. };
  143539. static static_codebook _16u1__p2_0 = {
  143540. 4, 81,
  143541. _vq_lengthlist__16u1__p2_0,
  143542. 1, -535822336, 1611661312, 2, 0,
  143543. _vq_quantlist__16u1__p2_0,
  143544. NULL,
  143545. &_vq_auxt__16u1__p2_0,
  143546. NULL,
  143547. 0
  143548. };
  143549. static long _vq_quantlist__16u1__p3_0[] = {
  143550. 2,
  143551. 1,
  143552. 3,
  143553. 0,
  143554. 4,
  143555. };
  143556. static long _vq_lengthlist__16u1__p3_0[] = {
  143557. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  143558. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  143559. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  143560. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  143561. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  143562. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  143563. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  143564. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  143565. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  143566. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  143567. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  143568. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  143569. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  143570. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  143571. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  143572. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  143573. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  143574. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  143575. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  143576. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  143577. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  143578. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  143579. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  143580. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  143581. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  143582. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  143583. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  143584. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  143585. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  143586. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  143587. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  143588. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  143589. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  143590. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  143591. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  143592. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  143593. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  143594. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  143595. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  143596. 16,
  143597. };
  143598. static float _vq_quantthresh__16u1__p3_0[] = {
  143599. -1.5, -0.5, 0.5, 1.5,
  143600. };
  143601. static long _vq_quantmap__16u1__p3_0[] = {
  143602. 3, 1, 0, 2, 4,
  143603. };
  143604. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  143605. _vq_quantthresh__16u1__p3_0,
  143606. _vq_quantmap__16u1__p3_0,
  143607. 5,
  143608. 5
  143609. };
  143610. static static_codebook _16u1__p3_0 = {
  143611. 4, 625,
  143612. _vq_lengthlist__16u1__p3_0,
  143613. 1, -533725184, 1611661312, 3, 0,
  143614. _vq_quantlist__16u1__p3_0,
  143615. NULL,
  143616. &_vq_auxt__16u1__p3_0,
  143617. NULL,
  143618. 0
  143619. };
  143620. static long _vq_quantlist__16u1__p4_0[] = {
  143621. 2,
  143622. 1,
  143623. 3,
  143624. 0,
  143625. 4,
  143626. };
  143627. static long _vq_lengthlist__16u1__p4_0[] = {
  143628. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  143629. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  143630. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  143631. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  143632. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  143633. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  143634. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  143635. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  143636. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  143637. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  143638. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  143639. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  143640. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  143641. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  143642. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  143643. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  143644. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  143645. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  143646. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  143647. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  143648. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  143649. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  143650. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  143651. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  143652. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  143653. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  143654. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  143655. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  143656. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  143657. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  143658. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  143659. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  143660. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  143661. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  143662. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  143663. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  143664. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  143665. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  143666. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  143667. 11,
  143668. };
  143669. static float _vq_quantthresh__16u1__p4_0[] = {
  143670. -1.5, -0.5, 0.5, 1.5,
  143671. };
  143672. static long _vq_quantmap__16u1__p4_0[] = {
  143673. 3, 1, 0, 2, 4,
  143674. };
  143675. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  143676. _vq_quantthresh__16u1__p4_0,
  143677. _vq_quantmap__16u1__p4_0,
  143678. 5,
  143679. 5
  143680. };
  143681. static static_codebook _16u1__p4_0 = {
  143682. 4, 625,
  143683. _vq_lengthlist__16u1__p4_0,
  143684. 1, -533725184, 1611661312, 3, 0,
  143685. _vq_quantlist__16u1__p4_0,
  143686. NULL,
  143687. &_vq_auxt__16u1__p4_0,
  143688. NULL,
  143689. 0
  143690. };
  143691. static long _vq_quantlist__16u1__p5_0[] = {
  143692. 4,
  143693. 3,
  143694. 5,
  143695. 2,
  143696. 6,
  143697. 1,
  143698. 7,
  143699. 0,
  143700. 8,
  143701. };
  143702. static long _vq_lengthlist__16u1__p5_0[] = {
  143703. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143704. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  143705. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  143706. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  143707. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  143708. 13,
  143709. };
  143710. static float _vq_quantthresh__16u1__p5_0[] = {
  143711. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143712. };
  143713. static long _vq_quantmap__16u1__p5_0[] = {
  143714. 7, 5, 3, 1, 0, 2, 4, 6,
  143715. 8,
  143716. };
  143717. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  143718. _vq_quantthresh__16u1__p5_0,
  143719. _vq_quantmap__16u1__p5_0,
  143720. 9,
  143721. 9
  143722. };
  143723. static static_codebook _16u1__p5_0 = {
  143724. 2, 81,
  143725. _vq_lengthlist__16u1__p5_0,
  143726. 1, -531628032, 1611661312, 4, 0,
  143727. _vq_quantlist__16u1__p5_0,
  143728. NULL,
  143729. &_vq_auxt__16u1__p5_0,
  143730. NULL,
  143731. 0
  143732. };
  143733. static long _vq_quantlist__16u1__p6_0[] = {
  143734. 4,
  143735. 3,
  143736. 5,
  143737. 2,
  143738. 6,
  143739. 1,
  143740. 7,
  143741. 0,
  143742. 8,
  143743. };
  143744. static long _vq_lengthlist__16u1__p6_0[] = {
  143745. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  143746. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  143747. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  143748. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  143749. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  143750. 11,
  143751. };
  143752. static float _vq_quantthresh__16u1__p6_0[] = {
  143753. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143754. };
  143755. static long _vq_quantmap__16u1__p6_0[] = {
  143756. 7, 5, 3, 1, 0, 2, 4, 6,
  143757. 8,
  143758. };
  143759. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  143760. _vq_quantthresh__16u1__p6_0,
  143761. _vq_quantmap__16u1__p6_0,
  143762. 9,
  143763. 9
  143764. };
  143765. static static_codebook _16u1__p6_0 = {
  143766. 2, 81,
  143767. _vq_lengthlist__16u1__p6_0,
  143768. 1, -531628032, 1611661312, 4, 0,
  143769. _vq_quantlist__16u1__p6_0,
  143770. NULL,
  143771. &_vq_auxt__16u1__p6_0,
  143772. NULL,
  143773. 0
  143774. };
  143775. static long _vq_quantlist__16u1__p7_0[] = {
  143776. 1,
  143777. 0,
  143778. 2,
  143779. };
  143780. static long _vq_lengthlist__16u1__p7_0[] = {
  143781. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  143782. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  143783. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  143784. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  143785. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  143786. 13,
  143787. };
  143788. static float _vq_quantthresh__16u1__p7_0[] = {
  143789. -5.5, 5.5,
  143790. };
  143791. static long _vq_quantmap__16u1__p7_0[] = {
  143792. 1, 0, 2,
  143793. };
  143794. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  143795. _vq_quantthresh__16u1__p7_0,
  143796. _vq_quantmap__16u1__p7_0,
  143797. 3,
  143798. 3
  143799. };
  143800. static static_codebook _16u1__p7_0 = {
  143801. 4, 81,
  143802. _vq_lengthlist__16u1__p7_0,
  143803. 1, -529137664, 1618345984, 2, 0,
  143804. _vq_quantlist__16u1__p7_0,
  143805. NULL,
  143806. &_vq_auxt__16u1__p7_0,
  143807. NULL,
  143808. 0
  143809. };
  143810. static long _vq_quantlist__16u1__p7_1[] = {
  143811. 5,
  143812. 4,
  143813. 6,
  143814. 3,
  143815. 7,
  143816. 2,
  143817. 8,
  143818. 1,
  143819. 9,
  143820. 0,
  143821. 10,
  143822. };
  143823. static long _vq_lengthlist__16u1__p7_1[] = {
  143824. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  143825. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  143826. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  143827. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  143828. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  143829. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  143830. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  143831. 8, 9, 9,10,10,10,10,10,10,
  143832. };
  143833. static float _vq_quantthresh__16u1__p7_1[] = {
  143834. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143835. 3.5, 4.5,
  143836. };
  143837. static long _vq_quantmap__16u1__p7_1[] = {
  143838. 9, 7, 5, 3, 1, 0, 2, 4,
  143839. 6, 8, 10,
  143840. };
  143841. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  143842. _vq_quantthresh__16u1__p7_1,
  143843. _vq_quantmap__16u1__p7_1,
  143844. 11,
  143845. 11
  143846. };
  143847. static static_codebook _16u1__p7_1 = {
  143848. 2, 121,
  143849. _vq_lengthlist__16u1__p7_1,
  143850. 1, -531365888, 1611661312, 4, 0,
  143851. _vq_quantlist__16u1__p7_1,
  143852. NULL,
  143853. &_vq_auxt__16u1__p7_1,
  143854. NULL,
  143855. 0
  143856. };
  143857. static long _vq_quantlist__16u1__p8_0[] = {
  143858. 5,
  143859. 4,
  143860. 6,
  143861. 3,
  143862. 7,
  143863. 2,
  143864. 8,
  143865. 1,
  143866. 9,
  143867. 0,
  143868. 10,
  143869. };
  143870. static long _vq_lengthlist__16u1__p8_0[] = {
  143871. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  143872. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  143873. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  143874. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  143875. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  143876. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  143877. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  143878. 13,14,14,15,15,16,16,15,16,
  143879. };
  143880. static float _vq_quantthresh__16u1__p8_0[] = {
  143881. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  143882. 38.5, 49.5,
  143883. };
  143884. static long _vq_quantmap__16u1__p8_0[] = {
  143885. 9, 7, 5, 3, 1, 0, 2, 4,
  143886. 6, 8, 10,
  143887. };
  143888. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  143889. _vq_quantthresh__16u1__p8_0,
  143890. _vq_quantmap__16u1__p8_0,
  143891. 11,
  143892. 11
  143893. };
  143894. static static_codebook _16u1__p8_0 = {
  143895. 2, 121,
  143896. _vq_lengthlist__16u1__p8_0,
  143897. 1, -524582912, 1618345984, 4, 0,
  143898. _vq_quantlist__16u1__p8_0,
  143899. NULL,
  143900. &_vq_auxt__16u1__p8_0,
  143901. NULL,
  143902. 0
  143903. };
  143904. static long _vq_quantlist__16u1__p8_1[] = {
  143905. 5,
  143906. 4,
  143907. 6,
  143908. 3,
  143909. 7,
  143910. 2,
  143911. 8,
  143912. 1,
  143913. 9,
  143914. 0,
  143915. 10,
  143916. };
  143917. static long _vq_lengthlist__16u1__p8_1[] = {
  143918. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  143919. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  143920. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  143921. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  143922. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  143923. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  143924. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  143925. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  143926. };
  143927. static float _vq_quantthresh__16u1__p8_1[] = {
  143928. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143929. 3.5, 4.5,
  143930. };
  143931. static long _vq_quantmap__16u1__p8_1[] = {
  143932. 9, 7, 5, 3, 1, 0, 2, 4,
  143933. 6, 8, 10,
  143934. };
  143935. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  143936. _vq_quantthresh__16u1__p8_1,
  143937. _vq_quantmap__16u1__p8_1,
  143938. 11,
  143939. 11
  143940. };
  143941. static static_codebook _16u1__p8_1 = {
  143942. 2, 121,
  143943. _vq_lengthlist__16u1__p8_1,
  143944. 1, -531365888, 1611661312, 4, 0,
  143945. _vq_quantlist__16u1__p8_1,
  143946. NULL,
  143947. &_vq_auxt__16u1__p8_1,
  143948. NULL,
  143949. 0
  143950. };
  143951. static long _vq_quantlist__16u1__p9_0[] = {
  143952. 7,
  143953. 6,
  143954. 8,
  143955. 5,
  143956. 9,
  143957. 4,
  143958. 10,
  143959. 3,
  143960. 11,
  143961. 2,
  143962. 12,
  143963. 1,
  143964. 13,
  143965. 0,
  143966. 14,
  143967. };
  143968. static long _vq_lengthlist__16u1__p9_0[] = {
  143969. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143970. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143971. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143972. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143973. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143974. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143975. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143976. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143977. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143978. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143979. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143980. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143981. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143982. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143983. 8,
  143984. };
  143985. static float _vq_quantthresh__16u1__p9_0[] = {
  143986. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  143987. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  143988. };
  143989. static long _vq_quantmap__16u1__p9_0[] = {
  143990. 13, 11, 9, 7, 5, 3, 1, 0,
  143991. 2, 4, 6, 8, 10, 12, 14,
  143992. };
  143993. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  143994. _vq_quantthresh__16u1__p9_0,
  143995. _vq_quantmap__16u1__p9_0,
  143996. 15,
  143997. 15
  143998. };
  143999. static static_codebook _16u1__p9_0 = {
  144000. 2, 225,
  144001. _vq_lengthlist__16u1__p9_0,
  144002. 1, -514071552, 1627381760, 4, 0,
  144003. _vq_quantlist__16u1__p9_0,
  144004. NULL,
  144005. &_vq_auxt__16u1__p9_0,
  144006. NULL,
  144007. 0
  144008. };
  144009. static long _vq_quantlist__16u1__p9_1[] = {
  144010. 7,
  144011. 6,
  144012. 8,
  144013. 5,
  144014. 9,
  144015. 4,
  144016. 10,
  144017. 3,
  144018. 11,
  144019. 2,
  144020. 12,
  144021. 1,
  144022. 13,
  144023. 0,
  144024. 14,
  144025. };
  144026. static long _vq_lengthlist__16u1__p9_1[] = {
  144027. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  144028. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  144029. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  144030. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  144031. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  144032. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  144033. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  144034. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  144035. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  144036. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144037. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  144038. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144039. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144040. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144041. 9,
  144042. };
  144043. static float _vq_quantthresh__16u1__p9_1[] = {
  144044. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  144045. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  144046. };
  144047. static long _vq_quantmap__16u1__p9_1[] = {
  144048. 13, 11, 9, 7, 5, 3, 1, 0,
  144049. 2, 4, 6, 8, 10, 12, 14,
  144050. };
  144051. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  144052. _vq_quantthresh__16u1__p9_1,
  144053. _vq_quantmap__16u1__p9_1,
  144054. 15,
  144055. 15
  144056. };
  144057. static static_codebook _16u1__p9_1 = {
  144058. 2, 225,
  144059. _vq_lengthlist__16u1__p9_1,
  144060. 1, -522338304, 1620115456, 4, 0,
  144061. _vq_quantlist__16u1__p9_1,
  144062. NULL,
  144063. &_vq_auxt__16u1__p9_1,
  144064. NULL,
  144065. 0
  144066. };
  144067. static long _vq_quantlist__16u1__p9_2[] = {
  144068. 8,
  144069. 7,
  144070. 9,
  144071. 6,
  144072. 10,
  144073. 5,
  144074. 11,
  144075. 4,
  144076. 12,
  144077. 3,
  144078. 13,
  144079. 2,
  144080. 14,
  144081. 1,
  144082. 15,
  144083. 0,
  144084. 16,
  144085. };
  144086. static long _vq_lengthlist__16u1__p9_2[] = {
  144087. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  144088. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  144089. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  144090. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  144091. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  144092. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  144093. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  144094. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  144095. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  144096. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  144097. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  144098. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  144099. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  144100. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  144101. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  144102. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  144103. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  144104. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  144105. 10,
  144106. };
  144107. static float _vq_quantthresh__16u1__p9_2[] = {
  144108. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144109. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144110. };
  144111. static long _vq_quantmap__16u1__p9_2[] = {
  144112. 15, 13, 11, 9, 7, 5, 3, 1,
  144113. 0, 2, 4, 6, 8, 10, 12, 14,
  144114. 16,
  144115. };
  144116. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  144117. _vq_quantthresh__16u1__p9_2,
  144118. _vq_quantmap__16u1__p9_2,
  144119. 17,
  144120. 17
  144121. };
  144122. static static_codebook _16u1__p9_2 = {
  144123. 2, 289,
  144124. _vq_lengthlist__16u1__p9_2,
  144125. 1, -529530880, 1611661312, 5, 0,
  144126. _vq_quantlist__16u1__p9_2,
  144127. NULL,
  144128. &_vq_auxt__16u1__p9_2,
  144129. NULL,
  144130. 0
  144131. };
  144132. static long _huff_lengthlist__16u1__short[] = {
  144133. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  144134. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  144135. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  144136. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  144137. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  144138. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  144139. 16,16,16,16,
  144140. };
  144141. static static_codebook _huff_book__16u1__short = {
  144142. 2, 100,
  144143. _huff_lengthlist__16u1__short,
  144144. 0, 0, 0, 0, 0,
  144145. NULL,
  144146. NULL,
  144147. NULL,
  144148. NULL,
  144149. 0
  144150. };
  144151. static long _huff_lengthlist__16u2__long[] = {
  144152. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  144153. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  144154. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  144155. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  144156. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  144157. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  144158. 13,14,18,18,
  144159. };
  144160. static static_codebook _huff_book__16u2__long = {
  144161. 2, 100,
  144162. _huff_lengthlist__16u2__long,
  144163. 0, 0, 0, 0, 0,
  144164. NULL,
  144165. NULL,
  144166. NULL,
  144167. NULL,
  144168. 0
  144169. };
  144170. static long _huff_lengthlist__16u2__short[] = {
  144171. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  144172. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  144173. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  144174. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  144175. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  144176. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  144177. 16,16,16,16,
  144178. };
  144179. static static_codebook _huff_book__16u2__short = {
  144180. 2, 100,
  144181. _huff_lengthlist__16u2__short,
  144182. 0, 0, 0, 0, 0,
  144183. NULL,
  144184. NULL,
  144185. NULL,
  144186. NULL,
  144187. 0
  144188. };
  144189. static long _vq_quantlist__16u2_p1_0[] = {
  144190. 1,
  144191. 0,
  144192. 2,
  144193. };
  144194. static long _vq_lengthlist__16u2_p1_0[] = {
  144195. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  144196. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  144197. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  144198. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  144199. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  144200. 10,
  144201. };
  144202. static float _vq_quantthresh__16u2_p1_0[] = {
  144203. -0.5, 0.5,
  144204. };
  144205. static long _vq_quantmap__16u2_p1_0[] = {
  144206. 1, 0, 2,
  144207. };
  144208. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  144209. _vq_quantthresh__16u2_p1_0,
  144210. _vq_quantmap__16u2_p1_0,
  144211. 3,
  144212. 3
  144213. };
  144214. static static_codebook _16u2_p1_0 = {
  144215. 4, 81,
  144216. _vq_lengthlist__16u2_p1_0,
  144217. 1, -535822336, 1611661312, 2, 0,
  144218. _vq_quantlist__16u2_p1_0,
  144219. NULL,
  144220. &_vq_auxt__16u2_p1_0,
  144221. NULL,
  144222. 0
  144223. };
  144224. static long _vq_quantlist__16u2_p2_0[] = {
  144225. 2,
  144226. 1,
  144227. 3,
  144228. 0,
  144229. 4,
  144230. };
  144231. static long _vq_lengthlist__16u2_p2_0[] = {
  144232. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  144233. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  144234. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  144235. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  144236. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  144237. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  144238. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  144239. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  144240. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  144241. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  144242. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  144243. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  144244. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  144245. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  144246. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  144247. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  144248. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  144249. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  144250. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  144251. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  144252. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  144253. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  144254. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  144255. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  144256. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  144257. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  144258. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  144259. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  144260. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  144261. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  144262. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  144263. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  144264. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  144265. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  144266. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  144267. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  144268. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  144269. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  144270. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  144271. 13,
  144272. };
  144273. static float _vq_quantthresh__16u2_p2_0[] = {
  144274. -1.5, -0.5, 0.5, 1.5,
  144275. };
  144276. static long _vq_quantmap__16u2_p2_0[] = {
  144277. 3, 1, 0, 2, 4,
  144278. };
  144279. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  144280. _vq_quantthresh__16u2_p2_0,
  144281. _vq_quantmap__16u2_p2_0,
  144282. 5,
  144283. 5
  144284. };
  144285. static static_codebook _16u2_p2_0 = {
  144286. 4, 625,
  144287. _vq_lengthlist__16u2_p2_0,
  144288. 1, -533725184, 1611661312, 3, 0,
  144289. _vq_quantlist__16u2_p2_0,
  144290. NULL,
  144291. &_vq_auxt__16u2_p2_0,
  144292. NULL,
  144293. 0
  144294. };
  144295. static long _vq_quantlist__16u2_p3_0[] = {
  144296. 4,
  144297. 3,
  144298. 5,
  144299. 2,
  144300. 6,
  144301. 1,
  144302. 7,
  144303. 0,
  144304. 8,
  144305. };
  144306. static long _vq_lengthlist__16u2_p3_0[] = {
  144307. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  144308. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  144309. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  144310. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  144311. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  144312. 11,
  144313. };
  144314. static float _vq_quantthresh__16u2_p3_0[] = {
  144315. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144316. };
  144317. static long _vq_quantmap__16u2_p3_0[] = {
  144318. 7, 5, 3, 1, 0, 2, 4, 6,
  144319. 8,
  144320. };
  144321. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  144322. _vq_quantthresh__16u2_p3_0,
  144323. _vq_quantmap__16u2_p3_0,
  144324. 9,
  144325. 9
  144326. };
  144327. static static_codebook _16u2_p3_0 = {
  144328. 2, 81,
  144329. _vq_lengthlist__16u2_p3_0,
  144330. 1, -531628032, 1611661312, 4, 0,
  144331. _vq_quantlist__16u2_p3_0,
  144332. NULL,
  144333. &_vq_auxt__16u2_p3_0,
  144334. NULL,
  144335. 0
  144336. };
  144337. static long _vq_quantlist__16u2_p4_0[] = {
  144338. 8,
  144339. 7,
  144340. 9,
  144341. 6,
  144342. 10,
  144343. 5,
  144344. 11,
  144345. 4,
  144346. 12,
  144347. 3,
  144348. 13,
  144349. 2,
  144350. 14,
  144351. 1,
  144352. 15,
  144353. 0,
  144354. 16,
  144355. };
  144356. static long _vq_lengthlist__16u2_p4_0[] = {
  144357. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  144358. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  144359. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  144360. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  144361. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  144362. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  144363. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  144364. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  144365. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  144366. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  144367. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  144368. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  144369. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  144370. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  144371. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  144372. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  144373. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  144374. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  144375. 14,
  144376. };
  144377. static float _vq_quantthresh__16u2_p4_0[] = {
  144378. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144379. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144380. };
  144381. static long _vq_quantmap__16u2_p4_0[] = {
  144382. 15, 13, 11, 9, 7, 5, 3, 1,
  144383. 0, 2, 4, 6, 8, 10, 12, 14,
  144384. 16,
  144385. };
  144386. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  144387. _vq_quantthresh__16u2_p4_0,
  144388. _vq_quantmap__16u2_p4_0,
  144389. 17,
  144390. 17
  144391. };
  144392. static static_codebook _16u2_p4_0 = {
  144393. 2, 289,
  144394. _vq_lengthlist__16u2_p4_0,
  144395. 1, -529530880, 1611661312, 5, 0,
  144396. _vq_quantlist__16u2_p4_0,
  144397. NULL,
  144398. &_vq_auxt__16u2_p4_0,
  144399. NULL,
  144400. 0
  144401. };
  144402. static long _vq_quantlist__16u2_p5_0[] = {
  144403. 1,
  144404. 0,
  144405. 2,
  144406. };
  144407. static long _vq_lengthlist__16u2_p5_0[] = {
  144408. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  144409. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  144410. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  144411. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  144412. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  144413. 10,
  144414. };
  144415. static float _vq_quantthresh__16u2_p5_0[] = {
  144416. -5.5, 5.5,
  144417. };
  144418. static long _vq_quantmap__16u2_p5_0[] = {
  144419. 1, 0, 2,
  144420. };
  144421. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  144422. _vq_quantthresh__16u2_p5_0,
  144423. _vq_quantmap__16u2_p5_0,
  144424. 3,
  144425. 3
  144426. };
  144427. static static_codebook _16u2_p5_0 = {
  144428. 4, 81,
  144429. _vq_lengthlist__16u2_p5_0,
  144430. 1, -529137664, 1618345984, 2, 0,
  144431. _vq_quantlist__16u2_p5_0,
  144432. NULL,
  144433. &_vq_auxt__16u2_p5_0,
  144434. NULL,
  144435. 0
  144436. };
  144437. static long _vq_quantlist__16u2_p5_1[] = {
  144438. 5,
  144439. 4,
  144440. 6,
  144441. 3,
  144442. 7,
  144443. 2,
  144444. 8,
  144445. 1,
  144446. 9,
  144447. 0,
  144448. 10,
  144449. };
  144450. static long _vq_lengthlist__16u2_p5_1[] = {
  144451. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  144452. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  144453. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  144454. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  144455. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  144456. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  144457. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  144458. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144459. };
  144460. static float _vq_quantthresh__16u2_p5_1[] = {
  144461. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144462. 3.5, 4.5,
  144463. };
  144464. static long _vq_quantmap__16u2_p5_1[] = {
  144465. 9, 7, 5, 3, 1, 0, 2, 4,
  144466. 6, 8, 10,
  144467. };
  144468. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  144469. _vq_quantthresh__16u2_p5_1,
  144470. _vq_quantmap__16u2_p5_1,
  144471. 11,
  144472. 11
  144473. };
  144474. static static_codebook _16u2_p5_1 = {
  144475. 2, 121,
  144476. _vq_lengthlist__16u2_p5_1,
  144477. 1, -531365888, 1611661312, 4, 0,
  144478. _vq_quantlist__16u2_p5_1,
  144479. NULL,
  144480. &_vq_auxt__16u2_p5_1,
  144481. NULL,
  144482. 0
  144483. };
  144484. static long _vq_quantlist__16u2_p6_0[] = {
  144485. 6,
  144486. 5,
  144487. 7,
  144488. 4,
  144489. 8,
  144490. 3,
  144491. 9,
  144492. 2,
  144493. 10,
  144494. 1,
  144495. 11,
  144496. 0,
  144497. 12,
  144498. };
  144499. static long _vq_lengthlist__16u2_p6_0[] = {
  144500. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  144501. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  144502. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  144503. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  144504. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  144505. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  144506. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  144507. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  144508. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  144509. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  144510. 12,13,13,14,14,14,14,15,15,
  144511. };
  144512. static float _vq_quantthresh__16u2_p6_0[] = {
  144513. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144514. 12.5, 17.5, 22.5, 27.5,
  144515. };
  144516. static long _vq_quantmap__16u2_p6_0[] = {
  144517. 11, 9, 7, 5, 3, 1, 0, 2,
  144518. 4, 6, 8, 10, 12,
  144519. };
  144520. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  144521. _vq_quantthresh__16u2_p6_0,
  144522. _vq_quantmap__16u2_p6_0,
  144523. 13,
  144524. 13
  144525. };
  144526. static static_codebook _16u2_p6_0 = {
  144527. 2, 169,
  144528. _vq_lengthlist__16u2_p6_0,
  144529. 1, -526516224, 1616117760, 4, 0,
  144530. _vq_quantlist__16u2_p6_0,
  144531. NULL,
  144532. &_vq_auxt__16u2_p6_0,
  144533. NULL,
  144534. 0
  144535. };
  144536. static long _vq_quantlist__16u2_p6_1[] = {
  144537. 2,
  144538. 1,
  144539. 3,
  144540. 0,
  144541. 4,
  144542. };
  144543. static long _vq_lengthlist__16u2_p6_1[] = {
  144544. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  144545. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  144546. };
  144547. static float _vq_quantthresh__16u2_p6_1[] = {
  144548. -1.5, -0.5, 0.5, 1.5,
  144549. };
  144550. static long _vq_quantmap__16u2_p6_1[] = {
  144551. 3, 1, 0, 2, 4,
  144552. };
  144553. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  144554. _vq_quantthresh__16u2_p6_1,
  144555. _vq_quantmap__16u2_p6_1,
  144556. 5,
  144557. 5
  144558. };
  144559. static static_codebook _16u2_p6_1 = {
  144560. 2, 25,
  144561. _vq_lengthlist__16u2_p6_1,
  144562. 1, -533725184, 1611661312, 3, 0,
  144563. _vq_quantlist__16u2_p6_1,
  144564. NULL,
  144565. &_vq_auxt__16u2_p6_1,
  144566. NULL,
  144567. 0
  144568. };
  144569. static long _vq_quantlist__16u2_p7_0[] = {
  144570. 6,
  144571. 5,
  144572. 7,
  144573. 4,
  144574. 8,
  144575. 3,
  144576. 9,
  144577. 2,
  144578. 10,
  144579. 1,
  144580. 11,
  144581. 0,
  144582. 12,
  144583. };
  144584. static long _vq_lengthlist__16u2_p7_0[] = {
  144585. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  144586. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  144587. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  144588. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  144589. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  144590. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  144591. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  144592. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  144593. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  144594. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  144595. 12,13,13,13,14,14,14,15,14,
  144596. };
  144597. static float _vq_quantthresh__16u2_p7_0[] = {
  144598. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  144599. 27.5, 38.5, 49.5, 60.5,
  144600. };
  144601. static long _vq_quantmap__16u2_p7_0[] = {
  144602. 11, 9, 7, 5, 3, 1, 0, 2,
  144603. 4, 6, 8, 10, 12,
  144604. };
  144605. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  144606. _vq_quantthresh__16u2_p7_0,
  144607. _vq_quantmap__16u2_p7_0,
  144608. 13,
  144609. 13
  144610. };
  144611. static static_codebook _16u2_p7_0 = {
  144612. 2, 169,
  144613. _vq_lengthlist__16u2_p7_0,
  144614. 1, -523206656, 1618345984, 4, 0,
  144615. _vq_quantlist__16u2_p7_0,
  144616. NULL,
  144617. &_vq_auxt__16u2_p7_0,
  144618. NULL,
  144619. 0
  144620. };
  144621. static long _vq_quantlist__16u2_p7_1[] = {
  144622. 5,
  144623. 4,
  144624. 6,
  144625. 3,
  144626. 7,
  144627. 2,
  144628. 8,
  144629. 1,
  144630. 9,
  144631. 0,
  144632. 10,
  144633. };
  144634. static long _vq_lengthlist__16u2_p7_1[] = {
  144635. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  144636. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  144637. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  144638. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  144639. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  144640. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  144641. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  144642. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144643. };
  144644. static float _vq_quantthresh__16u2_p7_1[] = {
  144645. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144646. 3.5, 4.5,
  144647. };
  144648. static long _vq_quantmap__16u2_p7_1[] = {
  144649. 9, 7, 5, 3, 1, 0, 2, 4,
  144650. 6, 8, 10,
  144651. };
  144652. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  144653. _vq_quantthresh__16u2_p7_1,
  144654. _vq_quantmap__16u2_p7_1,
  144655. 11,
  144656. 11
  144657. };
  144658. static static_codebook _16u2_p7_1 = {
  144659. 2, 121,
  144660. _vq_lengthlist__16u2_p7_1,
  144661. 1, -531365888, 1611661312, 4, 0,
  144662. _vq_quantlist__16u2_p7_1,
  144663. NULL,
  144664. &_vq_auxt__16u2_p7_1,
  144665. NULL,
  144666. 0
  144667. };
  144668. static long _vq_quantlist__16u2_p8_0[] = {
  144669. 7,
  144670. 6,
  144671. 8,
  144672. 5,
  144673. 9,
  144674. 4,
  144675. 10,
  144676. 3,
  144677. 11,
  144678. 2,
  144679. 12,
  144680. 1,
  144681. 13,
  144682. 0,
  144683. 14,
  144684. };
  144685. static long _vq_lengthlist__16u2_p8_0[] = {
  144686. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  144687. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  144688. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  144689. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  144690. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  144691. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  144692. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  144693. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  144694. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  144695. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  144696. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  144697. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  144698. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  144699. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  144700. 14,
  144701. };
  144702. static float _vq_quantthresh__16u2_p8_0[] = {
  144703. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  144704. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  144705. };
  144706. static long _vq_quantmap__16u2_p8_0[] = {
  144707. 13, 11, 9, 7, 5, 3, 1, 0,
  144708. 2, 4, 6, 8, 10, 12, 14,
  144709. };
  144710. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  144711. _vq_quantthresh__16u2_p8_0,
  144712. _vq_quantmap__16u2_p8_0,
  144713. 15,
  144714. 15
  144715. };
  144716. static static_codebook _16u2_p8_0 = {
  144717. 2, 225,
  144718. _vq_lengthlist__16u2_p8_0,
  144719. 1, -520986624, 1620377600, 4, 0,
  144720. _vq_quantlist__16u2_p8_0,
  144721. NULL,
  144722. &_vq_auxt__16u2_p8_0,
  144723. NULL,
  144724. 0
  144725. };
  144726. static long _vq_quantlist__16u2_p8_1[] = {
  144727. 10,
  144728. 9,
  144729. 11,
  144730. 8,
  144731. 12,
  144732. 7,
  144733. 13,
  144734. 6,
  144735. 14,
  144736. 5,
  144737. 15,
  144738. 4,
  144739. 16,
  144740. 3,
  144741. 17,
  144742. 2,
  144743. 18,
  144744. 1,
  144745. 19,
  144746. 0,
  144747. 20,
  144748. };
  144749. static long _vq_lengthlist__16u2_p8_1[] = {
  144750. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  144751. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  144752. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  144753. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  144754. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  144755. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  144756. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  144757. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  144758. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  144759. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  144760. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  144761. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  144762. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  144763. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  144764. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  144765. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  144766. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  144767. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  144768. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  144769. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  144770. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  144771. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  144772. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  144773. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  144774. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  144775. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  144776. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  144777. 11,11,10,11,11,11,10,11,11,
  144778. };
  144779. static float _vq_quantthresh__16u2_p8_1[] = {
  144780. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  144781. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  144782. 6.5, 7.5, 8.5, 9.5,
  144783. };
  144784. static long _vq_quantmap__16u2_p8_1[] = {
  144785. 19, 17, 15, 13, 11, 9, 7, 5,
  144786. 3, 1, 0, 2, 4, 6, 8, 10,
  144787. 12, 14, 16, 18, 20,
  144788. };
  144789. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  144790. _vq_quantthresh__16u2_p8_1,
  144791. _vq_quantmap__16u2_p8_1,
  144792. 21,
  144793. 21
  144794. };
  144795. static static_codebook _16u2_p8_1 = {
  144796. 2, 441,
  144797. _vq_lengthlist__16u2_p8_1,
  144798. 1, -529268736, 1611661312, 5, 0,
  144799. _vq_quantlist__16u2_p8_1,
  144800. NULL,
  144801. &_vq_auxt__16u2_p8_1,
  144802. NULL,
  144803. 0
  144804. };
  144805. static long _vq_quantlist__16u2_p9_0[] = {
  144806. 5586,
  144807. 4655,
  144808. 6517,
  144809. 3724,
  144810. 7448,
  144811. 2793,
  144812. 8379,
  144813. 1862,
  144814. 9310,
  144815. 931,
  144816. 10241,
  144817. 0,
  144818. 11172,
  144819. 5521,
  144820. 5651,
  144821. };
  144822. static long _vq_lengthlist__16u2_p9_0[] = {
  144823. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  144824. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144825. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144826. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144827. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144828. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144829. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144830. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144831. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144832. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144833. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144834. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144835. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  144836. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  144837. 5,
  144838. };
  144839. static float _vq_quantthresh__16u2_p9_0[] = {
  144840. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  144841. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  144842. };
  144843. static long _vq_quantmap__16u2_p9_0[] = {
  144844. 11, 9, 7, 5, 3, 1, 13, 0,
  144845. 14, 2, 4, 6, 8, 10, 12,
  144846. };
  144847. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  144848. _vq_quantthresh__16u2_p9_0,
  144849. _vq_quantmap__16u2_p9_0,
  144850. 15,
  144851. 15
  144852. };
  144853. static static_codebook _16u2_p9_0 = {
  144854. 2, 225,
  144855. _vq_lengthlist__16u2_p9_0,
  144856. 1, -510275072, 1611661312, 14, 0,
  144857. _vq_quantlist__16u2_p9_0,
  144858. NULL,
  144859. &_vq_auxt__16u2_p9_0,
  144860. NULL,
  144861. 0
  144862. };
  144863. static long _vq_quantlist__16u2_p9_1[] = {
  144864. 392,
  144865. 343,
  144866. 441,
  144867. 294,
  144868. 490,
  144869. 245,
  144870. 539,
  144871. 196,
  144872. 588,
  144873. 147,
  144874. 637,
  144875. 98,
  144876. 686,
  144877. 49,
  144878. 735,
  144879. 0,
  144880. 784,
  144881. 388,
  144882. 396,
  144883. };
  144884. static long _vq_lengthlist__16u2_p9_1[] = {
  144885. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  144886. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  144887. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  144888. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  144889. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  144890. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  144891. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144892. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  144893. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  144894. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144895. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144896. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144897. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144898. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  144899. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  144900. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144901. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144902. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144903. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144904. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  144905. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  144906. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  144907. 11,11,11,11,11,11,11, 5, 4,
  144908. };
  144909. static float _vq_quantthresh__16u2_p9_1[] = {
  144910. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  144911. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  144912. 318.5, 367.5,
  144913. };
  144914. static long _vq_quantmap__16u2_p9_1[] = {
  144915. 15, 13, 11, 9, 7, 5, 3, 1,
  144916. 17, 0, 18, 2, 4, 6, 8, 10,
  144917. 12, 14, 16,
  144918. };
  144919. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  144920. _vq_quantthresh__16u2_p9_1,
  144921. _vq_quantmap__16u2_p9_1,
  144922. 19,
  144923. 19
  144924. };
  144925. static static_codebook _16u2_p9_1 = {
  144926. 2, 361,
  144927. _vq_lengthlist__16u2_p9_1,
  144928. 1, -518488064, 1611661312, 10, 0,
  144929. _vq_quantlist__16u2_p9_1,
  144930. NULL,
  144931. &_vq_auxt__16u2_p9_1,
  144932. NULL,
  144933. 0
  144934. };
  144935. static long _vq_quantlist__16u2_p9_2[] = {
  144936. 24,
  144937. 23,
  144938. 25,
  144939. 22,
  144940. 26,
  144941. 21,
  144942. 27,
  144943. 20,
  144944. 28,
  144945. 19,
  144946. 29,
  144947. 18,
  144948. 30,
  144949. 17,
  144950. 31,
  144951. 16,
  144952. 32,
  144953. 15,
  144954. 33,
  144955. 14,
  144956. 34,
  144957. 13,
  144958. 35,
  144959. 12,
  144960. 36,
  144961. 11,
  144962. 37,
  144963. 10,
  144964. 38,
  144965. 9,
  144966. 39,
  144967. 8,
  144968. 40,
  144969. 7,
  144970. 41,
  144971. 6,
  144972. 42,
  144973. 5,
  144974. 43,
  144975. 4,
  144976. 44,
  144977. 3,
  144978. 45,
  144979. 2,
  144980. 46,
  144981. 1,
  144982. 47,
  144983. 0,
  144984. 48,
  144985. };
  144986. static long _vq_lengthlist__16u2_p9_2[] = {
  144987. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  144988. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  144989. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  144990. 11,
  144991. };
  144992. static float _vq_quantthresh__16u2_p9_2[] = {
  144993. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  144994. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  144995. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144996. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144997. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  144998. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  144999. };
  145000. static long _vq_quantmap__16u2_p9_2[] = {
  145001. 47, 45, 43, 41, 39, 37, 35, 33,
  145002. 31, 29, 27, 25, 23, 21, 19, 17,
  145003. 15, 13, 11, 9, 7, 5, 3, 1,
  145004. 0, 2, 4, 6, 8, 10, 12, 14,
  145005. 16, 18, 20, 22, 24, 26, 28, 30,
  145006. 32, 34, 36, 38, 40, 42, 44, 46,
  145007. 48,
  145008. };
  145009. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  145010. _vq_quantthresh__16u2_p9_2,
  145011. _vq_quantmap__16u2_p9_2,
  145012. 49,
  145013. 49
  145014. };
  145015. static static_codebook _16u2_p9_2 = {
  145016. 1, 49,
  145017. _vq_lengthlist__16u2_p9_2,
  145018. 1, -526909440, 1611661312, 6, 0,
  145019. _vq_quantlist__16u2_p9_2,
  145020. NULL,
  145021. &_vq_auxt__16u2_p9_2,
  145022. NULL,
  145023. 0
  145024. };
  145025. static long _vq_quantlist__8u0__p1_0[] = {
  145026. 1,
  145027. 0,
  145028. 2,
  145029. };
  145030. static long _vq_lengthlist__8u0__p1_0[] = {
  145031. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  145032. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  145033. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  145034. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  145035. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  145036. 11,
  145037. };
  145038. static float _vq_quantthresh__8u0__p1_0[] = {
  145039. -0.5, 0.5,
  145040. };
  145041. static long _vq_quantmap__8u0__p1_0[] = {
  145042. 1, 0, 2,
  145043. };
  145044. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  145045. _vq_quantthresh__8u0__p1_0,
  145046. _vq_quantmap__8u0__p1_0,
  145047. 3,
  145048. 3
  145049. };
  145050. static static_codebook _8u0__p1_0 = {
  145051. 4, 81,
  145052. _vq_lengthlist__8u0__p1_0,
  145053. 1, -535822336, 1611661312, 2, 0,
  145054. _vq_quantlist__8u0__p1_0,
  145055. NULL,
  145056. &_vq_auxt__8u0__p1_0,
  145057. NULL,
  145058. 0
  145059. };
  145060. static long _vq_quantlist__8u0__p2_0[] = {
  145061. 1,
  145062. 0,
  145063. 2,
  145064. };
  145065. static long _vq_lengthlist__8u0__p2_0[] = {
  145066. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  145067. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  145068. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  145069. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  145070. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  145071. 8,
  145072. };
  145073. static float _vq_quantthresh__8u0__p2_0[] = {
  145074. -0.5, 0.5,
  145075. };
  145076. static long _vq_quantmap__8u0__p2_0[] = {
  145077. 1, 0, 2,
  145078. };
  145079. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  145080. _vq_quantthresh__8u0__p2_0,
  145081. _vq_quantmap__8u0__p2_0,
  145082. 3,
  145083. 3
  145084. };
  145085. static static_codebook _8u0__p2_0 = {
  145086. 4, 81,
  145087. _vq_lengthlist__8u0__p2_0,
  145088. 1, -535822336, 1611661312, 2, 0,
  145089. _vq_quantlist__8u0__p2_0,
  145090. NULL,
  145091. &_vq_auxt__8u0__p2_0,
  145092. NULL,
  145093. 0
  145094. };
  145095. static long _vq_quantlist__8u0__p3_0[] = {
  145096. 2,
  145097. 1,
  145098. 3,
  145099. 0,
  145100. 4,
  145101. };
  145102. static long _vq_lengthlist__8u0__p3_0[] = {
  145103. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145104. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145105. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  145106. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  145107. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  145108. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  145109. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  145110. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  145111. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  145112. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  145113. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  145114. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  145115. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  145116. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  145117. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  145118. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  145119. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  145120. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  145121. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  145122. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  145123. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  145124. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  145125. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  145126. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  145127. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  145128. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  145129. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  145130. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  145131. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  145132. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  145133. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  145134. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  145135. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  145136. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  145137. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  145138. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  145139. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  145140. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  145141. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  145142. 16,
  145143. };
  145144. static float _vq_quantthresh__8u0__p3_0[] = {
  145145. -1.5, -0.5, 0.5, 1.5,
  145146. };
  145147. static long _vq_quantmap__8u0__p3_0[] = {
  145148. 3, 1, 0, 2, 4,
  145149. };
  145150. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  145151. _vq_quantthresh__8u0__p3_0,
  145152. _vq_quantmap__8u0__p3_0,
  145153. 5,
  145154. 5
  145155. };
  145156. static static_codebook _8u0__p3_0 = {
  145157. 4, 625,
  145158. _vq_lengthlist__8u0__p3_0,
  145159. 1, -533725184, 1611661312, 3, 0,
  145160. _vq_quantlist__8u0__p3_0,
  145161. NULL,
  145162. &_vq_auxt__8u0__p3_0,
  145163. NULL,
  145164. 0
  145165. };
  145166. static long _vq_quantlist__8u0__p4_0[] = {
  145167. 2,
  145168. 1,
  145169. 3,
  145170. 0,
  145171. 4,
  145172. };
  145173. static long _vq_lengthlist__8u0__p4_0[] = {
  145174. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  145175. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  145176. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  145177. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  145178. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  145179. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  145180. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  145181. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  145182. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  145183. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  145184. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  145185. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  145186. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  145187. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  145188. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  145189. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  145190. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  145191. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  145192. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  145193. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  145194. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  145195. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  145196. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  145197. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  145198. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  145199. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  145200. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  145201. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  145202. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  145203. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  145204. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  145205. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  145206. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  145207. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  145208. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  145209. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  145210. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  145211. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  145212. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  145213. 12,
  145214. };
  145215. static float _vq_quantthresh__8u0__p4_0[] = {
  145216. -1.5, -0.5, 0.5, 1.5,
  145217. };
  145218. static long _vq_quantmap__8u0__p4_0[] = {
  145219. 3, 1, 0, 2, 4,
  145220. };
  145221. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  145222. _vq_quantthresh__8u0__p4_0,
  145223. _vq_quantmap__8u0__p4_0,
  145224. 5,
  145225. 5
  145226. };
  145227. static static_codebook _8u0__p4_0 = {
  145228. 4, 625,
  145229. _vq_lengthlist__8u0__p4_0,
  145230. 1, -533725184, 1611661312, 3, 0,
  145231. _vq_quantlist__8u0__p4_0,
  145232. NULL,
  145233. &_vq_auxt__8u0__p4_0,
  145234. NULL,
  145235. 0
  145236. };
  145237. static long _vq_quantlist__8u0__p5_0[] = {
  145238. 4,
  145239. 3,
  145240. 5,
  145241. 2,
  145242. 6,
  145243. 1,
  145244. 7,
  145245. 0,
  145246. 8,
  145247. };
  145248. static long _vq_lengthlist__8u0__p5_0[] = {
  145249. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  145250. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  145251. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  145252. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  145253. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  145254. 12,
  145255. };
  145256. static float _vq_quantthresh__8u0__p5_0[] = {
  145257. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145258. };
  145259. static long _vq_quantmap__8u0__p5_0[] = {
  145260. 7, 5, 3, 1, 0, 2, 4, 6,
  145261. 8,
  145262. };
  145263. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  145264. _vq_quantthresh__8u0__p5_0,
  145265. _vq_quantmap__8u0__p5_0,
  145266. 9,
  145267. 9
  145268. };
  145269. static static_codebook _8u0__p5_0 = {
  145270. 2, 81,
  145271. _vq_lengthlist__8u0__p5_0,
  145272. 1, -531628032, 1611661312, 4, 0,
  145273. _vq_quantlist__8u0__p5_0,
  145274. NULL,
  145275. &_vq_auxt__8u0__p5_0,
  145276. NULL,
  145277. 0
  145278. };
  145279. static long _vq_quantlist__8u0__p6_0[] = {
  145280. 6,
  145281. 5,
  145282. 7,
  145283. 4,
  145284. 8,
  145285. 3,
  145286. 9,
  145287. 2,
  145288. 10,
  145289. 1,
  145290. 11,
  145291. 0,
  145292. 12,
  145293. };
  145294. static long _vq_lengthlist__8u0__p6_0[] = {
  145295. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  145296. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  145297. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  145298. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  145299. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  145300. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  145301. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  145302. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  145303. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  145304. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  145305. 16, 0,15, 0,17, 0, 0, 0, 0,
  145306. };
  145307. static float _vq_quantthresh__8u0__p6_0[] = {
  145308. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  145309. 12.5, 17.5, 22.5, 27.5,
  145310. };
  145311. static long _vq_quantmap__8u0__p6_0[] = {
  145312. 11, 9, 7, 5, 3, 1, 0, 2,
  145313. 4, 6, 8, 10, 12,
  145314. };
  145315. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  145316. _vq_quantthresh__8u0__p6_0,
  145317. _vq_quantmap__8u0__p6_0,
  145318. 13,
  145319. 13
  145320. };
  145321. static static_codebook _8u0__p6_0 = {
  145322. 2, 169,
  145323. _vq_lengthlist__8u0__p6_0,
  145324. 1, -526516224, 1616117760, 4, 0,
  145325. _vq_quantlist__8u0__p6_0,
  145326. NULL,
  145327. &_vq_auxt__8u0__p6_0,
  145328. NULL,
  145329. 0
  145330. };
  145331. static long _vq_quantlist__8u0__p6_1[] = {
  145332. 2,
  145333. 1,
  145334. 3,
  145335. 0,
  145336. 4,
  145337. };
  145338. static long _vq_lengthlist__8u0__p6_1[] = {
  145339. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  145340. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  145341. };
  145342. static float _vq_quantthresh__8u0__p6_1[] = {
  145343. -1.5, -0.5, 0.5, 1.5,
  145344. };
  145345. static long _vq_quantmap__8u0__p6_1[] = {
  145346. 3, 1, 0, 2, 4,
  145347. };
  145348. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  145349. _vq_quantthresh__8u0__p6_1,
  145350. _vq_quantmap__8u0__p6_1,
  145351. 5,
  145352. 5
  145353. };
  145354. static static_codebook _8u0__p6_1 = {
  145355. 2, 25,
  145356. _vq_lengthlist__8u0__p6_1,
  145357. 1, -533725184, 1611661312, 3, 0,
  145358. _vq_quantlist__8u0__p6_1,
  145359. NULL,
  145360. &_vq_auxt__8u0__p6_1,
  145361. NULL,
  145362. 0
  145363. };
  145364. static long _vq_quantlist__8u0__p7_0[] = {
  145365. 1,
  145366. 0,
  145367. 2,
  145368. };
  145369. static long _vq_lengthlist__8u0__p7_0[] = {
  145370. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145371. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145372. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145373. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145374. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145375. 7,
  145376. };
  145377. static float _vq_quantthresh__8u0__p7_0[] = {
  145378. -157.5, 157.5,
  145379. };
  145380. static long _vq_quantmap__8u0__p7_0[] = {
  145381. 1, 0, 2,
  145382. };
  145383. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  145384. _vq_quantthresh__8u0__p7_0,
  145385. _vq_quantmap__8u0__p7_0,
  145386. 3,
  145387. 3
  145388. };
  145389. static static_codebook _8u0__p7_0 = {
  145390. 4, 81,
  145391. _vq_lengthlist__8u0__p7_0,
  145392. 1, -518803456, 1628680192, 2, 0,
  145393. _vq_quantlist__8u0__p7_0,
  145394. NULL,
  145395. &_vq_auxt__8u0__p7_0,
  145396. NULL,
  145397. 0
  145398. };
  145399. static long _vq_quantlist__8u0__p7_1[] = {
  145400. 7,
  145401. 6,
  145402. 8,
  145403. 5,
  145404. 9,
  145405. 4,
  145406. 10,
  145407. 3,
  145408. 11,
  145409. 2,
  145410. 12,
  145411. 1,
  145412. 13,
  145413. 0,
  145414. 14,
  145415. };
  145416. static long _vq_lengthlist__8u0__p7_1[] = {
  145417. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  145418. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  145419. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  145420. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  145421. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  145422. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  145423. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145424. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145425. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145426. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145427. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145428. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145429. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  145430. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145431. 10,
  145432. };
  145433. static float _vq_quantthresh__8u0__p7_1[] = {
  145434. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  145435. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  145436. };
  145437. static long _vq_quantmap__8u0__p7_1[] = {
  145438. 13, 11, 9, 7, 5, 3, 1, 0,
  145439. 2, 4, 6, 8, 10, 12, 14,
  145440. };
  145441. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  145442. _vq_quantthresh__8u0__p7_1,
  145443. _vq_quantmap__8u0__p7_1,
  145444. 15,
  145445. 15
  145446. };
  145447. static static_codebook _8u0__p7_1 = {
  145448. 2, 225,
  145449. _vq_lengthlist__8u0__p7_1,
  145450. 1, -520986624, 1620377600, 4, 0,
  145451. _vq_quantlist__8u0__p7_1,
  145452. NULL,
  145453. &_vq_auxt__8u0__p7_1,
  145454. NULL,
  145455. 0
  145456. };
  145457. static long _vq_quantlist__8u0__p7_2[] = {
  145458. 10,
  145459. 9,
  145460. 11,
  145461. 8,
  145462. 12,
  145463. 7,
  145464. 13,
  145465. 6,
  145466. 14,
  145467. 5,
  145468. 15,
  145469. 4,
  145470. 16,
  145471. 3,
  145472. 17,
  145473. 2,
  145474. 18,
  145475. 1,
  145476. 19,
  145477. 0,
  145478. 20,
  145479. };
  145480. static long _vq_lengthlist__8u0__p7_2[] = {
  145481. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  145482. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  145483. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  145484. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  145485. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  145486. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  145487. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  145488. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  145489. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  145490. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  145491. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  145492. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  145493. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  145494. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  145495. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  145496. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  145497. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  145498. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  145499. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  145500. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  145501. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  145502. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  145503. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  145504. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  145505. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  145506. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  145507. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  145508. 11,12,11,11,11,10,10,11,11,
  145509. };
  145510. static float _vq_quantthresh__8u0__p7_2[] = {
  145511. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  145512. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  145513. 6.5, 7.5, 8.5, 9.5,
  145514. };
  145515. static long _vq_quantmap__8u0__p7_2[] = {
  145516. 19, 17, 15, 13, 11, 9, 7, 5,
  145517. 3, 1, 0, 2, 4, 6, 8, 10,
  145518. 12, 14, 16, 18, 20,
  145519. };
  145520. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  145521. _vq_quantthresh__8u0__p7_2,
  145522. _vq_quantmap__8u0__p7_2,
  145523. 21,
  145524. 21
  145525. };
  145526. static static_codebook _8u0__p7_2 = {
  145527. 2, 441,
  145528. _vq_lengthlist__8u0__p7_2,
  145529. 1, -529268736, 1611661312, 5, 0,
  145530. _vq_quantlist__8u0__p7_2,
  145531. NULL,
  145532. &_vq_auxt__8u0__p7_2,
  145533. NULL,
  145534. 0
  145535. };
  145536. static long _huff_lengthlist__8u0__single[] = {
  145537. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  145538. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  145539. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  145540. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  145541. };
  145542. static static_codebook _huff_book__8u0__single = {
  145543. 2, 64,
  145544. _huff_lengthlist__8u0__single,
  145545. 0, 0, 0, 0, 0,
  145546. NULL,
  145547. NULL,
  145548. NULL,
  145549. NULL,
  145550. 0
  145551. };
  145552. static long _vq_quantlist__8u1__p1_0[] = {
  145553. 1,
  145554. 0,
  145555. 2,
  145556. };
  145557. static long _vq_lengthlist__8u1__p1_0[] = {
  145558. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  145559. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  145560. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  145561. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  145562. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  145563. 10,
  145564. };
  145565. static float _vq_quantthresh__8u1__p1_0[] = {
  145566. -0.5, 0.5,
  145567. };
  145568. static long _vq_quantmap__8u1__p1_0[] = {
  145569. 1, 0, 2,
  145570. };
  145571. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  145572. _vq_quantthresh__8u1__p1_0,
  145573. _vq_quantmap__8u1__p1_0,
  145574. 3,
  145575. 3
  145576. };
  145577. static static_codebook _8u1__p1_0 = {
  145578. 4, 81,
  145579. _vq_lengthlist__8u1__p1_0,
  145580. 1, -535822336, 1611661312, 2, 0,
  145581. _vq_quantlist__8u1__p1_0,
  145582. NULL,
  145583. &_vq_auxt__8u1__p1_0,
  145584. NULL,
  145585. 0
  145586. };
  145587. static long _vq_quantlist__8u1__p2_0[] = {
  145588. 1,
  145589. 0,
  145590. 2,
  145591. };
  145592. static long _vq_lengthlist__8u1__p2_0[] = {
  145593. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  145594. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  145595. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  145596. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  145597. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  145598. 7,
  145599. };
  145600. static float _vq_quantthresh__8u1__p2_0[] = {
  145601. -0.5, 0.5,
  145602. };
  145603. static long _vq_quantmap__8u1__p2_0[] = {
  145604. 1, 0, 2,
  145605. };
  145606. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  145607. _vq_quantthresh__8u1__p2_0,
  145608. _vq_quantmap__8u1__p2_0,
  145609. 3,
  145610. 3
  145611. };
  145612. static static_codebook _8u1__p2_0 = {
  145613. 4, 81,
  145614. _vq_lengthlist__8u1__p2_0,
  145615. 1, -535822336, 1611661312, 2, 0,
  145616. _vq_quantlist__8u1__p2_0,
  145617. NULL,
  145618. &_vq_auxt__8u1__p2_0,
  145619. NULL,
  145620. 0
  145621. };
  145622. static long _vq_quantlist__8u1__p3_0[] = {
  145623. 2,
  145624. 1,
  145625. 3,
  145626. 0,
  145627. 4,
  145628. };
  145629. static long _vq_lengthlist__8u1__p3_0[] = {
  145630. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145631. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145632. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  145633. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  145634. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  145635. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  145636. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  145637. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  145638. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  145639. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  145640. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  145641. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  145642. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  145643. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  145644. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  145645. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  145646. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  145647. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  145648. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  145649. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  145650. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  145651. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  145652. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  145653. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  145654. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  145655. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  145656. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  145657. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  145658. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  145659. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  145660. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  145661. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  145662. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  145663. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  145664. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  145665. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  145666. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  145667. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  145668. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  145669. 16,
  145670. };
  145671. static float _vq_quantthresh__8u1__p3_0[] = {
  145672. -1.5, -0.5, 0.5, 1.5,
  145673. };
  145674. static long _vq_quantmap__8u1__p3_0[] = {
  145675. 3, 1, 0, 2, 4,
  145676. };
  145677. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  145678. _vq_quantthresh__8u1__p3_0,
  145679. _vq_quantmap__8u1__p3_0,
  145680. 5,
  145681. 5
  145682. };
  145683. static static_codebook _8u1__p3_0 = {
  145684. 4, 625,
  145685. _vq_lengthlist__8u1__p3_0,
  145686. 1, -533725184, 1611661312, 3, 0,
  145687. _vq_quantlist__8u1__p3_0,
  145688. NULL,
  145689. &_vq_auxt__8u1__p3_0,
  145690. NULL,
  145691. 0
  145692. };
  145693. static long _vq_quantlist__8u1__p4_0[] = {
  145694. 2,
  145695. 1,
  145696. 3,
  145697. 0,
  145698. 4,
  145699. };
  145700. static long _vq_lengthlist__8u1__p4_0[] = {
  145701. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  145702. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  145703. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  145704. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  145705. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  145706. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  145707. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  145708. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  145709. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  145710. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  145711. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  145712. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  145713. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  145714. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  145715. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  145716. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  145717. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  145718. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  145719. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  145720. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  145721. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  145722. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  145723. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  145724. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  145725. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  145726. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  145727. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  145728. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  145729. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  145730. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  145731. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  145732. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  145733. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  145734. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  145735. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  145736. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  145737. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  145738. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  145739. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  145740. 10,
  145741. };
  145742. static float _vq_quantthresh__8u1__p4_0[] = {
  145743. -1.5, -0.5, 0.5, 1.5,
  145744. };
  145745. static long _vq_quantmap__8u1__p4_0[] = {
  145746. 3, 1, 0, 2, 4,
  145747. };
  145748. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  145749. _vq_quantthresh__8u1__p4_0,
  145750. _vq_quantmap__8u1__p4_0,
  145751. 5,
  145752. 5
  145753. };
  145754. static static_codebook _8u1__p4_0 = {
  145755. 4, 625,
  145756. _vq_lengthlist__8u1__p4_0,
  145757. 1, -533725184, 1611661312, 3, 0,
  145758. _vq_quantlist__8u1__p4_0,
  145759. NULL,
  145760. &_vq_auxt__8u1__p4_0,
  145761. NULL,
  145762. 0
  145763. };
  145764. static long _vq_quantlist__8u1__p5_0[] = {
  145765. 4,
  145766. 3,
  145767. 5,
  145768. 2,
  145769. 6,
  145770. 1,
  145771. 7,
  145772. 0,
  145773. 8,
  145774. };
  145775. static long _vq_lengthlist__8u1__p5_0[] = {
  145776. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  145777. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  145778. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  145779. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  145780. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  145781. 13,
  145782. };
  145783. static float _vq_quantthresh__8u1__p5_0[] = {
  145784. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145785. };
  145786. static long _vq_quantmap__8u1__p5_0[] = {
  145787. 7, 5, 3, 1, 0, 2, 4, 6,
  145788. 8,
  145789. };
  145790. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  145791. _vq_quantthresh__8u1__p5_0,
  145792. _vq_quantmap__8u1__p5_0,
  145793. 9,
  145794. 9
  145795. };
  145796. static static_codebook _8u1__p5_0 = {
  145797. 2, 81,
  145798. _vq_lengthlist__8u1__p5_0,
  145799. 1, -531628032, 1611661312, 4, 0,
  145800. _vq_quantlist__8u1__p5_0,
  145801. NULL,
  145802. &_vq_auxt__8u1__p5_0,
  145803. NULL,
  145804. 0
  145805. };
  145806. static long _vq_quantlist__8u1__p6_0[] = {
  145807. 4,
  145808. 3,
  145809. 5,
  145810. 2,
  145811. 6,
  145812. 1,
  145813. 7,
  145814. 0,
  145815. 8,
  145816. };
  145817. static long _vq_lengthlist__8u1__p6_0[] = {
  145818. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  145819. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  145820. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  145821. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  145822. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  145823. 10,
  145824. };
  145825. static float _vq_quantthresh__8u1__p6_0[] = {
  145826. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145827. };
  145828. static long _vq_quantmap__8u1__p6_0[] = {
  145829. 7, 5, 3, 1, 0, 2, 4, 6,
  145830. 8,
  145831. };
  145832. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  145833. _vq_quantthresh__8u1__p6_0,
  145834. _vq_quantmap__8u1__p6_0,
  145835. 9,
  145836. 9
  145837. };
  145838. static static_codebook _8u1__p6_0 = {
  145839. 2, 81,
  145840. _vq_lengthlist__8u1__p6_0,
  145841. 1, -531628032, 1611661312, 4, 0,
  145842. _vq_quantlist__8u1__p6_0,
  145843. NULL,
  145844. &_vq_auxt__8u1__p6_0,
  145845. NULL,
  145846. 0
  145847. };
  145848. static long _vq_quantlist__8u1__p7_0[] = {
  145849. 1,
  145850. 0,
  145851. 2,
  145852. };
  145853. static long _vq_lengthlist__8u1__p7_0[] = {
  145854. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  145855. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  145856. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  145857. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  145858. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  145859. 11,
  145860. };
  145861. static float _vq_quantthresh__8u1__p7_0[] = {
  145862. -5.5, 5.5,
  145863. };
  145864. static long _vq_quantmap__8u1__p7_0[] = {
  145865. 1, 0, 2,
  145866. };
  145867. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  145868. _vq_quantthresh__8u1__p7_0,
  145869. _vq_quantmap__8u1__p7_0,
  145870. 3,
  145871. 3
  145872. };
  145873. static static_codebook _8u1__p7_0 = {
  145874. 4, 81,
  145875. _vq_lengthlist__8u1__p7_0,
  145876. 1, -529137664, 1618345984, 2, 0,
  145877. _vq_quantlist__8u1__p7_0,
  145878. NULL,
  145879. &_vq_auxt__8u1__p7_0,
  145880. NULL,
  145881. 0
  145882. };
  145883. static long _vq_quantlist__8u1__p7_1[] = {
  145884. 5,
  145885. 4,
  145886. 6,
  145887. 3,
  145888. 7,
  145889. 2,
  145890. 8,
  145891. 1,
  145892. 9,
  145893. 0,
  145894. 10,
  145895. };
  145896. static long _vq_lengthlist__8u1__p7_1[] = {
  145897. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  145898. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  145899. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  145900. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145901. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  145902. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  145903. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  145904. 9, 9, 9, 9, 9,10,10,10,10,
  145905. };
  145906. static float _vq_quantthresh__8u1__p7_1[] = {
  145907. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145908. 3.5, 4.5,
  145909. };
  145910. static long _vq_quantmap__8u1__p7_1[] = {
  145911. 9, 7, 5, 3, 1, 0, 2, 4,
  145912. 6, 8, 10,
  145913. };
  145914. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  145915. _vq_quantthresh__8u1__p7_1,
  145916. _vq_quantmap__8u1__p7_1,
  145917. 11,
  145918. 11
  145919. };
  145920. static static_codebook _8u1__p7_1 = {
  145921. 2, 121,
  145922. _vq_lengthlist__8u1__p7_1,
  145923. 1, -531365888, 1611661312, 4, 0,
  145924. _vq_quantlist__8u1__p7_1,
  145925. NULL,
  145926. &_vq_auxt__8u1__p7_1,
  145927. NULL,
  145928. 0
  145929. };
  145930. static long _vq_quantlist__8u1__p8_0[] = {
  145931. 5,
  145932. 4,
  145933. 6,
  145934. 3,
  145935. 7,
  145936. 2,
  145937. 8,
  145938. 1,
  145939. 9,
  145940. 0,
  145941. 10,
  145942. };
  145943. static long _vq_lengthlist__8u1__p8_0[] = {
  145944. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  145945. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  145946. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  145947. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  145948. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  145949. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  145950. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  145951. 12,13,13,14,14,15,15,15,15,
  145952. };
  145953. static float _vq_quantthresh__8u1__p8_0[] = {
  145954. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  145955. 38.5, 49.5,
  145956. };
  145957. static long _vq_quantmap__8u1__p8_0[] = {
  145958. 9, 7, 5, 3, 1, 0, 2, 4,
  145959. 6, 8, 10,
  145960. };
  145961. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  145962. _vq_quantthresh__8u1__p8_0,
  145963. _vq_quantmap__8u1__p8_0,
  145964. 11,
  145965. 11
  145966. };
  145967. static static_codebook _8u1__p8_0 = {
  145968. 2, 121,
  145969. _vq_lengthlist__8u1__p8_0,
  145970. 1, -524582912, 1618345984, 4, 0,
  145971. _vq_quantlist__8u1__p8_0,
  145972. NULL,
  145973. &_vq_auxt__8u1__p8_0,
  145974. NULL,
  145975. 0
  145976. };
  145977. static long _vq_quantlist__8u1__p8_1[] = {
  145978. 5,
  145979. 4,
  145980. 6,
  145981. 3,
  145982. 7,
  145983. 2,
  145984. 8,
  145985. 1,
  145986. 9,
  145987. 0,
  145988. 10,
  145989. };
  145990. static long _vq_lengthlist__8u1__p8_1[] = {
  145991. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  145992. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  145993. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  145994. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  145995. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145996. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  145997. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  145998. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  145999. };
  146000. static float _vq_quantthresh__8u1__p8_1[] = {
  146001. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146002. 3.5, 4.5,
  146003. };
  146004. static long _vq_quantmap__8u1__p8_1[] = {
  146005. 9, 7, 5, 3, 1, 0, 2, 4,
  146006. 6, 8, 10,
  146007. };
  146008. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  146009. _vq_quantthresh__8u1__p8_1,
  146010. _vq_quantmap__8u1__p8_1,
  146011. 11,
  146012. 11
  146013. };
  146014. static static_codebook _8u1__p8_1 = {
  146015. 2, 121,
  146016. _vq_lengthlist__8u1__p8_1,
  146017. 1, -531365888, 1611661312, 4, 0,
  146018. _vq_quantlist__8u1__p8_1,
  146019. NULL,
  146020. &_vq_auxt__8u1__p8_1,
  146021. NULL,
  146022. 0
  146023. };
  146024. static long _vq_quantlist__8u1__p9_0[] = {
  146025. 7,
  146026. 6,
  146027. 8,
  146028. 5,
  146029. 9,
  146030. 4,
  146031. 10,
  146032. 3,
  146033. 11,
  146034. 2,
  146035. 12,
  146036. 1,
  146037. 13,
  146038. 0,
  146039. 14,
  146040. };
  146041. static long _vq_lengthlist__8u1__p9_0[] = {
  146042. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  146043. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  146044. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146045. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146046. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146047. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146048. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146049. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146050. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146051. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146052. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146053. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146054. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  146055. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146056. 10,
  146057. };
  146058. static float _vq_quantthresh__8u1__p9_0[] = {
  146059. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  146060. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  146061. };
  146062. static long _vq_quantmap__8u1__p9_0[] = {
  146063. 13, 11, 9, 7, 5, 3, 1, 0,
  146064. 2, 4, 6, 8, 10, 12, 14,
  146065. };
  146066. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  146067. _vq_quantthresh__8u1__p9_0,
  146068. _vq_quantmap__8u1__p9_0,
  146069. 15,
  146070. 15
  146071. };
  146072. static static_codebook _8u1__p9_0 = {
  146073. 2, 225,
  146074. _vq_lengthlist__8u1__p9_0,
  146075. 1, -514071552, 1627381760, 4, 0,
  146076. _vq_quantlist__8u1__p9_0,
  146077. NULL,
  146078. &_vq_auxt__8u1__p9_0,
  146079. NULL,
  146080. 0
  146081. };
  146082. static long _vq_quantlist__8u1__p9_1[] = {
  146083. 7,
  146084. 6,
  146085. 8,
  146086. 5,
  146087. 9,
  146088. 4,
  146089. 10,
  146090. 3,
  146091. 11,
  146092. 2,
  146093. 12,
  146094. 1,
  146095. 13,
  146096. 0,
  146097. 14,
  146098. };
  146099. static long _vq_lengthlist__8u1__p9_1[] = {
  146100. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  146101. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  146102. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  146103. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  146104. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  146105. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  146106. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  146107. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  146108. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  146109. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  146110. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  146111. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  146112. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  146113. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  146114. 13,
  146115. };
  146116. static float _vq_quantthresh__8u1__p9_1[] = {
  146117. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  146118. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  146119. };
  146120. static long _vq_quantmap__8u1__p9_1[] = {
  146121. 13, 11, 9, 7, 5, 3, 1, 0,
  146122. 2, 4, 6, 8, 10, 12, 14,
  146123. };
  146124. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  146125. _vq_quantthresh__8u1__p9_1,
  146126. _vq_quantmap__8u1__p9_1,
  146127. 15,
  146128. 15
  146129. };
  146130. static static_codebook _8u1__p9_1 = {
  146131. 2, 225,
  146132. _vq_lengthlist__8u1__p9_1,
  146133. 1, -522338304, 1620115456, 4, 0,
  146134. _vq_quantlist__8u1__p9_1,
  146135. NULL,
  146136. &_vq_auxt__8u1__p9_1,
  146137. NULL,
  146138. 0
  146139. };
  146140. static long _vq_quantlist__8u1__p9_2[] = {
  146141. 8,
  146142. 7,
  146143. 9,
  146144. 6,
  146145. 10,
  146146. 5,
  146147. 11,
  146148. 4,
  146149. 12,
  146150. 3,
  146151. 13,
  146152. 2,
  146153. 14,
  146154. 1,
  146155. 15,
  146156. 0,
  146157. 16,
  146158. };
  146159. static long _vq_lengthlist__8u1__p9_2[] = {
  146160. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146161. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  146162. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146163. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  146164. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146165. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  146166. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146167. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  146168. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  146169. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  146170. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  146171. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  146172. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  146173. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  146174. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  146175. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  146176. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146177. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146178. 10,
  146179. };
  146180. static float _vq_quantthresh__8u1__p9_2[] = {
  146181. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146182. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146183. };
  146184. static long _vq_quantmap__8u1__p9_2[] = {
  146185. 15, 13, 11, 9, 7, 5, 3, 1,
  146186. 0, 2, 4, 6, 8, 10, 12, 14,
  146187. 16,
  146188. };
  146189. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  146190. _vq_quantthresh__8u1__p9_2,
  146191. _vq_quantmap__8u1__p9_2,
  146192. 17,
  146193. 17
  146194. };
  146195. static static_codebook _8u1__p9_2 = {
  146196. 2, 289,
  146197. _vq_lengthlist__8u1__p9_2,
  146198. 1, -529530880, 1611661312, 5, 0,
  146199. _vq_quantlist__8u1__p9_2,
  146200. NULL,
  146201. &_vq_auxt__8u1__p9_2,
  146202. NULL,
  146203. 0
  146204. };
  146205. static long _huff_lengthlist__8u1__single[] = {
  146206. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  146207. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  146208. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  146209. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  146210. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  146211. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  146212. 13, 8, 8,15,
  146213. };
  146214. static static_codebook _huff_book__8u1__single = {
  146215. 2, 100,
  146216. _huff_lengthlist__8u1__single,
  146217. 0, 0, 0, 0, 0,
  146218. NULL,
  146219. NULL,
  146220. NULL,
  146221. NULL,
  146222. 0
  146223. };
  146224. static long _huff_lengthlist__44u0__long[] = {
  146225. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146226. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146227. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146228. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146229. };
  146230. static static_codebook _huff_book__44u0__long = {
  146231. 2, 64,
  146232. _huff_lengthlist__44u0__long,
  146233. 0, 0, 0, 0, 0,
  146234. NULL,
  146235. NULL,
  146236. NULL,
  146237. NULL,
  146238. 0
  146239. };
  146240. static long _vq_quantlist__44u0__p1_0[] = {
  146241. 1,
  146242. 0,
  146243. 2,
  146244. };
  146245. static long _vq_lengthlist__44u0__p1_0[] = {
  146246. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146247. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146248. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146249. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146250. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146251. 13,
  146252. };
  146253. static float _vq_quantthresh__44u0__p1_0[] = {
  146254. -0.5, 0.5,
  146255. };
  146256. static long _vq_quantmap__44u0__p1_0[] = {
  146257. 1, 0, 2,
  146258. };
  146259. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  146260. _vq_quantthresh__44u0__p1_0,
  146261. _vq_quantmap__44u0__p1_0,
  146262. 3,
  146263. 3
  146264. };
  146265. static static_codebook _44u0__p1_0 = {
  146266. 4, 81,
  146267. _vq_lengthlist__44u0__p1_0,
  146268. 1, -535822336, 1611661312, 2, 0,
  146269. _vq_quantlist__44u0__p1_0,
  146270. NULL,
  146271. &_vq_auxt__44u0__p1_0,
  146272. NULL,
  146273. 0
  146274. };
  146275. static long _vq_quantlist__44u0__p2_0[] = {
  146276. 1,
  146277. 0,
  146278. 2,
  146279. };
  146280. static long _vq_lengthlist__44u0__p2_0[] = {
  146281. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146282. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  146283. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146284. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  146285. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146286. 9,
  146287. };
  146288. static float _vq_quantthresh__44u0__p2_0[] = {
  146289. -0.5, 0.5,
  146290. };
  146291. static long _vq_quantmap__44u0__p2_0[] = {
  146292. 1, 0, 2,
  146293. };
  146294. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  146295. _vq_quantthresh__44u0__p2_0,
  146296. _vq_quantmap__44u0__p2_0,
  146297. 3,
  146298. 3
  146299. };
  146300. static static_codebook _44u0__p2_0 = {
  146301. 4, 81,
  146302. _vq_lengthlist__44u0__p2_0,
  146303. 1, -535822336, 1611661312, 2, 0,
  146304. _vq_quantlist__44u0__p2_0,
  146305. NULL,
  146306. &_vq_auxt__44u0__p2_0,
  146307. NULL,
  146308. 0
  146309. };
  146310. static long _vq_quantlist__44u0__p3_0[] = {
  146311. 2,
  146312. 1,
  146313. 3,
  146314. 0,
  146315. 4,
  146316. };
  146317. static long _vq_lengthlist__44u0__p3_0[] = {
  146318. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146319. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  146320. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  146321. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  146322. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  146323. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  146324. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  146325. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  146326. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  146327. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146328. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146329. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146330. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146331. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146332. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146333. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146334. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146335. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  146336. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  146337. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  146338. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  146339. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146340. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146341. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146342. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146343. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146344. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146345. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146346. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146347. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146348. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146349. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146350. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146351. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146352. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146353. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146354. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146355. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146356. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146357. 19,
  146358. };
  146359. static float _vq_quantthresh__44u0__p3_0[] = {
  146360. -1.5, -0.5, 0.5, 1.5,
  146361. };
  146362. static long _vq_quantmap__44u0__p3_0[] = {
  146363. 3, 1, 0, 2, 4,
  146364. };
  146365. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  146366. _vq_quantthresh__44u0__p3_0,
  146367. _vq_quantmap__44u0__p3_0,
  146368. 5,
  146369. 5
  146370. };
  146371. static static_codebook _44u0__p3_0 = {
  146372. 4, 625,
  146373. _vq_lengthlist__44u0__p3_0,
  146374. 1, -533725184, 1611661312, 3, 0,
  146375. _vq_quantlist__44u0__p3_0,
  146376. NULL,
  146377. &_vq_auxt__44u0__p3_0,
  146378. NULL,
  146379. 0
  146380. };
  146381. static long _vq_quantlist__44u0__p4_0[] = {
  146382. 2,
  146383. 1,
  146384. 3,
  146385. 0,
  146386. 4,
  146387. };
  146388. static long _vq_lengthlist__44u0__p4_0[] = {
  146389. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146390. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146391. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146392. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146393. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146394. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146395. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146396. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146397. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146398. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146399. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146400. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146401. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146402. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146403. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146404. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146405. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146406. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146407. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146408. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146409. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146410. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146411. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146412. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146413. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146414. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146415. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146416. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146417. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146418. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146419. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146420. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146421. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146422. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146423. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146424. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146425. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146426. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146427. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146428. 12,
  146429. };
  146430. static float _vq_quantthresh__44u0__p4_0[] = {
  146431. -1.5, -0.5, 0.5, 1.5,
  146432. };
  146433. static long _vq_quantmap__44u0__p4_0[] = {
  146434. 3, 1, 0, 2, 4,
  146435. };
  146436. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  146437. _vq_quantthresh__44u0__p4_0,
  146438. _vq_quantmap__44u0__p4_0,
  146439. 5,
  146440. 5
  146441. };
  146442. static static_codebook _44u0__p4_0 = {
  146443. 4, 625,
  146444. _vq_lengthlist__44u0__p4_0,
  146445. 1, -533725184, 1611661312, 3, 0,
  146446. _vq_quantlist__44u0__p4_0,
  146447. NULL,
  146448. &_vq_auxt__44u0__p4_0,
  146449. NULL,
  146450. 0
  146451. };
  146452. static long _vq_quantlist__44u0__p5_0[] = {
  146453. 4,
  146454. 3,
  146455. 5,
  146456. 2,
  146457. 6,
  146458. 1,
  146459. 7,
  146460. 0,
  146461. 8,
  146462. };
  146463. static long _vq_lengthlist__44u0__p5_0[] = {
  146464. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  146465. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  146466. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  146467. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146468. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  146469. 12,
  146470. };
  146471. static float _vq_quantthresh__44u0__p5_0[] = {
  146472. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146473. };
  146474. static long _vq_quantmap__44u0__p5_0[] = {
  146475. 7, 5, 3, 1, 0, 2, 4, 6,
  146476. 8,
  146477. };
  146478. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  146479. _vq_quantthresh__44u0__p5_0,
  146480. _vq_quantmap__44u0__p5_0,
  146481. 9,
  146482. 9
  146483. };
  146484. static static_codebook _44u0__p5_0 = {
  146485. 2, 81,
  146486. _vq_lengthlist__44u0__p5_0,
  146487. 1, -531628032, 1611661312, 4, 0,
  146488. _vq_quantlist__44u0__p5_0,
  146489. NULL,
  146490. &_vq_auxt__44u0__p5_0,
  146491. NULL,
  146492. 0
  146493. };
  146494. static long _vq_quantlist__44u0__p6_0[] = {
  146495. 6,
  146496. 5,
  146497. 7,
  146498. 4,
  146499. 8,
  146500. 3,
  146501. 9,
  146502. 2,
  146503. 10,
  146504. 1,
  146505. 11,
  146506. 0,
  146507. 12,
  146508. };
  146509. static long _vq_lengthlist__44u0__p6_0[] = {
  146510. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  146511. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  146512. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  146513. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  146514. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  146515. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  146516. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  146517. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  146518. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  146519. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  146520. 15,17,16,17,18,17,17,18, 0,
  146521. };
  146522. static float _vq_quantthresh__44u0__p6_0[] = {
  146523. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146524. 12.5, 17.5, 22.5, 27.5,
  146525. };
  146526. static long _vq_quantmap__44u0__p6_0[] = {
  146527. 11, 9, 7, 5, 3, 1, 0, 2,
  146528. 4, 6, 8, 10, 12,
  146529. };
  146530. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  146531. _vq_quantthresh__44u0__p6_0,
  146532. _vq_quantmap__44u0__p6_0,
  146533. 13,
  146534. 13
  146535. };
  146536. static static_codebook _44u0__p6_0 = {
  146537. 2, 169,
  146538. _vq_lengthlist__44u0__p6_0,
  146539. 1, -526516224, 1616117760, 4, 0,
  146540. _vq_quantlist__44u0__p6_0,
  146541. NULL,
  146542. &_vq_auxt__44u0__p6_0,
  146543. NULL,
  146544. 0
  146545. };
  146546. static long _vq_quantlist__44u0__p6_1[] = {
  146547. 2,
  146548. 1,
  146549. 3,
  146550. 0,
  146551. 4,
  146552. };
  146553. static long _vq_lengthlist__44u0__p6_1[] = {
  146554. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  146555. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  146556. };
  146557. static float _vq_quantthresh__44u0__p6_1[] = {
  146558. -1.5, -0.5, 0.5, 1.5,
  146559. };
  146560. static long _vq_quantmap__44u0__p6_1[] = {
  146561. 3, 1, 0, 2, 4,
  146562. };
  146563. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  146564. _vq_quantthresh__44u0__p6_1,
  146565. _vq_quantmap__44u0__p6_1,
  146566. 5,
  146567. 5
  146568. };
  146569. static static_codebook _44u0__p6_1 = {
  146570. 2, 25,
  146571. _vq_lengthlist__44u0__p6_1,
  146572. 1, -533725184, 1611661312, 3, 0,
  146573. _vq_quantlist__44u0__p6_1,
  146574. NULL,
  146575. &_vq_auxt__44u0__p6_1,
  146576. NULL,
  146577. 0
  146578. };
  146579. static long _vq_quantlist__44u0__p7_0[] = {
  146580. 2,
  146581. 1,
  146582. 3,
  146583. 0,
  146584. 4,
  146585. };
  146586. static long _vq_lengthlist__44u0__p7_0[] = {
  146587. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  146588. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146589. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146590. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146591. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146592. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146593. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146594. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  146595. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146596. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146597. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146598. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146599. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146600. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146601. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146602. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146603. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146604. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146605. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146606. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146607. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146608. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146609. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146610. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146611. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146612. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146613. 11,11,11,11,11,11,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,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146617. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  146618. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146619. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146620. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146621. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146622. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146623. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146624. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146625. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146626. 10,
  146627. };
  146628. static float _vq_quantthresh__44u0__p7_0[] = {
  146629. -253.5, -84.5, 84.5, 253.5,
  146630. };
  146631. static long _vq_quantmap__44u0__p7_0[] = {
  146632. 3, 1, 0, 2, 4,
  146633. };
  146634. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  146635. _vq_quantthresh__44u0__p7_0,
  146636. _vq_quantmap__44u0__p7_0,
  146637. 5,
  146638. 5
  146639. };
  146640. static static_codebook _44u0__p7_0 = {
  146641. 4, 625,
  146642. _vq_lengthlist__44u0__p7_0,
  146643. 1, -518709248, 1626677248, 3, 0,
  146644. _vq_quantlist__44u0__p7_0,
  146645. NULL,
  146646. &_vq_auxt__44u0__p7_0,
  146647. NULL,
  146648. 0
  146649. };
  146650. static long _vq_quantlist__44u0__p7_1[] = {
  146651. 6,
  146652. 5,
  146653. 7,
  146654. 4,
  146655. 8,
  146656. 3,
  146657. 9,
  146658. 2,
  146659. 10,
  146660. 1,
  146661. 11,
  146662. 0,
  146663. 12,
  146664. };
  146665. static long _vq_lengthlist__44u0__p7_1[] = {
  146666. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  146667. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  146668. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  146669. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  146670. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  146671. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  146672. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  146673. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  146674. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  146675. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  146676. 15,15,15,15,15,15,15,15,15,
  146677. };
  146678. static float _vq_quantthresh__44u0__p7_1[] = {
  146679. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146680. 32.5, 45.5, 58.5, 71.5,
  146681. };
  146682. static long _vq_quantmap__44u0__p7_1[] = {
  146683. 11, 9, 7, 5, 3, 1, 0, 2,
  146684. 4, 6, 8, 10, 12,
  146685. };
  146686. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  146687. _vq_quantthresh__44u0__p7_1,
  146688. _vq_quantmap__44u0__p7_1,
  146689. 13,
  146690. 13
  146691. };
  146692. static static_codebook _44u0__p7_1 = {
  146693. 2, 169,
  146694. _vq_lengthlist__44u0__p7_1,
  146695. 1, -523010048, 1618608128, 4, 0,
  146696. _vq_quantlist__44u0__p7_1,
  146697. NULL,
  146698. &_vq_auxt__44u0__p7_1,
  146699. NULL,
  146700. 0
  146701. };
  146702. static long _vq_quantlist__44u0__p7_2[] = {
  146703. 6,
  146704. 5,
  146705. 7,
  146706. 4,
  146707. 8,
  146708. 3,
  146709. 9,
  146710. 2,
  146711. 10,
  146712. 1,
  146713. 11,
  146714. 0,
  146715. 12,
  146716. };
  146717. static long _vq_lengthlist__44u0__p7_2[] = {
  146718. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  146719. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  146720. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  146721. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146722. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  146723. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  146724. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  146725. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146726. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146727. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  146728. 9, 9, 9,10, 9, 9,10,10, 9,
  146729. };
  146730. static float _vq_quantthresh__44u0__p7_2[] = {
  146731. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146732. 2.5, 3.5, 4.5, 5.5,
  146733. };
  146734. static long _vq_quantmap__44u0__p7_2[] = {
  146735. 11, 9, 7, 5, 3, 1, 0, 2,
  146736. 4, 6, 8, 10, 12,
  146737. };
  146738. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  146739. _vq_quantthresh__44u0__p7_2,
  146740. _vq_quantmap__44u0__p7_2,
  146741. 13,
  146742. 13
  146743. };
  146744. static static_codebook _44u0__p7_2 = {
  146745. 2, 169,
  146746. _vq_lengthlist__44u0__p7_2,
  146747. 1, -531103744, 1611661312, 4, 0,
  146748. _vq_quantlist__44u0__p7_2,
  146749. NULL,
  146750. &_vq_auxt__44u0__p7_2,
  146751. NULL,
  146752. 0
  146753. };
  146754. static long _huff_lengthlist__44u0__short[] = {
  146755. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  146756. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  146757. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  146758. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  146759. };
  146760. static static_codebook _huff_book__44u0__short = {
  146761. 2, 64,
  146762. _huff_lengthlist__44u0__short,
  146763. 0, 0, 0, 0, 0,
  146764. NULL,
  146765. NULL,
  146766. NULL,
  146767. NULL,
  146768. 0
  146769. };
  146770. static long _huff_lengthlist__44u1__long[] = {
  146771. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146772. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146773. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146774. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146775. };
  146776. static static_codebook _huff_book__44u1__long = {
  146777. 2, 64,
  146778. _huff_lengthlist__44u1__long,
  146779. 0, 0, 0, 0, 0,
  146780. NULL,
  146781. NULL,
  146782. NULL,
  146783. NULL,
  146784. 0
  146785. };
  146786. static long _vq_quantlist__44u1__p1_0[] = {
  146787. 1,
  146788. 0,
  146789. 2,
  146790. };
  146791. static long _vq_lengthlist__44u1__p1_0[] = {
  146792. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146793. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146794. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146795. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146796. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146797. 13,
  146798. };
  146799. static float _vq_quantthresh__44u1__p1_0[] = {
  146800. -0.5, 0.5,
  146801. };
  146802. static long _vq_quantmap__44u1__p1_0[] = {
  146803. 1, 0, 2,
  146804. };
  146805. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  146806. _vq_quantthresh__44u1__p1_0,
  146807. _vq_quantmap__44u1__p1_0,
  146808. 3,
  146809. 3
  146810. };
  146811. static static_codebook _44u1__p1_0 = {
  146812. 4, 81,
  146813. _vq_lengthlist__44u1__p1_0,
  146814. 1, -535822336, 1611661312, 2, 0,
  146815. _vq_quantlist__44u1__p1_0,
  146816. NULL,
  146817. &_vq_auxt__44u1__p1_0,
  146818. NULL,
  146819. 0
  146820. };
  146821. static long _vq_quantlist__44u1__p2_0[] = {
  146822. 1,
  146823. 0,
  146824. 2,
  146825. };
  146826. static long _vq_lengthlist__44u1__p2_0[] = {
  146827. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146828. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  146829. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146830. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  146831. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146832. 9,
  146833. };
  146834. static float _vq_quantthresh__44u1__p2_0[] = {
  146835. -0.5, 0.5,
  146836. };
  146837. static long _vq_quantmap__44u1__p2_0[] = {
  146838. 1, 0, 2,
  146839. };
  146840. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  146841. _vq_quantthresh__44u1__p2_0,
  146842. _vq_quantmap__44u1__p2_0,
  146843. 3,
  146844. 3
  146845. };
  146846. static static_codebook _44u1__p2_0 = {
  146847. 4, 81,
  146848. _vq_lengthlist__44u1__p2_0,
  146849. 1, -535822336, 1611661312, 2, 0,
  146850. _vq_quantlist__44u1__p2_0,
  146851. NULL,
  146852. &_vq_auxt__44u1__p2_0,
  146853. NULL,
  146854. 0
  146855. };
  146856. static long _vq_quantlist__44u1__p3_0[] = {
  146857. 2,
  146858. 1,
  146859. 3,
  146860. 0,
  146861. 4,
  146862. };
  146863. static long _vq_lengthlist__44u1__p3_0[] = {
  146864. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146865. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  146866. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  146867. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  146868. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  146869. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  146870. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  146871. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  146872. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  146873. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146874. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146875. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146876. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146877. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146878. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146879. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146880. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146881. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  146882. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  146883. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  146884. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  146885. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146886. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146887. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146888. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146889. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146890. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146891. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146892. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146893. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146894. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146895. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146896. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146897. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146898. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146899. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146900. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146901. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146902. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146903. 19,
  146904. };
  146905. static float _vq_quantthresh__44u1__p3_0[] = {
  146906. -1.5, -0.5, 0.5, 1.5,
  146907. };
  146908. static long _vq_quantmap__44u1__p3_0[] = {
  146909. 3, 1, 0, 2, 4,
  146910. };
  146911. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  146912. _vq_quantthresh__44u1__p3_0,
  146913. _vq_quantmap__44u1__p3_0,
  146914. 5,
  146915. 5
  146916. };
  146917. static static_codebook _44u1__p3_0 = {
  146918. 4, 625,
  146919. _vq_lengthlist__44u1__p3_0,
  146920. 1, -533725184, 1611661312, 3, 0,
  146921. _vq_quantlist__44u1__p3_0,
  146922. NULL,
  146923. &_vq_auxt__44u1__p3_0,
  146924. NULL,
  146925. 0
  146926. };
  146927. static long _vq_quantlist__44u1__p4_0[] = {
  146928. 2,
  146929. 1,
  146930. 3,
  146931. 0,
  146932. 4,
  146933. };
  146934. static long _vq_lengthlist__44u1__p4_0[] = {
  146935. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146936. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146937. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146938. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146939. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146940. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146941. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146942. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146943. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146944. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146945. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146946. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146947. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146948. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146949. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146950. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146951. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146952. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146953. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146954. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146955. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146956. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146957. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146958. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146959. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146960. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146961. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146962. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146963. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146964. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146965. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146966. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146967. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146968. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146969. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146970. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146971. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146972. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146973. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146974. 12,
  146975. };
  146976. static float _vq_quantthresh__44u1__p4_0[] = {
  146977. -1.5, -0.5, 0.5, 1.5,
  146978. };
  146979. static long _vq_quantmap__44u1__p4_0[] = {
  146980. 3, 1, 0, 2, 4,
  146981. };
  146982. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  146983. _vq_quantthresh__44u1__p4_0,
  146984. _vq_quantmap__44u1__p4_0,
  146985. 5,
  146986. 5
  146987. };
  146988. static static_codebook _44u1__p4_0 = {
  146989. 4, 625,
  146990. _vq_lengthlist__44u1__p4_0,
  146991. 1, -533725184, 1611661312, 3, 0,
  146992. _vq_quantlist__44u1__p4_0,
  146993. NULL,
  146994. &_vq_auxt__44u1__p4_0,
  146995. NULL,
  146996. 0
  146997. };
  146998. static long _vq_quantlist__44u1__p5_0[] = {
  146999. 4,
  147000. 3,
  147001. 5,
  147002. 2,
  147003. 6,
  147004. 1,
  147005. 7,
  147006. 0,
  147007. 8,
  147008. };
  147009. static long _vq_lengthlist__44u1__p5_0[] = {
  147010. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  147011. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  147012. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  147013. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  147014. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  147015. 12,
  147016. };
  147017. static float _vq_quantthresh__44u1__p5_0[] = {
  147018. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147019. };
  147020. static long _vq_quantmap__44u1__p5_0[] = {
  147021. 7, 5, 3, 1, 0, 2, 4, 6,
  147022. 8,
  147023. };
  147024. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  147025. _vq_quantthresh__44u1__p5_0,
  147026. _vq_quantmap__44u1__p5_0,
  147027. 9,
  147028. 9
  147029. };
  147030. static static_codebook _44u1__p5_0 = {
  147031. 2, 81,
  147032. _vq_lengthlist__44u1__p5_0,
  147033. 1, -531628032, 1611661312, 4, 0,
  147034. _vq_quantlist__44u1__p5_0,
  147035. NULL,
  147036. &_vq_auxt__44u1__p5_0,
  147037. NULL,
  147038. 0
  147039. };
  147040. static long _vq_quantlist__44u1__p6_0[] = {
  147041. 6,
  147042. 5,
  147043. 7,
  147044. 4,
  147045. 8,
  147046. 3,
  147047. 9,
  147048. 2,
  147049. 10,
  147050. 1,
  147051. 11,
  147052. 0,
  147053. 12,
  147054. };
  147055. static long _vq_lengthlist__44u1__p6_0[] = {
  147056. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  147057. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  147058. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  147059. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  147060. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  147061. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  147062. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  147063. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  147064. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  147065. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  147066. 15,17,16,17,18,17,17,18, 0,
  147067. };
  147068. static float _vq_quantthresh__44u1__p6_0[] = {
  147069. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147070. 12.5, 17.5, 22.5, 27.5,
  147071. };
  147072. static long _vq_quantmap__44u1__p6_0[] = {
  147073. 11, 9, 7, 5, 3, 1, 0, 2,
  147074. 4, 6, 8, 10, 12,
  147075. };
  147076. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  147077. _vq_quantthresh__44u1__p6_0,
  147078. _vq_quantmap__44u1__p6_0,
  147079. 13,
  147080. 13
  147081. };
  147082. static static_codebook _44u1__p6_0 = {
  147083. 2, 169,
  147084. _vq_lengthlist__44u1__p6_0,
  147085. 1, -526516224, 1616117760, 4, 0,
  147086. _vq_quantlist__44u1__p6_0,
  147087. NULL,
  147088. &_vq_auxt__44u1__p6_0,
  147089. NULL,
  147090. 0
  147091. };
  147092. static long _vq_quantlist__44u1__p6_1[] = {
  147093. 2,
  147094. 1,
  147095. 3,
  147096. 0,
  147097. 4,
  147098. };
  147099. static long _vq_lengthlist__44u1__p6_1[] = {
  147100. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  147101. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  147102. };
  147103. static float _vq_quantthresh__44u1__p6_1[] = {
  147104. -1.5, -0.5, 0.5, 1.5,
  147105. };
  147106. static long _vq_quantmap__44u1__p6_1[] = {
  147107. 3, 1, 0, 2, 4,
  147108. };
  147109. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  147110. _vq_quantthresh__44u1__p6_1,
  147111. _vq_quantmap__44u1__p6_1,
  147112. 5,
  147113. 5
  147114. };
  147115. static static_codebook _44u1__p6_1 = {
  147116. 2, 25,
  147117. _vq_lengthlist__44u1__p6_1,
  147118. 1, -533725184, 1611661312, 3, 0,
  147119. _vq_quantlist__44u1__p6_1,
  147120. NULL,
  147121. &_vq_auxt__44u1__p6_1,
  147122. NULL,
  147123. 0
  147124. };
  147125. static long _vq_quantlist__44u1__p7_0[] = {
  147126. 3,
  147127. 2,
  147128. 4,
  147129. 1,
  147130. 5,
  147131. 0,
  147132. 6,
  147133. };
  147134. static long _vq_lengthlist__44u1__p7_0[] = {
  147135. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147136. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147137. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  147138. 8,
  147139. };
  147140. static float _vq_quantthresh__44u1__p7_0[] = {
  147141. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  147142. };
  147143. static long _vq_quantmap__44u1__p7_0[] = {
  147144. 5, 3, 1, 0, 2, 4, 6,
  147145. };
  147146. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  147147. _vq_quantthresh__44u1__p7_0,
  147148. _vq_quantmap__44u1__p7_0,
  147149. 7,
  147150. 7
  147151. };
  147152. static static_codebook _44u1__p7_0 = {
  147153. 2, 49,
  147154. _vq_lengthlist__44u1__p7_0,
  147155. 1, -518017024, 1626677248, 3, 0,
  147156. _vq_quantlist__44u1__p7_0,
  147157. NULL,
  147158. &_vq_auxt__44u1__p7_0,
  147159. NULL,
  147160. 0
  147161. };
  147162. static long _vq_quantlist__44u1__p7_1[] = {
  147163. 6,
  147164. 5,
  147165. 7,
  147166. 4,
  147167. 8,
  147168. 3,
  147169. 9,
  147170. 2,
  147171. 10,
  147172. 1,
  147173. 11,
  147174. 0,
  147175. 12,
  147176. };
  147177. static long _vq_lengthlist__44u1__p7_1[] = {
  147178. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  147179. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  147180. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  147181. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  147182. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  147183. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  147184. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  147185. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  147186. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  147187. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  147188. 15,15,15,15,15,15,15,15,15,
  147189. };
  147190. static float _vq_quantthresh__44u1__p7_1[] = {
  147191. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147192. 32.5, 45.5, 58.5, 71.5,
  147193. };
  147194. static long _vq_quantmap__44u1__p7_1[] = {
  147195. 11, 9, 7, 5, 3, 1, 0, 2,
  147196. 4, 6, 8, 10, 12,
  147197. };
  147198. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  147199. _vq_quantthresh__44u1__p7_1,
  147200. _vq_quantmap__44u1__p7_1,
  147201. 13,
  147202. 13
  147203. };
  147204. static static_codebook _44u1__p7_1 = {
  147205. 2, 169,
  147206. _vq_lengthlist__44u1__p7_1,
  147207. 1, -523010048, 1618608128, 4, 0,
  147208. _vq_quantlist__44u1__p7_1,
  147209. NULL,
  147210. &_vq_auxt__44u1__p7_1,
  147211. NULL,
  147212. 0
  147213. };
  147214. static long _vq_quantlist__44u1__p7_2[] = {
  147215. 6,
  147216. 5,
  147217. 7,
  147218. 4,
  147219. 8,
  147220. 3,
  147221. 9,
  147222. 2,
  147223. 10,
  147224. 1,
  147225. 11,
  147226. 0,
  147227. 12,
  147228. };
  147229. static long _vq_lengthlist__44u1__p7_2[] = {
  147230. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  147231. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  147232. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  147233. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147234. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  147235. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  147236. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  147237. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147238. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147239. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  147240. 9, 9, 9,10, 9, 9,10,10, 9,
  147241. };
  147242. static float _vq_quantthresh__44u1__p7_2[] = {
  147243. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147244. 2.5, 3.5, 4.5, 5.5,
  147245. };
  147246. static long _vq_quantmap__44u1__p7_2[] = {
  147247. 11, 9, 7, 5, 3, 1, 0, 2,
  147248. 4, 6, 8, 10, 12,
  147249. };
  147250. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  147251. _vq_quantthresh__44u1__p7_2,
  147252. _vq_quantmap__44u1__p7_2,
  147253. 13,
  147254. 13
  147255. };
  147256. static static_codebook _44u1__p7_2 = {
  147257. 2, 169,
  147258. _vq_lengthlist__44u1__p7_2,
  147259. 1, -531103744, 1611661312, 4, 0,
  147260. _vq_quantlist__44u1__p7_2,
  147261. NULL,
  147262. &_vq_auxt__44u1__p7_2,
  147263. NULL,
  147264. 0
  147265. };
  147266. static long _huff_lengthlist__44u1__short[] = {
  147267. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  147268. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  147269. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  147270. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  147271. };
  147272. static static_codebook _huff_book__44u1__short = {
  147273. 2, 64,
  147274. _huff_lengthlist__44u1__short,
  147275. 0, 0, 0, 0, 0,
  147276. NULL,
  147277. NULL,
  147278. NULL,
  147279. NULL,
  147280. 0
  147281. };
  147282. static long _huff_lengthlist__44u2__long[] = {
  147283. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  147284. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  147285. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  147286. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  147287. };
  147288. static static_codebook _huff_book__44u2__long = {
  147289. 2, 64,
  147290. _huff_lengthlist__44u2__long,
  147291. 0, 0, 0, 0, 0,
  147292. NULL,
  147293. NULL,
  147294. NULL,
  147295. NULL,
  147296. 0
  147297. };
  147298. static long _vq_quantlist__44u2__p1_0[] = {
  147299. 1,
  147300. 0,
  147301. 2,
  147302. };
  147303. static long _vq_lengthlist__44u2__p1_0[] = {
  147304. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  147305. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147306. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  147307. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  147308. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  147309. 13,
  147310. };
  147311. static float _vq_quantthresh__44u2__p1_0[] = {
  147312. -0.5, 0.5,
  147313. };
  147314. static long _vq_quantmap__44u2__p1_0[] = {
  147315. 1, 0, 2,
  147316. };
  147317. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  147318. _vq_quantthresh__44u2__p1_0,
  147319. _vq_quantmap__44u2__p1_0,
  147320. 3,
  147321. 3
  147322. };
  147323. static static_codebook _44u2__p1_0 = {
  147324. 4, 81,
  147325. _vq_lengthlist__44u2__p1_0,
  147326. 1, -535822336, 1611661312, 2, 0,
  147327. _vq_quantlist__44u2__p1_0,
  147328. NULL,
  147329. &_vq_auxt__44u2__p1_0,
  147330. NULL,
  147331. 0
  147332. };
  147333. static long _vq_quantlist__44u2__p2_0[] = {
  147334. 1,
  147335. 0,
  147336. 2,
  147337. };
  147338. static long _vq_lengthlist__44u2__p2_0[] = {
  147339. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147340. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  147341. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147342. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147343. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  147344. 9,
  147345. };
  147346. static float _vq_quantthresh__44u2__p2_0[] = {
  147347. -0.5, 0.5,
  147348. };
  147349. static long _vq_quantmap__44u2__p2_0[] = {
  147350. 1, 0, 2,
  147351. };
  147352. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  147353. _vq_quantthresh__44u2__p2_0,
  147354. _vq_quantmap__44u2__p2_0,
  147355. 3,
  147356. 3
  147357. };
  147358. static static_codebook _44u2__p2_0 = {
  147359. 4, 81,
  147360. _vq_lengthlist__44u2__p2_0,
  147361. 1, -535822336, 1611661312, 2, 0,
  147362. _vq_quantlist__44u2__p2_0,
  147363. NULL,
  147364. &_vq_auxt__44u2__p2_0,
  147365. NULL,
  147366. 0
  147367. };
  147368. static long _vq_quantlist__44u2__p3_0[] = {
  147369. 2,
  147370. 1,
  147371. 3,
  147372. 0,
  147373. 4,
  147374. };
  147375. static long _vq_lengthlist__44u2__p3_0[] = {
  147376. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147377. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147378. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147379. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147380. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  147381. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  147382. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  147383. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  147384. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147385. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147386. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  147387. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147388. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  147389. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  147390. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  147391. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  147392. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  147393. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  147394. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  147395. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  147396. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  147397. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  147398. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  147399. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  147400. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  147401. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  147402. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  147403. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  147404. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  147405. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  147406. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  147407. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  147408. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  147409. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  147410. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  147411. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  147412. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  147413. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  147414. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  147415. 0,
  147416. };
  147417. static float _vq_quantthresh__44u2__p3_0[] = {
  147418. -1.5, -0.5, 0.5, 1.5,
  147419. };
  147420. static long _vq_quantmap__44u2__p3_0[] = {
  147421. 3, 1, 0, 2, 4,
  147422. };
  147423. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  147424. _vq_quantthresh__44u2__p3_0,
  147425. _vq_quantmap__44u2__p3_0,
  147426. 5,
  147427. 5
  147428. };
  147429. static static_codebook _44u2__p3_0 = {
  147430. 4, 625,
  147431. _vq_lengthlist__44u2__p3_0,
  147432. 1, -533725184, 1611661312, 3, 0,
  147433. _vq_quantlist__44u2__p3_0,
  147434. NULL,
  147435. &_vq_auxt__44u2__p3_0,
  147436. NULL,
  147437. 0
  147438. };
  147439. static long _vq_quantlist__44u2__p4_0[] = {
  147440. 2,
  147441. 1,
  147442. 3,
  147443. 0,
  147444. 4,
  147445. };
  147446. static long _vq_lengthlist__44u2__p4_0[] = {
  147447. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147448. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147449. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  147450. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  147451. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  147452. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147453. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  147454. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  147455. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147456. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147457. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  147458. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147459. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  147460. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  147461. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  147462. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  147463. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  147464. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147465. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147466. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  147467. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147468. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  147469. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  147470. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147471. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  147472. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  147473. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  147474. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  147475. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147476. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  147477. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  147478. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  147479. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  147480. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147481. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  147482. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  147483. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  147484. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  147485. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  147486. 13,
  147487. };
  147488. static float _vq_quantthresh__44u2__p4_0[] = {
  147489. -1.5, -0.5, 0.5, 1.5,
  147490. };
  147491. static long _vq_quantmap__44u2__p4_0[] = {
  147492. 3, 1, 0, 2, 4,
  147493. };
  147494. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  147495. _vq_quantthresh__44u2__p4_0,
  147496. _vq_quantmap__44u2__p4_0,
  147497. 5,
  147498. 5
  147499. };
  147500. static static_codebook _44u2__p4_0 = {
  147501. 4, 625,
  147502. _vq_lengthlist__44u2__p4_0,
  147503. 1, -533725184, 1611661312, 3, 0,
  147504. _vq_quantlist__44u2__p4_0,
  147505. NULL,
  147506. &_vq_auxt__44u2__p4_0,
  147507. NULL,
  147508. 0
  147509. };
  147510. static long _vq_quantlist__44u2__p5_0[] = {
  147511. 4,
  147512. 3,
  147513. 5,
  147514. 2,
  147515. 6,
  147516. 1,
  147517. 7,
  147518. 0,
  147519. 8,
  147520. };
  147521. static long _vq_lengthlist__44u2__p5_0[] = {
  147522. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  147523. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  147524. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  147525. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  147526. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  147527. 13,
  147528. };
  147529. static float _vq_quantthresh__44u2__p5_0[] = {
  147530. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147531. };
  147532. static long _vq_quantmap__44u2__p5_0[] = {
  147533. 7, 5, 3, 1, 0, 2, 4, 6,
  147534. 8,
  147535. };
  147536. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  147537. _vq_quantthresh__44u2__p5_0,
  147538. _vq_quantmap__44u2__p5_0,
  147539. 9,
  147540. 9
  147541. };
  147542. static static_codebook _44u2__p5_0 = {
  147543. 2, 81,
  147544. _vq_lengthlist__44u2__p5_0,
  147545. 1, -531628032, 1611661312, 4, 0,
  147546. _vq_quantlist__44u2__p5_0,
  147547. NULL,
  147548. &_vq_auxt__44u2__p5_0,
  147549. NULL,
  147550. 0
  147551. };
  147552. static long _vq_quantlist__44u2__p6_0[] = {
  147553. 6,
  147554. 5,
  147555. 7,
  147556. 4,
  147557. 8,
  147558. 3,
  147559. 9,
  147560. 2,
  147561. 10,
  147562. 1,
  147563. 11,
  147564. 0,
  147565. 12,
  147566. };
  147567. static long _vq_lengthlist__44u2__p6_0[] = {
  147568. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  147569. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  147570. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  147571. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  147572. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  147573. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  147574. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  147575. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  147576. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  147577. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  147578. 15,17,17,16,18,17,18, 0, 0,
  147579. };
  147580. static float _vq_quantthresh__44u2__p6_0[] = {
  147581. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147582. 12.5, 17.5, 22.5, 27.5,
  147583. };
  147584. static long _vq_quantmap__44u2__p6_0[] = {
  147585. 11, 9, 7, 5, 3, 1, 0, 2,
  147586. 4, 6, 8, 10, 12,
  147587. };
  147588. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  147589. _vq_quantthresh__44u2__p6_0,
  147590. _vq_quantmap__44u2__p6_0,
  147591. 13,
  147592. 13
  147593. };
  147594. static static_codebook _44u2__p6_0 = {
  147595. 2, 169,
  147596. _vq_lengthlist__44u2__p6_0,
  147597. 1, -526516224, 1616117760, 4, 0,
  147598. _vq_quantlist__44u2__p6_0,
  147599. NULL,
  147600. &_vq_auxt__44u2__p6_0,
  147601. NULL,
  147602. 0
  147603. };
  147604. static long _vq_quantlist__44u2__p6_1[] = {
  147605. 2,
  147606. 1,
  147607. 3,
  147608. 0,
  147609. 4,
  147610. };
  147611. static long _vq_lengthlist__44u2__p6_1[] = {
  147612. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147613. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147614. };
  147615. static float _vq_quantthresh__44u2__p6_1[] = {
  147616. -1.5, -0.5, 0.5, 1.5,
  147617. };
  147618. static long _vq_quantmap__44u2__p6_1[] = {
  147619. 3, 1, 0, 2, 4,
  147620. };
  147621. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  147622. _vq_quantthresh__44u2__p6_1,
  147623. _vq_quantmap__44u2__p6_1,
  147624. 5,
  147625. 5
  147626. };
  147627. static static_codebook _44u2__p6_1 = {
  147628. 2, 25,
  147629. _vq_lengthlist__44u2__p6_1,
  147630. 1, -533725184, 1611661312, 3, 0,
  147631. _vq_quantlist__44u2__p6_1,
  147632. NULL,
  147633. &_vq_auxt__44u2__p6_1,
  147634. NULL,
  147635. 0
  147636. };
  147637. static long _vq_quantlist__44u2__p7_0[] = {
  147638. 4,
  147639. 3,
  147640. 5,
  147641. 2,
  147642. 6,
  147643. 1,
  147644. 7,
  147645. 0,
  147646. 8,
  147647. };
  147648. static long _vq_lengthlist__44u2__p7_0[] = {
  147649. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  147650. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  147651. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147652. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147653. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147654. 11,
  147655. };
  147656. static float _vq_quantthresh__44u2__p7_0[] = {
  147657. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  147658. };
  147659. static long _vq_quantmap__44u2__p7_0[] = {
  147660. 7, 5, 3, 1, 0, 2, 4, 6,
  147661. 8,
  147662. };
  147663. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  147664. _vq_quantthresh__44u2__p7_0,
  147665. _vq_quantmap__44u2__p7_0,
  147666. 9,
  147667. 9
  147668. };
  147669. static static_codebook _44u2__p7_0 = {
  147670. 2, 81,
  147671. _vq_lengthlist__44u2__p7_0,
  147672. 1, -516612096, 1626677248, 4, 0,
  147673. _vq_quantlist__44u2__p7_0,
  147674. NULL,
  147675. &_vq_auxt__44u2__p7_0,
  147676. NULL,
  147677. 0
  147678. };
  147679. static long _vq_quantlist__44u2__p7_1[] = {
  147680. 6,
  147681. 5,
  147682. 7,
  147683. 4,
  147684. 8,
  147685. 3,
  147686. 9,
  147687. 2,
  147688. 10,
  147689. 1,
  147690. 11,
  147691. 0,
  147692. 12,
  147693. };
  147694. static long _vq_lengthlist__44u2__p7_1[] = {
  147695. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  147696. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  147697. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  147698. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  147699. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  147700. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  147701. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  147702. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  147703. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  147704. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  147705. 14,14,14,17,15,17,17,17,17,
  147706. };
  147707. static float _vq_quantthresh__44u2__p7_1[] = {
  147708. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147709. 32.5, 45.5, 58.5, 71.5,
  147710. };
  147711. static long _vq_quantmap__44u2__p7_1[] = {
  147712. 11, 9, 7, 5, 3, 1, 0, 2,
  147713. 4, 6, 8, 10, 12,
  147714. };
  147715. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  147716. _vq_quantthresh__44u2__p7_1,
  147717. _vq_quantmap__44u2__p7_1,
  147718. 13,
  147719. 13
  147720. };
  147721. static static_codebook _44u2__p7_1 = {
  147722. 2, 169,
  147723. _vq_lengthlist__44u2__p7_1,
  147724. 1, -523010048, 1618608128, 4, 0,
  147725. _vq_quantlist__44u2__p7_1,
  147726. NULL,
  147727. &_vq_auxt__44u2__p7_1,
  147728. NULL,
  147729. 0
  147730. };
  147731. static long _vq_quantlist__44u2__p7_2[] = {
  147732. 6,
  147733. 5,
  147734. 7,
  147735. 4,
  147736. 8,
  147737. 3,
  147738. 9,
  147739. 2,
  147740. 10,
  147741. 1,
  147742. 11,
  147743. 0,
  147744. 12,
  147745. };
  147746. static long _vq_lengthlist__44u2__p7_2[] = {
  147747. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  147748. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  147749. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  147750. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147751. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  147752. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  147753. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  147754. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147755. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  147756. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  147757. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147758. };
  147759. static float _vq_quantthresh__44u2__p7_2[] = {
  147760. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147761. 2.5, 3.5, 4.5, 5.5,
  147762. };
  147763. static long _vq_quantmap__44u2__p7_2[] = {
  147764. 11, 9, 7, 5, 3, 1, 0, 2,
  147765. 4, 6, 8, 10, 12,
  147766. };
  147767. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  147768. _vq_quantthresh__44u2__p7_2,
  147769. _vq_quantmap__44u2__p7_2,
  147770. 13,
  147771. 13
  147772. };
  147773. static static_codebook _44u2__p7_2 = {
  147774. 2, 169,
  147775. _vq_lengthlist__44u2__p7_2,
  147776. 1, -531103744, 1611661312, 4, 0,
  147777. _vq_quantlist__44u2__p7_2,
  147778. NULL,
  147779. &_vq_auxt__44u2__p7_2,
  147780. NULL,
  147781. 0
  147782. };
  147783. static long _huff_lengthlist__44u2__short[] = {
  147784. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  147785. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  147786. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  147787. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  147788. };
  147789. static static_codebook _huff_book__44u2__short = {
  147790. 2, 64,
  147791. _huff_lengthlist__44u2__short,
  147792. 0, 0, 0, 0, 0,
  147793. NULL,
  147794. NULL,
  147795. NULL,
  147796. NULL,
  147797. 0
  147798. };
  147799. static long _huff_lengthlist__44u3__long[] = {
  147800. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  147801. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  147802. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  147803. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  147804. };
  147805. static static_codebook _huff_book__44u3__long = {
  147806. 2, 64,
  147807. _huff_lengthlist__44u3__long,
  147808. 0, 0, 0, 0, 0,
  147809. NULL,
  147810. NULL,
  147811. NULL,
  147812. NULL,
  147813. 0
  147814. };
  147815. static long _vq_quantlist__44u3__p1_0[] = {
  147816. 1,
  147817. 0,
  147818. 2,
  147819. };
  147820. static long _vq_lengthlist__44u3__p1_0[] = {
  147821. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  147822. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147823. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  147824. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  147825. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  147826. 13,
  147827. };
  147828. static float _vq_quantthresh__44u3__p1_0[] = {
  147829. -0.5, 0.5,
  147830. };
  147831. static long _vq_quantmap__44u3__p1_0[] = {
  147832. 1, 0, 2,
  147833. };
  147834. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  147835. _vq_quantthresh__44u3__p1_0,
  147836. _vq_quantmap__44u3__p1_0,
  147837. 3,
  147838. 3
  147839. };
  147840. static static_codebook _44u3__p1_0 = {
  147841. 4, 81,
  147842. _vq_lengthlist__44u3__p1_0,
  147843. 1, -535822336, 1611661312, 2, 0,
  147844. _vq_quantlist__44u3__p1_0,
  147845. NULL,
  147846. &_vq_auxt__44u3__p1_0,
  147847. NULL,
  147848. 0
  147849. };
  147850. static long _vq_quantlist__44u3__p2_0[] = {
  147851. 1,
  147852. 0,
  147853. 2,
  147854. };
  147855. static long _vq_lengthlist__44u3__p2_0[] = {
  147856. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147857. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  147858. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147859. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147860. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  147861. 9,
  147862. };
  147863. static float _vq_quantthresh__44u3__p2_0[] = {
  147864. -0.5, 0.5,
  147865. };
  147866. static long _vq_quantmap__44u3__p2_0[] = {
  147867. 1, 0, 2,
  147868. };
  147869. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  147870. _vq_quantthresh__44u3__p2_0,
  147871. _vq_quantmap__44u3__p2_0,
  147872. 3,
  147873. 3
  147874. };
  147875. static static_codebook _44u3__p2_0 = {
  147876. 4, 81,
  147877. _vq_lengthlist__44u3__p2_0,
  147878. 1, -535822336, 1611661312, 2, 0,
  147879. _vq_quantlist__44u3__p2_0,
  147880. NULL,
  147881. &_vq_auxt__44u3__p2_0,
  147882. NULL,
  147883. 0
  147884. };
  147885. static long _vq_quantlist__44u3__p3_0[] = {
  147886. 2,
  147887. 1,
  147888. 3,
  147889. 0,
  147890. 4,
  147891. };
  147892. static long _vq_lengthlist__44u3__p3_0[] = {
  147893. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147894. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147895. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147896. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147897. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  147898. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  147899. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  147900. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  147901. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147902. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147903. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  147904. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147905. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  147906. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  147907. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  147908. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  147909. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  147910. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  147911. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  147912. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  147913. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  147914. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  147915. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  147916. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  147917. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  147918. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  147919. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  147920. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  147921. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  147922. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  147923. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  147924. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  147925. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  147926. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  147927. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  147928. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  147929. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  147930. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  147931. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  147932. 0,
  147933. };
  147934. static float _vq_quantthresh__44u3__p3_0[] = {
  147935. -1.5, -0.5, 0.5, 1.5,
  147936. };
  147937. static long _vq_quantmap__44u3__p3_0[] = {
  147938. 3, 1, 0, 2, 4,
  147939. };
  147940. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  147941. _vq_quantthresh__44u3__p3_0,
  147942. _vq_quantmap__44u3__p3_0,
  147943. 5,
  147944. 5
  147945. };
  147946. static static_codebook _44u3__p3_0 = {
  147947. 4, 625,
  147948. _vq_lengthlist__44u3__p3_0,
  147949. 1, -533725184, 1611661312, 3, 0,
  147950. _vq_quantlist__44u3__p3_0,
  147951. NULL,
  147952. &_vq_auxt__44u3__p3_0,
  147953. NULL,
  147954. 0
  147955. };
  147956. static long _vq_quantlist__44u3__p4_0[] = {
  147957. 2,
  147958. 1,
  147959. 3,
  147960. 0,
  147961. 4,
  147962. };
  147963. static long _vq_lengthlist__44u3__p4_0[] = {
  147964. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147965. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147966. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  147967. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  147968. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  147969. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147970. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  147971. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  147972. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147973. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147974. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  147975. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147976. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  147977. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  147978. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  147979. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  147980. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  147981. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147982. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147983. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  147984. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147985. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  147986. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  147987. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147988. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  147989. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  147990. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  147991. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  147992. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147993. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  147994. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  147995. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  147996. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  147997. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147998. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  147999. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  148000. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  148001. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  148002. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  148003. 13,
  148004. };
  148005. static float _vq_quantthresh__44u3__p4_0[] = {
  148006. -1.5, -0.5, 0.5, 1.5,
  148007. };
  148008. static long _vq_quantmap__44u3__p4_0[] = {
  148009. 3, 1, 0, 2, 4,
  148010. };
  148011. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  148012. _vq_quantthresh__44u3__p4_0,
  148013. _vq_quantmap__44u3__p4_0,
  148014. 5,
  148015. 5
  148016. };
  148017. static static_codebook _44u3__p4_0 = {
  148018. 4, 625,
  148019. _vq_lengthlist__44u3__p4_0,
  148020. 1, -533725184, 1611661312, 3, 0,
  148021. _vq_quantlist__44u3__p4_0,
  148022. NULL,
  148023. &_vq_auxt__44u3__p4_0,
  148024. NULL,
  148025. 0
  148026. };
  148027. static long _vq_quantlist__44u3__p5_0[] = {
  148028. 4,
  148029. 3,
  148030. 5,
  148031. 2,
  148032. 6,
  148033. 1,
  148034. 7,
  148035. 0,
  148036. 8,
  148037. };
  148038. static long _vq_lengthlist__44u3__p5_0[] = {
  148039. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  148040. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  148041. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  148042. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  148043. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  148044. 12,
  148045. };
  148046. static float _vq_quantthresh__44u3__p5_0[] = {
  148047. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148048. };
  148049. static long _vq_quantmap__44u3__p5_0[] = {
  148050. 7, 5, 3, 1, 0, 2, 4, 6,
  148051. 8,
  148052. };
  148053. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  148054. _vq_quantthresh__44u3__p5_0,
  148055. _vq_quantmap__44u3__p5_0,
  148056. 9,
  148057. 9
  148058. };
  148059. static static_codebook _44u3__p5_0 = {
  148060. 2, 81,
  148061. _vq_lengthlist__44u3__p5_0,
  148062. 1, -531628032, 1611661312, 4, 0,
  148063. _vq_quantlist__44u3__p5_0,
  148064. NULL,
  148065. &_vq_auxt__44u3__p5_0,
  148066. NULL,
  148067. 0
  148068. };
  148069. static long _vq_quantlist__44u3__p6_0[] = {
  148070. 6,
  148071. 5,
  148072. 7,
  148073. 4,
  148074. 8,
  148075. 3,
  148076. 9,
  148077. 2,
  148078. 10,
  148079. 1,
  148080. 11,
  148081. 0,
  148082. 12,
  148083. };
  148084. static long _vq_lengthlist__44u3__p6_0[] = {
  148085. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  148086. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148087. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148088. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148089. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  148090. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  148091. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  148092. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  148093. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  148094. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  148095. 15,16,16,16,17,18,16,20,18,
  148096. };
  148097. static float _vq_quantthresh__44u3__p6_0[] = {
  148098. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148099. 12.5, 17.5, 22.5, 27.5,
  148100. };
  148101. static long _vq_quantmap__44u3__p6_0[] = {
  148102. 11, 9, 7, 5, 3, 1, 0, 2,
  148103. 4, 6, 8, 10, 12,
  148104. };
  148105. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  148106. _vq_quantthresh__44u3__p6_0,
  148107. _vq_quantmap__44u3__p6_0,
  148108. 13,
  148109. 13
  148110. };
  148111. static static_codebook _44u3__p6_0 = {
  148112. 2, 169,
  148113. _vq_lengthlist__44u3__p6_0,
  148114. 1, -526516224, 1616117760, 4, 0,
  148115. _vq_quantlist__44u3__p6_0,
  148116. NULL,
  148117. &_vq_auxt__44u3__p6_0,
  148118. NULL,
  148119. 0
  148120. };
  148121. static long _vq_quantlist__44u3__p6_1[] = {
  148122. 2,
  148123. 1,
  148124. 3,
  148125. 0,
  148126. 4,
  148127. };
  148128. static long _vq_lengthlist__44u3__p6_1[] = {
  148129. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148130. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148131. };
  148132. static float _vq_quantthresh__44u3__p6_1[] = {
  148133. -1.5, -0.5, 0.5, 1.5,
  148134. };
  148135. static long _vq_quantmap__44u3__p6_1[] = {
  148136. 3, 1, 0, 2, 4,
  148137. };
  148138. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  148139. _vq_quantthresh__44u3__p6_1,
  148140. _vq_quantmap__44u3__p6_1,
  148141. 5,
  148142. 5
  148143. };
  148144. static static_codebook _44u3__p6_1 = {
  148145. 2, 25,
  148146. _vq_lengthlist__44u3__p6_1,
  148147. 1, -533725184, 1611661312, 3, 0,
  148148. _vq_quantlist__44u3__p6_1,
  148149. NULL,
  148150. &_vq_auxt__44u3__p6_1,
  148151. NULL,
  148152. 0
  148153. };
  148154. static long _vq_quantlist__44u3__p7_0[] = {
  148155. 4,
  148156. 3,
  148157. 5,
  148158. 2,
  148159. 6,
  148160. 1,
  148161. 7,
  148162. 0,
  148163. 8,
  148164. };
  148165. static long _vq_lengthlist__44u3__p7_0[] = {
  148166. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  148167. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148168. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148169. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148170. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148171. 9,
  148172. };
  148173. static float _vq_quantthresh__44u3__p7_0[] = {
  148174. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  148175. };
  148176. static long _vq_quantmap__44u3__p7_0[] = {
  148177. 7, 5, 3, 1, 0, 2, 4, 6,
  148178. 8,
  148179. };
  148180. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  148181. _vq_quantthresh__44u3__p7_0,
  148182. _vq_quantmap__44u3__p7_0,
  148183. 9,
  148184. 9
  148185. };
  148186. static static_codebook _44u3__p7_0 = {
  148187. 2, 81,
  148188. _vq_lengthlist__44u3__p7_0,
  148189. 1, -515907584, 1627381760, 4, 0,
  148190. _vq_quantlist__44u3__p7_0,
  148191. NULL,
  148192. &_vq_auxt__44u3__p7_0,
  148193. NULL,
  148194. 0
  148195. };
  148196. static long _vq_quantlist__44u3__p7_1[] = {
  148197. 7,
  148198. 6,
  148199. 8,
  148200. 5,
  148201. 9,
  148202. 4,
  148203. 10,
  148204. 3,
  148205. 11,
  148206. 2,
  148207. 12,
  148208. 1,
  148209. 13,
  148210. 0,
  148211. 14,
  148212. };
  148213. static long _vq_lengthlist__44u3__p7_1[] = {
  148214. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  148215. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  148216. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  148217. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  148218. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  148219. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  148220. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  148221. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  148222. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  148223. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  148224. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  148225. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  148226. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  148227. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  148228. 17,
  148229. };
  148230. static float _vq_quantthresh__44u3__p7_1[] = {
  148231. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148232. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148233. };
  148234. static long _vq_quantmap__44u3__p7_1[] = {
  148235. 13, 11, 9, 7, 5, 3, 1, 0,
  148236. 2, 4, 6, 8, 10, 12, 14,
  148237. };
  148238. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  148239. _vq_quantthresh__44u3__p7_1,
  148240. _vq_quantmap__44u3__p7_1,
  148241. 15,
  148242. 15
  148243. };
  148244. static static_codebook _44u3__p7_1 = {
  148245. 2, 225,
  148246. _vq_lengthlist__44u3__p7_1,
  148247. 1, -522338304, 1620115456, 4, 0,
  148248. _vq_quantlist__44u3__p7_1,
  148249. NULL,
  148250. &_vq_auxt__44u3__p7_1,
  148251. NULL,
  148252. 0
  148253. };
  148254. static long _vq_quantlist__44u3__p7_2[] = {
  148255. 8,
  148256. 7,
  148257. 9,
  148258. 6,
  148259. 10,
  148260. 5,
  148261. 11,
  148262. 4,
  148263. 12,
  148264. 3,
  148265. 13,
  148266. 2,
  148267. 14,
  148268. 1,
  148269. 15,
  148270. 0,
  148271. 16,
  148272. };
  148273. static long _vq_lengthlist__44u3__p7_2[] = {
  148274. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148275. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148276. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  148277. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148278. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  148279. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148280. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  148281. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148282. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  148283. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  148284. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148285. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  148286. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  148287. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148288. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  148289. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  148290. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148291. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  148292. 11,
  148293. };
  148294. static float _vq_quantthresh__44u3__p7_2[] = {
  148295. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148296. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148297. };
  148298. static long _vq_quantmap__44u3__p7_2[] = {
  148299. 15, 13, 11, 9, 7, 5, 3, 1,
  148300. 0, 2, 4, 6, 8, 10, 12, 14,
  148301. 16,
  148302. };
  148303. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  148304. _vq_quantthresh__44u3__p7_2,
  148305. _vq_quantmap__44u3__p7_2,
  148306. 17,
  148307. 17
  148308. };
  148309. static static_codebook _44u3__p7_2 = {
  148310. 2, 289,
  148311. _vq_lengthlist__44u3__p7_2,
  148312. 1, -529530880, 1611661312, 5, 0,
  148313. _vq_quantlist__44u3__p7_2,
  148314. NULL,
  148315. &_vq_auxt__44u3__p7_2,
  148316. NULL,
  148317. 0
  148318. };
  148319. static long _huff_lengthlist__44u3__short[] = {
  148320. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  148321. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  148322. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  148323. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  148324. };
  148325. static static_codebook _huff_book__44u3__short = {
  148326. 2, 64,
  148327. _huff_lengthlist__44u3__short,
  148328. 0, 0, 0, 0, 0,
  148329. NULL,
  148330. NULL,
  148331. NULL,
  148332. NULL,
  148333. 0
  148334. };
  148335. static long _huff_lengthlist__44u4__long[] = {
  148336. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  148337. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  148338. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  148339. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  148340. };
  148341. static static_codebook _huff_book__44u4__long = {
  148342. 2, 64,
  148343. _huff_lengthlist__44u4__long,
  148344. 0, 0, 0, 0, 0,
  148345. NULL,
  148346. NULL,
  148347. NULL,
  148348. NULL,
  148349. 0
  148350. };
  148351. static long _vq_quantlist__44u4__p1_0[] = {
  148352. 1,
  148353. 0,
  148354. 2,
  148355. };
  148356. static long _vq_lengthlist__44u4__p1_0[] = {
  148357. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  148358. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  148359. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  148360. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  148361. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  148362. 13,
  148363. };
  148364. static float _vq_quantthresh__44u4__p1_0[] = {
  148365. -0.5, 0.5,
  148366. };
  148367. static long _vq_quantmap__44u4__p1_0[] = {
  148368. 1, 0, 2,
  148369. };
  148370. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  148371. _vq_quantthresh__44u4__p1_0,
  148372. _vq_quantmap__44u4__p1_0,
  148373. 3,
  148374. 3
  148375. };
  148376. static static_codebook _44u4__p1_0 = {
  148377. 4, 81,
  148378. _vq_lengthlist__44u4__p1_0,
  148379. 1, -535822336, 1611661312, 2, 0,
  148380. _vq_quantlist__44u4__p1_0,
  148381. NULL,
  148382. &_vq_auxt__44u4__p1_0,
  148383. NULL,
  148384. 0
  148385. };
  148386. static long _vq_quantlist__44u4__p2_0[] = {
  148387. 1,
  148388. 0,
  148389. 2,
  148390. };
  148391. static long _vq_lengthlist__44u4__p2_0[] = {
  148392. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  148393. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  148394. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  148395. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  148396. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  148397. 9,
  148398. };
  148399. static float _vq_quantthresh__44u4__p2_0[] = {
  148400. -0.5, 0.5,
  148401. };
  148402. static long _vq_quantmap__44u4__p2_0[] = {
  148403. 1, 0, 2,
  148404. };
  148405. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  148406. _vq_quantthresh__44u4__p2_0,
  148407. _vq_quantmap__44u4__p2_0,
  148408. 3,
  148409. 3
  148410. };
  148411. static static_codebook _44u4__p2_0 = {
  148412. 4, 81,
  148413. _vq_lengthlist__44u4__p2_0,
  148414. 1, -535822336, 1611661312, 2, 0,
  148415. _vq_quantlist__44u4__p2_0,
  148416. NULL,
  148417. &_vq_auxt__44u4__p2_0,
  148418. NULL,
  148419. 0
  148420. };
  148421. static long _vq_quantlist__44u4__p3_0[] = {
  148422. 2,
  148423. 1,
  148424. 3,
  148425. 0,
  148426. 4,
  148427. };
  148428. static long _vq_lengthlist__44u4__p3_0[] = {
  148429. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  148430. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148431. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  148432. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  148433. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  148434. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  148435. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  148436. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  148437. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  148438. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  148439. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  148440. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  148441. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  148442. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  148443. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  148444. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  148445. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  148446. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  148447. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  148448. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  148449. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  148450. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  148451. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  148452. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  148453. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  148454. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  148455. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  148456. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  148457. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  148458. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  148459. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  148460. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  148461. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  148462. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  148463. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  148464. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  148465. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  148466. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  148467. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  148468. 0,
  148469. };
  148470. static float _vq_quantthresh__44u4__p3_0[] = {
  148471. -1.5, -0.5, 0.5, 1.5,
  148472. };
  148473. static long _vq_quantmap__44u4__p3_0[] = {
  148474. 3, 1, 0, 2, 4,
  148475. };
  148476. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  148477. _vq_quantthresh__44u4__p3_0,
  148478. _vq_quantmap__44u4__p3_0,
  148479. 5,
  148480. 5
  148481. };
  148482. static static_codebook _44u4__p3_0 = {
  148483. 4, 625,
  148484. _vq_lengthlist__44u4__p3_0,
  148485. 1, -533725184, 1611661312, 3, 0,
  148486. _vq_quantlist__44u4__p3_0,
  148487. NULL,
  148488. &_vq_auxt__44u4__p3_0,
  148489. NULL,
  148490. 0
  148491. };
  148492. static long _vq_quantlist__44u4__p4_0[] = {
  148493. 2,
  148494. 1,
  148495. 3,
  148496. 0,
  148497. 4,
  148498. };
  148499. static long _vq_lengthlist__44u4__p4_0[] = {
  148500. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  148501. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  148502. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  148503. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  148504. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  148505. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  148506. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  148507. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  148508. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  148509. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  148510. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  148511. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148512. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  148513. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  148514. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  148515. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  148516. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  148517. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148518. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  148519. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  148520. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  148521. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  148522. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  148523. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  148524. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  148525. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  148526. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  148527. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  148528. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  148529. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  148530. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  148531. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  148532. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  148533. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  148534. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  148535. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  148536. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  148537. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  148538. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  148539. 13,
  148540. };
  148541. static float _vq_quantthresh__44u4__p4_0[] = {
  148542. -1.5, -0.5, 0.5, 1.5,
  148543. };
  148544. static long _vq_quantmap__44u4__p4_0[] = {
  148545. 3, 1, 0, 2, 4,
  148546. };
  148547. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  148548. _vq_quantthresh__44u4__p4_0,
  148549. _vq_quantmap__44u4__p4_0,
  148550. 5,
  148551. 5
  148552. };
  148553. static static_codebook _44u4__p4_0 = {
  148554. 4, 625,
  148555. _vq_lengthlist__44u4__p4_0,
  148556. 1, -533725184, 1611661312, 3, 0,
  148557. _vq_quantlist__44u4__p4_0,
  148558. NULL,
  148559. &_vq_auxt__44u4__p4_0,
  148560. NULL,
  148561. 0
  148562. };
  148563. static long _vq_quantlist__44u4__p5_0[] = {
  148564. 4,
  148565. 3,
  148566. 5,
  148567. 2,
  148568. 6,
  148569. 1,
  148570. 7,
  148571. 0,
  148572. 8,
  148573. };
  148574. static long _vq_lengthlist__44u4__p5_0[] = {
  148575. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  148576. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  148577. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  148578. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  148579. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  148580. 12,
  148581. };
  148582. static float _vq_quantthresh__44u4__p5_0[] = {
  148583. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148584. };
  148585. static long _vq_quantmap__44u4__p5_0[] = {
  148586. 7, 5, 3, 1, 0, 2, 4, 6,
  148587. 8,
  148588. };
  148589. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  148590. _vq_quantthresh__44u4__p5_0,
  148591. _vq_quantmap__44u4__p5_0,
  148592. 9,
  148593. 9
  148594. };
  148595. static static_codebook _44u4__p5_0 = {
  148596. 2, 81,
  148597. _vq_lengthlist__44u4__p5_0,
  148598. 1, -531628032, 1611661312, 4, 0,
  148599. _vq_quantlist__44u4__p5_0,
  148600. NULL,
  148601. &_vq_auxt__44u4__p5_0,
  148602. NULL,
  148603. 0
  148604. };
  148605. static long _vq_quantlist__44u4__p6_0[] = {
  148606. 6,
  148607. 5,
  148608. 7,
  148609. 4,
  148610. 8,
  148611. 3,
  148612. 9,
  148613. 2,
  148614. 10,
  148615. 1,
  148616. 11,
  148617. 0,
  148618. 12,
  148619. };
  148620. static long _vq_lengthlist__44u4__p6_0[] = {
  148621. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  148622. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148623. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148624. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148625. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  148626. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  148627. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  148628. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  148629. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  148630. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  148631. 16,16,16,17,17,18,17,20,21,
  148632. };
  148633. static float _vq_quantthresh__44u4__p6_0[] = {
  148634. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148635. 12.5, 17.5, 22.5, 27.5,
  148636. };
  148637. static long _vq_quantmap__44u4__p6_0[] = {
  148638. 11, 9, 7, 5, 3, 1, 0, 2,
  148639. 4, 6, 8, 10, 12,
  148640. };
  148641. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  148642. _vq_quantthresh__44u4__p6_0,
  148643. _vq_quantmap__44u4__p6_0,
  148644. 13,
  148645. 13
  148646. };
  148647. static static_codebook _44u4__p6_0 = {
  148648. 2, 169,
  148649. _vq_lengthlist__44u4__p6_0,
  148650. 1, -526516224, 1616117760, 4, 0,
  148651. _vq_quantlist__44u4__p6_0,
  148652. NULL,
  148653. &_vq_auxt__44u4__p6_0,
  148654. NULL,
  148655. 0
  148656. };
  148657. static long _vq_quantlist__44u4__p6_1[] = {
  148658. 2,
  148659. 1,
  148660. 3,
  148661. 0,
  148662. 4,
  148663. };
  148664. static long _vq_lengthlist__44u4__p6_1[] = {
  148665. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148666. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148667. };
  148668. static float _vq_quantthresh__44u4__p6_1[] = {
  148669. -1.5, -0.5, 0.5, 1.5,
  148670. };
  148671. static long _vq_quantmap__44u4__p6_1[] = {
  148672. 3, 1, 0, 2, 4,
  148673. };
  148674. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  148675. _vq_quantthresh__44u4__p6_1,
  148676. _vq_quantmap__44u4__p6_1,
  148677. 5,
  148678. 5
  148679. };
  148680. static static_codebook _44u4__p6_1 = {
  148681. 2, 25,
  148682. _vq_lengthlist__44u4__p6_1,
  148683. 1, -533725184, 1611661312, 3, 0,
  148684. _vq_quantlist__44u4__p6_1,
  148685. NULL,
  148686. &_vq_auxt__44u4__p6_1,
  148687. NULL,
  148688. 0
  148689. };
  148690. static long _vq_quantlist__44u4__p7_0[] = {
  148691. 6,
  148692. 5,
  148693. 7,
  148694. 4,
  148695. 8,
  148696. 3,
  148697. 9,
  148698. 2,
  148699. 10,
  148700. 1,
  148701. 11,
  148702. 0,
  148703. 12,
  148704. };
  148705. static long _vq_lengthlist__44u4__p7_0[] = {
  148706. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  148707. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  148708. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148709. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148710. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148711. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148712. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148713. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148714. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148715. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148716. 11,11,11,11,11,11,11,11,11,
  148717. };
  148718. static float _vq_quantthresh__44u4__p7_0[] = {
  148719. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  148720. 637.5, 892.5, 1147.5, 1402.5,
  148721. };
  148722. static long _vq_quantmap__44u4__p7_0[] = {
  148723. 11, 9, 7, 5, 3, 1, 0, 2,
  148724. 4, 6, 8, 10, 12,
  148725. };
  148726. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  148727. _vq_quantthresh__44u4__p7_0,
  148728. _vq_quantmap__44u4__p7_0,
  148729. 13,
  148730. 13
  148731. };
  148732. static static_codebook _44u4__p7_0 = {
  148733. 2, 169,
  148734. _vq_lengthlist__44u4__p7_0,
  148735. 1, -514332672, 1627381760, 4, 0,
  148736. _vq_quantlist__44u4__p7_0,
  148737. NULL,
  148738. &_vq_auxt__44u4__p7_0,
  148739. NULL,
  148740. 0
  148741. };
  148742. static long _vq_quantlist__44u4__p7_1[] = {
  148743. 7,
  148744. 6,
  148745. 8,
  148746. 5,
  148747. 9,
  148748. 4,
  148749. 10,
  148750. 3,
  148751. 11,
  148752. 2,
  148753. 12,
  148754. 1,
  148755. 13,
  148756. 0,
  148757. 14,
  148758. };
  148759. static long _vq_lengthlist__44u4__p7_1[] = {
  148760. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  148761. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  148762. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  148763. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  148764. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  148765. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  148766. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  148767. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  148768. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  148769. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  148770. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  148771. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  148772. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  148773. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  148774. 16,
  148775. };
  148776. static float _vq_quantthresh__44u4__p7_1[] = {
  148777. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148778. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148779. };
  148780. static long _vq_quantmap__44u4__p7_1[] = {
  148781. 13, 11, 9, 7, 5, 3, 1, 0,
  148782. 2, 4, 6, 8, 10, 12, 14,
  148783. };
  148784. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  148785. _vq_quantthresh__44u4__p7_1,
  148786. _vq_quantmap__44u4__p7_1,
  148787. 15,
  148788. 15
  148789. };
  148790. static static_codebook _44u4__p7_1 = {
  148791. 2, 225,
  148792. _vq_lengthlist__44u4__p7_1,
  148793. 1, -522338304, 1620115456, 4, 0,
  148794. _vq_quantlist__44u4__p7_1,
  148795. NULL,
  148796. &_vq_auxt__44u4__p7_1,
  148797. NULL,
  148798. 0
  148799. };
  148800. static long _vq_quantlist__44u4__p7_2[] = {
  148801. 8,
  148802. 7,
  148803. 9,
  148804. 6,
  148805. 10,
  148806. 5,
  148807. 11,
  148808. 4,
  148809. 12,
  148810. 3,
  148811. 13,
  148812. 2,
  148813. 14,
  148814. 1,
  148815. 15,
  148816. 0,
  148817. 16,
  148818. };
  148819. static long _vq_lengthlist__44u4__p7_2[] = {
  148820. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148821. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148822. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148823. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148824. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  148825. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148826. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148827. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  148828. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  148829. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  148830. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148831. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  148832. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  148833. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  148834. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  148835. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  148836. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148837. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  148838. 10,
  148839. };
  148840. static float _vq_quantthresh__44u4__p7_2[] = {
  148841. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148842. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148843. };
  148844. static long _vq_quantmap__44u4__p7_2[] = {
  148845. 15, 13, 11, 9, 7, 5, 3, 1,
  148846. 0, 2, 4, 6, 8, 10, 12, 14,
  148847. 16,
  148848. };
  148849. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  148850. _vq_quantthresh__44u4__p7_2,
  148851. _vq_quantmap__44u4__p7_2,
  148852. 17,
  148853. 17
  148854. };
  148855. static static_codebook _44u4__p7_2 = {
  148856. 2, 289,
  148857. _vq_lengthlist__44u4__p7_2,
  148858. 1, -529530880, 1611661312, 5, 0,
  148859. _vq_quantlist__44u4__p7_2,
  148860. NULL,
  148861. &_vq_auxt__44u4__p7_2,
  148862. NULL,
  148863. 0
  148864. };
  148865. static long _huff_lengthlist__44u4__short[] = {
  148866. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  148867. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  148868. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  148869. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  148870. };
  148871. static static_codebook _huff_book__44u4__short = {
  148872. 2, 64,
  148873. _huff_lengthlist__44u4__short,
  148874. 0, 0, 0, 0, 0,
  148875. NULL,
  148876. NULL,
  148877. NULL,
  148878. NULL,
  148879. 0
  148880. };
  148881. static long _huff_lengthlist__44u5__long[] = {
  148882. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  148883. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  148884. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  148885. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  148886. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  148887. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  148888. 14, 8, 7, 8,
  148889. };
  148890. static static_codebook _huff_book__44u5__long = {
  148891. 2, 100,
  148892. _huff_lengthlist__44u5__long,
  148893. 0, 0, 0, 0, 0,
  148894. NULL,
  148895. NULL,
  148896. NULL,
  148897. NULL,
  148898. 0
  148899. };
  148900. static long _vq_quantlist__44u5__p1_0[] = {
  148901. 1,
  148902. 0,
  148903. 2,
  148904. };
  148905. static long _vq_lengthlist__44u5__p1_0[] = {
  148906. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  148907. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  148908. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  148909. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  148910. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  148911. 12,
  148912. };
  148913. static float _vq_quantthresh__44u5__p1_0[] = {
  148914. -0.5, 0.5,
  148915. };
  148916. static long _vq_quantmap__44u5__p1_0[] = {
  148917. 1, 0, 2,
  148918. };
  148919. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  148920. _vq_quantthresh__44u5__p1_0,
  148921. _vq_quantmap__44u5__p1_0,
  148922. 3,
  148923. 3
  148924. };
  148925. static static_codebook _44u5__p1_0 = {
  148926. 4, 81,
  148927. _vq_lengthlist__44u5__p1_0,
  148928. 1, -535822336, 1611661312, 2, 0,
  148929. _vq_quantlist__44u5__p1_0,
  148930. NULL,
  148931. &_vq_auxt__44u5__p1_0,
  148932. NULL,
  148933. 0
  148934. };
  148935. static long _vq_quantlist__44u5__p2_0[] = {
  148936. 1,
  148937. 0,
  148938. 2,
  148939. };
  148940. static long _vq_lengthlist__44u5__p2_0[] = {
  148941. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  148942. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  148943. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  148944. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  148945. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  148946. 9,
  148947. };
  148948. static float _vq_quantthresh__44u5__p2_0[] = {
  148949. -0.5, 0.5,
  148950. };
  148951. static long _vq_quantmap__44u5__p2_0[] = {
  148952. 1, 0, 2,
  148953. };
  148954. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  148955. _vq_quantthresh__44u5__p2_0,
  148956. _vq_quantmap__44u5__p2_0,
  148957. 3,
  148958. 3
  148959. };
  148960. static static_codebook _44u5__p2_0 = {
  148961. 4, 81,
  148962. _vq_lengthlist__44u5__p2_0,
  148963. 1, -535822336, 1611661312, 2, 0,
  148964. _vq_quantlist__44u5__p2_0,
  148965. NULL,
  148966. &_vq_auxt__44u5__p2_0,
  148967. NULL,
  148968. 0
  148969. };
  148970. static long _vq_quantlist__44u5__p3_0[] = {
  148971. 2,
  148972. 1,
  148973. 3,
  148974. 0,
  148975. 4,
  148976. };
  148977. static long _vq_lengthlist__44u5__p3_0[] = {
  148978. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  148979. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148980. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  148981. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  148982. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  148983. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  148984. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  148985. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  148986. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  148987. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  148988. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  148989. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  148990. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  148991. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  148992. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  148993. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  148994. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  148995. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  148996. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  148997. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  148998. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  148999. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  149000. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  149001. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  149002. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  149003. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  149004. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  149005. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  149006. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  149007. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  149008. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  149009. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  149010. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  149011. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  149012. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  149013. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  149014. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  149015. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  149016. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  149017. 0,
  149018. };
  149019. static float _vq_quantthresh__44u5__p3_0[] = {
  149020. -1.5, -0.5, 0.5, 1.5,
  149021. };
  149022. static long _vq_quantmap__44u5__p3_0[] = {
  149023. 3, 1, 0, 2, 4,
  149024. };
  149025. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  149026. _vq_quantthresh__44u5__p3_0,
  149027. _vq_quantmap__44u5__p3_0,
  149028. 5,
  149029. 5
  149030. };
  149031. static static_codebook _44u5__p3_0 = {
  149032. 4, 625,
  149033. _vq_lengthlist__44u5__p3_0,
  149034. 1, -533725184, 1611661312, 3, 0,
  149035. _vq_quantlist__44u5__p3_0,
  149036. NULL,
  149037. &_vq_auxt__44u5__p3_0,
  149038. NULL,
  149039. 0
  149040. };
  149041. static long _vq_quantlist__44u5__p4_0[] = {
  149042. 2,
  149043. 1,
  149044. 3,
  149045. 0,
  149046. 4,
  149047. };
  149048. static long _vq_lengthlist__44u5__p4_0[] = {
  149049. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149050. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  149051. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  149052. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  149053. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  149054. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  149055. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  149056. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  149057. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  149058. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  149059. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  149060. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  149061. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149062. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  149063. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  149064. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  149065. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  149066. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  149067. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  149068. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  149069. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  149070. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  149071. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  149072. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  149073. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  149074. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  149075. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  149076. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  149077. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  149078. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  149079. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  149080. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  149081. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  149082. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  149083. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  149084. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  149085. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  149086. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  149087. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  149088. 12,
  149089. };
  149090. static float _vq_quantthresh__44u5__p4_0[] = {
  149091. -1.5, -0.5, 0.5, 1.5,
  149092. };
  149093. static long _vq_quantmap__44u5__p4_0[] = {
  149094. 3, 1, 0, 2, 4,
  149095. };
  149096. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  149097. _vq_quantthresh__44u5__p4_0,
  149098. _vq_quantmap__44u5__p4_0,
  149099. 5,
  149100. 5
  149101. };
  149102. static static_codebook _44u5__p4_0 = {
  149103. 4, 625,
  149104. _vq_lengthlist__44u5__p4_0,
  149105. 1, -533725184, 1611661312, 3, 0,
  149106. _vq_quantlist__44u5__p4_0,
  149107. NULL,
  149108. &_vq_auxt__44u5__p4_0,
  149109. NULL,
  149110. 0
  149111. };
  149112. static long _vq_quantlist__44u5__p5_0[] = {
  149113. 4,
  149114. 3,
  149115. 5,
  149116. 2,
  149117. 6,
  149118. 1,
  149119. 7,
  149120. 0,
  149121. 8,
  149122. };
  149123. static long _vq_lengthlist__44u5__p5_0[] = {
  149124. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149125. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  149126. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  149127. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  149128. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  149129. 14,
  149130. };
  149131. static float _vq_quantthresh__44u5__p5_0[] = {
  149132. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149133. };
  149134. static long _vq_quantmap__44u5__p5_0[] = {
  149135. 7, 5, 3, 1, 0, 2, 4, 6,
  149136. 8,
  149137. };
  149138. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  149139. _vq_quantthresh__44u5__p5_0,
  149140. _vq_quantmap__44u5__p5_0,
  149141. 9,
  149142. 9
  149143. };
  149144. static static_codebook _44u5__p5_0 = {
  149145. 2, 81,
  149146. _vq_lengthlist__44u5__p5_0,
  149147. 1, -531628032, 1611661312, 4, 0,
  149148. _vq_quantlist__44u5__p5_0,
  149149. NULL,
  149150. &_vq_auxt__44u5__p5_0,
  149151. NULL,
  149152. 0
  149153. };
  149154. static long _vq_quantlist__44u5__p6_0[] = {
  149155. 4,
  149156. 3,
  149157. 5,
  149158. 2,
  149159. 6,
  149160. 1,
  149161. 7,
  149162. 0,
  149163. 8,
  149164. };
  149165. static long _vq_lengthlist__44u5__p6_0[] = {
  149166. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  149167. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  149168. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  149169. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  149170. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  149171. 11,
  149172. };
  149173. static float _vq_quantthresh__44u5__p6_0[] = {
  149174. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149175. };
  149176. static long _vq_quantmap__44u5__p6_0[] = {
  149177. 7, 5, 3, 1, 0, 2, 4, 6,
  149178. 8,
  149179. };
  149180. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  149181. _vq_quantthresh__44u5__p6_0,
  149182. _vq_quantmap__44u5__p6_0,
  149183. 9,
  149184. 9
  149185. };
  149186. static static_codebook _44u5__p6_0 = {
  149187. 2, 81,
  149188. _vq_lengthlist__44u5__p6_0,
  149189. 1, -531628032, 1611661312, 4, 0,
  149190. _vq_quantlist__44u5__p6_0,
  149191. NULL,
  149192. &_vq_auxt__44u5__p6_0,
  149193. NULL,
  149194. 0
  149195. };
  149196. static long _vq_quantlist__44u5__p7_0[] = {
  149197. 1,
  149198. 0,
  149199. 2,
  149200. };
  149201. static long _vq_lengthlist__44u5__p7_0[] = {
  149202. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  149203. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  149204. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  149205. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  149206. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  149207. 12,
  149208. };
  149209. static float _vq_quantthresh__44u5__p7_0[] = {
  149210. -5.5, 5.5,
  149211. };
  149212. static long _vq_quantmap__44u5__p7_0[] = {
  149213. 1, 0, 2,
  149214. };
  149215. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  149216. _vq_quantthresh__44u5__p7_0,
  149217. _vq_quantmap__44u5__p7_0,
  149218. 3,
  149219. 3
  149220. };
  149221. static static_codebook _44u5__p7_0 = {
  149222. 4, 81,
  149223. _vq_lengthlist__44u5__p7_0,
  149224. 1, -529137664, 1618345984, 2, 0,
  149225. _vq_quantlist__44u5__p7_0,
  149226. NULL,
  149227. &_vq_auxt__44u5__p7_0,
  149228. NULL,
  149229. 0
  149230. };
  149231. static long _vq_quantlist__44u5__p7_1[] = {
  149232. 5,
  149233. 4,
  149234. 6,
  149235. 3,
  149236. 7,
  149237. 2,
  149238. 8,
  149239. 1,
  149240. 9,
  149241. 0,
  149242. 10,
  149243. };
  149244. static long _vq_lengthlist__44u5__p7_1[] = {
  149245. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  149246. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  149247. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  149248. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  149249. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  149250. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149251. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  149252. 9, 9, 9, 9, 9,10,10,10,10,
  149253. };
  149254. static float _vq_quantthresh__44u5__p7_1[] = {
  149255. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149256. 3.5, 4.5,
  149257. };
  149258. static long _vq_quantmap__44u5__p7_1[] = {
  149259. 9, 7, 5, 3, 1, 0, 2, 4,
  149260. 6, 8, 10,
  149261. };
  149262. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  149263. _vq_quantthresh__44u5__p7_1,
  149264. _vq_quantmap__44u5__p7_1,
  149265. 11,
  149266. 11
  149267. };
  149268. static static_codebook _44u5__p7_1 = {
  149269. 2, 121,
  149270. _vq_lengthlist__44u5__p7_1,
  149271. 1, -531365888, 1611661312, 4, 0,
  149272. _vq_quantlist__44u5__p7_1,
  149273. NULL,
  149274. &_vq_auxt__44u5__p7_1,
  149275. NULL,
  149276. 0
  149277. };
  149278. static long _vq_quantlist__44u5__p8_0[] = {
  149279. 5,
  149280. 4,
  149281. 6,
  149282. 3,
  149283. 7,
  149284. 2,
  149285. 8,
  149286. 1,
  149287. 9,
  149288. 0,
  149289. 10,
  149290. };
  149291. static long _vq_lengthlist__44u5__p8_0[] = {
  149292. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  149293. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  149294. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  149295. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  149296. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  149297. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  149298. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  149299. 12,13,13,14,14,14,14,15,15,
  149300. };
  149301. static float _vq_quantthresh__44u5__p8_0[] = {
  149302. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149303. 38.5, 49.5,
  149304. };
  149305. static long _vq_quantmap__44u5__p8_0[] = {
  149306. 9, 7, 5, 3, 1, 0, 2, 4,
  149307. 6, 8, 10,
  149308. };
  149309. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  149310. _vq_quantthresh__44u5__p8_0,
  149311. _vq_quantmap__44u5__p8_0,
  149312. 11,
  149313. 11
  149314. };
  149315. static static_codebook _44u5__p8_0 = {
  149316. 2, 121,
  149317. _vq_lengthlist__44u5__p8_0,
  149318. 1, -524582912, 1618345984, 4, 0,
  149319. _vq_quantlist__44u5__p8_0,
  149320. NULL,
  149321. &_vq_auxt__44u5__p8_0,
  149322. NULL,
  149323. 0
  149324. };
  149325. static long _vq_quantlist__44u5__p8_1[] = {
  149326. 5,
  149327. 4,
  149328. 6,
  149329. 3,
  149330. 7,
  149331. 2,
  149332. 8,
  149333. 1,
  149334. 9,
  149335. 0,
  149336. 10,
  149337. };
  149338. static long _vq_lengthlist__44u5__p8_1[] = {
  149339. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  149340. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  149341. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  149342. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  149343. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  149344. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  149345. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149346. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149347. };
  149348. static float _vq_quantthresh__44u5__p8_1[] = {
  149349. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149350. 3.5, 4.5,
  149351. };
  149352. static long _vq_quantmap__44u5__p8_1[] = {
  149353. 9, 7, 5, 3, 1, 0, 2, 4,
  149354. 6, 8, 10,
  149355. };
  149356. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  149357. _vq_quantthresh__44u5__p8_1,
  149358. _vq_quantmap__44u5__p8_1,
  149359. 11,
  149360. 11
  149361. };
  149362. static static_codebook _44u5__p8_1 = {
  149363. 2, 121,
  149364. _vq_lengthlist__44u5__p8_1,
  149365. 1, -531365888, 1611661312, 4, 0,
  149366. _vq_quantlist__44u5__p8_1,
  149367. NULL,
  149368. &_vq_auxt__44u5__p8_1,
  149369. NULL,
  149370. 0
  149371. };
  149372. static long _vq_quantlist__44u5__p9_0[] = {
  149373. 6,
  149374. 5,
  149375. 7,
  149376. 4,
  149377. 8,
  149378. 3,
  149379. 9,
  149380. 2,
  149381. 10,
  149382. 1,
  149383. 11,
  149384. 0,
  149385. 12,
  149386. };
  149387. static long _vq_lengthlist__44u5__p9_0[] = {
  149388. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  149389. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  149390. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  149391. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  149392. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149393. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149394. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149395. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149396. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  149397. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  149398. 12,12,12,12,12,12,12,12,12,
  149399. };
  149400. static float _vq_quantthresh__44u5__p9_0[] = {
  149401. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  149402. 637.5, 892.5, 1147.5, 1402.5,
  149403. };
  149404. static long _vq_quantmap__44u5__p9_0[] = {
  149405. 11, 9, 7, 5, 3, 1, 0, 2,
  149406. 4, 6, 8, 10, 12,
  149407. };
  149408. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  149409. _vq_quantthresh__44u5__p9_0,
  149410. _vq_quantmap__44u5__p9_0,
  149411. 13,
  149412. 13
  149413. };
  149414. static static_codebook _44u5__p9_0 = {
  149415. 2, 169,
  149416. _vq_lengthlist__44u5__p9_0,
  149417. 1, -514332672, 1627381760, 4, 0,
  149418. _vq_quantlist__44u5__p9_0,
  149419. NULL,
  149420. &_vq_auxt__44u5__p9_0,
  149421. NULL,
  149422. 0
  149423. };
  149424. static long _vq_quantlist__44u5__p9_1[] = {
  149425. 7,
  149426. 6,
  149427. 8,
  149428. 5,
  149429. 9,
  149430. 4,
  149431. 10,
  149432. 3,
  149433. 11,
  149434. 2,
  149435. 12,
  149436. 1,
  149437. 13,
  149438. 0,
  149439. 14,
  149440. };
  149441. static long _vq_lengthlist__44u5__p9_1[] = {
  149442. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  149443. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  149444. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  149445. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  149446. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  149447. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  149448. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  149449. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  149450. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  149451. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  149452. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  149453. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  149454. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  149455. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  149456. 14,
  149457. };
  149458. static float _vq_quantthresh__44u5__p9_1[] = {
  149459. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  149460. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  149461. };
  149462. static long _vq_quantmap__44u5__p9_1[] = {
  149463. 13, 11, 9, 7, 5, 3, 1, 0,
  149464. 2, 4, 6, 8, 10, 12, 14,
  149465. };
  149466. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  149467. _vq_quantthresh__44u5__p9_1,
  149468. _vq_quantmap__44u5__p9_1,
  149469. 15,
  149470. 15
  149471. };
  149472. static static_codebook _44u5__p9_1 = {
  149473. 2, 225,
  149474. _vq_lengthlist__44u5__p9_1,
  149475. 1, -522338304, 1620115456, 4, 0,
  149476. _vq_quantlist__44u5__p9_1,
  149477. NULL,
  149478. &_vq_auxt__44u5__p9_1,
  149479. NULL,
  149480. 0
  149481. };
  149482. static long _vq_quantlist__44u5__p9_2[] = {
  149483. 8,
  149484. 7,
  149485. 9,
  149486. 6,
  149487. 10,
  149488. 5,
  149489. 11,
  149490. 4,
  149491. 12,
  149492. 3,
  149493. 13,
  149494. 2,
  149495. 14,
  149496. 1,
  149497. 15,
  149498. 0,
  149499. 16,
  149500. };
  149501. static long _vq_lengthlist__44u5__p9_2[] = {
  149502. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149503. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149504. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149505. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149506. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149507. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  149508. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149509. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  149510. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149511. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  149512. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  149513. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  149514. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  149515. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  149516. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  149517. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  149518. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  149519. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  149520. 10,
  149521. };
  149522. static float _vq_quantthresh__44u5__p9_2[] = {
  149523. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149524. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149525. };
  149526. static long _vq_quantmap__44u5__p9_2[] = {
  149527. 15, 13, 11, 9, 7, 5, 3, 1,
  149528. 0, 2, 4, 6, 8, 10, 12, 14,
  149529. 16,
  149530. };
  149531. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  149532. _vq_quantthresh__44u5__p9_2,
  149533. _vq_quantmap__44u5__p9_2,
  149534. 17,
  149535. 17
  149536. };
  149537. static static_codebook _44u5__p9_2 = {
  149538. 2, 289,
  149539. _vq_lengthlist__44u5__p9_2,
  149540. 1, -529530880, 1611661312, 5, 0,
  149541. _vq_quantlist__44u5__p9_2,
  149542. NULL,
  149543. &_vq_auxt__44u5__p9_2,
  149544. NULL,
  149545. 0
  149546. };
  149547. static long _huff_lengthlist__44u5__short[] = {
  149548. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  149549. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  149550. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  149551. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  149552. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  149553. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  149554. 6, 8,15,17,
  149555. };
  149556. static static_codebook _huff_book__44u5__short = {
  149557. 2, 100,
  149558. _huff_lengthlist__44u5__short,
  149559. 0, 0, 0, 0, 0,
  149560. NULL,
  149561. NULL,
  149562. NULL,
  149563. NULL,
  149564. 0
  149565. };
  149566. static long _huff_lengthlist__44u6__long[] = {
  149567. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  149568. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  149569. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  149570. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  149571. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  149572. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  149573. 13, 8, 7, 7,
  149574. };
  149575. static static_codebook _huff_book__44u6__long = {
  149576. 2, 100,
  149577. _huff_lengthlist__44u6__long,
  149578. 0, 0, 0, 0, 0,
  149579. NULL,
  149580. NULL,
  149581. NULL,
  149582. NULL,
  149583. 0
  149584. };
  149585. static long _vq_quantlist__44u6__p1_0[] = {
  149586. 1,
  149587. 0,
  149588. 2,
  149589. };
  149590. static long _vq_lengthlist__44u6__p1_0[] = {
  149591. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149592. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  149593. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149594. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  149595. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  149596. 12,
  149597. };
  149598. static float _vq_quantthresh__44u6__p1_0[] = {
  149599. -0.5, 0.5,
  149600. };
  149601. static long _vq_quantmap__44u6__p1_0[] = {
  149602. 1, 0, 2,
  149603. };
  149604. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  149605. _vq_quantthresh__44u6__p1_0,
  149606. _vq_quantmap__44u6__p1_0,
  149607. 3,
  149608. 3
  149609. };
  149610. static static_codebook _44u6__p1_0 = {
  149611. 4, 81,
  149612. _vq_lengthlist__44u6__p1_0,
  149613. 1, -535822336, 1611661312, 2, 0,
  149614. _vq_quantlist__44u6__p1_0,
  149615. NULL,
  149616. &_vq_auxt__44u6__p1_0,
  149617. NULL,
  149618. 0
  149619. };
  149620. static long _vq_quantlist__44u6__p2_0[] = {
  149621. 1,
  149622. 0,
  149623. 2,
  149624. };
  149625. static long _vq_lengthlist__44u6__p2_0[] = {
  149626. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149627. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149628. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  149629. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149630. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149631. 9,
  149632. };
  149633. static float _vq_quantthresh__44u6__p2_0[] = {
  149634. -0.5, 0.5,
  149635. };
  149636. static long _vq_quantmap__44u6__p2_0[] = {
  149637. 1, 0, 2,
  149638. };
  149639. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  149640. _vq_quantthresh__44u6__p2_0,
  149641. _vq_quantmap__44u6__p2_0,
  149642. 3,
  149643. 3
  149644. };
  149645. static static_codebook _44u6__p2_0 = {
  149646. 4, 81,
  149647. _vq_lengthlist__44u6__p2_0,
  149648. 1, -535822336, 1611661312, 2, 0,
  149649. _vq_quantlist__44u6__p2_0,
  149650. NULL,
  149651. &_vq_auxt__44u6__p2_0,
  149652. NULL,
  149653. 0
  149654. };
  149655. static long _vq_quantlist__44u6__p3_0[] = {
  149656. 2,
  149657. 1,
  149658. 3,
  149659. 0,
  149660. 4,
  149661. };
  149662. static long _vq_lengthlist__44u6__p3_0[] = {
  149663. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149664. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  149665. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149666. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  149667. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  149668. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  149669. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  149670. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  149671. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  149672. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  149673. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  149674. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  149675. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  149676. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  149677. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  149678. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  149679. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  149680. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  149681. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  149682. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  149683. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  149684. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  149685. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  149686. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  149687. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  149688. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  149689. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  149690. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  149691. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  149692. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  149693. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  149694. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  149695. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  149696. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  149697. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  149698. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  149699. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  149700. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  149701. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  149702. 19,
  149703. };
  149704. static float _vq_quantthresh__44u6__p3_0[] = {
  149705. -1.5, -0.5, 0.5, 1.5,
  149706. };
  149707. static long _vq_quantmap__44u6__p3_0[] = {
  149708. 3, 1, 0, 2, 4,
  149709. };
  149710. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  149711. _vq_quantthresh__44u6__p3_0,
  149712. _vq_quantmap__44u6__p3_0,
  149713. 5,
  149714. 5
  149715. };
  149716. static static_codebook _44u6__p3_0 = {
  149717. 4, 625,
  149718. _vq_lengthlist__44u6__p3_0,
  149719. 1, -533725184, 1611661312, 3, 0,
  149720. _vq_quantlist__44u6__p3_0,
  149721. NULL,
  149722. &_vq_auxt__44u6__p3_0,
  149723. NULL,
  149724. 0
  149725. };
  149726. static long _vq_quantlist__44u6__p4_0[] = {
  149727. 2,
  149728. 1,
  149729. 3,
  149730. 0,
  149731. 4,
  149732. };
  149733. static long _vq_lengthlist__44u6__p4_0[] = {
  149734. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149735. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  149736. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  149737. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  149738. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  149739. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  149740. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149741. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  149742. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  149743. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  149744. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  149745. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  149746. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149747. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  149748. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  149749. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  149750. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  149751. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  149752. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  149753. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  149754. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  149755. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  149756. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  149757. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  149758. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  149759. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  149760. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  149761. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  149762. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  149763. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  149764. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  149765. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149766. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  149767. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  149768. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  149769. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  149770. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  149771. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  149772. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  149773. 13,
  149774. };
  149775. static float _vq_quantthresh__44u6__p4_0[] = {
  149776. -1.5, -0.5, 0.5, 1.5,
  149777. };
  149778. static long _vq_quantmap__44u6__p4_0[] = {
  149779. 3, 1, 0, 2, 4,
  149780. };
  149781. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  149782. _vq_quantthresh__44u6__p4_0,
  149783. _vq_quantmap__44u6__p4_0,
  149784. 5,
  149785. 5
  149786. };
  149787. static static_codebook _44u6__p4_0 = {
  149788. 4, 625,
  149789. _vq_lengthlist__44u6__p4_0,
  149790. 1, -533725184, 1611661312, 3, 0,
  149791. _vq_quantlist__44u6__p4_0,
  149792. NULL,
  149793. &_vq_auxt__44u6__p4_0,
  149794. NULL,
  149795. 0
  149796. };
  149797. static long _vq_quantlist__44u6__p5_0[] = {
  149798. 4,
  149799. 3,
  149800. 5,
  149801. 2,
  149802. 6,
  149803. 1,
  149804. 7,
  149805. 0,
  149806. 8,
  149807. };
  149808. static long _vq_lengthlist__44u6__p5_0[] = {
  149809. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149810. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  149811. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  149812. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  149813. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  149814. 14,
  149815. };
  149816. static float _vq_quantthresh__44u6__p5_0[] = {
  149817. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149818. };
  149819. static long _vq_quantmap__44u6__p5_0[] = {
  149820. 7, 5, 3, 1, 0, 2, 4, 6,
  149821. 8,
  149822. };
  149823. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  149824. _vq_quantthresh__44u6__p5_0,
  149825. _vq_quantmap__44u6__p5_0,
  149826. 9,
  149827. 9
  149828. };
  149829. static static_codebook _44u6__p5_0 = {
  149830. 2, 81,
  149831. _vq_lengthlist__44u6__p5_0,
  149832. 1, -531628032, 1611661312, 4, 0,
  149833. _vq_quantlist__44u6__p5_0,
  149834. NULL,
  149835. &_vq_auxt__44u6__p5_0,
  149836. NULL,
  149837. 0
  149838. };
  149839. static long _vq_quantlist__44u6__p6_0[] = {
  149840. 4,
  149841. 3,
  149842. 5,
  149843. 2,
  149844. 6,
  149845. 1,
  149846. 7,
  149847. 0,
  149848. 8,
  149849. };
  149850. static long _vq_lengthlist__44u6__p6_0[] = {
  149851. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  149852. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  149853. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  149854. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  149855. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  149856. 12,
  149857. };
  149858. static float _vq_quantthresh__44u6__p6_0[] = {
  149859. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149860. };
  149861. static long _vq_quantmap__44u6__p6_0[] = {
  149862. 7, 5, 3, 1, 0, 2, 4, 6,
  149863. 8,
  149864. };
  149865. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  149866. _vq_quantthresh__44u6__p6_0,
  149867. _vq_quantmap__44u6__p6_0,
  149868. 9,
  149869. 9
  149870. };
  149871. static static_codebook _44u6__p6_0 = {
  149872. 2, 81,
  149873. _vq_lengthlist__44u6__p6_0,
  149874. 1, -531628032, 1611661312, 4, 0,
  149875. _vq_quantlist__44u6__p6_0,
  149876. NULL,
  149877. &_vq_auxt__44u6__p6_0,
  149878. NULL,
  149879. 0
  149880. };
  149881. static long _vq_quantlist__44u6__p7_0[] = {
  149882. 1,
  149883. 0,
  149884. 2,
  149885. };
  149886. static long _vq_lengthlist__44u6__p7_0[] = {
  149887. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  149888. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  149889. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  149890. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  149891. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  149892. 10,
  149893. };
  149894. static float _vq_quantthresh__44u6__p7_0[] = {
  149895. -5.5, 5.5,
  149896. };
  149897. static long _vq_quantmap__44u6__p7_0[] = {
  149898. 1, 0, 2,
  149899. };
  149900. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  149901. _vq_quantthresh__44u6__p7_0,
  149902. _vq_quantmap__44u6__p7_0,
  149903. 3,
  149904. 3
  149905. };
  149906. static static_codebook _44u6__p7_0 = {
  149907. 4, 81,
  149908. _vq_lengthlist__44u6__p7_0,
  149909. 1, -529137664, 1618345984, 2, 0,
  149910. _vq_quantlist__44u6__p7_0,
  149911. NULL,
  149912. &_vq_auxt__44u6__p7_0,
  149913. NULL,
  149914. 0
  149915. };
  149916. static long _vq_quantlist__44u6__p7_1[] = {
  149917. 5,
  149918. 4,
  149919. 6,
  149920. 3,
  149921. 7,
  149922. 2,
  149923. 8,
  149924. 1,
  149925. 9,
  149926. 0,
  149927. 10,
  149928. };
  149929. static long _vq_lengthlist__44u6__p7_1[] = {
  149930. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  149931. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  149932. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  149933. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  149934. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  149935. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  149936. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  149937. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149938. };
  149939. static float _vq_quantthresh__44u6__p7_1[] = {
  149940. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149941. 3.5, 4.5,
  149942. };
  149943. static long _vq_quantmap__44u6__p7_1[] = {
  149944. 9, 7, 5, 3, 1, 0, 2, 4,
  149945. 6, 8, 10,
  149946. };
  149947. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  149948. _vq_quantthresh__44u6__p7_1,
  149949. _vq_quantmap__44u6__p7_1,
  149950. 11,
  149951. 11
  149952. };
  149953. static static_codebook _44u6__p7_1 = {
  149954. 2, 121,
  149955. _vq_lengthlist__44u6__p7_1,
  149956. 1, -531365888, 1611661312, 4, 0,
  149957. _vq_quantlist__44u6__p7_1,
  149958. NULL,
  149959. &_vq_auxt__44u6__p7_1,
  149960. NULL,
  149961. 0
  149962. };
  149963. static long _vq_quantlist__44u6__p8_0[] = {
  149964. 5,
  149965. 4,
  149966. 6,
  149967. 3,
  149968. 7,
  149969. 2,
  149970. 8,
  149971. 1,
  149972. 9,
  149973. 0,
  149974. 10,
  149975. };
  149976. static long _vq_lengthlist__44u6__p8_0[] = {
  149977. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  149978. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  149979. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  149980. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  149981. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  149982. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  149983. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  149984. 12,13,13,14,14,14,15,15,15,
  149985. };
  149986. static float _vq_quantthresh__44u6__p8_0[] = {
  149987. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149988. 38.5, 49.5,
  149989. };
  149990. static long _vq_quantmap__44u6__p8_0[] = {
  149991. 9, 7, 5, 3, 1, 0, 2, 4,
  149992. 6, 8, 10,
  149993. };
  149994. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  149995. _vq_quantthresh__44u6__p8_0,
  149996. _vq_quantmap__44u6__p8_0,
  149997. 11,
  149998. 11
  149999. };
  150000. static static_codebook _44u6__p8_0 = {
  150001. 2, 121,
  150002. _vq_lengthlist__44u6__p8_0,
  150003. 1, -524582912, 1618345984, 4, 0,
  150004. _vq_quantlist__44u6__p8_0,
  150005. NULL,
  150006. &_vq_auxt__44u6__p8_0,
  150007. NULL,
  150008. 0
  150009. };
  150010. static long _vq_quantlist__44u6__p8_1[] = {
  150011. 5,
  150012. 4,
  150013. 6,
  150014. 3,
  150015. 7,
  150016. 2,
  150017. 8,
  150018. 1,
  150019. 9,
  150020. 0,
  150021. 10,
  150022. };
  150023. static long _vq_lengthlist__44u6__p8_1[] = {
  150024. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  150025. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  150026. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  150027. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  150028. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  150029. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  150030. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  150031. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  150032. };
  150033. static float _vq_quantthresh__44u6__p8_1[] = {
  150034. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150035. 3.5, 4.5,
  150036. };
  150037. static long _vq_quantmap__44u6__p8_1[] = {
  150038. 9, 7, 5, 3, 1, 0, 2, 4,
  150039. 6, 8, 10,
  150040. };
  150041. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  150042. _vq_quantthresh__44u6__p8_1,
  150043. _vq_quantmap__44u6__p8_1,
  150044. 11,
  150045. 11
  150046. };
  150047. static static_codebook _44u6__p8_1 = {
  150048. 2, 121,
  150049. _vq_lengthlist__44u6__p8_1,
  150050. 1, -531365888, 1611661312, 4, 0,
  150051. _vq_quantlist__44u6__p8_1,
  150052. NULL,
  150053. &_vq_auxt__44u6__p8_1,
  150054. NULL,
  150055. 0
  150056. };
  150057. static long _vq_quantlist__44u6__p9_0[] = {
  150058. 7,
  150059. 6,
  150060. 8,
  150061. 5,
  150062. 9,
  150063. 4,
  150064. 10,
  150065. 3,
  150066. 11,
  150067. 2,
  150068. 12,
  150069. 1,
  150070. 13,
  150071. 0,
  150072. 14,
  150073. };
  150074. static long _vq_lengthlist__44u6__p9_0[] = {
  150075. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  150076. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  150077. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  150078. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  150079. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150080. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150081. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150082. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150083. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150084. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150085. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150086. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150087. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150088. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150089. 14,
  150090. };
  150091. static float _vq_quantthresh__44u6__p9_0[] = {
  150092. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  150093. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  150094. };
  150095. static long _vq_quantmap__44u6__p9_0[] = {
  150096. 13, 11, 9, 7, 5, 3, 1, 0,
  150097. 2, 4, 6, 8, 10, 12, 14,
  150098. };
  150099. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  150100. _vq_quantthresh__44u6__p9_0,
  150101. _vq_quantmap__44u6__p9_0,
  150102. 15,
  150103. 15
  150104. };
  150105. static static_codebook _44u6__p9_0 = {
  150106. 2, 225,
  150107. _vq_lengthlist__44u6__p9_0,
  150108. 1, -514071552, 1627381760, 4, 0,
  150109. _vq_quantlist__44u6__p9_0,
  150110. NULL,
  150111. &_vq_auxt__44u6__p9_0,
  150112. NULL,
  150113. 0
  150114. };
  150115. static long _vq_quantlist__44u6__p9_1[] = {
  150116. 7,
  150117. 6,
  150118. 8,
  150119. 5,
  150120. 9,
  150121. 4,
  150122. 10,
  150123. 3,
  150124. 11,
  150125. 2,
  150126. 12,
  150127. 1,
  150128. 13,
  150129. 0,
  150130. 14,
  150131. };
  150132. static long _vq_lengthlist__44u6__p9_1[] = {
  150133. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  150134. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  150135. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  150136. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  150137. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  150138. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  150139. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  150140. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  150141. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  150142. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  150143. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  150144. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  150145. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  150146. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  150147. 13,
  150148. };
  150149. static float _vq_quantthresh__44u6__p9_1[] = {
  150150. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  150151. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  150152. };
  150153. static long _vq_quantmap__44u6__p9_1[] = {
  150154. 13, 11, 9, 7, 5, 3, 1, 0,
  150155. 2, 4, 6, 8, 10, 12, 14,
  150156. };
  150157. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  150158. _vq_quantthresh__44u6__p9_1,
  150159. _vq_quantmap__44u6__p9_1,
  150160. 15,
  150161. 15
  150162. };
  150163. static static_codebook _44u6__p9_1 = {
  150164. 2, 225,
  150165. _vq_lengthlist__44u6__p9_1,
  150166. 1, -522338304, 1620115456, 4, 0,
  150167. _vq_quantlist__44u6__p9_1,
  150168. NULL,
  150169. &_vq_auxt__44u6__p9_1,
  150170. NULL,
  150171. 0
  150172. };
  150173. static long _vq_quantlist__44u6__p9_2[] = {
  150174. 8,
  150175. 7,
  150176. 9,
  150177. 6,
  150178. 10,
  150179. 5,
  150180. 11,
  150181. 4,
  150182. 12,
  150183. 3,
  150184. 13,
  150185. 2,
  150186. 14,
  150187. 1,
  150188. 15,
  150189. 0,
  150190. 16,
  150191. };
  150192. static long _vq_lengthlist__44u6__p9_2[] = {
  150193. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  150194. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  150195. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  150196. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150197. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150198. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150199. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150200. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150201. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150202. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  150203. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  150204. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150205. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  150206. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  150207. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  150208. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  150209. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  150210. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  150211. 10,
  150212. };
  150213. static float _vq_quantthresh__44u6__p9_2[] = {
  150214. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150215. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150216. };
  150217. static long _vq_quantmap__44u6__p9_2[] = {
  150218. 15, 13, 11, 9, 7, 5, 3, 1,
  150219. 0, 2, 4, 6, 8, 10, 12, 14,
  150220. 16,
  150221. };
  150222. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  150223. _vq_quantthresh__44u6__p9_2,
  150224. _vq_quantmap__44u6__p9_2,
  150225. 17,
  150226. 17
  150227. };
  150228. static static_codebook _44u6__p9_2 = {
  150229. 2, 289,
  150230. _vq_lengthlist__44u6__p9_2,
  150231. 1, -529530880, 1611661312, 5, 0,
  150232. _vq_quantlist__44u6__p9_2,
  150233. NULL,
  150234. &_vq_auxt__44u6__p9_2,
  150235. NULL,
  150236. 0
  150237. };
  150238. static long _huff_lengthlist__44u6__short[] = {
  150239. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  150240. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  150241. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  150242. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  150243. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  150244. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  150245. 7, 6, 9,16,
  150246. };
  150247. static static_codebook _huff_book__44u6__short = {
  150248. 2, 100,
  150249. _huff_lengthlist__44u6__short,
  150250. 0, 0, 0, 0, 0,
  150251. NULL,
  150252. NULL,
  150253. NULL,
  150254. NULL,
  150255. 0
  150256. };
  150257. static long _huff_lengthlist__44u7__long[] = {
  150258. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  150259. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  150260. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  150261. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  150262. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  150263. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  150264. 12, 8, 6, 7,
  150265. };
  150266. static static_codebook _huff_book__44u7__long = {
  150267. 2, 100,
  150268. _huff_lengthlist__44u7__long,
  150269. 0, 0, 0, 0, 0,
  150270. NULL,
  150271. NULL,
  150272. NULL,
  150273. NULL,
  150274. 0
  150275. };
  150276. static long _vq_quantlist__44u7__p1_0[] = {
  150277. 1,
  150278. 0,
  150279. 2,
  150280. };
  150281. static long _vq_lengthlist__44u7__p1_0[] = {
  150282. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  150283. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  150284. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  150285. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  150286. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  150287. 12,
  150288. };
  150289. static float _vq_quantthresh__44u7__p1_0[] = {
  150290. -0.5, 0.5,
  150291. };
  150292. static long _vq_quantmap__44u7__p1_0[] = {
  150293. 1, 0, 2,
  150294. };
  150295. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  150296. _vq_quantthresh__44u7__p1_0,
  150297. _vq_quantmap__44u7__p1_0,
  150298. 3,
  150299. 3
  150300. };
  150301. static static_codebook _44u7__p1_0 = {
  150302. 4, 81,
  150303. _vq_lengthlist__44u7__p1_0,
  150304. 1, -535822336, 1611661312, 2, 0,
  150305. _vq_quantlist__44u7__p1_0,
  150306. NULL,
  150307. &_vq_auxt__44u7__p1_0,
  150308. NULL,
  150309. 0
  150310. };
  150311. static long _vq_quantlist__44u7__p2_0[] = {
  150312. 1,
  150313. 0,
  150314. 2,
  150315. };
  150316. static long _vq_lengthlist__44u7__p2_0[] = {
  150317. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  150318. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  150319. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  150320. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  150321. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  150322. 9,
  150323. };
  150324. static float _vq_quantthresh__44u7__p2_0[] = {
  150325. -0.5, 0.5,
  150326. };
  150327. static long _vq_quantmap__44u7__p2_0[] = {
  150328. 1, 0, 2,
  150329. };
  150330. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  150331. _vq_quantthresh__44u7__p2_0,
  150332. _vq_quantmap__44u7__p2_0,
  150333. 3,
  150334. 3
  150335. };
  150336. static static_codebook _44u7__p2_0 = {
  150337. 4, 81,
  150338. _vq_lengthlist__44u7__p2_0,
  150339. 1, -535822336, 1611661312, 2, 0,
  150340. _vq_quantlist__44u7__p2_0,
  150341. NULL,
  150342. &_vq_auxt__44u7__p2_0,
  150343. NULL,
  150344. 0
  150345. };
  150346. static long _vq_quantlist__44u7__p3_0[] = {
  150347. 2,
  150348. 1,
  150349. 3,
  150350. 0,
  150351. 4,
  150352. };
  150353. static long _vq_lengthlist__44u7__p3_0[] = {
  150354. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  150355. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  150356. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  150357. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  150358. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  150359. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  150360. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  150361. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  150362. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  150363. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  150364. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  150365. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  150366. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  150367. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  150368. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  150369. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  150370. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  150371. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  150372. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  150373. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  150374. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  150375. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  150376. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  150377. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  150378. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  150379. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  150380. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  150381. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  150382. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  150383. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  150384. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  150385. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  150386. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  150387. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  150388. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  150389. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  150390. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  150391. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  150392. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  150393. 0,
  150394. };
  150395. static float _vq_quantthresh__44u7__p3_0[] = {
  150396. -1.5, -0.5, 0.5, 1.5,
  150397. };
  150398. static long _vq_quantmap__44u7__p3_0[] = {
  150399. 3, 1, 0, 2, 4,
  150400. };
  150401. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  150402. _vq_quantthresh__44u7__p3_0,
  150403. _vq_quantmap__44u7__p3_0,
  150404. 5,
  150405. 5
  150406. };
  150407. static static_codebook _44u7__p3_0 = {
  150408. 4, 625,
  150409. _vq_lengthlist__44u7__p3_0,
  150410. 1, -533725184, 1611661312, 3, 0,
  150411. _vq_quantlist__44u7__p3_0,
  150412. NULL,
  150413. &_vq_auxt__44u7__p3_0,
  150414. NULL,
  150415. 0
  150416. };
  150417. static long _vq_quantlist__44u7__p4_0[] = {
  150418. 2,
  150419. 1,
  150420. 3,
  150421. 0,
  150422. 4,
  150423. };
  150424. static long _vq_lengthlist__44u7__p4_0[] = {
  150425. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  150426. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  150427. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  150428. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  150429. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  150430. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  150431. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  150432. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  150433. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  150434. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  150435. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  150436. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  150437. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  150438. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  150439. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  150440. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  150441. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  150442. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  150443. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  150444. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  150445. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  150446. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  150447. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  150448. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  150449. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  150450. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  150451. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  150452. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  150453. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  150454. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  150455. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  150456. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150457. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  150458. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  150459. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  150460. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  150461. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  150462. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  150463. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  150464. 14,
  150465. };
  150466. static float _vq_quantthresh__44u7__p4_0[] = {
  150467. -1.5, -0.5, 0.5, 1.5,
  150468. };
  150469. static long _vq_quantmap__44u7__p4_0[] = {
  150470. 3, 1, 0, 2, 4,
  150471. };
  150472. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  150473. _vq_quantthresh__44u7__p4_0,
  150474. _vq_quantmap__44u7__p4_0,
  150475. 5,
  150476. 5
  150477. };
  150478. static static_codebook _44u7__p4_0 = {
  150479. 4, 625,
  150480. _vq_lengthlist__44u7__p4_0,
  150481. 1, -533725184, 1611661312, 3, 0,
  150482. _vq_quantlist__44u7__p4_0,
  150483. NULL,
  150484. &_vq_auxt__44u7__p4_0,
  150485. NULL,
  150486. 0
  150487. };
  150488. static long _vq_quantlist__44u7__p5_0[] = {
  150489. 4,
  150490. 3,
  150491. 5,
  150492. 2,
  150493. 6,
  150494. 1,
  150495. 7,
  150496. 0,
  150497. 8,
  150498. };
  150499. static long _vq_lengthlist__44u7__p5_0[] = {
  150500. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  150501. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  150502. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  150503. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  150504. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  150505. 14,
  150506. };
  150507. static float _vq_quantthresh__44u7__p5_0[] = {
  150508. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150509. };
  150510. static long _vq_quantmap__44u7__p5_0[] = {
  150511. 7, 5, 3, 1, 0, 2, 4, 6,
  150512. 8,
  150513. };
  150514. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  150515. _vq_quantthresh__44u7__p5_0,
  150516. _vq_quantmap__44u7__p5_0,
  150517. 9,
  150518. 9
  150519. };
  150520. static static_codebook _44u7__p5_0 = {
  150521. 2, 81,
  150522. _vq_lengthlist__44u7__p5_0,
  150523. 1, -531628032, 1611661312, 4, 0,
  150524. _vq_quantlist__44u7__p5_0,
  150525. NULL,
  150526. &_vq_auxt__44u7__p5_0,
  150527. NULL,
  150528. 0
  150529. };
  150530. static long _vq_quantlist__44u7__p6_0[] = {
  150531. 4,
  150532. 3,
  150533. 5,
  150534. 2,
  150535. 6,
  150536. 1,
  150537. 7,
  150538. 0,
  150539. 8,
  150540. };
  150541. static long _vq_lengthlist__44u7__p6_0[] = {
  150542. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  150543. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  150544. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  150545. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  150546. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  150547. 12,
  150548. };
  150549. static float _vq_quantthresh__44u7__p6_0[] = {
  150550. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150551. };
  150552. static long _vq_quantmap__44u7__p6_0[] = {
  150553. 7, 5, 3, 1, 0, 2, 4, 6,
  150554. 8,
  150555. };
  150556. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  150557. _vq_quantthresh__44u7__p6_0,
  150558. _vq_quantmap__44u7__p6_0,
  150559. 9,
  150560. 9
  150561. };
  150562. static static_codebook _44u7__p6_0 = {
  150563. 2, 81,
  150564. _vq_lengthlist__44u7__p6_0,
  150565. 1, -531628032, 1611661312, 4, 0,
  150566. _vq_quantlist__44u7__p6_0,
  150567. NULL,
  150568. &_vq_auxt__44u7__p6_0,
  150569. NULL,
  150570. 0
  150571. };
  150572. static long _vq_quantlist__44u7__p7_0[] = {
  150573. 1,
  150574. 0,
  150575. 2,
  150576. };
  150577. static long _vq_lengthlist__44u7__p7_0[] = {
  150578. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  150579. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  150580. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  150581. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  150582. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  150583. 10,
  150584. };
  150585. static float _vq_quantthresh__44u7__p7_0[] = {
  150586. -5.5, 5.5,
  150587. };
  150588. static long _vq_quantmap__44u7__p7_0[] = {
  150589. 1, 0, 2,
  150590. };
  150591. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  150592. _vq_quantthresh__44u7__p7_0,
  150593. _vq_quantmap__44u7__p7_0,
  150594. 3,
  150595. 3
  150596. };
  150597. static static_codebook _44u7__p7_0 = {
  150598. 4, 81,
  150599. _vq_lengthlist__44u7__p7_0,
  150600. 1, -529137664, 1618345984, 2, 0,
  150601. _vq_quantlist__44u7__p7_0,
  150602. NULL,
  150603. &_vq_auxt__44u7__p7_0,
  150604. NULL,
  150605. 0
  150606. };
  150607. static long _vq_quantlist__44u7__p7_1[] = {
  150608. 5,
  150609. 4,
  150610. 6,
  150611. 3,
  150612. 7,
  150613. 2,
  150614. 8,
  150615. 1,
  150616. 9,
  150617. 0,
  150618. 10,
  150619. };
  150620. static long _vq_lengthlist__44u7__p7_1[] = {
  150621. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  150622. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  150623. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  150624. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  150625. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  150626. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150627. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  150628. 8, 9, 9, 9, 9, 9,10,10,10,
  150629. };
  150630. static float _vq_quantthresh__44u7__p7_1[] = {
  150631. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150632. 3.5, 4.5,
  150633. };
  150634. static long _vq_quantmap__44u7__p7_1[] = {
  150635. 9, 7, 5, 3, 1, 0, 2, 4,
  150636. 6, 8, 10,
  150637. };
  150638. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  150639. _vq_quantthresh__44u7__p7_1,
  150640. _vq_quantmap__44u7__p7_1,
  150641. 11,
  150642. 11
  150643. };
  150644. static static_codebook _44u7__p7_1 = {
  150645. 2, 121,
  150646. _vq_lengthlist__44u7__p7_1,
  150647. 1, -531365888, 1611661312, 4, 0,
  150648. _vq_quantlist__44u7__p7_1,
  150649. NULL,
  150650. &_vq_auxt__44u7__p7_1,
  150651. NULL,
  150652. 0
  150653. };
  150654. static long _vq_quantlist__44u7__p8_0[] = {
  150655. 5,
  150656. 4,
  150657. 6,
  150658. 3,
  150659. 7,
  150660. 2,
  150661. 8,
  150662. 1,
  150663. 9,
  150664. 0,
  150665. 10,
  150666. };
  150667. static long _vq_lengthlist__44u7__p8_0[] = {
  150668. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  150669. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  150670. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  150671. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  150672. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  150673. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  150674. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  150675. 12,13,13,14,14,15,15,15,16,
  150676. };
  150677. static float _vq_quantthresh__44u7__p8_0[] = {
  150678. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  150679. 38.5, 49.5,
  150680. };
  150681. static long _vq_quantmap__44u7__p8_0[] = {
  150682. 9, 7, 5, 3, 1, 0, 2, 4,
  150683. 6, 8, 10,
  150684. };
  150685. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  150686. _vq_quantthresh__44u7__p8_0,
  150687. _vq_quantmap__44u7__p8_0,
  150688. 11,
  150689. 11
  150690. };
  150691. static static_codebook _44u7__p8_0 = {
  150692. 2, 121,
  150693. _vq_lengthlist__44u7__p8_0,
  150694. 1, -524582912, 1618345984, 4, 0,
  150695. _vq_quantlist__44u7__p8_0,
  150696. NULL,
  150697. &_vq_auxt__44u7__p8_0,
  150698. NULL,
  150699. 0
  150700. };
  150701. static long _vq_quantlist__44u7__p8_1[] = {
  150702. 5,
  150703. 4,
  150704. 6,
  150705. 3,
  150706. 7,
  150707. 2,
  150708. 8,
  150709. 1,
  150710. 9,
  150711. 0,
  150712. 10,
  150713. };
  150714. static long _vq_lengthlist__44u7__p8_1[] = {
  150715. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  150716. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  150717. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  150718. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  150719. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  150720. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  150721. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  150722. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  150723. };
  150724. static float _vq_quantthresh__44u7__p8_1[] = {
  150725. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150726. 3.5, 4.5,
  150727. };
  150728. static long _vq_quantmap__44u7__p8_1[] = {
  150729. 9, 7, 5, 3, 1, 0, 2, 4,
  150730. 6, 8, 10,
  150731. };
  150732. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  150733. _vq_quantthresh__44u7__p8_1,
  150734. _vq_quantmap__44u7__p8_1,
  150735. 11,
  150736. 11
  150737. };
  150738. static static_codebook _44u7__p8_1 = {
  150739. 2, 121,
  150740. _vq_lengthlist__44u7__p8_1,
  150741. 1, -531365888, 1611661312, 4, 0,
  150742. _vq_quantlist__44u7__p8_1,
  150743. NULL,
  150744. &_vq_auxt__44u7__p8_1,
  150745. NULL,
  150746. 0
  150747. };
  150748. static long _vq_quantlist__44u7__p9_0[] = {
  150749. 5,
  150750. 4,
  150751. 6,
  150752. 3,
  150753. 7,
  150754. 2,
  150755. 8,
  150756. 1,
  150757. 9,
  150758. 0,
  150759. 10,
  150760. };
  150761. static long _vq_lengthlist__44u7__p9_0[] = {
  150762. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  150763. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  150764. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150765. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150766. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150767. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150768. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  150769. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150770. };
  150771. static float _vq_quantthresh__44u7__p9_0[] = {
  150772. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  150773. 2229.5, 2866.5,
  150774. };
  150775. static long _vq_quantmap__44u7__p9_0[] = {
  150776. 9, 7, 5, 3, 1, 0, 2, 4,
  150777. 6, 8, 10,
  150778. };
  150779. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  150780. _vq_quantthresh__44u7__p9_0,
  150781. _vq_quantmap__44u7__p9_0,
  150782. 11,
  150783. 11
  150784. };
  150785. static static_codebook _44u7__p9_0 = {
  150786. 2, 121,
  150787. _vq_lengthlist__44u7__p9_0,
  150788. 1, -512171520, 1630791680, 4, 0,
  150789. _vq_quantlist__44u7__p9_0,
  150790. NULL,
  150791. &_vq_auxt__44u7__p9_0,
  150792. NULL,
  150793. 0
  150794. };
  150795. static long _vq_quantlist__44u7__p9_1[] = {
  150796. 6,
  150797. 5,
  150798. 7,
  150799. 4,
  150800. 8,
  150801. 3,
  150802. 9,
  150803. 2,
  150804. 10,
  150805. 1,
  150806. 11,
  150807. 0,
  150808. 12,
  150809. };
  150810. static long _vq_lengthlist__44u7__p9_1[] = {
  150811. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  150812. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  150813. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  150814. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  150815. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  150816. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  150817. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  150818. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  150819. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  150820. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  150821. 15,15,15,15,17,17,16,17,16,
  150822. };
  150823. static float _vq_quantthresh__44u7__p9_1[] = {
  150824. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  150825. 122.5, 171.5, 220.5, 269.5,
  150826. };
  150827. static long _vq_quantmap__44u7__p9_1[] = {
  150828. 11, 9, 7, 5, 3, 1, 0, 2,
  150829. 4, 6, 8, 10, 12,
  150830. };
  150831. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  150832. _vq_quantthresh__44u7__p9_1,
  150833. _vq_quantmap__44u7__p9_1,
  150834. 13,
  150835. 13
  150836. };
  150837. static static_codebook _44u7__p9_1 = {
  150838. 2, 169,
  150839. _vq_lengthlist__44u7__p9_1,
  150840. 1, -518889472, 1622704128, 4, 0,
  150841. _vq_quantlist__44u7__p9_1,
  150842. NULL,
  150843. &_vq_auxt__44u7__p9_1,
  150844. NULL,
  150845. 0
  150846. };
  150847. static long _vq_quantlist__44u7__p9_2[] = {
  150848. 24,
  150849. 23,
  150850. 25,
  150851. 22,
  150852. 26,
  150853. 21,
  150854. 27,
  150855. 20,
  150856. 28,
  150857. 19,
  150858. 29,
  150859. 18,
  150860. 30,
  150861. 17,
  150862. 31,
  150863. 16,
  150864. 32,
  150865. 15,
  150866. 33,
  150867. 14,
  150868. 34,
  150869. 13,
  150870. 35,
  150871. 12,
  150872. 36,
  150873. 11,
  150874. 37,
  150875. 10,
  150876. 38,
  150877. 9,
  150878. 39,
  150879. 8,
  150880. 40,
  150881. 7,
  150882. 41,
  150883. 6,
  150884. 42,
  150885. 5,
  150886. 43,
  150887. 4,
  150888. 44,
  150889. 3,
  150890. 45,
  150891. 2,
  150892. 46,
  150893. 1,
  150894. 47,
  150895. 0,
  150896. 48,
  150897. };
  150898. static long _vq_lengthlist__44u7__p9_2[] = {
  150899. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  150900. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  150901. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  150902. 8,
  150903. };
  150904. static float _vq_quantthresh__44u7__p9_2[] = {
  150905. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  150906. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  150907. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150908. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150909. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  150910. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  150911. };
  150912. static long _vq_quantmap__44u7__p9_2[] = {
  150913. 47, 45, 43, 41, 39, 37, 35, 33,
  150914. 31, 29, 27, 25, 23, 21, 19, 17,
  150915. 15, 13, 11, 9, 7, 5, 3, 1,
  150916. 0, 2, 4, 6, 8, 10, 12, 14,
  150917. 16, 18, 20, 22, 24, 26, 28, 30,
  150918. 32, 34, 36, 38, 40, 42, 44, 46,
  150919. 48,
  150920. };
  150921. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  150922. _vq_quantthresh__44u7__p9_2,
  150923. _vq_quantmap__44u7__p9_2,
  150924. 49,
  150925. 49
  150926. };
  150927. static static_codebook _44u7__p9_2 = {
  150928. 1, 49,
  150929. _vq_lengthlist__44u7__p9_2,
  150930. 1, -526909440, 1611661312, 6, 0,
  150931. _vq_quantlist__44u7__p9_2,
  150932. NULL,
  150933. &_vq_auxt__44u7__p9_2,
  150934. NULL,
  150935. 0
  150936. };
  150937. static long _huff_lengthlist__44u7__short[] = {
  150938. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  150939. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  150940. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  150941. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  150942. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  150943. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  150944. 6, 8, 5, 9,
  150945. };
  150946. static static_codebook _huff_book__44u7__short = {
  150947. 2, 100,
  150948. _huff_lengthlist__44u7__short,
  150949. 0, 0, 0, 0, 0,
  150950. NULL,
  150951. NULL,
  150952. NULL,
  150953. NULL,
  150954. 0
  150955. };
  150956. static long _huff_lengthlist__44u8__long[] = {
  150957. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  150958. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  150959. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  150960. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  150961. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  150962. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  150963. 10, 8, 8, 9,
  150964. };
  150965. static static_codebook _huff_book__44u8__long = {
  150966. 2, 100,
  150967. _huff_lengthlist__44u8__long,
  150968. 0, 0, 0, 0, 0,
  150969. NULL,
  150970. NULL,
  150971. NULL,
  150972. NULL,
  150973. 0
  150974. };
  150975. static long _huff_lengthlist__44u8__short[] = {
  150976. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  150977. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  150978. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  150979. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  150980. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  150981. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  150982. 10,10,15,17,
  150983. };
  150984. static static_codebook _huff_book__44u8__short = {
  150985. 2, 100,
  150986. _huff_lengthlist__44u8__short,
  150987. 0, 0, 0, 0, 0,
  150988. NULL,
  150989. NULL,
  150990. NULL,
  150991. NULL,
  150992. 0
  150993. };
  150994. static long _vq_quantlist__44u8_p1_0[] = {
  150995. 1,
  150996. 0,
  150997. 2,
  150998. };
  150999. static long _vq_lengthlist__44u8_p1_0[] = {
  151000. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  151001. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  151002. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  151003. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  151004. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  151005. 10,
  151006. };
  151007. static float _vq_quantthresh__44u8_p1_0[] = {
  151008. -0.5, 0.5,
  151009. };
  151010. static long _vq_quantmap__44u8_p1_0[] = {
  151011. 1, 0, 2,
  151012. };
  151013. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  151014. _vq_quantthresh__44u8_p1_0,
  151015. _vq_quantmap__44u8_p1_0,
  151016. 3,
  151017. 3
  151018. };
  151019. static static_codebook _44u8_p1_0 = {
  151020. 4, 81,
  151021. _vq_lengthlist__44u8_p1_0,
  151022. 1, -535822336, 1611661312, 2, 0,
  151023. _vq_quantlist__44u8_p1_0,
  151024. NULL,
  151025. &_vq_auxt__44u8_p1_0,
  151026. NULL,
  151027. 0
  151028. };
  151029. static long _vq_quantlist__44u8_p2_0[] = {
  151030. 2,
  151031. 1,
  151032. 3,
  151033. 0,
  151034. 4,
  151035. };
  151036. static long _vq_lengthlist__44u8_p2_0[] = {
  151037. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  151038. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  151039. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  151040. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  151041. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  151042. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  151043. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  151044. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  151045. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  151046. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  151047. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  151048. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  151049. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  151050. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  151051. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  151052. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  151053. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  151054. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  151055. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  151056. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  151057. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  151058. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  151059. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  151060. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  151061. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  151062. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  151063. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  151064. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  151065. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  151066. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  151067. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  151068. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  151069. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  151070. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  151071. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  151072. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  151073. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  151074. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  151075. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  151076. 14,
  151077. };
  151078. static float _vq_quantthresh__44u8_p2_0[] = {
  151079. -1.5, -0.5, 0.5, 1.5,
  151080. };
  151081. static long _vq_quantmap__44u8_p2_0[] = {
  151082. 3, 1, 0, 2, 4,
  151083. };
  151084. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  151085. _vq_quantthresh__44u8_p2_0,
  151086. _vq_quantmap__44u8_p2_0,
  151087. 5,
  151088. 5
  151089. };
  151090. static static_codebook _44u8_p2_0 = {
  151091. 4, 625,
  151092. _vq_lengthlist__44u8_p2_0,
  151093. 1, -533725184, 1611661312, 3, 0,
  151094. _vq_quantlist__44u8_p2_0,
  151095. NULL,
  151096. &_vq_auxt__44u8_p2_0,
  151097. NULL,
  151098. 0
  151099. };
  151100. static long _vq_quantlist__44u8_p3_0[] = {
  151101. 4,
  151102. 3,
  151103. 5,
  151104. 2,
  151105. 6,
  151106. 1,
  151107. 7,
  151108. 0,
  151109. 8,
  151110. };
  151111. static long _vq_lengthlist__44u8_p3_0[] = {
  151112. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  151113. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  151114. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  151115. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  151116. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  151117. 12,
  151118. };
  151119. static float _vq_quantthresh__44u8_p3_0[] = {
  151120. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  151121. };
  151122. static long _vq_quantmap__44u8_p3_0[] = {
  151123. 7, 5, 3, 1, 0, 2, 4, 6,
  151124. 8,
  151125. };
  151126. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  151127. _vq_quantthresh__44u8_p3_0,
  151128. _vq_quantmap__44u8_p3_0,
  151129. 9,
  151130. 9
  151131. };
  151132. static static_codebook _44u8_p3_0 = {
  151133. 2, 81,
  151134. _vq_lengthlist__44u8_p3_0,
  151135. 1, -531628032, 1611661312, 4, 0,
  151136. _vq_quantlist__44u8_p3_0,
  151137. NULL,
  151138. &_vq_auxt__44u8_p3_0,
  151139. NULL,
  151140. 0
  151141. };
  151142. static long _vq_quantlist__44u8_p4_0[] = {
  151143. 8,
  151144. 7,
  151145. 9,
  151146. 6,
  151147. 10,
  151148. 5,
  151149. 11,
  151150. 4,
  151151. 12,
  151152. 3,
  151153. 13,
  151154. 2,
  151155. 14,
  151156. 1,
  151157. 15,
  151158. 0,
  151159. 16,
  151160. };
  151161. static long _vq_lengthlist__44u8_p4_0[] = {
  151162. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  151163. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  151164. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  151165. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  151166. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  151167. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  151168. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  151169. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  151170. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  151171. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  151172. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  151173. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  151174. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  151175. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  151176. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  151177. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  151178. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  151179. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  151180. 14,
  151181. };
  151182. static float _vq_quantthresh__44u8_p4_0[] = {
  151183. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151184. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151185. };
  151186. static long _vq_quantmap__44u8_p4_0[] = {
  151187. 15, 13, 11, 9, 7, 5, 3, 1,
  151188. 0, 2, 4, 6, 8, 10, 12, 14,
  151189. 16,
  151190. };
  151191. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  151192. _vq_quantthresh__44u8_p4_0,
  151193. _vq_quantmap__44u8_p4_0,
  151194. 17,
  151195. 17
  151196. };
  151197. static static_codebook _44u8_p4_0 = {
  151198. 2, 289,
  151199. _vq_lengthlist__44u8_p4_0,
  151200. 1, -529530880, 1611661312, 5, 0,
  151201. _vq_quantlist__44u8_p4_0,
  151202. NULL,
  151203. &_vq_auxt__44u8_p4_0,
  151204. NULL,
  151205. 0
  151206. };
  151207. static long _vq_quantlist__44u8_p5_0[] = {
  151208. 1,
  151209. 0,
  151210. 2,
  151211. };
  151212. static long _vq_lengthlist__44u8_p5_0[] = {
  151213. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  151214. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  151215. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  151216. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  151217. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  151218. 10,
  151219. };
  151220. static float _vq_quantthresh__44u8_p5_0[] = {
  151221. -5.5, 5.5,
  151222. };
  151223. static long _vq_quantmap__44u8_p5_0[] = {
  151224. 1, 0, 2,
  151225. };
  151226. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  151227. _vq_quantthresh__44u8_p5_0,
  151228. _vq_quantmap__44u8_p5_0,
  151229. 3,
  151230. 3
  151231. };
  151232. static static_codebook _44u8_p5_0 = {
  151233. 4, 81,
  151234. _vq_lengthlist__44u8_p5_0,
  151235. 1, -529137664, 1618345984, 2, 0,
  151236. _vq_quantlist__44u8_p5_0,
  151237. NULL,
  151238. &_vq_auxt__44u8_p5_0,
  151239. NULL,
  151240. 0
  151241. };
  151242. static long _vq_quantlist__44u8_p5_1[] = {
  151243. 5,
  151244. 4,
  151245. 6,
  151246. 3,
  151247. 7,
  151248. 2,
  151249. 8,
  151250. 1,
  151251. 9,
  151252. 0,
  151253. 10,
  151254. };
  151255. static long _vq_lengthlist__44u8_p5_1[] = {
  151256. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  151257. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  151258. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  151259. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  151260. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  151261. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  151262. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  151263. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  151264. };
  151265. static float _vq_quantthresh__44u8_p5_1[] = {
  151266. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151267. 3.5, 4.5,
  151268. };
  151269. static long _vq_quantmap__44u8_p5_1[] = {
  151270. 9, 7, 5, 3, 1, 0, 2, 4,
  151271. 6, 8, 10,
  151272. };
  151273. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  151274. _vq_quantthresh__44u8_p5_1,
  151275. _vq_quantmap__44u8_p5_1,
  151276. 11,
  151277. 11
  151278. };
  151279. static static_codebook _44u8_p5_1 = {
  151280. 2, 121,
  151281. _vq_lengthlist__44u8_p5_1,
  151282. 1, -531365888, 1611661312, 4, 0,
  151283. _vq_quantlist__44u8_p5_1,
  151284. NULL,
  151285. &_vq_auxt__44u8_p5_1,
  151286. NULL,
  151287. 0
  151288. };
  151289. static long _vq_quantlist__44u8_p6_0[] = {
  151290. 6,
  151291. 5,
  151292. 7,
  151293. 4,
  151294. 8,
  151295. 3,
  151296. 9,
  151297. 2,
  151298. 10,
  151299. 1,
  151300. 11,
  151301. 0,
  151302. 12,
  151303. };
  151304. static long _vq_lengthlist__44u8_p6_0[] = {
  151305. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  151306. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  151307. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  151308. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  151309. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  151310. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  151311. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  151312. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  151313. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  151314. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  151315. 11,11,11,11,11,12,11,12,12,
  151316. };
  151317. static float _vq_quantthresh__44u8_p6_0[] = {
  151318. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  151319. 12.5, 17.5, 22.5, 27.5,
  151320. };
  151321. static long _vq_quantmap__44u8_p6_0[] = {
  151322. 11, 9, 7, 5, 3, 1, 0, 2,
  151323. 4, 6, 8, 10, 12,
  151324. };
  151325. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  151326. _vq_quantthresh__44u8_p6_0,
  151327. _vq_quantmap__44u8_p6_0,
  151328. 13,
  151329. 13
  151330. };
  151331. static static_codebook _44u8_p6_0 = {
  151332. 2, 169,
  151333. _vq_lengthlist__44u8_p6_0,
  151334. 1, -526516224, 1616117760, 4, 0,
  151335. _vq_quantlist__44u8_p6_0,
  151336. NULL,
  151337. &_vq_auxt__44u8_p6_0,
  151338. NULL,
  151339. 0
  151340. };
  151341. static long _vq_quantlist__44u8_p6_1[] = {
  151342. 2,
  151343. 1,
  151344. 3,
  151345. 0,
  151346. 4,
  151347. };
  151348. static long _vq_lengthlist__44u8_p6_1[] = {
  151349. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  151350. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  151351. };
  151352. static float _vq_quantthresh__44u8_p6_1[] = {
  151353. -1.5, -0.5, 0.5, 1.5,
  151354. };
  151355. static long _vq_quantmap__44u8_p6_1[] = {
  151356. 3, 1, 0, 2, 4,
  151357. };
  151358. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  151359. _vq_quantthresh__44u8_p6_1,
  151360. _vq_quantmap__44u8_p6_1,
  151361. 5,
  151362. 5
  151363. };
  151364. static static_codebook _44u8_p6_1 = {
  151365. 2, 25,
  151366. _vq_lengthlist__44u8_p6_1,
  151367. 1, -533725184, 1611661312, 3, 0,
  151368. _vq_quantlist__44u8_p6_1,
  151369. NULL,
  151370. &_vq_auxt__44u8_p6_1,
  151371. NULL,
  151372. 0
  151373. };
  151374. static long _vq_quantlist__44u8_p7_0[] = {
  151375. 6,
  151376. 5,
  151377. 7,
  151378. 4,
  151379. 8,
  151380. 3,
  151381. 9,
  151382. 2,
  151383. 10,
  151384. 1,
  151385. 11,
  151386. 0,
  151387. 12,
  151388. };
  151389. static long _vq_lengthlist__44u8_p7_0[] = {
  151390. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  151391. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  151392. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  151393. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  151394. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  151395. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  151396. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  151397. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  151398. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  151399. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  151400. 13,13,14,14,14,15,15,15,16,
  151401. };
  151402. static float _vq_quantthresh__44u8_p7_0[] = {
  151403. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  151404. 27.5, 38.5, 49.5, 60.5,
  151405. };
  151406. static long _vq_quantmap__44u8_p7_0[] = {
  151407. 11, 9, 7, 5, 3, 1, 0, 2,
  151408. 4, 6, 8, 10, 12,
  151409. };
  151410. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  151411. _vq_quantthresh__44u8_p7_0,
  151412. _vq_quantmap__44u8_p7_0,
  151413. 13,
  151414. 13
  151415. };
  151416. static static_codebook _44u8_p7_0 = {
  151417. 2, 169,
  151418. _vq_lengthlist__44u8_p7_0,
  151419. 1, -523206656, 1618345984, 4, 0,
  151420. _vq_quantlist__44u8_p7_0,
  151421. NULL,
  151422. &_vq_auxt__44u8_p7_0,
  151423. NULL,
  151424. 0
  151425. };
  151426. static long _vq_quantlist__44u8_p7_1[] = {
  151427. 5,
  151428. 4,
  151429. 6,
  151430. 3,
  151431. 7,
  151432. 2,
  151433. 8,
  151434. 1,
  151435. 9,
  151436. 0,
  151437. 10,
  151438. };
  151439. static long _vq_lengthlist__44u8_p7_1[] = {
  151440. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  151441. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  151442. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  151443. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  151444. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  151445. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  151446. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  151447. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  151448. };
  151449. static float _vq_quantthresh__44u8_p7_1[] = {
  151450. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151451. 3.5, 4.5,
  151452. };
  151453. static long _vq_quantmap__44u8_p7_1[] = {
  151454. 9, 7, 5, 3, 1, 0, 2, 4,
  151455. 6, 8, 10,
  151456. };
  151457. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  151458. _vq_quantthresh__44u8_p7_1,
  151459. _vq_quantmap__44u8_p7_1,
  151460. 11,
  151461. 11
  151462. };
  151463. static static_codebook _44u8_p7_1 = {
  151464. 2, 121,
  151465. _vq_lengthlist__44u8_p7_1,
  151466. 1, -531365888, 1611661312, 4, 0,
  151467. _vq_quantlist__44u8_p7_1,
  151468. NULL,
  151469. &_vq_auxt__44u8_p7_1,
  151470. NULL,
  151471. 0
  151472. };
  151473. static long _vq_quantlist__44u8_p8_0[] = {
  151474. 7,
  151475. 6,
  151476. 8,
  151477. 5,
  151478. 9,
  151479. 4,
  151480. 10,
  151481. 3,
  151482. 11,
  151483. 2,
  151484. 12,
  151485. 1,
  151486. 13,
  151487. 0,
  151488. 14,
  151489. };
  151490. static long _vq_lengthlist__44u8_p8_0[] = {
  151491. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  151492. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  151493. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  151494. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  151495. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  151496. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  151497. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  151498. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  151499. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  151500. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  151501. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  151502. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  151503. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  151504. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  151505. 17,
  151506. };
  151507. static float _vq_quantthresh__44u8_p8_0[] = {
  151508. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  151509. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  151510. };
  151511. static long _vq_quantmap__44u8_p8_0[] = {
  151512. 13, 11, 9, 7, 5, 3, 1, 0,
  151513. 2, 4, 6, 8, 10, 12, 14,
  151514. };
  151515. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  151516. _vq_quantthresh__44u8_p8_0,
  151517. _vq_quantmap__44u8_p8_0,
  151518. 15,
  151519. 15
  151520. };
  151521. static static_codebook _44u8_p8_0 = {
  151522. 2, 225,
  151523. _vq_lengthlist__44u8_p8_0,
  151524. 1, -520986624, 1620377600, 4, 0,
  151525. _vq_quantlist__44u8_p8_0,
  151526. NULL,
  151527. &_vq_auxt__44u8_p8_0,
  151528. NULL,
  151529. 0
  151530. };
  151531. static long _vq_quantlist__44u8_p8_1[] = {
  151532. 10,
  151533. 9,
  151534. 11,
  151535. 8,
  151536. 12,
  151537. 7,
  151538. 13,
  151539. 6,
  151540. 14,
  151541. 5,
  151542. 15,
  151543. 4,
  151544. 16,
  151545. 3,
  151546. 17,
  151547. 2,
  151548. 18,
  151549. 1,
  151550. 19,
  151551. 0,
  151552. 20,
  151553. };
  151554. static long _vq_lengthlist__44u8_p8_1[] = {
  151555. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  151556. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151557. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  151558. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  151559. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151560. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  151561. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  151562. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  151563. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151564. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151565. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  151566. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  151567. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151568. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151569. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151570. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  151571. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  151572. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  151573. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  151574. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  151575. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151576. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151577. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151578. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  151579. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  151580. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151581. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  151582. 10,10,10,10,10,10,10,10,10,
  151583. };
  151584. static float _vq_quantthresh__44u8_p8_1[] = {
  151585. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  151586. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  151587. 6.5, 7.5, 8.5, 9.5,
  151588. };
  151589. static long _vq_quantmap__44u8_p8_1[] = {
  151590. 19, 17, 15, 13, 11, 9, 7, 5,
  151591. 3, 1, 0, 2, 4, 6, 8, 10,
  151592. 12, 14, 16, 18, 20,
  151593. };
  151594. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  151595. _vq_quantthresh__44u8_p8_1,
  151596. _vq_quantmap__44u8_p8_1,
  151597. 21,
  151598. 21
  151599. };
  151600. static static_codebook _44u8_p8_1 = {
  151601. 2, 441,
  151602. _vq_lengthlist__44u8_p8_1,
  151603. 1, -529268736, 1611661312, 5, 0,
  151604. _vq_quantlist__44u8_p8_1,
  151605. NULL,
  151606. &_vq_auxt__44u8_p8_1,
  151607. NULL,
  151608. 0
  151609. };
  151610. static long _vq_quantlist__44u8_p9_0[] = {
  151611. 4,
  151612. 3,
  151613. 5,
  151614. 2,
  151615. 6,
  151616. 1,
  151617. 7,
  151618. 0,
  151619. 8,
  151620. };
  151621. static long _vq_lengthlist__44u8_p9_0[] = {
  151622. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  151623. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151624. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151625. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151626. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  151627. 8,
  151628. };
  151629. static float _vq_quantthresh__44u8_p9_0[] = {
  151630. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  151631. };
  151632. static long _vq_quantmap__44u8_p9_0[] = {
  151633. 7, 5, 3, 1, 0, 2, 4, 6,
  151634. 8,
  151635. };
  151636. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  151637. _vq_quantthresh__44u8_p9_0,
  151638. _vq_quantmap__44u8_p9_0,
  151639. 9,
  151640. 9
  151641. };
  151642. static static_codebook _44u8_p9_0 = {
  151643. 2, 81,
  151644. _vq_lengthlist__44u8_p9_0,
  151645. 1, -511895552, 1631393792, 4, 0,
  151646. _vq_quantlist__44u8_p9_0,
  151647. NULL,
  151648. &_vq_auxt__44u8_p9_0,
  151649. NULL,
  151650. 0
  151651. };
  151652. static long _vq_quantlist__44u8_p9_1[] = {
  151653. 9,
  151654. 8,
  151655. 10,
  151656. 7,
  151657. 11,
  151658. 6,
  151659. 12,
  151660. 5,
  151661. 13,
  151662. 4,
  151663. 14,
  151664. 3,
  151665. 15,
  151666. 2,
  151667. 16,
  151668. 1,
  151669. 17,
  151670. 0,
  151671. 18,
  151672. };
  151673. static long _vq_lengthlist__44u8_p9_1[] = {
  151674. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  151675. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  151676. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  151677. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  151678. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  151679. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  151680. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  151681. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  151682. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  151683. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  151684. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  151685. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  151686. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  151687. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  151688. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  151689. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  151690. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  151691. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  151692. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  151693. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  151694. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  151695. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  151696. 16,15,16,16,16,16,16,16,16,
  151697. };
  151698. static float _vq_quantthresh__44u8_p9_1[] = {
  151699. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  151700. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  151701. 367.5, 416.5,
  151702. };
  151703. static long _vq_quantmap__44u8_p9_1[] = {
  151704. 17, 15, 13, 11, 9, 7, 5, 3,
  151705. 1, 0, 2, 4, 6, 8, 10, 12,
  151706. 14, 16, 18,
  151707. };
  151708. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  151709. _vq_quantthresh__44u8_p9_1,
  151710. _vq_quantmap__44u8_p9_1,
  151711. 19,
  151712. 19
  151713. };
  151714. static static_codebook _44u8_p9_1 = {
  151715. 2, 361,
  151716. _vq_lengthlist__44u8_p9_1,
  151717. 1, -518287360, 1622704128, 5, 0,
  151718. _vq_quantlist__44u8_p9_1,
  151719. NULL,
  151720. &_vq_auxt__44u8_p9_1,
  151721. NULL,
  151722. 0
  151723. };
  151724. static long _vq_quantlist__44u8_p9_2[] = {
  151725. 24,
  151726. 23,
  151727. 25,
  151728. 22,
  151729. 26,
  151730. 21,
  151731. 27,
  151732. 20,
  151733. 28,
  151734. 19,
  151735. 29,
  151736. 18,
  151737. 30,
  151738. 17,
  151739. 31,
  151740. 16,
  151741. 32,
  151742. 15,
  151743. 33,
  151744. 14,
  151745. 34,
  151746. 13,
  151747. 35,
  151748. 12,
  151749. 36,
  151750. 11,
  151751. 37,
  151752. 10,
  151753. 38,
  151754. 9,
  151755. 39,
  151756. 8,
  151757. 40,
  151758. 7,
  151759. 41,
  151760. 6,
  151761. 42,
  151762. 5,
  151763. 43,
  151764. 4,
  151765. 44,
  151766. 3,
  151767. 45,
  151768. 2,
  151769. 46,
  151770. 1,
  151771. 47,
  151772. 0,
  151773. 48,
  151774. };
  151775. static long _vq_lengthlist__44u8_p9_2[] = {
  151776. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  151777. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151778. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151779. 7,
  151780. };
  151781. static float _vq_quantthresh__44u8_p9_2[] = {
  151782. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  151783. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  151784. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151785. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151786. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  151787. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  151788. };
  151789. static long _vq_quantmap__44u8_p9_2[] = {
  151790. 47, 45, 43, 41, 39, 37, 35, 33,
  151791. 31, 29, 27, 25, 23, 21, 19, 17,
  151792. 15, 13, 11, 9, 7, 5, 3, 1,
  151793. 0, 2, 4, 6, 8, 10, 12, 14,
  151794. 16, 18, 20, 22, 24, 26, 28, 30,
  151795. 32, 34, 36, 38, 40, 42, 44, 46,
  151796. 48,
  151797. };
  151798. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  151799. _vq_quantthresh__44u8_p9_2,
  151800. _vq_quantmap__44u8_p9_2,
  151801. 49,
  151802. 49
  151803. };
  151804. static static_codebook _44u8_p9_2 = {
  151805. 1, 49,
  151806. _vq_lengthlist__44u8_p9_2,
  151807. 1, -526909440, 1611661312, 6, 0,
  151808. _vq_quantlist__44u8_p9_2,
  151809. NULL,
  151810. &_vq_auxt__44u8_p9_2,
  151811. NULL,
  151812. 0
  151813. };
  151814. static long _huff_lengthlist__44u9__long[] = {
  151815. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  151816. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  151817. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  151818. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  151819. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  151820. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  151821. 10, 8, 8, 9,
  151822. };
  151823. static static_codebook _huff_book__44u9__long = {
  151824. 2, 100,
  151825. _huff_lengthlist__44u9__long,
  151826. 0, 0, 0, 0, 0,
  151827. NULL,
  151828. NULL,
  151829. NULL,
  151830. NULL,
  151831. 0
  151832. };
  151833. static long _huff_lengthlist__44u9__short[] = {
  151834. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  151835. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  151836. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  151837. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  151838. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  151839. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  151840. 9, 9,12,15,
  151841. };
  151842. static static_codebook _huff_book__44u9__short = {
  151843. 2, 100,
  151844. _huff_lengthlist__44u9__short,
  151845. 0, 0, 0, 0, 0,
  151846. NULL,
  151847. NULL,
  151848. NULL,
  151849. NULL,
  151850. 0
  151851. };
  151852. static long _vq_quantlist__44u9_p1_0[] = {
  151853. 1,
  151854. 0,
  151855. 2,
  151856. };
  151857. static long _vq_lengthlist__44u9_p1_0[] = {
  151858. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  151859. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  151860. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  151861. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  151862. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  151863. 10,
  151864. };
  151865. static float _vq_quantthresh__44u9_p1_0[] = {
  151866. -0.5, 0.5,
  151867. };
  151868. static long _vq_quantmap__44u9_p1_0[] = {
  151869. 1, 0, 2,
  151870. };
  151871. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  151872. _vq_quantthresh__44u9_p1_0,
  151873. _vq_quantmap__44u9_p1_0,
  151874. 3,
  151875. 3
  151876. };
  151877. static static_codebook _44u9_p1_0 = {
  151878. 4, 81,
  151879. _vq_lengthlist__44u9_p1_0,
  151880. 1, -535822336, 1611661312, 2, 0,
  151881. _vq_quantlist__44u9_p1_0,
  151882. NULL,
  151883. &_vq_auxt__44u9_p1_0,
  151884. NULL,
  151885. 0
  151886. };
  151887. static long _vq_quantlist__44u9_p2_0[] = {
  151888. 2,
  151889. 1,
  151890. 3,
  151891. 0,
  151892. 4,
  151893. };
  151894. static long _vq_lengthlist__44u9_p2_0[] = {
  151895. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  151896. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  151897. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  151898. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  151899. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  151900. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  151901. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  151902. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  151903. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  151904. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  151905. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  151906. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  151907. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  151908. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  151909. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  151910. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  151911. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  151912. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  151913. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  151914. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  151915. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  151916. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  151917. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  151918. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  151919. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  151920. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  151921. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  151922. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  151923. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  151924. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  151925. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  151926. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  151927. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  151928. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  151929. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  151930. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  151931. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  151932. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  151933. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  151934. 14,
  151935. };
  151936. static float _vq_quantthresh__44u9_p2_0[] = {
  151937. -1.5, -0.5, 0.5, 1.5,
  151938. };
  151939. static long _vq_quantmap__44u9_p2_0[] = {
  151940. 3, 1, 0, 2, 4,
  151941. };
  151942. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  151943. _vq_quantthresh__44u9_p2_0,
  151944. _vq_quantmap__44u9_p2_0,
  151945. 5,
  151946. 5
  151947. };
  151948. static static_codebook _44u9_p2_0 = {
  151949. 4, 625,
  151950. _vq_lengthlist__44u9_p2_0,
  151951. 1, -533725184, 1611661312, 3, 0,
  151952. _vq_quantlist__44u9_p2_0,
  151953. NULL,
  151954. &_vq_auxt__44u9_p2_0,
  151955. NULL,
  151956. 0
  151957. };
  151958. static long _vq_quantlist__44u9_p3_0[] = {
  151959. 4,
  151960. 3,
  151961. 5,
  151962. 2,
  151963. 6,
  151964. 1,
  151965. 7,
  151966. 0,
  151967. 8,
  151968. };
  151969. static long _vq_lengthlist__44u9_p3_0[] = {
  151970. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  151971. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  151972. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  151973. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  151974. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  151975. 11,
  151976. };
  151977. static float _vq_quantthresh__44u9_p3_0[] = {
  151978. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  151979. };
  151980. static long _vq_quantmap__44u9_p3_0[] = {
  151981. 7, 5, 3, 1, 0, 2, 4, 6,
  151982. 8,
  151983. };
  151984. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  151985. _vq_quantthresh__44u9_p3_0,
  151986. _vq_quantmap__44u9_p3_0,
  151987. 9,
  151988. 9
  151989. };
  151990. static static_codebook _44u9_p3_0 = {
  151991. 2, 81,
  151992. _vq_lengthlist__44u9_p3_0,
  151993. 1, -531628032, 1611661312, 4, 0,
  151994. _vq_quantlist__44u9_p3_0,
  151995. NULL,
  151996. &_vq_auxt__44u9_p3_0,
  151997. NULL,
  151998. 0
  151999. };
  152000. static long _vq_quantlist__44u9_p4_0[] = {
  152001. 8,
  152002. 7,
  152003. 9,
  152004. 6,
  152005. 10,
  152006. 5,
  152007. 11,
  152008. 4,
  152009. 12,
  152010. 3,
  152011. 13,
  152012. 2,
  152013. 14,
  152014. 1,
  152015. 15,
  152016. 0,
  152017. 16,
  152018. };
  152019. static long _vq_lengthlist__44u9_p4_0[] = {
  152020. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  152021. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  152022. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  152023. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  152024. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  152025. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  152026. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  152027. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  152028. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  152029. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  152030. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  152031. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  152032. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  152033. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  152034. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  152035. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  152036. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  152037. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  152038. 14,
  152039. };
  152040. static float _vq_quantthresh__44u9_p4_0[] = {
  152041. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152042. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152043. };
  152044. static long _vq_quantmap__44u9_p4_0[] = {
  152045. 15, 13, 11, 9, 7, 5, 3, 1,
  152046. 0, 2, 4, 6, 8, 10, 12, 14,
  152047. 16,
  152048. };
  152049. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  152050. _vq_quantthresh__44u9_p4_0,
  152051. _vq_quantmap__44u9_p4_0,
  152052. 17,
  152053. 17
  152054. };
  152055. static static_codebook _44u9_p4_0 = {
  152056. 2, 289,
  152057. _vq_lengthlist__44u9_p4_0,
  152058. 1, -529530880, 1611661312, 5, 0,
  152059. _vq_quantlist__44u9_p4_0,
  152060. NULL,
  152061. &_vq_auxt__44u9_p4_0,
  152062. NULL,
  152063. 0
  152064. };
  152065. static long _vq_quantlist__44u9_p5_0[] = {
  152066. 1,
  152067. 0,
  152068. 2,
  152069. };
  152070. static long _vq_lengthlist__44u9_p5_0[] = {
  152071. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  152072. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  152073. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  152074. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  152075. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  152076. 10,
  152077. };
  152078. static float _vq_quantthresh__44u9_p5_0[] = {
  152079. -5.5, 5.5,
  152080. };
  152081. static long _vq_quantmap__44u9_p5_0[] = {
  152082. 1, 0, 2,
  152083. };
  152084. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  152085. _vq_quantthresh__44u9_p5_0,
  152086. _vq_quantmap__44u9_p5_0,
  152087. 3,
  152088. 3
  152089. };
  152090. static static_codebook _44u9_p5_0 = {
  152091. 4, 81,
  152092. _vq_lengthlist__44u9_p5_0,
  152093. 1, -529137664, 1618345984, 2, 0,
  152094. _vq_quantlist__44u9_p5_0,
  152095. NULL,
  152096. &_vq_auxt__44u9_p5_0,
  152097. NULL,
  152098. 0
  152099. };
  152100. static long _vq_quantlist__44u9_p5_1[] = {
  152101. 5,
  152102. 4,
  152103. 6,
  152104. 3,
  152105. 7,
  152106. 2,
  152107. 8,
  152108. 1,
  152109. 9,
  152110. 0,
  152111. 10,
  152112. };
  152113. static long _vq_lengthlist__44u9_p5_1[] = {
  152114. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  152115. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  152116. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  152117. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  152118. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  152119. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  152120. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  152121. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  152122. };
  152123. static float _vq_quantthresh__44u9_p5_1[] = {
  152124. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  152125. 3.5, 4.5,
  152126. };
  152127. static long _vq_quantmap__44u9_p5_1[] = {
  152128. 9, 7, 5, 3, 1, 0, 2, 4,
  152129. 6, 8, 10,
  152130. };
  152131. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  152132. _vq_quantthresh__44u9_p5_1,
  152133. _vq_quantmap__44u9_p5_1,
  152134. 11,
  152135. 11
  152136. };
  152137. static static_codebook _44u9_p5_1 = {
  152138. 2, 121,
  152139. _vq_lengthlist__44u9_p5_1,
  152140. 1, -531365888, 1611661312, 4, 0,
  152141. _vq_quantlist__44u9_p5_1,
  152142. NULL,
  152143. &_vq_auxt__44u9_p5_1,
  152144. NULL,
  152145. 0
  152146. };
  152147. static long _vq_quantlist__44u9_p6_0[] = {
  152148. 6,
  152149. 5,
  152150. 7,
  152151. 4,
  152152. 8,
  152153. 3,
  152154. 9,
  152155. 2,
  152156. 10,
  152157. 1,
  152158. 11,
  152159. 0,
  152160. 12,
  152161. };
  152162. static long _vq_lengthlist__44u9_p6_0[] = {
  152163. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  152164. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  152165. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152166. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  152167. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  152168. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  152169. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  152170. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  152171. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  152172. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  152173. 10,11,11,11,11,12,11,12,12,
  152174. };
  152175. static float _vq_quantthresh__44u9_p6_0[] = {
  152176. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  152177. 12.5, 17.5, 22.5, 27.5,
  152178. };
  152179. static long _vq_quantmap__44u9_p6_0[] = {
  152180. 11, 9, 7, 5, 3, 1, 0, 2,
  152181. 4, 6, 8, 10, 12,
  152182. };
  152183. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  152184. _vq_quantthresh__44u9_p6_0,
  152185. _vq_quantmap__44u9_p6_0,
  152186. 13,
  152187. 13
  152188. };
  152189. static static_codebook _44u9_p6_0 = {
  152190. 2, 169,
  152191. _vq_lengthlist__44u9_p6_0,
  152192. 1, -526516224, 1616117760, 4, 0,
  152193. _vq_quantlist__44u9_p6_0,
  152194. NULL,
  152195. &_vq_auxt__44u9_p6_0,
  152196. NULL,
  152197. 0
  152198. };
  152199. static long _vq_quantlist__44u9_p6_1[] = {
  152200. 2,
  152201. 1,
  152202. 3,
  152203. 0,
  152204. 4,
  152205. };
  152206. static long _vq_lengthlist__44u9_p6_1[] = {
  152207. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  152208. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  152209. };
  152210. static float _vq_quantthresh__44u9_p6_1[] = {
  152211. -1.5, -0.5, 0.5, 1.5,
  152212. };
  152213. static long _vq_quantmap__44u9_p6_1[] = {
  152214. 3, 1, 0, 2, 4,
  152215. };
  152216. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  152217. _vq_quantthresh__44u9_p6_1,
  152218. _vq_quantmap__44u9_p6_1,
  152219. 5,
  152220. 5
  152221. };
  152222. static static_codebook _44u9_p6_1 = {
  152223. 2, 25,
  152224. _vq_lengthlist__44u9_p6_1,
  152225. 1, -533725184, 1611661312, 3, 0,
  152226. _vq_quantlist__44u9_p6_1,
  152227. NULL,
  152228. &_vq_auxt__44u9_p6_1,
  152229. NULL,
  152230. 0
  152231. };
  152232. static long _vq_quantlist__44u9_p7_0[] = {
  152233. 6,
  152234. 5,
  152235. 7,
  152236. 4,
  152237. 8,
  152238. 3,
  152239. 9,
  152240. 2,
  152241. 10,
  152242. 1,
  152243. 11,
  152244. 0,
  152245. 12,
  152246. };
  152247. static long _vq_lengthlist__44u9_p7_0[] = {
  152248. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  152249. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  152250. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  152251. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  152252. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  152253. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  152254. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  152255. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  152256. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  152257. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  152258. 12,13,13,14,14,14,15,15,15,
  152259. };
  152260. static float _vq_quantthresh__44u9_p7_0[] = {
  152261. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  152262. 27.5, 38.5, 49.5, 60.5,
  152263. };
  152264. static long _vq_quantmap__44u9_p7_0[] = {
  152265. 11, 9, 7, 5, 3, 1, 0, 2,
  152266. 4, 6, 8, 10, 12,
  152267. };
  152268. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  152269. _vq_quantthresh__44u9_p7_0,
  152270. _vq_quantmap__44u9_p7_0,
  152271. 13,
  152272. 13
  152273. };
  152274. static static_codebook _44u9_p7_0 = {
  152275. 2, 169,
  152276. _vq_lengthlist__44u9_p7_0,
  152277. 1, -523206656, 1618345984, 4, 0,
  152278. _vq_quantlist__44u9_p7_0,
  152279. NULL,
  152280. &_vq_auxt__44u9_p7_0,
  152281. NULL,
  152282. 0
  152283. };
  152284. static long _vq_quantlist__44u9_p7_1[] = {
  152285. 5,
  152286. 4,
  152287. 6,
  152288. 3,
  152289. 7,
  152290. 2,
  152291. 8,
  152292. 1,
  152293. 9,
  152294. 0,
  152295. 10,
  152296. };
  152297. static long _vq_lengthlist__44u9_p7_1[] = {
  152298. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  152299. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  152300. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  152301. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152302. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152303. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152304. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  152305. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  152306. };
  152307. static float _vq_quantthresh__44u9_p7_1[] = {
  152308. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  152309. 3.5, 4.5,
  152310. };
  152311. static long _vq_quantmap__44u9_p7_1[] = {
  152312. 9, 7, 5, 3, 1, 0, 2, 4,
  152313. 6, 8, 10,
  152314. };
  152315. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  152316. _vq_quantthresh__44u9_p7_1,
  152317. _vq_quantmap__44u9_p7_1,
  152318. 11,
  152319. 11
  152320. };
  152321. static static_codebook _44u9_p7_1 = {
  152322. 2, 121,
  152323. _vq_lengthlist__44u9_p7_1,
  152324. 1, -531365888, 1611661312, 4, 0,
  152325. _vq_quantlist__44u9_p7_1,
  152326. NULL,
  152327. &_vq_auxt__44u9_p7_1,
  152328. NULL,
  152329. 0
  152330. };
  152331. static long _vq_quantlist__44u9_p8_0[] = {
  152332. 7,
  152333. 6,
  152334. 8,
  152335. 5,
  152336. 9,
  152337. 4,
  152338. 10,
  152339. 3,
  152340. 11,
  152341. 2,
  152342. 12,
  152343. 1,
  152344. 13,
  152345. 0,
  152346. 14,
  152347. };
  152348. static long _vq_lengthlist__44u9_p8_0[] = {
  152349. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  152350. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  152351. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  152352. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  152353. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  152354. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  152355. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  152356. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  152357. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  152358. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  152359. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  152360. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  152361. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  152362. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  152363. 15,
  152364. };
  152365. static float _vq_quantthresh__44u9_p8_0[] = {
  152366. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  152367. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  152368. };
  152369. static long _vq_quantmap__44u9_p8_0[] = {
  152370. 13, 11, 9, 7, 5, 3, 1, 0,
  152371. 2, 4, 6, 8, 10, 12, 14,
  152372. };
  152373. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  152374. _vq_quantthresh__44u9_p8_0,
  152375. _vq_quantmap__44u9_p8_0,
  152376. 15,
  152377. 15
  152378. };
  152379. static static_codebook _44u9_p8_0 = {
  152380. 2, 225,
  152381. _vq_lengthlist__44u9_p8_0,
  152382. 1, -520986624, 1620377600, 4, 0,
  152383. _vq_quantlist__44u9_p8_0,
  152384. NULL,
  152385. &_vq_auxt__44u9_p8_0,
  152386. NULL,
  152387. 0
  152388. };
  152389. static long _vq_quantlist__44u9_p8_1[] = {
  152390. 10,
  152391. 9,
  152392. 11,
  152393. 8,
  152394. 12,
  152395. 7,
  152396. 13,
  152397. 6,
  152398. 14,
  152399. 5,
  152400. 15,
  152401. 4,
  152402. 16,
  152403. 3,
  152404. 17,
  152405. 2,
  152406. 18,
  152407. 1,
  152408. 19,
  152409. 0,
  152410. 20,
  152411. };
  152412. static long _vq_lengthlist__44u9_p8_1[] = {
  152413. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  152414. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152415. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  152416. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  152417. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  152418. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  152419. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  152420. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  152421. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152422. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152423. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  152424. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  152425. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152426. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  152427. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152428. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  152429. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152430. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152431. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  152432. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  152433. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152434. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  152435. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  152436. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  152437. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  152438. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  152439. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152440. 10,10,10,10,10,10,10,10,10,
  152441. };
  152442. static float _vq_quantthresh__44u9_p8_1[] = {
  152443. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  152444. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  152445. 6.5, 7.5, 8.5, 9.5,
  152446. };
  152447. static long _vq_quantmap__44u9_p8_1[] = {
  152448. 19, 17, 15, 13, 11, 9, 7, 5,
  152449. 3, 1, 0, 2, 4, 6, 8, 10,
  152450. 12, 14, 16, 18, 20,
  152451. };
  152452. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  152453. _vq_quantthresh__44u9_p8_1,
  152454. _vq_quantmap__44u9_p8_1,
  152455. 21,
  152456. 21
  152457. };
  152458. static static_codebook _44u9_p8_1 = {
  152459. 2, 441,
  152460. _vq_lengthlist__44u9_p8_1,
  152461. 1, -529268736, 1611661312, 5, 0,
  152462. _vq_quantlist__44u9_p8_1,
  152463. NULL,
  152464. &_vq_auxt__44u9_p8_1,
  152465. NULL,
  152466. 0
  152467. };
  152468. static long _vq_quantlist__44u9_p9_0[] = {
  152469. 7,
  152470. 6,
  152471. 8,
  152472. 5,
  152473. 9,
  152474. 4,
  152475. 10,
  152476. 3,
  152477. 11,
  152478. 2,
  152479. 12,
  152480. 1,
  152481. 13,
  152482. 0,
  152483. 14,
  152484. };
  152485. static long _vq_lengthlist__44u9_p9_0[] = {
  152486. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  152487. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  152488. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152489. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152490. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152491. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152492. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152493. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152494. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152495. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152496. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152497. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152498. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152499. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152500. 10,
  152501. };
  152502. static float _vq_quantthresh__44u9_p9_0[] = {
  152503. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  152504. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  152505. };
  152506. static long _vq_quantmap__44u9_p9_0[] = {
  152507. 13, 11, 9, 7, 5, 3, 1, 0,
  152508. 2, 4, 6, 8, 10, 12, 14,
  152509. };
  152510. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  152511. _vq_quantthresh__44u9_p9_0,
  152512. _vq_quantmap__44u9_p9_0,
  152513. 15,
  152514. 15
  152515. };
  152516. static static_codebook _44u9_p9_0 = {
  152517. 2, 225,
  152518. _vq_lengthlist__44u9_p9_0,
  152519. 1, -510036736, 1631393792, 4, 0,
  152520. _vq_quantlist__44u9_p9_0,
  152521. NULL,
  152522. &_vq_auxt__44u9_p9_0,
  152523. NULL,
  152524. 0
  152525. };
  152526. static long _vq_quantlist__44u9_p9_1[] = {
  152527. 9,
  152528. 8,
  152529. 10,
  152530. 7,
  152531. 11,
  152532. 6,
  152533. 12,
  152534. 5,
  152535. 13,
  152536. 4,
  152537. 14,
  152538. 3,
  152539. 15,
  152540. 2,
  152541. 16,
  152542. 1,
  152543. 17,
  152544. 0,
  152545. 18,
  152546. };
  152547. static long _vq_lengthlist__44u9_p9_1[] = {
  152548. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  152549. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  152550. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  152551. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  152552. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  152553. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  152554. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  152555. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  152556. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  152557. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  152558. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  152559. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  152560. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  152561. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  152562. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  152563. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  152564. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  152565. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  152566. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  152567. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  152568. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  152569. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  152570. 17,17,15,17,15,17,16,16,17,
  152571. };
  152572. static float _vq_quantthresh__44u9_p9_1[] = {
  152573. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  152574. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  152575. 367.5, 416.5,
  152576. };
  152577. static long _vq_quantmap__44u9_p9_1[] = {
  152578. 17, 15, 13, 11, 9, 7, 5, 3,
  152579. 1, 0, 2, 4, 6, 8, 10, 12,
  152580. 14, 16, 18,
  152581. };
  152582. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  152583. _vq_quantthresh__44u9_p9_1,
  152584. _vq_quantmap__44u9_p9_1,
  152585. 19,
  152586. 19
  152587. };
  152588. static static_codebook _44u9_p9_1 = {
  152589. 2, 361,
  152590. _vq_lengthlist__44u9_p9_1,
  152591. 1, -518287360, 1622704128, 5, 0,
  152592. _vq_quantlist__44u9_p9_1,
  152593. NULL,
  152594. &_vq_auxt__44u9_p9_1,
  152595. NULL,
  152596. 0
  152597. };
  152598. static long _vq_quantlist__44u9_p9_2[] = {
  152599. 24,
  152600. 23,
  152601. 25,
  152602. 22,
  152603. 26,
  152604. 21,
  152605. 27,
  152606. 20,
  152607. 28,
  152608. 19,
  152609. 29,
  152610. 18,
  152611. 30,
  152612. 17,
  152613. 31,
  152614. 16,
  152615. 32,
  152616. 15,
  152617. 33,
  152618. 14,
  152619. 34,
  152620. 13,
  152621. 35,
  152622. 12,
  152623. 36,
  152624. 11,
  152625. 37,
  152626. 10,
  152627. 38,
  152628. 9,
  152629. 39,
  152630. 8,
  152631. 40,
  152632. 7,
  152633. 41,
  152634. 6,
  152635. 42,
  152636. 5,
  152637. 43,
  152638. 4,
  152639. 44,
  152640. 3,
  152641. 45,
  152642. 2,
  152643. 46,
  152644. 1,
  152645. 47,
  152646. 0,
  152647. 48,
  152648. };
  152649. static long _vq_lengthlist__44u9_p9_2[] = {
  152650. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  152651. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152652. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152653. 7,
  152654. };
  152655. static float _vq_quantthresh__44u9_p9_2[] = {
  152656. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  152657. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  152658. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152659. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152660. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  152661. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  152662. };
  152663. static long _vq_quantmap__44u9_p9_2[] = {
  152664. 47, 45, 43, 41, 39, 37, 35, 33,
  152665. 31, 29, 27, 25, 23, 21, 19, 17,
  152666. 15, 13, 11, 9, 7, 5, 3, 1,
  152667. 0, 2, 4, 6, 8, 10, 12, 14,
  152668. 16, 18, 20, 22, 24, 26, 28, 30,
  152669. 32, 34, 36, 38, 40, 42, 44, 46,
  152670. 48,
  152671. };
  152672. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  152673. _vq_quantthresh__44u9_p9_2,
  152674. _vq_quantmap__44u9_p9_2,
  152675. 49,
  152676. 49
  152677. };
  152678. static static_codebook _44u9_p9_2 = {
  152679. 1, 49,
  152680. _vq_lengthlist__44u9_p9_2,
  152681. 1, -526909440, 1611661312, 6, 0,
  152682. _vq_quantlist__44u9_p9_2,
  152683. NULL,
  152684. &_vq_auxt__44u9_p9_2,
  152685. NULL,
  152686. 0
  152687. };
  152688. static long _huff_lengthlist__44un1__long[] = {
  152689. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  152690. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  152691. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  152692. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  152693. };
  152694. static static_codebook _huff_book__44un1__long = {
  152695. 2, 64,
  152696. _huff_lengthlist__44un1__long,
  152697. 0, 0, 0, 0, 0,
  152698. NULL,
  152699. NULL,
  152700. NULL,
  152701. NULL,
  152702. 0
  152703. };
  152704. static long _vq_quantlist__44un1__p1_0[] = {
  152705. 1,
  152706. 0,
  152707. 2,
  152708. };
  152709. static long _vq_lengthlist__44un1__p1_0[] = {
  152710. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  152711. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  152712. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  152713. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  152714. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  152715. 12,
  152716. };
  152717. static float _vq_quantthresh__44un1__p1_0[] = {
  152718. -0.5, 0.5,
  152719. };
  152720. static long _vq_quantmap__44un1__p1_0[] = {
  152721. 1, 0, 2,
  152722. };
  152723. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  152724. _vq_quantthresh__44un1__p1_0,
  152725. _vq_quantmap__44un1__p1_0,
  152726. 3,
  152727. 3
  152728. };
  152729. static static_codebook _44un1__p1_0 = {
  152730. 4, 81,
  152731. _vq_lengthlist__44un1__p1_0,
  152732. 1, -535822336, 1611661312, 2, 0,
  152733. _vq_quantlist__44un1__p1_0,
  152734. NULL,
  152735. &_vq_auxt__44un1__p1_0,
  152736. NULL,
  152737. 0
  152738. };
  152739. static long _vq_quantlist__44un1__p2_0[] = {
  152740. 1,
  152741. 0,
  152742. 2,
  152743. };
  152744. static long _vq_lengthlist__44un1__p2_0[] = {
  152745. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  152746. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  152747. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  152748. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  152749. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  152750. 8,
  152751. };
  152752. static float _vq_quantthresh__44un1__p2_0[] = {
  152753. -0.5, 0.5,
  152754. };
  152755. static long _vq_quantmap__44un1__p2_0[] = {
  152756. 1, 0, 2,
  152757. };
  152758. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  152759. _vq_quantthresh__44un1__p2_0,
  152760. _vq_quantmap__44un1__p2_0,
  152761. 3,
  152762. 3
  152763. };
  152764. static static_codebook _44un1__p2_0 = {
  152765. 4, 81,
  152766. _vq_lengthlist__44un1__p2_0,
  152767. 1, -535822336, 1611661312, 2, 0,
  152768. _vq_quantlist__44un1__p2_0,
  152769. NULL,
  152770. &_vq_auxt__44un1__p2_0,
  152771. NULL,
  152772. 0
  152773. };
  152774. static long _vq_quantlist__44un1__p3_0[] = {
  152775. 2,
  152776. 1,
  152777. 3,
  152778. 0,
  152779. 4,
  152780. };
  152781. static long _vq_lengthlist__44un1__p3_0[] = {
  152782. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  152783. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  152784. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  152785. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  152786. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  152787. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  152788. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  152789. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  152790. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  152791. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  152792. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  152793. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  152794. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  152795. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  152796. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  152797. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  152798. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  152799. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  152800. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  152801. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  152802. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  152803. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  152804. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  152805. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  152806. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  152807. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  152808. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  152809. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  152810. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  152811. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  152812. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  152813. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  152814. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  152815. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  152816. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  152817. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  152818. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  152819. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  152820. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  152821. 17,
  152822. };
  152823. static float _vq_quantthresh__44un1__p3_0[] = {
  152824. -1.5, -0.5, 0.5, 1.5,
  152825. };
  152826. static long _vq_quantmap__44un1__p3_0[] = {
  152827. 3, 1, 0, 2, 4,
  152828. };
  152829. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  152830. _vq_quantthresh__44un1__p3_0,
  152831. _vq_quantmap__44un1__p3_0,
  152832. 5,
  152833. 5
  152834. };
  152835. static static_codebook _44un1__p3_0 = {
  152836. 4, 625,
  152837. _vq_lengthlist__44un1__p3_0,
  152838. 1, -533725184, 1611661312, 3, 0,
  152839. _vq_quantlist__44un1__p3_0,
  152840. NULL,
  152841. &_vq_auxt__44un1__p3_0,
  152842. NULL,
  152843. 0
  152844. };
  152845. static long _vq_quantlist__44un1__p4_0[] = {
  152846. 2,
  152847. 1,
  152848. 3,
  152849. 0,
  152850. 4,
  152851. };
  152852. static long _vq_lengthlist__44un1__p4_0[] = {
  152853. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  152854. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  152855. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  152856. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  152857. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  152858. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  152859. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  152860. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  152861. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  152862. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  152863. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  152864. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  152865. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  152866. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  152867. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  152868. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  152869. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  152870. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  152871. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  152872. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  152873. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  152874. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  152875. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  152876. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  152877. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  152878. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  152879. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  152880. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  152881. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  152882. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  152883. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  152884. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  152885. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  152886. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  152887. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  152888. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  152889. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  152890. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  152891. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  152892. 12,
  152893. };
  152894. static float _vq_quantthresh__44un1__p4_0[] = {
  152895. -1.5, -0.5, 0.5, 1.5,
  152896. };
  152897. static long _vq_quantmap__44un1__p4_0[] = {
  152898. 3, 1, 0, 2, 4,
  152899. };
  152900. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  152901. _vq_quantthresh__44un1__p4_0,
  152902. _vq_quantmap__44un1__p4_0,
  152903. 5,
  152904. 5
  152905. };
  152906. static static_codebook _44un1__p4_0 = {
  152907. 4, 625,
  152908. _vq_lengthlist__44un1__p4_0,
  152909. 1, -533725184, 1611661312, 3, 0,
  152910. _vq_quantlist__44un1__p4_0,
  152911. NULL,
  152912. &_vq_auxt__44un1__p4_0,
  152913. NULL,
  152914. 0
  152915. };
  152916. static long _vq_quantlist__44un1__p5_0[] = {
  152917. 4,
  152918. 3,
  152919. 5,
  152920. 2,
  152921. 6,
  152922. 1,
  152923. 7,
  152924. 0,
  152925. 8,
  152926. };
  152927. static long _vq_lengthlist__44un1__p5_0[] = {
  152928. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  152929. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  152930. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  152931. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  152932. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  152933. 12,
  152934. };
  152935. static float _vq_quantthresh__44un1__p5_0[] = {
  152936. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  152937. };
  152938. static long _vq_quantmap__44un1__p5_0[] = {
  152939. 7, 5, 3, 1, 0, 2, 4, 6,
  152940. 8,
  152941. };
  152942. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  152943. _vq_quantthresh__44un1__p5_0,
  152944. _vq_quantmap__44un1__p5_0,
  152945. 9,
  152946. 9
  152947. };
  152948. static static_codebook _44un1__p5_0 = {
  152949. 2, 81,
  152950. _vq_lengthlist__44un1__p5_0,
  152951. 1, -531628032, 1611661312, 4, 0,
  152952. _vq_quantlist__44un1__p5_0,
  152953. NULL,
  152954. &_vq_auxt__44un1__p5_0,
  152955. NULL,
  152956. 0
  152957. };
  152958. static long _vq_quantlist__44un1__p6_0[] = {
  152959. 6,
  152960. 5,
  152961. 7,
  152962. 4,
  152963. 8,
  152964. 3,
  152965. 9,
  152966. 2,
  152967. 10,
  152968. 1,
  152969. 11,
  152970. 0,
  152971. 12,
  152972. };
  152973. static long _vq_lengthlist__44un1__p6_0[] = {
  152974. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  152975. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  152976. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  152977. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  152978. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  152979. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  152980. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  152981. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  152982. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  152983. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  152984. 16, 0,15,18,18, 0,16, 0, 0,
  152985. };
  152986. static float _vq_quantthresh__44un1__p6_0[] = {
  152987. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  152988. 12.5, 17.5, 22.5, 27.5,
  152989. };
  152990. static long _vq_quantmap__44un1__p6_0[] = {
  152991. 11, 9, 7, 5, 3, 1, 0, 2,
  152992. 4, 6, 8, 10, 12,
  152993. };
  152994. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  152995. _vq_quantthresh__44un1__p6_0,
  152996. _vq_quantmap__44un1__p6_0,
  152997. 13,
  152998. 13
  152999. };
  153000. static static_codebook _44un1__p6_0 = {
  153001. 2, 169,
  153002. _vq_lengthlist__44un1__p6_0,
  153003. 1, -526516224, 1616117760, 4, 0,
  153004. _vq_quantlist__44un1__p6_0,
  153005. NULL,
  153006. &_vq_auxt__44un1__p6_0,
  153007. NULL,
  153008. 0
  153009. };
  153010. static long _vq_quantlist__44un1__p6_1[] = {
  153011. 2,
  153012. 1,
  153013. 3,
  153014. 0,
  153015. 4,
  153016. };
  153017. static long _vq_lengthlist__44un1__p6_1[] = {
  153018. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  153019. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  153020. };
  153021. static float _vq_quantthresh__44un1__p6_1[] = {
  153022. -1.5, -0.5, 0.5, 1.5,
  153023. };
  153024. static long _vq_quantmap__44un1__p6_1[] = {
  153025. 3, 1, 0, 2, 4,
  153026. };
  153027. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  153028. _vq_quantthresh__44un1__p6_1,
  153029. _vq_quantmap__44un1__p6_1,
  153030. 5,
  153031. 5
  153032. };
  153033. static static_codebook _44un1__p6_1 = {
  153034. 2, 25,
  153035. _vq_lengthlist__44un1__p6_1,
  153036. 1, -533725184, 1611661312, 3, 0,
  153037. _vq_quantlist__44un1__p6_1,
  153038. NULL,
  153039. &_vq_auxt__44un1__p6_1,
  153040. NULL,
  153041. 0
  153042. };
  153043. static long _vq_quantlist__44un1__p7_0[] = {
  153044. 2,
  153045. 1,
  153046. 3,
  153047. 0,
  153048. 4,
  153049. };
  153050. static long _vq_lengthlist__44un1__p7_0[] = {
  153051. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  153052. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  153053. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153054. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153055. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153056. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153057. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153058. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  153059. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153060. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153061. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  153062. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153063. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153064. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153065. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153066. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  153067. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153068. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  153069. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153070. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153071. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153072. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153073. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153074. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153075. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153076. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153077. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153078. 11,11,11,11,11,11,11,11,11,11,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,11,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,11,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. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153088. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153089. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153090. 10,
  153091. };
  153092. static float _vq_quantthresh__44un1__p7_0[] = {
  153093. -253.5, -84.5, 84.5, 253.5,
  153094. };
  153095. static long _vq_quantmap__44un1__p7_0[] = {
  153096. 3, 1, 0, 2, 4,
  153097. };
  153098. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  153099. _vq_quantthresh__44un1__p7_0,
  153100. _vq_quantmap__44un1__p7_0,
  153101. 5,
  153102. 5
  153103. };
  153104. static static_codebook _44un1__p7_0 = {
  153105. 4, 625,
  153106. _vq_lengthlist__44un1__p7_0,
  153107. 1, -518709248, 1626677248, 3, 0,
  153108. _vq_quantlist__44un1__p7_0,
  153109. NULL,
  153110. &_vq_auxt__44un1__p7_0,
  153111. NULL,
  153112. 0
  153113. };
  153114. static long _vq_quantlist__44un1__p7_1[] = {
  153115. 6,
  153116. 5,
  153117. 7,
  153118. 4,
  153119. 8,
  153120. 3,
  153121. 9,
  153122. 2,
  153123. 10,
  153124. 1,
  153125. 11,
  153126. 0,
  153127. 12,
  153128. };
  153129. static long _vq_lengthlist__44un1__p7_1[] = {
  153130. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  153131. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  153132. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  153133. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  153134. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  153135. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  153136. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  153137. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  153138. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  153139. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  153140. 12,13,13,12,13,13,14,14,14,
  153141. };
  153142. static float _vq_quantthresh__44un1__p7_1[] = {
  153143. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  153144. 32.5, 45.5, 58.5, 71.5,
  153145. };
  153146. static long _vq_quantmap__44un1__p7_1[] = {
  153147. 11, 9, 7, 5, 3, 1, 0, 2,
  153148. 4, 6, 8, 10, 12,
  153149. };
  153150. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  153151. _vq_quantthresh__44un1__p7_1,
  153152. _vq_quantmap__44un1__p7_1,
  153153. 13,
  153154. 13
  153155. };
  153156. static static_codebook _44un1__p7_1 = {
  153157. 2, 169,
  153158. _vq_lengthlist__44un1__p7_1,
  153159. 1, -523010048, 1618608128, 4, 0,
  153160. _vq_quantlist__44un1__p7_1,
  153161. NULL,
  153162. &_vq_auxt__44un1__p7_1,
  153163. NULL,
  153164. 0
  153165. };
  153166. static long _vq_quantlist__44un1__p7_2[] = {
  153167. 6,
  153168. 5,
  153169. 7,
  153170. 4,
  153171. 8,
  153172. 3,
  153173. 9,
  153174. 2,
  153175. 10,
  153176. 1,
  153177. 11,
  153178. 0,
  153179. 12,
  153180. };
  153181. static long _vq_lengthlist__44un1__p7_2[] = {
  153182. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  153183. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  153184. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  153185. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  153186. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  153187. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  153188. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  153189. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  153190. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  153191. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  153192. 9, 9, 9,10,10,10,10,10,10,
  153193. };
  153194. static float _vq_quantthresh__44un1__p7_2[] = {
  153195. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  153196. 2.5, 3.5, 4.5, 5.5,
  153197. };
  153198. static long _vq_quantmap__44un1__p7_2[] = {
  153199. 11, 9, 7, 5, 3, 1, 0, 2,
  153200. 4, 6, 8, 10, 12,
  153201. };
  153202. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  153203. _vq_quantthresh__44un1__p7_2,
  153204. _vq_quantmap__44un1__p7_2,
  153205. 13,
  153206. 13
  153207. };
  153208. static static_codebook _44un1__p7_2 = {
  153209. 2, 169,
  153210. _vq_lengthlist__44un1__p7_2,
  153211. 1, -531103744, 1611661312, 4, 0,
  153212. _vq_quantlist__44un1__p7_2,
  153213. NULL,
  153214. &_vq_auxt__44un1__p7_2,
  153215. NULL,
  153216. 0
  153217. };
  153218. static long _huff_lengthlist__44un1__short[] = {
  153219. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  153220. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  153221. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  153222. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  153223. };
  153224. static static_codebook _huff_book__44un1__short = {
  153225. 2, 64,
  153226. _huff_lengthlist__44un1__short,
  153227. 0, 0, 0, 0, 0,
  153228. NULL,
  153229. NULL,
  153230. NULL,
  153231. NULL,
  153232. 0
  153233. };
  153234. /*** End of inlined file: res_books_uncoupled.h ***/
  153235. /***** residue backends *********************************************/
  153236. static vorbis_info_residue0 _residue_44_low_un={
  153237. 0,-1, -1, 8,-1,
  153238. {0},
  153239. {-1},
  153240. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  153241. { -1, 25, -1, 45, -1, -1, -1}
  153242. };
  153243. static vorbis_info_residue0 _residue_44_mid_un={
  153244. 0,-1, -1, 10,-1,
  153245. /* 0 1 2 3 4 5 6 7 8 9 */
  153246. {0},
  153247. {-1},
  153248. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  153249. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  153250. };
  153251. static vorbis_info_residue0 _residue_44_hi_un={
  153252. 0,-1, -1, 10,-1,
  153253. /* 0 1 2 3 4 5 6 7 8 9 */
  153254. {0},
  153255. {-1},
  153256. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  153257. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  153258. };
  153259. /* mapping conventions:
  153260. only one submap (this would change for efficient 5.1 support for example)*/
  153261. /* Four psychoacoustic profiles are used, one for each blocktype */
  153262. static vorbis_info_mapping0 _map_nominal_u[2]={
  153263. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  153264. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  153265. };
  153266. static static_bookblock _resbook_44u_n1={
  153267. {
  153268. {0},
  153269. {0,0,&_44un1__p1_0},
  153270. {0,0,&_44un1__p2_0},
  153271. {0,0,&_44un1__p3_0},
  153272. {0,0,&_44un1__p4_0},
  153273. {0,0,&_44un1__p5_0},
  153274. {&_44un1__p6_0,&_44un1__p6_1},
  153275. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  153276. }
  153277. };
  153278. static static_bookblock _resbook_44u_0={
  153279. {
  153280. {0},
  153281. {0,0,&_44u0__p1_0},
  153282. {0,0,&_44u0__p2_0},
  153283. {0,0,&_44u0__p3_0},
  153284. {0,0,&_44u0__p4_0},
  153285. {0,0,&_44u0__p5_0},
  153286. {&_44u0__p6_0,&_44u0__p6_1},
  153287. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  153288. }
  153289. };
  153290. static static_bookblock _resbook_44u_1={
  153291. {
  153292. {0},
  153293. {0,0,&_44u1__p1_0},
  153294. {0,0,&_44u1__p2_0},
  153295. {0,0,&_44u1__p3_0},
  153296. {0,0,&_44u1__p4_0},
  153297. {0,0,&_44u1__p5_0},
  153298. {&_44u1__p6_0,&_44u1__p6_1},
  153299. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  153300. }
  153301. };
  153302. static static_bookblock _resbook_44u_2={
  153303. {
  153304. {0},
  153305. {0,0,&_44u2__p1_0},
  153306. {0,0,&_44u2__p2_0},
  153307. {0,0,&_44u2__p3_0},
  153308. {0,0,&_44u2__p4_0},
  153309. {0,0,&_44u2__p5_0},
  153310. {&_44u2__p6_0,&_44u2__p6_1},
  153311. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  153312. }
  153313. };
  153314. static static_bookblock _resbook_44u_3={
  153315. {
  153316. {0},
  153317. {0,0,&_44u3__p1_0},
  153318. {0,0,&_44u3__p2_0},
  153319. {0,0,&_44u3__p3_0},
  153320. {0,0,&_44u3__p4_0},
  153321. {0,0,&_44u3__p5_0},
  153322. {&_44u3__p6_0,&_44u3__p6_1},
  153323. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  153324. }
  153325. };
  153326. static static_bookblock _resbook_44u_4={
  153327. {
  153328. {0},
  153329. {0,0,&_44u4__p1_0},
  153330. {0,0,&_44u4__p2_0},
  153331. {0,0,&_44u4__p3_0},
  153332. {0,0,&_44u4__p4_0},
  153333. {0,0,&_44u4__p5_0},
  153334. {&_44u4__p6_0,&_44u4__p6_1},
  153335. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  153336. }
  153337. };
  153338. static static_bookblock _resbook_44u_5={
  153339. {
  153340. {0},
  153341. {0,0,&_44u5__p1_0},
  153342. {0,0,&_44u5__p2_0},
  153343. {0,0,&_44u5__p3_0},
  153344. {0,0,&_44u5__p4_0},
  153345. {0,0,&_44u5__p5_0},
  153346. {0,0,&_44u5__p6_0},
  153347. {&_44u5__p7_0,&_44u5__p7_1},
  153348. {&_44u5__p8_0,&_44u5__p8_1},
  153349. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  153350. }
  153351. };
  153352. static static_bookblock _resbook_44u_6={
  153353. {
  153354. {0},
  153355. {0,0,&_44u6__p1_0},
  153356. {0,0,&_44u6__p2_0},
  153357. {0,0,&_44u6__p3_0},
  153358. {0,0,&_44u6__p4_0},
  153359. {0,0,&_44u6__p5_0},
  153360. {0,0,&_44u6__p6_0},
  153361. {&_44u6__p7_0,&_44u6__p7_1},
  153362. {&_44u6__p8_0,&_44u6__p8_1},
  153363. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  153364. }
  153365. };
  153366. static static_bookblock _resbook_44u_7={
  153367. {
  153368. {0},
  153369. {0,0,&_44u7__p1_0},
  153370. {0,0,&_44u7__p2_0},
  153371. {0,0,&_44u7__p3_0},
  153372. {0,0,&_44u7__p4_0},
  153373. {0,0,&_44u7__p5_0},
  153374. {0,0,&_44u7__p6_0},
  153375. {&_44u7__p7_0,&_44u7__p7_1},
  153376. {&_44u7__p8_0,&_44u7__p8_1},
  153377. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  153378. }
  153379. };
  153380. static static_bookblock _resbook_44u_8={
  153381. {
  153382. {0},
  153383. {0,0,&_44u8_p1_0},
  153384. {0,0,&_44u8_p2_0},
  153385. {0,0,&_44u8_p3_0},
  153386. {0,0,&_44u8_p4_0},
  153387. {&_44u8_p5_0,&_44u8_p5_1},
  153388. {&_44u8_p6_0,&_44u8_p6_1},
  153389. {&_44u8_p7_0,&_44u8_p7_1},
  153390. {&_44u8_p8_0,&_44u8_p8_1},
  153391. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  153392. }
  153393. };
  153394. static static_bookblock _resbook_44u_9={
  153395. {
  153396. {0},
  153397. {0,0,&_44u9_p1_0},
  153398. {0,0,&_44u9_p2_0},
  153399. {0,0,&_44u9_p3_0},
  153400. {0,0,&_44u9_p4_0},
  153401. {&_44u9_p5_0,&_44u9_p5_1},
  153402. {&_44u9_p6_0,&_44u9_p6_1},
  153403. {&_44u9_p7_0,&_44u9_p7_1},
  153404. {&_44u9_p8_0,&_44u9_p8_1},
  153405. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  153406. }
  153407. };
  153408. static vorbis_residue_template _res_44u_n1[]={
  153409. {1,0, &_residue_44_low_un,
  153410. &_huff_book__44un1__short,&_huff_book__44un1__short,
  153411. &_resbook_44u_n1,&_resbook_44u_n1},
  153412. {1,0, &_residue_44_low_un,
  153413. &_huff_book__44un1__long,&_huff_book__44un1__long,
  153414. &_resbook_44u_n1,&_resbook_44u_n1}
  153415. };
  153416. static vorbis_residue_template _res_44u_0[]={
  153417. {1,0, &_residue_44_low_un,
  153418. &_huff_book__44u0__short,&_huff_book__44u0__short,
  153419. &_resbook_44u_0,&_resbook_44u_0},
  153420. {1,0, &_residue_44_low_un,
  153421. &_huff_book__44u0__long,&_huff_book__44u0__long,
  153422. &_resbook_44u_0,&_resbook_44u_0}
  153423. };
  153424. static vorbis_residue_template _res_44u_1[]={
  153425. {1,0, &_residue_44_low_un,
  153426. &_huff_book__44u1__short,&_huff_book__44u1__short,
  153427. &_resbook_44u_1,&_resbook_44u_1},
  153428. {1,0, &_residue_44_low_un,
  153429. &_huff_book__44u1__long,&_huff_book__44u1__long,
  153430. &_resbook_44u_1,&_resbook_44u_1}
  153431. };
  153432. static vorbis_residue_template _res_44u_2[]={
  153433. {1,0, &_residue_44_low_un,
  153434. &_huff_book__44u2__short,&_huff_book__44u2__short,
  153435. &_resbook_44u_2,&_resbook_44u_2},
  153436. {1,0, &_residue_44_low_un,
  153437. &_huff_book__44u2__long,&_huff_book__44u2__long,
  153438. &_resbook_44u_2,&_resbook_44u_2}
  153439. };
  153440. static vorbis_residue_template _res_44u_3[]={
  153441. {1,0, &_residue_44_low_un,
  153442. &_huff_book__44u3__short,&_huff_book__44u3__short,
  153443. &_resbook_44u_3,&_resbook_44u_3},
  153444. {1,0, &_residue_44_low_un,
  153445. &_huff_book__44u3__long,&_huff_book__44u3__long,
  153446. &_resbook_44u_3,&_resbook_44u_3}
  153447. };
  153448. static vorbis_residue_template _res_44u_4[]={
  153449. {1,0, &_residue_44_low_un,
  153450. &_huff_book__44u4__short,&_huff_book__44u4__short,
  153451. &_resbook_44u_4,&_resbook_44u_4},
  153452. {1,0, &_residue_44_low_un,
  153453. &_huff_book__44u4__long,&_huff_book__44u4__long,
  153454. &_resbook_44u_4,&_resbook_44u_4}
  153455. };
  153456. static vorbis_residue_template _res_44u_5[]={
  153457. {1,0, &_residue_44_mid_un,
  153458. &_huff_book__44u5__short,&_huff_book__44u5__short,
  153459. &_resbook_44u_5,&_resbook_44u_5},
  153460. {1,0, &_residue_44_mid_un,
  153461. &_huff_book__44u5__long,&_huff_book__44u5__long,
  153462. &_resbook_44u_5,&_resbook_44u_5}
  153463. };
  153464. static vorbis_residue_template _res_44u_6[]={
  153465. {1,0, &_residue_44_mid_un,
  153466. &_huff_book__44u6__short,&_huff_book__44u6__short,
  153467. &_resbook_44u_6,&_resbook_44u_6},
  153468. {1,0, &_residue_44_mid_un,
  153469. &_huff_book__44u6__long,&_huff_book__44u6__long,
  153470. &_resbook_44u_6,&_resbook_44u_6}
  153471. };
  153472. static vorbis_residue_template _res_44u_7[]={
  153473. {1,0, &_residue_44_mid_un,
  153474. &_huff_book__44u7__short,&_huff_book__44u7__short,
  153475. &_resbook_44u_7,&_resbook_44u_7},
  153476. {1,0, &_residue_44_mid_un,
  153477. &_huff_book__44u7__long,&_huff_book__44u7__long,
  153478. &_resbook_44u_7,&_resbook_44u_7}
  153479. };
  153480. static vorbis_residue_template _res_44u_8[]={
  153481. {1,0, &_residue_44_hi_un,
  153482. &_huff_book__44u8__short,&_huff_book__44u8__short,
  153483. &_resbook_44u_8,&_resbook_44u_8},
  153484. {1,0, &_residue_44_hi_un,
  153485. &_huff_book__44u8__long,&_huff_book__44u8__long,
  153486. &_resbook_44u_8,&_resbook_44u_8}
  153487. };
  153488. static vorbis_residue_template _res_44u_9[]={
  153489. {1,0, &_residue_44_hi_un,
  153490. &_huff_book__44u9__short,&_huff_book__44u9__short,
  153491. &_resbook_44u_9,&_resbook_44u_9},
  153492. {1,0, &_residue_44_hi_un,
  153493. &_huff_book__44u9__long,&_huff_book__44u9__long,
  153494. &_resbook_44u_9,&_resbook_44u_9}
  153495. };
  153496. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  153497. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  153498. { _map_nominal_u, _res_44u_0 }, /* 0 */
  153499. { _map_nominal_u, _res_44u_1 }, /* 1 */
  153500. { _map_nominal_u, _res_44u_2 }, /* 2 */
  153501. { _map_nominal_u, _res_44u_3 }, /* 3 */
  153502. { _map_nominal_u, _res_44u_4 }, /* 4 */
  153503. { _map_nominal_u, _res_44u_5 }, /* 5 */
  153504. { _map_nominal_u, _res_44u_6 }, /* 6 */
  153505. { _map_nominal_u, _res_44u_7 }, /* 7 */
  153506. { _map_nominal_u, _res_44u_8 }, /* 8 */
  153507. { _map_nominal_u, _res_44u_9 }, /* 9 */
  153508. };
  153509. /*** End of inlined file: residue_44u.h ***/
  153510. static double rate_mapping_44_un[12]={
  153511. 32000.,48000.,60000.,70000.,80000.,86000.,
  153512. 96000.,110000.,120000.,140000.,160000.,240001.
  153513. };
  153514. ve_setup_data_template ve_setup_44_uncoupled={
  153515. 11,
  153516. rate_mapping_44_un,
  153517. quality_mapping_44,
  153518. -1,
  153519. 40000,
  153520. 50000,
  153521. blocksize_short_44,
  153522. blocksize_long_44,
  153523. _psy_tone_masteratt_44,
  153524. _psy_tone_0dB,
  153525. _psy_tone_suppress,
  153526. _vp_tonemask_adj_otherblock,
  153527. _vp_tonemask_adj_longblock,
  153528. _vp_tonemask_adj_otherblock,
  153529. _psy_noiseguards_44,
  153530. _psy_noisebias_impulse,
  153531. _psy_noisebias_padding,
  153532. _psy_noisebias_trans,
  153533. _psy_noisebias_long,
  153534. _psy_noise_suppress,
  153535. _psy_compand_44,
  153536. _psy_compand_short_mapping,
  153537. _psy_compand_long_mapping,
  153538. {_noise_start_short_44,_noise_start_long_44},
  153539. {_noise_part_short_44,_noise_part_long_44},
  153540. _noise_thresh_44,
  153541. _psy_ath_floater,
  153542. _psy_ath_abs,
  153543. _psy_lowpass_44,
  153544. _psy_global_44,
  153545. _global_mapping_44,
  153546. NULL,
  153547. _floor_books,
  153548. _floor,
  153549. _floor_short_mapping_44,
  153550. _floor_long_mapping_44,
  153551. _mapres_template_44_uncoupled
  153552. };
  153553. /*** End of inlined file: setup_44u.h ***/
  153554. /*** Start of inlined file: setup_32.h ***/
  153555. static double rate_mapping_32[12]={
  153556. 18000.,28000.,35000.,45000.,56000.,60000.,
  153557. 75000.,90000.,100000.,115000.,150000.,190000.,
  153558. };
  153559. static double rate_mapping_32_un[12]={
  153560. 30000.,42000.,52000.,64000.,72000.,78000.,
  153561. 86000.,92000.,110000.,120000.,140000.,190000.,
  153562. };
  153563. static double _psy_lowpass_32[12]={
  153564. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  153565. };
  153566. ve_setup_data_template ve_setup_32_stereo={
  153567. 11,
  153568. rate_mapping_32,
  153569. quality_mapping_44,
  153570. 2,
  153571. 26000,
  153572. 40000,
  153573. blocksize_short_44,
  153574. blocksize_long_44,
  153575. _psy_tone_masteratt_44,
  153576. _psy_tone_0dB,
  153577. _psy_tone_suppress,
  153578. _vp_tonemask_adj_otherblock,
  153579. _vp_tonemask_adj_longblock,
  153580. _vp_tonemask_adj_otherblock,
  153581. _psy_noiseguards_44,
  153582. _psy_noisebias_impulse,
  153583. _psy_noisebias_padding,
  153584. _psy_noisebias_trans,
  153585. _psy_noisebias_long,
  153586. _psy_noise_suppress,
  153587. _psy_compand_44,
  153588. _psy_compand_short_mapping,
  153589. _psy_compand_long_mapping,
  153590. {_noise_start_short_44,_noise_start_long_44},
  153591. {_noise_part_short_44,_noise_part_long_44},
  153592. _noise_thresh_44,
  153593. _psy_ath_floater,
  153594. _psy_ath_abs,
  153595. _psy_lowpass_32,
  153596. _psy_global_44,
  153597. _global_mapping_44,
  153598. _psy_stereo_modes_44,
  153599. _floor_books,
  153600. _floor,
  153601. _floor_short_mapping_44,
  153602. _floor_long_mapping_44,
  153603. _mapres_template_44_stereo
  153604. };
  153605. ve_setup_data_template ve_setup_32_uncoupled={
  153606. 11,
  153607. rate_mapping_32_un,
  153608. quality_mapping_44,
  153609. -1,
  153610. 26000,
  153611. 40000,
  153612. blocksize_short_44,
  153613. blocksize_long_44,
  153614. _psy_tone_masteratt_44,
  153615. _psy_tone_0dB,
  153616. _psy_tone_suppress,
  153617. _vp_tonemask_adj_otherblock,
  153618. _vp_tonemask_adj_longblock,
  153619. _vp_tonemask_adj_otherblock,
  153620. _psy_noiseguards_44,
  153621. _psy_noisebias_impulse,
  153622. _psy_noisebias_padding,
  153623. _psy_noisebias_trans,
  153624. _psy_noisebias_long,
  153625. _psy_noise_suppress,
  153626. _psy_compand_44,
  153627. _psy_compand_short_mapping,
  153628. _psy_compand_long_mapping,
  153629. {_noise_start_short_44,_noise_start_long_44},
  153630. {_noise_part_short_44,_noise_part_long_44},
  153631. _noise_thresh_44,
  153632. _psy_ath_floater,
  153633. _psy_ath_abs,
  153634. _psy_lowpass_32,
  153635. _psy_global_44,
  153636. _global_mapping_44,
  153637. NULL,
  153638. _floor_books,
  153639. _floor,
  153640. _floor_short_mapping_44,
  153641. _floor_long_mapping_44,
  153642. _mapres_template_44_uncoupled
  153643. };
  153644. /*** End of inlined file: setup_32.h ***/
  153645. /*** Start of inlined file: setup_8.h ***/
  153646. /*** Start of inlined file: psych_8.h ***/
  153647. static att3 _psy_tone_masteratt_8[3]={
  153648. {{ 32, 25, 12}, 0, 0}, /* 0 */
  153649. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153650. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153651. };
  153652. static vp_adjblock _vp_tonemask_adj_8[3]={
  153653. /* adjust for mode zero */
  153654. /* 63 125 250 500 1 2 4 8 16 */
  153655. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153656. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153657. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  153658. };
  153659. static noise3 _psy_noisebias_8[3]={
  153660. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153661. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153662. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  153663. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153664. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153665. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153666. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153667. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153668. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153669. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153670. };
  153671. /* stereo mode by base quality level */
  153672. static adj_stereo _psy_stereo_modes_8[3]={
  153673. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153674. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153675. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153676. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153677. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153678. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153679. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153680. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153681. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153682. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153683. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153684. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153685. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153686. };
  153687. static noiseguard _psy_noiseguards_8[2]={
  153688. {10,10,-1},
  153689. {10,10,-1},
  153690. };
  153691. static compandblock _psy_compand_8[2]={
  153692. {{
  153693. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  153694. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  153695. 12,12,13,13,14,14,15, 15, /* 23dB */
  153696. 16,16,17,17,17,18,18, 19, /* 31dB */
  153697. 19,19,20,21,22,23,24, 25, /* 39dB */
  153698. }},
  153699. {{
  153700. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  153701. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  153702. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  153703. 9,10,11,12,13,14,15, 16, /* 31dB */
  153704. 17,18,19,20,21,22,23, 24, /* 39dB */
  153705. }},
  153706. };
  153707. static double _psy_lowpass_8[3]={3.,4.,4.};
  153708. static int _noise_start_8[2]={
  153709. 64,64,
  153710. };
  153711. static int _noise_part_8[2]={
  153712. 8,8,
  153713. };
  153714. static int _psy_ath_floater_8[3]={
  153715. -100,-100,-105,
  153716. };
  153717. static int _psy_ath_abs_8[3]={
  153718. -130,-130,-140,
  153719. };
  153720. /*** End of inlined file: psych_8.h ***/
  153721. /*** Start of inlined file: residue_8.h ***/
  153722. /***** residue backends *********************************************/
  153723. static static_bookblock _resbook_8s_0={
  153724. {
  153725. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  153726. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  153727. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  153728. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  153729. }
  153730. };
  153731. static static_bookblock _resbook_8s_1={
  153732. {
  153733. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  153734. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  153735. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  153736. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  153737. }
  153738. };
  153739. static vorbis_residue_template _res_8s_0[]={
  153740. {2,0, &_residue_44_mid,
  153741. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  153742. &_resbook_8s_0,&_resbook_8s_0},
  153743. };
  153744. static vorbis_residue_template _res_8s_1[]={
  153745. {2,0, &_residue_44_mid,
  153746. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  153747. &_resbook_8s_1,&_resbook_8s_1},
  153748. };
  153749. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  153750. { _map_nominal, _res_8s_0 }, /* 0 */
  153751. { _map_nominal, _res_8s_1 }, /* 1 */
  153752. };
  153753. static static_bookblock _resbook_8u_0={
  153754. {
  153755. {0},
  153756. {0,0,&_8u0__p1_0},
  153757. {0,0,&_8u0__p2_0},
  153758. {0,0,&_8u0__p3_0},
  153759. {0,0,&_8u0__p4_0},
  153760. {0,0,&_8u0__p5_0},
  153761. {&_8u0__p6_0,&_8u0__p6_1},
  153762. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  153763. }
  153764. };
  153765. static static_bookblock _resbook_8u_1={
  153766. {
  153767. {0},
  153768. {0,0,&_8u1__p1_0},
  153769. {0,0,&_8u1__p2_0},
  153770. {0,0,&_8u1__p3_0},
  153771. {0,0,&_8u1__p4_0},
  153772. {0,0,&_8u1__p5_0},
  153773. {0,0,&_8u1__p6_0},
  153774. {&_8u1__p7_0,&_8u1__p7_1},
  153775. {&_8u1__p8_0,&_8u1__p8_1},
  153776. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  153777. }
  153778. };
  153779. static vorbis_residue_template _res_8u_0[]={
  153780. {1,0, &_residue_44_low_un,
  153781. &_huff_book__8u0__single,&_huff_book__8u0__single,
  153782. &_resbook_8u_0,&_resbook_8u_0},
  153783. };
  153784. static vorbis_residue_template _res_8u_1[]={
  153785. {1,0, &_residue_44_mid_un,
  153786. &_huff_book__8u1__single,&_huff_book__8u1__single,
  153787. &_resbook_8u_1,&_resbook_8u_1},
  153788. };
  153789. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  153790. { _map_nominal_u, _res_8u_0 }, /* 0 */
  153791. { _map_nominal_u, _res_8u_1 }, /* 1 */
  153792. };
  153793. /*** End of inlined file: residue_8.h ***/
  153794. static int blocksize_8[2]={
  153795. 512,512
  153796. };
  153797. static int _floor_mapping_8[2]={
  153798. 6,6,
  153799. };
  153800. static double rate_mapping_8[3]={
  153801. 6000.,9000.,32000.,
  153802. };
  153803. static double rate_mapping_8_uncoupled[3]={
  153804. 8000.,14000.,42000.,
  153805. };
  153806. static double quality_mapping_8[3]={
  153807. -.1,.0,1.
  153808. };
  153809. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  153810. static double _global_mapping_8[3]={ 1., 2., 3. };
  153811. ve_setup_data_template ve_setup_8_stereo={
  153812. 2,
  153813. rate_mapping_8,
  153814. quality_mapping_8,
  153815. 2,
  153816. 8000,
  153817. 9000,
  153818. blocksize_8,
  153819. blocksize_8,
  153820. _psy_tone_masteratt_8,
  153821. _psy_tone_0dB,
  153822. _psy_tone_suppress,
  153823. _vp_tonemask_adj_8,
  153824. NULL,
  153825. _vp_tonemask_adj_8,
  153826. _psy_noiseguards_8,
  153827. _psy_noisebias_8,
  153828. _psy_noisebias_8,
  153829. NULL,
  153830. NULL,
  153831. _psy_noise_suppress,
  153832. _psy_compand_8,
  153833. _psy_compand_8_mapping,
  153834. NULL,
  153835. {_noise_start_8,_noise_start_8},
  153836. {_noise_part_8,_noise_part_8},
  153837. _noise_thresh_5only,
  153838. _psy_ath_floater_8,
  153839. _psy_ath_abs_8,
  153840. _psy_lowpass_8,
  153841. _psy_global_44,
  153842. _global_mapping_8,
  153843. _psy_stereo_modes_8,
  153844. _floor_books,
  153845. _floor,
  153846. _floor_mapping_8,
  153847. NULL,
  153848. _mapres_template_8_stereo
  153849. };
  153850. ve_setup_data_template ve_setup_8_uncoupled={
  153851. 2,
  153852. rate_mapping_8_uncoupled,
  153853. quality_mapping_8,
  153854. -1,
  153855. 8000,
  153856. 9000,
  153857. blocksize_8,
  153858. blocksize_8,
  153859. _psy_tone_masteratt_8,
  153860. _psy_tone_0dB,
  153861. _psy_tone_suppress,
  153862. _vp_tonemask_adj_8,
  153863. NULL,
  153864. _vp_tonemask_adj_8,
  153865. _psy_noiseguards_8,
  153866. _psy_noisebias_8,
  153867. _psy_noisebias_8,
  153868. NULL,
  153869. NULL,
  153870. _psy_noise_suppress,
  153871. _psy_compand_8,
  153872. _psy_compand_8_mapping,
  153873. NULL,
  153874. {_noise_start_8,_noise_start_8},
  153875. {_noise_part_8,_noise_part_8},
  153876. _noise_thresh_5only,
  153877. _psy_ath_floater_8,
  153878. _psy_ath_abs_8,
  153879. _psy_lowpass_8,
  153880. _psy_global_44,
  153881. _global_mapping_8,
  153882. _psy_stereo_modes_8,
  153883. _floor_books,
  153884. _floor,
  153885. _floor_mapping_8,
  153886. NULL,
  153887. _mapres_template_8_uncoupled
  153888. };
  153889. /*** End of inlined file: setup_8.h ***/
  153890. /*** Start of inlined file: setup_11.h ***/
  153891. /*** Start of inlined file: psych_11.h ***/
  153892. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  153893. static att3 _psy_tone_masteratt_11[3]={
  153894. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153895. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153896. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153897. };
  153898. static vp_adjblock _vp_tonemask_adj_11[3]={
  153899. /* adjust for mode zero */
  153900. /* 63 125 250 500 1 2 4 8 16 */
  153901. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  153902. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  153903. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  153904. };
  153905. static noise3 _psy_noisebias_11[3]={
  153906. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153907. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153908. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  153909. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153910. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  153911. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153912. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153913. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153914. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153915. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153916. };
  153917. static double _noise_thresh_11[3]={ .3,.5,.5 };
  153918. /*** End of inlined file: psych_11.h ***/
  153919. static int blocksize_11[2]={
  153920. 512,512
  153921. };
  153922. static int _floor_mapping_11[2]={
  153923. 6,6,
  153924. };
  153925. static double rate_mapping_11[3]={
  153926. 8000.,13000.,44000.,
  153927. };
  153928. static double rate_mapping_11_uncoupled[3]={
  153929. 12000.,20000.,50000.,
  153930. };
  153931. static double quality_mapping_11[3]={
  153932. -.1,.0,1.
  153933. };
  153934. ve_setup_data_template ve_setup_11_stereo={
  153935. 2,
  153936. rate_mapping_11,
  153937. quality_mapping_11,
  153938. 2,
  153939. 9000,
  153940. 15000,
  153941. blocksize_11,
  153942. blocksize_11,
  153943. _psy_tone_masteratt_11,
  153944. _psy_tone_0dB,
  153945. _psy_tone_suppress,
  153946. _vp_tonemask_adj_11,
  153947. NULL,
  153948. _vp_tonemask_adj_11,
  153949. _psy_noiseguards_8,
  153950. _psy_noisebias_11,
  153951. _psy_noisebias_11,
  153952. NULL,
  153953. NULL,
  153954. _psy_noise_suppress,
  153955. _psy_compand_8,
  153956. _psy_compand_8_mapping,
  153957. NULL,
  153958. {_noise_start_8,_noise_start_8},
  153959. {_noise_part_8,_noise_part_8},
  153960. _noise_thresh_11,
  153961. _psy_ath_floater_8,
  153962. _psy_ath_abs_8,
  153963. _psy_lowpass_11,
  153964. _psy_global_44,
  153965. _global_mapping_8,
  153966. _psy_stereo_modes_8,
  153967. _floor_books,
  153968. _floor,
  153969. _floor_mapping_11,
  153970. NULL,
  153971. _mapres_template_8_stereo
  153972. };
  153973. ve_setup_data_template ve_setup_11_uncoupled={
  153974. 2,
  153975. rate_mapping_11_uncoupled,
  153976. quality_mapping_11,
  153977. -1,
  153978. 9000,
  153979. 15000,
  153980. blocksize_11,
  153981. blocksize_11,
  153982. _psy_tone_masteratt_11,
  153983. _psy_tone_0dB,
  153984. _psy_tone_suppress,
  153985. _vp_tonemask_adj_11,
  153986. NULL,
  153987. _vp_tonemask_adj_11,
  153988. _psy_noiseguards_8,
  153989. _psy_noisebias_11,
  153990. _psy_noisebias_11,
  153991. NULL,
  153992. NULL,
  153993. _psy_noise_suppress,
  153994. _psy_compand_8,
  153995. _psy_compand_8_mapping,
  153996. NULL,
  153997. {_noise_start_8,_noise_start_8},
  153998. {_noise_part_8,_noise_part_8},
  153999. _noise_thresh_11,
  154000. _psy_ath_floater_8,
  154001. _psy_ath_abs_8,
  154002. _psy_lowpass_11,
  154003. _psy_global_44,
  154004. _global_mapping_8,
  154005. _psy_stereo_modes_8,
  154006. _floor_books,
  154007. _floor,
  154008. _floor_mapping_11,
  154009. NULL,
  154010. _mapres_template_8_uncoupled
  154011. };
  154012. /*** End of inlined file: setup_11.h ***/
  154013. /*** Start of inlined file: setup_16.h ***/
  154014. /*** Start of inlined file: psych_16.h ***/
  154015. /* stereo mode by base quality level */
  154016. static adj_stereo _psy_stereo_modes_16[4]={
  154017. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  154018. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154019. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154020. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  154021. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154022. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154023. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154024. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  154025. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154026. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154027. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154028. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154029. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154030. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  154031. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  154032. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  154033. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154034. };
  154035. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  154036. static att3 _psy_tone_masteratt_16[4]={
  154037. {{ 30, 25, 12}, 0, 0}, /* 0 */
  154038. {{ 25, 22, 12}, 0, 0}, /* 0 */
  154039. {{ 20, 12, 0}, 0, 0}, /* 0 */
  154040. {{ 15, 0, -14}, 0, 0}, /* 0 */
  154041. };
  154042. static vp_adjblock _vp_tonemask_adj_16[4]={
  154043. /* adjust for mode zero */
  154044. /* 63 125 250 500 1 2 4 8 16 */
  154045. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  154046. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  154047. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  154048. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  154049. };
  154050. static noise3 _psy_noisebias_16_short[4]={
  154051. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154052. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  154053. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  154054. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154055. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  154056. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  154057. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  154058. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  154059. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  154060. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154061. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154062. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  154063. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154064. };
  154065. static noise3 _psy_noisebias_16_impulse[4]={
  154066. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154067. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  154068. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  154069. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154070. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  154071. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  154072. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  154073. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  154074. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  154075. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154076. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154077. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  154078. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154079. };
  154080. static noise3 _psy_noisebias_16[4]={
  154081. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154082. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  154083. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  154084. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154085. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  154086. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  154087. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154088. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  154089. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  154090. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154091. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154092. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  154093. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154094. };
  154095. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  154096. static int _noise_start_16[3]={ 256,256,9999 };
  154097. static int _noise_part_16[4]={ 8,8,8,8 };
  154098. static int _psy_ath_floater_16[4]={
  154099. -100,-100,-100,-105,
  154100. };
  154101. static int _psy_ath_abs_16[4]={
  154102. -130,-130,-130,-140,
  154103. };
  154104. /*** End of inlined file: psych_16.h ***/
  154105. /*** Start of inlined file: residue_16.h ***/
  154106. /***** residue backends *********************************************/
  154107. static static_bookblock _resbook_16s_0={
  154108. {
  154109. {0},
  154110. {0,0,&_16c0_s_p1_0},
  154111. {0,0,&_16c0_s_p2_0},
  154112. {0,0,&_16c0_s_p3_0},
  154113. {0,0,&_16c0_s_p4_0},
  154114. {0,0,&_16c0_s_p5_0},
  154115. {0,0,&_16c0_s_p6_0},
  154116. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  154117. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  154118. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  154119. }
  154120. };
  154121. static static_bookblock _resbook_16s_1={
  154122. {
  154123. {0},
  154124. {0,0,&_16c1_s_p1_0},
  154125. {0,0,&_16c1_s_p2_0},
  154126. {0,0,&_16c1_s_p3_0},
  154127. {0,0,&_16c1_s_p4_0},
  154128. {0,0,&_16c1_s_p5_0},
  154129. {0,0,&_16c1_s_p6_0},
  154130. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  154131. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  154132. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  154133. }
  154134. };
  154135. static static_bookblock _resbook_16s_2={
  154136. {
  154137. {0},
  154138. {0,0,&_16c2_s_p1_0},
  154139. {0,0,&_16c2_s_p2_0},
  154140. {0,0,&_16c2_s_p3_0},
  154141. {0,0,&_16c2_s_p4_0},
  154142. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  154143. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  154144. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  154145. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  154146. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  154147. }
  154148. };
  154149. static vorbis_residue_template _res_16s_0[]={
  154150. {2,0, &_residue_44_mid,
  154151. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  154152. &_resbook_16s_0,&_resbook_16s_0},
  154153. };
  154154. static vorbis_residue_template _res_16s_1[]={
  154155. {2,0, &_residue_44_mid,
  154156. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  154157. &_resbook_16s_1,&_resbook_16s_1},
  154158. {2,0, &_residue_44_mid,
  154159. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  154160. &_resbook_16s_1,&_resbook_16s_1}
  154161. };
  154162. static vorbis_residue_template _res_16s_2[]={
  154163. {2,0, &_residue_44_high,
  154164. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  154165. &_resbook_16s_2,&_resbook_16s_2},
  154166. {2,0, &_residue_44_high,
  154167. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  154168. &_resbook_16s_2,&_resbook_16s_2}
  154169. };
  154170. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  154171. { _map_nominal, _res_16s_0 }, /* 0 */
  154172. { _map_nominal, _res_16s_1 }, /* 1 */
  154173. { _map_nominal, _res_16s_2 }, /* 2 */
  154174. };
  154175. static static_bookblock _resbook_16u_0={
  154176. {
  154177. {0},
  154178. {0,0,&_16u0__p1_0},
  154179. {0,0,&_16u0__p2_0},
  154180. {0,0,&_16u0__p3_0},
  154181. {0,0,&_16u0__p4_0},
  154182. {0,0,&_16u0__p5_0},
  154183. {&_16u0__p6_0,&_16u0__p6_1},
  154184. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  154185. }
  154186. };
  154187. static static_bookblock _resbook_16u_1={
  154188. {
  154189. {0},
  154190. {0,0,&_16u1__p1_0},
  154191. {0,0,&_16u1__p2_0},
  154192. {0,0,&_16u1__p3_0},
  154193. {0,0,&_16u1__p4_0},
  154194. {0,0,&_16u1__p5_0},
  154195. {0,0,&_16u1__p6_0},
  154196. {&_16u1__p7_0,&_16u1__p7_1},
  154197. {&_16u1__p8_0,&_16u1__p8_1},
  154198. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  154199. }
  154200. };
  154201. static static_bookblock _resbook_16u_2={
  154202. {
  154203. {0},
  154204. {0,0,&_16u2_p1_0},
  154205. {0,0,&_16u2_p2_0},
  154206. {0,0,&_16u2_p3_0},
  154207. {0,0,&_16u2_p4_0},
  154208. {&_16u2_p5_0,&_16u2_p5_1},
  154209. {&_16u2_p6_0,&_16u2_p6_1},
  154210. {&_16u2_p7_0,&_16u2_p7_1},
  154211. {&_16u2_p8_0,&_16u2_p8_1},
  154212. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  154213. }
  154214. };
  154215. static vorbis_residue_template _res_16u_0[]={
  154216. {1,0, &_residue_44_low_un,
  154217. &_huff_book__16u0__single,&_huff_book__16u0__single,
  154218. &_resbook_16u_0,&_resbook_16u_0},
  154219. };
  154220. static vorbis_residue_template _res_16u_1[]={
  154221. {1,0, &_residue_44_mid_un,
  154222. &_huff_book__16u1__short,&_huff_book__16u1__short,
  154223. &_resbook_16u_1,&_resbook_16u_1},
  154224. {1,0, &_residue_44_mid_un,
  154225. &_huff_book__16u1__long,&_huff_book__16u1__long,
  154226. &_resbook_16u_1,&_resbook_16u_1}
  154227. };
  154228. static vorbis_residue_template _res_16u_2[]={
  154229. {1,0, &_residue_44_hi_un,
  154230. &_huff_book__16u2__short,&_huff_book__16u2__short,
  154231. &_resbook_16u_2,&_resbook_16u_2},
  154232. {1,0, &_residue_44_hi_un,
  154233. &_huff_book__16u2__long,&_huff_book__16u2__long,
  154234. &_resbook_16u_2,&_resbook_16u_2}
  154235. };
  154236. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  154237. { _map_nominal_u, _res_16u_0 }, /* 0 */
  154238. { _map_nominal_u, _res_16u_1 }, /* 1 */
  154239. { _map_nominal_u, _res_16u_2 }, /* 2 */
  154240. };
  154241. /*** End of inlined file: residue_16.h ***/
  154242. static int blocksize_16_short[3]={
  154243. 1024,512,512
  154244. };
  154245. static int blocksize_16_long[3]={
  154246. 1024,1024,1024
  154247. };
  154248. static int _floor_mapping_16_short[3]={
  154249. 9,3,3
  154250. };
  154251. static int _floor_mapping_16[3]={
  154252. 9,9,9
  154253. };
  154254. static double rate_mapping_16[4]={
  154255. 12000.,20000.,44000.,86000.
  154256. };
  154257. static double rate_mapping_16_uncoupled[4]={
  154258. 16000.,28000.,64000.,100000.
  154259. };
  154260. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  154261. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  154262. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  154263. ve_setup_data_template ve_setup_16_stereo={
  154264. 3,
  154265. rate_mapping_16,
  154266. quality_mapping_16,
  154267. 2,
  154268. 15000,
  154269. 19000,
  154270. blocksize_16_short,
  154271. blocksize_16_long,
  154272. _psy_tone_masteratt_16,
  154273. _psy_tone_0dB,
  154274. _psy_tone_suppress,
  154275. _vp_tonemask_adj_16,
  154276. _vp_tonemask_adj_16,
  154277. _vp_tonemask_adj_16,
  154278. _psy_noiseguards_8,
  154279. _psy_noisebias_16_impulse,
  154280. _psy_noisebias_16_short,
  154281. _psy_noisebias_16_short,
  154282. _psy_noisebias_16,
  154283. _psy_noise_suppress,
  154284. _psy_compand_8,
  154285. _psy_compand_16_mapping,
  154286. _psy_compand_16_mapping,
  154287. {_noise_start_16,_noise_start_16},
  154288. { _noise_part_16, _noise_part_16},
  154289. _noise_thresh_16,
  154290. _psy_ath_floater_16,
  154291. _psy_ath_abs_16,
  154292. _psy_lowpass_16,
  154293. _psy_global_44,
  154294. _global_mapping_16,
  154295. _psy_stereo_modes_16,
  154296. _floor_books,
  154297. _floor,
  154298. _floor_mapping_16_short,
  154299. _floor_mapping_16,
  154300. _mapres_template_16_stereo
  154301. };
  154302. ve_setup_data_template ve_setup_16_uncoupled={
  154303. 3,
  154304. rate_mapping_16_uncoupled,
  154305. quality_mapping_16,
  154306. -1,
  154307. 15000,
  154308. 19000,
  154309. blocksize_16_short,
  154310. blocksize_16_long,
  154311. _psy_tone_masteratt_16,
  154312. _psy_tone_0dB,
  154313. _psy_tone_suppress,
  154314. _vp_tonemask_adj_16,
  154315. _vp_tonemask_adj_16,
  154316. _vp_tonemask_adj_16,
  154317. _psy_noiseguards_8,
  154318. _psy_noisebias_16_impulse,
  154319. _psy_noisebias_16_short,
  154320. _psy_noisebias_16_short,
  154321. _psy_noisebias_16,
  154322. _psy_noise_suppress,
  154323. _psy_compand_8,
  154324. _psy_compand_16_mapping,
  154325. _psy_compand_16_mapping,
  154326. {_noise_start_16,_noise_start_16},
  154327. { _noise_part_16, _noise_part_16},
  154328. _noise_thresh_16,
  154329. _psy_ath_floater_16,
  154330. _psy_ath_abs_16,
  154331. _psy_lowpass_16,
  154332. _psy_global_44,
  154333. _global_mapping_16,
  154334. _psy_stereo_modes_16,
  154335. _floor_books,
  154336. _floor,
  154337. _floor_mapping_16_short,
  154338. _floor_mapping_16,
  154339. _mapres_template_16_uncoupled
  154340. };
  154341. /*** End of inlined file: setup_16.h ***/
  154342. /*** Start of inlined file: setup_22.h ***/
  154343. static double rate_mapping_22[4]={
  154344. 15000.,20000.,44000.,86000.
  154345. };
  154346. static double rate_mapping_22_uncoupled[4]={
  154347. 16000.,28000.,50000.,90000.
  154348. };
  154349. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  154350. ve_setup_data_template ve_setup_22_stereo={
  154351. 3,
  154352. rate_mapping_22,
  154353. quality_mapping_16,
  154354. 2,
  154355. 19000,
  154356. 26000,
  154357. blocksize_16_short,
  154358. blocksize_16_long,
  154359. _psy_tone_masteratt_16,
  154360. _psy_tone_0dB,
  154361. _psy_tone_suppress,
  154362. _vp_tonemask_adj_16,
  154363. _vp_tonemask_adj_16,
  154364. _vp_tonemask_adj_16,
  154365. _psy_noiseguards_8,
  154366. _psy_noisebias_16_impulse,
  154367. _psy_noisebias_16_short,
  154368. _psy_noisebias_16_short,
  154369. _psy_noisebias_16,
  154370. _psy_noise_suppress,
  154371. _psy_compand_8,
  154372. _psy_compand_8_mapping,
  154373. _psy_compand_8_mapping,
  154374. {_noise_start_16,_noise_start_16},
  154375. { _noise_part_16, _noise_part_16},
  154376. _noise_thresh_16,
  154377. _psy_ath_floater_16,
  154378. _psy_ath_abs_16,
  154379. _psy_lowpass_22,
  154380. _psy_global_44,
  154381. _global_mapping_16,
  154382. _psy_stereo_modes_16,
  154383. _floor_books,
  154384. _floor,
  154385. _floor_mapping_16_short,
  154386. _floor_mapping_16,
  154387. _mapres_template_16_stereo
  154388. };
  154389. ve_setup_data_template ve_setup_22_uncoupled={
  154390. 3,
  154391. rate_mapping_22_uncoupled,
  154392. quality_mapping_16,
  154393. -1,
  154394. 19000,
  154395. 26000,
  154396. blocksize_16_short,
  154397. blocksize_16_long,
  154398. _psy_tone_masteratt_16,
  154399. _psy_tone_0dB,
  154400. _psy_tone_suppress,
  154401. _vp_tonemask_adj_16,
  154402. _vp_tonemask_adj_16,
  154403. _vp_tonemask_adj_16,
  154404. _psy_noiseguards_8,
  154405. _psy_noisebias_16_impulse,
  154406. _psy_noisebias_16_short,
  154407. _psy_noisebias_16_short,
  154408. _psy_noisebias_16,
  154409. _psy_noise_suppress,
  154410. _psy_compand_8,
  154411. _psy_compand_8_mapping,
  154412. _psy_compand_8_mapping,
  154413. {_noise_start_16,_noise_start_16},
  154414. { _noise_part_16, _noise_part_16},
  154415. _noise_thresh_16,
  154416. _psy_ath_floater_16,
  154417. _psy_ath_abs_16,
  154418. _psy_lowpass_22,
  154419. _psy_global_44,
  154420. _global_mapping_16,
  154421. _psy_stereo_modes_16,
  154422. _floor_books,
  154423. _floor,
  154424. _floor_mapping_16_short,
  154425. _floor_mapping_16,
  154426. _mapres_template_16_uncoupled
  154427. };
  154428. /*** End of inlined file: setup_22.h ***/
  154429. /*** Start of inlined file: setup_X.h ***/
  154430. static double rate_mapping_X[12]={
  154431. -1.,-1.,-1.,-1.,-1.,-1.,
  154432. -1.,-1.,-1.,-1.,-1.,-1.
  154433. };
  154434. ve_setup_data_template ve_setup_X_stereo={
  154435. 11,
  154436. rate_mapping_X,
  154437. quality_mapping_44,
  154438. 2,
  154439. 50000,
  154440. 200000,
  154441. blocksize_short_44,
  154442. blocksize_long_44,
  154443. _psy_tone_masteratt_44,
  154444. _psy_tone_0dB,
  154445. _psy_tone_suppress,
  154446. _vp_tonemask_adj_otherblock,
  154447. _vp_tonemask_adj_longblock,
  154448. _vp_tonemask_adj_otherblock,
  154449. _psy_noiseguards_44,
  154450. _psy_noisebias_impulse,
  154451. _psy_noisebias_padding,
  154452. _psy_noisebias_trans,
  154453. _psy_noisebias_long,
  154454. _psy_noise_suppress,
  154455. _psy_compand_44,
  154456. _psy_compand_short_mapping,
  154457. _psy_compand_long_mapping,
  154458. {_noise_start_short_44,_noise_start_long_44},
  154459. {_noise_part_short_44,_noise_part_long_44},
  154460. _noise_thresh_44,
  154461. _psy_ath_floater,
  154462. _psy_ath_abs,
  154463. _psy_lowpass_44,
  154464. _psy_global_44,
  154465. _global_mapping_44,
  154466. _psy_stereo_modes_44,
  154467. _floor_books,
  154468. _floor,
  154469. _floor_short_mapping_44,
  154470. _floor_long_mapping_44,
  154471. _mapres_template_44_stereo
  154472. };
  154473. ve_setup_data_template ve_setup_X_uncoupled={
  154474. 11,
  154475. rate_mapping_X,
  154476. quality_mapping_44,
  154477. -1,
  154478. 50000,
  154479. 200000,
  154480. blocksize_short_44,
  154481. blocksize_long_44,
  154482. _psy_tone_masteratt_44,
  154483. _psy_tone_0dB,
  154484. _psy_tone_suppress,
  154485. _vp_tonemask_adj_otherblock,
  154486. _vp_tonemask_adj_longblock,
  154487. _vp_tonemask_adj_otherblock,
  154488. _psy_noiseguards_44,
  154489. _psy_noisebias_impulse,
  154490. _psy_noisebias_padding,
  154491. _psy_noisebias_trans,
  154492. _psy_noisebias_long,
  154493. _psy_noise_suppress,
  154494. _psy_compand_44,
  154495. _psy_compand_short_mapping,
  154496. _psy_compand_long_mapping,
  154497. {_noise_start_short_44,_noise_start_long_44},
  154498. {_noise_part_short_44,_noise_part_long_44},
  154499. _noise_thresh_44,
  154500. _psy_ath_floater,
  154501. _psy_ath_abs,
  154502. _psy_lowpass_44,
  154503. _psy_global_44,
  154504. _global_mapping_44,
  154505. NULL,
  154506. _floor_books,
  154507. _floor,
  154508. _floor_short_mapping_44,
  154509. _floor_long_mapping_44,
  154510. _mapres_template_44_uncoupled
  154511. };
  154512. ve_setup_data_template ve_setup_XX_stereo={
  154513. 2,
  154514. rate_mapping_X,
  154515. quality_mapping_8,
  154516. 2,
  154517. 0,
  154518. 8000,
  154519. blocksize_8,
  154520. blocksize_8,
  154521. _psy_tone_masteratt_8,
  154522. _psy_tone_0dB,
  154523. _psy_tone_suppress,
  154524. _vp_tonemask_adj_8,
  154525. NULL,
  154526. _vp_tonemask_adj_8,
  154527. _psy_noiseguards_8,
  154528. _psy_noisebias_8,
  154529. _psy_noisebias_8,
  154530. NULL,
  154531. NULL,
  154532. _psy_noise_suppress,
  154533. _psy_compand_8,
  154534. _psy_compand_8_mapping,
  154535. NULL,
  154536. {_noise_start_8,_noise_start_8},
  154537. {_noise_part_8,_noise_part_8},
  154538. _noise_thresh_5only,
  154539. _psy_ath_floater_8,
  154540. _psy_ath_abs_8,
  154541. _psy_lowpass_8,
  154542. _psy_global_44,
  154543. _global_mapping_8,
  154544. _psy_stereo_modes_8,
  154545. _floor_books,
  154546. _floor,
  154547. _floor_mapping_8,
  154548. NULL,
  154549. _mapres_template_8_stereo
  154550. };
  154551. ve_setup_data_template ve_setup_XX_uncoupled={
  154552. 2,
  154553. rate_mapping_X,
  154554. quality_mapping_8,
  154555. -1,
  154556. 0,
  154557. 8000,
  154558. blocksize_8,
  154559. blocksize_8,
  154560. _psy_tone_masteratt_8,
  154561. _psy_tone_0dB,
  154562. _psy_tone_suppress,
  154563. _vp_tonemask_adj_8,
  154564. NULL,
  154565. _vp_tonemask_adj_8,
  154566. _psy_noiseguards_8,
  154567. _psy_noisebias_8,
  154568. _psy_noisebias_8,
  154569. NULL,
  154570. NULL,
  154571. _psy_noise_suppress,
  154572. _psy_compand_8,
  154573. _psy_compand_8_mapping,
  154574. NULL,
  154575. {_noise_start_8,_noise_start_8},
  154576. {_noise_part_8,_noise_part_8},
  154577. _noise_thresh_5only,
  154578. _psy_ath_floater_8,
  154579. _psy_ath_abs_8,
  154580. _psy_lowpass_8,
  154581. _psy_global_44,
  154582. _global_mapping_8,
  154583. _psy_stereo_modes_8,
  154584. _floor_books,
  154585. _floor,
  154586. _floor_mapping_8,
  154587. NULL,
  154588. _mapres_template_8_uncoupled
  154589. };
  154590. /*** End of inlined file: setup_X.h ***/
  154591. static ve_setup_data_template *setup_list[]={
  154592. &ve_setup_44_stereo,
  154593. &ve_setup_44_uncoupled,
  154594. &ve_setup_32_stereo,
  154595. &ve_setup_32_uncoupled,
  154596. &ve_setup_22_stereo,
  154597. &ve_setup_22_uncoupled,
  154598. &ve_setup_16_stereo,
  154599. &ve_setup_16_uncoupled,
  154600. &ve_setup_11_stereo,
  154601. &ve_setup_11_uncoupled,
  154602. &ve_setup_8_stereo,
  154603. &ve_setup_8_uncoupled,
  154604. &ve_setup_X_stereo,
  154605. &ve_setup_X_uncoupled,
  154606. &ve_setup_XX_stereo,
  154607. &ve_setup_XX_uncoupled,
  154608. 0
  154609. };
  154610. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  154611. if(vi && vi->codec_setup){
  154612. vi->version=0;
  154613. vi->channels=ch;
  154614. vi->rate=rate;
  154615. return(0);
  154616. }
  154617. return(OV_EINVAL);
  154618. }
  154619. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  154620. static_codebook ***books,
  154621. vorbis_info_floor1 *in,
  154622. int *x){
  154623. int i,k,is=s;
  154624. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  154625. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154626. memcpy(f,in+x[is],sizeof(*f));
  154627. /* fill in the lowpass field, even if it's temporary */
  154628. f->n=ci->blocksizes[block]>>1;
  154629. /* books */
  154630. {
  154631. int partitions=f->partitions;
  154632. int maxclass=-1;
  154633. int maxbook=-1;
  154634. for(i=0;i<partitions;i++)
  154635. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  154636. for(i=0;i<=maxclass;i++){
  154637. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  154638. f->class_book[i]+=ci->books;
  154639. for(k=0;k<(1<<f->class_subs[i]);k++){
  154640. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  154641. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  154642. }
  154643. }
  154644. for(i=0;i<=maxbook;i++)
  154645. ci->book_param[ci->books++]=books[x[is]][i];
  154646. }
  154647. /* for now, we're only using floor 1 */
  154648. ci->floor_type[ci->floors]=1;
  154649. ci->floor_param[ci->floors]=f;
  154650. ci->floors++;
  154651. return;
  154652. }
  154653. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  154654. vorbis_info_psy_global *in,
  154655. double *x){
  154656. int i,is=s;
  154657. double ds=s-is;
  154658. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154659. vorbis_info_psy_global *g=&ci->psy_g_param;
  154660. memcpy(g,in+(int)x[is],sizeof(*g));
  154661. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154662. is=(int)ds;
  154663. ds-=is;
  154664. if(ds==0 && is>0){
  154665. is--;
  154666. ds=1.;
  154667. }
  154668. /* interpolate the trigger threshholds */
  154669. for(i=0;i<4;i++){
  154670. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  154671. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  154672. }
  154673. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  154674. return;
  154675. }
  154676. static void vorbis_encode_global_stereo(vorbis_info *vi,
  154677. highlevel_encode_setup *hi,
  154678. adj_stereo *p){
  154679. float s=hi->stereo_point_setting;
  154680. int i,is=s;
  154681. double ds=s-is;
  154682. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154683. vorbis_info_psy_global *g=&ci->psy_g_param;
  154684. if(p){
  154685. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  154686. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  154687. if(hi->managed){
  154688. /* interpolate the kHz threshholds */
  154689. for(i=0;i<PACKETBLOBS;i++){
  154690. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  154691. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154692. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154693. g->coupling_pkHz[i]=kHz;
  154694. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  154695. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154696. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154697. }
  154698. }else{
  154699. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  154700. for(i=0;i<PACKETBLOBS;i++){
  154701. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154702. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154703. g->coupling_pkHz[i]=kHz;
  154704. }
  154705. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  154706. for(i=0;i<PACKETBLOBS;i++){
  154707. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154708. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154709. }
  154710. }
  154711. }else{
  154712. for(i=0;i<PACKETBLOBS;i++){
  154713. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  154714. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  154715. }
  154716. }
  154717. return;
  154718. }
  154719. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  154720. int *nn_start,
  154721. int *nn_partition,
  154722. double *nn_thresh,
  154723. int block){
  154724. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154725. vorbis_info_psy *p=ci->psy_param[block];
  154726. highlevel_encode_setup *hi=&ci->hi;
  154727. int is=s;
  154728. if(block>=ci->psys)
  154729. ci->psys=block+1;
  154730. if(!p){
  154731. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  154732. ci->psy_param[block]=p;
  154733. }
  154734. memcpy(p,&_psy_info_template,sizeof(*p));
  154735. p->blockflag=block>>1;
  154736. if(hi->noise_normalize_p){
  154737. p->normal_channel_p=1;
  154738. p->normal_point_p=1;
  154739. p->normal_start=nn_start[is];
  154740. p->normal_partition=nn_partition[is];
  154741. p->normal_thresh=nn_thresh[is];
  154742. }
  154743. return;
  154744. }
  154745. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  154746. att3 *att,
  154747. int *max,
  154748. vp_adjblock *in){
  154749. int i,is=s;
  154750. double ds=s-is;
  154751. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154752. vorbis_info_psy *p=ci->psy_param[block];
  154753. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  154754. filling the values in here */
  154755. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  154756. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  154757. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  154758. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  154759. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  154760. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  154761. for(i=0;i<P_BANDS;i++)
  154762. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  154763. return;
  154764. }
  154765. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  154766. compandblock *in, double *x){
  154767. int i,is=s;
  154768. double ds=s-is;
  154769. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154770. vorbis_info_psy *p=ci->psy_param[block];
  154771. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154772. is=(int)ds;
  154773. ds-=is;
  154774. if(ds==0 && is>0){
  154775. is--;
  154776. ds=1.;
  154777. }
  154778. /* interpolate the compander settings */
  154779. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  154780. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  154781. return;
  154782. }
  154783. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  154784. int *suppress){
  154785. int is=s;
  154786. double ds=s-is;
  154787. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154788. vorbis_info_psy *p=ci->psy_param[block];
  154789. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154790. return;
  154791. }
  154792. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  154793. int *suppress,
  154794. noise3 *in,
  154795. noiseguard *guard,
  154796. double userbias){
  154797. int i,is=s,j;
  154798. double ds=s-is;
  154799. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154800. vorbis_info_psy *p=ci->psy_param[block];
  154801. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  154802. p->noisewindowlomin=guard[block].lo;
  154803. p->noisewindowhimin=guard[block].hi;
  154804. p->noisewindowfixed=guard[block].fixed;
  154805. for(j=0;j<P_NOISECURVES;j++)
  154806. for(i=0;i<P_BANDS;i++)
  154807. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  154808. /* impulse blocks may take a user specified bias to boost the
  154809. nominal/high noise encoding depth */
  154810. for(j=0;j<P_NOISECURVES;j++){
  154811. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  154812. for(i=0;i<P_BANDS;i++){
  154813. p->noiseoff[j][i]+=userbias;
  154814. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  154815. }
  154816. }
  154817. return;
  154818. }
  154819. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  154820. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154821. vorbis_info_psy *p=ci->psy_param[block];
  154822. p->ath_adjatt=ci->hi.ath_floating_dB;
  154823. p->ath_maxatt=ci->hi.ath_absolute_dB;
  154824. return;
  154825. }
  154826. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  154827. int i;
  154828. for(i=0;i<ci->books;i++)
  154829. if(ci->book_param[i]==book)return(i);
  154830. return(ci->books++);
  154831. }
  154832. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  154833. int *shortb,int *longb){
  154834. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154835. int is=s;
  154836. int blockshort=shortb[is];
  154837. int blocklong=longb[is];
  154838. ci->blocksizes[0]=blockshort;
  154839. ci->blocksizes[1]=blocklong;
  154840. }
  154841. static void vorbis_encode_residue_setup(vorbis_info *vi,
  154842. int number, int block,
  154843. vorbis_residue_template *res){
  154844. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154845. int i,n;
  154846. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  154847. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  154848. memcpy(r,res->res,sizeof(*r));
  154849. if(ci->residues<=number)ci->residues=number+1;
  154850. switch(ci->blocksizes[block]){
  154851. case 64:case 128:case 256:
  154852. r->grouping=16;
  154853. break;
  154854. default:
  154855. r->grouping=32;
  154856. break;
  154857. }
  154858. ci->residue_type[number]=res->res_type;
  154859. /* to be adjusted by lowpass/pointlimit later */
  154860. n=r->end=ci->blocksizes[block]>>1;
  154861. if(res->res_type==2)
  154862. n=r->end*=vi->channels;
  154863. /* fill in all the books */
  154864. {
  154865. int booklist=0,k;
  154866. if(ci->hi.managed){
  154867. for(i=0;i<r->partitions;i++)
  154868. for(k=0;k<3;k++)
  154869. if(res->books_base_managed->books[i][k])
  154870. r->secondstages[i]|=(1<<k);
  154871. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  154872. ci->book_param[r->groupbook]=res->book_aux_managed;
  154873. for(i=0;i<r->partitions;i++){
  154874. for(k=0;k<3;k++){
  154875. if(res->books_base_managed->books[i][k]){
  154876. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  154877. r->booklist[booklist++]=bookid;
  154878. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  154879. }
  154880. }
  154881. }
  154882. }else{
  154883. for(i=0;i<r->partitions;i++)
  154884. for(k=0;k<3;k++)
  154885. if(res->books_base->books[i][k])
  154886. r->secondstages[i]|=(1<<k);
  154887. r->groupbook=book_dup_or_new(ci,res->book_aux);
  154888. ci->book_param[r->groupbook]=res->book_aux;
  154889. for(i=0;i<r->partitions;i++){
  154890. for(k=0;k<3;k++){
  154891. if(res->books_base->books[i][k]){
  154892. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  154893. r->booklist[booklist++]=bookid;
  154894. ci->book_param[bookid]=res->books_base->books[i][k];
  154895. }
  154896. }
  154897. }
  154898. }
  154899. }
  154900. /* lowpass setup/pointlimit */
  154901. {
  154902. double freq=ci->hi.lowpass_kHz*1000.;
  154903. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  154904. double nyq=vi->rate/2.;
  154905. long blocksize=ci->blocksizes[block]>>1;
  154906. /* lowpass needs to be set in the floor and the residue. */
  154907. if(freq>nyq)freq=nyq;
  154908. /* in the floor, the granularity can be very fine; it doesn't alter
  154909. the encoding structure, only the samples used to fit the floor
  154910. approximation */
  154911. f->n=freq/nyq*blocksize;
  154912. /* this res may by limited by the maximum pointlimit of the mode,
  154913. not the lowpass. the floor is always lowpass limited. */
  154914. if(res->limit_type){
  154915. if(ci->hi.managed)
  154916. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  154917. else
  154918. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  154919. if(freq>nyq)freq=nyq;
  154920. }
  154921. /* in the residue, we're constrained, physically, by partition
  154922. boundaries. We still lowpass 'wherever', but we have to round up
  154923. here to next boundary, or the vorbis spec will round it *down* to
  154924. previous boundary in encode/decode */
  154925. if(ci->residue_type[block]==2)
  154926. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  154927. r->grouping;
  154928. else
  154929. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  154930. r->grouping;
  154931. }
  154932. }
  154933. /* we assume two maps in this encoder */
  154934. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  154935. vorbis_mapping_template *maps){
  154936. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154937. int i,j,is=s,modes=2;
  154938. vorbis_info_mapping0 *map=maps[is].map;
  154939. vorbis_info_mode *mode=_mode_template;
  154940. vorbis_residue_template *res=maps[is].res;
  154941. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  154942. for(i=0;i<modes;i++){
  154943. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  154944. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  154945. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  154946. if(i>=ci->modes)ci->modes=i+1;
  154947. ci->map_type[i]=0;
  154948. memcpy(ci->map_param[i],map+i,sizeof(*map));
  154949. if(i>=ci->maps)ci->maps=i+1;
  154950. for(j=0;j<map[i].submaps;j++)
  154951. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  154952. ,res+map[i].residuesubmap[j]);
  154953. }
  154954. }
  154955. static double setting_to_approx_bitrate(vorbis_info *vi){
  154956. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154957. highlevel_encode_setup *hi=&ci->hi;
  154958. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  154959. int is=hi->base_setting;
  154960. double ds=hi->base_setting-is;
  154961. int ch=vi->channels;
  154962. double *r=setup->rate_mapping;
  154963. if(r==NULL)
  154964. return(-1);
  154965. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  154966. }
  154967. static void get_setup_template(vorbis_info *vi,
  154968. long ch,long srate,
  154969. double req,int q_or_bitrate){
  154970. int i=0,j;
  154971. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154972. highlevel_encode_setup *hi=&ci->hi;
  154973. if(q_or_bitrate)req/=ch;
  154974. while(setup_list[i]){
  154975. if(setup_list[i]->coupling_restriction==-1 ||
  154976. setup_list[i]->coupling_restriction==ch){
  154977. if(srate>=setup_list[i]->samplerate_min_restriction &&
  154978. srate<=setup_list[i]->samplerate_max_restriction){
  154979. int mappings=setup_list[i]->mappings;
  154980. double *map=(q_or_bitrate?
  154981. setup_list[i]->rate_mapping:
  154982. setup_list[i]->quality_mapping);
  154983. /* the template matches. Does the requested quality mode
  154984. fall within this template's modes? */
  154985. if(req<map[0]){++i;continue;}
  154986. if(req>map[setup_list[i]->mappings]){++i;continue;}
  154987. for(j=0;j<mappings;j++)
  154988. if(req>=map[j] && req<map[j+1])break;
  154989. /* an all-points match */
  154990. hi->setup=setup_list[i];
  154991. if(j==mappings)
  154992. hi->base_setting=j-.001;
  154993. else{
  154994. float low=map[j];
  154995. float high=map[j+1];
  154996. float del=(req-low)/(high-low);
  154997. hi->base_setting=j+del;
  154998. }
  154999. return;
  155000. }
  155001. }
  155002. i++;
  155003. }
  155004. hi->setup=NULL;
  155005. }
  155006. /* encoders will need to use vorbis_info_init beforehand and call
  155007. vorbis_info clear when all done */
  155008. /* two interfaces; this, more detailed one, and later a convenience
  155009. layer on top */
  155010. /* the final setup call */
  155011. int vorbis_encode_setup_init(vorbis_info *vi){
  155012. int i0=0,singleblock=0;
  155013. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155014. ve_setup_data_template *setup=NULL;
  155015. highlevel_encode_setup *hi=&ci->hi;
  155016. if(ci==NULL)return(OV_EINVAL);
  155017. if(!hi->impulse_block_p)i0=1;
  155018. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  155019. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  155020. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  155021. /* again, bound this to avoid the app shooting itself int he foot
  155022. too badly */
  155023. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  155024. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  155025. /* get the appropriate setup template; matches the fetch in previous
  155026. stages */
  155027. setup=(ve_setup_data_template *)hi->setup;
  155028. if(setup==NULL)return(OV_EINVAL);
  155029. hi->set_in_stone=1;
  155030. /* choose block sizes from configured sizes as well as paying
  155031. attention to long_block_p and short_block_p. If the configured
  155032. short and long blocks are the same length, we set long_block_p
  155033. and unset short_block_p */
  155034. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  155035. setup->blocksize_short,
  155036. setup->blocksize_long);
  155037. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  155038. /* floor setup; choose proper floor params. Allocated on the floor
  155039. stack in order; if we alloc only long floor, it's 0 */
  155040. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  155041. setup->floor_books,
  155042. setup->floor_params,
  155043. setup->floor_short_mapping);
  155044. if(!singleblock)
  155045. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  155046. setup->floor_books,
  155047. setup->floor_params,
  155048. setup->floor_long_mapping);
  155049. /* setup of [mostly] short block detection and stereo*/
  155050. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  155051. setup->global_params,
  155052. setup->global_mapping);
  155053. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  155054. /* basic psych setup and noise normalization */
  155055. vorbis_encode_psyset_setup(vi,hi->short_setting,
  155056. setup->psy_noise_normal_start[0],
  155057. setup->psy_noise_normal_partition[0],
  155058. setup->psy_noise_normal_thresh,
  155059. 0);
  155060. vorbis_encode_psyset_setup(vi,hi->short_setting,
  155061. setup->psy_noise_normal_start[0],
  155062. setup->psy_noise_normal_partition[0],
  155063. setup->psy_noise_normal_thresh,
  155064. 1);
  155065. if(!singleblock){
  155066. vorbis_encode_psyset_setup(vi,hi->long_setting,
  155067. setup->psy_noise_normal_start[1],
  155068. setup->psy_noise_normal_partition[1],
  155069. setup->psy_noise_normal_thresh,
  155070. 2);
  155071. vorbis_encode_psyset_setup(vi,hi->long_setting,
  155072. setup->psy_noise_normal_start[1],
  155073. setup->psy_noise_normal_partition[1],
  155074. setup->psy_noise_normal_thresh,
  155075. 3);
  155076. }
  155077. /* tone masking setup */
  155078. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  155079. setup->psy_tone_masteratt,
  155080. setup->psy_tone_0dB,
  155081. setup->psy_tone_adj_impulse);
  155082. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  155083. setup->psy_tone_masteratt,
  155084. setup->psy_tone_0dB,
  155085. setup->psy_tone_adj_other);
  155086. if(!singleblock){
  155087. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  155088. setup->psy_tone_masteratt,
  155089. setup->psy_tone_0dB,
  155090. setup->psy_tone_adj_other);
  155091. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  155092. setup->psy_tone_masteratt,
  155093. setup->psy_tone_0dB,
  155094. setup->psy_tone_adj_long);
  155095. }
  155096. /* noise companding setup */
  155097. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  155098. setup->psy_noise_compand,
  155099. setup->psy_noise_compand_short_mapping);
  155100. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  155101. setup->psy_noise_compand,
  155102. setup->psy_noise_compand_short_mapping);
  155103. if(!singleblock){
  155104. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  155105. setup->psy_noise_compand,
  155106. setup->psy_noise_compand_long_mapping);
  155107. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  155108. setup->psy_noise_compand,
  155109. setup->psy_noise_compand_long_mapping);
  155110. }
  155111. /* peak guarding setup */
  155112. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  155113. setup->psy_tone_dBsuppress);
  155114. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  155115. setup->psy_tone_dBsuppress);
  155116. if(!singleblock){
  155117. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  155118. setup->psy_tone_dBsuppress);
  155119. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  155120. setup->psy_tone_dBsuppress);
  155121. }
  155122. /* noise bias setup */
  155123. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  155124. setup->psy_noise_dBsuppress,
  155125. setup->psy_noise_bias_impulse,
  155126. setup->psy_noiseguards,
  155127. (i0==0?hi->impulse_noisetune:0.));
  155128. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  155129. setup->psy_noise_dBsuppress,
  155130. setup->psy_noise_bias_padding,
  155131. setup->psy_noiseguards,0.);
  155132. if(!singleblock){
  155133. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  155134. setup->psy_noise_dBsuppress,
  155135. setup->psy_noise_bias_trans,
  155136. setup->psy_noiseguards,0.);
  155137. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  155138. setup->psy_noise_dBsuppress,
  155139. setup->psy_noise_bias_long,
  155140. setup->psy_noiseguards,0.);
  155141. }
  155142. vorbis_encode_ath_setup(vi,0);
  155143. vorbis_encode_ath_setup(vi,1);
  155144. if(!singleblock){
  155145. vorbis_encode_ath_setup(vi,2);
  155146. vorbis_encode_ath_setup(vi,3);
  155147. }
  155148. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  155149. /* set bitrate readonlies and management */
  155150. if(hi->bitrate_av>0)
  155151. vi->bitrate_nominal=hi->bitrate_av;
  155152. else{
  155153. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  155154. }
  155155. vi->bitrate_lower=hi->bitrate_min;
  155156. vi->bitrate_upper=hi->bitrate_max;
  155157. if(hi->bitrate_av)
  155158. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  155159. else
  155160. vi->bitrate_window=0.;
  155161. if(hi->managed){
  155162. ci->bi.avg_rate=hi->bitrate_av;
  155163. ci->bi.min_rate=hi->bitrate_min;
  155164. ci->bi.max_rate=hi->bitrate_max;
  155165. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  155166. ci->bi.reservoir_bias=
  155167. hi->bitrate_reservoir_bias;
  155168. ci->bi.slew_damp=hi->bitrate_av_damp;
  155169. }
  155170. return(0);
  155171. }
  155172. static int vorbis_encode_setup_setting(vorbis_info *vi,
  155173. long channels,
  155174. long rate){
  155175. int ret=0,i,is;
  155176. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155177. highlevel_encode_setup *hi=&ci->hi;
  155178. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  155179. double ds;
  155180. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  155181. if(ret)return(ret);
  155182. is=hi->base_setting;
  155183. ds=hi->base_setting-is;
  155184. hi->short_setting=hi->base_setting;
  155185. hi->long_setting=hi->base_setting;
  155186. hi->managed=0;
  155187. hi->impulse_block_p=1;
  155188. hi->noise_normalize_p=1;
  155189. hi->stereo_point_setting=hi->base_setting;
  155190. hi->lowpass_kHz=
  155191. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  155192. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  155193. setup->psy_ath_float[is+1]*ds;
  155194. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  155195. setup->psy_ath_abs[is+1]*ds;
  155196. hi->amplitude_track_dBpersec=-6.;
  155197. hi->trigger_setting=hi->base_setting;
  155198. for(i=0;i<4;i++){
  155199. hi->block[i].tone_mask_setting=hi->base_setting;
  155200. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  155201. hi->block[i].noise_bias_setting=hi->base_setting;
  155202. hi->block[i].noise_compand_setting=hi->base_setting;
  155203. }
  155204. return(ret);
  155205. }
  155206. int vorbis_encode_setup_vbr(vorbis_info *vi,
  155207. long channels,
  155208. long rate,
  155209. float quality){
  155210. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155211. highlevel_encode_setup *hi=&ci->hi;
  155212. quality+=.0000001;
  155213. if(quality>=1.)quality=.9999;
  155214. get_setup_template(vi,channels,rate,quality,0);
  155215. if(!hi->setup)return OV_EIMPL;
  155216. return vorbis_encode_setup_setting(vi,channels,rate);
  155217. }
  155218. int vorbis_encode_init_vbr(vorbis_info *vi,
  155219. long channels,
  155220. long rate,
  155221. float base_quality /* 0. to 1. */
  155222. ){
  155223. int ret=0;
  155224. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  155225. if(ret){
  155226. vorbis_info_clear(vi);
  155227. return ret;
  155228. }
  155229. ret=vorbis_encode_setup_init(vi);
  155230. if(ret)
  155231. vorbis_info_clear(vi);
  155232. return(ret);
  155233. }
  155234. int vorbis_encode_setup_managed(vorbis_info *vi,
  155235. long channels,
  155236. long rate,
  155237. long max_bitrate,
  155238. long nominal_bitrate,
  155239. long min_bitrate){
  155240. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155241. highlevel_encode_setup *hi=&ci->hi;
  155242. double tnominal=nominal_bitrate;
  155243. int ret=0;
  155244. if(nominal_bitrate<=0.){
  155245. if(max_bitrate>0.){
  155246. if(min_bitrate>0.)
  155247. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  155248. else
  155249. nominal_bitrate=max_bitrate*.875;
  155250. }else{
  155251. if(min_bitrate>0.){
  155252. nominal_bitrate=min_bitrate;
  155253. }else{
  155254. return(OV_EINVAL);
  155255. }
  155256. }
  155257. }
  155258. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  155259. if(!hi->setup)return OV_EIMPL;
  155260. ret=vorbis_encode_setup_setting(vi,channels,rate);
  155261. if(ret){
  155262. vorbis_info_clear(vi);
  155263. return ret;
  155264. }
  155265. /* initialize management with sane defaults */
  155266. hi->managed=1;
  155267. hi->bitrate_min=min_bitrate;
  155268. hi->bitrate_max=max_bitrate;
  155269. hi->bitrate_av=tnominal;
  155270. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  155271. hi->bitrate_reservoir=nominal_bitrate*2;
  155272. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  155273. return(ret);
  155274. }
  155275. int vorbis_encode_init(vorbis_info *vi,
  155276. long channels,
  155277. long rate,
  155278. long max_bitrate,
  155279. long nominal_bitrate,
  155280. long min_bitrate){
  155281. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  155282. max_bitrate,
  155283. nominal_bitrate,
  155284. min_bitrate);
  155285. if(ret){
  155286. vorbis_info_clear(vi);
  155287. return(ret);
  155288. }
  155289. ret=vorbis_encode_setup_init(vi);
  155290. if(ret)
  155291. vorbis_info_clear(vi);
  155292. return(ret);
  155293. }
  155294. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  155295. if(vi){
  155296. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155297. highlevel_encode_setup *hi=&ci->hi;
  155298. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  155299. if(setp && hi->set_in_stone)return(OV_EINVAL);
  155300. switch(number){
  155301. /* now deprecated *****************/
  155302. case OV_ECTL_RATEMANAGE_GET:
  155303. {
  155304. struct ovectl_ratemanage_arg *ai=
  155305. (struct ovectl_ratemanage_arg *)arg;
  155306. ai->management_active=hi->managed;
  155307. ai->bitrate_hard_window=ai->bitrate_av_window=
  155308. (double)hi->bitrate_reservoir/vi->rate;
  155309. ai->bitrate_av_window_center=1.;
  155310. ai->bitrate_hard_min=hi->bitrate_min;
  155311. ai->bitrate_hard_max=hi->bitrate_max;
  155312. ai->bitrate_av_lo=hi->bitrate_av;
  155313. ai->bitrate_av_hi=hi->bitrate_av;
  155314. }
  155315. return(0);
  155316. /* now deprecated *****************/
  155317. case OV_ECTL_RATEMANAGE_SET:
  155318. {
  155319. struct ovectl_ratemanage_arg *ai=
  155320. (struct ovectl_ratemanage_arg *)arg;
  155321. if(ai==NULL){
  155322. hi->managed=0;
  155323. }else{
  155324. hi->managed=ai->management_active;
  155325. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  155326. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  155327. }
  155328. }
  155329. return 0;
  155330. /* now deprecated *****************/
  155331. case OV_ECTL_RATEMANAGE_AVG:
  155332. {
  155333. struct ovectl_ratemanage_arg *ai=
  155334. (struct ovectl_ratemanage_arg *)arg;
  155335. if(ai==NULL){
  155336. hi->bitrate_av=0;
  155337. }else{
  155338. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  155339. }
  155340. }
  155341. return(0);
  155342. /* now deprecated *****************/
  155343. case OV_ECTL_RATEMANAGE_HARD:
  155344. {
  155345. struct ovectl_ratemanage_arg *ai=
  155346. (struct ovectl_ratemanage_arg *)arg;
  155347. if(ai==NULL){
  155348. hi->bitrate_min=0;
  155349. hi->bitrate_max=0;
  155350. }else{
  155351. hi->bitrate_min=ai->bitrate_hard_min;
  155352. hi->bitrate_max=ai->bitrate_hard_max;
  155353. hi->bitrate_reservoir=ai->bitrate_hard_window*
  155354. (hi->bitrate_max+hi->bitrate_min)*.5;
  155355. }
  155356. if(hi->bitrate_reservoir<128.)
  155357. hi->bitrate_reservoir=128.;
  155358. }
  155359. return(0);
  155360. /* replacement ratemanage interface */
  155361. case OV_ECTL_RATEMANAGE2_GET:
  155362. {
  155363. struct ovectl_ratemanage2_arg *ai=
  155364. (struct ovectl_ratemanage2_arg *)arg;
  155365. if(ai==NULL)return OV_EINVAL;
  155366. ai->management_active=hi->managed;
  155367. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  155368. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  155369. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  155370. ai->bitrate_average_damping=hi->bitrate_av_damp;
  155371. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  155372. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  155373. }
  155374. return (0);
  155375. case OV_ECTL_RATEMANAGE2_SET:
  155376. {
  155377. struct ovectl_ratemanage2_arg *ai=
  155378. (struct ovectl_ratemanage2_arg *)arg;
  155379. if(ai==NULL){
  155380. hi->managed=0;
  155381. }else{
  155382. /* sanity check; only catch invariant violations */
  155383. if(ai->bitrate_limit_min_kbps>0 &&
  155384. ai->bitrate_average_kbps>0 &&
  155385. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  155386. return OV_EINVAL;
  155387. if(ai->bitrate_limit_max_kbps>0 &&
  155388. ai->bitrate_average_kbps>0 &&
  155389. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  155390. return OV_EINVAL;
  155391. if(ai->bitrate_limit_min_kbps>0 &&
  155392. ai->bitrate_limit_max_kbps>0 &&
  155393. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  155394. return OV_EINVAL;
  155395. if(ai->bitrate_average_damping <= 0.)
  155396. return OV_EINVAL;
  155397. if(ai->bitrate_limit_reservoir_bits < 0)
  155398. return OV_EINVAL;
  155399. if(ai->bitrate_limit_reservoir_bias < 0.)
  155400. return OV_EINVAL;
  155401. if(ai->bitrate_limit_reservoir_bias > 1.)
  155402. return OV_EINVAL;
  155403. hi->managed=ai->management_active;
  155404. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  155405. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  155406. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  155407. hi->bitrate_av_damp=ai->bitrate_average_damping;
  155408. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  155409. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  155410. }
  155411. }
  155412. return 0;
  155413. case OV_ECTL_LOWPASS_GET:
  155414. {
  155415. double *farg=(double *)arg;
  155416. *farg=hi->lowpass_kHz;
  155417. }
  155418. return(0);
  155419. case OV_ECTL_LOWPASS_SET:
  155420. {
  155421. double *farg=(double *)arg;
  155422. hi->lowpass_kHz=*farg;
  155423. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  155424. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  155425. }
  155426. return(0);
  155427. case OV_ECTL_IBLOCK_GET:
  155428. {
  155429. double *farg=(double *)arg;
  155430. *farg=hi->impulse_noisetune;
  155431. }
  155432. return(0);
  155433. case OV_ECTL_IBLOCK_SET:
  155434. {
  155435. double *farg=(double *)arg;
  155436. hi->impulse_noisetune=*farg;
  155437. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  155438. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  155439. }
  155440. return(0);
  155441. }
  155442. return(OV_EIMPL);
  155443. }
  155444. return(OV_EINVAL);
  155445. }
  155446. #endif
  155447. /*** End of inlined file: vorbisenc.c ***/
  155448. /*** Start of inlined file: vorbisfile.c ***/
  155449. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  155450. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  155451. // tasks..
  155452. #if JUCE_MSVC
  155453. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  155454. #endif
  155455. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  155456. #if JUCE_USE_OGGVORBIS
  155457. #include <stdlib.h>
  155458. #include <stdio.h>
  155459. #include <errno.h>
  155460. #include <string.h>
  155461. #include <math.h>
  155462. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  155463. one logical bitstream arranged end to end (the only form of Ogg
  155464. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  155465. multiplexing] is not allowed in Vorbis) */
  155466. /* A Vorbis file can be played beginning to end (streamed) without
  155467. worrying ahead of time about chaining (see decoder_example.c). If
  155468. we have the whole file, however, and want random access
  155469. (seeking/scrubbing) or desire to know the total length/time of a
  155470. file, we need to account for the possibility of chaining. */
  155471. /* We can handle things a number of ways; we can determine the entire
  155472. bitstream structure right off the bat, or find pieces on demand.
  155473. This example determines and caches structure for the entire
  155474. bitstream, but builds a virtual decoder on the fly when moving
  155475. between links in the chain. */
  155476. /* There are also different ways to implement seeking. Enough
  155477. information exists in an Ogg bitstream to seek to
  155478. sample-granularity positions in the output. Or, one can seek by
  155479. picking some portion of the stream roughly in the desired area if
  155480. we only want coarse navigation through the stream. */
  155481. /*************************************************************************
  155482. * Many, many internal helpers. The intention is not to be confusing;
  155483. * rampant duplication and monolithic function implementation would be
  155484. * harder to understand anyway. The high level functions are last. Begin
  155485. * grokking near the end of the file */
  155486. /* read a little more data from the file/pipe into the ogg_sync framer
  155487. */
  155488. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  155489. over 8k gets what they deserve */
  155490. static long _get_data(OggVorbis_File *vf){
  155491. errno=0;
  155492. if(vf->datasource){
  155493. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  155494. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  155495. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  155496. if(bytes==0 && errno)return(-1);
  155497. return(bytes);
  155498. }else
  155499. return(0);
  155500. }
  155501. /* save a tiny smidge of verbosity to make the code more readable */
  155502. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  155503. if(vf->datasource){
  155504. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  155505. vf->offset=offset;
  155506. ogg_sync_reset(&vf->oy);
  155507. }else{
  155508. /* shouldn't happen unless someone writes a broken callback */
  155509. return;
  155510. }
  155511. }
  155512. /* The read/seek functions track absolute position within the stream */
  155513. /* from the head of the stream, get the next page. boundary specifies
  155514. if the function is allowed to fetch more data from the stream (and
  155515. how much) or only use internally buffered data.
  155516. boundary: -1) unbounded search
  155517. 0) read no additional data; use cached only
  155518. n) search for a new page beginning for n bytes
  155519. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  155520. n) found a page at absolute offset n */
  155521. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  155522. ogg_int64_t boundary){
  155523. if(boundary>0)boundary+=vf->offset;
  155524. while(1){
  155525. long more;
  155526. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  155527. more=ogg_sync_pageseek(&vf->oy,og);
  155528. if(more<0){
  155529. /* skipped n bytes */
  155530. vf->offset-=more;
  155531. }else{
  155532. if(more==0){
  155533. /* send more paramedics */
  155534. if(!boundary)return(OV_FALSE);
  155535. {
  155536. long ret=_get_data(vf);
  155537. if(ret==0)return(OV_EOF);
  155538. if(ret<0)return(OV_EREAD);
  155539. }
  155540. }else{
  155541. /* got a page. Return the offset at the page beginning,
  155542. advance the internal offset past the page end */
  155543. ogg_int64_t ret=vf->offset;
  155544. vf->offset+=more;
  155545. return(ret);
  155546. }
  155547. }
  155548. }
  155549. }
  155550. /* find the latest page beginning before the current stream cursor
  155551. position. Much dirtier than the above as Ogg doesn't have any
  155552. backward search linkage. no 'readp' as it will certainly have to
  155553. read. */
  155554. /* returns offset or OV_EREAD, OV_FAULT */
  155555. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  155556. ogg_int64_t begin=vf->offset;
  155557. ogg_int64_t end=begin;
  155558. ogg_int64_t ret;
  155559. ogg_int64_t offset=-1;
  155560. while(offset==-1){
  155561. begin-=CHUNKSIZE;
  155562. if(begin<0)
  155563. begin=0;
  155564. _seek_helper(vf,begin);
  155565. while(vf->offset<end){
  155566. ret=_get_next_page(vf,og,end-vf->offset);
  155567. if(ret==OV_EREAD)return(OV_EREAD);
  155568. if(ret<0){
  155569. break;
  155570. }else{
  155571. offset=ret;
  155572. }
  155573. }
  155574. }
  155575. /* we have the offset. Actually snork and hold the page now */
  155576. _seek_helper(vf,offset);
  155577. ret=_get_next_page(vf,og,CHUNKSIZE);
  155578. if(ret<0)
  155579. /* this shouldn't be possible */
  155580. return(OV_EFAULT);
  155581. return(offset);
  155582. }
  155583. /* finds each bitstream link one at a time using a bisection search
  155584. (has to begin by knowing the offset of the lb's initial page).
  155585. Recurses for each link so it can alloc the link storage after
  155586. finding them all, then unroll and fill the cache at the same time */
  155587. static int _bisect_forward_serialno(OggVorbis_File *vf,
  155588. ogg_int64_t begin,
  155589. ogg_int64_t searched,
  155590. ogg_int64_t end,
  155591. long currentno,
  155592. long m){
  155593. ogg_int64_t endsearched=end;
  155594. ogg_int64_t next=end;
  155595. ogg_page og;
  155596. ogg_int64_t ret;
  155597. /* the below guards against garbage seperating the last and
  155598. first pages of two links. */
  155599. while(searched<endsearched){
  155600. ogg_int64_t bisect;
  155601. if(endsearched-searched<CHUNKSIZE){
  155602. bisect=searched;
  155603. }else{
  155604. bisect=(searched+endsearched)/2;
  155605. }
  155606. _seek_helper(vf,bisect);
  155607. ret=_get_next_page(vf,&og,-1);
  155608. if(ret==OV_EREAD)return(OV_EREAD);
  155609. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  155610. endsearched=bisect;
  155611. if(ret>=0)next=ret;
  155612. }else{
  155613. searched=ret+og.header_len+og.body_len;
  155614. }
  155615. }
  155616. _seek_helper(vf,next);
  155617. ret=_get_next_page(vf,&og,-1);
  155618. if(ret==OV_EREAD)return(OV_EREAD);
  155619. if(searched>=end || ret<0){
  155620. vf->links=m+1;
  155621. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  155622. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  155623. vf->offsets[m+1]=searched;
  155624. }else{
  155625. ret=_bisect_forward_serialno(vf,next,vf->offset,
  155626. end,ogg_page_serialno(&og),m+1);
  155627. if(ret==OV_EREAD)return(OV_EREAD);
  155628. }
  155629. vf->offsets[m]=begin;
  155630. vf->serialnos[m]=currentno;
  155631. return(0);
  155632. }
  155633. /* uses the local ogg_stream storage in vf; this is important for
  155634. non-streaming input sources */
  155635. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  155636. long *serialno,ogg_page *og_ptr){
  155637. ogg_page og;
  155638. ogg_packet op;
  155639. int i,ret;
  155640. if(!og_ptr){
  155641. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  155642. if(llret==OV_EREAD)return(OV_EREAD);
  155643. if(llret<0)return OV_ENOTVORBIS;
  155644. og_ptr=&og;
  155645. }
  155646. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  155647. if(serialno)*serialno=vf->os.serialno;
  155648. vf->ready_state=STREAMSET;
  155649. /* extract the initial header from the first page and verify that the
  155650. Ogg bitstream is in fact Vorbis data */
  155651. vorbis_info_init(vi);
  155652. vorbis_comment_init(vc);
  155653. i=0;
  155654. while(i<3){
  155655. ogg_stream_pagein(&vf->os,og_ptr);
  155656. while(i<3){
  155657. int result=ogg_stream_packetout(&vf->os,&op);
  155658. if(result==0)break;
  155659. if(result==-1){
  155660. ret=OV_EBADHEADER;
  155661. goto bail_header;
  155662. }
  155663. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  155664. goto bail_header;
  155665. }
  155666. i++;
  155667. }
  155668. if(i<3)
  155669. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  155670. ret=OV_EBADHEADER;
  155671. goto bail_header;
  155672. }
  155673. }
  155674. return 0;
  155675. bail_header:
  155676. vorbis_info_clear(vi);
  155677. vorbis_comment_clear(vc);
  155678. vf->ready_state=OPENED;
  155679. return ret;
  155680. }
  155681. /* last step of the OggVorbis_File initialization; get all the
  155682. vorbis_info structs and PCM positions. Only called by the seekable
  155683. initialization (local stream storage is hacked slightly; pay
  155684. attention to how that's done) */
  155685. /* this is void and does not propogate errors up because we want to be
  155686. able to open and use damaged bitstreams as well as we can. Just
  155687. watch out for missing information for links in the OggVorbis_File
  155688. struct */
  155689. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  155690. ogg_page og;
  155691. int i;
  155692. ogg_int64_t ret;
  155693. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  155694. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  155695. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  155696. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  155697. for(i=0;i<vf->links;i++){
  155698. if(i==0){
  155699. /* we already grabbed the initial header earlier. Just set the offset */
  155700. vf->dataoffsets[i]=dataoffset;
  155701. _seek_helper(vf,dataoffset);
  155702. }else{
  155703. /* seek to the location of the initial header */
  155704. _seek_helper(vf,vf->offsets[i]);
  155705. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  155706. vf->dataoffsets[i]=-1;
  155707. }else{
  155708. vf->dataoffsets[i]=vf->offset;
  155709. }
  155710. }
  155711. /* fetch beginning PCM offset */
  155712. if(vf->dataoffsets[i]!=-1){
  155713. ogg_int64_t accumulated=0;
  155714. long lastblock=-1;
  155715. int result;
  155716. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  155717. while(1){
  155718. ogg_packet op;
  155719. ret=_get_next_page(vf,&og,-1);
  155720. if(ret<0)
  155721. /* this should not be possible unless the file is
  155722. truncated/mangled */
  155723. break;
  155724. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  155725. break;
  155726. /* count blocksizes of all frames in the page */
  155727. ogg_stream_pagein(&vf->os,&og);
  155728. while((result=ogg_stream_packetout(&vf->os,&op))){
  155729. if(result>0){ /* ignore holes */
  155730. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  155731. if(lastblock!=-1)
  155732. accumulated+=(lastblock+thisblock)>>2;
  155733. lastblock=thisblock;
  155734. }
  155735. }
  155736. if(ogg_page_granulepos(&og)!=-1){
  155737. /* pcm offset of last packet on the first audio page */
  155738. accumulated= ogg_page_granulepos(&og)-accumulated;
  155739. break;
  155740. }
  155741. }
  155742. /* less than zero? This is a stream with samples trimmed off
  155743. the beginning, a normal occurrence; set the offset to zero */
  155744. if(accumulated<0)accumulated=0;
  155745. vf->pcmlengths[i*2]=accumulated;
  155746. }
  155747. /* get the PCM length of this link. To do this,
  155748. get the last page of the stream */
  155749. {
  155750. ogg_int64_t end=vf->offsets[i+1];
  155751. _seek_helper(vf,end);
  155752. while(1){
  155753. ret=_get_prev_page(vf,&og);
  155754. if(ret<0){
  155755. /* this should not be possible */
  155756. vorbis_info_clear(vf->vi+i);
  155757. vorbis_comment_clear(vf->vc+i);
  155758. break;
  155759. }
  155760. if(ogg_page_granulepos(&og)!=-1){
  155761. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  155762. break;
  155763. }
  155764. vf->offset=ret;
  155765. }
  155766. }
  155767. }
  155768. }
  155769. static int _make_decode_ready(OggVorbis_File *vf){
  155770. if(vf->ready_state>STREAMSET)return 0;
  155771. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  155772. if(vf->seekable){
  155773. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  155774. return OV_EBADLINK;
  155775. }else{
  155776. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  155777. return OV_EBADLINK;
  155778. }
  155779. vorbis_block_init(&vf->vd,&vf->vb);
  155780. vf->ready_state=INITSET;
  155781. vf->bittrack=0.f;
  155782. vf->samptrack=0.f;
  155783. return 0;
  155784. }
  155785. static int _open_seekable2(OggVorbis_File *vf){
  155786. long serialno=vf->current_serialno;
  155787. ogg_int64_t dataoffset=vf->offset, end;
  155788. ogg_page og;
  155789. /* we're partially open and have a first link header state in
  155790. storage in vf */
  155791. /* we can seek, so set out learning all about this file */
  155792. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  155793. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  155794. /* We get the offset for the last page of the physical bitstream.
  155795. Most OggVorbis files will contain a single logical bitstream */
  155796. end=_get_prev_page(vf,&og);
  155797. if(end<0)return(end);
  155798. /* more than one logical bitstream? */
  155799. if(ogg_page_serialno(&og)!=serialno){
  155800. /* Chained bitstream. Bisect-search each logical bitstream
  155801. section. Do so based on serial number only */
  155802. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  155803. }else{
  155804. /* Only one logical bitstream */
  155805. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  155806. }
  155807. /* the initial header memory is referenced by vf after; don't free it */
  155808. _prefetch_all_headers(vf,dataoffset);
  155809. return(ov_raw_seek(vf,0));
  155810. }
  155811. /* clear out the current logical bitstream decoder */
  155812. static void _decode_clear(OggVorbis_File *vf){
  155813. vorbis_dsp_clear(&vf->vd);
  155814. vorbis_block_clear(&vf->vb);
  155815. vf->ready_state=OPENED;
  155816. }
  155817. /* fetch and process a packet. Handles the case where we're at a
  155818. bitstream boundary and dumps the decoding machine. If the decoding
  155819. machine is unloaded, it loads it. It also keeps pcm_offset up to
  155820. date (seek and read both use this. seek uses a special hack with
  155821. readp).
  155822. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  155823. 0) need more data (only if readp==0)
  155824. 1) got a packet
  155825. */
  155826. static int _fetch_and_process_packet(OggVorbis_File *vf,
  155827. ogg_packet *op_in,
  155828. int readp,
  155829. int spanp){
  155830. ogg_page og;
  155831. /* handle one packet. Try to fetch it from current stream state */
  155832. /* extract packets from page */
  155833. while(1){
  155834. /* process a packet if we can. If the machine isn't loaded,
  155835. neither is a page */
  155836. if(vf->ready_state==INITSET){
  155837. while(1) {
  155838. ogg_packet op;
  155839. ogg_packet *op_ptr=(op_in?op_in:&op);
  155840. int result=ogg_stream_packetout(&vf->os,op_ptr);
  155841. ogg_int64_t granulepos;
  155842. op_in=NULL;
  155843. if(result==-1)return(OV_HOLE); /* hole in the data. */
  155844. if(result>0){
  155845. /* got a packet. process it */
  155846. granulepos=op_ptr->granulepos;
  155847. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  155848. header handling. The
  155849. header packets aren't
  155850. audio, so if/when we
  155851. submit them,
  155852. vorbis_synthesis will
  155853. reject them */
  155854. /* suck in the synthesis data and track bitrate */
  155855. {
  155856. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155857. /* for proper use of libvorbis within libvorbisfile,
  155858. oldsamples will always be zero. */
  155859. if(oldsamples)return(OV_EFAULT);
  155860. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  155861. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  155862. vf->bittrack+=op_ptr->bytes*8;
  155863. }
  155864. /* update the pcm offset. */
  155865. if(granulepos!=-1 && !op_ptr->e_o_s){
  155866. int link=(vf->seekable?vf->current_link:0);
  155867. int i,samples;
  155868. /* this packet has a pcm_offset on it (the last packet
  155869. completed on a page carries the offset) After processing
  155870. (above), we know the pcm position of the *last* sample
  155871. ready to be returned. Find the offset of the *first*
  155872. As an aside, this trick is inaccurate if we begin
  155873. reading anew right at the last page; the end-of-stream
  155874. granulepos declares the last frame in the stream, and the
  155875. last packet of the last page may be a partial frame.
  155876. So, we need a previous granulepos from an in-sequence page
  155877. to have a reference point. Thus the !op_ptr->e_o_s clause
  155878. above */
  155879. if(vf->seekable && link>0)
  155880. granulepos-=vf->pcmlengths[link*2];
  155881. if(granulepos<0)granulepos=0; /* actually, this
  155882. shouldn't be possible
  155883. here unless the stream
  155884. is very broken */
  155885. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  155886. granulepos-=samples;
  155887. for(i=0;i<link;i++)
  155888. granulepos+=vf->pcmlengths[i*2+1];
  155889. vf->pcm_offset=granulepos;
  155890. }
  155891. return(1);
  155892. }
  155893. }
  155894. else
  155895. break;
  155896. }
  155897. }
  155898. if(vf->ready_state>=OPENED){
  155899. ogg_int64_t ret;
  155900. if(!readp)return(0);
  155901. if((ret=_get_next_page(vf,&og,-1))<0){
  155902. return(OV_EOF); /* eof.
  155903. leave unitialized */
  155904. }
  155905. /* bitrate tracking; add the header's bytes here, the body bytes
  155906. are done by packet above */
  155907. vf->bittrack+=og.header_len*8;
  155908. /* has our decoding just traversed a bitstream boundary? */
  155909. if(vf->ready_state==INITSET){
  155910. if(vf->current_serialno!=ogg_page_serialno(&og)){
  155911. if(!spanp)
  155912. return(OV_EOF);
  155913. _decode_clear(vf);
  155914. if(!vf->seekable){
  155915. vorbis_info_clear(vf->vi);
  155916. vorbis_comment_clear(vf->vc);
  155917. }
  155918. }
  155919. }
  155920. }
  155921. /* Do we need to load a new machine before submitting the page? */
  155922. /* This is different in the seekable and non-seekable cases.
  155923. In the seekable case, we already have all the header
  155924. information loaded and cached; we just initialize the machine
  155925. with it and continue on our merry way.
  155926. In the non-seekable (streaming) case, we'll only be at a
  155927. boundary if we just left the previous logical bitstream and
  155928. we're now nominally at the header of the next bitstream
  155929. */
  155930. if(vf->ready_state!=INITSET){
  155931. int link;
  155932. if(vf->ready_state<STREAMSET){
  155933. if(vf->seekable){
  155934. vf->current_serialno=ogg_page_serialno(&og);
  155935. /* match the serialno to bitstream section. We use this rather than
  155936. offset positions to avoid problems near logical bitstream
  155937. boundaries */
  155938. for(link=0;link<vf->links;link++)
  155939. if(vf->serialnos[link]==vf->current_serialno)break;
  155940. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  155941. stream. error out,
  155942. leave machine
  155943. uninitialized */
  155944. vf->current_link=link;
  155945. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  155946. vf->ready_state=STREAMSET;
  155947. }else{
  155948. /* we're streaming */
  155949. /* fetch the three header packets, build the info struct */
  155950. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  155951. if(ret)return(ret);
  155952. vf->current_link++;
  155953. link=0;
  155954. }
  155955. }
  155956. {
  155957. int ret=_make_decode_ready(vf);
  155958. if(ret<0)return ret;
  155959. }
  155960. }
  155961. ogg_stream_pagein(&vf->os,&og);
  155962. }
  155963. }
  155964. /* if, eg, 64 bit stdio is configured by default, this will build with
  155965. fseek64 */
  155966. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  155967. if(f==NULL)return(-1);
  155968. return fseek(f,off,whence);
  155969. }
  155970. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  155971. long ibytes, ov_callbacks callbacks){
  155972. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  155973. int ret;
  155974. memset(vf,0,sizeof(*vf));
  155975. vf->datasource=f;
  155976. vf->callbacks = callbacks;
  155977. /* init the framing state */
  155978. ogg_sync_init(&vf->oy);
  155979. /* perhaps some data was previously read into a buffer for testing
  155980. against other stream types. Allow initialization from this
  155981. previously read data (as we may be reading from a non-seekable
  155982. stream) */
  155983. if(initial){
  155984. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  155985. memcpy(buffer,initial,ibytes);
  155986. ogg_sync_wrote(&vf->oy,ibytes);
  155987. }
  155988. /* can we seek? Stevens suggests the seek test was portable */
  155989. if(offsettest!=-1)vf->seekable=1;
  155990. /* No seeking yet; Set up a 'single' (current) logical bitstream
  155991. entry for partial open */
  155992. vf->links=1;
  155993. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  155994. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  155995. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  155996. /* Try to fetch the headers, maintaining all the storage */
  155997. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  155998. vf->datasource=NULL;
  155999. ov_clear(vf);
  156000. }else
  156001. vf->ready_state=PARTOPEN;
  156002. return(ret);
  156003. }
  156004. static int _ov_open2(OggVorbis_File *vf){
  156005. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  156006. vf->ready_state=OPENED;
  156007. if(vf->seekable){
  156008. int ret=_open_seekable2(vf);
  156009. if(ret){
  156010. vf->datasource=NULL;
  156011. ov_clear(vf);
  156012. }
  156013. return(ret);
  156014. }else
  156015. vf->ready_state=STREAMSET;
  156016. return 0;
  156017. }
  156018. /* clear out the OggVorbis_File struct */
  156019. int ov_clear(OggVorbis_File *vf){
  156020. if(vf){
  156021. vorbis_block_clear(&vf->vb);
  156022. vorbis_dsp_clear(&vf->vd);
  156023. ogg_stream_clear(&vf->os);
  156024. if(vf->vi && vf->links){
  156025. int i;
  156026. for(i=0;i<vf->links;i++){
  156027. vorbis_info_clear(vf->vi+i);
  156028. vorbis_comment_clear(vf->vc+i);
  156029. }
  156030. _ogg_free(vf->vi);
  156031. _ogg_free(vf->vc);
  156032. }
  156033. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  156034. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  156035. if(vf->serialnos)_ogg_free(vf->serialnos);
  156036. if(vf->offsets)_ogg_free(vf->offsets);
  156037. ogg_sync_clear(&vf->oy);
  156038. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  156039. memset(vf,0,sizeof(*vf));
  156040. }
  156041. #ifdef DEBUG_LEAKS
  156042. _VDBG_dump();
  156043. #endif
  156044. return(0);
  156045. }
  156046. /* inspects the OggVorbis file and finds/documents all the logical
  156047. bitstreams contained in it. Tries to be tolerant of logical
  156048. bitstream sections that are truncated/woogie.
  156049. return: -1) error
  156050. 0) OK
  156051. */
  156052. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  156053. ov_callbacks callbacks){
  156054. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  156055. if(ret)return ret;
  156056. return _ov_open2(vf);
  156057. }
  156058. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  156059. ov_callbacks callbacks = {
  156060. (size_t (*)(void *, size_t, size_t, void *)) fread,
  156061. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  156062. (int (*)(void *)) fclose,
  156063. (long (*)(void *)) ftell
  156064. };
  156065. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  156066. }
  156067. /* cheap hack for game usage where downsampling is desirable; there's
  156068. no need for SRC as we can just do it cheaply in libvorbis. */
  156069. int ov_halfrate(OggVorbis_File *vf,int flag){
  156070. int i;
  156071. if(vf->vi==NULL)return OV_EINVAL;
  156072. if(!vf->seekable)return OV_EINVAL;
  156073. if(vf->ready_state>=STREAMSET)
  156074. _decode_clear(vf); /* clear out stream state; later on libvorbis
  156075. will be able to swap this on the fly, but
  156076. for now dumping the decode machine is needed
  156077. to reinit the MDCT lookups. 1.1 libvorbis
  156078. is planned to be able to switch on the fly */
  156079. for(i=0;i<vf->links;i++){
  156080. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  156081. ov_halfrate(vf,0);
  156082. return OV_EINVAL;
  156083. }
  156084. }
  156085. return 0;
  156086. }
  156087. int ov_halfrate_p(OggVorbis_File *vf){
  156088. if(vf->vi==NULL)return OV_EINVAL;
  156089. return vorbis_synthesis_halfrate_p(vf->vi);
  156090. }
  156091. /* Only partially open the vorbis file; test for Vorbisness, and load
  156092. the headers for the first chain. Do not seek (although test for
  156093. seekability). Use ov_test_open to finish opening the file, else
  156094. ov_clear to close/free it. Same return codes as open. */
  156095. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  156096. ov_callbacks callbacks)
  156097. {
  156098. return _ov_open1(f,vf,initial,ibytes,callbacks);
  156099. }
  156100. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  156101. ov_callbacks callbacks = {
  156102. (size_t (*)(void *, size_t, size_t, void *)) fread,
  156103. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  156104. (int (*)(void *)) fclose,
  156105. (long (*)(void *)) ftell
  156106. };
  156107. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  156108. }
  156109. int ov_test_open(OggVorbis_File *vf){
  156110. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  156111. return _ov_open2(vf);
  156112. }
  156113. /* How many logical bitstreams in this physical bitstream? */
  156114. long ov_streams(OggVorbis_File *vf){
  156115. return vf->links;
  156116. }
  156117. /* Is the FILE * associated with vf seekable? */
  156118. long ov_seekable(OggVorbis_File *vf){
  156119. return vf->seekable;
  156120. }
  156121. /* returns the bitrate for a given logical bitstream or the entire
  156122. physical bitstream. If the file is open for random access, it will
  156123. find the *actual* average bitrate. If the file is streaming, it
  156124. returns the nominal bitrate (if set) else the average of the
  156125. upper/lower bounds (if set) else -1 (unset).
  156126. If you want the actual bitrate field settings, get them from the
  156127. vorbis_info structs */
  156128. long ov_bitrate(OggVorbis_File *vf,int i){
  156129. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156130. if(i>=vf->links)return(OV_EINVAL);
  156131. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  156132. if(i<0){
  156133. ogg_int64_t bits=0;
  156134. int i;
  156135. float br;
  156136. for(i=0;i<vf->links;i++)
  156137. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  156138. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  156139. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  156140. * so this is slightly transformed to make it work.
  156141. */
  156142. br = bits/ov_time_total(vf,-1);
  156143. return(rint(br));
  156144. }else{
  156145. if(vf->seekable){
  156146. /* return the actual bitrate */
  156147. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  156148. }else{
  156149. /* return nominal if set */
  156150. if(vf->vi[i].bitrate_nominal>0){
  156151. return vf->vi[i].bitrate_nominal;
  156152. }else{
  156153. if(vf->vi[i].bitrate_upper>0){
  156154. if(vf->vi[i].bitrate_lower>0){
  156155. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  156156. }else{
  156157. return vf->vi[i].bitrate_upper;
  156158. }
  156159. }
  156160. return(OV_FALSE);
  156161. }
  156162. }
  156163. }
  156164. }
  156165. /* returns the actual bitrate since last call. returns -1 if no
  156166. additional data to offer since last call (or at beginning of stream),
  156167. EINVAL if stream is only partially open
  156168. */
  156169. long ov_bitrate_instant(OggVorbis_File *vf){
  156170. int link=(vf->seekable?vf->current_link:0);
  156171. long ret;
  156172. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156173. if(vf->samptrack==0)return(OV_FALSE);
  156174. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  156175. vf->bittrack=0.f;
  156176. vf->samptrack=0.f;
  156177. return(ret);
  156178. }
  156179. /* Guess */
  156180. long ov_serialnumber(OggVorbis_File *vf,int i){
  156181. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  156182. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  156183. if(i<0){
  156184. return(vf->current_serialno);
  156185. }else{
  156186. return(vf->serialnos[i]);
  156187. }
  156188. }
  156189. /* returns: total raw (compressed) length of content if i==-1
  156190. raw (compressed) length of that logical bitstream for i==0 to n
  156191. OV_EINVAL if the stream is not seekable (we can't know the length)
  156192. or if stream is only partially open
  156193. */
  156194. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  156195. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156196. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156197. if(i<0){
  156198. ogg_int64_t acc=0;
  156199. int i;
  156200. for(i=0;i<vf->links;i++)
  156201. acc+=ov_raw_total(vf,i);
  156202. return(acc);
  156203. }else{
  156204. return(vf->offsets[i+1]-vf->offsets[i]);
  156205. }
  156206. }
  156207. /* returns: total PCM length (samples) of content if i==-1 PCM length
  156208. (samples) of that logical bitstream for i==0 to n
  156209. OV_EINVAL if the stream is not seekable (we can't know the
  156210. length) or only partially open
  156211. */
  156212. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  156213. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156214. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156215. if(i<0){
  156216. ogg_int64_t acc=0;
  156217. int i;
  156218. for(i=0;i<vf->links;i++)
  156219. acc+=ov_pcm_total(vf,i);
  156220. return(acc);
  156221. }else{
  156222. return(vf->pcmlengths[i*2+1]);
  156223. }
  156224. }
  156225. /* returns: total seconds of content if i==-1
  156226. seconds in that logical bitstream for i==0 to n
  156227. OV_EINVAL if the stream is not seekable (we can't know the
  156228. length) or only partially open
  156229. */
  156230. double ov_time_total(OggVorbis_File *vf,int i){
  156231. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156232. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156233. if(i<0){
  156234. double acc=0;
  156235. int i;
  156236. for(i=0;i<vf->links;i++)
  156237. acc+=ov_time_total(vf,i);
  156238. return(acc);
  156239. }else{
  156240. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  156241. }
  156242. }
  156243. /* seek to an offset relative to the *compressed* data. This also
  156244. scans packets to update the PCM cursor. It will cross a logical
  156245. bitstream boundary, but only if it can't get any packets out of the
  156246. tail of the bitstream we seek to (so no surprises).
  156247. returns zero on success, nonzero on failure */
  156248. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156249. ogg_stream_state work_os;
  156250. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156251. if(!vf->seekable)
  156252. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  156253. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  156254. /* don't yet clear out decoding machine (if it's initialized), in
  156255. the case we're in the same link. Restart the decode lapping, and
  156256. let _fetch_and_process_packet deal with a potential bitstream
  156257. boundary */
  156258. vf->pcm_offset=-1;
  156259. ogg_stream_reset_serialno(&vf->os,
  156260. vf->current_serialno); /* must set serialno */
  156261. vorbis_synthesis_restart(&vf->vd);
  156262. _seek_helper(vf,pos);
  156263. /* we need to make sure the pcm_offset is set, but we don't want to
  156264. advance the raw cursor past good packets just to get to the first
  156265. with a granulepos. That's not equivalent behavior to beginning
  156266. decoding as immediately after the seek position as possible.
  156267. So, a hack. We use two stream states; a local scratch state and
  156268. the shared vf->os stream state. We use the local state to
  156269. scan, and the shared state as a buffer for later decode.
  156270. Unfortuantely, on the last page we still advance to last packet
  156271. because the granulepos on the last page is not necessarily on a
  156272. packet boundary, and we need to make sure the granpos is
  156273. correct.
  156274. */
  156275. {
  156276. ogg_page og;
  156277. ogg_packet op;
  156278. int lastblock=0;
  156279. int accblock=0;
  156280. int thisblock;
  156281. int eosflag;
  156282. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  156283. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  156284. return from not necessarily
  156285. starting from the beginning */
  156286. while(1){
  156287. if(vf->ready_state>=STREAMSET){
  156288. /* snarf/scan a packet if we can */
  156289. int result=ogg_stream_packetout(&work_os,&op);
  156290. if(result>0){
  156291. if(vf->vi[vf->current_link].codec_setup){
  156292. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156293. if(thisblock<0){
  156294. ogg_stream_packetout(&vf->os,NULL);
  156295. thisblock=0;
  156296. }else{
  156297. if(eosflag)
  156298. ogg_stream_packetout(&vf->os,NULL);
  156299. else
  156300. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  156301. }
  156302. if(op.granulepos!=-1){
  156303. int i,link=vf->current_link;
  156304. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  156305. if(granulepos<0)granulepos=0;
  156306. for(i=0;i<link;i++)
  156307. granulepos+=vf->pcmlengths[i*2+1];
  156308. vf->pcm_offset=granulepos-accblock;
  156309. break;
  156310. }
  156311. lastblock=thisblock;
  156312. continue;
  156313. }else
  156314. ogg_stream_packetout(&vf->os,NULL);
  156315. }
  156316. }
  156317. if(!lastblock){
  156318. if(_get_next_page(vf,&og,-1)<0){
  156319. vf->pcm_offset=ov_pcm_total(vf,-1);
  156320. break;
  156321. }
  156322. }else{
  156323. /* huh? Bogus stream with packets but no granulepos */
  156324. vf->pcm_offset=-1;
  156325. break;
  156326. }
  156327. /* has our decoding just traversed a bitstream boundary? */
  156328. if(vf->ready_state>=STREAMSET)
  156329. if(vf->current_serialno!=ogg_page_serialno(&og)){
  156330. _decode_clear(vf); /* clear out stream state */
  156331. ogg_stream_clear(&work_os);
  156332. }
  156333. if(vf->ready_state<STREAMSET){
  156334. int link;
  156335. vf->current_serialno=ogg_page_serialno(&og);
  156336. for(link=0;link<vf->links;link++)
  156337. if(vf->serialnos[link]==vf->current_serialno)break;
  156338. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  156339. error out, leave
  156340. machine uninitialized */
  156341. vf->current_link=link;
  156342. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156343. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  156344. vf->ready_state=STREAMSET;
  156345. }
  156346. ogg_stream_pagein(&vf->os,&og);
  156347. ogg_stream_pagein(&work_os,&og);
  156348. eosflag=ogg_page_eos(&og);
  156349. }
  156350. }
  156351. ogg_stream_clear(&work_os);
  156352. vf->bittrack=0.f;
  156353. vf->samptrack=0.f;
  156354. return(0);
  156355. seek_error:
  156356. /* dump the machine so we're in a known state */
  156357. vf->pcm_offset=-1;
  156358. ogg_stream_clear(&work_os);
  156359. _decode_clear(vf);
  156360. return OV_EBADLINK;
  156361. }
  156362. /* Page granularity seek (faster than sample granularity because we
  156363. don't do the last bit of decode to find a specific sample).
  156364. Seek to the last [granule marked] page preceeding the specified pos
  156365. location, such that decoding past the returned point will quickly
  156366. arrive at the requested position. */
  156367. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  156368. int link=-1;
  156369. ogg_int64_t result=0;
  156370. ogg_int64_t total=ov_pcm_total(vf,-1);
  156371. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156372. if(!vf->seekable)return(OV_ENOSEEK);
  156373. if(pos<0 || pos>total)return(OV_EINVAL);
  156374. /* which bitstream section does this pcm offset occur in? */
  156375. for(link=vf->links-1;link>=0;link--){
  156376. total-=vf->pcmlengths[link*2+1];
  156377. if(pos>=total)break;
  156378. }
  156379. /* search within the logical bitstream for the page with the highest
  156380. pcm_pos preceeding (or equal to) pos. There is a danger here;
  156381. missing pages or incorrect frame number information in the
  156382. bitstream could make our task impossible. Account for that (it
  156383. would be an error condition) */
  156384. /* new search algorithm by HB (Nicholas Vinen) */
  156385. {
  156386. ogg_int64_t end=vf->offsets[link+1];
  156387. ogg_int64_t begin=vf->offsets[link];
  156388. ogg_int64_t begintime = vf->pcmlengths[link*2];
  156389. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  156390. ogg_int64_t target=pos-total+begintime;
  156391. ogg_int64_t best=begin;
  156392. ogg_page og;
  156393. while(begin<end){
  156394. ogg_int64_t bisect;
  156395. if(end-begin<CHUNKSIZE){
  156396. bisect=begin;
  156397. }else{
  156398. /* take a (pretty decent) guess. */
  156399. bisect=begin +
  156400. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  156401. if(bisect<=begin)
  156402. bisect=begin+1;
  156403. }
  156404. _seek_helper(vf,bisect);
  156405. while(begin<end){
  156406. result=_get_next_page(vf,&og,end-vf->offset);
  156407. if(result==OV_EREAD) goto seek_error;
  156408. if(result<0){
  156409. if(bisect<=begin+1)
  156410. end=begin; /* found it */
  156411. else{
  156412. if(bisect==0) goto seek_error;
  156413. bisect-=CHUNKSIZE;
  156414. if(bisect<=begin)bisect=begin+1;
  156415. _seek_helper(vf,bisect);
  156416. }
  156417. }else{
  156418. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  156419. if(granulepos==-1)continue;
  156420. if(granulepos<target){
  156421. best=result; /* raw offset of packet with granulepos */
  156422. begin=vf->offset; /* raw offset of next page */
  156423. begintime=granulepos;
  156424. if(target-begintime>44100)break;
  156425. bisect=begin; /* *not* begin + 1 */
  156426. }else{
  156427. if(bisect<=begin+1)
  156428. end=begin; /* found it */
  156429. else{
  156430. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  156431. end=result;
  156432. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  156433. if(bisect<=begin)bisect=begin+1;
  156434. _seek_helper(vf,bisect);
  156435. }else{
  156436. end=result;
  156437. endtime=granulepos;
  156438. break;
  156439. }
  156440. }
  156441. }
  156442. }
  156443. }
  156444. }
  156445. /* found our page. seek to it, update pcm offset. Easier case than
  156446. raw_seek, don't keep packets preceeding granulepos. */
  156447. {
  156448. ogg_page og;
  156449. ogg_packet op;
  156450. /* seek */
  156451. _seek_helper(vf,best);
  156452. vf->pcm_offset=-1;
  156453. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  156454. if(link!=vf->current_link){
  156455. /* Different link; dump entire decode machine */
  156456. _decode_clear(vf);
  156457. vf->current_link=link;
  156458. vf->current_serialno=ogg_page_serialno(&og);
  156459. vf->ready_state=STREAMSET;
  156460. }else{
  156461. vorbis_synthesis_restart(&vf->vd);
  156462. }
  156463. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156464. ogg_stream_pagein(&vf->os,&og);
  156465. /* pull out all but last packet; the one with granulepos */
  156466. while(1){
  156467. result=ogg_stream_packetpeek(&vf->os,&op);
  156468. if(result==0){
  156469. /* !!! the packet finishing this page originated on a
  156470. preceeding page. Keep fetching previous pages until we
  156471. get one with a granulepos or without the 'continued' flag
  156472. set. Then just use raw_seek for simplicity. */
  156473. _seek_helper(vf,best);
  156474. while(1){
  156475. result=_get_prev_page(vf,&og);
  156476. if(result<0) goto seek_error;
  156477. if(ogg_page_granulepos(&og)>-1 ||
  156478. !ogg_page_continued(&og)){
  156479. return ov_raw_seek(vf,result);
  156480. }
  156481. vf->offset=result;
  156482. }
  156483. }
  156484. if(result<0){
  156485. result = OV_EBADPACKET;
  156486. goto seek_error;
  156487. }
  156488. if(op.granulepos!=-1){
  156489. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156490. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156491. vf->pcm_offset+=total;
  156492. break;
  156493. }else
  156494. result=ogg_stream_packetout(&vf->os,NULL);
  156495. }
  156496. }
  156497. }
  156498. /* verify result */
  156499. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  156500. result=OV_EFAULT;
  156501. goto seek_error;
  156502. }
  156503. vf->bittrack=0.f;
  156504. vf->samptrack=0.f;
  156505. return(0);
  156506. seek_error:
  156507. /* dump machine so we're in a known state */
  156508. vf->pcm_offset=-1;
  156509. _decode_clear(vf);
  156510. return (int)result;
  156511. }
  156512. /* seek to a sample offset relative to the decompressed pcm stream
  156513. returns zero on success, nonzero on failure */
  156514. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156515. int thisblock,lastblock=0;
  156516. int ret=ov_pcm_seek_page(vf,pos);
  156517. if(ret<0)return(ret);
  156518. if((ret=_make_decode_ready(vf)))return ret;
  156519. /* discard leading packets we don't need for the lapping of the
  156520. position we want; don't decode them */
  156521. while(1){
  156522. ogg_packet op;
  156523. ogg_page og;
  156524. int ret=ogg_stream_packetpeek(&vf->os,&op);
  156525. if(ret>0){
  156526. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156527. if(thisblock<0){
  156528. ogg_stream_packetout(&vf->os,NULL);
  156529. continue; /* non audio packet */
  156530. }
  156531. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  156532. if(vf->pcm_offset+((thisblock+
  156533. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  156534. /* remove the packet from packet queue and track its granulepos */
  156535. ogg_stream_packetout(&vf->os,NULL);
  156536. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  156537. only tracking, no
  156538. pcm_decode */
  156539. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  156540. /* end of logical stream case is hard, especially with exact
  156541. length positioning. */
  156542. if(op.granulepos>-1){
  156543. int i;
  156544. /* always believe the stream markers */
  156545. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156546. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156547. for(i=0;i<vf->current_link;i++)
  156548. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  156549. }
  156550. lastblock=thisblock;
  156551. }else{
  156552. if(ret<0 && ret!=OV_HOLE)break;
  156553. /* suck in a new page */
  156554. if(_get_next_page(vf,&og,-1)<0)break;
  156555. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  156556. if(vf->ready_state<STREAMSET){
  156557. int link;
  156558. vf->current_serialno=ogg_page_serialno(&og);
  156559. for(link=0;link<vf->links;link++)
  156560. if(vf->serialnos[link]==vf->current_serialno)break;
  156561. if(link==vf->links)return(OV_EBADLINK);
  156562. vf->current_link=link;
  156563. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156564. vf->ready_state=STREAMSET;
  156565. ret=_make_decode_ready(vf);
  156566. if(ret)return ret;
  156567. lastblock=0;
  156568. }
  156569. ogg_stream_pagein(&vf->os,&og);
  156570. }
  156571. }
  156572. vf->bittrack=0.f;
  156573. vf->samptrack=0.f;
  156574. /* discard samples until we reach the desired position. Crossing a
  156575. logical bitstream boundary with abandon is OK. */
  156576. while(vf->pcm_offset<pos){
  156577. ogg_int64_t target=pos-vf->pcm_offset;
  156578. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156579. if(samples>target)samples=target;
  156580. vorbis_synthesis_read(&vf->vd,samples);
  156581. vf->pcm_offset+=samples;
  156582. if(samples<target)
  156583. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  156584. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  156585. }
  156586. return 0;
  156587. }
  156588. /* seek to a playback time relative to the decompressed pcm stream
  156589. returns zero on success, nonzero on failure */
  156590. int ov_time_seek(OggVorbis_File *vf,double seconds){
  156591. /* translate time to PCM position and call ov_pcm_seek */
  156592. int link=-1;
  156593. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156594. double time_total=ov_time_total(vf,-1);
  156595. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156596. if(!vf->seekable)return(OV_ENOSEEK);
  156597. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156598. /* which bitstream section does this time offset occur in? */
  156599. for(link=vf->links-1;link>=0;link--){
  156600. pcm_total-=vf->pcmlengths[link*2+1];
  156601. time_total-=ov_time_total(vf,link);
  156602. if(seconds>=time_total)break;
  156603. }
  156604. /* enough information to convert time offset to pcm offset */
  156605. {
  156606. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156607. return(ov_pcm_seek(vf,target));
  156608. }
  156609. }
  156610. /* page-granularity version of ov_time_seek
  156611. returns zero on success, nonzero on failure */
  156612. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  156613. /* translate time to PCM position and call ov_pcm_seek */
  156614. int link=-1;
  156615. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156616. double time_total=ov_time_total(vf,-1);
  156617. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156618. if(!vf->seekable)return(OV_ENOSEEK);
  156619. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156620. /* which bitstream section does this time offset occur in? */
  156621. for(link=vf->links-1;link>=0;link--){
  156622. pcm_total-=vf->pcmlengths[link*2+1];
  156623. time_total-=ov_time_total(vf,link);
  156624. if(seconds>=time_total)break;
  156625. }
  156626. /* enough information to convert time offset to pcm offset */
  156627. {
  156628. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156629. return(ov_pcm_seek_page(vf,target));
  156630. }
  156631. }
  156632. /* tell the current stream offset cursor. Note that seek followed by
  156633. tell will likely not give the set offset due to caching */
  156634. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  156635. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156636. return(vf->offset);
  156637. }
  156638. /* return PCM offset (sample) of next PCM sample to be read */
  156639. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  156640. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156641. return(vf->pcm_offset);
  156642. }
  156643. /* return time offset (seconds) of next PCM sample to be read */
  156644. double ov_time_tell(OggVorbis_File *vf){
  156645. int link=0;
  156646. ogg_int64_t pcm_total=0;
  156647. double time_total=0.f;
  156648. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156649. if(vf->seekable){
  156650. pcm_total=ov_pcm_total(vf,-1);
  156651. time_total=ov_time_total(vf,-1);
  156652. /* which bitstream section does this time offset occur in? */
  156653. for(link=vf->links-1;link>=0;link--){
  156654. pcm_total-=vf->pcmlengths[link*2+1];
  156655. time_total-=ov_time_total(vf,link);
  156656. if(vf->pcm_offset>=pcm_total)break;
  156657. }
  156658. }
  156659. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  156660. }
  156661. /* link: -1) return the vorbis_info struct for the bitstream section
  156662. currently being decoded
  156663. 0-n) to request information for a specific bitstream section
  156664. In the case of a non-seekable bitstream, any call returns the
  156665. current bitstream. NULL in the case that the machine is not
  156666. initialized */
  156667. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  156668. if(vf->seekable){
  156669. if(link<0)
  156670. if(vf->ready_state>=STREAMSET)
  156671. return vf->vi+vf->current_link;
  156672. else
  156673. return vf->vi;
  156674. else
  156675. if(link>=vf->links)
  156676. return NULL;
  156677. else
  156678. return vf->vi+link;
  156679. }else{
  156680. return vf->vi;
  156681. }
  156682. }
  156683. /* grr, strong typing, grr, no templates/inheritence, grr */
  156684. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  156685. if(vf->seekable){
  156686. if(link<0)
  156687. if(vf->ready_state>=STREAMSET)
  156688. return vf->vc+vf->current_link;
  156689. else
  156690. return vf->vc;
  156691. else
  156692. if(link>=vf->links)
  156693. return NULL;
  156694. else
  156695. return vf->vc+link;
  156696. }else{
  156697. return vf->vc;
  156698. }
  156699. }
  156700. static int host_is_big_endian() {
  156701. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  156702. unsigned char *bytewise = (unsigned char *)&pattern;
  156703. if (bytewise[0] == 0xfe) return 1;
  156704. return 0;
  156705. }
  156706. /* up to this point, everything could more or less hide the multiple
  156707. logical bitstream nature of chaining from the toplevel application
  156708. if the toplevel application didn't particularly care. However, at
  156709. the point that we actually read audio back, the multiple-section
  156710. nature must surface: Multiple bitstream sections do not necessarily
  156711. have to have the same number of channels or sampling rate.
  156712. ov_read returns the sequential logical bitstream number currently
  156713. being decoded along with the PCM data in order that the toplevel
  156714. application can take action on channel/sample rate changes. This
  156715. number will be incremented even for streamed (non-seekable) streams
  156716. (for seekable streams, it represents the actual logical bitstream
  156717. index within the physical bitstream. Note that the accessor
  156718. functions above are aware of this dichotomy).
  156719. input values: buffer) a buffer to hold packed PCM data for return
  156720. length) the byte length requested to be placed into buffer
  156721. bigendianp) should the data be packed LSB first (0) or
  156722. MSB first (1)
  156723. word) word size for output. currently 1 (byte) or
  156724. 2 (16 bit short)
  156725. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156726. 0) EOF
  156727. n) number of bytes of PCM actually returned. The
  156728. below works on a packet-by-packet basis, so the
  156729. return length is not related to the 'length' passed
  156730. in, just guaranteed to fit.
  156731. *section) set to the logical bitstream number */
  156732. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  156733. int bigendianp,int word,int sgned,int *bitstream){
  156734. int i,j;
  156735. int host_endian = host_is_big_endian();
  156736. float **pcm;
  156737. long samples;
  156738. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156739. while(1){
  156740. if(vf->ready_state==INITSET){
  156741. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156742. if(samples)break;
  156743. }
  156744. /* suck in another packet */
  156745. {
  156746. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156747. if(ret==OV_EOF)
  156748. return(0);
  156749. if(ret<=0)
  156750. return(ret);
  156751. }
  156752. }
  156753. if(samples>0){
  156754. /* yay! proceed to pack data into the byte buffer */
  156755. long channels=ov_info(vf,-1)->channels;
  156756. long bytespersample=word * channels;
  156757. vorbis_fpu_control fpu;
  156758. (void) fpu; // (to avoid a warning about it being unused)
  156759. if(samples>length/bytespersample)samples=length/bytespersample;
  156760. if(samples <= 0)
  156761. return OV_EINVAL;
  156762. /* a tight loop to pack each size */
  156763. {
  156764. int val;
  156765. if(word==1){
  156766. int off=(sgned?0:128);
  156767. vorbis_fpu_setround(&fpu);
  156768. for(j=0;j<samples;j++)
  156769. for(i=0;i<channels;i++){
  156770. val=vorbis_ftoi(pcm[i][j]*128.f);
  156771. if(val>127)val=127;
  156772. else if(val<-128)val=-128;
  156773. *buffer++=val+off;
  156774. }
  156775. vorbis_fpu_restore(fpu);
  156776. }else{
  156777. int off=(sgned?0:32768);
  156778. if(host_endian==bigendianp){
  156779. if(sgned){
  156780. vorbis_fpu_setround(&fpu);
  156781. for(i=0;i<channels;i++) { /* It's faster in this order */
  156782. float *src=pcm[i];
  156783. short *dest=((short *)buffer)+i;
  156784. for(j=0;j<samples;j++) {
  156785. val=vorbis_ftoi(src[j]*32768.f);
  156786. if(val>32767)val=32767;
  156787. else if(val<-32768)val=-32768;
  156788. *dest=val;
  156789. dest+=channels;
  156790. }
  156791. }
  156792. vorbis_fpu_restore(fpu);
  156793. }else{
  156794. vorbis_fpu_setround(&fpu);
  156795. for(i=0;i<channels;i++) {
  156796. float *src=pcm[i];
  156797. short *dest=((short *)buffer)+i;
  156798. for(j=0;j<samples;j++) {
  156799. val=vorbis_ftoi(src[j]*32768.f);
  156800. if(val>32767)val=32767;
  156801. else if(val<-32768)val=-32768;
  156802. *dest=val+off;
  156803. dest+=channels;
  156804. }
  156805. }
  156806. vorbis_fpu_restore(fpu);
  156807. }
  156808. }else if(bigendianp){
  156809. vorbis_fpu_setround(&fpu);
  156810. for(j=0;j<samples;j++)
  156811. for(i=0;i<channels;i++){
  156812. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156813. if(val>32767)val=32767;
  156814. else if(val<-32768)val=-32768;
  156815. val+=off;
  156816. *buffer++=(val>>8);
  156817. *buffer++=(val&0xff);
  156818. }
  156819. vorbis_fpu_restore(fpu);
  156820. }else{
  156821. int val;
  156822. vorbis_fpu_setround(&fpu);
  156823. for(j=0;j<samples;j++)
  156824. for(i=0;i<channels;i++){
  156825. val=vorbis_ftoi(pcm[i][j]*32768.f);
  156826. if(val>32767)val=32767;
  156827. else if(val<-32768)val=-32768;
  156828. val+=off;
  156829. *buffer++=(val&0xff);
  156830. *buffer++=(val>>8);
  156831. }
  156832. vorbis_fpu_restore(fpu);
  156833. }
  156834. }
  156835. }
  156836. vorbis_synthesis_read(&vf->vd,samples);
  156837. vf->pcm_offset+=samples;
  156838. if(bitstream)*bitstream=vf->current_link;
  156839. return(samples*bytespersample);
  156840. }else{
  156841. return(samples);
  156842. }
  156843. }
  156844. /* input values: pcm_channels) a float vector per channel of output
  156845. length) the sample length being read by the app
  156846. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156847. 0) EOF
  156848. n) number of samples of PCM actually returned. The
  156849. below works on a packet-by-packet basis, so the
  156850. return length is not related to the 'length' passed
  156851. in, just guaranteed to fit.
  156852. *section) set to the logical bitstream number */
  156853. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  156854. int *bitstream){
  156855. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156856. while(1){
  156857. if(vf->ready_state==INITSET){
  156858. float **pcm;
  156859. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156860. if(samples){
  156861. if(pcm_channels)*pcm_channels=pcm;
  156862. if(samples>length)samples=length;
  156863. vorbis_synthesis_read(&vf->vd,samples);
  156864. vf->pcm_offset+=samples;
  156865. if(bitstream)*bitstream=vf->current_link;
  156866. return samples;
  156867. }
  156868. }
  156869. /* suck in another packet */
  156870. {
  156871. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156872. if(ret==OV_EOF)return(0);
  156873. if(ret<=0)return(ret);
  156874. }
  156875. }
  156876. }
  156877. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  156878. extern void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,
  156879. ogg_int64_t off);
  156880. static void _ov_splice(float **pcm,float **lappcm,
  156881. int n1, int n2,
  156882. int ch1, int ch2,
  156883. float *w1, float *w2){
  156884. int i,j;
  156885. float *w=w1;
  156886. int n=n1;
  156887. if(n1>n2){
  156888. n=n2;
  156889. w=w2;
  156890. }
  156891. /* splice */
  156892. for(j=0;j<ch1 && j<ch2;j++){
  156893. float *s=lappcm[j];
  156894. float *d=pcm[j];
  156895. for(i=0;i<n;i++){
  156896. float wd=w[i]*w[i];
  156897. float ws=1.-wd;
  156898. d[i]=d[i]*wd + s[i]*ws;
  156899. }
  156900. }
  156901. /* window from zero */
  156902. for(;j<ch2;j++){
  156903. float *d=pcm[j];
  156904. for(i=0;i<n;i++){
  156905. float wd=w[i]*w[i];
  156906. d[i]=d[i]*wd;
  156907. }
  156908. }
  156909. }
  156910. /* make sure vf is INITSET */
  156911. static int _ov_initset(OggVorbis_File *vf){
  156912. while(1){
  156913. if(vf->ready_state==INITSET)break;
  156914. /* suck in another packet */
  156915. {
  156916. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156917. if(ret<0 && ret!=OV_HOLE)return(ret);
  156918. }
  156919. }
  156920. return 0;
  156921. }
  156922. /* make sure vf is INITSET and that we have a primed buffer; if
  156923. we're crosslapping at a stream section boundary, this also makes
  156924. sure we're sanity checking against the right stream information */
  156925. static int _ov_initprime(OggVorbis_File *vf){
  156926. vorbis_dsp_state *vd=&vf->vd;
  156927. while(1){
  156928. if(vf->ready_state==INITSET)
  156929. if(vorbis_synthesis_pcmout(vd,NULL))break;
  156930. /* suck in another packet */
  156931. {
  156932. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  156933. if(ret<0 && ret!=OV_HOLE)return(ret);
  156934. }
  156935. }
  156936. return 0;
  156937. }
  156938. /* grab enough data for lapping from vf; this may be in the form of
  156939. unreturned, already-decoded pcm, remaining PCM we will need to
  156940. decode, or synthetic postextrapolation from last packets. */
  156941. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  156942. float **lappcm,int lapsize){
  156943. int lapcount=0,i;
  156944. float **pcm;
  156945. /* try first to decode the lapping data */
  156946. while(lapcount<lapsize){
  156947. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  156948. if(samples){
  156949. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  156950. for(i=0;i<vi->channels;i++)
  156951. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  156952. lapcount+=samples;
  156953. vorbis_synthesis_read(vd,samples);
  156954. }else{
  156955. /* suck in another packet */
  156956. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  156957. if(ret==OV_EOF)break;
  156958. }
  156959. }
  156960. if(lapcount<lapsize){
  156961. /* failed to get lapping data from normal decode; pry it from the
  156962. postextrapolation buffering, or the second half of the MDCT
  156963. from the last packet */
  156964. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  156965. if(samples==0){
  156966. for(i=0;i<vi->channels;i++)
  156967. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  156968. lapcount=lapsize;
  156969. }else{
  156970. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  156971. for(i=0;i<vi->channels;i++)
  156972. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  156973. lapcount+=samples;
  156974. }
  156975. }
  156976. }
  156977. /* this sets up crosslapping of a sample by using trailing data from
  156978. sample 1 and lapping it into the windowing buffer of sample 2 */
  156979. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  156980. vorbis_info *vi1,*vi2;
  156981. float **lappcm;
  156982. float **pcm;
  156983. float *w1,*w2;
  156984. int n1,n2,i,ret,hs1,hs2;
  156985. if(vf1==vf2)return(0); /* degenerate case */
  156986. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  156987. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  156988. /* the relevant overlap buffers must be pre-checked and pre-primed
  156989. before looking at settings in the event that priming would cross
  156990. a bitstream boundary. So, do it now */
  156991. ret=_ov_initset(vf1);
  156992. if(ret)return(ret);
  156993. ret=_ov_initprime(vf2);
  156994. if(ret)return(ret);
  156995. vi1=ov_info(vf1,-1);
  156996. vi2=ov_info(vf2,-1);
  156997. hs1=ov_halfrate_p(vf1);
  156998. hs2=ov_halfrate_p(vf2);
  156999. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  157000. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  157001. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  157002. w1=vorbis_window(&vf1->vd,0);
  157003. w2=vorbis_window(&vf2->vd,0);
  157004. for(i=0;i<vi1->channels;i++)
  157005. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157006. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  157007. /* have a lapping buffer from vf1; now to splice it into the lapping
  157008. buffer of vf2 */
  157009. /* consolidate and expose the buffer. */
  157010. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  157011. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  157012. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  157013. /* splice */
  157014. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  157015. /* done */
  157016. return(0);
  157017. }
  157018. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  157019. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  157020. vorbis_info *vi;
  157021. float **lappcm;
  157022. float **pcm;
  157023. float *w1,*w2;
  157024. int n1,n2,ch1,ch2,hs;
  157025. int i,ret;
  157026. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157027. ret=_ov_initset(vf);
  157028. if(ret)return(ret);
  157029. vi=ov_info(vf,-1);
  157030. hs=ov_halfrate_p(vf);
  157031. ch1=vi->channels;
  157032. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  157033. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  157034. persistent; even if the decode state
  157035. from this link gets dumped, this
  157036. window array continues to exist */
  157037. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  157038. for(i=0;i<ch1;i++)
  157039. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157040. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  157041. /* have lapping data; seek and prime the buffer */
  157042. ret=localseek(vf,pos);
  157043. if(ret)return ret;
  157044. ret=_ov_initprime(vf);
  157045. if(ret)return(ret);
  157046. /* Guard against cross-link changes; they're perfectly legal */
  157047. vi=ov_info(vf,-1);
  157048. ch2=vi->channels;
  157049. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  157050. w2=vorbis_window(&vf->vd,0);
  157051. /* consolidate and expose the buffer. */
  157052. vorbis_synthesis_lapout(&vf->vd,&pcm);
  157053. /* splice */
  157054. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  157055. /* done */
  157056. return(0);
  157057. }
  157058. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157059. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  157060. }
  157061. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157062. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  157063. }
  157064. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157065. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  157066. }
  157067. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  157068. int (*localseek)(OggVorbis_File *,double)){
  157069. vorbis_info *vi;
  157070. float **lappcm;
  157071. float **pcm;
  157072. float *w1,*w2;
  157073. int n1,n2,ch1,ch2,hs;
  157074. int i,ret;
  157075. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157076. ret=_ov_initset(vf);
  157077. if(ret)return(ret);
  157078. vi=ov_info(vf,-1);
  157079. hs=ov_halfrate_p(vf);
  157080. ch1=vi->channels;
  157081. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  157082. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  157083. persistent; even if the decode state
  157084. from this link gets dumped, this
  157085. window array continues to exist */
  157086. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  157087. for(i=0;i<ch1;i++)
  157088. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157089. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  157090. /* have lapping data; seek and prime the buffer */
  157091. ret=localseek(vf,pos);
  157092. if(ret)return ret;
  157093. ret=_ov_initprime(vf);
  157094. if(ret)return(ret);
  157095. /* Guard against cross-link changes; they're perfectly legal */
  157096. vi=ov_info(vf,-1);
  157097. ch2=vi->channels;
  157098. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  157099. w2=vorbis_window(&vf->vd,0);
  157100. /* consolidate and expose the buffer. */
  157101. vorbis_synthesis_lapout(&vf->vd,&pcm);
  157102. /* splice */
  157103. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  157104. /* done */
  157105. return(0);
  157106. }
  157107. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  157108. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  157109. }
  157110. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  157111. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  157112. }
  157113. #endif
  157114. /*** End of inlined file: vorbisfile.c ***/
  157115. /*** Start of inlined file: window.c ***/
  157116. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  157117. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  157118. // tasks..
  157119. #if JUCE_MSVC
  157120. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  157121. #endif
  157122. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  157123. #if JUCE_USE_OGGVORBIS
  157124. #include <stdlib.h>
  157125. #include <math.h>
  157126. static float vwin64[32] = {
  157127. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  157128. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  157129. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  157130. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  157131. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  157132. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  157133. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  157134. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  157135. };
  157136. static float vwin128[64] = {
  157137. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  157138. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  157139. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  157140. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  157141. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  157142. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  157143. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  157144. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  157145. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  157146. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  157147. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  157148. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  157149. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  157150. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  157151. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  157152. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  157153. };
  157154. static float vwin256[128] = {
  157155. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  157156. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  157157. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  157158. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  157159. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  157160. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  157161. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  157162. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  157163. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  157164. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  157165. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  157166. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  157167. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  157168. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  157169. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  157170. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  157171. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  157172. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  157173. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  157174. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  157175. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  157176. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  157177. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  157178. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  157179. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  157180. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  157181. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  157182. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  157183. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  157184. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  157185. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  157186. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  157187. };
  157188. static float vwin512[256] = {
  157189. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  157190. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  157191. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  157192. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  157193. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  157194. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  157195. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  157196. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  157197. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  157198. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  157199. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  157200. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  157201. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  157202. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  157203. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  157204. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  157205. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  157206. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  157207. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  157208. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  157209. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  157210. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  157211. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  157212. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  157213. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  157214. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  157215. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  157216. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  157217. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  157218. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  157219. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  157220. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  157221. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  157222. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  157223. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  157224. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  157225. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  157226. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  157227. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  157228. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  157229. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  157230. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  157231. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  157232. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  157233. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  157234. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  157235. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  157236. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  157237. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  157238. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  157239. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  157240. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  157241. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  157242. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  157243. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  157244. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  157245. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  157246. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  157247. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  157248. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  157249. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  157250. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  157251. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  157252. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  157253. };
  157254. static float vwin1024[512] = {
  157255. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  157256. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  157257. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  157258. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  157259. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  157260. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  157261. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  157262. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  157263. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  157264. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  157265. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  157266. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  157267. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  157268. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  157269. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  157270. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  157271. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  157272. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  157273. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  157274. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  157275. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  157276. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  157277. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  157278. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  157279. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  157280. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  157281. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  157282. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  157283. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  157284. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  157285. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  157286. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  157287. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  157288. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  157289. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  157290. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  157291. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  157292. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  157293. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  157294. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  157295. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  157296. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  157297. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  157298. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  157299. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  157300. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  157301. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  157302. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  157303. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  157304. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  157305. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  157306. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  157307. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  157308. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  157309. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  157310. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  157311. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  157312. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  157313. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  157314. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  157315. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  157316. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  157317. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  157318. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  157319. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  157320. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  157321. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  157322. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  157323. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  157324. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  157325. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  157326. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  157327. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  157328. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  157329. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  157330. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  157331. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  157332. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  157333. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  157334. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  157335. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  157336. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  157337. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  157338. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  157339. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  157340. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  157341. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  157342. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  157343. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  157344. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  157345. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  157346. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  157347. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  157348. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  157349. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  157350. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  157351. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  157352. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  157353. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  157354. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  157355. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  157356. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  157357. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  157358. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  157359. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  157360. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  157361. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  157362. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  157363. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  157364. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  157365. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  157366. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  157367. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  157368. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  157369. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  157370. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  157371. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  157372. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  157373. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  157374. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  157375. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  157376. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  157377. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  157378. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  157379. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  157380. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  157381. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  157382. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  157383. };
  157384. static float vwin2048[1024] = {
  157385. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  157386. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  157387. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  157388. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  157389. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  157390. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  157391. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  157392. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  157393. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  157394. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  157395. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  157396. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  157397. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  157398. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  157399. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  157400. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  157401. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  157402. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  157403. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  157404. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  157405. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  157406. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  157407. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  157408. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  157409. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  157410. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  157411. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  157412. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  157413. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  157414. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  157415. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  157416. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  157417. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  157418. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  157419. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  157420. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  157421. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  157422. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  157423. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  157424. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  157425. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  157426. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  157427. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  157428. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  157429. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  157430. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  157431. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  157432. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  157433. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  157434. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  157435. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  157436. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  157437. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  157438. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  157439. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  157440. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  157441. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  157442. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  157443. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  157444. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  157445. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  157446. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  157447. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  157448. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  157449. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  157450. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  157451. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  157452. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  157453. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  157454. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  157455. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  157456. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  157457. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  157458. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  157459. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  157460. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  157461. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  157462. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  157463. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  157464. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  157465. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  157466. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  157467. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  157468. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  157469. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  157470. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  157471. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  157472. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  157473. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  157474. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  157475. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  157476. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  157477. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  157478. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  157479. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  157480. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  157481. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  157482. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  157483. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  157484. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  157485. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  157486. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  157487. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  157488. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  157489. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  157490. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  157491. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  157492. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  157493. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  157494. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  157495. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  157496. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  157497. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  157498. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  157499. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  157500. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  157501. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  157502. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  157503. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  157504. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  157505. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  157506. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  157507. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  157508. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  157509. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  157510. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  157511. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  157512. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  157513. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  157514. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  157515. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  157516. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  157517. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  157518. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  157519. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  157520. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  157521. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  157522. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  157523. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  157524. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  157525. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  157526. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  157527. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  157528. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  157529. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  157530. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  157531. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  157532. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  157533. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  157534. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  157535. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  157536. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  157537. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  157538. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  157539. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  157540. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  157541. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  157542. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  157543. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  157544. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  157545. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  157546. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  157547. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  157548. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  157549. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  157550. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  157551. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  157552. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  157553. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  157554. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  157555. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  157556. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  157557. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  157558. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  157559. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  157560. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  157561. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  157562. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  157563. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  157564. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  157565. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  157566. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  157567. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  157568. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  157569. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  157570. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  157571. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  157572. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  157573. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  157574. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  157575. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  157576. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  157577. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  157578. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  157579. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  157580. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  157581. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  157582. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  157583. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  157584. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  157585. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  157586. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  157587. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  157588. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  157589. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  157590. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  157591. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  157592. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  157593. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  157594. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  157595. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  157596. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  157597. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  157598. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  157599. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  157600. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  157601. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  157602. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  157603. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  157604. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  157605. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  157606. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  157607. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  157608. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  157609. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  157610. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  157611. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  157612. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  157613. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  157614. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  157615. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  157616. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  157617. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  157618. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  157619. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  157620. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  157621. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  157622. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  157623. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  157624. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  157625. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  157626. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  157627. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  157628. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  157629. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  157630. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  157631. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  157632. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  157633. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  157634. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  157635. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  157636. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  157637. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  157638. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  157639. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  157640. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  157641. };
  157642. static float vwin4096[2048] = {
  157643. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  157644. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  157645. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  157646. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  157647. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  157648. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  157649. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  157650. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  157651. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  157652. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  157653. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  157654. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  157655. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  157656. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  157657. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  157658. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  157659. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  157660. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  157661. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  157662. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  157663. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  157664. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  157665. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  157666. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  157667. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  157668. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  157669. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  157670. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  157671. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  157672. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  157673. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  157674. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  157675. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  157676. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  157677. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  157678. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  157679. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  157680. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  157681. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  157682. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  157683. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  157684. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  157685. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  157686. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  157687. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  157688. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  157689. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  157690. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  157691. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  157692. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  157693. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  157694. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  157695. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  157696. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  157697. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  157698. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  157699. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  157700. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  157701. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  157702. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  157703. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  157704. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  157705. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  157706. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  157707. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  157708. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  157709. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  157710. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  157711. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  157712. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  157713. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  157714. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  157715. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  157716. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  157717. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  157718. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  157719. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  157720. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  157721. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  157722. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  157723. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  157724. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  157725. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  157726. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  157727. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  157728. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  157729. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  157730. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  157731. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  157732. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  157733. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  157734. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  157735. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  157736. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  157737. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  157738. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  157739. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  157740. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  157741. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  157742. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  157743. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  157744. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  157745. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  157746. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  157747. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  157748. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  157749. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  157750. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  157751. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  157752. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  157753. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  157754. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  157755. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  157756. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  157757. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  157758. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  157759. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  157760. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  157761. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  157762. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  157763. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  157764. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  157765. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  157766. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  157767. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  157768. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  157769. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  157770. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  157771. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  157772. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  157773. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  157774. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  157775. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  157776. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  157777. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  157778. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  157779. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  157780. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  157781. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  157782. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  157783. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  157784. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  157785. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  157786. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  157787. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  157788. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  157789. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  157790. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  157791. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  157792. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  157793. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  157794. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  157795. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  157796. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  157797. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  157798. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  157799. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  157800. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  157801. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  157802. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  157803. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  157804. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  157805. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  157806. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  157807. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  157808. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  157809. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  157810. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  157811. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  157812. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  157813. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  157814. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  157815. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  157816. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  157817. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  157818. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  157819. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  157820. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  157821. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  157822. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  157823. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  157824. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  157825. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  157826. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  157827. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  157828. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  157829. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  157830. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  157831. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  157832. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  157833. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  157834. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  157835. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  157836. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  157837. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  157838. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  157839. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  157840. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  157841. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  157842. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  157843. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  157844. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  157845. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  157846. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  157847. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  157848. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  157849. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  157850. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  157851. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  157852. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  157853. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  157854. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  157855. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  157856. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  157857. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  157858. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  157859. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  157860. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  157861. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  157862. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  157863. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  157864. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  157865. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  157866. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  157867. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  157868. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  157869. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  157870. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  157871. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  157872. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  157873. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  157874. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  157875. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  157876. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  157877. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  157878. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  157879. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  157880. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  157881. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  157882. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  157883. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  157884. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  157885. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  157886. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  157887. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  157888. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  157889. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  157890. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  157891. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  157892. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  157893. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  157894. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  157895. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  157896. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  157897. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  157898. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  157899. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  157900. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  157901. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  157902. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  157903. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  157904. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  157905. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  157906. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  157907. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  157908. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  157909. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  157910. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  157911. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  157912. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  157913. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  157914. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  157915. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  157916. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  157917. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  157918. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  157919. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  157920. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  157921. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  157922. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  157923. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  157924. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  157925. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  157926. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  157927. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  157928. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  157929. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  157930. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  157931. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  157932. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  157933. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  157934. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  157935. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  157936. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  157937. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  157938. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  157939. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  157940. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  157941. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  157942. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  157943. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  157944. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  157945. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  157946. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  157947. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  157948. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  157949. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  157950. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  157951. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  157952. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  157953. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  157954. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  157955. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  157956. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  157957. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  157958. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  157959. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  157960. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  157961. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  157962. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  157963. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  157964. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  157965. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  157966. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  157967. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  157968. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  157969. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  157970. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  157971. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  157972. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  157973. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  157974. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  157975. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  157976. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  157977. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  157978. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  157979. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  157980. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  157981. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  157982. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  157983. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  157984. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  157985. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  157986. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  157987. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  157988. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  157989. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  157990. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  157991. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  157992. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  157993. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  157994. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  157995. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  157996. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  157997. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  157998. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  157999. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  158000. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  158001. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  158002. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  158003. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  158004. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  158005. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  158006. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  158007. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  158008. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  158009. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  158010. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  158011. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  158012. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  158013. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  158014. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  158015. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  158016. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  158017. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  158018. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  158019. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  158020. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  158021. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  158022. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  158023. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  158024. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  158025. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  158026. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  158027. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  158028. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  158029. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  158030. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  158031. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  158032. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  158033. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  158034. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  158035. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  158036. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  158037. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  158038. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  158039. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  158040. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  158041. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  158042. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  158043. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  158044. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  158045. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  158046. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  158047. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  158048. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  158049. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  158050. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  158051. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  158052. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  158053. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  158054. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  158055. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  158056. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  158057. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  158058. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  158059. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  158060. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  158061. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  158062. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  158063. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  158064. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  158065. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  158066. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  158067. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  158068. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  158069. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  158070. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  158071. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  158072. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  158073. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  158074. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  158075. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  158076. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  158077. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  158078. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  158079. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  158080. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  158081. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  158082. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  158083. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  158084. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  158085. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  158086. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  158087. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  158088. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  158089. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  158090. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  158091. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  158092. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  158093. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  158094. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  158095. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  158096. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  158097. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  158098. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  158099. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  158100. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  158101. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  158102. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  158103. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  158104. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  158105. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  158106. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  158107. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  158108. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  158109. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  158110. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  158111. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  158112. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  158113. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  158114. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  158115. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  158116. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  158117. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  158118. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  158119. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  158120. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  158121. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  158122. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  158123. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  158124. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  158125. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  158126. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  158127. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  158128. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  158129. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  158130. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  158131. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  158132. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  158133. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  158134. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  158135. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  158136. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  158137. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  158138. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  158139. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  158140. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  158141. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  158142. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  158143. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  158144. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  158145. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  158146. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  158147. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  158148. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  158149. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  158150. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  158151. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  158152. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  158153. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  158154. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158155. };
  158156. static float vwin8192[4096] = {
  158157. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  158158. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  158159. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  158160. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  158161. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  158162. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  158163. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  158164. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  158165. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  158166. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  158167. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  158168. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  158169. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  158170. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  158171. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  158172. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  158173. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  158174. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  158175. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  158176. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  158177. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  158178. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  158179. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  158180. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  158181. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  158182. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  158183. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  158184. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  158185. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  158186. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  158187. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  158188. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  158189. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  158190. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  158191. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  158192. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  158193. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  158194. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  158195. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  158196. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  158197. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  158198. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  158199. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  158200. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  158201. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  158202. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  158203. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  158204. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  158205. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  158206. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  158207. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  158208. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  158209. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  158210. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  158211. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  158212. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  158213. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  158214. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  158215. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  158216. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  158217. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  158218. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  158219. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  158220. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  158221. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  158222. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  158223. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  158224. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  158225. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  158226. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  158227. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  158228. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  158229. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  158230. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  158231. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  158232. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  158233. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  158234. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  158235. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  158236. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  158237. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  158238. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  158239. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  158240. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  158241. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  158242. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  158243. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  158244. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  158245. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  158246. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  158247. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  158248. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  158249. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  158250. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  158251. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  158252. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  158253. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  158254. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  158255. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  158256. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  158257. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  158258. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  158259. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  158260. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  158261. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  158262. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  158263. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  158264. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  158265. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  158266. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  158267. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  158268. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  158269. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  158270. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  158271. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  158272. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  158273. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  158274. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  158275. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  158276. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  158277. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  158278. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  158279. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  158280. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  158281. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  158282. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  158283. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  158284. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  158285. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  158286. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  158287. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  158288. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  158289. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  158290. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  158291. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  158292. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  158293. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  158294. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  158295. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  158296. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  158297. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  158298. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  158299. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  158300. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  158301. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  158302. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  158303. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  158304. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  158305. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  158306. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  158307. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  158308. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  158309. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  158310. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  158311. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  158312. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  158313. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  158314. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  158315. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  158316. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  158317. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  158318. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  158319. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  158320. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  158321. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  158322. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  158323. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  158324. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  158325. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  158326. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  158327. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  158328. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  158329. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  158330. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  158331. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  158332. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  158333. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  158334. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  158335. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  158336. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  158337. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  158338. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  158339. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  158340. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  158341. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  158342. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  158343. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  158344. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  158345. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  158346. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  158347. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  158348. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  158349. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  158350. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  158351. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  158352. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  158353. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  158354. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  158355. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  158356. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  158357. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  158358. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  158359. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  158360. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  158361. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  158362. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  158363. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  158364. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  158365. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  158366. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  158367. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  158368. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  158369. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  158370. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  158371. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  158372. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  158373. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  158374. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  158375. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  158376. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  158377. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  158378. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  158379. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  158380. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  158381. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  158382. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  158383. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  158384. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  158385. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  158386. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  158387. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  158388. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  158389. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  158390. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  158391. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  158392. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  158393. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  158394. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  158395. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  158396. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  158397. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  158398. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  158399. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  158400. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  158401. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  158402. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  158403. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  158404. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  158405. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  158406. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  158407. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  158408. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  158409. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  158410. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  158411. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  158412. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  158413. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  158414. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  158415. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  158416. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  158417. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  158418. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  158419. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  158420. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  158421. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  158422. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  158423. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  158424. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  158425. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  158426. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  158427. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  158428. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  158429. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  158430. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  158431. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  158432. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  158433. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  158434. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  158435. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  158436. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  158437. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  158438. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  158439. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  158440. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  158441. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  158442. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  158443. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  158444. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  158445. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  158446. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  158447. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  158448. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  158449. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  158450. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  158451. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  158452. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  158453. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  158454. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  158455. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  158456. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  158457. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  158458. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  158459. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  158460. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  158461. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  158462. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  158463. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  158464. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  158465. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  158466. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  158467. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  158468. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  158469. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  158470. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  158471. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  158472. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  158473. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  158474. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  158475. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  158476. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  158477. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  158478. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  158479. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  158480. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  158481. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  158482. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  158483. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  158484. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  158485. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  158486. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  158487. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  158488. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  158489. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  158490. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  158491. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  158492. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  158493. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  158494. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  158495. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  158496. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  158497. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  158498. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  158499. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  158500. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  158501. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  158502. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  158503. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  158504. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  158505. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  158506. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  158507. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  158508. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  158509. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  158510. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  158511. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  158512. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  158513. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  158514. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  158515. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  158516. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  158517. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  158518. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  158519. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  158520. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  158521. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  158522. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  158523. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  158524. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  158525. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  158526. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  158527. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  158528. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  158529. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  158530. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  158531. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  158532. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  158533. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  158534. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  158535. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  158536. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  158537. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  158538. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  158539. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  158540. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  158541. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  158542. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  158543. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  158544. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  158545. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  158546. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  158547. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  158548. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  158549. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  158550. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  158551. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  158552. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  158553. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  158554. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  158555. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  158556. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  158557. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  158558. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  158559. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  158560. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  158561. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  158562. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  158563. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  158564. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  158565. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  158566. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  158567. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  158568. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  158569. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  158570. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  158571. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  158572. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  158573. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  158574. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  158575. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  158576. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  158577. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  158578. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  158579. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  158580. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  158581. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  158582. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  158583. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  158584. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  158585. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  158586. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  158587. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  158588. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  158589. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  158590. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  158591. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  158592. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  158593. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  158594. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  158595. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  158596. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  158597. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  158598. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  158599. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  158600. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  158601. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  158602. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  158603. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  158604. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  158605. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  158606. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  158607. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  158608. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  158609. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  158610. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  158611. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  158612. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  158613. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  158614. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  158615. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  158616. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  158617. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  158618. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  158619. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  158620. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  158621. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  158622. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  158623. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  158624. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  158625. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  158626. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  158627. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  158628. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  158629. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  158630. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  158631. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  158632. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  158633. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  158634. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  158635. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  158636. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  158637. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  158638. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  158639. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  158640. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  158641. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  158642. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  158643. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  158644. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  158645. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  158646. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  158647. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  158648. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  158649. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  158650. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  158651. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  158652. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  158653. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  158654. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  158655. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  158656. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  158657. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  158658. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  158659. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  158660. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  158661. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  158662. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  158663. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  158664. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  158665. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  158666. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  158667. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  158668. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  158669. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  158670. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  158671. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  158672. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  158673. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  158674. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  158675. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  158676. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  158677. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  158678. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  158679. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  158680. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  158681. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  158682. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  158683. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  158684. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  158685. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  158686. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  158687. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  158688. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  158689. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  158690. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  158691. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  158692. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  158693. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  158694. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  158695. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  158696. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  158697. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  158698. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  158699. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  158700. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  158701. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  158702. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  158703. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  158704. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  158705. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  158706. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  158707. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  158708. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  158709. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  158710. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  158711. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  158712. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  158713. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  158714. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  158715. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  158716. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  158717. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  158718. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  158719. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  158720. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  158721. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  158722. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  158723. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  158724. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  158725. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  158726. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  158727. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  158728. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  158729. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  158730. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  158731. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  158732. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  158733. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  158734. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  158735. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  158736. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  158737. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  158738. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  158739. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  158740. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  158741. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  158742. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  158743. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  158744. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  158745. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  158746. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  158747. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  158748. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  158749. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  158750. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  158751. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  158752. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  158753. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  158754. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  158755. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  158756. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  158757. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  158758. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  158759. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  158760. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  158761. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  158762. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  158763. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  158764. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  158765. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  158766. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  158767. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  158768. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  158769. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  158770. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  158771. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  158772. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  158773. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  158774. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  158775. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  158776. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  158777. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  158778. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  158779. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  158780. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  158781. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  158782. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  158783. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  158784. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  158785. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  158786. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  158787. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  158788. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  158789. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  158790. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  158791. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  158792. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  158793. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  158794. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  158795. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  158796. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  158797. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  158798. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  158799. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  158800. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  158801. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  158802. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  158803. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  158804. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  158805. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  158806. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  158807. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  158808. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  158809. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  158810. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  158811. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  158812. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  158813. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  158814. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  158815. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  158816. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  158817. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  158818. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  158819. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  158820. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  158821. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  158822. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  158823. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  158824. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  158825. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  158826. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  158827. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  158828. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  158829. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  158830. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  158831. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  158832. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  158833. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  158834. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  158835. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  158836. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  158837. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  158838. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  158839. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  158840. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  158841. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  158842. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  158843. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  158844. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  158845. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  158846. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  158847. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  158848. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  158849. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  158850. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  158851. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  158852. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  158853. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  158854. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  158855. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  158856. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  158857. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  158858. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  158859. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  158860. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  158861. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  158862. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  158863. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  158864. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  158865. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  158866. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  158867. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  158868. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  158869. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  158870. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  158871. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  158872. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  158873. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  158874. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  158875. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  158876. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  158877. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  158878. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  158879. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  158880. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  158881. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  158882. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  158883. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  158884. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  158885. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  158886. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  158887. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  158888. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  158889. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  158890. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  158891. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  158892. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  158893. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  158894. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  158895. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  158896. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  158897. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  158898. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  158899. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  158900. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  158901. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  158902. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  158903. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  158904. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  158905. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  158906. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  158907. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  158908. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  158909. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  158910. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  158911. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  158912. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  158913. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  158914. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  158915. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  158916. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  158917. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  158918. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  158919. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  158920. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  158921. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  158922. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  158923. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  158924. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  158925. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  158926. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  158927. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  158928. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  158929. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  158930. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  158931. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  158932. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  158933. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  158934. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  158935. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  158936. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  158937. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  158938. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  158939. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  158940. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  158941. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  158942. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  158943. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  158944. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  158945. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  158946. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  158947. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  158948. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  158949. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  158950. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  158951. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  158952. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  158953. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  158954. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  158955. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  158956. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  158957. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  158958. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  158959. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  158960. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  158961. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  158962. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  158963. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  158964. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  158965. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  158966. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  158967. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  158968. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  158969. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  158970. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  158971. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  158972. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  158973. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  158974. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  158975. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  158976. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  158977. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  158978. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  158979. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  158980. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  158981. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  158982. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  158983. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  158984. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  158985. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  158986. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  158987. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  158988. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  158989. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  158990. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  158991. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  158992. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  158993. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  158994. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  158995. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  158996. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  158997. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  158998. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  158999. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  159000. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  159001. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  159002. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  159003. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  159004. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  159005. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  159006. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  159007. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  159008. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  159009. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  159010. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  159011. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  159012. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  159013. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  159014. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  159015. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  159016. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  159017. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  159018. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  159019. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  159020. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  159021. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  159022. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  159023. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  159024. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  159025. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  159026. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  159027. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  159028. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  159029. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  159030. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  159031. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  159032. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  159033. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  159034. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  159035. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  159036. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  159037. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  159038. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  159039. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  159040. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  159041. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  159042. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  159043. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  159044. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  159045. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  159046. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  159047. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  159048. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  159049. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  159050. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  159051. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  159052. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  159053. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  159054. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  159055. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  159056. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  159057. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  159058. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  159059. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  159060. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  159061. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  159062. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  159063. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  159064. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  159065. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  159066. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  159067. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  159068. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  159069. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  159070. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  159071. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  159072. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  159073. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  159074. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  159075. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  159076. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  159077. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  159078. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  159079. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  159080. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  159081. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  159082. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  159083. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  159084. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  159085. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  159086. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  159087. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  159088. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  159089. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  159090. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  159091. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  159092. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  159093. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  159094. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  159095. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  159096. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  159097. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  159098. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  159099. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  159100. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  159101. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  159102. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  159103. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  159104. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  159105. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  159106. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  159107. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  159108. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  159109. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  159110. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  159111. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  159112. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  159113. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  159114. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  159115. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  159116. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  159117. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  159118. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  159119. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  159120. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  159121. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  159122. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  159123. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  159124. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  159125. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  159126. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  159127. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  159128. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  159129. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  159130. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  159131. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  159132. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  159133. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  159134. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  159135. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  159136. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  159137. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  159138. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  159139. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  159140. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  159141. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  159142. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  159143. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  159144. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  159145. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  159146. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  159147. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  159148. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  159149. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  159150. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  159151. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  159152. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  159153. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  159154. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  159155. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  159156. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  159157. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  159158. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  159159. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  159160. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  159161. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  159162. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  159163. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  159164. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  159165. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  159166. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  159167. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  159168. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  159169. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  159170. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  159171. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  159172. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  159173. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  159174. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  159175. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  159176. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  159177. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  159178. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  159179. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  159180. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  159181. };
  159182. static float *vwin[8] = {
  159183. vwin64,
  159184. vwin128,
  159185. vwin256,
  159186. vwin512,
  159187. vwin1024,
  159188. vwin2048,
  159189. vwin4096,
  159190. vwin8192,
  159191. };
  159192. float *_vorbis_window_get(int n){
  159193. return vwin[n];
  159194. }
  159195. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  159196. int lW,int W,int nW){
  159197. lW=(W?lW:0);
  159198. nW=(W?nW:0);
  159199. {
  159200. float *windowLW=vwin[winno[lW]];
  159201. float *windowNW=vwin[winno[nW]];
  159202. long n=blocksizes[W];
  159203. long ln=blocksizes[lW];
  159204. long rn=blocksizes[nW];
  159205. long leftbegin=n/4-ln/4;
  159206. long leftend=leftbegin+ln/2;
  159207. long rightbegin=n/2+n/4-rn/4;
  159208. long rightend=rightbegin+rn/2;
  159209. int i,p;
  159210. for(i=0;i<leftbegin;i++)
  159211. d[i]=0.f;
  159212. for(p=0;i<leftend;i++,p++)
  159213. d[i]*=windowLW[p];
  159214. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  159215. d[i]*=windowNW[p];
  159216. for(;i<n;i++)
  159217. d[i]=0.f;
  159218. }
  159219. }
  159220. #endif
  159221. /*** End of inlined file: window.c ***/
  159222. #else
  159223. #include <vorbis/vorbisenc.h>
  159224. #include <vorbis/codec.h>
  159225. #include <vorbis/vorbisfile.h>
  159226. #endif
  159227. }
  159228. #undef max
  159229. #undef min
  159230. BEGIN_JUCE_NAMESPACE
  159231. static const char* const oggFormatName = "Ogg-Vorbis file";
  159232. static const char* const oggExtensions[] = { ".ogg", 0 };
  159233. class OggReader : public AudioFormatReader
  159234. {
  159235. OggVorbisNamespace::OggVorbis_File ovFile;
  159236. OggVorbisNamespace::ov_callbacks callbacks;
  159237. AudioSampleBuffer reservoir;
  159238. int reservoirStart, samplesInReservoir;
  159239. public:
  159240. OggReader (InputStream* const inp)
  159241. : AudioFormatReader (inp, TRANS (oggFormatName)),
  159242. reservoir (2, 4096),
  159243. reservoirStart (0),
  159244. samplesInReservoir (0)
  159245. {
  159246. using namespace OggVorbisNamespace;
  159247. sampleRate = 0;
  159248. usesFloatingPointData = true;
  159249. callbacks.read_func = &oggReadCallback;
  159250. callbacks.seek_func = &oggSeekCallback;
  159251. callbacks.close_func = &oggCloseCallback;
  159252. callbacks.tell_func = &oggTellCallback;
  159253. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  159254. if (err == 0)
  159255. {
  159256. vorbis_info* info = ov_info (&ovFile, -1);
  159257. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  159258. numChannels = info->channels;
  159259. bitsPerSample = 16;
  159260. sampleRate = info->rate;
  159261. reservoir.setSize (numChannels,
  159262. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  159263. }
  159264. }
  159265. ~OggReader()
  159266. {
  159267. OggVorbisNamespace::ov_clear (&ovFile);
  159268. }
  159269. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  159270. int64 startSampleInFile, int numSamples)
  159271. {
  159272. while (numSamples > 0)
  159273. {
  159274. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  159275. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  159276. {
  159277. // got a few samples overlapping, so use them before seeking..
  159278. const int numToUse = jmin (numSamples, numAvailable);
  159279. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  159280. if (destSamples[i] != 0)
  159281. memcpy (destSamples[i] + startOffsetInDestBuffer,
  159282. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  159283. sizeof (float) * numToUse);
  159284. startSampleInFile += numToUse;
  159285. numSamples -= numToUse;
  159286. startOffsetInDestBuffer += numToUse;
  159287. if (numSamples == 0)
  159288. break;
  159289. }
  159290. if (startSampleInFile < reservoirStart
  159291. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  159292. {
  159293. // buffer miss, so refill the reservoir
  159294. int bitStream = 0;
  159295. reservoirStart = jmax (0, (int) startSampleInFile);
  159296. samplesInReservoir = reservoir.getNumSamples();
  159297. if (reservoirStart != (int) OggVorbisNamespace::ov_pcm_tell (&ovFile))
  159298. OggVorbisNamespace::ov_pcm_seek (&ovFile, reservoirStart);
  159299. int offset = 0;
  159300. int numToRead = samplesInReservoir;
  159301. while (numToRead > 0)
  159302. {
  159303. float** dataIn = 0;
  159304. const int samps = OggVorbisNamespace::ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  159305. if (samps <= 0)
  159306. break;
  159307. jassert (samps <= numToRead);
  159308. for (int i = jmin ((int) numChannels, reservoir.getNumChannels()); --i >= 0;)
  159309. {
  159310. memcpy (reservoir.getSampleData (i, offset),
  159311. dataIn[i],
  159312. sizeof (float) * samps);
  159313. }
  159314. numToRead -= samps;
  159315. offset += samps;
  159316. }
  159317. if (numToRead > 0)
  159318. reservoir.clear (offset, numToRead);
  159319. }
  159320. }
  159321. if (numSamples > 0)
  159322. {
  159323. for (int i = numDestChannels; --i >= 0;)
  159324. if (destSamples[i] != 0)
  159325. zeromem (destSamples[i] + startOffsetInDestBuffer,
  159326. sizeof (int) * numSamples);
  159327. }
  159328. return true;
  159329. }
  159330. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  159331. {
  159332. return (size_t) (static_cast <InputStream*> (datasource)->read (ptr, (int) (size * nmemb)) / size);
  159333. }
  159334. static int oggSeekCallback (void* datasource, OggVorbisNamespace::ogg_int64_t offset, int whence)
  159335. {
  159336. InputStream* const in = static_cast <InputStream*> (datasource);
  159337. if (whence == SEEK_CUR)
  159338. offset += in->getPosition();
  159339. else if (whence == SEEK_END)
  159340. offset += in->getTotalLength();
  159341. in->setPosition (offset);
  159342. return 0;
  159343. }
  159344. static int oggCloseCallback (void*)
  159345. {
  159346. return 0;
  159347. }
  159348. static long oggTellCallback (void* datasource)
  159349. {
  159350. return (long) static_cast <InputStream*> (datasource)->getPosition();
  159351. }
  159352. juce_UseDebuggingNewOperator
  159353. };
  159354. class OggWriter : public AudioFormatWriter
  159355. {
  159356. OggVorbisNamespace::ogg_stream_state os;
  159357. OggVorbisNamespace::ogg_page og;
  159358. OggVorbisNamespace::ogg_packet op;
  159359. OggVorbisNamespace::vorbis_info vi;
  159360. OggVorbisNamespace::vorbis_comment vc;
  159361. OggVorbisNamespace::vorbis_dsp_state vd;
  159362. OggVorbisNamespace::vorbis_block vb;
  159363. public:
  159364. bool ok;
  159365. OggWriter (OutputStream* const out,
  159366. const double sampleRate,
  159367. const int numChannels,
  159368. const int bitsPerSample,
  159369. const int qualityIndex)
  159370. : AudioFormatWriter (out, TRANS (oggFormatName),
  159371. sampleRate,
  159372. numChannels,
  159373. bitsPerSample)
  159374. {
  159375. using namespace OggVorbisNamespace;
  159376. ok = false;
  159377. vorbis_info_init (&vi);
  159378. if (vorbis_encode_init_vbr (&vi,
  159379. numChannels,
  159380. (int) sampleRate,
  159381. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  159382. {
  159383. vorbis_comment_init (&vc);
  159384. if (JUCEApplication::getInstance() != 0)
  159385. vorbis_comment_add_tag (&vc, "ENCODER", const_cast <char*> (JUCEApplication::getInstance()->getApplicationName().toUTF8()));
  159386. vorbis_analysis_init (&vd, &vi);
  159387. vorbis_block_init (&vd, &vb);
  159388. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  159389. ogg_packet header;
  159390. ogg_packet header_comm;
  159391. ogg_packet header_code;
  159392. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  159393. ogg_stream_packetin (&os, &header);
  159394. ogg_stream_packetin (&os, &header_comm);
  159395. ogg_stream_packetin (&os, &header_code);
  159396. for (;;)
  159397. {
  159398. if (ogg_stream_flush (&os, &og) == 0)
  159399. break;
  159400. output->write (og.header, og.header_len);
  159401. output->write (og.body, og.body_len);
  159402. }
  159403. ok = true;
  159404. }
  159405. }
  159406. ~OggWriter()
  159407. {
  159408. using namespace OggVorbisNamespace;
  159409. if (ok)
  159410. {
  159411. // write a zero-length packet to show ogg that we're finished..
  159412. write (0, 0);
  159413. ogg_stream_clear (&os);
  159414. vorbis_block_clear (&vb);
  159415. vorbis_dsp_clear (&vd);
  159416. vorbis_comment_clear (&vc);
  159417. vorbis_info_clear (&vi);
  159418. output->flush();
  159419. }
  159420. else
  159421. {
  159422. vorbis_info_clear (&vi);
  159423. output = 0; // to stop the base class deleting this, as it needs to be returned
  159424. // to the caller of createWriter()
  159425. }
  159426. }
  159427. bool write (const int** samplesToWrite, int numSamples)
  159428. {
  159429. using namespace OggVorbisNamespace;
  159430. if (! ok)
  159431. return false;
  159432. if (numSamples > 0)
  159433. {
  159434. const double gain = 1.0 / 0x80000000u;
  159435. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  159436. for (int i = numChannels; --i >= 0;)
  159437. {
  159438. float* const dst = vorbisBuffer[i];
  159439. const int* const src = samplesToWrite [i];
  159440. if (src != 0 && dst != 0)
  159441. {
  159442. for (int j = 0; j < numSamples; ++j)
  159443. dst[j] = (float) (src[j] * gain);
  159444. }
  159445. }
  159446. }
  159447. vorbis_analysis_wrote (&vd, numSamples);
  159448. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  159449. {
  159450. vorbis_analysis (&vb, 0);
  159451. vorbis_bitrate_addblock (&vb);
  159452. while (vorbis_bitrate_flushpacket (&vd, &op))
  159453. {
  159454. ogg_stream_packetin (&os, &op);
  159455. for (;;)
  159456. {
  159457. if (ogg_stream_pageout (&os, &og) == 0)
  159458. break;
  159459. output->write (og.header, og.header_len);
  159460. output->write (og.body, og.body_len);
  159461. if (ogg_page_eos (&og))
  159462. break;
  159463. }
  159464. }
  159465. }
  159466. return true;
  159467. }
  159468. juce_UseDebuggingNewOperator
  159469. };
  159470. OggVorbisAudioFormat::OggVorbisAudioFormat()
  159471. : AudioFormat (TRANS (oggFormatName), StringArray (oggExtensions))
  159472. {
  159473. }
  159474. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  159475. {
  159476. }
  159477. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  159478. {
  159479. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  159480. return Array <int> (rates);
  159481. }
  159482. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  159483. {
  159484. const int depths[] = { 32, 0 };
  159485. return Array <int> (depths);
  159486. }
  159487. bool OggVorbisAudioFormat::canDoStereo() { return true; }
  159488. bool OggVorbisAudioFormat::canDoMono() { return true; }
  159489. bool OggVorbisAudioFormat::isCompressed() { return true; }
  159490. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  159491. const bool deleteStreamIfOpeningFails)
  159492. {
  159493. ScopedPointer <OggReader> r (new OggReader (in));
  159494. if (r->sampleRate != 0)
  159495. return r.release();
  159496. if (! deleteStreamIfOpeningFails)
  159497. r->input = 0;
  159498. return 0;
  159499. }
  159500. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  159501. double sampleRate,
  159502. unsigned int numChannels,
  159503. int bitsPerSample,
  159504. const StringPairArray& /*metadataValues*/,
  159505. int qualityOptionIndex)
  159506. {
  159507. ScopedPointer <OggWriter> w (new OggWriter (out,
  159508. sampleRate,
  159509. numChannels,
  159510. bitsPerSample,
  159511. qualityOptionIndex));
  159512. return w->ok ? w.release() : 0;
  159513. }
  159514. const StringArray OggVorbisAudioFormat::getQualityOptions()
  159515. {
  159516. StringArray s;
  159517. s.add ("Low Quality");
  159518. s.add ("Medium Quality");
  159519. s.add ("High Quality");
  159520. return s;
  159521. }
  159522. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  159523. {
  159524. FileInputStream* const in = source.createInputStream();
  159525. if (in != 0)
  159526. {
  159527. ScopedPointer <AudioFormatReader> r (createReaderFor (in, true));
  159528. if (r != 0)
  159529. {
  159530. const int64 numSamps = r->lengthInSamples;
  159531. r = 0;
  159532. const int64 fileNumSamps = source.getSize() / 4;
  159533. const double ratio = numSamps / (double) fileNumSamps;
  159534. if (ratio > 12.0)
  159535. return 0;
  159536. else if (ratio > 6.0)
  159537. return 1;
  159538. else
  159539. return 2;
  159540. }
  159541. }
  159542. return 1;
  159543. }
  159544. END_JUCE_NAMESPACE
  159545. #endif
  159546. /*** End of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  159547. #endif
  159548. #if JUCE_BUILD_CORE && ! JUCE_ONLY_BUILD_CORE_LIBRARY // do these in the core section to help balance the sizes
  159549. /*** Start of inlined file: juce_JPEGLoader.cpp ***/
  159550. #if JUCE_MSVC
  159551. #pragma warning (push)
  159552. #endif
  159553. namespace jpeglibNamespace
  159554. {
  159555. #if JUCE_INCLUDE_JPEGLIB_CODE
  159556. #if JUCE_MINGW
  159557. typedef unsigned char boolean;
  159558. #endif
  159559. #define JPEG_INTERNALS
  159560. #undef FAR
  159561. /*** Start of inlined file: jpeglib.h ***/
  159562. #ifndef JPEGLIB_H
  159563. #define JPEGLIB_H
  159564. /*
  159565. * First we include the configuration files that record how this
  159566. * installation of the JPEG library is set up. jconfig.h can be
  159567. * generated automatically for many systems. jmorecfg.h contains
  159568. * manual configuration options that most people need not worry about.
  159569. */
  159570. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  159571. /*** Start of inlined file: jconfig.h ***/
  159572. /* see jconfig.doc for explanations */
  159573. // disable all the warnings under MSVC
  159574. #ifdef _MSC_VER
  159575. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  159576. #endif
  159577. #ifdef __BORLANDC__
  159578. #pragma warn -8057
  159579. #pragma warn -8019
  159580. #pragma warn -8004
  159581. #pragma warn -8008
  159582. #endif
  159583. #define HAVE_PROTOTYPES
  159584. #define HAVE_UNSIGNED_CHAR
  159585. #define HAVE_UNSIGNED_SHORT
  159586. /* #define void char */
  159587. /* #define const */
  159588. #undef CHAR_IS_UNSIGNED
  159589. #define HAVE_STDDEF_H
  159590. #define HAVE_STDLIB_H
  159591. #undef NEED_BSD_STRINGS
  159592. #undef NEED_SYS_TYPES_H
  159593. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  159594. #undef NEED_SHORT_EXTERNAL_NAMES
  159595. #undef INCOMPLETE_TYPES_BROKEN
  159596. /* Define "boolean" as unsigned char, not int, per Windows custom */
  159597. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  159598. typedef unsigned char boolean;
  159599. #endif
  159600. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  159601. #ifdef JPEG_INTERNALS
  159602. #undef RIGHT_SHIFT_IS_UNSIGNED
  159603. #endif /* JPEG_INTERNALS */
  159604. #ifdef JPEG_CJPEG_DJPEG
  159605. #define BMP_SUPPORTED /* BMP image file format */
  159606. #define GIF_SUPPORTED /* GIF image file format */
  159607. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  159608. #undef RLE_SUPPORTED /* Utah RLE image file format */
  159609. #define TARGA_SUPPORTED /* Targa image file format */
  159610. #define TWO_FILE_COMMANDLINE /* optional */
  159611. #define USE_SETMODE /* Microsoft has setmode() */
  159612. #undef NEED_SIGNAL_CATCHER
  159613. #undef DONT_USE_B_MODE
  159614. #undef PROGRESS_REPORT /* optional */
  159615. #endif /* JPEG_CJPEG_DJPEG */
  159616. /*** End of inlined file: jconfig.h ***/
  159617. /* widely used configuration options */
  159618. #endif
  159619. /*** Start of inlined file: jmorecfg.h ***/
  159620. /*
  159621. * Define BITS_IN_JSAMPLE as either
  159622. * 8 for 8-bit sample values (the usual setting)
  159623. * 12 for 12-bit sample values
  159624. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  159625. * JPEG standard, and the IJG code does not support anything else!
  159626. * We do not support run-time selection of data precision, sorry.
  159627. */
  159628. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  159629. /*
  159630. * Maximum number of components (color channels) allowed in JPEG image.
  159631. * To meet the letter of the JPEG spec, set this to 255. However, darn
  159632. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  159633. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  159634. * really short on memory. (Each allowed component costs a hundred or so
  159635. * bytes of storage, whether actually used in an image or not.)
  159636. */
  159637. #define MAX_COMPONENTS 10 /* maximum number of image components */
  159638. /*
  159639. * Basic data types.
  159640. * You may need to change these if you have a machine with unusual data
  159641. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  159642. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  159643. * but it had better be at least 16.
  159644. */
  159645. /* Representation of a single sample (pixel element value).
  159646. * We frequently allocate large arrays of these, so it's important to keep
  159647. * them small. But if you have memory to burn and access to char or short
  159648. * arrays is very slow on your hardware, you might want to change these.
  159649. */
  159650. #if BITS_IN_JSAMPLE == 8
  159651. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  159652. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  159653. */
  159654. #ifdef HAVE_UNSIGNED_CHAR
  159655. typedef unsigned char JSAMPLE;
  159656. #define GETJSAMPLE(value) ((int) (value))
  159657. #else /* not HAVE_UNSIGNED_CHAR */
  159658. typedef char JSAMPLE;
  159659. #ifdef CHAR_IS_UNSIGNED
  159660. #define GETJSAMPLE(value) ((int) (value))
  159661. #else
  159662. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  159663. #endif /* CHAR_IS_UNSIGNED */
  159664. #endif /* HAVE_UNSIGNED_CHAR */
  159665. #define MAXJSAMPLE 255
  159666. #define CENTERJSAMPLE 128
  159667. #endif /* BITS_IN_JSAMPLE == 8 */
  159668. #if BITS_IN_JSAMPLE == 12
  159669. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  159670. * On nearly all machines "short" will do nicely.
  159671. */
  159672. typedef short JSAMPLE;
  159673. #define GETJSAMPLE(value) ((int) (value))
  159674. #define MAXJSAMPLE 4095
  159675. #define CENTERJSAMPLE 2048
  159676. #endif /* BITS_IN_JSAMPLE == 12 */
  159677. /* Representation of a DCT frequency coefficient.
  159678. * This should be a signed value of at least 16 bits; "short" is usually OK.
  159679. * Again, we allocate large arrays of these, but you can change to int
  159680. * if you have memory to burn and "short" is really slow.
  159681. */
  159682. typedef short JCOEF;
  159683. /* Compressed datastreams are represented as arrays of JOCTET.
  159684. * These must be EXACTLY 8 bits wide, at least once they are written to
  159685. * external storage. Note that when using the stdio data source/destination
  159686. * managers, this is also the data type passed to fread/fwrite.
  159687. */
  159688. #ifdef HAVE_UNSIGNED_CHAR
  159689. typedef unsigned char JOCTET;
  159690. #define GETJOCTET(value) (value)
  159691. #else /* not HAVE_UNSIGNED_CHAR */
  159692. typedef char JOCTET;
  159693. #ifdef CHAR_IS_UNSIGNED
  159694. #define GETJOCTET(value) (value)
  159695. #else
  159696. #define GETJOCTET(value) ((value) & 0xFF)
  159697. #endif /* CHAR_IS_UNSIGNED */
  159698. #endif /* HAVE_UNSIGNED_CHAR */
  159699. /* These typedefs are used for various table entries and so forth.
  159700. * They must be at least as wide as specified; but making them too big
  159701. * won't cost a huge amount of memory, so we don't provide special
  159702. * extraction code like we did for JSAMPLE. (In other words, these
  159703. * typedefs live at a different point on the speed/space tradeoff curve.)
  159704. */
  159705. /* UINT8 must hold at least the values 0..255. */
  159706. #ifdef HAVE_UNSIGNED_CHAR
  159707. typedef unsigned char UINT8;
  159708. #else /* not HAVE_UNSIGNED_CHAR */
  159709. #ifdef CHAR_IS_UNSIGNED
  159710. typedef char UINT8;
  159711. #else /* not CHAR_IS_UNSIGNED */
  159712. typedef short UINT8;
  159713. #endif /* CHAR_IS_UNSIGNED */
  159714. #endif /* HAVE_UNSIGNED_CHAR */
  159715. /* UINT16 must hold at least the values 0..65535. */
  159716. #ifdef HAVE_UNSIGNED_SHORT
  159717. typedef unsigned short UINT16;
  159718. #else /* not HAVE_UNSIGNED_SHORT */
  159719. typedef unsigned int UINT16;
  159720. #endif /* HAVE_UNSIGNED_SHORT */
  159721. /* INT16 must hold at least the values -32768..32767. */
  159722. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  159723. typedef short INT16;
  159724. #endif
  159725. /* INT32 must hold at least signed 32-bit values. */
  159726. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  159727. typedef long INT32;
  159728. #endif
  159729. /* Datatype used for image dimensions. The JPEG standard only supports
  159730. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  159731. * "unsigned int" is sufficient on all machines. However, if you need to
  159732. * handle larger images and you don't mind deviating from the spec, you
  159733. * can change this datatype.
  159734. */
  159735. typedef unsigned int JDIMENSION;
  159736. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  159737. /* These macros are used in all function definitions and extern declarations.
  159738. * You could modify them if you need to change function linkage conventions;
  159739. * in particular, you'll need to do that to make the library a Windows DLL.
  159740. * Another application is to make all functions global for use with debuggers
  159741. * or code profilers that require it.
  159742. */
  159743. /* a function called through method pointers: */
  159744. #define METHODDEF(type) static type
  159745. /* a function used only in its module: */
  159746. #define LOCAL(type) static type
  159747. /* a function referenced thru EXTERNs: */
  159748. #define GLOBAL(type) type
  159749. /* a reference to a GLOBAL function: */
  159750. #define EXTERN(type) extern type
  159751. /* This macro is used to declare a "method", that is, a function pointer.
  159752. * We want to supply prototype parameters if the compiler can cope.
  159753. * Note that the arglist parameter must be parenthesized!
  159754. * Again, you can customize this if you need special linkage keywords.
  159755. */
  159756. #ifdef HAVE_PROTOTYPES
  159757. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  159758. #else
  159759. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  159760. #endif
  159761. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  159762. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  159763. * by just saying "FAR *" where such a pointer is needed. In a few places
  159764. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  159765. */
  159766. #ifdef NEED_FAR_POINTERS
  159767. #define FAR far
  159768. #else
  159769. #define FAR
  159770. #endif
  159771. /*
  159772. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  159773. * in standard header files. Or you may have conflicts with application-
  159774. * specific header files that you want to include together with these files.
  159775. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  159776. */
  159777. #ifndef HAVE_BOOLEAN
  159778. typedef int boolean;
  159779. #endif
  159780. #ifndef FALSE /* in case these macros already exist */
  159781. #define FALSE 0 /* values of boolean */
  159782. #endif
  159783. #ifndef TRUE
  159784. #define TRUE 1
  159785. #endif
  159786. /*
  159787. * The remaining options affect code selection within the JPEG library,
  159788. * but they don't need to be visible to most applications using the library.
  159789. * To minimize application namespace pollution, the symbols won't be
  159790. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  159791. */
  159792. #ifdef JPEG_INTERNALS
  159793. #define JPEG_INTERNAL_OPTIONS
  159794. #endif
  159795. #ifdef JPEG_INTERNAL_OPTIONS
  159796. /*
  159797. * These defines indicate whether to include various optional functions.
  159798. * Undefining some of these symbols will produce a smaller but less capable
  159799. * library. Note that you can leave certain source files out of the
  159800. * compilation/linking process if you've #undef'd the corresponding symbols.
  159801. * (You may HAVE to do that if your compiler doesn't like null source files.)
  159802. */
  159803. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  159804. /* Capability options common to encoder and decoder: */
  159805. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  159806. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  159807. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  159808. /* Encoder capability options: */
  159809. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159810. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159811. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159812. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  159813. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  159814. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  159815. * precision, so jchuff.c normally uses entropy optimization to compute
  159816. * usable tables for higher precision. If you don't want to do optimization,
  159817. * you'll have to supply different default Huffman tables.
  159818. * The exact same statements apply for progressive JPEG: the default tables
  159819. * don't work for progressive mode. (This may get fixed, however.)
  159820. */
  159821. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  159822. /* Decoder capability options: */
  159823. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  159824. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  159825. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  159826. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  159827. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  159828. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  159829. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  159830. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  159831. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  159832. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  159833. /* more capability options later, no doubt */
  159834. /*
  159835. * Ordering of RGB data in scanlines passed to or from the application.
  159836. * If your application wants to deal with data in the order B,G,R, just
  159837. * change these macros. You can also deal with formats such as R,G,B,X
  159838. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  159839. * the offsets will also change the order in which colormap data is organized.
  159840. * RESTRICTIONS:
  159841. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  159842. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  159843. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  159844. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  159845. * is not 3 (they don't understand about dummy color components!). So you
  159846. * can't use color quantization if you change that value.
  159847. */
  159848. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  159849. #define RGB_GREEN 1 /* Offset of Green */
  159850. #define RGB_BLUE 2 /* Offset of Blue */
  159851. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  159852. /* Definitions for speed-related optimizations. */
  159853. /* If your compiler supports inline functions, define INLINE
  159854. * as the inline keyword; otherwise define it as empty.
  159855. */
  159856. #ifndef INLINE
  159857. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  159858. #define INLINE __inline__
  159859. #endif
  159860. #ifndef INLINE
  159861. #define INLINE /* default is to define it as empty */
  159862. #endif
  159863. #endif
  159864. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  159865. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  159866. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  159867. */
  159868. #ifndef MULTIPLIER
  159869. #define MULTIPLIER int /* type for fastest integer multiply */
  159870. #endif
  159871. /* FAST_FLOAT should be either float or double, whichever is done faster
  159872. * by your compiler. (Note that this type is only used in the floating point
  159873. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  159874. * Typically, float is faster in ANSI C compilers, while double is faster in
  159875. * pre-ANSI compilers (because they insist on converting to double anyway).
  159876. * The code below therefore chooses float if we have ANSI-style prototypes.
  159877. */
  159878. #ifndef FAST_FLOAT
  159879. #ifdef HAVE_PROTOTYPES
  159880. #define FAST_FLOAT float
  159881. #else
  159882. #define FAST_FLOAT double
  159883. #endif
  159884. #endif
  159885. #endif /* JPEG_INTERNAL_OPTIONS */
  159886. /*** End of inlined file: jmorecfg.h ***/
  159887. /* seldom changed options */
  159888. /* Version ID for the JPEG library.
  159889. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  159890. */
  159891. #define JPEG_LIB_VERSION 62 /* Version 6b */
  159892. /* Various constants determining the sizes of things.
  159893. * All of these are specified by the JPEG standard, so don't change them
  159894. * if you want to be compatible.
  159895. */
  159896. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  159897. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  159898. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  159899. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  159900. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  159901. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  159902. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  159903. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  159904. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  159905. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  159906. * to handle it. We even let you do this from the jconfig.h file. However,
  159907. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  159908. * sometimes emits noncompliant files doesn't mean you should too.
  159909. */
  159910. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  159911. #ifndef D_MAX_BLOCKS_IN_MCU
  159912. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  159913. #endif
  159914. /* Data structures for images (arrays of samples and of DCT coefficients).
  159915. * On 80x86 machines, the image arrays are too big for near pointers,
  159916. * but the pointer arrays can fit in near memory.
  159917. */
  159918. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  159919. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  159920. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  159921. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  159922. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  159923. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  159924. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  159925. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  159926. /* Types for JPEG compression parameters and working tables. */
  159927. /* DCT coefficient quantization tables. */
  159928. typedef struct {
  159929. /* This array gives the coefficient quantizers in natural array order
  159930. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  159931. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  159932. */
  159933. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  159934. /* This field is used only during compression. It's initialized FALSE when
  159935. * the table is created, and set TRUE when it's been output to the file.
  159936. * You could suppress output of a table by setting this to TRUE.
  159937. * (See jpeg_suppress_tables for an example.)
  159938. */
  159939. boolean sent_table; /* TRUE when table has been output */
  159940. } JQUANT_TBL;
  159941. /* Huffman coding tables. */
  159942. typedef struct {
  159943. /* These two fields directly represent the contents of a JPEG DHT marker */
  159944. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  159945. /* length k bits; bits[0] is unused */
  159946. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  159947. /* This field is used only during compression. It's initialized FALSE when
  159948. * the table is created, and set TRUE when it's been output to the file.
  159949. * You could suppress output of a table by setting this to TRUE.
  159950. * (See jpeg_suppress_tables for an example.)
  159951. */
  159952. boolean sent_table; /* TRUE when table has been output */
  159953. } JHUFF_TBL;
  159954. /* Basic info about one component (color channel). */
  159955. typedef struct {
  159956. /* These values are fixed over the whole image. */
  159957. /* For compression, they must be supplied by parameter setup; */
  159958. /* for decompression, they are read from the SOF marker. */
  159959. int component_id; /* identifier for this component (0..255) */
  159960. int component_index; /* its index in SOF or cinfo->comp_info[] */
  159961. int h_samp_factor; /* horizontal sampling factor (1..4) */
  159962. int v_samp_factor; /* vertical sampling factor (1..4) */
  159963. int quant_tbl_no; /* quantization table selector (0..3) */
  159964. /* These values may vary between scans. */
  159965. /* For compression, they must be supplied by parameter setup; */
  159966. /* for decompression, they are read from the SOS marker. */
  159967. /* The decompressor output side may not use these variables. */
  159968. int dc_tbl_no; /* DC entropy table selector (0..3) */
  159969. int ac_tbl_no; /* AC entropy table selector (0..3) */
  159970. /* Remaining fields should be treated as private by applications. */
  159971. /* These values are computed during compression or decompression startup: */
  159972. /* Component's size in DCT blocks.
  159973. * Any dummy blocks added to complete an MCU are not counted; therefore
  159974. * these values do not depend on whether a scan is interleaved or not.
  159975. */
  159976. JDIMENSION width_in_blocks;
  159977. JDIMENSION height_in_blocks;
  159978. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  159979. * For decompression this is the size of the output from one DCT block,
  159980. * reflecting any scaling we choose to apply during the IDCT step.
  159981. * Values of 1,2,4,8 are likely to be supported. Note that different
  159982. * components may receive different IDCT scalings.
  159983. */
  159984. int DCT_scaled_size;
  159985. /* The downsampled dimensions are the component's actual, unpadded number
  159986. * of samples at the main buffer (preprocessing/compression interface), thus
  159987. * downsampled_width = ceil(image_width * Hi/Hmax)
  159988. * and similarly for height. For decompression, IDCT scaling is included, so
  159989. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  159990. */
  159991. JDIMENSION downsampled_width; /* actual width in samples */
  159992. JDIMENSION downsampled_height; /* actual height in samples */
  159993. /* This flag is used only for decompression. In cases where some of the
  159994. * components will be ignored (eg grayscale output from YCbCr image),
  159995. * we can skip most computations for the unused components.
  159996. */
  159997. boolean component_needed; /* do we need the value of this component? */
  159998. /* These values are computed before starting a scan of the component. */
  159999. /* The decompressor output side may not use these variables. */
  160000. int MCU_width; /* number of blocks per MCU, horizontally */
  160001. int MCU_height; /* number of blocks per MCU, vertically */
  160002. int MCU_blocks; /* MCU_width * MCU_height */
  160003. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  160004. int last_col_width; /* # of non-dummy blocks across in last MCU */
  160005. int last_row_height; /* # of non-dummy blocks down in last MCU */
  160006. /* Saved quantization table for component; NULL if none yet saved.
  160007. * See jdinput.c comments about the need for this information.
  160008. * This field is currently used only for decompression.
  160009. */
  160010. JQUANT_TBL * quant_table;
  160011. /* Private per-component storage for DCT or IDCT subsystem. */
  160012. void * dct_table;
  160013. } jpeg_component_info;
  160014. /* The script for encoding a multiple-scan file is an array of these: */
  160015. typedef struct {
  160016. int comps_in_scan; /* number of components encoded in this scan */
  160017. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  160018. int Ss, Se; /* progressive JPEG spectral selection parms */
  160019. int Ah, Al; /* progressive JPEG successive approx. parms */
  160020. } jpeg_scan_info;
  160021. /* The decompressor can save APPn and COM markers in a list of these: */
  160022. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  160023. struct jpeg_marker_struct {
  160024. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  160025. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  160026. unsigned int original_length; /* # bytes of data in the file */
  160027. unsigned int data_length; /* # bytes of data saved at data[] */
  160028. JOCTET FAR * data; /* the data contained in the marker */
  160029. /* the marker length word is not counted in data_length or original_length */
  160030. };
  160031. /* Known color spaces. */
  160032. typedef enum {
  160033. JCS_UNKNOWN, /* error/unspecified */
  160034. JCS_GRAYSCALE, /* monochrome */
  160035. JCS_RGB, /* red/green/blue */
  160036. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  160037. JCS_CMYK, /* C/M/Y/K */
  160038. JCS_YCCK /* Y/Cb/Cr/K */
  160039. } J_COLOR_SPACE;
  160040. /* DCT/IDCT algorithm options. */
  160041. typedef enum {
  160042. JDCT_ISLOW, /* slow but accurate integer algorithm */
  160043. JDCT_IFAST, /* faster, less accurate integer method */
  160044. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  160045. } J_DCT_METHOD;
  160046. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  160047. #define JDCT_DEFAULT JDCT_ISLOW
  160048. #endif
  160049. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  160050. #define JDCT_FASTEST JDCT_IFAST
  160051. #endif
  160052. /* Dithering options for decompression. */
  160053. typedef enum {
  160054. JDITHER_NONE, /* no dithering */
  160055. JDITHER_ORDERED, /* simple ordered dither */
  160056. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  160057. } J_DITHER_MODE;
  160058. /* Common fields between JPEG compression and decompression master structs. */
  160059. #define jpeg_common_fields \
  160060. struct jpeg_error_mgr * err; /* Error handler module */\
  160061. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  160062. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  160063. void * client_data; /* Available for use by application */\
  160064. boolean is_decompressor; /* So common code can tell which is which */\
  160065. int global_state /* For checking call sequence validity */
  160066. /* Routines that are to be used by both halves of the library are declared
  160067. * to receive a pointer to this structure. There are no actual instances of
  160068. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  160069. */
  160070. struct jpeg_common_struct {
  160071. jpeg_common_fields; /* Fields common to both master struct types */
  160072. /* Additional fields follow in an actual jpeg_compress_struct or
  160073. * jpeg_decompress_struct. All three structs must agree on these
  160074. * initial fields! (This would be a lot cleaner in C++.)
  160075. */
  160076. };
  160077. typedef struct jpeg_common_struct * j_common_ptr;
  160078. typedef struct jpeg_compress_struct * j_compress_ptr;
  160079. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  160080. /* Master record for a compression instance */
  160081. struct jpeg_compress_struct {
  160082. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  160083. /* Destination for compressed data */
  160084. struct jpeg_destination_mgr * dest;
  160085. /* Description of source image --- these fields must be filled in by
  160086. * outer application before starting compression. in_color_space must
  160087. * be correct before you can even call jpeg_set_defaults().
  160088. */
  160089. JDIMENSION image_width; /* input image width */
  160090. JDIMENSION image_height; /* input image height */
  160091. int input_components; /* # of color components in input image */
  160092. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  160093. double input_gamma; /* image gamma of input image */
  160094. /* Compression parameters --- these fields must be set before calling
  160095. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  160096. * initialize everything to reasonable defaults, then changing anything
  160097. * the application specifically wants to change. That way you won't get
  160098. * burnt when new parameters are added. Also note that there are several
  160099. * helper routines to simplify changing parameters.
  160100. */
  160101. int data_precision; /* bits of precision in image data */
  160102. int num_components; /* # of color components in JPEG image */
  160103. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  160104. jpeg_component_info * comp_info;
  160105. /* comp_info[i] describes component that appears i'th in SOF */
  160106. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  160107. /* ptrs to coefficient quantization tables, or NULL if not defined */
  160108. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160109. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160110. /* ptrs to Huffman coding tables, or NULL if not defined */
  160111. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  160112. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  160113. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  160114. int num_scans; /* # of entries in scan_info array */
  160115. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  160116. /* The default value of scan_info is NULL, which causes a single-scan
  160117. * sequential JPEG file to be emitted. To create a multi-scan file,
  160118. * set num_scans and scan_info to point to an array of scan definitions.
  160119. */
  160120. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  160121. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  160122. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  160123. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  160124. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  160125. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  160126. /* The restart interval can be specified in absolute MCUs by setting
  160127. * restart_interval, or in MCU rows by setting restart_in_rows
  160128. * (in which case the correct restart_interval will be figured
  160129. * for each scan).
  160130. */
  160131. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  160132. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  160133. /* Parameters controlling emission of special markers. */
  160134. boolean write_JFIF_header; /* should a JFIF marker be written? */
  160135. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  160136. UINT8 JFIF_minor_version;
  160137. /* These three values are not used by the JPEG code, merely copied */
  160138. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  160139. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  160140. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  160141. UINT8 density_unit; /* JFIF code for pixel size units */
  160142. UINT16 X_density; /* Horizontal pixel density */
  160143. UINT16 Y_density; /* Vertical pixel density */
  160144. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  160145. /* State variable: index of next scanline to be written to
  160146. * jpeg_write_scanlines(). Application may use this to control its
  160147. * processing loop, e.g., "while (next_scanline < image_height)".
  160148. */
  160149. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  160150. /* Remaining fields are known throughout compressor, but generally
  160151. * should not be touched by a surrounding application.
  160152. */
  160153. /*
  160154. * These fields are computed during compression startup
  160155. */
  160156. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  160157. int max_h_samp_factor; /* largest h_samp_factor */
  160158. int max_v_samp_factor; /* largest v_samp_factor */
  160159. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  160160. /* The coefficient controller receives data in units of MCU rows as defined
  160161. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  160162. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  160163. * "iMCU" (interleaved MCU) row.
  160164. */
  160165. /*
  160166. * These fields are valid during any one scan.
  160167. * They describe the components and MCUs actually appearing in the scan.
  160168. */
  160169. int comps_in_scan; /* # of JPEG components in this scan */
  160170. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  160171. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  160172. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  160173. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  160174. int blocks_in_MCU; /* # of DCT blocks per MCU */
  160175. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  160176. /* MCU_membership[i] is index in cur_comp_info of component owning */
  160177. /* i'th block in an MCU */
  160178. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  160179. /*
  160180. * Links to compression subobjects (methods and private variables of modules)
  160181. */
  160182. struct jpeg_comp_master * master;
  160183. struct jpeg_c_main_controller * main;
  160184. struct jpeg_c_prep_controller * prep;
  160185. struct jpeg_c_coef_controller * coef;
  160186. struct jpeg_marker_writer * marker;
  160187. struct jpeg_color_converter * cconvert;
  160188. struct jpeg_downsampler * downsample;
  160189. struct jpeg_forward_dct * fdct;
  160190. struct jpeg_entropy_encoder * entropy;
  160191. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  160192. int script_space_size;
  160193. };
  160194. /* Master record for a decompression instance */
  160195. struct jpeg_decompress_struct {
  160196. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  160197. /* Source of compressed data */
  160198. struct jpeg_source_mgr * src;
  160199. /* Basic description of image --- filled in by jpeg_read_header(). */
  160200. /* Application may inspect these values to decide how to process image. */
  160201. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  160202. JDIMENSION image_height; /* nominal image height */
  160203. int num_components; /* # of color components in JPEG image */
  160204. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  160205. /* Decompression processing parameters --- these fields must be set before
  160206. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  160207. * them to default values.
  160208. */
  160209. J_COLOR_SPACE out_color_space; /* colorspace for output */
  160210. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  160211. double output_gamma; /* image gamma wanted in output */
  160212. boolean buffered_image; /* TRUE=multiple output passes */
  160213. boolean raw_data_out; /* TRUE=downsampled data wanted */
  160214. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  160215. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  160216. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  160217. boolean quantize_colors; /* TRUE=colormapped output wanted */
  160218. /* the following are ignored if not quantize_colors: */
  160219. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  160220. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  160221. int desired_number_of_colors; /* max # colors to use in created colormap */
  160222. /* these are significant only in buffered-image mode: */
  160223. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  160224. boolean enable_external_quant;/* enable future use of external colormap */
  160225. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  160226. /* Description of actual output image that will be returned to application.
  160227. * These fields are computed by jpeg_start_decompress().
  160228. * You can also use jpeg_calc_output_dimensions() to determine these values
  160229. * in advance of calling jpeg_start_decompress().
  160230. */
  160231. JDIMENSION output_width; /* scaled image width */
  160232. JDIMENSION output_height; /* scaled image height */
  160233. int out_color_components; /* # of color components in out_color_space */
  160234. int output_components; /* # of color components returned */
  160235. /* output_components is 1 (a colormap index) when quantizing colors;
  160236. * otherwise it equals out_color_components.
  160237. */
  160238. int rec_outbuf_height; /* min recommended height of scanline buffer */
  160239. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  160240. * high, space and time will be wasted due to unnecessary data copying.
  160241. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  160242. */
  160243. /* When quantizing colors, the output colormap is described by these fields.
  160244. * The application can supply a colormap by setting colormap non-NULL before
  160245. * calling jpeg_start_decompress; otherwise a colormap is created during
  160246. * jpeg_start_decompress or jpeg_start_output.
  160247. * The map has out_color_components rows and actual_number_of_colors columns.
  160248. */
  160249. int actual_number_of_colors; /* number of entries in use */
  160250. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  160251. /* State variables: these variables indicate the progress of decompression.
  160252. * The application may examine these but must not modify them.
  160253. */
  160254. /* Row index of next scanline to be read from jpeg_read_scanlines().
  160255. * Application may use this to control its processing loop, e.g.,
  160256. * "while (output_scanline < output_height)".
  160257. */
  160258. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  160259. /* Current input scan number and number of iMCU rows completed in scan.
  160260. * These indicate the progress of the decompressor input side.
  160261. */
  160262. int input_scan_number; /* Number of SOS markers seen so far */
  160263. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  160264. /* The "output scan number" is the notional scan being displayed by the
  160265. * output side. The decompressor will not allow output scan/row number
  160266. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  160267. */
  160268. int output_scan_number; /* Nominal scan number being displayed */
  160269. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  160270. /* Current progression status. coef_bits[c][i] indicates the precision
  160271. * with which component c's DCT coefficient i (in zigzag order) is known.
  160272. * It is -1 when no data has yet been received, otherwise it is the point
  160273. * transform (shift) value for the most recent scan of the coefficient
  160274. * (thus, 0 at completion of the progression).
  160275. * This pointer is NULL when reading a non-progressive file.
  160276. */
  160277. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  160278. /* Internal JPEG parameters --- the application usually need not look at
  160279. * these fields. Note that the decompressor output side may not use
  160280. * any parameters that can change between scans.
  160281. */
  160282. /* Quantization and Huffman tables are carried forward across input
  160283. * datastreams when processing abbreviated JPEG datastreams.
  160284. */
  160285. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  160286. /* ptrs to coefficient quantization tables, or NULL if not defined */
  160287. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160288. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160289. /* ptrs to Huffman coding tables, or NULL if not defined */
  160290. /* These parameters are never carried across datastreams, since they
  160291. * are given in SOF/SOS markers or defined to be reset by SOI.
  160292. */
  160293. int data_precision; /* bits of precision in image data */
  160294. jpeg_component_info * comp_info;
  160295. /* comp_info[i] describes component that appears i'th in SOF */
  160296. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  160297. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  160298. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  160299. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  160300. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  160301. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  160302. /* These fields record data obtained from optional markers recognized by
  160303. * the JPEG library.
  160304. */
  160305. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  160306. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  160307. UINT8 JFIF_major_version; /* JFIF version number */
  160308. UINT8 JFIF_minor_version;
  160309. UINT8 density_unit; /* JFIF code for pixel size units */
  160310. UINT16 X_density; /* Horizontal pixel density */
  160311. UINT16 Y_density; /* Vertical pixel density */
  160312. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  160313. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  160314. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  160315. /* Aside from the specific data retained from APPn markers known to the
  160316. * library, the uninterpreted contents of any or all APPn and COM markers
  160317. * can be saved in a list for examination by the application.
  160318. */
  160319. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  160320. /* Remaining fields are known throughout decompressor, but generally
  160321. * should not be touched by a surrounding application.
  160322. */
  160323. /*
  160324. * These fields are computed during decompression startup
  160325. */
  160326. int max_h_samp_factor; /* largest h_samp_factor */
  160327. int max_v_samp_factor; /* largest v_samp_factor */
  160328. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  160329. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  160330. /* The coefficient controller's input and output progress is measured in
  160331. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  160332. * in fully interleaved JPEG scans, but are used whether the scan is
  160333. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  160334. * rows of each component. Therefore, the IDCT output contains
  160335. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  160336. */
  160337. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  160338. /*
  160339. * These fields are valid during any one scan.
  160340. * They describe the components and MCUs actually appearing in the scan.
  160341. * Note that the decompressor output side must not use these fields.
  160342. */
  160343. int comps_in_scan; /* # of JPEG components in this scan */
  160344. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  160345. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  160346. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  160347. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  160348. int blocks_in_MCU; /* # of DCT blocks per MCU */
  160349. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  160350. /* MCU_membership[i] is index in cur_comp_info of component owning */
  160351. /* i'th block in an MCU */
  160352. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  160353. /* This field is shared between entropy decoder and marker parser.
  160354. * It is either zero or the code of a JPEG marker that has been
  160355. * read from the data source, but has not yet been processed.
  160356. */
  160357. int unread_marker;
  160358. /*
  160359. * Links to decompression subobjects (methods, private variables of modules)
  160360. */
  160361. struct jpeg_decomp_master * master;
  160362. struct jpeg_d_main_controller * main;
  160363. struct jpeg_d_coef_controller * coef;
  160364. struct jpeg_d_post_controller * post;
  160365. struct jpeg_input_controller * inputctl;
  160366. struct jpeg_marker_reader * marker;
  160367. struct jpeg_entropy_decoder * entropy;
  160368. struct jpeg_inverse_dct * idct;
  160369. struct jpeg_upsampler * upsample;
  160370. struct jpeg_color_deconverter * cconvert;
  160371. struct jpeg_color_quantizer * cquantize;
  160372. };
  160373. /* "Object" declarations for JPEG modules that may be supplied or called
  160374. * directly by the surrounding application.
  160375. * As with all objects in the JPEG library, these structs only define the
  160376. * publicly visible methods and state variables of a module. Additional
  160377. * private fields may exist after the public ones.
  160378. */
  160379. /* Error handler object */
  160380. struct jpeg_error_mgr {
  160381. /* Error exit handler: does not return to caller */
  160382. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  160383. /* Conditionally emit a trace or warning message */
  160384. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  160385. /* Routine that actually outputs a trace or error message */
  160386. JMETHOD(void, output_message, (j_common_ptr cinfo));
  160387. /* Format a message string for the most recent JPEG error or message */
  160388. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  160389. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  160390. /* Reset error state variables at start of a new image */
  160391. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  160392. /* The message ID code and any parameters are saved here.
  160393. * A message can have one string parameter or up to 8 int parameters.
  160394. */
  160395. int msg_code;
  160396. #define JMSG_STR_PARM_MAX 80
  160397. union {
  160398. int i[8];
  160399. char s[JMSG_STR_PARM_MAX];
  160400. } msg_parm;
  160401. /* Standard state variables for error facility */
  160402. int trace_level; /* max msg_level that will be displayed */
  160403. /* For recoverable corrupt-data errors, we emit a warning message,
  160404. * but keep going unless emit_message chooses to abort. emit_message
  160405. * should count warnings in num_warnings. The surrounding application
  160406. * can check for bad data by seeing if num_warnings is nonzero at the
  160407. * end of processing.
  160408. */
  160409. long num_warnings; /* number of corrupt-data warnings */
  160410. /* These fields point to the table(s) of error message strings.
  160411. * An application can change the table pointer to switch to a different
  160412. * message list (typically, to change the language in which errors are
  160413. * reported). Some applications may wish to add additional error codes
  160414. * that will be handled by the JPEG library error mechanism; the second
  160415. * table pointer is used for this purpose.
  160416. *
  160417. * First table includes all errors generated by JPEG library itself.
  160418. * Error code 0 is reserved for a "no such error string" message.
  160419. */
  160420. const char * const * jpeg_message_table; /* Library errors */
  160421. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  160422. /* Second table can be added by application (see cjpeg/djpeg for example).
  160423. * It contains strings numbered first_addon_message..last_addon_message.
  160424. */
  160425. const char * const * addon_message_table; /* Non-library errors */
  160426. int first_addon_message; /* code for first string in addon table */
  160427. int last_addon_message; /* code for last string in addon table */
  160428. };
  160429. /* Progress monitor object */
  160430. struct jpeg_progress_mgr {
  160431. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  160432. long pass_counter; /* work units completed in this pass */
  160433. long pass_limit; /* total number of work units in this pass */
  160434. int completed_passes; /* passes completed so far */
  160435. int total_passes; /* total number of passes expected */
  160436. };
  160437. /* Data destination object for compression */
  160438. struct jpeg_destination_mgr {
  160439. JOCTET * next_output_byte; /* => next byte to write in buffer */
  160440. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  160441. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  160442. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  160443. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  160444. };
  160445. /* Data source object for decompression */
  160446. struct jpeg_source_mgr {
  160447. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  160448. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  160449. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  160450. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  160451. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  160452. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  160453. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  160454. };
  160455. /* Memory manager object.
  160456. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  160457. * and "really big" objects (virtual arrays with backing store if needed).
  160458. * The memory manager does not allow individual objects to be freed; rather,
  160459. * each created object is assigned to a pool, and whole pools can be freed
  160460. * at once. This is faster and more convenient than remembering exactly what
  160461. * to free, especially where malloc()/free() are not too speedy.
  160462. * NB: alloc routines never return NULL. They exit to error_exit if not
  160463. * successful.
  160464. */
  160465. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  160466. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  160467. #define JPOOL_NUMPOOLS 2
  160468. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  160469. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  160470. struct jpeg_memory_mgr {
  160471. /* Method pointers */
  160472. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  160473. size_t sizeofobject));
  160474. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  160475. size_t sizeofobject));
  160476. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  160477. JDIMENSION samplesperrow,
  160478. JDIMENSION numrows));
  160479. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  160480. JDIMENSION blocksperrow,
  160481. JDIMENSION numrows));
  160482. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  160483. int pool_id,
  160484. boolean pre_zero,
  160485. JDIMENSION samplesperrow,
  160486. JDIMENSION numrows,
  160487. JDIMENSION maxaccess));
  160488. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  160489. int pool_id,
  160490. boolean pre_zero,
  160491. JDIMENSION blocksperrow,
  160492. JDIMENSION numrows,
  160493. JDIMENSION maxaccess));
  160494. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  160495. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  160496. jvirt_sarray_ptr ptr,
  160497. JDIMENSION start_row,
  160498. JDIMENSION num_rows,
  160499. boolean writable));
  160500. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  160501. jvirt_barray_ptr ptr,
  160502. JDIMENSION start_row,
  160503. JDIMENSION num_rows,
  160504. boolean writable));
  160505. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  160506. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  160507. /* Limit on memory allocation for this JPEG object. (Note that this is
  160508. * merely advisory, not a guaranteed maximum; it only affects the space
  160509. * used for virtual-array buffers.) May be changed by outer application
  160510. * after creating the JPEG object.
  160511. */
  160512. long max_memory_to_use;
  160513. /* Maximum allocation request accepted by alloc_large. */
  160514. long max_alloc_chunk;
  160515. };
  160516. /* Routine signature for application-supplied marker processing methods.
  160517. * Need not pass marker code since it is stored in cinfo->unread_marker.
  160518. */
  160519. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  160520. /* Declarations for routines called by application.
  160521. * The JPP macro hides prototype parameters from compilers that can't cope.
  160522. * Note JPP requires double parentheses.
  160523. */
  160524. #ifdef HAVE_PROTOTYPES
  160525. #define JPP(arglist) arglist
  160526. #else
  160527. #define JPP(arglist) ()
  160528. #endif
  160529. /* Short forms of external names for systems with brain-damaged linkers.
  160530. * We shorten external names to be unique in the first six letters, which
  160531. * is good enough for all known systems.
  160532. * (If your compiler itself needs names to be unique in less than 15
  160533. * characters, you are out of luck. Get a better compiler.)
  160534. */
  160535. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160536. #define jpeg_std_error jStdError
  160537. #define jpeg_CreateCompress jCreaCompress
  160538. #define jpeg_CreateDecompress jCreaDecompress
  160539. #define jpeg_destroy_compress jDestCompress
  160540. #define jpeg_destroy_decompress jDestDecompress
  160541. #define jpeg_stdio_dest jStdDest
  160542. #define jpeg_stdio_src jStdSrc
  160543. #define jpeg_set_defaults jSetDefaults
  160544. #define jpeg_set_colorspace jSetColorspace
  160545. #define jpeg_default_colorspace jDefColorspace
  160546. #define jpeg_set_quality jSetQuality
  160547. #define jpeg_set_linear_quality jSetLQuality
  160548. #define jpeg_add_quant_table jAddQuantTable
  160549. #define jpeg_quality_scaling jQualityScaling
  160550. #define jpeg_simple_progression jSimProgress
  160551. #define jpeg_suppress_tables jSuppressTables
  160552. #define jpeg_alloc_quant_table jAlcQTable
  160553. #define jpeg_alloc_huff_table jAlcHTable
  160554. #define jpeg_start_compress jStrtCompress
  160555. #define jpeg_write_scanlines jWrtScanlines
  160556. #define jpeg_finish_compress jFinCompress
  160557. #define jpeg_write_raw_data jWrtRawData
  160558. #define jpeg_write_marker jWrtMarker
  160559. #define jpeg_write_m_header jWrtMHeader
  160560. #define jpeg_write_m_byte jWrtMByte
  160561. #define jpeg_write_tables jWrtTables
  160562. #define jpeg_read_header jReadHeader
  160563. #define jpeg_start_decompress jStrtDecompress
  160564. #define jpeg_read_scanlines jReadScanlines
  160565. #define jpeg_finish_decompress jFinDecompress
  160566. #define jpeg_read_raw_data jReadRawData
  160567. #define jpeg_has_multiple_scans jHasMultScn
  160568. #define jpeg_start_output jStrtOutput
  160569. #define jpeg_finish_output jFinOutput
  160570. #define jpeg_input_complete jInComplete
  160571. #define jpeg_new_colormap jNewCMap
  160572. #define jpeg_consume_input jConsumeInput
  160573. #define jpeg_calc_output_dimensions jCalcDimensions
  160574. #define jpeg_save_markers jSaveMarkers
  160575. #define jpeg_set_marker_processor jSetMarker
  160576. #define jpeg_read_coefficients jReadCoefs
  160577. #define jpeg_write_coefficients jWrtCoefs
  160578. #define jpeg_copy_critical_parameters jCopyCrit
  160579. #define jpeg_abort_compress jAbrtCompress
  160580. #define jpeg_abort_decompress jAbrtDecompress
  160581. #define jpeg_abort jAbort
  160582. #define jpeg_destroy jDestroy
  160583. #define jpeg_resync_to_restart jResyncRestart
  160584. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160585. /* Default error-management setup */
  160586. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  160587. JPP((struct jpeg_error_mgr * err));
  160588. /* Initialization of JPEG compression objects.
  160589. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  160590. * names that applications should call. These expand to calls on
  160591. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  160592. * passed for version mismatch checking.
  160593. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  160594. */
  160595. #define jpeg_create_compress(cinfo) \
  160596. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  160597. (size_t) sizeof(struct jpeg_compress_struct))
  160598. #define jpeg_create_decompress(cinfo) \
  160599. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  160600. (size_t) sizeof(struct jpeg_decompress_struct))
  160601. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  160602. int version, size_t structsize));
  160603. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  160604. int version, size_t structsize));
  160605. /* Destruction of JPEG compression objects */
  160606. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  160607. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  160608. /* Standard data source and destination managers: stdio streams. */
  160609. /* Caller is responsible for opening the file before and closing after. */
  160610. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  160611. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  160612. /* Default parameter setup for compression */
  160613. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  160614. /* Compression parameter setup aids */
  160615. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  160616. J_COLOR_SPACE colorspace));
  160617. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  160618. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  160619. boolean force_baseline));
  160620. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  160621. int scale_factor,
  160622. boolean force_baseline));
  160623. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  160624. const unsigned int *basic_table,
  160625. int scale_factor,
  160626. boolean force_baseline));
  160627. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  160628. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  160629. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  160630. boolean suppress));
  160631. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  160632. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  160633. /* Main entry points for compression */
  160634. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  160635. boolean write_all_tables));
  160636. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  160637. JSAMPARRAY scanlines,
  160638. JDIMENSION num_lines));
  160639. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  160640. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  160641. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  160642. JSAMPIMAGE data,
  160643. JDIMENSION num_lines));
  160644. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  160645. EXTERN(void) jpeg_write_marker
  160646. JPP((j_compress_ptr cinfo, int marker,
  160647. const JOCTET * dataptr, unsigned int datalen));
  160648. /* Same, but piecemeal. */
  160649. EXTERN(void) jpeg_write_m_header
  160650. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  160651. EXTERN(void) jpeg_write_m_byte
  160652. JPP((j_compress_ptr cinfo, int val));
  160653. /* Alternate compression function: just write an abbreviated table file */
  160654. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  160655. /* Decompression startup: read start of JPEG datastream to see what's there */
  160656. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  160657. boolean require_image));
  160658. /* Return value is one of: */
  160659. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  160660. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  160661. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  160662. /* If you pass require_image = TRUE (normal case), you need not check for
  160663. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  160664. * JPEG_SUSPENDED is only possible if you use a data source module that can
  160665. * give a suspension return (the stdio source module doesn't).
  160666. */
  160667. /* Main entry points for decompression */
  160668. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  160669. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  160670. JSAMPARRAY scanlines,
  160671. JDIMENSION max_lines));
  160672. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  160673. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  160674. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  160675. JSAMPIMAGE data,
  160676. JDIMENSION max_lines));
  160677. /* Additional entry points for buffered-image mode. */
  160678. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  160679. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  160680. int scan_number));
  160681. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  160682. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  160683. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  160684. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  160685. /* Return value is one of: */
  160686. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  160687. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  160688. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  160689. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  160690. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  160691. /* Precalculate output dimensions for current decompression parameters. */
  160692. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  160693. /* Control saving of COM and APPn markers into marker_list. */
  160694. EXTERN(void) jpeg_save_markers
  160695. JPP((j_decompress_ptr cinfo, int marker_code,
  160696. unsigned int length_limit));
  160697. /* Install a special processing method for COM or APPn markers. */
  160698. EXTERN(void) jpeg_set_marker_processor
  160699. JPP((j_decompress_ptr cinfo, int marker_code,
  160700. jpeg_marker_parser_method routine));
  160701. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  160702. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  160703. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  160704. jvirt_barray_ptr * coef_arrays));
  160705. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  160706. j_compress_ptr dstinfo));
  160707. /* If you choose to abort compression or decompression before completing
  160708. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  160709. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  160710. * if you're done with the JPEG object, but if you want to clean it up and
  160711. * reuse it, call this:
  160712. */
  160713. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  160714. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  160715. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  160716. * flavor of JPEG object. These may be more convenient in some places.
  160717. */
  160718. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  160719. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  160720. /* Default restart-marker-resync procedure for use by data source modules */
  160721. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  160722. int desired));
  160723. /* These marker codes are exported since applications and data source modules
  160724. * are likely to want to use them.
  160725. */
  160726. #define JPEG_RST0 0xD0 /* RST0 marker code */
  160727. #define JPEG_EOI 0xD9 /* EOI marker code */
  160728. #define JPEG_APP0 0xE0 /* APP0 marker code */
  160729. #define JPEG_COM 0xFE /* COM marker code */
  160730. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  160731. * for structure definitions that are never filled in, keep it quiet by
  160732. * supplying dummy definitions for the various substructures.
  160733. */
  160734. #ifdef INCOMPLETE_TYPES_BROKEN
  160735. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  160736. struct jvirt_sarray_control { long dummy; };
  160737. struct jvirt_barray_control { long dummy; };
  160738. struct jpeg_comp_master { long dummy; };
  160739. struct jpeg_c_main_controller { long dummy; };
  160740. struct jpeg_c_prep_controller { long dummy; };
  160741. struct jpeg_c_coef_controller { long dummy; };
  160742. struct jpeg_marker_writer { long dummy; };
  160743. struct jpeg_color_converter { long dummy; };
  160744. struct jpeg_downsampler { long dummy; };
  160745. struct jpeg_forward_dct { long dummy; };
  160746. struct jpeg_entropy_encoder { long dummy; };
  160747. struct jpeg_decomp_master { long dummy; };
  160748. struct jpeg_d_main_controller { long dummy; };
  160749. struct jpeg_d_coef_controller { long dummy; };
  160750. struct jpeg_d_post_controller { long dummy; };
  160751. struct jpeg_input_controller { long dummy; };
  160752. struct jpeg_marker_reader { long dummy; };
  160753. struct jpeg_entropy_decoder { long dummy; };
  160754. struct jpeg_inverse_dct { long dummy; };
  160755. struct jpeg_upsampler { long dummy; };
  160756. struct jpeg_color_deconverter { long dummy; };
  160757. struct jpeg_color_quantizer { long dummy; };
  160758. #endif /* JPEG_INTERNALS */
  160759. #endif /* INCOMPLETE_TYPES_BROKEN */
  160760. /*
  160761. * The JPEG library modules define JPEG_INTERNALS before including this file.
  160762. * The internal structure declarations are read only when that is true.
  160763. * Applications using the library should not include jpegint.h, but may wish
  160764. * to include jerror.h.
  160765. */
  160766. #ifdef JPEG_INTERNALS
  160767. /*** Start of inlined file: jpegint.h ***/
  160768. /* Declarations for both compression & decompression */
  160769. typedef enum { /* Operating modes for buffer controllers */
  160770. JBUF_PASS_THRU, /* Plain stripwise operation */
  160771. /* Remaining modes require a full-image buffer to have been created */
  160772. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  160773. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  160774. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  160775. } J_BUF_MODE;
  160776. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  160777. #define CSTATE_START 100 /* after create_compress */
  160778. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  160779. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  160780. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  160781. #define DSTATE_START 200 /* after create_decompress */
  160782. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  160783. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  160784. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  160785. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  160786. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  160787. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  160788. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  160789. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  160790. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  160791. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  160792. /* Declarations for compression modules */
  160793. /* Master control module */
  160794. struct jpeg_comp_master {
  160795. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  160796. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  160797. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160798. /* State variables made visible to other modules */
  160799. boolean call_pass_startup; /* True if pass_startup must be called */
  160800. boolean is_last_pass; /* True during last pass */
  160801. };
  160802. /* Main buffer control (downsampled-data buffer) */
  160803. struct jpeg_c_main_controller {
  160804. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160805. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  160806. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  160807. JDIMENSION in_rows_avail));
  160808. };
  160809. /* Compression preprocessing (downsampling input buffer control) */
  160810. struct jpeg_c_prep_controller {
  160811. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160812. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  160813. JSAMPARRAY input_buf,
  160814. JDIMENSION *in_row_ctr,
  160815. JDIMENSION in_rows_avail,
  160816. JSAMPIMAGE output_buf,
  160817. JDIMENSION *out_row_group_ctr,
  160818. JDIMENSION out_row_groups_avail));
  160819. };
  160820. /* Coefficient buffer control */
  160821. struct jpeg_c_coef_controller {
  160822. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  160823. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  160824. JSAMPIMAGE input_buf));
  160825. };
  160826. /* Colorspace conversion */
  160827. struct jpeg_color_converter {
  160828. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160829. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  160830. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  160831. JDIMENSION output_row, int num_rows));
  160832. };
  160833. /* Downsampling */
  160834. struct jpeg_downsampler {
  160835. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160836. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  160837. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  160838. JSAMPIMAGE output_buf,
  160839. JDIMENSION out_row_group_index));
  160840. boolean need_context_rows; /* TRUE if need rows above & below */
  160841. };
  160842. /* Forward DCT (also controls coefficient quantization) */
  160843. struct jpeg_forward_dct {
  160844. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  160845. /* perhaps this should be an array??? */
  160846. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  160847. jpeg_component_info * compptr,
  160848. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  160849. JDIMENSION start_row, JDIMENSION start_col,
  160850. JDIMENSION num_blocks));
  160851. };
  160852. /* Entropy encoding */
  160853. struct jpeg_entropy_encoder {
  160854. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  160855. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  160856. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  160857. };
  160858. /* Marker writing */
  160859. struct jpeg_marker_writer {
  160860. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  160861. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  160862. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  160863. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  160864. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  160865. /* These routines are exported to allow insertion of extra markers */
  160866. /* Probably only COM and APPn markers should be written this way */
  160867. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  160868. unsigned int datalen));
  160869. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  160870. };
  160871. /* Declarations for decompression modules */
  160872. /* Master control module */
  160873. struct jpeg_decomp_master {
  160874. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  160875. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  160876. /* State variables made visible to other modules */
  160877. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  160878. };
  160879. /* Input control module */
  160880. struct jpeg_input_controller {
  160881. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  160882. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  160883. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160884. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  160885. /* State variables made visible to other modules */
  160886. boolean has_multiple_scans; /* True if file has multiple scans */
  160887. boolean eoi_reached; /* True when EOI has been consumed */
  160888. };
  160889. /* Main buffer control (downsampled-data buffer) */
  160890. struct jpeg_d_main_controller {
  160891. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160892. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  160893. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  160894. JDIMENSION out_rows_avail));
  160895. };
  160896. /* Coefficient buffer control */
  160897. struct jpeg_d_coef_controller {
  160898. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  160899. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  160900. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  160901. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  160902. JSAMPIMAGE output_buf));
  160903. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  160904. jvirt_barray_ptr *coef_arrays;
  160905. };
  160906. /* Decompression postprocessing (color quantization buffer control) */
  160907. struct jpeg_d_post_controller {
  160908. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  160909. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  160910. JSAMPIMAGE input_buf,
  160911. JDIMENSION *in_row_group_ctr,
  160912. JDIMENSION in_row_groups_avail,
  160913. JSAMPARRAY output_buf,
  160914. JDIMENSION *out_row_ctr,
  160915. JDIMENSION out_rows_avail));
  160916. };
  160917. /* Marker reading & parsing */
  160918. struct jpeg_marker_reader {
  160919. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  160920. /* Read markers until SOS or EOI.
  160921. * Returns same codes as are defined for jpeg_consume_input:
  160922. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  160923. */
  160924. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  160925. /* Read a restart marker --- exported for use by entropy decoder only */
  160926. jpeg_marker_parser_method read_restart_marker;
  160927. /* State of marker reader --- nominally internal, but applications
  160928. * supplying COM or APPn handlers might like to know the state.
  160929. */
  160930. boolean saw_SOI; /* found SOI? */
  160931. boolean saw_SOF; /* found SOF? */
  160932. int next_restart_num; /* next restart number expected (0-7) */
  160933. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  160934. };
  160935. /* Entropy decoding */
  160936. struct jpeg_entropy_decoder {
  160937. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160938. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  160939. JBLOCKROW *MCU_data));
  160940. /* This is here to share code between baseline and progressive decoders; */
  160941. /* other modules probably should not use it */
  160942. boolean insufficient_data; /* set TRUE after emitting warning */
  160943. };
  160944. /* Inverse DCT (also performs dequantization) */
  160945. typedef JMETHOD(void, inverse_DCT_method_ptr,
  160946. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  160947. JCOEFPTR coef_block,
  160948. JSAMPARRAY output_buf, JDIMENSION output_col));
  160949. struct jpeg_inverse_dct {
  160950. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160951. /* It is useful to allow each component to have a separate IDCT method. */
  160952. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  160953. };
  160954. /* Upsampling (note that upsampler must also call color converter) */
  160955. struct jpeg_upsampler {
  160956. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160957. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  160958. JSAMPIMAGE input_buf,
  160959. JDIMENSION *in_row_group_ctr,
  160960. JDIMENSION in_row_groups_avail,
  160961. JSAMPARRAY output_buf,
  160962. JDIMENSION *out_row_ctr,
  160963. JDIMENSION out_rows_avail));
  160964. boolean need_context_rows; /* TRUE if need rows above & below */
  160965. };
  160966. /* Colorspace conversion */
  160967. struct jpeg_color_deconverter {
  160968. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  160969. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  160970. JSAMPIMAGE input_buf, JDIMENSION input_row,
  160971. JSAMPARRAY output_buf, int num_rows));
  160972. };
  160973. /* Color quantization or color precision reduction */
  160974. struct jpeg_color_quantizer {
  160975. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  160976. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  160977. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  160978. int num_rows));
  160979. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  160980. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  160981. };
  160982. /* Miscellaneous useful macros */
  160983. #undef MAX
  160984. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  160985. #undef MIN
  160986. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  160987. /* We assume that right shift corresponds to signed division by 2 with
  160988. * rounding towards minus infinity. This is correct for typical "arithmetic
  160989. * shift" instructions that shift in copies of the sign bit. But some
  160990. * C compilers implement >> with an unsigned shift. For these machines you
  160991. * must define RIGHT_SHIFT_IS_UNSIGNED.
  160992. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  160993. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  160994. * included in the variables of any routine using RIGHT_SHIFT.
  160995. */
  160996. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  160997. #define SHIFT_TEMPS INT32 shift_temp;
  160998. #define RIGHT_SHIFT(x,shft) \
  160999. ((shift_temp = (x)) < 0 ? \
  161000. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  161001. (shift_temp >> (shft)))
  161002. #else
  161003. #define SHIFT_TEMPS
  161004. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  161005. #endif
  161006. /* Short forms of external names for systems with brain-damaged linkers. */
  161007. #ifdef NEED_SHORT_EXTERNAL_NAMES
  161008. #define jinit_compress_master jICompress
  161009. #define jinit_c_master_control jICMaster
  161010. #define jinit_c_main_controller jICMainC
  161011. #define jinit_c_prep_controller jICPrepC
  161012. #define jinit_c_coef_controller jICCoefC
  161013. #define jinit_color_converter jICColor
  161014. #define jinit_downsampler jIDownsampler
  161015. #define jinit_forward_dct jIFDCT
  161016. #define jinit_huff_encoder jIHEncoder
  161017. #define jinit_phuff_encoder jIPHEncoder
  161018. #define jinit_marker_writer jIMWriter
  161019. #define jinit_master_decompress jIDMaster
  161020. #define jinit_d_main_controller jIDMainC
  161021. #define jinit_d_coef_controller jIDCoefC
  161022. #define jinit_d_post_controller jIDPostC
  161023. #define jinit_input_controller jIInCtlr
  161024. #define jinit_marker_reader jIMReader
  161025. #define jinit_huff_decoder jIHDecoder
  161026. #define jinit_phuff_decoder jIPHDecoder
  161027. #define jinit_inverse_dct jIIDCT
  161028. #define jinit_upsampler jIUpsampler
  161029. #define jinit_color_deconverter jIDColor
  161030. #define jinit_1pass_quantizer jI1Quant
  161031. #define jinit_2pass_quantizer jI2Quant
  161032. #define jinit_merged_upsampler jIMUpsampler
  161033. #define jinit_memory_mgr jIMemMgr
  161034. #define jdiv_round_up jDivRound
  161035. #define jround_up jRound
  161036. #define jcopy_sample_rows jCopySamples
  161037. #define jcopy_block_row jCopyBlocks
  161038. #define jzero_far jZeroFar
  161039. #define jpeg_zigzag_order jZIGTable
  161040. #define jpeg_natural_order jZAGTable
  161041. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  161042. /* Compression module initialization routines */
  161043. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  161044. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  161045. boolean transcode_only));
  161046. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  161047. boolean need_full_buffer));
  161048. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  161049. boolean need_full_buffer));
  161050. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  161051. boolean need_full_buffer));
  161052. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  161053. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  161054. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  161055. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  161056. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  161057. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  161058. /* Decompression module initialization routines */
  161059. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  161060. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  161061. boolean need_full_buffer));
  161062. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  161063. boolean need_full_buffer));
  161064. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  161065. boolean need_full_buffer));
  161066. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  161067. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  161068. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  161069. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  161070. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  161071. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  161072. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  161073. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  161074. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  161075. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  161076. /* Memory manager initialization */
  161077. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  161078. /* Utility routines in jutils.c */
  161079. EXTERN(long) jdiv_round_up JPP((long a, long b));
  161080. EXTERN(long) jround_up JPP((long a, long b));
  161081. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  161082. JSAMPARRAY output_array, int dest_row,
  161083. int num_rows, JDIMENSION num_cols));
  161084. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  161085. JDIMENSION num_blocks));
  161086. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  161087. /* Constant tables in jutils.c */
  161088. #if 0 /* This table is not actually needed in v6a */
  161089. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  161090. #endif
  161091. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  161092. /* Suppress undefined-structure complaints if necessary. */
  161093. #ifdef INCOMPLETE_TYPES_BROKEN
  161094. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  161095. struct jvirt_sarray_control { long dummy; };
  161096. struct jvirt_barray_control { long dummy; };
  161097. #endif
  161098. #endif /* INCOMPLETE_TYPES_BROKEN */
  161099. /*** End of inlined file: jpegint.h ***/
  161100. /* fetch private declarations */
  161101. /*** Start of inlined file: jerror.h ***/
  161102. /*
  161103. * To define the enum list of message codes, include this file without
  161104. * defining macro JMESSAGE. To create a message string table, include it
  161105. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  161106. */
  161107. #ifndef JMESSAGE
  161108. #ifndef JERROR_H
  161109. /* First time through, define the enum list */
  161110. #define JMAKE_ENUM_LIST
  161111. #else
  161112. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  161113. #define JMESSAGE(code,string)
  161114. #endif /* JERROR_H */
  161115. #endif /* JMESSAGE */
  161116. #ifdef JMAKE_ENUM_LIST
  161117. typedef enum {
  161118. #define JMESSAGE(code,string) code ,
  161119. #endif /* JMAKE_ENUM_LIST */
  161120. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  161121. /* For maintenance convenience, list is alphabetical by message code name */
  161122. JMESSAGE(JERR_ARITH_NOTIMPL,
  161123. "Sorry, there are legal restrictions on arithmetic coding")
  161124. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  161125. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  161126. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  161127. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  161128. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  161129. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  161130. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  161131. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  161132. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  161133. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  161134. JMESSAGE(JERR_BAD_LIB_VERSION,
  161135. "Wrong JPEG library version: library is %d, caller expects %d")
  161136. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  161137. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  161138. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  161139. JMESSAGE(JERR_BAD_PROGRESSION,
  161140. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  161141. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  161142. "Invalid progressive parameters at scan script entry %d")
  161143. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  161144. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  161145. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  161146. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  161147. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  161148. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  161149. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  161150. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  161151. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  161152. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  161153. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  161154. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  161155. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  161156. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  161157. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  161158. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  161159. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  161160. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  161161. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  161162. JMESSAGE(JERR_FILE_READ, "Input file read error")
  161163. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  161164. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  161165. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  161166. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  161167. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  161168. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  161169. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  161170. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  161171. "Cannot transcode due to multiple use of quantization table %d")
  161172. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  161173. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  161174. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  161175. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  161176. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  161177. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  161178. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  161179. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  161180. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  161181. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  161182. JMESSAGE(JERR_QUANT_COMPONENTS,
  161183. "Cannot quantize more than %d color components")
  161184. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  161185. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  161186. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  161187. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  161188. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  161189. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  161190. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  161191. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  161192. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  161193. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  161194. JMESSAGE(JERR_TFILE_WRITE,
  161195. "Write failed on temporary file --- out of disk space?")
  161196. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  161197. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  161198. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  161199. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  161200. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  161201. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  161202. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  161203. JMESSAGE(JMSG_VERSION, JVERSION)
  161204. JMESSAGE(JTRC_16BIT_TABLES,
  161205. "Caution: quantization tables are too coarse for baseline JPEG")
  161206. JMESSAGE(JTRC_ADOBE,
  161207. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  161208. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  161209. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  161210. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  161211. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  161212. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  161213. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  161214. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  161215. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  161216. JMESSAGE(JTRC_EOI, "End Of Image")
  161217. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  161218. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  161219. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  161220. "Warning: thumbnail image size does not match data length %u")
  161221. JMESSAGE(JTRC_JFIF_EXTENSION,
  161222. "JFIF extension marker: type 0x%02x, length %u")
  161223. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  161224. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  161225. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  161226. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  161227. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  161228. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  161229. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  161230. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  161231. JMESSAGE(JTRC_RST, "RST%d")
  161232. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  161233. "Smoothing not supported with nonstandard sampling ratios")
  161234. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  161235. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  161236. JMESSAGE(JTRC_SOI, "Start of Image")
  161237. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  161238. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  161239. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  161240. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  161241. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  161242. JMESSAGE(JTRC_THUMB_JPEG,
  161243. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  161244. JMESSAGE(JTRC_THUMB_PALETTE,
  161245. "JFIF extension marker: palette thumbnail image, length %u")
  161246. JMESSAGE(JTRC_THUMB_RGB,
  161247. "JFIF extension marker: RGB thumbnail image, length %u")
  161248. JMESSAGE(JTRC_UNKNOWN_IDS,
  161249. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  161250. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  161251. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  161252. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  161253. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  161254. "Inconsistent progression sequence for component %d coefficient %d")
  161255. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  161256. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  161257. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  161258. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  161259. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  161260. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  161261. JMESSAGE(JWRN_MUST_RESYNC,
  161262. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  161263. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  161264. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  161265. #ifdef JMAKE_ENUM_LIST
  161266. JMSG_LASTMSGCODE
  161267. } J_MESSAGE_CODE;
  161268. #undef JMAKE_ENUM_LIST
  161269. #endif /* JMAKE_ENUM_LIST */
  161270. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  161271. #undef JMESSAGE
  161272. #ifndef JERROR_H
  161273. #define JERROR_H
  161274. /* Macros to simplify using the error and trace message stuff */
  161275. /* The first parameter is either type of cinfo pointer */
  161276. /* Fatal errors (print message and exit) */
  161277. #define ERREXIT(cinfo,code) \
  161278. ((cinfo)->err->msg_code = (code), \
  161279. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161280. #define ERREXIT1(cinfo,code,p1) \
  161281. ((cinfo)->err->msg_code = (code), \
  161282. (cinfo)->err->msg_parm.i[0] = (p1), \
  161283. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161284. #define ERREXIT2(cinfo,code,p1,p2) \
  161285. ((cinfo)->err->msg_code = (code), \
  161286. (cinfo)->err->msg_parm.i[0] = (p1), \
  161287. (cinfo)->err->msg_parm.i[1] = (p2), \
  161288. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161289. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  161290. ((cinfo)->err->msg_code = (code), \
  161291. (cinfo)->err->msg_parm.i[0] = (p1), \
  161292. (cinfo)->err->msg_parm.i[1] = (p2), \
  161293. (cinfo)->err->msg_parm.i[2] = (p3), \
  161294. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161295. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  161296. ((cinfo)->err->msg_code = (code), \
  161297. (cinfo)->err->msg_parm.i[0] = (p1), \
  161298. (cinfo)->err->msg_parm.i[1] = (p2), \
  161299. (cinfo)->err->msg_parm.i[2] = (p3), \
  161300. (cinfo)->err->msg_parm.i[3] = (p4), \
  161301. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161302. #define ERREXITS(cinfo,code,str) \
  161303. ((cinfo)->err->msg_code = (code), \
  161304. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161305. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161306. #define MAKESTMT(stuff) do { stuff } while (0)
  161307. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  161308. #define WARNMS(cinfo,code) \
  161309. ((cinfo)->err->msg_code = (code), \
  161310. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161311. #define WARNMS1(cinfo,code,p1) \
  161312. ((cinfo)->err->msg_code = (code), \
  161313. (cinfo)->err->msg_parm.i[0] = (p1), \
  161314. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161315. #define WARNMS2(cinfo,code,p1,p2) \
  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->emit_message) ((j_common_ptr) (cinfo), -1))
  161320. /* Informational/debugging messages */
  161321. #define TRACEMS(cinfo,lvl,code) \
  161322. ((cinfo)->err->msg_code = (code), \
  161323. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161324. #define TRACEMS1(cinfo,lvl,code,p1) \
  161325. ((cinfo)->err->msg_code = (code), \
  161326. (cinfo)->err->msg_parm.i[0] = (p1), \
  161327. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161328. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  161329. ((cinfo)->err->msg_code = (code), \
  161330. (cinfo)->err->msg_parm.i[0] = (p1), \
  161331. (cinfo)->err->msg_parm.i[1] = (p2), \
  161332. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161333. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  161334. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161335. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  161336. (cinfo)->err->msg_code = (code); \
  161337. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161338. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  161339. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161340. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161341. (cinfo)->err->msg_code = (code); \
  161342. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161343. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  161344. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161345. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161346. _mp[4] = (p5); \
  161347. (cinfo)->err->msg_code = (code); \
  161348. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161349. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  161350. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161351. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161352. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  161353. (cinfo)->err->msg_code = (code); \
  161354. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161355. #define TRACEMSS(cinfo,lvl,code,str) \
  161356. ((cinfo)->err->msg_code = (code), \
  161357. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161358. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161359. #endif /* JERROR_H */
  161360. /*** End of inlined file: jerror.h ***/
  161361. /* fetch error codes too */
  161362. #endif
  161363. #endif /* JPEGLIB_H */
  161364. /*** End of inlined file: jpeglib.h ***/
  161365. /*** Start of inlined file: jcapimin.c ***/
  161366. #define JPEG_INTERNALS
  161367. /*** Start of inlined file: jinclude.h ***/
  161368. /* Include auto-config file to find out which system include files we need. */
  161369. #ifndef __jinclude_h__
  161370. #define __jinclude_h__
  161371. /*** Start of inlined file: jconfig.h ***/
  161372. /* see jconfig.doc for explanations */
  161373. // disable all the warnings under MSVC
  161374. #ifdef _MSC_VER
  161375. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  161376. #endif
  161377. #ifdef __BORLANDC__
  161378. #pragma warn -8057
  161379. #pragma warn -8019
  161380. #pragma warn -8004
  161381. #pragma warn -8008
  161382. #endif
  161383. #define HAVE_PROTOTYPES
  161384. #define HAVE_UNSIGNED_CHAR
  161385. #define HAVE_UNSIGNED_SHORT
  161386. /* #define void char */
  161387. /* #define const */
  161388. #undef CHAR_IS_UNSIGNED
  161389. #define HAVE_STDDEF_H
  161390. #define HAVE_STDLIB_H
  161391. #undef NEED_BSD_STRINGS
  161392. #undef NEED_SYS_TYPES_H
  161393. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  161394. #undef NEED_SHORT_EXTERNAL_NAMES
  161395. #undef INCOMPLETE_TYPES_BROKEN
  161396. /* Define "boolean" as unsigned char, not int, per Windows custom */
  161397. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  161398. typedef unsigned char boolean;
  161399. #endif
  161400. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  161401. #ifdef JPEG_INTERNALS
  161402. #undef RIGHT_SHIFT_IS_UNSIGNED
  161403. #endif /* JPEG_INTERNALS */
  161404. #ifdef JPEG_CJPEG_DJPEG
  161405. #define BMP_SUPPORTED /* BMP image file format */
  161406. #define GIF_SUPPORTED /* GIF image file format */
  161407. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  161408. #undef RLE_SUPPORTED /* Utah RLE image file format */
  161409. #define TARGA_SUPPORTED /* Targa image file format */
  161410. #define TWO_FILE_COMMANDLINE /* optional */
  161411. #define USE_SETMODE /* Microsoft has setmode() */
  161412. #undef NEED_SIGNAL_CATCHER
  161413. #undef DONT_USE_B_MODE
  161414. #undef PROGRESS_REPORT /* optional */
  161415. #endif /* JPEG_CJPEG_DJPEG */
  161416. /*** End of inlined file: jconfig.h ***/
  161417. /* auto configuration options */
  161418. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  161419. /*
  161420. * We need the NULL macro and size_t typedef.
  161421. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  161422. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  161423. * pull in <sys/types.h> as well.
  161424. * Note that the core JPEG library does not require <stdio.h>;
  161425. * only the default error handler and data source/destination modules do.
  161426. * But we must pull it in because of the references to FILE in jpeglib.h.
  161427. * You can remove those references if you want to compile without <stdio.h>.
  161428. */
  161429. #ifdef HAVE_STDDEF_H
  161430. #include <stddef.h>
  161431. #endif
  161432. #ifdef HAVE_STDLIB_H
  161433. #include <stdlib.h>
  161434. #endif
  161435. #ifdef NEED_SYS_TYPES_H
  161436. #include <sys/types.h>
  161437. #endif
  161438. #include <stdio.h>
  161439. /*
  161440. * We need memory copying and zeroing functions, plus strncpy().
  161441. * ANSI and System V implementations declare these in <string.h>.
  161442. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  161443. * Some systems may declare memset and memcpy in <memory.h>.
  161444. *
  161445. * NOTE: we assume the size parameters to these functions are of type size_t.
  161446. * Change the casts in these macros if not!
  161447. */
  161448. #ifdef NEED_BSD_STRINGS
  161449. #include <strings.h>
  161450. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  161451. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  161452. #else /* not BSD, assume ANSI/SysV string lib */
  161453. #include <string.h>
  161454. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  161455. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  161456. #endif
  161457. /*
  161458. * In ANSI C, and indeed any rational implementation, size_t is also the
  161459. * type returned by sizeof(). However, it seems there are some irrational
  161460. * implementations out there, in which sizeof() returns an int even though
  161461. * size_t is defined as long or unsigned long. To ensure consistent results
  161462. * we always use this SIZEOF() macro in place of using sizeof() directly.
  161463. */
  161464. #define SIZEOF(object) ((size_t) sizeof(object))
  161465. /*
  161466. * The modules that use fread() and fwrite() always invoke them through
  161467. * these macros. On some systems you may need to twiddle the argument casts.
  161468. * CAUTION: argument order is different from underlying functions!
  161469. */
  161470. #define JFREAD(file,buf,sizeofbuf) \
  161471. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161472. #define JFWRITE(file,buf,sizeofbuf) \
  161473. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161474. typedef enum { /* JPEG marker codes */
  161475. M_SOF0 = 0xc0,
  161476. M_SOF1 = 0xc1,
  161477. M_SOF2 = 0xc2,
  161478. M_SOF3 = 0xc3,
  161479. M_SOF5 = 0xc5,
  161480. M_SOF6 = 0xc6,
  161481. M_SOF7 = 0xc7,
  161482. M_JPG = 0xc8,
  161483. M_SOF9 = 0xc9,
  161484. M_SOF10 = 0xca,
  161485. M_SOF11 = 0xcb,
  161486. M_SOF13 = 0xcd,
  161487. M_SOF14 = 0xce,
  161488. M_SOF15 = 0xcf,
  161489. M_DHT = 0xc4,
  161490. M_DAC = 0xcc,
  161491. M_RST0 = 0xd0,
  161492. M_RST1 = 0xd1,
  161493. M_RST2 = 0xd2,
  161494. M_RST3 = 0xd3,
  161495. M_RST4 = 0xd4,
  161496. M_RST5 = 0xd5,
  161497. M_RST6 = 0xd6,
  161498. M_RST7 = 0xd7,
  161499. M_SOI = 0xd8,
  161500. M_EOI = 0xd9,
  161501. M_SOS = 0xda,
  161502. M_DQT = 0xdb,
  161503. M_DNL = 0xdc,
  161504. M_DRI = 0xdd,
  161505. M_DHP = 0xde,
  161506. M_EXP = 0xdf,
  161507. M_APP0 = 0xe0,
  161508. M_APP1 = 0xe1,
  161509. M_APP2 = 0xe2,
  161510. M_APP3 = 0xe3,
  161511. M_APP4 = 0xe4,
  161512. M_APP5 = 0xe5,
  161513. M_APP6 = 0xe6,
  161514. M_APP7 = 0xe7,
  161515. M_APP8 = 0xe8,
  161516. M_APP9 = 0xe9,
  161517. M_APP10 = 0xea,
  161518. M_APP11 = 0xeb,
  161519. M_APP12 = 0xec,
  161520. M_APP13 = 0xed,
  161521. M_APP14 = 0xee,
  161522. M_APP15 = 0xef,
  161523. M_JPG0 = 0xf0,
  161524. M_JPG13 = 0xfd,
  161525. M_COM = 0xfe,
  161526. M_TEM = 0x01,
  161527. M_ERROR = 0x100
  161528. } JPEG_MARKER;
  161529. /*
  161530. * Figure F.12: extend sign bit.
  161531. * On some machines, a shift and add will be faster than a table lookup.
  161532. */
  161533. #ifdef AVOID_TABLES
  161534. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  161535. #else
  161536. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  161537. static const int extend_test[16] = /* entry n is 2**(n-1) */
  161538. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  161539. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  161540. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  161541. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  161542. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  161543. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  161544. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  161545. #endif /* AVOID_TABLES */
  161546. #endif
  161547. /*** End of inlined file: jinclude.h ***/
  161548. /*
  161549. * Initialization of a JPEG compression object.
  161550. * The error manager must already be set up (in case memory manager fails).
  161551. */
  161552. GLOBAL(void)
  161553. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  161554. {
  161555. int i;
  161556. /* Guard against version mismatches between library and caller. */
  161557. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  161558. if (version != JPEG_LIB_VERSION)
  161559. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  161560. if (structsize != SIZEOF(struct jpeg_compress_struct))
  161561. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  161562. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  161563. /* For debugging purposes, we zero the whole master structure.
  161564. * But the application has already set the err pointer, and may have set
  161565. * client_data, so we have to save and restore those fields.
  161566. * Note: if application hasn't set client_data, tools like Purify may
  161567. * complain here.
  161568. */
  161569. {
  161570. struct jpeg_error_mgr * err = cinfo->err;
  161571. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  161572. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  161573. cinfo->err = err;
  161574. cinfo->client_data = client_data;
  161575. }
  161576. cinfo->is_decompressor = FALSE;
  161577. /* Initialize a memory manager instance for this object */
  161578. jinit_memory_mgr((j_common_ptr) cinfo);
  161579. /* Zero out pointers to permanent structures. */
  161580. cinfo->progress = NULL;
  161581. cinfo->dest = NULL;
  161582. cinfo->comp_info = NULL;
  161583. for (i = 0; i < NUM_QUANT_TBLS; i++)
  161584. cinfo->quant_tbl_ptrs[i] = NULL;
  161585. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161586. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  161587. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  161588. }
  161589. cinfo->script_space = NULL;
  161590. cinfo->input_gamma = 1.0; /* in case application forgets */
  161591. /* OK, I'm ready */
  161592. cinfo->global_state = CSTATE_START;
  161593. }
  161594. /*
  161595. * Destruction of a JPEG compression object
  161596. */
  161597. GLOBAL(void)
  161598. jpeg_destroy_compress (j_compress_ptr cinfo)
  161599. {
  161600. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  161601. }
  161602. /*
  161603. * Abort processing of a JPEG compression operation,
  161604. * but don't destroy the object itself.
  161605. */
  161606. GLOBAL(void)
  161607. jpeg_abort_compress (j_compress_ptr cinfo)
  161608. {
  161609. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  161610. }
  161611. /*
  161612. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  161613. * Marks all currently defined tables as already written (if suppress)
  161614. * or not written (if !suppress). This will control whether they get emitted
  161615. * by a subsequent jpeg_start_compress call.
  161616. *
  161617. * This routine is exported for use by applications that want to produce
  161618. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  161619. * since it is called by jpeg_start_compress, we put it here --- otherwise
  161620. * jcparam.o would be linked whether the application used it or not.
  161621. */
  161622. GLOBAL(void)
  161623. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  161624. {
  161625. int i;
  161626. JQUANT_TBL * qtbl;
  161627. JHUFF_TBL * htbl;
  161628. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  161629. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  161630. qtbl->sent_table = suppress;
  161631. }
  161632. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161633. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  161634. htbl->sent_table = suppress;
  161635. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  161636. htbl->sent_table = suppress;
  161637. }
  161638. }
  161639. /*
  161640. * Finish JPEG compression.
  161641. *
  161642. * If a multipass operating mode was selected, this may do a great deal of
  161643. * work including most of the actual output.
  161644. */
  161645. GLOBAL(void)
  161646. jpeg_finish_compress (j_compress_ptr cinfo)
  161647. {
  161648. JDIMENSION iMCU_row;
  161649. if (cinfo->global_state == CSTATE_SCANNING ||
  161650. cinfo->global_state == CSTATE_RAW_OK) {
  161651. /* Terminate first pass */
  161652. if (cinfo->next_scanline < cinfo->image_height)
  161653. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  161654. (*cinfo->master->finish_pass) (cinfo);
  161655. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  161656. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161657. /* Perform any remaining passes */
  161658. while (! cinfo->master->is_last_pass) {
  161659. (*cinfo->master->prepare_for_pass) (cinfo);
  161660. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  161661. if (cinfo->progress != NULL) {
  161662. cinfo->progress->pass_counter = (long) iMCU_row;
  161663. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  161664. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161665. }
  161666. /* We bypass the main controller and invoke coef controller directly;
  161667. * all work is being done from the coefficient buffer.
  161668. */
  161669. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  161670. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  161671. }
  161672. (*cinfo->master->finish_pass) (cinfo);
  161673. }
  161674. /* Write EOI, do final cleanup */
  161675. (*cinfo->marker->write_file_trailer) (cinfo);
  161676. (*cinfo->dest->term_destination) (cinfo);
  161677. /* We can use jpeg_abort to release memory and reset global_state */
  161678. jpeg_abort((j_common_ptr) cinfo);
  161679. }
  161680. /*
  161681. * Write a special marker.
  161682. * This is only recommended for writing COM or APPn markers.
  161683. * Must be called after jpeg_start_compress() and before
  161684. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  161685. */
  161686. GLOBAL(void)
  161687. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  161688. const JOCTET *dataptr, unsigned int datalen)
  161689. {
  161690. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  161691. if (cinfo->next_scanline != 0 ||
  161692. (cinfo->global_state != CSTATE_SCANNING &&
  161693. cinfo->global_state != CSTATE_RAW_OK &&
  161694. cinfo->global_state != CSTATE_WRCOEFS))
  161695. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161696. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161697. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  161698. while (datalen--) {
  161699. (*write_marker_byte) (cinfo, *dataptr);
  161700. dataptr++;
  161701. }
  161702. }
  161703. /* Same, but piecemeal. */
  161704. GLOBAL(void)
  161705. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  161706. {
  161707. if (cinfo->next_scanline != 0 ||
  161708. (cinfo->global_state != CSTATE_SCANNING &&
  161709. cinfo->global_state != CSTATE_RAW_OK &&
  161710. cinfo->global_state != CSTATE_WRCOEFS))
  161711. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161712. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161713. }
  161714. GLOBAL(void)
  161715. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  161716. {
  161717. (*cinfo->marker->write_marker_byte) (cinfo, val);
  161718. }
  161719. /*
  161720. * Alternate compression function: just write an abbreviated table file.
  161721. * Before calling this, all parameters and a data destination must be set up.
  161722. *
  161723. * To produce a pair of files containing abbreviated tables and abbreviated
  161724. * image data, one would proceed as follows:
  161725. *
  161726. * initialize JPEG object
  161727. * set JPEG parameters
  161728. * set destination to table file
  161729. * jpeg_write_tables(cinfo);
  161730. * set destination to image file
  161731. * jpeg_start_compress(cinfo, FALSE);
  161732. * write data...
  161733. * jpeg_finish_compress(cinfo);
  161734. *
  161735. * jpeg_write_tables has the side effect of marking all tables written
  161736. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  161737. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  161738. */
  161739. GLOBAL(void)
  161740. jpeg_write_tables (j_compress_ptr cinfo)
  161741. {
  161742. if (cinfo->global_state != CSTATE_START)
  161743. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161744. /* (Re)initialize error mgr and destination modules */
  161745. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161746. (*cinfo->dest->init_destination) (cinfo);
  161747. /* Initialize the marker writer ... bit of a crock to do it here. */
  161748. jinit_marker_writer(cinfo);
  161749. /* Write them tables! */
  161750. (*cinfo->marker->write_tables_only) (cinfo);
  161751. /* And clean up. */
  161752. (*cinfo->dest->term_destination) (cinfo);
  161753. /*
  161754. * In library releases up through v6a, we called jpeg_abort() here to free
  161755. * any working memory allocated by the destination manager and marker
  161756. * writer. Some applications had a problem with that: they allocated space
  161757. * of their own from the library memory manager, and didn't want it to go
  161758. * away during write_tables. So now we do nothing. This will cause a
  161759. * memory leak if an app calls write_tables repeatedly without doing a full
  161760. * compression cycle or otherwise resetting the JPEG object. However, that
  161761. * seems less bad than unexpectedly freeing memory in the normal case.
  161762. * An app that prefers the old behavior can call jpeg_abort for itself after
  161763. * each call to jpeg_write_tables().
  161764. */
  161765. }
  161766. /*** End of inlined file: jcapimin.c ***/
  161767. /*** Start of inlined file: jcapistd.c ***/
  161768. #define JPEG_INTERNALS
  161769. /*
  161770. * Compression initialization.
  161771. * Before calling this, all parameters and a data destination must be set up.
  161772. *
  161773. * We require a write_all_tables parameter as a failsafe check when writing
  161774. * multiple datastreams from the same compression object. Since prior runs
  161775. * will have left all the tables marked sent_table=TRUE, a subsequent run
  161776. * would emit an abbreviated stream (no tables) by default. This may be what
  161777. * is wanted, but for safety's sake it should not be the default behavior:
  161778. * programmers should have to make a deliberate choice to emit abbreviated
  161779. * images. Therefore the documentation and examples should encourage people
  161780. * to pass write_all_tables=TRUE; then it will take active thought to do the
  161781. * wrong thing.
  161782. */
  161783. GLOBAL(void)
  161784. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  161785. {
  161786. if (cinfo->global_state != CSTATE_START)
  161787. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161788. if (write_all_tables)
  161789. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  161790. /* (Re)initialize error mgr and destination modules */
  161791. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161792. (*cinfo->dest->init_destination) (cinfo);
  161793. /* Perform master selection of active modules */
  161794. jinit_compress_master(cinfo);
  161795. /* Set up for the first pass */
  161796. (*cinfo->master->prepare_for_pass) (cinfo);
  161797. /* Ready for application to drive first pass through jpeg_write_scanlines
  161798. * or jpeg_write_raw_data.
  161799. */
  161800. cinfo->next_scanline = 0;
  161801. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  161802. }
  161803. /*
  161804. * Write some scanlines of data to the JPEG compressor.
  161805. *
  161806. * The return value will be the number of lines actually written.
  161807. * This should be less than the supplied num_lines only in case that
  161808. * the data destination module has requested suspension of the compressor,
  161809. * or if more than image_height scanlines are passed in.
  161810. *
  161811. * Note: we warn about excess calls to jpeg_write_scanlines() since
  161812. * this likely signals an application programmer error. However,
  161813. * excess scanlines passed in the last valid call are *silently* ignored,
  161814. * so that the application need not adjust num_lines for end-of-image
  161815. * when using a multiple-scanline buffer.
  161816. */
  161817. GLOBAL(JDIMENSION)
  161818. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  161819. JDIMENSION num_lines)
  161820. {
  161821. JDIMENSION row_ctr, rows_left;
  161822. if (cinfo->global_state != CSTATE_SCANNING)
  161823. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161824. if (cinfo->next_scanline >= cinfo->image_height)
  161825. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161826. /* Call progress monitor hook if present */
  161827. if (cinfo->progress != NULL) {
  161828. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  161829. cinfo->progress->pass_limit = (long) cinfo->image_height;
  161830. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161831. }
  161832. /* Give master control module another chance if this is first call to
  161833. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  161834. * delayed so that application can write COM, etc, markers between
  161835. * jpeg_start_compress and jpeg_write_scanlines.
  161836. */
  161837. if (cinfo->master->call_pass_startup)
  161838. (*cinfo->master->pass_startup) (cinfo);
  161839. /* Ignore any extra scanlines at bottom of image. */
  161840. rows_left = cinfo->image_height - cinfo->next_scanline;
  161841. if (num_lines > rows_left)
  161842. num_lines = rows_left;
  161843. row_ctr = 0;
  161844. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  161845. cinfo->next_scanline += row_ctr;
  161846. return row_ctr;
  161847. }
  161848. /*
  161849. * Alternate entry point to write raw data.
  161850. * Processes exactly one iMCU row per call, unless suspended.
  161851. */
  161852. GLOBAL(JDIMENSION)
  161853. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  161854. JDIMENSION num_lines)
  161855. {
  161856. JDIMENSION lines_per_iMCU_row;
  161857. if (cinfo->global_state != CSTATE_RAW_OK)
  161858. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161859. if (cinfo->next_scanline >= cinfo->image_height) {
  161860. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  161861. return 0;
  161862. }
  161863. /* Call progress monitor hook if present */
  161864. if (cinfo->progress != NULL) {
  161865. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  161866. cinfo->progress->pass_limit = (long) cinfo->image_height;
  161867. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161868. }
  161869. /* Give master control module another chance if this is first call to
  161870. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  161871. * delayed so that application can write COM, etc, markers between
  161872. * jpeg_start_compress and jpeg_write_raw_data.
  161873. */
  161874. if (cinfo->master->call_pass_startup)
  161875. (*cinfo->master->pass_startup) (cinfo);
  161876. /* Verify that at least one iMCU row has been passed. */
  161877. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  161878. if (num_lines < lines_per_iMCU_row)
  161879. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  161880. /* Directly compress the row. */
  161881. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  161882. /* If compressor did not consume the whole row, suspend processing. */
  161883. return 0;
  161884. }
  161885. /* OK, we processed one iMCU row. */
  161886. cinfo->next_scanline += lines_per_iMCU_row;
  161887. return lines_per_iMCU_row;
  161888. }
  161889. /*** End of inlined file: jcapistd.c ***/
  161890. /*** Start of inlined file: jccoefct.c ***/
  161891. #define JPEG_INTERNALS
  161892. /* We use a full-image coefficient buffer when doing Huffman optimization,
  161893. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  161894. * step is run during the first pass, and subsequent passes need only read
  161895. * the buffered coefficients.
  161896. */
  161897. #ifdef ENTROPY_OPT_SUPPORTED
  161898. #define FULL_COEF_BUFFER_SUPPORTED
  161899. #else
  161900. #ifdef C_MULTISCAN_FILES_SUPPORTED
  161901. #define FULL_COEF_BUFFER_SUPPORTED
  161902. #endif
  161903. #endif
  161904. /* Private buffer controller object */
  161905. typedef struct {
  161906. struct jpeg_c_coef_controller pub; /* public fields */
  161907. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  161908. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  161909. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  161910. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  161911. /* For single-pass compression, it's sufficient to buffer just one MCU
  161912. * (although this may prove a bit slow in practice). We allocate a
  161913. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  161914. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  161915. * it's not really very big; this is to keep the module interfaces unchanged
  161916. * when a large coefficient buffer is necessary.)
  161917. * In multi-pass modes, this array points to the current MCU's blocks
  161918. * within the virtual arrays.
  161919. */
  161920. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  161921. /* In multi-pass modes, we need a virtual block array for each component. */
  161922. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  161923. } my_coef_controller;
  161924. typedef my_coef_controller * my_coef_ptr;
  161925. /* Forward declarations */
  161926. METHODDEF(boolean) compress_data
  161927. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161928. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161929. METHODDEF(boolean) compress_first_pass
  161930. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161931. METHODDEF(boolean) compress_output
  161932. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  161933. #endif
  161934. LOCAL(void)
  161935. start_iMCU_row (j_compress_ptr cinfo)
  161936. /* Reset within-iMCU-row counters for a new row */
  161937. {
  161938. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161939. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  161940. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  161941. * But at the bottom of the image, process only what's left.
  161942. */
  161943. if (cinfo->comps_in_scan > 1) {
  161944. coef->MCU_rows_per_iMCU_row = 1;
  161945. } else {
  161946. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  161947. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  161948. else
  161949. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  161950. }
  161951. coef->mcu_ctr = 0;
  161952. coef->MCU_vert_offset = 0;
  161953. }
  161954. /*
  161955. * Initialize for a processing pass.
  161956. */
  161957. METHODDEF(void)
  161958. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  161959. {
  161960. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161961. coef->iMCU_row_num = 0;
  161962. start_iMCU_row(cinfo);
  161963. switch (pass_mode) {
  161964. case JBUF_PASS_THRU:
  161965. if (coef->whole_image[0] != NULL)
  161966. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161967. coef->pub.compress_data = compress_data;
  161968. break;
  161969. #ifdef FULL_COEF_BUFFER_SUPPORTED
  161970. case JBUF_SAVE_AND_PASS:
  161971. if (coef->whole_image[0] == NULL)
  161972. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161973. coef->pub.compress_data = compress_first_pass;
  161974. break;
  161975. case JBUF_CRANK_DEST:
  161976. if (coef->whole_image[0] == NULL)
  161977. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161978. coef->pub.compress_data = compress_output;
  161979. break;
  161980. #endif
  161981. default:
  161982. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  161983. break;
  161984. }
  161985. }
  161986. /*
  161987. * Process some data in the single-pass case.
  161988. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  161989. * per call, ie, v_samp_factor block rows for each component in the image.
  161990. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  161991. *
  161992. * NB: input_buf contains a plane for each component in image,
  161993. * which we index according to the component's SOF position.
  161994. */
  161995. METHODDEF(boolean)
  161996. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  161997. {
  161998. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  161999. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162000. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  162001. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162002. int blkn, bi, ci, yindex, yoffset, blockcnt;
  162003. JDIMENSION ypos, xpos;
  162004. jpeg_component_info *compptr;
  162005. /* Loop to write as much as one whole iMCU row */
  162006. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162007. yoffset++) {
  162008. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  162009. MCU_col_num++) {
  162010. /* Determine where data comes from in input_buf and do the DCT thing.
  162011. * Each call on forward_DCT processes a horizontal row of DCT blocks
  162012. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  162013. * sequentially. Dummy blocks at the right or bottom edge are filled in
  162014. * specially. The data in them does not matter for image reconstruction,
  162015. * so we fill them with values that will encode to the smallest amount of
  162016. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  162017. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  162018. */
  162019. blkn = 0;
  162020. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162021. compptr = cinfo->cur_comp_info[ci];
  162022. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  162023. : compptr->last_col_width;
  162024. xpos = MCU_col_num * compptr->MCU_sample_width;
  162025. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  162026. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162027. if (coef->iMCU_row_num < last_iMCU_row ||
  162028. yoffset+yindex < compptr->last_row_height) {
  162029. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  162030. input_buf[compptr->component_index],
  162031. coef->MCU_buffer[blkn],
  162032. ypos, xpos, (JDIMENSION) blockcnt);
  162033. if (blockcnt < compptr->MCU_width) {
  162034. /* Create some dummy blocks at the right edge of the image. */
  162035. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  162036. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  162037. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  162038. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  162039. }
  162040. }
  162041. } else {
  162042. /* Create a row of dummy blocks at the bottom of the image. */
  162043. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  162044. compptr->MCU_width * SIZEOF(JBLOCK));
  162045. for (bi = 0; bi < compptr->MCU_width; bi++) {
  162046. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  162047. }
  162048. }
  162049. blkn += compptr->MCU_width;
  162050. ypos += DCTSIZE;
  162051. }
  162052. }
  162053. /* Try to write the MCU. In event of a suspension failure, we will
  162054. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  162055. */
  162056. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  162057. /* Suspension forced; update state counters and exit */
  162058. coef->MCU_vert_offset = yoffset;
  162059. coef->mcu_ctr = MCU_col_num;
  162060. return FALSE;
  162061. }
  162062. }
  162063. /* Completed an MCU row, but perhaps not an iMCU row */
  162064. coef->mcu_ctr = 0;
  162065. }
  162066. /* Completed the iMCU row, advance counters for next one */
  162067. coef->iMCU_row_num++;
  162068. start_iMCU_row(cinfo);
  162069. return TRUE;
  162070. }
  162071. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162072. /*
  162073. * Process some data in the first pass of a multi-pass case.
  162074. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162075. * per call, ie, v_samp_factor block rows for each component in the image.
  162076. * This amount of data is read from the source buffer, DCT'd and quantized,
  162077. * and saved into the virtual arrays. We also generate suitable dummy blocks
  162078. * as needed at the right and lower edges. (The dummy blocks are constructed
  162079. * in the virtual arrays, which have been padded appropriately.) This makes
  162080. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  162081. *
  162082. * We must also emit the data to the entropy encoder. This is conveniently
  162083. * done by calling compress_output() after we've loaded the current strip
  162084. * of the virtual arrays.
  162085. *
  162086. * NB: input_buf contains a plane for each component in image. All
  162087. * components are DCT'd and loaded into the virtual arrays in this pass.
  162088. * However, it may be that only a subset of the components are emitted to
  162089. * the entropy encoder during this first pass; be careful about looking
  162090. * at the scan-dependent variables (MCU dimensions, etc).
  162091. */
  162092. METHODDEF(boolean)
  162093. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  162094. {
  162095. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162096. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162097. JDIMENSION blocks_across, MCUs_across, MCUindex;
  162098. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  162099. JCOEF lastDC;
  162100. jpeg_component_info *compptr;
  162101. JBLOCKARRAY buffer;
  162102. JBLOCKROW thisblockrow, lastblockrow;
  162103. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162104. ci++, compptr++) {
  162105. /* Align the virtual buffer for this component. */
  162106. buffer = (*cinfo->mem->access_virt_barray)
  162107. ((j_common_ptr) cinfo, coef->whole_image[ci],
  162108. coef->iMCU_row_num * compptr->v_samp_factor,
  162109. (JDIMENSION) compptr->v_samp_factor, TRUE);
  162110. /* Count non-dummy DCT block rows in this iMCU row. */
  162111. if (coef->iMCU_row_num < last_iMCU_row)
  162112. block_rows = compptr->v_samp_factor;
  162113. else {
  162114. /* NB: can't use last_row_height here, since may not be set! */
  162115. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  162116. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  162117. }
  162118. blocks_across = compptr->width_in_blocks;
  162119. h_samp_factor = compptr->h_samp_factor;
  162120. /* Count number of dummy blocks to be added at the right margin. */
  162121. ndummy = (int) (blocks_across % h_samp_factor);
  162122. if (ndummy > 0)
  162123. ndummy = h_samp_factor - ndummy;
  162124. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  162125. * on forward_DCT processes a complete horizontal row of DCT blocks.
  162126. */
  162127. for (block_row = 0; block_row < block_rows; block_row++) {
  162128. thisblockrow = buffer[block_row];
  162129. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  162130. input_buf[ci], thisblockrow,
  162131. (JDIMENSION) (block_row * DCTSIZE),
  162132. (JDIMENSION) 0, blocks_across);
  162133. if (ndummy > 0) {
  162134. /* Create dummy blocks at the right edge of the image. */
  162135. thisblockrow += blocks_across; /* => first dummy block */
  162136. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  162137. lastDC = thisblockrow[-1][0];
  162138. for (bi = 0; bi < ndummy; bi++) {
  162139. thisblockrow[bi][0] = lastDC;
  162140. }
  162141. }
  162142. }
  162143. /* If at end of image, create dummy block rows as needed.
  162144. * The tricky part here is that within each MCU, we want the DC values
  162145. * of the dummy blocks to match the last real block's DC value.
  162146. * This squeezes a few more bytes out of the resulting file...
  162147. */
  162148. if (coef->iMCU_row_num == last_iMCU_row) {
  162149. blocks_across += ndummy; /* include lower right corner */
  162150. MCUs_across = blocks_across / h_samp_factor;
  162151. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  162152. block_row++) {
  162153. thisblockrow = buffer[block_row];
  162154. lastblockrow = buffer[block_row-1];
  162155. jzero_far((void FAR *) thisblockrow,
  162156. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  162157. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  162158. lastDC = lastblockrow[h_samp_factor-1][0];
  162159. for (bi = 0; bi < h_samp_factor; bi++) {
  162160. thisblockrow[bi][0] = lastDC;
  162161. }
  162162. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  162163. lastblockrow += h_samp_factor;
  162164. }
  162165. }
  162166. }
  162167. }
  162168. /* NB: compress_output will increment iMCU_row_num if successful.
  162169. * A suspension return will result in redoing all the work above next time.
  162170. */
  162171. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  162172. return compress_output(cinfo, input_buf);
  162173. }
  162174. /*
  162175. * Process some data in subsequent passes of a multi-pass case.
  162176. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162177. * per call, ie, v_samp_factor block rows for each component in the scan.
  162178. * The data is obtained from the virtual arrays and fed to the entropy coder.
  162179. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  162180. *
  162181. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  162182. */
  162183. METHODDEF(boolean)
  162184. compress_output (j_compress_ptr cinfo, JSAMPIMAGE)
  162185. {
  162186. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162187. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162188. int blkn, ci, xindex, yindex, yoffset;
  162189. JDIMENSION start_col;
  162190. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  162191. JBLOCKROW buffer_ptr;
  162192. jpeg_component_info *compptr;
  162193. /* Align the virtual buffers for the components used in this scan.
  162194. * NB: during first pass, this is safe only because the buffers will
  162195. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  162196. */
  162197. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162198. compptr = cinfo->cur_comp_info[ci];
  162199. buffer[ci] = (*cinfo->mem->access_virt_barray)
  162200. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  162201. coef->iMCU_row_num * compptr->v_samp_factor,
  162202. (JDIMENSION) compptr->v_samp_factor, FALSE);
  162203. }
  162204. /* Loop to process one whole iMCU row */
  162205. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162206. yoffset++) {
  162207. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  162208. MCU_col_num++) {
  162209. /* Construct list of pointers to DCT blocks belonging to this MCU */
  162210. blkn = 0; /* index of current DCT block within MCU */
  162211. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162212. compptr = cinfo->cur_comp_info[ci];
  162213. start_col = MCU_col_num * compptr->MCU_width;
  162214. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162215. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  162216. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  162217. coef->MCU_buffer[blkn++] = buffer_ptr++;
  162218. }
  162219. }
  162220. }
  162221. /* Try to write the MCU. */
  162222. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  162223. /* Suspension forced; update state counters and exit */
  162224. coef->MCU_vert_offset = yoffset;
  162225. coef->mcu_ctr = MCU_col_num;
  162226. return FALSE;
  162227. }
  162228. }
  162229. /* Completed an MCU row, but perhaps not an iMCU row */
  162230. coef->mcu_ctr = 0;
  162231. }
  162232. /* Completed the iMCU row, advance counters for next one */
  162233. coef->iMCU_row_num++;
  162234. start_iMCU_row(cinfo);
  162235. return TRUE;
  162236. }
  162237. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  162238. /*
  162239. * Initialize coefficient buffer controller.
  162240. */
  162241. GLOBAL(void)
  162242. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  162243. {
  162244. my_coef_ptr coef;
  162245. coef = (my_coef_ptr)
  162246. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162247. SIZEOF(my_coef_controller));
  162248. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  162249. coef->pub.start_pass = start_pass_coef;
  162250. /* Create the coefficient buffer. */
  162251. if (need_full_buffer) {
  162252. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162253. /* Allocate a full-image virtual array for each component, */
  162254. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  162255. int ci;
  162256. jpeg_component_info *compptr;
  162257. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162258. ci++, compptr++) {
  162259. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  162260. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  162261. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  162262. (long) compptr->h_samp_factor),
  162263. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  162264. (long) compptr->v_samp_factor),
  162265. (JDIMENSION) compptr->v_samp_factor);
  162266. }
  162267. #else
  162268. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162269. #endif
  162270. } else {
  162271. /* We only need a single-MCU buffer. */
  162272. JBLOCKROW buffer;
  162273. int i;
  162274. buffer = (JBLOCKROW)
  162275. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162276. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  162277. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  162278. coef->MCU_buffer[i] = buffer + i;
  162279. }
  162280. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  162281. }
  162282. }
  162283. /*** End of inlined file: jccoefct.c ***/
  162284. /*** Start of inlined file: jccolor.c ***/
  162285. #define JPEG_INTERNALS
  162286. /* Private subobject */
  162287. typedef struct {
  162288. struct jpeg_color_converter pub; /* public fields */
  162289. /* Private state for RGB->YCC conversion */
  162290. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  162291. } my_color_converter;
  162292. typedef my_color_converter * my_cconvert_ptr;
  162293. /**************** RGB -> YCbCr conversion: most common case **************/
  162294. /*
  162295. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  162296. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  162297. * The conversion equations to be implemented are therefore
  162298. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  162299. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  162300. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  162301. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  162302. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  162303. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  162304. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  162305. * were not represented exactly. Now we sacrifice exact representation of
  162306. * maximum red and maximum blue in order to get exact grayscales.
  162307. *
  162308. * To avoid floating-point arithmetic, we represent the fractional constants
  162309. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  162310. * the products by 2^16, with appropriate rounding, to get the correct answer.
  162311. *
  162312. * For even more speed, we avoid doing any multiplications in the inner loop
  162313. * by precalculating the constants times R,G,B for all possible values.
  162314. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  162315. * for 12-bit samples it is still acceptable. It's not very reasonable for
  162316. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  162317. * colorspace anyway.
  162318. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  162319. * in the tables to save adding them separately in the inner loop.
  162320. */
  162321. #define SCALEBITS 16 /* speediest right-shift on some machines */
  162322. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  162323. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  162324. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  162325. /* We allocate one big table and divide it up into eight parts, instead of
  162326. * doing eight alloc_small requests. This lets us use a single table base
  162327. * address, which can be held in a register in the inner loops on many
  162328. * machines (more than can hold all eight addresses, anyway).
  162329. */
  162330. #define R_Y_OFF 0 /* offset to R => Y section */
  162331. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  162332. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  162333. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  162334. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  162335. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  162336. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  162337. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  162338. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  162339. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  162340. /*
  162341. * Initialize for RGB->YCC colorspace conversion.
  162342. */
  162343. METHODDEF(void)
  162344. rgb_ycc_start (j_compress_ptr cinfo)
  162345. {
  162346. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162347. INT32 * rgb_ycc_tab;
  162348. INT32 i;
  162349. /* Allocate and fill in the conversion tables. */
  162350. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  162351. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162352. (TABLE_SIZE * SIZEOF(INT32)));
  162353. for (i = 0; i <= MAXJSAMPLE; i++) {
  162354. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  162355. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  162356. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  162357. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  162358. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  162359. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  162360. * This ensures that the maximum output will round to MAXJSAMPLE
  162361. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  162362. */
  162363. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162364. /* B=>Cb and R=>Cr tables are the same
  162365. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162366. */
  162367. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  162368. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  162369. }
  162370. }
  162371. /*
  162372. * Convert some rows of samples to the JPEG colorspace.
  162373. *
  162374. * Note that we change from the application's interleaved-pixel format
  162375. * to our internal noninterleaved, one-plane-per-component format.
  162376. * The input buffer is therefore three times as wide as the output buffer.
  162377. *
  162378. * A starting row offset is provided only for the output buffer. The caller
  162379. * can easily adjust the passed input_buf value to accommodate any row
  162380. * offset required on that side.
  162381. */
  162382. METHODDEF(void)
  162383. rgb_ycc_convert (j_compress_ptr cinfo,
  162384. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162385. JDIMENSION output_row, int num_rows)
  162386. {
  162387. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162388. register int r, g, b;
  162389. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162390. register JSAMPROW inptr;
  162391. register JSAMPROW outptr0, outptr1, outptr2;
  162392. register JDIMENSION col;
  162393. JDIMENSION num_cols = cinfo->image_width;
  162394. while (--num_rows >= 0) {
  162395. inptr = *input_buf++;
  162396. outptr0 = output_buf[0][output_row];
  162397. outptr1 = output_buf[1][output_row];
  162398. outptr2 = output_buf[2][output_row];
  162399. output_row++;
  162400. for (col = 0; col < num_cols; col++) {
  162401. r = GETJSAMPLE(inptr[RGB_RED]);
  162402. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162403. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162404. inptr += RGB_PIXELSIZE;
  162405. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162406. * must be too; we do not need an explicit range-limiting operation.
  162407. * Hence the value being shifted is never negative, and we don't
  162408. * need the general RIGHT_SHIFT macro.
  162409. */
  162410. /* Y */
  162411. outptr0[col] = (JSAMPLE)
  162412. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162413. >> SCALEBITS);
  162414. /* Cb */
  162415. outptr1[col] = (JSAMPLE)
  162416. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162417. >> SCALEBITS);
  162418. /* Cr */
  162419. outptr2[col] = (JSAMPLE)
  162420. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162421. >> SCALEBITS);
  162422. }
  162423. }
  162424. }
  162425. /**************** Cases other than RGB -> YCbCr **************/
  162426. /*
  162427. * Convert some rows of samples to the JPEG colorspace.
  162428. * This version handles RGB->grayscale conversion, which is the same
  162429. * as the RGB->Y portion of RGB->YCbCr.
  162430. * We assume rgb_ycc_start has been called (we only use the Y tables).
  162431. */
  162432. METHODDEF(void)
  162433. rgb_gray_convert (j_compress_ptr cinfo,
  162434. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162435. JDIMENSION output_row, int num_rows)
  162436. {
  162437. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162438. register int r, g, b;
  162439. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162440. register JSAMPROW inptr;
  162441. register JSAMPROW outptr;
  162442. register JDIMENSION col;
  162443. JDIMENSION num_cols = cinfo->image_width;
  162444. while (--num_rows >= 0) {
  162445. inptr = *input_buf++;
  162446. outptr = output_buf[0][output_row];
  162447. output_row++;
  162448. for (col = 0; col < num_cols; col++) {
  162449. r = GETJSAMPLE(inptr[RGB_RED]);
  162450. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162451. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162452. inptr += RGB_PIXELSIZE;
  162453. /* Y */
  162454. outptr[col] = (JSAMPLE)
  162455. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162456. >> SCALEBITS);
  162457. }
  162458. }
  162459. }
  162460. /*
  162461. * Convert some rows of samples to the JPEG colorspace.
  162462. * This version handles Adobe-style CMYK->YCCK conversion,
  162463. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  162464. * conversion as above, while passing K (black) unchanged.
  162465. * We assume rgb_ycc_start has been called.
  162466. */
  162467. METHODDEF(void)
  162468. cmyk_ycck_convert (j_compress_ptr cinfo,
  162469. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162470. JDIMENSION output_row, int num_rows)
  162471. {
  162472. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162473. register int r, g, b;
  162474. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162475. register JSAMPROW inptr;
  162476. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  162477. register JDIMENSION col;
  162478. JDIMENSION num_cols = cinfo->image_width;
  162479. while (--num_rows >= 0) {
  162480. inptr = *input_buf++;
  162481. outptr0 = output_buf[0][output_row];
  162482. outptr1 = output_buf[1][output_row];
  162483. outptr2 = output_buf[2][output_row];
  162484. outptr3 = output_buf[3][output_row];
  162485. output_row++;
  162486. for (col = 0; col < num_cols; col++) {
  162487. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  162488. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  162489. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  162490. /* K passes through as-is */
  162491. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  162492. inptr += 4;
  162493. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162494. * must be too; we do not need an explicit range-limiting operation.
  162495. * Hence the value being shifted is never negative, and we don't
  162496. * need the general RIGHT_SHIFT macro.
  162497. */
  162498. /* Y */
  162499. outptr0[col] = (JSAMPLE)
  162500. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162501. >> SCALEBITS);
  162502. /* Cb */
  162503. outptr1[col] = (JSAMPLE)
  162504. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162505. >> SCALEBITS);
  162506. /* Cr */
  162507. outptr2[col] = (JSAMPLE)
  162508. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162509. >> SCALEBITS);
  162510. }
  162511. }
  162512. }
  162513. /*
  162514. * Convert some rows of samples to the JPEG colorspace.
  162515. * This version handles grayscale output with no conversion.
  162516. * The source can be either plain grayscale or YCbCr (since Y == gray).
  162517. */
  162518. METHODDEF(void)
  162519. grayscale_convert (j_compress_ptr cinfo,
  162520. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162521. JDIMENSION output_row, int num_rows)
  162522. {
  162523. register JSAMPROW inptr;
  162524. register JSAMPROW outptr;
  162525. register JDIMENSION col;
  162526. JDIMENSION num_cols = cinfo->image_width;
  162527. int instride = cinfo->input_components;
  162528. while (--num_rows >= 0) {
  162529. inptr = *input_buf++;
  162530. outptr = output_buf[0][output_row];
  162531. output_row++;
  162532. for (col = 0; col < num_cols; col++) {
  162533. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  162534. inptr += instride;
  162535. }
  162536. }
  162537. }
  162538. /*
  162539. * Convert some rows of samples to the JPEG colorspace.
  162540. * This version handles multi-component colorspaces without conversion.
  162541. * We assume input_components == num_components.
  162542. */
  162543. METHODDEF(void)
  162544. null_convert (j_compress_ptr cinfo,
  162545. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162546. JDIMENSION output_row, int num_rows)
  162547. {
  162548. register JSAMPROW inptr;
  162549. register JSAMPROW outptr;
  162550. register JDIMENSION col;
  162551. register int ci;
  162552. int nc = cinfo->num_components;
  162553. JDIMENSION num_cols = cinfo->image_width;
  162554. while (--num_rows >= 0) {
  162555. /* It seems fastest to make a separate pass for each component. */
  162556. for (ci = 0; ci < nc; ci++) {
  162557. inptr = *input_buf;
  162558. outptr = output_buf[ci][output_row];
  162559. for (col = 0; col < num_cols; col++) {
  162560. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  162561. inptr += nc;
  162562. }
  162563. }
  162564. input_buf++;
  162565. output_row++;
  162566. }
  162567. }
  162568. /*
  162569. * Empty method for start_pass.
  162570. */
  162571. METHODDEF(void)
  162572. null_method (j_compress_ptr)
  162573. {
  162574. /* no work needed */
  162575. }
  162576. /*
  162577. * Module initialization routine for input colorspace conversion.
  162578. */
  162579. GLOBAL(void)
  162580. jinit_color_converter (j_compress_ptr cinfo)
  162581. {
  162582. my_cconvert_ptr cconvert;
  162583. cconvert = (my_cconvert_ptr)
  162584. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162585. SIZEOF(my_color_converter));
  162586. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  162587. /* set start_pass to null method until we find out differently */
  162588. cconvert->pub.start_pass = null_method;
  162589. /* Make sure input_components agrees with in_color_space */
  162590. switch (cinfo->in_color_space) {
  162591. case JCS_GRAYSCALE:
  162592. if (cinfo->input_components != 1)
  162593. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162594. break;
  162595. case JCS_RGB:
  162596. #if RGB_PIXELSIZE != 3
  162597. if (cinfo->input_components != RGB_PIXELSIZE)
  162598. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162599. break;
  162600. #endif /* else share code with YCbCr */
  162601. case JCS_YCbCr:
  162602. if (cinfo->input_components != 3)
  162603. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162604. break;
  162605. case JCS_CMYK:
  162606. case JCS_YCCK:
  162607. if (cinfo->input_components != 4)
  162608. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162609. break;
  162610. default: /* JCS_UNKNOWN can be anything */
  162611. if (cinfo->input_components < 1)
  162612. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162613. break;
  162614. }
  162615. /* Check num_components, set conversion method based on requested space */
  162616. switch (cinfo->jpeg_color_space) {
  162617. case JCS_GRAYSCALE:
  162618. if (cinfo->num_components != 1)
  162619. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162620. if (cinfo->in_color_space == JCS_GRAYSCALE)
  162621. cconvert->pub.color_convert = grayscale_convert;
  162622. else if (cinfo->in_color_space == JCS_RGB) {
  162623. cconvert->pub.start_pass = rgb_ycc_start;
  162624. cconvert->pub.color_convert = rgb_gray_convert;
  162625. } else if (cinfo->in_color_space == JCS_YCbCr)
  162626. cconvert->pub.color_convert = grayscale_convert;
  162627. else
  162628. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162629. break;
  162630. case JCS_RGB:
  162631. if (cinfo->num_components != 3)
  162632. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162633. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  162634. cconvert->pub.color_convert = null_convert;
  162635. else
  162636. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162637. break;
  162638. case JCS_YCbCr:
  162639. if (cinfo->num_components != 3)
  162640. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162641. if (cinfo->in_color_space == JCS_RGB) {
  162642. cconvert->pub.start_pass = rgb_ycc_start;
  162643. cconvert->pub.color_convert = rgb_ycc_convert;
  162644. } else if (cinfo->in_color_space == JCS_YCbCr)
  162645. cconvert->pub.color_convert = null_convert;
  162646. else
  162647. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162648. break;
  162649. case JCS_CMYK:
  162650. if (cinfo->num_components != 4)
  162651. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162652. if (cinfo->in_color_space == JCS_CMYK)
  162653. cconvert->pub.color_convert = null_convert;
  162654. else
  162655. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162656. break;
  162657. case JCS_YCCK:
  162658. if (cinfo->num_components != 4)
  162659. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162660. if (cinfo->in_color_space == JCS_CMYK) {
  162661. cconvert->pub.start_pass = rgb_ycc_start;
  162662. cconvert->pub.color_convert = cmyk_ycck_convert;
  162663. } else if (cinfo->in_color_space == JCS_YCCK)
  162664. cconvert->pub.color_convert = null_convert;
  162665. else
  162666. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162667. break;
  162668. default: /* allow null conversion of JCS_UNKNOWN */
  162669. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  162670. cinfo->num_components != cinfo->input_components)
  162671. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162672. cconvert->pub.color_convert = null_convert;
  162673. break;
  162674. }
  162675. }
  162676. /*** End of inlined file: jccolor.c ***/
  162677. #undef FIX
  162678. /*** Start of inlined file: jcdctmgr.c ***/
  162679. #define JPEG_INTERNALS
  162680. /*** Start of inlined file: jdct.h ***/
  162681. /*
  162682. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  162683. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  162684. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  162685. * implementations use an array of type FAST_FLOAT, instead.)
  162686. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  162687. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  162688. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  162689. * convention improves accuracy in integer implementations and saves some
  162690. * work in floating-point ones.
  162691. * Quantization of the output coefficients is done by jcdctmgr.c.
  162692. */
  162693. #ifndef __jdct_h__
  162694. #define __jdct_h__
  162695. #if BITS_IN_JSAMPLE == 8
  162696. typedef int DCTELEM; /* 16 or 32 bits is fine */
  162697. #else
  162698. typedef INT32 DCTELEM; /* must have 32 bits */
  162699. #endif
  162700. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  162701. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  162702. /*
  162703. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  162704. * to an output sample array. The routine must dequantize the input data as
  162705. * well as perform the IDCT; for dequantization, it uses the multiplier table
  162706. * pointed to by compptr->dct_table. The output data is to be placed into the
  162707. * sample array starting at a specified column. (Any row offset needed will
  162708. * be applied to the array pointer before it is passed to the IDCT code.)
  162709. * Note that the number of samples emitted by the IDCT routine is
  162710. * DCT_scaled_size * DCT_scaled_size.
  162711. */
  162712. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  162713. /*
  162714. * Each IDCT routine has its own ideas about the best dct_table element type.
  162715. */
  162716. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  162717. #if BITS_IN_JSAMPLE == 8
  162718. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  162719. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  162720. #else
  162721. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  162722. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  162723. #endif
  162724. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  162725. /*
  162726. * Each IDCT routine is responsible for range-limiting its results and
  162727. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  162728. * be quite far out of range if the input data is corrupt, so a bulletproof
  162729. * range-limiting step is required. We use a mask-and-table-lookup method
  162730. * to do the combined operations quickly. See the comments with
  162731. * prepare_range_limit_table (in jdmaster.c) for more info.
  162732. */
  162733. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  162734. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  162735. /* Short forms of external names for systems with brain-damaged linkers. */
  162736. #ifdef NEED_SHORT_EXTERNAL_NAMES
  162737. #define jpeg_fdct_islow jFDislow
  162738. #define jpeg_fdct_ifast jFDifast
  162739. #define jpeg_fdct_float jFDfloat
  162740. #define jpeg_idct_islow jRDislow
  162741. #define jpeg_idct_ifast jRDifast
  162742. #define jpeg_idct_float jRDfloat
  162743. #define jpeg_idct_4x4 jRD4x4
  162744. #define jpeg_idct_2x2 jRD2x2
  162745. #define jpeg_idct_1x1 jRD1x1
  162746. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  162747. /* Extern declarations for the forward and inverse DCT routines. */
  162748. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  162749. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  162750. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  162751. EXTERN(void) jpeg_idct_islow
  162752. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162753. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162754. EXTERN(void) jpeg_idct_ifast
  162755. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162756. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162757. EXTERN(void) jpeg_idct_float
  162758. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162759. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162760. EXTERN(void) jpeg_idct_4x4
  162761. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162762. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162763. EXTERN(void) jpeg_idct_2x2
  162764. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162765. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162766. EXTERN(void) jpeg_idct_1x1
  162767. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162768. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162769. /*
  162770. * Macros for handling fixed-point arithmetic; these are used by many
  162771. * but not all of the DCT/IDCT modules.
  162772. *
  162773. * All values are expected to be of type INT32.
  162774. * Fractional constants are scaled left by CONST_BITS bits.
  162775. * CONST_BITS is defined within each module using these macros,
  162776. * and may differ from one module to the next.
  162777. */
  162778. #define ONE ((INT32) 1)
  162779. #define CONST_SCALE (ONE << CONST_BITS)
  162780. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  162781. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  162782. * thus causing a lot of useless floating-point operations at run time.
  162783. */
  162784. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  162785. /* Descale and correctly round an INT32 value that's scaled by N bits.
  162786. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  162787. * the fudge factor is correct for either sign of X.
  162788. */
  162789. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  162790. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  162791. * This macro is used only when the two inputs will actually be no more than
  162792. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  162793. * full 32x32 multiply. This provides a useful speedup on many machines.
  162794. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  162795. * in C, but some C compilers will do the right thing if you provide the
  162796. * correct combination of casts.
  162797. */
  162798. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162799. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  162800. #endif
  162801. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  162802. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  162803. #endif
  162804. #ifndef MULTIPLY16C16 /* default definition */
  162805. #define MULTIPLY16C16(var,const) ((var) * (const))
  162806. #endif
  162807. /* Same except both inputs are variables. */
  162808. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  162809. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  162810. #endif
  162811. #ifndef MULTIPLY16V16 /* default definition */
  162812. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  162813. #endif
  162814. #endif
  162815. /*** End of inlined file: jdct.h ***/
  162816. /* Private declarations for DCT subsystem */
  162817. /* Private subobject for this module */
  162818. typedef struct {
  162819. struct jpeg_forward_dct pub; /* public fields */
  162820. /* Pointer to the DCT routine actually in use */
  162821. forward_DCT_method_ptr do_dct;
  162822. /* The actual post-DCT divisors --- not identical to the quant table
  162823. * entries, because of scaling (especially for an unnormalized DCT).
  162824. * Each table is given in normal array order.
  162825. */
  162826. DCTELEM * divisors[NUM_QUANT_TBLS];
  162827. #ifdef DCT_FLOAT_SUPPORTED
  162828. /* Same as above for the floating-point case. */
  162829. float_DCT_method_ptr do_float_dct;
  162830. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  162831. #endif
  162832. } my_fdct_controller;
  162833. typedef my_fdct_controller * my_fdct_ptr;
  162834. /*
  162835. * Initialize for a processing pass.
  162836. * Verify that all referenced Q-tables are present, and set up
  162837. * the divisor table for each one.
  162838. * In the current implementation, DCT of all components is done during
  162839. * the first pass, even if only some components will be output in the
  162840. * first scan. Hence all components should be examined here.
  162841. */
  162842. METHODDEF(void)
  162843. start_pass_fdctmgr (j_compress_ptr cinfo)
  162844. {
  162845. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162846. int ci, qtblno, i;
  162847. jpeg_component_info *compptr;
  162848. JQUANT_TBL * qtbl;
  162849. DCTELEM * dtbl;
  162850. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162851. ci++, compptr++) {
  162852. qtblno = compptr->quant_tbl_no;
  162853. /* Make sure specified quantization table is present */
  162854. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  162855. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  162856. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  162857. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  162858. /* Compute divisors for this quant table */
  162859. /* We may do this more than once for same table, but it's not a big deal */
  162860. switch (cinfo->dct_method) {
  162861. #ifdef DCT_ISLOW_SUPPORTED
  162862. case JDCT_ISLOW:
  162863. /* For LL&M IDCT method, divisors are equal to raw quantization
  162864. * coefficients multiplied by 8 (to counteract scaling).
  162865. */
  162866. if (fdct->divisors[qtblno] == NULL) {
  162867. fdct->divisors[qtblno] = (DCTELEM *)
  162868. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162869. DCTSIZE2 * SIZEOF(DCTELEM));
  162870. }
  162871. dtbl = fdct->divisors[qtblno];
  162872. for (i = 0; i < DCTSIZE2; i++) {
  162873. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  162874. }
  162875. break;
  162876. #endif
  162877. #ifdef DCT_IFAST_SUPPORTED
  162878. case JDCT_IFAST:
  162879. {
  162880. /* For AA&N IDCT method, divisors are equal to quantization
  162881. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162882. * scalefactor[0] = 1
  162883. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162884. * We apply a further scale factor of 8.
  162885. */
  162886. #define CONST_BITS 14
  162887. static const INT16 aanscales[DCTSIZE2] = {
  162888. /* precomputed values scaled up by 14 bits */
  162889. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162890. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  162891. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  162892. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  162893. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162894. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  162895. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  162896. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  162897. };
  162898. SHIFT_TEMPS
  162899. if (fdct->divisors[qtblno] == NULL) {
  162900. fdct->divisors[qtblno] = (DCTELEM *)
  162901. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162902. DCTSIZE2 * SIZEOF(DCTELEM));
  162903. }
  162904. dtbl = fdct->divisors[qtblno];
  162905. for (i = 0; i < DCTSIZE2; i++) {
  162906. dtbl[i] = (DCTELEM)
  162907. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  162908. (INT32) aanscales[i]),
  162909. CONST_BITS-3);
  162910. }
  162911. }
  162912. break;
  162913. #endif
  162914. #ifdef DCT_FLOAT_SUPPORTED
  162915. case JDCT_FLOAT:
  162916. {
  162917. /* For float AA&N IDCT method, divisors are equal to quantization
  162918. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162919. * scalefactor[0] = 1
  162920. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162921. * We apply a further scale factor of 8.
  162922. * What's actually stored is 1/divisor so that the inner loop can
  162923. * use a multiplication rather than a division.
  162924. */
  162925. FAST_FLOAT * fdtbl;
  162926. int row, col;
  162927. static const double aanscalefactor[DCTSIZE] = {
  162928. 1.0, 1.387039845, 1.306562965, 1.175875602,
  162929. 1.0, 0.785694958, 0.541196100, 0.275899379
  162930. };
  162931. if (fdct->float_divisors[qtblno] == NULL) {
  162932. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  162933. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162934. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  162935. }
  162936. fdtbl = fdct->float_divisors[qtblno];
  162937. i = 0;
  162938. for (row = 0; row < DCTSIZE; row++) {
  162939. for (col = 0; col < DCTSIZE; col++) {
  162940. fdtbl[i] = (FAST_FLOAT)
  162941. (1.0 / (((double) qtbl->quantval[i] *
  162942. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  162943. i++;
  162944. }
  162945. }
  162946. }
  162947. break;
  162948. #endif
  162949. default:
  162950. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162951. break;
  162952. }
  162953. }
  162954. }
  162955. /*
  162956. * Perform forward DCT on one or more blocks of a component.
  162957. *
  162958. * The input samples are taken from the sample_data[] array starting at
  162959. * position start_row/start_col, and moving to the right for any additional
  162960. * blocks. The quantized coefficients are returned in coef_blocks[].
  162961. */
  162962. METHODDEF(void)
  162963. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  162964. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  162965. JDIMENSION start_row, JDIMENSION start_col,
  162966. JDIMENSION num_blocks)
  162967. /* This version is used for integer DCT implementations. */
  162968. {
  162969. /* This routine is heavily used, so it's worth coding it tightly. */
  162970. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  162971. forward_DCT_method_ptr do_dct = fdct->do_dct;
  162972. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  162973. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  162974. JDIMENSION bi;
  162975. sample_data += start_row; /* fold in the vertical offset once */
  162976. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  162977. /* Load data into workspace, applying unsigned->signed conversion */
  162978. { register DCTELEM *workspaceptr;
  162979. register JSAMPROW elemptr;
  162980. register int elemr;
  162981. workspaceptr = workspace;
  162982. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  162983. elemptr = sample_data[elemr] + start_col;
  162984. #if DCTSIZE == 8 /* unroll the inner loop */
  162985. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162986. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162987. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162988. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162989. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162990. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162991. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162992. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162993. #else
  162994. { register int elemc;
  162995. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  162996. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  162997. }
  162998. }
  162999. #endif
  163000. }
  163001. }
  163002. /* Perform the DCT */
  163003. (*do_dct) (workspace);
  163004. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  163005. { register DCTELEM temp, qval;
  163006. register int i;
  163007. register JCOEFPTR output_ptr = coef_blocks[bi];
  163008. for (i = 0; i < DCTSIZE2; i++) {
  163009. qval = divisors[i];
  163010. temp = workspace[i];
  163011. /* Divide the coefficient value by qval, ensuring proper rounding.
  163012. * Since C does not specify the direction of rounding for negative
  163013. * quotients, we have to force the dividend positive for portability.
  163014. *
  163015. * In most files, at least half of the output values will be zero
  163016. * (at default quantization settings, more like three-quarters...)
  163017. * so we should ensure that this case is fast. On many machines,
  163018. * a comparison is enough cheaper than a divide to make a special test
  163019. * a win. Since both inputs will be nonnegative, we need only test
  163020. * for a < b to discover whether a/b is 0.
  163021. * If your machine's division is fast enough, define FAST_DIVIDE.
  163022. */
  163023. #ifdef FAST_DIVIDE
  163024. #define DIVIDE_BY(a,b) a /= b
  163025. #else
  163026. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  163027. #endif
  163028. if (temp < 0) {
  163029. temp = -temp;
  163030. temp += qval>>1; /* for rounding */
  163031. DIVIDE_BY(temp, qval);
  163032. temp = -temp;
  163033. } else {
  163034. temp += qval>>1; /* for rounding */
  163035. DIVIDE_BY(temp, qval);
  163036. }
  163037. output_ptr[i] = (JCOEF) temp;
  163038. }
  163039. }
  163040. }
  163041. }
  163042. #ifdef DCT_FLOAT_SUPPORTED
  163043. METHODDEF(void)
  163044. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163045. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  163046. JDIMENSION start_row, JDIMENSION start_col,
  163047. JDIMENSION num_blocks)
  163048. /* This version is used for floating-point DCT implementations. */
  163049. {
  163050. /* This routine is heavily used, so it's worth coding it tightly. */
  163051. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  163052. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  163053. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  163054. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  163055. JDIMENSION bi;
  163056. sample_data += start_row; /* fold in the vertical offset once */
  163057. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  163058. /* Load data into workspace, applying unsigned->signed conversion */
  163059. { register FAST_FLOAT *workspaceptr;
  163060. register JSAMPROW elemptr;
  163061. register int elemr;
  163062. workspaceptr = workspace;
  163063. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  163064. elemptr = sample_data[elemr] + start_col;
  163065. #if DCTSIZE == 8 /* unroll the inner loop */
  163066. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163067. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163068. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163069. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163070. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163071. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163072. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163073. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163074. #else
  163075. { register int elemc;
  163076. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  163077. *workspaceptr++ = (FAST_FLOAT)
  163078. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163079. }
  163080. }
  163081. #endif
  163082. }
  163083. }
  163084. /* Perform the DCT */
  163085. (*do_dct) (workspace);
  163086. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  163087. { register FAST_FLOAT temp;
  163088. register int i;
  163089. register JCOEFPTR output_ptr = coef_blocks[bi];
  163090. for (i = 0; i < DCTSIZE2; i++) {
  163091. /* Apply the quantization and scaling factor */
  163092. temp = workspace[i] * divisors[i];
  163093. /* Round to nearest integer.
  163094. * Since C does not specify the direction of rounding for negative
  163095. * quotients, we have to force the dividend positive for portability.
  163096. * The maximum coefficient size is +-16K (for 12-bit data), so this
  163097. * code should work for either 16-bit or 32-bit ints.
  163098. */
  163099. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  163100. }
  163101. }
  163102. }
  163103. }
  163104. #endif /* DCT_FLOAT_SUPPORTED */
  163105. /*
  163106. * Initialize FDCT manager.
  163107. */
  163108. GLOBAL(void)
  163109. jinit_forward_dct (j_compress_ptr cinfo)
  163110. {
  163111. my_fdct_ptr fdct;
  163112. int i;
  163113. fdct = (my_fdct_ptr)
  163114. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163115. SIZEOF(my_fdct_controller));
  163116. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  163117. fdct->pub.start_pass = start_pass_fdctmgr;
  163118. switch (cinfo->dct_method) {
  163119. #ifdef DCT_ISLOW_SUPPORTED
  163120. case JDCT_ISLOW:
  163121. fdct->pub.forward_DCT = forward_DCT;
  163122. fdct->do_dct = jpeg_fdct_islow;
  163123. break;
  163124. #endif
  163125. #ifdef DCT_IFAST_SUPPORTED
  163126. case JDCT_IFAST:
  163127. fdct->pub.forward_DCT = forward_DCT;
  163128. fdct->do_dct = jpeg_fdct_ifast;
  163129. break;
  163130. #endif
  163131. #ifdef DCT_FLOAT_SUPPORTED
  163132. case JDCT_FLOAT:
  163133. fdct->pub.forward_DCT = forward_DCT_float;
  163134. fdct->do_float_dct = jpeg_fdct_float;
  163135. break;
  163136. #endif
  163137. default:
  163138. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163139. break;
  163140. }
  163141. /* Mark divisor tables unallocated */
  163142. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  163143. fdct->divisors[i] = NULL;
  163144. #ifdef DCT_FLOAT_SUPPORTED
  163145. fdct->float_divisors[i] = NULL;
  163146. #endif
  163147. }
  163148. }
  163149. /*** End of inlined file: jcdctmgr.c ***/
  163150. #undef CONST_BITS
  163151. /*** Start of inlined file: jchuff.c ***/
  163152. #define JPEG_INTERNALS
  163153. /*** Start of inlined file: jchuff.h ***/
  163154. /* The legal range of a DCT coefficient is
  163155. * -1024 .. +1023 for 8-bit data;
  163156. * -16384 .. +16383 for 12-bit data.
  163157. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  163158. */
  163159. #ifndef _jchuff_h_
  163160. #define _jchuff_h_
  163161. #if BITS_IN_JSAMPLE == 8
  163162. #define MAX_COEF_BITS 10
  163163. #else
  163164. #define MAX_COEF_BITS 14
  163165. #endif
  163166. /* Derived data constructed for each Huffman table */
  163167. typedef struct {
  163168. unsigned int ehufco[256]; /* code for each symbol */
  163169. char ehufsi[256]; /* length of code for each symbol */
  163170. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  163171. } c_derived_tbl;
  163172. /* Short forms of external names for systems with brain-damaged linkers. */
  163173. #ifdef NEED_SHORT_EXTERNAL_NAMES
  163174. #define jpeg_make_c_derived_tbl jMkCDerived
  163175. #define jpeg_gen_optimal_table jGenOptTbl
  163176. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  163177. /* Expand a Huffman table definition into the derived format */
  163178. EXTERN(void) jpeg_make_c_derived_tbl
  163179. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  163180. c_derived_tbl ** pdtbl));
  163181. /* Generate an optimal table definition given the specified counts */
  163182. EXTERN(void) jpeg_gen_optimal_table
  163183. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  163184. #endif
  163185. /*** End of inlined file: jchuff.h ***/
  163186. /* Declarations shared with jcphuff.c */
  163187. /* Expanded entropy encoder object for Huffman encoding.
  163188. *
  163189. * The savable_state subrecord contains fields that change within an MCU,
  163190. * but must not be updated permanently until we complete the MCU.
  163191. */
  163192. typedef struct {
  163193. INT32 put_buffer; /* current bit-accumulation buffer */
  163194. int put_bits; /* # of bits now in it */
  163195. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  163196. } savable_state;
  163197. /* This macro is to work around compilers with missing or broken
  163198. * structure assignment. You'll need to fix this code if you have
  163199. * such a compiler and you change MAX_COMPS_IN_SCAN.
  163200. */
  163201. #ifndef NO_STRUCT_ASSIGN
  163202. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  163203. #else
  163204. #if MAX_COMPS_IN_SCAN == 4
  163205. #define ASSIGN_STATE(dest,src) \
  163206. ((dest).put_buffer = (src).put_buffer, \
  163207. (dest).put_bits = (src).put_bits, \
  163208. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  163209. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  163210. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  163211. (dest).last_dc_val[3] = (src).last_dc_val[3])
  163212. #endif
  163213. #endif
  163214. typedef struct {
  163215. struct jpeg_entropy_encoder pub; /* public fields */
  163216. savable_state saved; /* Bit buffer & DC state at start of MCU */
  163217. /* These fields are NOT loaded into local working state. */
  163218. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  163219. int next_restart_num; /* next restart number to write (0-7) */
  163220. /* Pointers to derived tables (these workspaces have image lifespan) */
  163221. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  163222. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  163223. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  163224. long * dc_count_ptrs[NUM_HUFF_TBLS];
  163225. long * ac_count_ptrs[NUM_HUFF_TBLS];
  163226. #endif
  163227. } huff_entropy_encoder;
  163228. typedef huff_entropy_encoder * huff_entropy_ptr;
  163229. /* Working state while writing an MCU.
  163230. * This struct contains all the fields that are needed by subroutines.
  163231. */
  163232. typedef struct {
  163233. JOCTET * next_output_byte; /* => next byte to write in buffer */
  163234. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  163235. savable_state cur; /* Current bit buffer & DC state */
  163236. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  163237. } working_state;
  163238. /* Forward declarations */
  163239. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  163240. JBLOCKROW *MCU_data));
  163241. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  163242. #ifdef ENTROPY_OPT_SUPPORTED
  163243. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  163244. JBLOCKROW *MCU_data));
  163245. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  163246. #endif
  163247. /*
  163248. * Initialize for a Huffman-compressed scan.
  163249. * If gather_statistics is TRUE, we do not output anything during the scan,
  163250. * just count the Huffman symbols used and generate Huffman code tables.
  163251. */
  163252. METHODDEF(void)
  163253. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  163254. {
  163255. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163256. int ci, dctbl, actbl;
  163257. jpeg_component_info * compptr;
  163258. if (gather_statistics) {
  163259. #ifdef ENTROPY_OPT_SUPPORTED
  163260. entropy->pub.encode_mcu = encode_mcu_gather;
  163261. entropy->pub.finish_pass = finish_pass_gather;
  163262. #else
  163263. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163264. #endif
  163265. } else {
  163266. entropy->pub.encode_mcu = encode_mcu_huff;
  163267. entropy->pub.finish_pass = finish_pass_huff;
  163268. }
  163269. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163270. compptr = cinfo->cur_comp_info[ci];
  163271. dctbl = compptr->dc_tbl_no;
  163272. actbl = compptr->ac_tbl_no;
  163273. if (gather_statistics) {
  163274. #ifdef ENTROPY_OPT_SUPPORTED
  163275. /* Check for invalid table indexes */
  163276. /* (make_c_derived_tbl does this in the other path) */
  163277. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  163278. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  163279. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  163280. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  163281. /* Allocate and zero the statistics tables */
  163282. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  163283. if (entropy->dc_count_ptrs[dctbl] == NULL)
  163284. entropy->dc_count_ptrs[dctbl] = (long *)
  163285. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163286. 257 * SIZEOF(long));
  163287. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  163288. if (entropy->ac_count_ptrs[actbl] == NULL)
  163289. entropy->ac_count_ptrs[actbl] = (long *)
  163290. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163291. 257 * SIZEOF(long));
  163292. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  163293. #endif
  163294. } else {
  163295. /* Compute derived values for Huffman tables */
  163296. /* We may do this more than once for a table, but it's not expensive */
  163297. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  163298. & entropy->dc_derived_tbls[dctbl]);
  163299. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  163300. & entropy->ac_derived_tbls[actbl]);
  163301. }
  163302. /* Initialize DC predictions to 0 */
  163303. entropy->saved.last_dc_val[ci] = 0;
  163304. }
  163305. /* Initialize bit buffer to empty */
  163306. entropy->saved.put_buffer = 0;
  163307. entropy->saved.put_bits = 0;
  163308. /* Initialize restart stuff */
  163309. entropy->restarts_to_go = cinfo->restart_interval;
  163310. entropy->next_restart_num = 0;
  163311. }
  163312. /*
  163313. * Compute the derived values for a Huffman table.
  163314. * This routine also performs some validation checks on the table.
  163315. *
  163316. * Note this is also used by jcphuff.c.
  163317. */
  163318. GLOBAL(void)
  163319. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  163320. c_derived_tbl ** pdtbl)
  163321. {
  163322. JHUFF_TBL *htbl;
  163323. c_derived_tbl *dtbl;
  163324. int p, i, l, lastp, si, maxsymbol;
  163325. char huffsize[257];
  163326. unsigned int huffcode[257];
  163327. unsigned int code;
  163328. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  163329. * paralleling the order of the symbols themselves in htbl->huffval[].
  163330. */
  163331. /* Find the input Huffman table */
  163332. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  163333. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163334. htbl =
  163335. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  163336. if (htbl == NULL)
  163337. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163338. /* Allocate a workspace if we haven't already done so. */
  163339. if (*pdtbl == NULL)
  163340. *pdtbl = (c_derived_tbl *)
  163341. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163342. SIZEOF(c_derived_tbl));
  163343. dtbl = *pdtbl;
  163344. /* Figure C.1: make table of Huffman code length for each symbol */
  163345. p = 0;
  163346. for (l = 1; l <= 16; l++) {
  163347. i = (int) htbl->bits[l];
  163348. if (i < 0 || p + i > 256) /* protect against table overrun */
  163349. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163350. while (i--)
  163351. huffsize[p++] = (char) l;
  163352. }
  163353. huffsize[p] = 0;
  163354. lastp = p;
  163355. /* Figure C.2: generate the codes themselves */
  163356. /* We also validate that the counts represent a legal Huffman code tree. */
  163357. code = 0;
  163358. si = huffsize[0];
  163359. p = 0;
  163360. while (huffsize[p]) {
  163361. while (((int) huffsize[p]) == si) {
  163362. huffcode[p++] = code;
  163363. code++;
  163364. }
  163365. /* code is now 1 more than the last code used for codelength si; but
  163366. * it must still fit in si bits, since no code is allowed to be all ones.
  163367. */
  163368. if (((INT32) code) >= (((INT32) 1) << si))
  163369. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163370. code <<= 1;
  163371. si++;
  163372. }
  163373. /* Figure C.3: generate encoding tables */
  163374. /* These are code and size indexed by symbol value */
  163375. /* Set all codeless symbols to have code length 0;
  163376. * this lets us detect duplicate VAL entries here, and later
  163377. * allows emit_bits to detect any attempt to emit such symbols.
  163378. */
  163379. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  163380. /* This is also a convenient place to check for out-of-range
  163381. * and duplicated VAL entries. We allow 0..255 for AC symbols
  163382. * but only 0..15 for DC. (We could constrain them further
  163383. * based on data depth and mode, but this seems enough.)
  163384. */
  163385. maxsymbol = isDC ? 15 : 255;
  163386. for (p = 0; p < lastp; p++) {
  163387. i = htbl->huffval[p];
  163388. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  163389. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163390. dtbl->ehufco[i] = huffcode[p];
  163391. dtbl->ehufsi[i] = huffsize[p];
  163392. }
  163393. }
  163394. /* Outputting bytes to the file */
  163395. /* Emit a byte, taking 'action' if must suspend. */
  163396. #define emit_byte(state,val,action) \
  163397. { *(state)->next_output_byte++ = (JOCTET) (val); \
  163398. if (--(state)->free_in_buffer == 0) \
  163399. if (! dump_buffer(state)) \
  163400. { action; } }
  163401. LOCAL(boolean)
  163402. dump_buffer (working_state * state)
  163403. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  163404. {
  163405. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  163406. if (! (*dest->empty_output_buffer) (state->cinfo))
  163407. return FALSE;
  163408. /* After a successful buffer dump, must reset buffer pointers */
  163409. state->next_output_byte = dest->next_output_byte;
  163410. state->free_in_buffer = dest->free_in_buffer;
  163411. return TRUE;
  163412. }
  163413. /* Outputting bits to the file */
  163414. /* Only the right 24 bits of put_buffer are used; the valid bits are
  163415. * left-justified in this part. At most 16 bits can be passed to emit_bits
  163416. * in one call, and we never retain more than 7 bits in put_buffer
  163417. * between calls, so 24 bits are sufficient.
  163418. */
  163419. INLINE
  163420. LOCAL(boolean)
  163421. emit_bits (working_state * state, unsigned int code, int size)
  163422. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  163423. {
  163424. /* This routine is heavily used, so it's worth coding tightly. */
  163425. register INT32 put_buffer = (INT32) code;
  163426. register int put_bits = state->cur.put_bits;
  163427. /* if size is 0, caller used an invalid Huffman table entry */
  163428. if (size == 0)
  163429. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  163430. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  163431. put_bits += size; /* new number of bits in buffer */
  163432. put_buffer <<= 24 - put_bits; /* align incoming bits */
  163433. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  163434. while (put_bits >= 8) {
  163435. int c = (int) ((put_buffer >> 16) & 0xFF);
  163436. emit_byte(state, c, return FALSE);
  163437. if (c == 0xFF) { /* need to stuff a zero byte? */
  163438. emit_byte(state, 0, return FALSE);
  163439. }
  163440. put_buffer <<= 8;
  163441. put_bits -= 8;
  163442. }
  163443. state->cur.put_buffer = put_buffer; /* update state variables */
  163444. state->cur.put_bits = put_bits;
  163445. return TRUE;
  163446. }
  163447. LOCAL(boolean)
  163448. flush_bits (working_state * state)
  163449. {
  163450. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  163451. return FALSE;
  163452. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  163453. state->cur.put_bits = 0;
  163454. return TRUE;
  163455. }
  163456. /* Encode a single block's worth of coefficients */
  163457. LOCAL(boolean)
  163458. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  163459. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  163460. {
  163461. register int temp, temp2;
  163462. register int nbits;
  163463. register int k, r, i;
  163464. /* Encode the DC coefficient difference per section F.1.2.1 */
  163465. temp = temp2 = block[0] - last_dc_val;
  163466. if (temp < 0) {
  163467. temp = -temp; /* temp is abs value of input */
  163468. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  163469. /* This code assumes we are on a two's complement machine */
  163470. temp2--;
  163471. }
  163472. /* Find the number of bits needed for the magnitude of the coefficient */
  163473. nbits = 0;
  163474. while (temp) {
  163475. nbits++;
  163476. temp >>= 1;
  163477. }
  163478. /* Check for out-of-range coefficient values.
  163479. * Since we're encoding a difference, the range limit is twice as much.
  163480. */
  163481. if (nbits > MAX_COEF_BITS+1)
  163482. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163483. /* Emit the Huffman-coded symbol for the number of bits */
  163484. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  163485. return FALSE;
  163486. /* Emit that number of bits of the value, if positive, */
  163487. /* or the complement of its magnitude, if negative. */
  163488. if (nbits) /* emit_bits rejects calls with size 0 */
  163489. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163490. return FALSE;
  163491. /* Encode the AC coefficients per section F.1.2.2 */
  163492. r = 0; /* r = run length of zeros */
  163493. for (k = 1; k < DCTSIZE2; k++) {
  163494. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163495. r++;
  163496. } else {
  163497. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163498. while (r > 15) {
  163499. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  163500. return FALSE;
  163501. r -= 16;
  163502. }
  163503. temp2 = temp;
  163504. if (temp < 0) {
  163505. temp = -temp; /* temp is abs value of input */
  163506. /* This code assumes we are on a two's complement machine */
  163507. temp2--;
  163508. }
  163509. /* Find the number of bits needed for the magnitude of the coefficient */
  163510. nbits = 1; /* there must be at least one 1 bit */
  163511. while ((temp >>= 1))
  163512. nbits++;
  163513. /* Check for out-of-range coefficient values */
  163514. if (nbits > MAX_COEF_BITS)
  163515. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163516. /* Emit Huffman symbol for run length / number of bits */
  163517. i = (r << 4) + nbits;
  163518. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  163519. return FALSE;
  163520. /* Emit that number of bits of the value, if positive, */
  163521. /* or the complement of its magnitude, if negative. */
  163522. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163523. return FALSE;
  163524. r = 0;
  163525. }
  163526. }
  163527. /* If the last coef(s) were zero, emit an end-of-block code */
  163528. if (r > 0)
  163529. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  163530. return FALSE;
  163531. return TRUE;
  163532. }
  163533. /*
  163534. * Emit a restart marker & resynchronize predictions.
  163535. */
  163536. LOCAL(boolean)
  163537. emit_restart (working_state * state, int restart_num)
  163538. {
  163539. int ci;
  163540. if (! flush_bits(state))
  163541. return FALSE;
  163542. emit_byte(state, 0xFF, return FALSE);
  163543. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  163544. /* Re-initialize DC predictions to 0 */
  163545. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  163546. state->cur.last_dc_val[ci] = 0;
  163547. /* The restart counter is not updated until we successfully write the MCU. */
  163548. return TRUE;
  163549. }
  163550. /*
  163551. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  163552. */
  163553. METHODDEF(boolean)
  163554. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163555. {
  163556. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163557. working_state state;
  163558. int blkn, ci;
  163559. jpeg_component_info * compptr;
  163560. /* Load up working state */
  163561. state.next_output_byte = cinfo->dest->next_output_byte;
  163562. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163563. ASSIGN_STATE(state.cur, entropy->saved);
  163564. state.cinfo = cinfo;
  163565. /* Emit restart marker if needed */
  163566. if (cinfo->restart_interval) {
  163567. if (entropy->restarts_to_go == 0)
  163568. if (! emit_restart(&state, entropy->next_restart_num))
  163569. return FALSE;
  163570. }
  163571. /* Encode the MCU data blocks */
  163572. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163573. ci = cinfo->MCU_membership[blkn];
  163574. compptr = cinfo->cur_comp_info[ci];
  163575. if (! encode_one_block(&state,
  163576. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  163577. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  163578. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  163579. return FALSE;
  163580. /* Update last_dc_val */
  163581. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  163582. }
  163583. /* Completed MCU, so update state */
  163584. cinfo->dest->next_output_byte = state.next_output_byte;
  163585. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163586. ASSIGN_STATE(entropy->saved, state.cur);
  163587. /* Update restart-interval state too */
  163588. if (cinfo->restart_interval) {
  163589. if (entropy->restarts_to_go == 0) {
  163590. entropy->restarts_to_go = cinfo->restart_interval;
  163591. entropy->next_restart_num++;
  163592. entropy->next_restart_num &= 7;
  163593. }
  163594. entropy->restarts_to_go--;
  163595. }
  163596. return TRUE;
  163597. }
  163598. /*
  163599. * Finish up at the end of a Huffman-compressed scan.
  163600. */
  163601. METHODDEF(void)
  163602. finish_pass_huff (j_compress_ptr cinfo)
  163603. {
  163604. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163605. working_state state;
  163606. /* Load up working state ... flush_bits needs it */
  163607. state.next_output_byte = cinfo->dest->next_output_byte;
  163608. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163609. ASSIGN_STATE(state.cur, entropy->saved);
  163610. state.cinfo = cinfo;
  163611. /* Flush out the last data */
  163612. if (! flush_bits(&state))
  163613. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  163614. /* Update state */
  163615. cinfo->dest->next_output_byte = state.next_output_byte;
  163616. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163617. ASSIGN_STATE(entropy->saved, state.cur);
  163618. }
  163619. /*
  163620. * Huffman coding optimization.
  163621. *
  163622. * We first scan the supplied data and count the number of uses of each symbol
  163623. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  163624. * Then we build a Huffman coding tree for the observed counts.
  163625. * Symbols which are not needed at all for the particular image are not
  163626. * assigned any code, which saves space in the DHT marker as well as in
  163627. * the compressed data.
  163628. */
  163629. #ifdef ENTROPY_OPT_SUPPORTED
  163630. /* Process a single block's worth of coefficients */
  163631. LOCAL(void)
  163632. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  163633. long dc_counts[], long ac_counts[])
  163634. {
  163635. register int temp;
  163636. register int nbits;
  163637. register int k, r;
  163638. /* Encode the DC coefficient difference per section F.1.2.1 */
  163639. temp = block[0] - last_dc_val;
  163640. if (temp < 0)
  163641. temp = -temp;
  163642. /* Find the number of bits needed for the magnitude of the coefficient */
  163643. nbits = 0;
  163644. while (temp) {
  163645. nbits++;
  163646. temp >>= 1;
  163647. }
  163648. /* Check for out-of-range coefficient values.
  163649. * Since we're encoding a difference, the range limit is twice as much.
  163650. */
  163651. if (nbits > MAX_COEF_BITS+1)
  163652. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163653. /* Count the Huffman symbol for the number of bits */
  163654. dc_counts[nbits]++;
  163655. /* Encode the AC coefficients per section F.1.2.2 */
  163656. r = 0; /* r = run length of zeros */
  163657. for (k = 1; k < DCTSIZE2; k++) {
  163658. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163659. r++;
  163660. } else {
  163661. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163662. while (r > 15) {
  163663. ac_counts[0xF0]++;
  163664. r -= 16;
  163665. }
  163666. /* Find the number of bits needed for the magnitude of the coefficient */
  163667. if (temp < 0)
  163668. temp = -temp;
  163669. /* Find the number of bits needed for the magnitude of the coefficient */
  163670. nbits = 1; /* there must be at least one 1 bit */
  163671. while ((temp >>= 1))
  163672. nbits++;
  163673. /* Check for out-of-range coefficient values */
  163674. if (nbits > MAX_COEF_BITS)
  163675. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163676. /* Count Huffman symbol for run length / number of bits */
  163677. ac_counts[(r << 4) + nbits]++;
  163678. r = 0;
  163679. }
  163680. }
  163681. /* If the last coef(s) were zero, emit an end-of-block code */
  163682. if (r > 0)
  163683. ac_counts[0]++;
  163684. }
  163685. /*
  163686. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  163687. * No data is actually output, so no suspension return is possible.
  163688. */
  163689. METHODDEF(boolean)
  163690. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163691. {
  163692. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163693. int blkn, ci;
  163694. jpeg_component_info * compptr;
  163695. /* Take care of restart intervals if needed */
  163696. if (cinfo->restart_interval) {
  163697. if (entropy->restarts_to_go == 0) {
  163698. /* Re-initialize DC predictions to 0 */
  163699. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  163700. entropy->saved.last_dc_val[ci] = 0;
  163701. /* Update restart state */
  163702. entropy->restarts_to_go = cinfo->restart_interval;
  163703. }
  163704. entropy->restarts_to_go--;
  163705. }
  163706. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163707. ci = cinfo->MCU_membership[blkn];
  163708. compptr = cinfo->cur_comp_info[ci];
  163709. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  163710. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  163711. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  163712. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  163713. }
  163714. return TRUE;
  163715. }
  163716. /*
  163717. * Generate the best Huffman code table for the given counts, fill htbl.
  163718. * Note this is also used by jcphuff.c.
  163719. *
  163720. * The JPEG standard requires that no symbol be assigned a codeword of all
  163721. * one bits (so that padding bits added at the end of a compressed segment
  163722. * can't look like a valid code). Because of the canonical ordering of
  163723. * codewords, this just means that there must be an unused slot in the
  163724. * longest codeword length category. Section K.2 of the JPEG spec suggests
  163725. * reserving such a slot by pretending that symbol 256 is a valid symbol
  163726. * with count 1. In theory that's not optimal; giving it count zero but
  163727. * including it in the symbol set anyway should give a better Huffman code.
  163728. * But the theoretically better code actually seems to come out worse in
  163729. * practice, because it produces more all-ones bytes (which incur stuffed
  163730. * zero bytes in the final file). In any case the difference is tiny.
  163731. *
  163732. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  163733. * If some symbols have a very small but nonzero probability, the Huffman tree
  163734. * must be adjusted to meet the code length restriction. We currently use
  163735. * the adjustment method suggested in JPEG section K.2. This method is *not*
  163736. * optimal; it may not choose the best possible limited-length code. But
  163737. * typically only very-low-frequency symbols will be given less-than-optimal
  163738. * lengths, so the code is almost optimal. Experimental comparisons against
  163739. * an optimal limited-length-code algorithm indicate that the difference is
  163740. * microscopic --- usually less than a hundredth of a percent of total size.
  163741. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  163742. */
  163743. GLOBAL(void)
  163744. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  163745. {
  163746. #define MAX_CLEN 32 /* assumed maximum initial code length */
  163747. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  163748. int codesize[257]; /* codesize[k] = code length of symbol k */
  163749. int others[257]; /* next symbol in current branch of tree */
  163750. int c1, c2;
  163751. int p, i, j;
  163752. long v;
  163753. /* This algorithm is explained in section K.2 of the JPEG standard */
  163754. MEMZERO(bits, SIZEOF(bits));
  163755. MEMZERO(codesize, SIZEOF(codesize));
  163756. for (i = 0; i < 257; i++)
  163757. others[i] = -1; /* init links to empty */
  163758. freq[256] = 1; /* make sure 256 has a nonzero count */
  163759. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  163760. * that no real symbol is given code-value of all ones, because 256
  163761. * will be placed last in the largest codeword category.
  163762. */
  163763. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  163764. for (;;) {
  163765. /* Find the smallest nonzero frequency, set c1 = its symbol */
  163766. /* In case of ties, take the larger symbol number */
  163767. c1 = -1;
  163768. v = 1000000000L;
  163769. for (i = 0; i <= 256; i++) {
  163770. if (freq[i] && freq[i] <= v) {
  163771. v = freq[i];
  163772. c1 = i;
  163773. }
  163774. }
  163775. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  163776. /* In case of ties, take the larger symbol number */
  163777. c2 = -1;
  163778. v = 1000000000L;
  163779. for (i = 0; i <= 256; i++) {
  163780. if (freq[i] && freq[i] <= v && i != c1) {
  163781. v = freq[i];
  163782. c2 = i;
  163783. }
  163784. }
  163785. /* Done if we've merged everything into one frequency */
  163786. if (c2 < 0)
  163787. break;
  163788. /* Else merge the two counts/trees */
  163789. freq[c1] += freq[c2];
  163790. freq[c2] = 0;
  163791. /* Increment the codesize of everything in c1's tree branch */
  163792. codesize[c1]++;
  163793. while (others[c1] >= 0) {
  163794. c1 = others[c1];
  163795. codesize[c1]++;
  163796. }
  163797. others[c1] = c2; /* chain c2 onto c1's tree branch */
  163798. /* Increment the codesize of everything in c2's tree branch */
  163799. codesize[c2]++;
  163800. while (others[c2] >= 0) {
  163801. c2 = others[c2];
  163802. codesize[c2]++;
  163803. }
  163804. }
  163805. /* Now count the number of symbols of each code length */
  163806. for (i = 0; i <= 256; i++) {
  163807. if (codesize[i]) {
  163808. /* The JPEG standard seems to think that this can't happen, */
  163809. /* but I'm paranoid... */
  163810. if (codesize[i] > MAX_CLEN)
  163811. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  163812. bits[codesize[i]]++;
  163813. }
  163814. }
  163815. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  163816. * Huffman procedure assigned any such lengths, we must adjust the coding.
  163817. * Here is what the JPEG spec says about how this next bit works:
  163818. * Since symbols are paired for the longest Huffman code, the symbols are
  163819. * removed from this length category two at a time. The prefix for the pair
  163820. * (which is one bit shorter) is allocated to one of the pair; then,
  163821. * skipping the BITS entry for that prefix length, a code word from the next
  163822. * shortest nonzero BITS entry is converted into a prefix for two code words
  163823. * one bit longer.
  163824. */
  163825. for (i = MAX_CLEN; i > 16; i--) {
  163826. while (bits[i] > 0) {
  163827. j = i - 2; /* find length of new prefix to be used */
  163828. while (bits[j] == 0)
  163829. j--;
  163830. bits[i] -= 2; /* remove two symbols */
  163831. bits[i-1]++; /* one goes in this length */
  163832. bits[j+1] += 2; /* two new symbols in this length */
  163833. bits[j]--; /* symbol of this length is now a prefix */
  163834. }
  163835. }
  163836. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  163837. while (bits[i] == 0) /* find largest codelength still in use */
  163838. i--;
  163839. bits[i]--;
  163840. /* Return final symbol counts (only for lengths 0..16) */
  163841. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  163842. /* Return a list of the symbols sorted by code length */
  163843. /* It's not real clear to me why we don't need to consider the codelength
  163844. * changes made above, but the JPEG spec seems to think this works.
  163845. */
  163846. p = 0;
  163847. for (i = 1; i <= MAX_CLEN; i++) {
  163848. for (j = 0; j <= 255; j++) {
  163849. if (codesize[j] == i) {
  163850. htbl->huffval[p] = (UINT8) j;
  163851. p++;
  163852. }
  163853. }
  163854. }
  163855. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  163856. htbl->sent_table = FALSE;
  163857. }
  163858. /*
  163859. * Finish up a statistics-gathering pass and create the new Huffman tables.
  163860. */
  163861. METHODDEF(void)
  163862. finish_pass_gather (j_compress_ptr cinfo)
  163863. {
  163864. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163865. int ci, dctbl, actbl;
  163866. jpeg_component_info * compptr;
  163867. JHUFF_TBL **htblptr;
  163868. boolean did_dc[NUM_HUFF_TBLS];
  163869. boolean did_ac[NUM_HUFF_TBLS];
  163870. /* It's important not to apply jpeg_gen_optimal_table more than once
  163871. * per table, because it clobbers the input frequency counts!
  163872. */
  163873. MEMZERO(did_dc, SIZEOF(did_dc));
  163874. MEMZERO(did_ac, SIZEOF(did_ac));
  163875. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163876. compptr = cinfo->cur_comp_info[ci];
  163877. dctbl = compptr->dc_tbl_no;
  163878. actbl = compptr->ac_tbl_no;
  163879. if (! did_dc[dctbl]) {
  163880. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  163881. if (*htblptr == NULL)
  163882. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163883. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  163884. did_dc[dctbl] = TRUE;
  163885. }
  163886. if (! did_ac[actbl]) {
  163887. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  163888. if (*htblptr == NULL)
  163889. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  163890. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  163891. did_ac[actbl] = TRUE;
  163892. }
  163893. }
  163894. }
  163895. #endif /* ENTROPY_OPT_SUPPORTED */
  163896. /*
  163897. * Module initialization routine for Huffman entropy encoding.
  163898. */
  163899. GLOBAL(void)
  163900. jinit_huff_encoder (j_compress_ptr cinfo)
  163901. {
  163902. huff_entropy_ptr entropy;
  163903. int i;
  163904. entropy = (huff_entropy_ptr)
  163905. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163906. SIZEOF(huff_entropy_encoder));
  163907. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  163908. entropy->pub.start_pass = start_pass_huff;
  163909. /* Mark tables unallocated */
  163910. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  163911. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  163912. #ifdef ENTROPY_OPT_SUPPORTED
  163913. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  163914. #endif
  163915. }
  163916. }
  163917. /*** End of inlined file: jchuff.c ***/
  163918. #undef emit_byte
  163919. /*** Start of inlined file: jcinit.c ***/
  163920. #define JPEG_INTERNALS
  163921. /*
  163922. * Master selection of compression modules.
  163923. * This is done once at the start of processing an image. We determine
  163924. * which modules will be used and give them appropriate initialization calls.
  163925. */
  163926. GLOBAL(void)
  163927. jinit_compress_master (j_compress_ptr cinfo)
  163928. {
  163929. /* Initialize master control (includes parameter checking/processing) */
  163930. jinit_c_master_control(cinfo, FALSE /* full compression */);
  163931. /* Preprocessing */
  163932. if (! cinfo->raw_data_in) {
  163933. jinit_color_converter(cinfo);
  163934. jinit_downsampler(cinfo);
  163935. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  163936. }
  163937. /* Forward DCT */
  163938. jinit_forward_dct(cinfo);
  163939. /* Entropy encoding: either Huffman or arithmetic coding. */
  163940. if (cinfo->arith_code) {
  163941. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  163942. } else {
  163943. if (cinfo->progressive_mode) {
  163944. #ifdef C_PROGRESSIVE_SUPPORTED
  163945. jinit_phuff_encoder(cinfo);
  163946. #else
  163947. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163948. #endif
  163949. } else
  163950. jinit_huff_encoder(cinfo);
  163951. }
  163952. /* Need a full-image coefficient buffer in any multi-pass mode. */
  163953. jinit_c_coef_controller(cinfo,
  163954. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  163955. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  163956. jinit_marker_writer(cinfo);
  163957. /* We can now tell the memory manager to allocate virtual arrays. */
  163958. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  163959. /* Write the datastream header (SOI) immediately.
  163960. * Frame and scan headers are postponed till later.
  163961. * This lets application insert special markers after the SOI.
  163962. */
  163963. (*cinfo->marker->write_file_header) (cinfo);
  163964. }
  163965. /*** End of inlined file: jcinit.c ***/
  163966. /*** Start of inlined file: jcmainct.c ***/
  163967. #define JPEG_INTERNALS
  163968. /* Note: currently, there is no operating mode in which a full-image buffer
  163969. * is needed at this step. If there were, that mode could not be used with
  163970. * "raw data" input, since this module is bypassed in that case. However,
  163971. * we've left the code here for possible use in special applications.
  163972. */
  163973. #undef FULL_MAIN_BUFFER_SUPPORTED
  163974. /* Private buffer controller object */
  163975. typedef struct {
  163976. struct jpeg_c_main_controller pub; /* public fields */
  163977. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  163978. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  163979. boolean suspended; /* remember if we suspended output */
  163980. J_BUF_MODE pass_mode; /* current operating mode */
  163981. /* If using just a strip buffer, this points to the entire set of buffers
  163982. * (we allocate one for each component). In the full-image case, this
  163983. * points to the currently accessible strips of the virtual arrays.
  163984. */
  163985. JSAMPARRAY buffer[MAX_COMPONENTS];
  163986. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163987. /* If using full-image storage, this array holds pointers to virtual-array
  163988. * control blocks for each component. Unused if not full-image storage.
  163989. */
  163990. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  163991. #endif
  163992. } my_main_controller;
  163993. typedef my_main_controller * my_main_ptr;
  163994. /* Forward declarations */
  163995. METHODDEF(void) process_data_simple_main
  163996. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  163997. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  163998. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  163999. METHODDEF(void) process_data_buffer_main
  164000. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  164001. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  164002. #endif
  164003. /*
  164004. * Initialize for a processing pass.
  164005. */
  164006. METHODDEF(void)
  164007. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  164008. {
  164009. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  164010. /* Do nothing in raw-data mode. */
  164011. if (cinfo->raw_data_in)
  164012. return;
  164013. main_->cur_iMCU_row = 0; /* initialize counters */
  164014. main_->rowgroup_ctr = 0;
  164015. main_->suspended = FALSE;
  164016. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  164017. switch (pass_mode) {
  164018. case JBUF_PASS_THRU:
  164019. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164020. if (main_->whole_image[0] != NULL)
  164021. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164022. #endif
  164023. main_->pub.process_data = process_data_simple_main;
  164024. break;
  164025. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164026. case JBUF_SAVE_SOURCE:
  164027. case JBUF_CRANK_DEST:
  164028. case JBUF_SAVE_AND_PASS:
  164029. if (main_->whole_image[0] == NULL)
  164030. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164031. main_->pub.process_data = process_data_buffer_main;
  164032. break;
  164033. #endif
  164034. default:
  164035. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164036. break;
  164037. }
  164038. }
  164039. /*
  164040. * Process some data.
  164041. * This routine handles the simple pass-through mode,
  164042. * where we have only a strip buffer.
  164043. */
  164044. METHODDEF(void)
  164045. process_data_simple_main (j_compress_ptr cinfo,
  164046. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  164047. JDIMENSION in_rows_avail)
  164048. {
  164049. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  164050. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  164051. /* Read input data if we haven't filled the main buffer yet */
  164052. if (main_->rowgroup_ctr < DCTSIZE)
  164053. (*cinfo->prep->pre_process_data) (cinfo,
  164054. input_buf, in_row_ctr, in_rows_avail,
  164055. main_->buffer, &main_->rowgroup_ctr,
  164056. (JDIMENSION) DCTSIZE);
  164057. /* If we don't have a full iMCU row buffered, return to application for
  164058. * more data. Note that preprocessor will always pad to fill the iMCU row
  164059. * at the bottom of the image.
  164060. */
  164061. if (main_->rowgroup_ctr != DCTSIZE)
  164062. return;
  164063. /* Send the completed row to the compressor */
  164064. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  164065. /* If compressor did not consume the whole row, then we must need to
  164066. * suspend processing and return to the application. In this situation
  164067. * we pretend we didn't yet consume the last input row; otherwise, if
  164068. * it happened to be the last row of the image, the application would
  164069. * think we were done.
  164070. */
  164071. if (! main_->suspended) {
  164072. (*in_row_ctr)--;
  164073. main_->suspended = TRUE;
  164074. }
  164075. return;
  164076. }
  164077. /* We did finish the row. Undo our little suspension hack if a previous
  164078. * call suspended; then mark the main buffer empty.
  164079. */
  164080. if (main_->suspended) {
  164081. (*in_row_ctr)++;
  164082. main_->suspended = FALSE;
  164083. }
  164084. main_->rowgroup_ctr = 0;
  164085. main_->cur_iMCU_row++;
  164086. }
  164087. }
  164088. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164089. /*
  164090. * Process some data.
  164091. * This routine handles all of the modes that use a full-size buffer.
  164092. */
  164093. METHODDEF(void)
  164094. process_data_buffer_main (j_compress_ptr cinfo,
  164095. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  164096. JDIMENSION in_rows_avail)
  164097. {
  164098. my_main_ptr main = (my_main_ptr) cinfo->main;
  164099. int ci;
  164100. jpeg_component_info *compptr;
  164101. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  164102. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  164103. /* Realign the virtual buffers if at the start of an iMCU row. */
  164104. if (main->rowgroup_ctr == 0) {
  164105. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164106. ci++, compptr++) {
  164107. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  164108. ((j_common_ptr) cinfo, main->whole_image[ci],
  164109. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  164110. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  164111. }
  164112. /* In a read pass, pretend we just read some source data. */
  164113. if (! writing) {
  164114. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  164115. main->rowgroup_ctr = DCTSIZE;
  164116. }
  164117. }
  164118. /* If a write pass, read input data until the current iMCU row is full. */
  164119. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  164120. if (writing) {
  164121. (*cinfo->prep->pre_process_data) (cinfo,
  164122. input_buf, in_row_ctr, in_rows_avail,
  164123. main->buffer, &main->rowgroup_ctr,
  164124. (JDIMENSION) DCTSIZE);
  164125. /* Return to application if we need more data to fill the iMCU row. */
  164126. if (main->rowgroup_ctr < DCTSIZE)
  164127. return;
  164128. }
  164129. /* Emit data, unless this is a sink-only pass. */
  164130. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  164131. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  164132. /* If compressor did not consume the whole row, then we must need to
  164133. * suspend processing and return to the application. In this situation
  164134. * we pretend we didn't yet consume the last input row; otherwise, if
  164135. * it happened to be the last row of the image, the application would
  164136. * think we were done.
  164137. */
  164138. if (! main->suspended) {
  164139. (*in_row_ctr)--;
  164140. main->suspended = TRUE;
  164141. }
  164142. return;
  164143. }
  164144. /* We did finish the row. Undo our little suspension hack if a previous
  164145. * call suspended; then mark the main buffer empty.
  164146. */
  164147. if (main->suspended) {
  164148. (*in_row_ctr)++;
  164149. main->suspended = FALSE;
  164150. }
  164151. }
  164152. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  164153. main->rowgroup_ctr = 0;
  164154. main->cur_iMCU_row++;
  164155. }
  164156. }
  164157. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  164158. /*
  164159. * Initialize main buffer controller.
  164160. */
  164161. GLOBAL(void)
  164162. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  164163. {
  164164. my_main_ptr main_;
  164165. int ci;
  164166. jpeg_component_info *compptr;
  164167. main_ = (my_main_ptr)
  164168. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164169. SIZEOF(my_main_controller));
  164170. cinfo->main = (struct jpeg_c_main_controller *) main_;
  164171. main_->pub.start_pass = start_pass_main;
  164172. /* We don't need to create a buffer in raw-data mode. */
  164173. if (cinfo->raw_data_in)
  164174. return;
  164175. /* Create the buffer. It holds downsampled data, so each component
  164176. * may be of a different size.
  164177. */
  164178. if (need_full_buffer) {
  164179. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164180. /* Allocate a full-image virtual array for each component */
  164181. /* Note we pad the bottom to a multiple of the iMCU height */
  164182. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164183. ci++, compptr++) {
  164184. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  164185. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  164186. compptr->width_in_blocks * DCTSIZE,
  164187. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  164188. (long) compptr->v_samp_factor) * DCTSIZE,
  164189. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  164190. }
  164191. #else
  164192. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164193. #endif
  164194. } else {
  164195. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164196. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  164197. #endif
  164198. /* Allocate a strip buffer for each component */
  164199. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164200. ci++, compptr++) {
  164201. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  164202. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164203. compptr->width_in_blocks * DCTSIZE,
  164204. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  164205. }
  164206. }
  164207. }
  164208. /*** End of inlined file: jcmainct.c ***/
  164209. /*** Start of inlined file: jcmarker.c ***/
  164210. #define JPEG_INTERNALS
  164211. /* Private state */
  164212. typedef struct {
  164213. struct jpeg_marker_writer pub; /* public fields */
  164214. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  164215. } my_marker_writer;
  164216. typedef my_marker_writer * my_marker_ptr;
  164217. /*
  164218. * Basic output routines.
  164219. *
  164220. * Note that we do not support suspension while writing a marker.
  164221. * Therefore, an application using suspension must ensure that there is
  164222. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  164223. * calling jpeg_start_compress, and enough space to write the trailing EOI
  164224. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  164225. * modes are not supported at all with suspension, so those two are the only
  164226. * points where markers will be written.
  164227. */
  164228. LOCAL(void)
  164229. emit_byte (j_compress_ptr cinfo, int val)
  164230. /* Emit a byte */
  164231. {
  164232. struct jpeg_destination_mgr * dest = cinfo->dest;
  164233. *(dest->next_output_byte)++ = (JOCTET) val;
  164234. if (--dest->free_in_buffer == 0) {
  164235. if (! (*dest->empty_output_buffer) (cinfo))
  164236. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  164237. }
  164238. }
  164239. LOCAL(void)
  164240. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  164241. /* Emit a marker code */
  164242. {
  164243. emit_byte(cinfo, 0xFF);
  164244. emit_byte(cinfo, (int) mark);
  164245. }
  164246. LOCAL(void)
  164247. emit_2bytes (j_compress_ptr cinfo, int value)
  164248. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  164249. {
  164250. emit_byte(cinfo, (value >> 8) & 0xFF);
  164251. emit_byte(cinfo, value & 0xFF);
  164252. }
  164253. /*
  164254. * Routines to write specific marker types.
  164255. */
  164256. LOCAL(int)
  164257. emit_dqt (j_compress_ptr cinfo, int index)
  164258. /* Emit a DQT marker */
  164259. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  164260. {
  164261. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  164262. int prec;
  164263. int i;
  164264. if (qtbl == NULL)
  164265. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  164266. prec = 0;
  164267. for (i = 0; i < DCTSIZE2; i++) {
  164268. if (qtbl->quantval[i] > 255)
  164269. prec = 1;
  164270. }
  164271. if (! qtbl->sent_table) {
  164272. emit_marker(cinfo, M_DQT);
  164273. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  164274. emit_byte(cinfo, index + (prec<<4));
  164275. for (i = 0; i < DCTSIZE2; i++) {
  164276. /* The table entries must be emitted in zigzag order. */
  164277. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  164278. if (prec)
  164279. emit_byte(cinfo, (int) (qval >> 8));
  164280. emit_byte(cinfo, (int) (qval & 0xFF));
  164281. }
  164282. qtbl->sent_table = TRUE;
  164283. }
  164284. return prec;
  164285. }
  164286. LOCAL(void)
  164287. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  164288. /* Emit a DHT marker */
  164289. {
  164290. JHUFF_TBL * htbl;
  164291. int length, i;
  164292. if (is_ac) {
  164293. htbl = cinfo->ac_huff_tbl_ptrs[index];
  164294. index += 0x10; /* output index has AC bit set */
  164295. } else {
  164296. htbl = cinfo->dc_huff_tbl_ptrs[index];
  164297. }
  164298. if (htbl == NULL)
  164299. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  164300. if (! htbl->sent_table) {
  164301. emit_marker(cinfo, M_DHT);
  164302. length = 0;
  164303. for (i = 1; i <= 16; i++)
  164304. length += htbl->bits[i];
  164305. emit_2bytes(cinfo, length + 2 + 1 + 16);
  164306. emit_byte(cinfo, index);
  164307. for (i = 1; i <= 16; i++)
  164308. emit_byte(cinfo, htbl->bits[i]);
  164309. for (i = 0; i < length; i++)
  164310. emit_byte(cinfo, htbl->huffval[i]);
  164311. htbl->sent_table = TRUE;
  164312. }
  164313. }
  164314. LOCAL(void)
  164315. emit_dac (j_compress_ptr)
  164316. /* Emit a DAC marker */
  164317. /* Since the useful info is so small, we want to emit all the tables in */
  164318. /* one DAC marker. Therefore this routine does its own scan of the table. */
  164319. {
  164320. #ifdef C_ARITH_CODING_SUPPORTED
  164321. char dc_in_use[NUM_ARITH_TBLS];
  164322. char ac_in_use[NUM_ARITH_TBLS];
  164323. int length, i;
  164324. jpeg_component_info *compptr;
  164325. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164326. dc_in_use[i] = ac_in_use[i] = 0;
  164327. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164328. compptr = cinfo->cur_comp_info[i];
  164329. dc_in_use[compptr->dc_tbl_no] = 1;
  164330. ac_in_use[compptr->ac_tbl_no] = 1;
  164331. }
  164332. length = 0;
  164333. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164334. length += dc_in_use[i] + ac_in_use[i];
  164335. emit_marker(cinfo, M_DAC);
  164336. emit_2bytes(cinfo, length*2 + 2);
  164337. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  164338. if (dc_in_use[i]) {
  164339. emit_byte(cinfo, i);
  164340. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  164341. }
  164342. if (ac_in_use[i]) {
  164343. emit_byte(cinfo, i + 0x10);
  164344. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  164345. }
  164346. }
  164347. #endif /* C_ARITH_CODING_SUPPORTED */
  164348. }
  164349. LOCAL(void)
  164350. emit_dri (j_compress_ptr cinfo)
  164351. /* Emit a DRI marker */
  164352. {
  164353. emit_marker(cinfo, M_DRI);
  164354. emit_2bytes(cinfo, 4); /* fixed length */
  164355. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  164356. }
  164357. LOCAL(void)
  164358. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  164359. /* Emit a SOF marker */
  164360. {
  164361. int ci;
  164362. jpeg_component_info *compptr;
  164363. emit_marker(cinfo, code);
  164364. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  164365. /* Make sure image isn't bigger than SOF field can handle */
  164366. if ((long) cinfo->image_height > 65535L ||
  164367. (long) cinfo->image_width > 65535L)
  164368. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  164369. emit_byte(cinfo, cinfo->data_precision);
  164370. emit_2bytes(cinfo, (int) cinfo->image_height);
  164371. emit_2bytes(cinfo, (int) cinfo->image_width);
  164372. emit_byte(cinfo, cinfo->num_components);
  164373. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164374. ci++, compptr++) {
  164375. emit_byte(cinfo, compptr->component_id);
  164376. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  164377. emit_byte(cinfo, compptr->quant_tbl_no);
  164378. }
  164379. }
  164380. LOCAL(void)
  164381. emit_sos (j_compress_ptr cinfo)
  164382. /* Emit a SOS marker */
  164383. {
  164384. int i, td, ta;
  164385. jpeg_component_info *compptr;
  164386. emit_marker(cinfo, M_SOS);
  164387. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  164388. emit_byte(cinfo, cinfo->comps_in_scan);
  164389. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164390. compptr = cinfo->cur_comp_info[i];
  164391. emit_byte(cinfo, compptr->component_id);
  164392. td = compptr->dc_tbl_no;
  164393. ta = compptr->ac_tbl_no;
  164394. if (cinfo->progressive_mode) {
  164395. /* Progressive mode: only DC or only AC tables are used in one scan;
  164396. * furthermore, Huffman coding of DC refinement uses no table at all.
  164397. * We emit 0 for unused field(s); this is recommended by the P&M text
  164398. * but does not seem to be specified in the standard.
  164399. */
  164400. if (cinfo->Ss == 0) {
  164401. ta = 0; /* DC scan */
  164402. if (cinfo->Ah != 0 && !cinfo->arith_code)
  164403. td = 0; /* no DC table either */
  164404. } else {
  164405. td = 0; /* AC scan */
  164406. }
  164407. }
  164408. emit_byte(cinfo, (td << 4) + ta);
  164409. }
  164410. emit_byte(cinfo, cinfo->Ss);
  164411. emit_byte(cinfo, cinfo->Se);
  164412. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  164413. }
  164414. LOCAL(void)
  164415. emit_jfif_app0 (j_compress_ptr cinfo)
  164416. /* Emit a JFIF-compliant APP0 marker */
  164417. {
  164418. /*
  164419. * Length of APP0 block (2 bytes)
  164420. * Block ID (4 bytes - ASCII "JFIF")
  164421. * Zero byte (1 byte to terminate the ID string)
  164422. * Version Major, Minor (2 bytes - major first)
  164423. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  164424. * Xdpu (2 bytes - dots per unit horizontal)
  164425. * Ydpu (2 bytes - dots per unit vertical)
  164426. * Thumbnail X size (1 byte)
  164427. * Thumbnail Y size (1 byte)
  164428. */
  164429. emit_marker(cinfo, M_APP0);
  164430. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  164431. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  164432. emit_byte(cinfo, 0x46);
  164433. emit_byte(cinfo, 0x49);
  164434. emit_byte(cinfo, 0x46);
  164435. emit_byte(cinfo, 0);
  164436. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  164437. emit_byte(cinfo, cinfo->JFIF_minor_version);
  164438. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  164439. emit_2bytes(cinfo, (int) cinfo->X_density);
  164440. emit_2bytes(cinfo, (int) cinfo->Y_density);
  164441. emit_byte(cinfo, 0); /* No thumbnail image */
  164442. emit_byte(cinfo, 0);
  164443. }
  164444. LOCAL(void)
  164445. emit_adobe_app14 (j_compress_ptr cinfo)
  164446. /* Emit an Adobe APP14 marker */
  164447. {
  164448. /*
  164449. * Length of APP14 block (2 bytes)
  164450. * Block ID (5 bytes - ASCII "Adobe")
  164451. * Version Number (2 bytes - currently 100)
  164452. * Flags0 (2 bytes - currently 0)
  164453. * Flags1 (2 bytes - currently 0)
  164454. * Color transform (1 byte)
  164455. *
  164456. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  164457. * now in circulation seem to use Version = 100, so that's what we write.
  164458. *
  164459. * We write the color transform byte as 1 if the JPEG color space is
  164460. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  164461. * whether the encoder performed a transformation, which is pretty useless.
  164462. */
  164463. emit_marker(cinfo, M_APP14);
  164464. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  164465. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  164466. emit_byte(cinfo, 0x64);
  164467. emit_byte(cinfo, 0x6F);
  164468. emit_byte(cinfo, 0x62);
  164469. emit_byte(cinfo, 0x65);
  164470. emit_2bytes(cinfo, 100); /* Version */
  164471. emit_2bytes(cinfo, 0); /* Flags0 */
  164472. emit_2bytes(cinfo, 0); /* Flags1 */
  164473. switch (cinfo->jpeg_color_space) {
  164474. case JCS_YCbCr:
  164475. emit_byte(cinfo, 1); /* Color transform = 1 */
  164476. break;
  164477. case JCS_YCCK:
  164478. emit_byte(cinfo, 2); /* Color transform = 2 */
  164479. break;
  164480. default:
  164481. emit_byte(cinfo, 0); /* Color transform = 0 */
  164482. break;
  164483. }
  164484. }
  164485. /*
  164486. * These routines allow writing an arbitrary marker with parameters.
  164487. * The only intended use is to emit COM or APPn markers after calling
  164488. * write_file_header and before calling write_frame_header.
  164489. * Other uses are not guaranteed to produce desirable results.
  164490. * Counting the parameter bytes properly is the caller's responsibility.
  164491. */
  164492. METHODDEF(void)
  164493. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  164494. /* Emit an arbitrary marker header */
  164495. {
  164496. if (datalen > (unsigned int) 65533) /* safety check */
  164497. ERREXIT(cinfo, JERR_BAD_LENGTH);
  164498. emit_marker(cinfo, (JPEG_MARKER) marker);
  164499. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  164500. }
  164501. METHODDEF(void)
  164502. write_marker_byte (j_compress_ptr cinfo, int val)
  164503. /* Emit one byte of marker parameters following write_marker_header */
  164504. {
  164505. emit_byte(cinfo, val);
  164506. }
  164507. /*
  164508. * Write datastream header.
  164509. * This consists of an SOI and optional APPn markers.
  164510. * We recommend use of the JFIF marker, but not the Adobe marker,
  164511. * when using YCbCr or grayscale data. The JFIF marker should NOT
  164512. * be used for any other JPEG colorspace. The Adobe marker is helpful
  164513. * to distinguish RGB, CMYK, and YCCK colorspaces.
  164514. * Note that an application can write additional header markers after
  164515. * jpeg_start_compress returns.
  164516. */
  164517. METHODDEF(void)
  164518. write_file_header (j_compress_ptr cinfo)
  164519. {
  164520. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164521. emit_marker(cinfo, M_SOI); /* first the SOI */
  164522. /* SOI is defined to reset restart interval to 0 */
  164523. marker->last_restart_interval = 0;
  164524. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  164525. emit_jfif_app0(cinfo);
  164526. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  164527. emit_adobe_app14(cinfo);
  164528. }
  164529. /*
  164530. * Write frame header.
  164531. * This consists of DQT and SOFn markers.
  164532. * Note that we do not emit the SOF until we have emitted the DQT(s).
  164533. * This avoids compatibility problems with incorrect implementations that
  164534. * try to error-check the quant table numbers as soon as they see the SOF.
  164535. */
  164536. METHODDEF(void)
  164537. write_frame_header (j_compress_ptr cinfo)
  164538. {
  164539. int ci, prec;
  164540. boolean is_baseline;
  164541. jpeg_component_info *compptr;
  164542. /* Emit DQT for each quantization table.
  164543. * Note that emit_dqt() suppresses any duplicate tables.
  164544. */
  164545. prec = 0;
  164546. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164547. ci++, compptr++) {
  164548. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  164549. }
  164550. /* now prec is nonzero iff there are any 16-bit quant tables. */
  164551. /* Check for a non-baseline specification.
  164552. * Note we assume that Huffman table numbers won't be changed later.
  164553. */
  164554. if (cinfo->arith_code || cinfo->progressive_mode ||
  164555. cinfo->data_precision != 8) {
  164556. is_baseline = FALSE;
  164557. } else {
  164558. is_baseline = TRUE;
  164559. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164560. ci++, compptr++) {
  164561. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  164562. is_baseline = FALSE;
  164563. }
  164564. if (prec && is_baseline) {
  164565. is_baseline = FALSE;
  164566. /* If it's baseline except for quantizer size, warn the user */
  164567. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  164568. }
  164569. }
  164570. /* Emit the proper SOF marker */
  164571. if (cinfo->arith_code) {
  164572. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  164573. } else {
  164574. if (cinfo->progressive_mode)
  164575. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  164576. else if (is_baseline)
  164577. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  164578. else
  164579. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  164580. }
  164581. }
  164582. /*
  164583. * Write scan header.
  164584. * This consists of DHT or DAC markers, optional DRI, and SOS.
  164585. * Compressed data will be written following the SOS.
  164586. */
  164587. METHODDEF(void)
  164588. write_scan_header (j_compress_ptr cinfo)
  164589. {
  164590. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164591. int i;
  164592. jpeg_component_info *compptr;
  164593. if (cinfo->arith_code) {
  164594. /* Emit arith conditioning info. We may have some duplication
  164595. * if the file has multiple scans, but it's so small it's hardly
  164596. * worth worrying about.
  164597. */
  164598. emit_dac(cinfo);
  164599. } else {
  164600. /* Emit Huffman tables.
  164601. * Note that emit_dht() suppresses any duplicate tables.
  164602. */
  164603. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164604. compptr = cinfo->cur_comp_info[i];
  164605. if (cinfo->progressive_mode) {
  164606. /* Progressive mode: only DC or only AC tables are used in one scan */
  164607. if (cinfo->Ss == 0) {
  164608. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  164609. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164610. } else {
  164611. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164612. }
  164613. } else {
  164614. /* Sequential mode: need both DC and AC tables */
  164615. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164616. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164617. }
  164618. }
  164619. }
  164620. /* Emit DRI if required --- note that DRI value could change for each scan.
  164621. * We avoid wasting space with unnecessary DRIs, however.
  164622. */
  164623. if (cinfo->restart_interval != marker->last_restart_interval) {
  164624. emit_dri(cinfo);
  164625. marker->last_restart_interval = cinfo->restart_interval;
  164626. }
  164627. emit_sos(cinfo);
  164628. }
  164629. /*
  164630. * Write datastream trailer.
  164631. */
  164632. METHODDEF(void)
  164633. write_file_trailer (j_compress_ptr cinfo)
  164634. {
  164635. emit_marker(cinfo, M_EOI);
  164636. }
  164637. /*
  164638. * Write an abbreviated table-specification datastream.
  164639. * This consists of SOI, DQT and DHT tables, and EOI.
  164640. * Any table that is defined and not marked sent_table = TRUE will be
  164641. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  164642. */
  164643. METHODDEF(void)
  164644. write_tables_only (j_compress_ptr cinfo)
  164645. {
  164646. int i;
  164647. emit_marker(cinfo, M_SOI);
  164648. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  164649. if (cinfo->quant_tbl_ptrs[i] != NULL)
  164650. (void) emit_dqt(cinfo, i);
  164651. }
  164652. if (! cinfo->arith_code) {
  164653. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164654. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  164655. emit_dht(cinfo, i, FALSE);
  164656. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  164657. emit_dht(cinfo, i, TRUE);
  164658. }
  164659. }
  164660. emit_marker(cinfo, M_EOI);
  164661. }
  164662. /*
  164663. * Initialize the marker writer module.
  164664. */
  164665. GLOBAL(void)
  164666. jinit_marker_writer (j_compress_ptr cinfo)
  164667. {
  164668. my_marker_ptr marker;
  164669. /* Create the subobject */
  164670. marker = (my_marker_ptr)
  164671. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164672. SIZEOF(my_marker_writer));
  164673. cinfo->marker = (struct jpeg_marker_writer *) marker;
  164674. /* Initialize method pointers */
  164675. marker->pub.write_file_header = write_file_header;
  164676. marker->pub.write_frame_header = write_frame_header;
  164677. marker->pub.write_scan_header = write_scan_header;
  164678. marker->pub.write_file_trailer = write_file_trailer;
  164679. marker->pub.write_tables_only = write_tables_only;
  164680. marker->pub.write_marker_header = write_marker_header;
  164681. marker->pub.write_marker_byte = write_marker_byte;
  164682. /* Initialize private state */
  164683. marker->last_restart_interval = 0;
  164684. }
  164685. /*** End of inlined file: jcmarker.c ***/
  164686. /*** Start of inlined file: jcmaster.c ***/
  164687. #define JPEG_INTERNALS
  164688. /* Private state */
  164689. typedef enum {
  164690. main_pass, /* input data, also do first output step */
  164691. huff_opt_pass, /* Huffman code optimization pass */
  164692. output_pass /* data output pass */
  164693. } c_pass_type;
  164694. typedef struct {
  164695. struct jpeg_comp_master pub; /* public fields */
  164696. c_pass_type pass_type; /* the type of the current pass */
  164697. int pass_number; /* # of passes completed */
  164698. int total_passes; /* total # of passes needed */
  164699. int scan_number; /* current index in scan_info[] */
  164700. } my_comp_master;
  164701. typedef my_comp_master * my_master_ptr;
  164702. /*
  164703. * Support routines that do various essential calculations.
  164704. */
  164705. LOCAL(void)
  164706. initial_setup (j_compress_ptr cinfo)
  164707. /* Do computations that are needed before master selection phase */
  164708. {
  164709. int ci;
  164710. jpeg_component_info *compptr;
  164711. long samplesperrow;
  164712. JDIMENSION jd_samplesperrow;
  164713. /* Sanity check on image dimensions */
  164714. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  164715. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  164716. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  164717. /* Make sure image isn't bigger than I can handle */
  164718. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  164719. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  164720. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  164721. /* Width of an input scanline must be representable as JDIMENSION. */
  164722. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  164723. jd_samplesperrow = (JDIMENSION) samplesperrow;
  164724. if ((long) jd_samplesperrow != samplesperrow)
  164725. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  164726. /* For now, precision must match compiled-in value... */
  164727. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  164728. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  164729. /* Check that number of components won't exceed internal array sizes */
  164730. if (cinfo->num_components > MAX_COMPONENTS)
  164731. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164732. MAX_COMPONENTS);
  164733. /* Compute maximum sampling factors; check factor validity */
  164734. cinfo->max_h_samp_factor = 1;
  164735. cinfo->max_v_samp_factor = 1;
  164736. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164737. ci++, compptr++) {
  164738. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  164739. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  164740. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  164741. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  164742. compptr->h_samp_factor);
  164743. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  164744. compptr->v_samp_factor);
  164745. }
  164746. /* Compute dimensions of components */
  164747. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164748. ci++, compptr++) {
  164749. /* Fill in the correct component_index value; don't rely on application */
  164750. compptr->component_index = ci;
  164751. /* For compression, we never do DCT scaling. */
  164752. compptr->DCT_scaled_size = DCTSIZE;
  164753. /* Size in DCT blocks */
  164754. compptr->width_in_blocks = (JDIMENSION)
  164755. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164756. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  164757. compptr->height_in_blocks = (JDIMENSION)
  164758. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164759. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  164760. /* Size in samples */
  164761. compptr->downsampled_width = (JDIMENSION)
  164762. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164763. (long) cinfo->max_h_samp_factor);
  164764. compptr->downsampled_height = (JDIMENSION)
  164765. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164766. (long) cinfo->max_v_samp_factor);
  164767. /* Mark component needed (this flag isn't actually used for compression) */
  164768. compptr->component_needed = TRUE;
  164769. }
  164770. /* Compute number of fully interleaved MCU rows (number of times that
  164771. * main controller will call coefficient controller).
  164772. */
  164773. cinfo->total_iMCU_rows = (JDIMENSION)
  164774. jdiv_round_up((long) cinfo->image_height,
  164775. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164776. }
  164777. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164778. LOCAL(void)
  164779. validate_script (j_compress_ptr cinfo)
  164780. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  164781. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  164782. */
  164783. {
  164784. const jpeg_scan_info * scanptr;
  164785. int scanno, ncomps, ci, coefi, thisi;
  164786. int Ss, Se, Ah, Al;
  164787. boolean component_sent[MAX_COMPONENTS];
  164788. #ifdef C_PROGRESSIVE_SUPPORTED
  164789. int * last_bitpos_ptr;
  164790. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  164791. /* -1 until that coefficient has been seen; then last Al for it */
  164792. #endif
  164793. if (cinfo->num_scans <= 0)
  164794. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  164795. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  164796. * for progressive JPEG, no scan can have this.
  164797. */
  164798. scanptr = cinfo->scan_info;
  164799. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  164800. #ifdef C_PROGRESSIVE_SUPPORTED
  164801. cinfo->progressive_mode = TRUE;
  164802. last_bitpos_ptr = & last_bitpos[0][0];
  164803. for (ci = 0; ci < cinfo->num_components; ci++)
  164804. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  164805. *last_bitpos_ptr++ = -1;
  164806. #else
  164807. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164808. #endif
  164809. } else {
  164810. cinfo->progressive_mode = FALSE;
  164811. for (ci = 0; ci < cinfo->num_components; ci++)
  164812. component_sent[ci] = FALSE;
  164813. }
  164814. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  164815. /* Validate component indexes */
  164816. ncomps = scanptr->comps_in_scan;
  164817. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  164818. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  164819. for (ci = 0; ci < ncomps; ci++) {
  164820. thisi = scanptr->component_index[ci];
  164821. if (thisi < 0 || thisi >= cinfo->num_components)
  164822. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164823. /* Components must appear in SOF order within each scan */
  164824. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  164825. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164826. }
  164827. /* Validate progression parameters */
  164828. Ss = scanptr->Ss;
  164829. Se = scanptr->Se;
  164830. Ah = scanptr->Ah;
  164831. Al = scanptr->Al;
  164832. if (cinfo->progressive_mode) {
  164833. #ifdef C_PROGRESSIVE_SUPPORTED
  164834. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  164835. * seems wrong: the upper bound ought to depend on data precision.
  164836. * Perhaps they really meant 0..N+1 for N-bit precision.
  164837. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  164838. * out-of-range reconstructed DC values during the first DC scan,
  164839. * which might cause problems for some decoders.
  164840. */
  164841. #if BITS_IN_JSAMPLE == 8
  164842. #define MAX_AH_AL 10
  164843. #else
  164844. #define MAX_AH_AL 13
  164845. #endif
  164846. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  164847. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  164848. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164849. if (Ss == 0) {
  164850. if (Se != 0) /* DC and AC together not OK */
  164851. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164852. } else {
  164853. if (ncomps != 1) /* AC scans must be for only one component */
  164854. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164855. }
  164856. for (ci = 0; ci < ncomps; ci++) {
  164857. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  164858. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  164859. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164860. for (coefi = Ss; coefi <= Se; coefi++) {
  164861. if (last_bitpos_ptr[coefi] < 0) {
  164862. /* first scan of this coefficient */
  164863. if (Ah != 0)
  164864. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164865. } else {
  164866. /* not first scan */
  164867. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  164868. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164869. }
  164870. last_bitpos_ptr[coefi] = Al;
  164871. }
  164872. }
  164873. #endif
  164874. } else {
  164875. /* For sequential JPEG, all progression parameters must be these: */
  164876. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  164877. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  164878. /* Make sure components are not sent twice */
  164879. for (ci = 0; ci < ncomps; ci++) {
  164880. thisi = scanptr->component_index[ci];
  164881. if (component_sent[thisi])
  164882. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  164883. component_sent[thisi] = TRUE;
  164884. }
  164885. }
  164886. }
  164887. /* Now verify that everything got sent. */
  164888. if (cinfo->progressive_mode) {
  164889. #ifdef C_PROGRESSIVE_SUPPORTED
  164890. /* For progressive mode, we only check that at least some DC data
  164891. * got sent for each component; the spec does not require that all bits
  164892. * of all coefficients be transmitted. Would it be wiser to enforce
  164893. * transmission of all coefficient bits??
  164894. */
  164895. for (ci = 0; ci < cinfo->num_components; ci++) {
  164896. if (last_bitpos[ci][0] < 0)
  164897. ERREXIT(cinfo, JERR_MISSING_DATA);
  164898. }
  164899. #endif
  164900. } else {
  164901. for (ci = 0; ci < cinfo->num_components; ci++) {
  164902. if (! component_sent[ci])
  164903. ERREXIT(cinfo, JERR_MISSING_DATA);
  164904. }
  164905. }
  164906. }
  164907. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  164908. LOCAL(void)
  164909. select_scan_parameters (j_compress_ptr cinfo)
  164910. /* Set up the scan parameters for the current scan */
  164911. {
  164912. int ci;
  164913. #ifdef C_MULTISCAN_FILES_SUPPORTED
  164914. if (cinfo->scan_info != NULL) {
  164915. /* Prepare for current scan --- the script is already validated */
  164916. my_master_ptr master = (my_master_ptr) cinfo->master;
  164917. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  164918. cinfo->comps_in_scan = scanptr->comps_in_scan;
  164919. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  164920. cinfo->cur_comp_info[ci] =
  164921. &cinfo->comp_info[scanptr->component_index[ci]];
  164922. }
  164923. cinfo->Ss = scanptr->Ss;
  164924. cinfo->Se = scanptr->Se;
  164925. cinfo->Ah = scanptr->Ah;
  164926. cinfo->Al = scanptr->Al;
  164927. }
  164928. else
  164929. #endif
  164930. {
  164931. /* Prepare for single sequential-JPEG scan containing all components */
  164932. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  164933. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164934. MAX_COMPS_IN_SCAN);
  164935. cinfo->comps_in_scan = cinfo->num_components;
  164936. for (ci = 0; ci < cinfo->num_components; ci++) {
  164937. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  164938. }
  164939. cinfo->Ss = 0;
  164940. cinfo->Se = DCTSIZE2-1;
  164941. cinfo->Ah = 0;
  164942. cinfo->Al = 0;
  164943. }
  164944. }
  164945. LOCAL(void)
  164946. per_scan_setup (j_compress_ptr cinfo)
  164947. /* Do computations that are needed before processing a JPEG scan */
  164948. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  164949. {
  164950. int ci, mcublks, tmp;
  164951. jpeg_component_info *compptr;
  164952. if (cinfo->comps_in_scan == 1) {
  164953. /* Noninterleaved (single-component) scan */
  164954. compptr = cinfo->cur_comp_info[0];
  164955. /* Overall image size in MCUs */
  164956. cinfo->MCUs_per_row = compptr->width_in_blocks;
  164957. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  164958. /* For noninterleaved scan, always one block per MCU */
  164959. compptr->MCU_width = 1;
  164960. compptr->MCU_height = 1;
  164961. compptr->MCU_blocks = 1;
  164962. compptr->MCU_sample_width = DCTSIZE;
  164963. compptr->last_col_width = 1;
  164964. /* For noninterleaved scans, it is convenient to define last_row_height
  164965. * as the number of block rows present in the last iMCU row.
  164966. */
  164967. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  164968. if (tmp == 0) tmp = compptr->v_samp_factor;
  164969. compptr->last_row_height = tmp;
  164970. /* Prepare array describing MCU composition */
  164971. cinfo->blocks_in_MCU = 1;
  164972. cinfo->MCU_membership[0] = 0;
  164973. } else {
  164974. /* Interleaved (multi-component) scan */
  164975. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  164976. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  164977. MAX_COMPS_IN_SCAN);
  164978. /* Overall image size in MCUs */
  164979. cinfo->MCUs_per_row = (JDIMENSION)
  164980. jdiv_round_up((long) cinfo->image_width,
  164981. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  164982. cinfo->MCU_rows_in_scan = (JDIMENSION)
  164983. jdiv_round_up((long) cinfo->image_height,
  164984. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  164985. cinfo->blocks_in_MCU = 0;
  164986. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164987. compptr = cinfo->cur_comp_info[ci];
  164988. /* Sampling factors give # of blocks of component in each MCU */
  164989. compptr->MCU_width = compptr->h_samp_factor;
  164990. compptr->MCU_height = compptr->v_samp_factor;
  164991. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  164992. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  164993. /* Figure number of non-dummy blocks in last MCU column & row */
  164994. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  164995. if (tmp == 0) tmp = compptr->MCU_width;
  164996. compptr->last_col_width = tmp;
  164997. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  164998. if (tmp == 0) tmp = compptr->MCU_height;
  164999. compptr->last_row_height = tmp;
  165000. /* Prepare array describing MCU composition */
  165001. mcublks = compptr->MCU_blocks;
  165002. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  165003. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  165004. while (mcublks-- > 0) {
  165005. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  165006. }
  165007. }
  165008. }
  165009. /* Convert restart specified in rows to actual MCU count. */
  165010. /* Note that count must fit in 16 bits, so we provide limiting. */
  165011. if (cinfo->restart_in_rows > 0) {
  165012. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  165013. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  165014. }
  165015. }
  165016. /*
  165017. * Per-pass setup.
  165018. * This is called at the beginning of each pass. We determine which modules
  165019. * will be active during this pass and give them appropriate start_pass calls.
  165020. * We also set is_last_pass to indicate whether any more passes will be
  165021. * required.
  165022. */
  165023. METHODDEF(void)
  165024. prepare_for_pass (j_compress_ptr cinfo)
  165025. {
  165026. my_master_ptr master = (my_master_ptr) cinfo->master;
  165027. switch (master->pass_type) {
  165028. case main_pass:
  165029. /* Initial pass: will collect input data, and do either Huffman
  165030. * optimization or data output for the first scan.
  165031. */
  165032. select_scan_parameters(cinfo);
  165033. per_scan_setup(cinfo);
  165034. if (! cinfo->raw_data_in) {
  165035. (*cinfo->cconvert->start_pass) (cinfo);
  165036. (*cinfo->downsample->start_pass) (cinfo);
  165037. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  165038. }
  165039. (*cinfo->fdct->start_pass) (cinfo);
  165040. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  165041. (*cinfo->coef->start_pass) (cinfo,
  165042. (master->total_passes > 1 ?
  165043. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  165044. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  165045. if (cinfo->optimize_coding) {
  165046. /* No immediate data output; postpone writing frame/scan headers */
  165047. master->pub.call_pass_startup = FALSE;
  165048. } else {
  165049. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  165050. master->pub.call_pass_startup = TRUE;
  165051. }
  165052. break;
  165053. #ifdef ENTROPY_OPT_SUPPORTED
  165054. case huff_opt_pass:
  165055. /* Do Huffman optimization for a scan after the first one. */
  165056. select_scan_parameters(cinfo);
  165057. per_scan_setup(cinfo);
  165058. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  165059. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  165060. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  165061. master->pub.call_pass_startup = FALSE;
  165062. break;
  165063. }
  165064. /* Special case: Huffman DC refinement scans need no Huffman table
  165065. * and therefore we can skip the optimization pass for them.
  165066. */
  165067. master->pass_type = output_pass;
  165068. master->pass_number++;
  165069. /*FALLTHROUGH*/
  165070. #endif
  165071. case output_pass:
  165072. /* Do a data-output pass. */
  165073. /* We need not repeat per-scan setup if prior optimization pass did it. */
  165074. if (! cinfo->optimize_coding) {
  165075. select_scan_parameters(cinfo);
  165076. per_scan_setup(cinfo);
  165077. }
  165078. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  165079. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  165080. /* We emit frame/scan headers now */
  165081. if (master->scan_number == 0)
  165082. (*cinfo->marker->write_frame_header) (cinfo);
  165083. (*cinfo->marker->write_scan_header) (cinfo);
  165084. master->pub.call_pass_startup = FALSE;
  165085. break;
  165086. default:
  165087. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165088. }
  165089. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  165090. /* Set up progress monitor's pass info if present */
  165091. if (cinfo->progress != NULL) {
  165092. cinfo->progress->completed_passes = master->pass_number;
  165093. cinfo->progress->total_passes = master->total_passes;
  165094. }
  165095. }
  165096. /*
  165097. * Special start-of-pass hook.
  165098. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  165099. * In single-pass processing, we need this hook because we don't want to
  165100. * write frame/scan headers during jpeg_start_compress; we want to let the
  165101. * application write COM markers etc. between jpeg_start_compress and the
  165102. * jpeg_write_scanlines loop.
  165103. * In multi-pass processing, this routine is not used.
  165104. */
  165105. METHODDEF(void)
  165106. pass_startup (j_compress_ptr cinfo)
  165107. {
  165108. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  165109. (*cinfo->marker->write_frame_header) (cinfo);
  165110. (*cinfo->marker->write_scan_header) (cinfo);
  165111. }
  165112. /*
  165113. * Finish up at end of pass.
  165114. */
  165115. METHODDEF(void)
  165116. finish_pass_master (j_compress_ptr cinfo)
  165117. {
  165118. my_master_ptr master = (my_master_ptr) cinfo->master;
  165119. /* The entropy coder always needs an end-of-pass call,
  165120. * either to analyze statistics or to flush its output buffer.
  165121. */
  165122. (*cinfo->entropy->finish_pass) (cinfo);
  165123. /* Update state for next pass */
  165124. switch (master->pass_type) {
  165125. case main_pass:
  165126. /* next pass is either output of scan 0 (after optimization)
  165127. * or output of scan 1 (if no optimization).
  165128. */
  165129. master->pass_type = output_pass;
  165130. if (! cinfo->optimize_coding)
  165131. master->scan_number++;
  165132. break;
  165133. case huff_opt_pass:
  165134. /* next pass is always output of current scan */
  165135. master->pass_type = output_pass;
  165136. break;
  165137. case output_pass:
  165138. /* next pass is either optimization or output of next scan */
  165139. if (cinfo->optimize_coding)
  165140. master->pass_type = huff_opt_pass;
  165141. master->scan_number++;
  165142. break;
  165143. }
  165144. master->pass_number++;
  165145. }
  165146. /*
  165147. * Initialize master compression control.
  165148. */
  165149. GLOBAL(void)
  165150. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  165151. {
  165152. my_master_ptr master;
  165153. master = (my_master_ptr)
  165154. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165155. SIZEOF(my_comp_master));
  165156. cinfo->master = (struct jpeg_comp_master *) master;
  165157. master->pub.prepare_for_pass = prepare_for_pass;
  165158. master->pub.pass_startup = pass_startup;
  165159. master->pub.finish_pass = finish_pass_master;
  165160. master->pub.is_last_pass = FALSE;
  165161. /* Validate parameters, determine derived values */
  165162. initial_setup(cinfo);
  165163. if (cinfo->scan_info != NULL) {
  165164. #ifdef C_MULTISCAN_FILES_SUPPORTED
  165165. validate_script(cinfo);
  165166. #else
  165167. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165168. #endif
  165169. } else {
  165170. cinfo->progressive_mode = FALSE;
  165171. cinfo->num_scans = 1;
  165172. }
  165173. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  165174. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  165175. /* Initialize my private state */
  165176. if (transcode_only) {
  165177. /* no main pass in transcoding */
  165178. if (cinfo->optimize_coding)
  165179. master->pass_type = huff_opt_pass;
  165180. else
  165181. master->pass_type = output_pass;
  165182. } else {
  165183. /* for normal compression, first pass is always this type: */
  165184. master->pass_type = main_pass;
  165185. }
  165186. master->scan_number = 0;
  165187. master->pass_number = 0;
  165188. if (cinfo->optimize_coding)
  165189. master->total_passes = cinfo->num_scans * 2;
  165190. else
  165191. master->total_passes = cinfo->num_scans;
  165192. }
  165193. /*** End of inlined file: jcmaster.c ***/
  165194. /*** Start of inlined file: jcomapi.c ***/
  165195. #define JPEG_INTERNALS
  165196. /*
  165197. * Abort processing of a JPEG compression or decompression operation,
  165198. * but don't destroy the object itself.
  165199. *
  165200. * For this, we merely clean up all the nonpermanent memory pools.
  165201. * Note that temp files (virtual arrays) are not allowed to belong to
  165202. * the permanent pool, so we will be able to close all temp files here.
  165203. * Closing a data source or destination, if necessary, is the application's
  165204. * responsibility.
  165205. */
  165206. GLOBAL(void)
  165207. jpeg_abort (j_common_ptr cinfo)
  165208. {
  165209. int pool;
  165210. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  165211. if (cinfo->mem == NULL)
  165212. return;
  165213. /* Releasing pools in reverse order might help avoid fragmentation
  165214. * with some (brain-damaged) malloc libraries.
  165215. */
  165216. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  165217. (*cinfo->mem->free_pool) (cinfo, pool);
  165218. }
  165219. /* Reset overall state for possible reuse of object */
  165220. if (cinfo->is_decompressor) {
  165221. cinfo->global_state = DSTATE_START;
  165222. /* Try to keep application from accessing now-deleted marker list.
  165223. * A bit kludgy to do it here, but this is the most central place.
  165224. */
  165225. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  165226. } else {
  165227. cinfo->global_state = CSTATE_START;
  165228. }
  165229. }
  165230. /*
  165231. * Destruction of a JPEG object.
  165232. *
  165233. * Everything gets deallocated except the master jpeg_compress_struct itself
  165234. * and the error manager struct. Both of these are supplied by the application
  165235. * and must be freed, if necessary, by the application. (Often they are on
  165236. * the stack and so don't need to be freed anyway.)
  165237. * Closing a data source or destination, if necessary, is the application's
  165238. * responsibility.
  165239. */
  165240. GLOBAL(void)
  165241. jpeg_destroy (j_common_ptr cinfo)
  165242. {
  165243. /* We need only tell the memory manager to release everything. */
  165244. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  165245. if (cinfo->mem != NULL)
  165246. (*cinfo->mem->self_destruct) (cinfo);
  165247. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  165248. cinfo->global_state = 0; /* mark it destroyed */
  165249. }
  165250. /*
  165251. * Convenience routines for allocating quantization and Huffman tables.
  165252. * (Would jutils.c be a more reasonable place to put these?)
  165253. */
  165254. GLOBAL(JQUANT_TBL *)
  165255. jpeg_alloc_quant_table (j_common_ptr cinfo)
  165256. {
  165257. JQUANT_TBL *tbl;
  165258. tbl = (JQUANT_TBL *)
  165259. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  165260. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  165261. return tbl;
  165262. }
  165263. GLOBAL(JHUFF_TBL *)
  165264. jpeg_alloc_huff_table (j_common_ptr cinfo)
  165265. {
  165266. JHUFF_TBL *tbl;
  165267. tbl = (JHUFF_TBL *)
  165268. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  165269. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  165270. return tbl;
  165271. }
  165272. /*** End of inlined file: jcomapi.c ***/
  165273. /*** Start of inlined file: jcparam.c ***/
  165274. #define JPEG_INTERNALS
  165275. /*
  165276. * Quantization table setup routines
  165277. */
  165278. GLOBAL(void)
  165279. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  165280. const unsigned int *basic_table,
  165281. int scale_factor, boolean force_baseline)
  165282. /* Define a quantization table equal to the basic_table times
  165283. * a scale factor (given as a percentage).
  165284. * If force_baseline is TRUE, the computed quantization table entries
  165285. * are limited to 1..255 for JPEG baseline compatibility.
  165286. */
  165287. {
  165288. JQUANT_TBL ** qtblptr;
  165289. int i;
  165290. long temp;
  165291. /* Safety check to ensure start_compress not called yet. */
  165292. if (cinfo->global_state != CSTATE_START)
  165293. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165294. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  165295. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  165296. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  165297. if (*qtblptr == NULL)
  165298. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  165299. for (i = 0; i < DCTSIZE2; i++) {
  165300. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  165301. /* limit the values to the valid range */
  165302. if (temp <= 0L) temp = 1L;
  165303. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  165304. if (force_baseline && temp > 255L)
  165305. temp = 255L; /* limit to baseline range if requested */
  165306. (*qtblptr)->quantval[i] = (UINT16) temp;
  165307. }
  165308. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165309. (*qtblptr)->sent_table = FALSE;
  165310. }
  165311. GLOBAL(void)
  165312. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  165313. boolean force_baseline)
  165314. /* Set or change the 'quality' (quantization) setting, using default tables
  165315. * and a straight percentage-scaling quality scale. In most cases it's better
  165316. * to use jpeg_set_quality (below); this entry point is provided for
  165317. * applications that insist on a linear percentage scaling.
  165318. */
  165319. {
  165320. /* These are the sample quantization tables given in JPEG spec section K.1.
  165321. * The spec says that the values given produce "good" quality, and
  165322. * when divided by 2, "very good" quality.
  165323. */
  165324. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  165325. 16, 11, 10, 16, 24, 40, 51, 61,
  165326. 12, 12, 14, 19, 26, 58, 60, 55,
  165327. 14, 13, 16, 24, 40, 57, 69, 56,
  165328. 14, 17, 22, 29, 51, 87, 80, 62,
  165329. 18, 22, 37, 56, 68, 109, 103, 77,
  165330. 24, 35, 55, 64, 81, 104, 113, 92,
  165331. 49, 64, 78, 87, 103, 121, 120, 101,
  165332. 72, 92, 95, 98, 112, 100, 103, 99
  165333. };
  165334. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  165335. 17, 18, 24, 47, 99, 99, 99, 99,
  165336. 18, 21, 26, 66, 99, 99, 99, 99,
  165337. 24, 26, 56, 99, 99, 99, 99, 99,
  165338. 47, 66, 99, 99, 99, 99, 99, 99,
  165339. 99, 99, 99, 99, 99, 99, 99, 99,
  165340. 99, 99, 99, 99, 99, 99, 99, 99,
  165341. 99, 99, 99, 99, 99, 99, 99, 99,
  165342. 99, 99, 99, 99, 99, 99, 99, 99
  165343. };
  165344. /* Set up two quantization tables using the specified scaling */
  165345. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  165346. scale_factor, force_baseline);
  165347. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  165348. scale_factor, force_baseline);
  165349. }
  165350. GLOBAL(int)
  165351. jpeg_quality_scaling (int quality)
  165352. /* Convert a user-specified quality rating to a percentage scaling factor
  165353. * for an underlying quantization table, using our recommended scaling curve.
  165354. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  165355. */
  165356. {
  165357. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  165358. if (quality <= 0) quality = 1;
  165359. if (quality > 100) quality = 100;
  165360. /* The basic table is used as-is (scaling 100) for a quality of 50.
  165361. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  165362. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  165363. * to make all the table entries 1 (hence, minimum quantization loss).
  165364. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  165365. */
  165366. if (quality < 50)
  165367. quality = 5000 / quality;
  165368. else
  165369. quality = 200 - quality*2;
  165370. return quality;
  165371. }
  165372. GLOBAL(void)
  165373. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  165374. /* Set or change the 'quality' (quantization) setting, using default tables.
  165375. * This is the standard quality-adjusting entry point for typical user
  165376. * interfaces; only those who want detailed control over quantization tables
  165377. * would use the preceding three routines directly.
  165378. */
  165379. {
  165380. /* Convert user 0-100 rating to percentage scaling */
  165381. quality = jpeg_quality_scaling(quality);
  165382. /* Set up standard quality tables */
  165383. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  165384. }
  165385. /*
  165386. * Huffman table setup routines
  165387. */
  165388. LOCAL(void)
  165389. add_huff_table (j_compress_ptr cinfo,
  165390. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  165391. /* Define a Huffman table */
  165392. {
  165393. int nsymbols, len;
  165394. if (*htblptr == NULL)
  165395. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  165396. /* Copy the number-of-symbols-of-each-code-length counts */
  165397. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  165398. /* Validate the counts. We do this here mainly so we can copy the right
  165399. * number of symbols from the val[] array, without risking marching off
  165400. * the end of memory. jchuff.c will do a more thorough test later.
  165401. */
  165402. nsymbols = 0;
  165403. for (len = 1; len <= 16; len++)
  165404. nsymbols += bits[len];
  165405. if (nsymbols < 1 || nsymbols > 256)
  165406. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  165407. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  165408. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165409. (*htblptr)->sent_table = FALSE;
  165410. }
  165411. LOCAL(void)
  165412. std_huff_tables (j_compress_ptr cinfo)
  165413. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  165414. /* IMPORTANT: these are only valid for 8-bit data precision! */
  165415. {
  165416. static const UINT8 bits_dc_luminance[17] =
  165417. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  165418. static const UINT8 val_dc_luminance[] =
  165419. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165420. static const UINT8 bits_dc_chrominance[17] =
  165421. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  165422. static const UINT8 val_dc_chrominance[] =
  165423. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165424. static const UINT8 bits_ac_luminance[17] =
  165425. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  165426. static const UINT8 val_ac_luminance[] =
  165427. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  165428. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  165429. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  165430. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  165431. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  165432. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  165433. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  165434. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  165435. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  165436. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  165437. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  165438. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  165439. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  165440. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  165441. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  165442. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  165443. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  165444. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  165445. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  165446. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165447. 0xf9, 0xfa };
  165448. static const UINT8 bits_ac_chrominance[17] =
  165449. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  165450. static const UINT8 val_ac_chrominance[] =
  165451. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  165452. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  165453. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  165454. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  165455. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  165456. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  165457. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  165458. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  165459. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  165460. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  165461. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  165462. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  165463. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  165464. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  165465. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  165466. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  165467. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  165468. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  165469. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  165470. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165471. 0xf9, 0xfa };
  165472. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  165473. bits_dc_luminance, val_dc_luminance);
  165474. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  165475. bits_ac_luminance, val_ac_luminance);
  165476. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  165477. bits_dc_chrominance, val_dc_chrominance);
  165478. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  165479. bits_ac_chrominance, val_ac_chrominance);
  165480. }
  165481. /*
  165482. * Default parameter setup for compression.
  165483. *
  165484. * Applications that don't choose to use this routine must do their
  165485. * own setup of all these parameters. Alternately, you can call this
  165486. * to establish defaults and then alter parameters selectively. This
  165487. * is the recommended approach since, if we add any new parameters,
  165488. * your code will still work (they'll be set to reasonable defaults).
  165489. */
  165490. GLOBAL(void)
  165491. jpeg_set_defaults (j_compress_ptr cinfo)
  165492. {
  165493. int i;
  165494. /* Safety check to ensure start_compress not called yet. */
  165495. if (cinfo->global_state != CSTATE_START)
  165496. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165497. /* Allocate comp_info array large enough for maximum component count.
  165498. * Array is made permanent in case application wants to compress
  165499. * multiple images at same param settings.
  165500. */
  165501. if (cinfo->comp_info == NULL)
  165502. cinfo->comp_info = (jpeg_component_info *)
  165503. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165504. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  165505. /* Initialize everything not dependent on the color space */
  165506. cinfo->data_precision = BITS_IN_JSAMPLE;
  165507. /* Set up two quantization tables using default quality of 75 */
  165508. jpeg_set_quality(cinfo, 75, TRUE);
  165509. /* Set up two Huffman tables */
  165510. std_huff_tables(cinfo);
  165511. /* Initialize default arithmetic coding conditioning */
  165512. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  165513. cinfo->arith_dc_L[i] = 0;
  165514. cinfo->arith_dc_U[i] = 1;
  165515. cinfo->arith_ac_K[i] = 5;
  165516. }
  165517. /* Default is no multiple-scan output */
  165518. cinfo->scan_info = NULL;
  165519. cinfo->num_scans = 0;
  165520. /* Expect normal source image, not raw downsampled data */
  165521. cinfo->raw_data_in = FALSE;
  165522. /* Use Huffman coding, not arithmetic coding, by default */
  165523. cinfo->arith_code = FALSE;
  165524. /* By default, don't do extra passes to optimize entropy coding */
  165525. cinfo->optimize_coding = FALSE;
  165526. /* The standard Huffman tables are only valid for 8-bit data precision.
  165527. * If the precision is higher, force optimization on so that usable
  165528. * tables will be computed. This test can be removed if default tables
  165529. * are supplied that are valid for the desired precision.
  165530. */
  165531. if (cinfo->data_precision > 8)
  165532. cinfo->optimize_coding = TRUE;
  165533. /* By default, use the simpler non-cosited sampling alignment */
  165534. cinfo->CCIR601_sampling = FALSE;
  165535. /* No input smoothing */
  165536. cinfo->smoothing_factor = 0;
  165537. /* DCT algorithm preference */
  165538. cinfo->dct_method = JDCT_DEFAULT;
  165539. /* No restart markers */
  165540. cinfo->restart_interval = 0;
  165541. cinfo->restart_in_rows = 0;
  165542. /* Fill in default JFIF marker parameters. Note that whether the marker
  165543. * will actually be written is determined by jpeg_set_colorspace.
  165544. *
  165545. * By default, the library emits JFIF version code 1.01.
  165546. * An application that wants to emit JFIF 1.02 extension markers should set
  165547. * JFIF_minor_version to 2. We could probably get away with just defaulting
  165548. * to 1.02, but there may still be some decoders in use that will complain
  165549. * about that; saying 1.01 should minimize compatibility problems.
  165550. */
  165551. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  165552. cinfo->JFIF_minor_version = 1;
  165553. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  165554. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  165555. cinfo->Y_density = 1;
  165556. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  165557. jpeg_default_colorspace(cinfo);
  165558. }
  165559. /*
  165560. * Select an appropriate JPEG colorspace for in_color_space.
  165561. */
  165562. GLOBAL(void)
  165563. jpeg_default_colorspace (j_compress_ptr cinfo)
  165564. {
  165565. switch (cinfo->in_color_space) {
  165566. case JCS_GRAYSCALE:
  165567. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  165568. break;
  165569. case JCS_RGB:
  165570. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165571. break;
  165572. case JCS_YCbCr:
  165573. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165574. break;
  165575. case JCS_CMYK:
  165576. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  165577. break;
  165578. case JCS_YCCK:
  165579. jpeg_set_colorspace(cinfo, JCS_YCCK);
  165580. break;
  165581. case JCS_UNKNOWN:
  165582. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  165583. break;
  165584. default:
  165585. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  165586. }
  165587. }
  165588. /*
  165589. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  165590. */
  165591. GLOBAL(void)
  165592. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  165593. {
  165594. jpeg_component_info * compptr;
  165595. int ci;
  165596. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  165597. (compptr = &cinfo->comp_info[index], \
  165598. compptr->component_id = (id), \
  165599. compptr->h_samp_factor = (hsamp), \
  165600. compptr->v_samp_factor = (vsamp), \
  165601. compptr->quant_tbl_no = (quant), \
  165602. compptr->dc_tbl_no = (dctbl), \
  165603. compptr->ac_tbl_no = (actbl) )
  165604. /* Safety check to ensure start_compress not called yet. */
  165605. if (cinfo->global_state != CSTATE_START)
  165606. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165607. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  165608. * tables 1 for chrominance components.
  165609. */
  165610. cinfo->jpeg_color_space = colorspace;
  165611. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  165612. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  165613. switch (colorspace) {
  165614. case JCS_GRAYSCALE:
  165615. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165616. cinfo->num_components = 1;
  165617. /* JFIF specifies component ID 1 */
  165618. SET_COMP(0, 1, 1,1, 0, 0,0);
  165619. break;
  165620. case JCS_RGB:
  165621. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  165622. cinfo->num_components = 3;
  165623. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  165624. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  165625. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  165626. break;
  165627. case JCS_YCbCr:
  165628. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165629. cinfo->num_components = 3;
  165630. /* JFIF specifies component IDs 1,2,3 */
  165631. /* We default to 2x2 subsamples of chrominance */
  165632. SET_COMP(0, 1, 2,2, 0, 0,0);
  165633. SET_COMP(1, 2, 1,1, 1, 1,1);
  165634. SET_COMP(2, 3, 1,1, 1, 1,1);
  165635. break;
  165636. case JCS_CMYK:
  165637. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  165638. cinfo->num_components = 4;
  165639. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  165640. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  165641. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  165642. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  165643. break;
  165644. case JCS_YCCK:
  165645. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  165646. cinfo->num_components = 4;
  165647. SET_COMP(0, 1, 2,2, 0, 0,0);
  165648. SET_COMP(1, 2, 1,1, 1, 1,1);
  165649. SET_COMP(2, 3, 1,1, 1, 1,1);
  165650. SET_COMP(3, 4, 2,2, 0, 0,0);
  165651. break;
  165652. case JCS_UNKNOWN:
  165653. cinfo->num_components = cinfo->input_components;
  165654. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  165655. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165656. MAX_COMPONENTS);
  165657. for (ci = 0; ci < cinfo->num_components; ci++) {
  165658. SET_COMP(ci, ci, 1,1, 0, 0,0);
  165659. }
  165660. break;
  165661. default:
  165662. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165663. }
  165664. }
  165665. #ifdef C_PROGRESSIVE_SUPPORTED
  165666. LOCAL(jpeg_scan_info *)
  165667. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  165668. int Ss, int Se, int Ah, int Al)
  165669. /* Support routine: generate one scan for specified component */
  165670. {
  165671. scanptr->comps_in_scan = 1;
  165672. scanptr->component_index[0] = ci;
  165673. scanptr->Ss = Ss;
  165674. scanptr->Se = Se;
  165675. scanptr->Ah = Ah;
  165676. scanptr->Al = Al;
  165677. scanptr++;
  165678. return scanptr;
  165679. }
  165680. LOCAL(jpeg_scan_info *)
  165681. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  165682. int Ss, int Se, int Ah, int Al)
  165683. /* Support routine: generate one scan for each component */
  165684. {
  165685. int ci;
  165686. for (ci = 0; ci < ncomps; ci++) {
  165687. scanptr->comps_in_scan = 1;
  165688. scanptr->component_index[0] = ci;
  165689. scanptr->Ss = Ss;
  165690. scanptr->Se = Se;
  165691. scanptr->Ah = Ah;
  165692. scanptr->Al = Al;
  165693. scanptr++;
  165694. }
  165695. return scanptr;
  165696. }
  165697. LOCAL(jpeg_scan_info *)
  165698. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  165699. /* Support routine: generate interleaved DC scan if possible, else N scans */
  165700. {
  165701. int ci;
  165702. if (ncomps <= MAX_COMPS_IN_SCAN) {
  165703. /* Single interleaved DC scan */
  165704. scanptr->comps_in_scan = ncomps;
  165705. for (ci = 0; ci < ncomps; ci++)
  165706. scanptr->component_index[ci] = ci;
  165707. scanptr->Ss = scanptr->Se = 0;
  165708. scanptr->Ah = Ah;
  165709. scanptr->Al = Al;
  165710. scanptr++;
  165711. } else {
  165712. /* Noninterleaved DC scan for each component */
  165713. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  165714. }
  165715. return scanptr;
  165716. }
  165717. /*
  165718. * Create a recommended progressive-JPEG script.
  165719. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  165720. */
  165721. GLOBAL(void)
  165722. jpeg_simple_progression (j_compress_ptr cinfo)
  165723. {
  165724. int ncomps = cinfo->num_components;
  165725. int nscans;
  165726. jpeg_scan_info * scanptr;
  165727. /* Safety check to ensure start_compress not called yet. */
  165728. if (cinfo->global_state != CSTATE_START)
  165729. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165730. /* Figure space needed for script. Calculation must match code below! */
  165731. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165732. /* Custom script for YCbCr color images. */
  165733. nscans = 10;
  165734. } else {
  165735. /* All-purpose script for other color spaces. */
  165736. if (ncomps > MAX_COMPS_IN_SCAN)
  165737. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  165738. else
  165739. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  165740. }
  165741. /* Allocate space for script.
  165742. * We need to put it in the permanent pool in case the application performs
  165743. * multiple compressions without changing the settings. To avoid a memory
  165744. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  165745. * object, we try to re-use previously allocated space, and we allocate
  165746. * enough space to handle YCbCr even if initially asked for grayscale.
  165747. */
  165748. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  165749. cinfo->script_space_size = MAX(nscans, 10);
  165750. cinfo->script_space = (jpeg_scan_info *)
  165751. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165752. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  165753. }
  165754. scanptr = cinfo->script_space;
  165755. cinfo->scan_info = scanptr;
  165756. cinfo->num_scans = nscans;
  165757. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165758. /* Custom script for YCbCr color images. */
  165759. /* Initial DC scan */
  165760. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165761. /* Initial AC scan: get some luma data out in a hurry */
  165762. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  165763. /* Chroma data is too small to be worth expending many scans on */
  165764. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  165765. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  165766. /* Complete spectral selection for luma AC */
  165767. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  165768. /* Refine next bit of luma AC */
  165769. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  165770. /* Finish DC successive approximation */
  165771. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165772. /* Finish AC successive approximation */
  165773. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  165774. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  165775. /* Luma bottom bit comes last since it's usually largest scan */
  165776. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  165777. } else {
  165778. /* All-purpose script for other color spaces. */
  165779. /* Successive approximation first pass */
  165780. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165781. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  165782. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  165783. /* Successive approximation second pass */
  165784. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  165785. /* Successive approximation final pass */
  165786. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165787. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  165788. }
  165789. }
  165790. #endif /* C_PROGRESSIVE_SUPPORTED */
  165791. /*** End of inlined file: jcparam.c ***/
  165792. /*** Start of inlined file: jcphuff.c ***/
  165793. #define JPEG_INTERNALS
  165794. #ifdef C_PROGRESSIVE_SUPPORTED
  165795. /* Expanded entropy encoder object for progressive Huffman encoding. */
  165796. typedef struct {
  165797. struct jpeg_entropy_encoder pub; /* public fields */
  165798. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  165799. boolean gather_statistics;
  165800. /* Bit-level coding status.
  165801. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  165802. */
  165803. JOCTET * next_output_byte; /* => next byte to write in buffer */
  165804. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  165805. INT32 put_buffer; /* current bit-accumulation buffer */
  165806. int put_bits; /* # of bits now in it */
  165807. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  165808. /* Coding status for DC components */
  165809. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  165810. /* Coding status for AC components */
  165811. int ac_tbl_no; /* the table number of the single component */
  165812. unsigned int EOBRUN; /* run length of EOBs */
  165813. unsigned int BE; /* # of buffered correction bits before MCU */
  165814. char * bit_buffer; /* buffer for correction bits (1 per char) */
  165815. /* packing correction bits tightly would save some space but cost time... */
  165816. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  165817. int next_restart_num; /* next restart number to write (0-7) */
  165818. /* Pointers to derived tables (these workspaces have image lifespan).
  165819. * Since any one scan codes only DC or only AC, we only need one set
  165820. * of tables, not one for DC and one for AC.
  165821. */
  165822. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  165823. /* Statistics tables for optimization; again, one set is enough */
  165824. long * count_ptrs[NUM_HUFF_TBLS];
  165825. } phuff_entropy_encoder;
  165826. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  165827. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  165828. * buffer can hold. Larger sizes may slightly improve compression, but
  165829. * 1000 is already well into the realm of overkill.
  165830. * The minimum safe size is 64 bits.
  165831. */
  165832. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  165833. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  165834. * We assume that int right shift is unsigned if INT32 right shift is,
  165835. * which should be safe.
  165836. */
  165837. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  165838. #define ISHIFT_TEMPS int ishift_temp;
  165839. #define IRIGHT_SHIFT(x,shft) \
  165840. ((ishift_temp = (x)) < 0 ? \
  165841. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  165842. (ishift_temp >> (shft)))
  165843. #else
  165844. #define ISHIFT_TEMPS
  165845. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  165846. #endif
  165847. /* Forward declarations */
  165848. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  165849. JBLOCKROW *MCU_data));
  165850. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  165851. JBLOCKROW *MCU_data));
  165852. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  165853. JBLOCKROW *MCU_data));
  165854. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  165855. JBLOCKROW *MCU_data));
  165856. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  165857. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  165858. /*
  165859. * Initialize for a Huffman-compressed scan using progressive JPEG.
  165860. */
  165861. METHODDEF(void)
  165862. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  165863. {
  165864. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  165865. boolean is_DC_band;
  165866. int ci, tbl;
  165867. jpeg_component_info * compptr;
  165868. entropy->cinfo = cinfo;
  165869. entropy->gather_statistics = gather_statistics;
  165870. is_DC_band = (cinfo->Ss == 0);
  165871. /* We assume jcmaster.c already validated the scan parameters. */
  165872. /* Select execution routines */
  165873. if (cinfo->Ah == 0) {
  165874. if (is_DC_band)
  165875. entropy->pub.encode_mcu = encode_mcu_DC_first;
  165876. else
  165877. entropy->pub.encode_mcu = encode_mcu_AC_first;
  165878. } else {
  165879. if (is_DC_band)
  165880. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  165881. else {
  165882. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  165883. /* AC refinement needs a correction bit buffer */
  165884. if (entropy->bit_buffer == NULL)
  165885. entropy->bit_buffer = (char *)
  165886. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165887. MAX_CORR_BITS * SIZEOF(char));
  165888. }
  165889. }
  165890. if (gather_statistics)
  165891. entropy->pub.finish_pass = finish_pass_gather_phuff;
  165892. else
  165893. entropy->pub.finish_pass = finish_pass_phuff;
  165894. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  165895. * for AC coefficients.
  165896. */
  165897. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165898. compptr = cinfo->cur_comp_info[ci];
  165899. /* Initialize DC predictions to 0 */
  165900. entropy->last_dc_val[ci] = 0;
  165901. /* Get table index */
  165902. if (is_DC_band) {
  165903. if (cinfo->Ah != 0) /* DC refinement needs no table */
  165904. continue;
  165905. tbl = compptr->dc_tbl_no;
  165906. } else {
  165907. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  165908. }
  165909. if (gather_statistics) {
  165910. /* Check for invalid table index */
  165911. /* (make_c_derived_tbl does this in the other path) */
  165912. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  165913. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  165914. /* Allocate and zero the statistics tables */
  165915. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  165916. if (entropy->count_ptrs[tbl] == NULL)
  165917. entropy->count_ptrs[tbl] = (long *)
  165918. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165919. 257 * SIZEOF(long));
  165920. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  165921. } else {
  165922. /* Compute derived values for Huffman table */
  165923. /* We may do this more than once for a table, but it's not expensive */
  165924. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  165925. & entropy->derived_tbls[tbl]);
  165926. }
  165927. }
  165928. /* Initialize AC stuff */
  165929. entropy->EOBRUN = 0;
  165930. entropy->BE = 0;
  165931. /* Initialize bit buffer to empty */
  165932. entropy->put_buffer = 0;
  165933. entropy->put_bits = 0;
  165934. /* Initialize restart stuff */
  165935. entropy->restarts_to_go = cinfo->restart_interval;
  165936. entropy->next_restart_num = 0;
  165937. }
  165938. /* Outputting bytes to the file.
  165939. * NB: these must be called only when actually outputting,
  165940. * that is, entropy->gather_statistics == FALSE.
  165941. */
  165942. /* Emit a byte */
  165943. #define emit_byte(entropy,val) \
  165944. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  165945. if (--(entropy)->free_in_buffer == 0) \
  165946. dump_buffer_p(entropy); }
  165947. LOCAL(void)
  165948. dump_buffer_p (phuff_entropy_ptr entropy)
  165949. /* Empty the output buffer; we do not support suspension in this module. */
  165950. {
  165951. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  165952. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  165953. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  165954. /* After a successful buffer dump, must reset buffer pointers */
  165955. entropy->next_output_byte = dest->next_output_byte;
  165956. entropy->free_in_buffer = dest->free_in_buffer;
  165957. }
  165958. /* Outputting bits to the file */
  165959. /* Only the right 24 bits of put_buffer are used; the valid bits are
  165960. * left-justified in this part. At most 16 bits can be passed to emit_bits
  165961. * in one call, and we never retain more than 7 bits in put_buffer
  165962. * between calls, so 24 bits are sufficient.
  165963. */
  165964. INLINE
  165965. LOCAL(void)
  165966. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  165967. /* Emit some bits, unless we are in gather mode */
  165968. {
  165969. /* This routine is heavily used, so it's worth coding tightly. */
  165970. register INT32 put_buffer = (INT32) code;
  165971. register int put_bits = entropy->put_bits;
  165972. /* if size is 0, caller used an invalid Huffman table entry */
  165973. if (size == 0)
  165974. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  165975. if (entropy->gather_statistics)
  165976. return; /* do nothing if we're only getting stats */
  165977. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  165978. put_bits += size; /* new number of bits in buffer */
  165979. put_buffer <<= 24 - put_bits; /* align incoming bits */
  165980. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  165981. while (put_bits >= 8) {
  165982. int c = (int) ((put_buffer >> 16) & 0xFF);
  165983. emit_byte(entropy, c);
  165984. if (c == 0xFF) { /* need to stuff a zero byte? */
  165985. emit_byte(entropy, 0);
  165986. }
  165987. put_buffer <<= 8;
  165988. put_bits -= 8;
  165989. }
  165990. entropy->put_buffer = put_buffer; /* update variables */
  165991. entropy->put_bits = put_bits;
  165992. }
  165993. LOCAL(void)
  165994. flush_bits_p (phuff_entropy_ptr entropy)
  165995. {
  165996. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  165997. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  165998. entropy->put_bits = 0;
  165999. }
  166000. /*
  166001. * Emit (or just count) a Huffman symbol.
  166002. */
  166003. INLINE
  166004. LOCAL(void)
  166005. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  166006. {
  166007. if (entropy->gather_statistics)
  166008. entropy->count_ptrs[tbl_no][symbol]++;
  166009. else {
  166010. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  166011. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  166012. }
  166013. }
  166014. /*
  166015. * Emit bits from a correction bit buffer.
  166016. */
  166017. LOCAL(void)
  166018. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  166019. unsigned int nbits)
  166020. {
  166021. if (entropy->gather_statistics)
  166022. return; /* no real work */
  166023. while (nbits > 0) {
  166024. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  166025. bufstart++;
  166026. nbits--;
  166027. }
  166028. }
  166029. /*
  166030. * Emit any pending EOBRUN symbol.
  166031. */
  166032. LOCAL(void)
  166033. emit_eobrun (phuff_entropy_ptr entropy)
  166034. {
  166035. register int temp, nbits;
  166036. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  166037. temp = entropy->EOBRUN;
  166038. nbits = 0;
  166039. while ((temp >>= 1))
  166040. nbits++;
  166041. /* safety check: shouldn't happen given limited correction-bit buffer */
  166042. if (nbits > 14)
  166043. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  166044. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  166045. if (nbits)
  166046. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  166047. entropy->EOBRUN = 0;
  166048. /* Emit any buffered correction bits */
  166049. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  166050. entropy->BE = 0;
  166051. }
  166052. }
  166053. /*
  166054. * Emit a restart marker & resynchronize predictions.
  166055. */
  166056. LOCAL(void)
  166057. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  166058. {
  166059. int ci;
  166060. emit_eobrun(entropy);
  166061. if (! entropy->gather_statistics) {
  166062. flush_bits_p(entropy);
  166063. emit_byte(entropy, 0xFF);
  166064. emit_byte(entropy, JPEG_RST0 + restart_num);
  166065. }
  166066. if (entropy->cinfo->Ss == 0) {
  166067. /* Re-initialize DC predictions to 0 */
  166068. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  166069. entropy->last_dc_val[ci] = 0;
  166070. } else {
  166071. /* Re-initialize all AC-related fields to 0 */
  166072. entropy->EOBRUN = 0;
  166073. entropy->BE = 0;
  166074. }
  166075. }
  166076. /*
  166077. * MCU encoding for DC initial scan (either spectral selection,
  166078. * or first pass of successive approximation).
  166079. */
  166080. METHODDEF(boolean)
  166081. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166082. {
  166083. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166084. register int temp, temp2;
  166085. register int nbits;
  166086. int blkn, ci;
  166087. int Al = cinfo->Al;
  166088. JBLOCKROW block;
  166089. jpeg_component_info * compptr;
  166090. ISHIFT_TEMPS
  166091. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166092. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166093. /* Emit restart marker if needed */
  166094. if (cinfo->restart_interval)
  166095. if (entropy->restarts_to_go == 0)
  166096. emit_restart_p(entropy, entropy->next_restart_num);
  166097. /* Encode the MCU data blocks */
  166098. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166099. block = MCU_data[blkn];
  166100. ci = cinfo->MCU_membership[blkn];
  166101. compptr = cinfo->cur_comp_info[ci];
  166102. /* Compute the DC value after the required point transform by Al.
  166103. * This is simply an arithmetic right shift.
  166104. */
  166105. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  166106. /* DC differences are figured on the point-transformed values. */
  166107. temp = temp2 - entropy->last_dc_val[ci];
  166108. entropy->last_dc_val[ci] = temp2;
  166109. /* Encode the DC coefficient difference per section G.1.2.1 */
  166110. temp2 = temp;
  166111. if (temp < 0) {
  166112. temp = -temp; /* temp is abs value of input */
  166113. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  166114. /* This code assumes we are on a two's complement machine */
  166115. temp2--;
  166116. }
  166117. /* Find the number of bits needed for the magnitude of the coefficient */
  166118. nbits = 0;
  166119. while (temp) {
  166120. nbits++;
  166121. temp >>= 1;
  166122. }
  166123. /* Check for out-of-range coefficient values.
  166124. * Since we're encoding a difference, the range limit is twice as much.
  166125. */
  166126. if (nbits > MAX_COEF_BITS+1)
  166127. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  166128. /* Count/emit the Huffman-coded symbol for the number of bits */
  166129. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  166130. /* Emit that number of bits of the value, if positive, */
  166131. /* or the complement of its magnitude, if negative. */
  166132. if (nbits) /* emit_bits rejects calls with size 0 */
  166133. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  166134. }
  166135. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166136. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166137. /* Update restart-interval state too */
  166138. if (cinfo->restart_interval) {
  166139. if (entropy->restarts_to_go == 0) {
  166140. entropy->restarts_to_go = cinfo->restart_interval;
  166141. entropy->next_restart_num++;
  166142. entropy->next_restart_num &= 7;
  166143. }
  166144. entropy->restarts_to_go--;
  166145. }
  166146. return TRUE;
  166147. }
  166148. /*
  166149. * MCU encoding for AC initial scan (either spectral selection,
  166150. * or first pass of successive approximation).
  166151. */
  166152. METHODDEF(boolean)
  166153. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166154. {
  166155. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166156. register int temp, temp2;
  166157. register int nbits;
  166158. register int r, k;
  166159. int Se = cinfo->Se;
  166160. int Al = cinfo->Al;
  166161. JBLOCKROW block;
  166162. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166163. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166164. /* Emit restart marker if needed */
  166165. if (cinfo->restart_interval)
  166166. if (entropy->restarts_to_go == 0)
  166167. emit_restart_p(entropy, entropy->next_restart_num);
  166168. /* Encode the MCU data block */
  166169. block = MCU_data[0];
  166170. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  166171. r = 0; /* r = run length of zeros */
  166172. for (k = cinfo->Ss; k <= Se; k++) {
  166173. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  166174. r++;
  166175. continue;
  166176. }
  166177. /* We must apply the point transform by Al. For AC coefficients this
  166178. * is an integer division with rounding towards 0. To do this portably
  166179. * in C, we shift after obtaining the absolute value; so the code is
  166180. * interwoven with finding the abs value (temp) and output bits (temp2).
  166181. */
  166182. if (temp < 0) {
  166183. temp = -temp; /* temp is abs value of input */
  166184. temp >>= Al; /* apply the point transform */
  166185. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  166186. temp2 = ~temp;
  166187. } else {
  166188. temp >>= Al; /* apply the point transform */
  166189. temp2 = temp;
  166190. }
  166191. /* Watch out for case that nonzero coef is zero after point transform */
  166192. if (temp == 0) {
  166193. r++;
  166194. continue;
  166195. }
  166196. /* Emit any pending EOBRUN */
  166197. if (entropy->EOBRUN > 0)
  166198. emit_eobrun(entropy);
  166199. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  166200. while (r > 15) {
  166201. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  166202. r -= 16;
  166203. }
  166204. /* Find the number of bits needed for the magnitude of the coefficient */
  166205. nbits = 1; /* there must be at least one 1 bit */
  166206. while ((temp >>= 1))
  166207. nbits++;
  166208. /* Check for out-of-range coefficient values */
  166209. if (nbits > MAX_COEF_BITS)
  166210. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  166211. /* Count/emit Huffman symbol for run length / number of bits */
  166212. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  166213. /* Emit that number of bits of the value, if positive, */
  166214. /* or the complement of its magnitude, if negative. */
  166215. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  166216. r = 0; /* reset zero run length */
  166217. }
  166218. if (r > 0) { /* If there are trailing zeroes, */
  166219. entropy->EOBRUN++; /* count an EOB */
  166220. if (entropy->EOBRUN == 0x7FFF)
  166221. emit_eobrun(entropy); /* force it out to avoid overflow */
  166222. }
  166223. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166224. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166225. /* Update restart-interval state too */
  166226. if (cinfo->restart_interval) {
  166227. if (entropy->restarts_to_go == 0) {
  166228. entropy->restarts_to_go = cinfo->restart_interval;
  166229. entropy->next_restart_num++;
  166230. entropy->next_restart_num &= 7;
  166231. }
  166232. entropy->restarts_to_go--;
  166233. }
  166234. return TRUE;
  166235. }
  166236. /*
  166237. * MCU encoding for DC successive approximation refinement scan.
  166238. * Note: we assume such scans can be multi-component, although the spec
  166239. * is not very clear on the point.
  166240. */
  166241. METHODDEF(boolean)
  166242. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166243. {
  166244. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166245. register int temp;
  166246. int blkn;
  166247. int Al = cinfo->Al;
  166248. JBLOCKROW block;
  166249. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166250. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166251. /* Emit restart marker if needed */
  166252. if (cinfo->restart_interval)
  166253. if (entropy->restarts_to_go == 0)
  166254. emit_restart_p(entropy, entropy->next_restart_num);
  166255. /* Encode the MCU data blocks */
  166256. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166257. block = MCU_data[blkn];
  166258. /* We simply emit the Al'th bit of the DC coefficient value. */
  166259. temp = (*block)[0];
  166260. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  166261. }
  166262. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166263. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166264. /* Update restart-interval state too */
  166265. if (cinfo->restart_interval) {
  166266. if (entropy->restarts_to_go == 0) {
  166267. entropy->restarts_to_go = cinfo->restart_interval;
  166268. entropy->next_restart_num++;
  166269. entropy->next_restart_num &= 7;
  166270. }
  166271. entropy->restarts_to_go--;
  166272. }
  166273. return TRUE;
  166274. }
  166275. /*
  166276. * MCU encoding for AC successive approximation refinement scan.
  166277. */
  166278. METHODDEF(boolean)
  166279. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166280. {
  166281. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166282. register int temp;
  166283. register int r, k;
  166284. int EOB;
  166285. char *BR_buffer;
  166286. unsigned int BR;
  166287. int Se = cinfo->Se;
  166288. int Al = cinfo->Al;
  166289. JBLOCKROW block;
  166290. int absvalues[DCTSIZE2];
  166291. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166292. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166293. /* Emit restart marker if needed */
  166294. if (cinfo->restart_interval)
  166295. if (entropy->restarts_to_go == 0)
  166296. emit_restart_p(entropy, entropy->next_restart_num);
  166297. /* Encode the MCU data block */
  166298. block = MCU_data[0];
  166299. /* It is convenient to make a pre-pass to determine the transformed
  166300. * coefficients' absolute values and the EOB position.
  166301. */
  166302. EOB = 0;
  166303. for (k = cinfo->Ss; k <= Se; k++) {
  166304. temp = (*block)[jpeg_natural_order[k]];
  166305. /* We must apply the point transform by Al. For AC coefficients this
  166306. * is an integer division with rounding towards 0. To do this portably
  166307. * in C, we shift after obtaining the absolute value.
  166308. */
  166309. if (temp < 0)
  166310. temp = -temp; /* temp is abs value of input */
  166311. temp >>= Al; /* apply the point transform */
  166312. absvalues[k] = temp; /* save abs value for main pass */
  166313. if (temp == 1)
  166314. EOB = k; /* EOB = index of last newly-nonzero coef */
  166315. }
  166316. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  166317. r = 0; /* r = run length of zeros */
  166318. BR = 0; /* BR = count of buffered bits added now */
  166319. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  166320. for (k = cinfo->Ss; k <= Se; k++) {
  166321. if ((temp = absvalues[k]) == 0) {
  166322. r++;
  166323. continue;
  166324. }
  166325. /* Emit any required ZRLs, but not if they can be folded into EOB */
  166326. while (r > 15 && k <= EOB) {
  166327. /* emit any pending EOBRUN and the BE correction bits */
  166328. emit_eobrun(entropy);
  166329. /* Emit ZRL */
  166330. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  166331. r -= 16;
  166332. /* Emit buffered correction bits that must be associated with ZRL */
  166333. emit_buffered_bits(entropy, BR_buffer, BR);
  166334. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166335. BR = 0;
  166336. }
  166337. /* If the coef was previously nonzero, it only needs a correction bit.
  166338. * NOTE: a straight translation of the spec's figure G.7 would suggest
  166339. * that we also need to test r > 15. But if r > 15, we can only get here
  166340. * if k > EOB, which implies that this coefficient is not 1.
  166341. */
  166342. if (temp > 1) {
  166343. /* The correction bit is the next bit of the absolute value. */
  166344. BR_buffer[BR++] = (char) (temp & 1);
  166345. continue;
  166346. }
  166347. /* Emit any pending EOBRUN and the BE correction bits */
  166348. emit_eobrun(entropy);
  166349. /* Count/emit Huffman symbol for run length / number of bits */
  166350. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  166351. /* Emit output bit for newly-nonzero coef */
  166352. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  166353. emit_bits_p(entropy, (unsigned int) temp, 1);
  166354. /* Emit buffered correction bits that must be associated with this code */
  166355. emit_buffered_bits(entropy, BR_buffer, BR);
  166356. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166357. BR = 0;
  166358. r = 0; /* reset zero run length */
  166359. }
  166360. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  166361. entropy->EOBRUN++; /* count an EOB */
  166362. entropy->BE += BR; /* concat my correction bits to older ones */
  166363. /* We force out the EOB if we risk either:
  166364. * 1. overflow of the EOB counter;
  166365. * 2. overflow of the correction bit buffer during the next MCU.
  166366. */
  166367. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  166368. emit_eobrun(entropy);
  166369. }
  166370. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166371. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166372. /* Update restart-interval state too */
  166373. if (cinfo->restart_interval) {
  166374. if (entropy->restarts_to_go == 0) {
  166375. entropy->restarts_to_go = cinfo->restart_interval;
  166376. entropy->next_restart_num++;
  166377. entropy->next_restart_num &= 7;
  166378. }
  166379. entropy->restarts_to_go--;
  166380. }
  166381. return TRUE;
  166382. }
  166383. /*
  166384. * Finish up at the end of a Huffman-compressed progressive scan.
  166385. */
  166386. METHODDEF(void)
  166387. finish_pass_phuff (j_compress_ptr cinfo)
  166388. {
  166389. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166390. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166391. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166392. /* Flush out any buffered data */
  166393. emit_eobrun(entropy);
  166394. flush_bits_p(entropy);
  166395. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166396. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166397. }
  166398. /*
  166399. * Finish up a statistics-gathering pass and create the new Huffman tables.
  166400. */
  166401. METHODDEF(void)
  166402. finish_pass_gather_phuff (j_compress_ptr cinfo)
  166403. {
  166404. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166405. boolean is_DC_band;
  166406. int ci, tbl;
  166407. jpeg_component_info * compptr;
  166408. JHUFF_TBL **htblptr;
  166409. boolean did[NUM_HUFF_TBLS];
  166410. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  166411. emit_eobrun(entropy);
  166412. is_DC_band = (cinfo->Ss == 0);
  166413. /* It's important not to apply jpeg_gen_optimal_table more than once
  166414. * per table, because it clobbers the input frequency counts!
  166415. */
  166416. MEMZERO(did, SIZEOF(did));
  166417. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166418. compptr = cinfo->cur_comp_info[ci];
  166419. if (is_DC_band) {
  166420. if (cinfo->Ah != 0) /* DC refinement needs no table */
  166421. continue;
  166422. tbl = compptr->dc_tbl_no;
  166423. } else {
  166424. tbl = compptr->ac_tbl_no;
  166425. }
  166426. if (! did[tbl]) {
  166427. if (is_DC_band)
  166428. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  166429. else
  166430. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  166431. if (*htblptr == NULL)
  166432. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  166433. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  166434. did[tbl] = TRUE;
  166435. }
  166436. }
  166437. }
  166438. /*
  166439. * Module initialization routine for progressive Huffman entropy encoding.
  166440. */
  166441. GLOBAL(void)
  166442. jinit_phuff_encoder (j_compress_ptr cinfo)
  166443. {
  166444. phuff_entropy_ptr entropy;
  166445. int i;
  166446. entropy = (phuff_entropy_ptr)
  166447. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166448. SIZEOF(phuff_entropy_encoder));
  166449. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  166450. entropy->pub.start_pass = start_pass_phuff;
  166451. /* Mark tables unallocated */
  166452. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  166453. entropy->derived_tbls[i] = NULL;
  166454. entropy->count_ptrs[i] = NULL;
  166455. }
  166456. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  166457. }
  166458. #endif /* C_PROGRESSIVE_SUPPORTED */
  166459. /*** End of inlined file: jcphuff.c ***/
  166460. /*** Start of inlined file: jcprepct.c ***/
  166461. #define JPEG_INTERNALS
  166462. /* At present, jcsample.c can request context rows only for smoothing.
  166463. * In the future, we might also need context rows for CCIR601 sampling
  166464. * or other more-complex downsampling procedures. The code to support
  166465. * context rows should be compiled only if needed.
  166466. */
  166467. #ifdef INPUT_SMOOTHING_SUPPORTED
  166468. #define CONTEXT_ROWS_SUPPORTED
  166469. #endif
  166470. /*
  166471. * For the simple (no-context-row) case, we just need to buffer one
  166472. * row group's worth of pixels for the downsampling step. At the bottom of
  166473. * the image, we pad to a full row group by replicating the last pixel row.
  166474. * The downsampler's last output row is then replicated if needed to pad
  166475. * out to a full iMCU row.
  166476. *
  166477. * When providing context rows, we must buffer three row groups' worth of
  166478. * pixels. Three row groups are physically allocated, but the row pointer
  166479. * arrays are made five row groups high, with the extra pointers above and
  166480. * below "wrapping around" to point to the last and first real row groups.
  166481. * This allows the downsampler to access the proper context rows.
  166482. * At the top and bottom of the image, we create dummy context rows by
  166483. * copying the first or last real pixel row. This copying could be avoided
  166484. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  166485. * trouble on the compression side.
  166486. */
  166487. /* Private buffer controller object */
  166488. typedef struct {
  166489. struct jpeg_c_prep_controller pub; /* public fields */
  166490. /* Downsampling input buffer. This buffer holds color-converted data
  166491. * until we have enough to do a downsample step.
  166492. */
  166493. JSAMPARRAY color_buf[MAX_COMPONENTS];
  166494. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  166495. int next_buf_row; /* index of next row to store in color_buf */
  166496. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  166497. int this_row_group; /* starting row index of group to process */
  166498. int next_buf_stop; /* downsample when we reach this index */
  166499. #endif
  166500. } my_prep_controller;
  166501. typedef my_prep_controller * my_prep_ptr;
  166502. /*
  166503. * Initialize for a processing pass.
  166504. */
  166505. METHODDEF(void)
  166506. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  166507. {
  166508. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166509. if (pass_mode != JBUF_PASS_THRU)
  166510. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166511. /* Initialize total-height counter for detecting bottom of image */
  166512. prep->rows_to_go = cinfo->image_height;
  166513. /* Mark the conversion buffer empty */
  166514. prep->next_buf_row = 0;
  166515. #ifdef CONTEXT_ROWS_SUPPORTED
  166516. /* Preset additional state variables for context mode.
  166517. * These aren't used in non-context mode, so we needn't test which mode.
  166518. */
  166519. prep->this_row_group = 0;
  166520. /* Set next_buf_stop to stop after two row groups have been read in. */
  166521. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  166522. #endif
  166523. }
  166524. /*
  166525. * Expand an image vertically from height input_rows to height output_rows,
  166526. * by duplicating the bottom row.
  166527. */
  166528. LOCAL(void)
  166529. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  166530. int input_rows, int output_rows)
  166531. {
  166532. register int row;
  166533. for (row = input_rows; row < output_rows; row++) {
  166534. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  166535. 1, num_cols);
  166536. }
  166537. }
  166538. /*
  166539. * Process some data in the simple no-context case.
  166540. *
  166541. * Preprocessor output data is counted in "row groups". A row group
  166542. * is defined to be v_samp_factor sample rows of each component.
  166543. * Downsampling will produce this much data from each max_v_samp_factor
  166544. * input rows.
  166545. */
  166546. METHODDEF(void)
  166547. pre_process_data (j_compress_ptr cinfo,
  166548. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166549. JDIMENSION in_rows_avail,
  166550. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166551. JDIMENSION out_row_groups_avail)
  166552. {
  166553. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166554. int numrows, ci;
  166555. JDIMENSION inrows;
  166556. jpeg_component_info * compptr;
  166557. while (*in_row_ctr < in_rows_avail &&
  166558. *out_row_group_ctr < out_row_groups_avail) {
  166559. /* Do color conversion to fill the conversion buffer. */
  166560. inrows = in_rows_avail - *in_row_ctr;
  166561. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  166562. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166563. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166564. prep->color_buf,
  166565. (JDIMENSION) prep->next_buf_row,
  166566. numrows);
  166567. *in_row_ctr += numrows;
  166568. prep->next_buf_row += numrows;
  166569. prep->rows_to_go -= numrows;
  166570. /* If at bottom of image, pad to fill the conversion buffer. */
  166571. if (prep->rows_to_go == 0 &&
  166572. prep->next_buf_row < cinfo->max_v_samp_factor) {
  166573. for (ci = 0; ci < cinfo->num_components; ci++) {
  166574. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166575. prep->next_buf_row, cinfo->max_v_samp_factor);
  166576. }
  166577. prep->next_buf_row = cinfo->max_v_samp_factor;
  166578. }
  166579. /* If we've filled the conversion buffer, empty it. */
  166580. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  166581. (*cinfo->downsample->downsample) (cinfo,
  166582. prep->color_buf, (JDIMENSION) 0,
  166583. output_buf, *out_row_group_ctr);
  166584. prep->next_buf_row = 0;
  166585. (*out_row_group_ctr)++;
  166586. }
  166587. /* If at bottom of image, pad the output to a full iMCU height.
  166588. * Note we assume the caller is providing a one-iMCU-height output buffer!
  166589. */
  166590. if (prep->rows_to_go == 0 &&
  166591. *out_row_group_ctr < out_row_groups_avail) {
  166592. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166593. ci++, compptr++) {
  166594. expand_bottom_edge(output_buf[ci],
  166595. compptr->width_in_blocks * DCTSIZE,
  166596. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  166597. (int) (out_row_groups_avail * compptr->v_samp_factor));
  166598. }
  166599. *out_row_group_ctr = out_row_groups_avail;
  166600. break; /* can exit outer loop without test */
  166601. }
  166602. }
  166603. }
  166604. #ifdef CONTEXT_ROWS_SUPPORTED
  166605. /*
  166606. * Process some data in the context case.
  166607. */
  166608. METHODDEF(void)
  166609. pre_process_context (j_compress_ptr cinfo,
  166610. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166611. JDIMENSION in_rows_avail,
  166612. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166613. JDIMENSION out_row_groups_avail)
  166614. {
  166615. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166616. int numrows, ci;
  166617. int buf_height = cinfo->max_v_samp_factor * 3;
  166618. JDIMENSION inrows;
  166619. while (*out_row_group_ctr < out_row_groups_avail) {
  166620. if (*in_row_ctr < in_rows_avail) {
  166621. /* Do color conversion to fill the conversion buffer. */
  166622. inrows = in_rows_avail - *in_row_ctr;
  166623. numrows = prep->next_buf_stop - prep->next_buf_row;
  166624. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166625. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166626. prep->color_buf,
  166627. (JDIMENSION) prep->next_buf_row,
  166628. numrows);
  166629. /* Pad at top of image, if first time through */
  166630. if (prep->rows_to_go == cinfo->image_height) {
  166631. for (ci = 0; ci < cinfo->num_components; ci++) {
  166632. int row;
  166633. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  166634. jcopy_sample_rows(prep->color_buf[ci], 0,
  166635. prep->color_buf[ci], -row,
  166636. 1, cinfo->image_width);
  166637. }
  166638. }
  166639. }
  166640. *in_row_ctr += numrows;
  166641. prep->next_buf_row += numrows;
  166642. prep->rows_to_go -= numrows;
  166643. } else {
  166644. /* Return for more data, unless we are at the bottom of the image. */
  166645. if (prep->rows_to_go != 0)
  166646. break;
  166647. /* When at bottom of image, pad to fill the conversion buffer. */
  166648. if (prep->next_buf_row < prep->next_buf_stop) {
  166649. for (ci = 0; ci < cinfo->num_components; ci++) {
  166650. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166651. prep->next_buf_row, prep->next_buf_stop);
  166652. }
  166653. prep->next_buf_row = prep->next_buf_stop;
  166654. }
  166655. }
  166656. /* If we've gotten enough data, downsample a row group. */
  166657. if (prep->next_buf_row == prep->next_buf_stop) {
  166658. (*cinfo->downsample->downsample) (cinfo,
  166659. prep->color_buf,
  166660. (JDIMENSION) prep->this_row_group,
  166661. output_buf, *out_row_group_ctr);
  166662. (*out_row_group_ctr)++;
  166663. /* Advance pointers with wraparound as necessary. */
  166664. prep->this_row_group += cinfo->max_v_samp_factor;
  166665. if (prep->this_row_group >= buf_height)
  166666. prep->this_row_group = 0;
  166667. if (prep->next_buf_row >= buf_height)
  166668. prep->next_buf_row = 0;
  166669. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  166670. }
  166671. }
  166672. }
  166673. /*
  166674. * Create the wrapped-around downsampling input buffer needed for context mode.
  166675. */
  166676. LOCAL(void)
  166677. create_context_buffer (j_compress_ptr cinfo)
  166678. {
  166679. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166680. int rgroup_height = cinfo->max_v_samp_factor;
  166681. int ci, i;
  166682. jpeg_component_info * compptr;
  166683. JSAMPARRAY true_buffer, fake_buffer;
  166684. /* Grab enough space for fake row pointers for all the components;
  166685. * we need five row groups' worth of pointers for each component.
  166686. */
  166687. fake_buffer = (JSAMPARRAY)
  166688. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166689. (cinfo->num_components * 5 * rgroup_height) *
  166690. SIZEOF(JSAMPROW));
  166691. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166692. ci++, compptr++) {
  166693. /* Allocate the actual buffer space (3 row groups) for this component.
  166694. * We make the buffer wide enough to allow the downsampler to edge-expand
  166695. * horizontally within the buffer, if it so chooses.
  166696. */
  166697. true_buffer = (*cinfo->mem->alloc_sarray)
  166698. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166699. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166700. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166701. (JDIMENSION) (3 * rgroup_height));
  166702. /* Copy true buffer row pointers into the middle of the fake row array */
  166703. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  166704. 3 * rgroup_height * SIZEOF(JSAMPROW));
  166705. /* Fill in the above and below wraparound pointers */
  166706. for (i = 0; i < rgroup_height; i++) {
  166707. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  166708. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  166709. }
  166710. prep->color_buf[ci] = fake_buffer + rgroup_height;
  166711. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  166712. }
  166713. }
  166714. #endif /* CONTEXT_ROWS_SUPPORTED */
  166715. /*
  166716. * Initialize preprocessing controller.
  166717. */
  166718. GLOBAL(void)
  166719. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  166720. {
  166721. my_prep_ptr prep;
  166722. int ci;
  166723. jpeg_component_info * compptr;
  166724. if (need_full_buffer) /* safety check */
  166725. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166726. prep = (my_prep_ptr)
  166727. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166728. SIZEOF(my_prep_controller));
  166729. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  166730. prep->pub.start_pass = start_pass_prep;
  166731. /* Allocate the color conversion buffer.
  166732. * We make the buffer wide enough to allow the downsampler to edge-expand
  166733. * horizontally within the buffer, if it so chooses.
  166734. */
  166735. if (cinfo->downsample->need_context_rows) {
  166736. /* Set up to provide context rows */
  166737. #ifdef CONTEXT_ROWS_SUPPORTED
  166738. prep->pub.pre_process_data = pre_process_context;
  166739. create_context_buffer(cinfo);
  166740. #else
  166741. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166742. #endif
  166743. } else {
  166744. /* No context, just make it tall enough for one row group */
  166745. prep->pub.pre_process_data = pre_process_data;
  166746. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166747. ci++, compptr++) {
  166748. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  166749. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166750. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166751. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166752. (JDIMENSION) cinfo->max_v_samp_factor);
  166753. }
  166754. }
  166755. }
  166756. /*** End of inlined file: jcprepct.c ***/
  166757. /*** Start of inlined file: jcsample.c ***/
  166758. #define JPEG_INTERNALS
  166759. /* Pointer to routine to downsample a single component */
  166760. typedef JMETHOD(void, downsample1_ptr,
  166761. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166762. JSAMPARRAY input_data, JSAMPARRAY output_data));
  166763. /* Private subobject */
  166764. typedef struct {
  166765. struct jpeg_downsampler pub; /* public fields */
  166766. /* Downsampling method pointers, one per component */
  166767. downsample1_ptr methods[MAX_COMPONENTS];
  166768. } my_downsampler;
  166769. typedef my_downsampler * my_downsample_ptr;
  166770. /*
  166771. * Initialize for a downsampling pass.
  166772. */
  166773. METHODDEF(void)
  166774. start_pass_downsample (j_compress_ptr)
  166775. {
  166776. /* no work for now */
  166777. }
  166778. /*
  166779. * Expand a component horizontally from width input_cols to width output_cols,
  166780. * by duplicating the rightmost samples.
  166781. */
  166782. LOCAL(void)
  166783. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  166784. JDIMENSION input_cols, JDIMENSION output_cols)
  166785. {
  166786. register JSAMPROW ptr;
  166787. register JSAMPLE pixval;
  166788. register int count;
  166789. int row;
  166790. int numcols = (int) (output_cols - input_cols);
  166791. if (numcols > 0) {
  166792. for (row = 0; row < num_rows; row++) {
  166793. ptr = image_data[row] + input_cols;
  166794. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  166795. for (count = numcols; count > 0; count--)
  166796. *ptr++ = pixval;
  166797. }
  166798. }
  166799. }
  166800. /*
  166801. * Do downsampling for a whole row group (all components).
  166802. *
  166803. * In this version we simply downsample each component independently.
  166804. */
  166805. METHODDEF(void)
  166806. sep_downsample (j_compress_ptr cinfo,
  166807. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  166808. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  166809. {
  166810. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  166811. int ci;
  166812. jpeg_component_info * compptr;
  166813. JSAMPARRAY in_ptr, out_ptr;
  166814. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166815. ci++, compptr++) {
  166816. in_ptr = input_buf[ci] + in_row_index;
  166817. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  166818. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  166819. }
  166820. }
  166821. /*
  166822. * Downsample pixel values of a single component.
  166823. * One row group is processed per call.
  166824. * This version handles arbitrary integral sampling ratios, without smoothing.
  166825. * Note that this version is not actually used for customary sampling ratios.
  166826. */
  166827. METHODDEF(void)
  166828. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166829. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166830. {
  166831. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  166832. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  166833. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166834. JSAMPROW inptr, outptr;
  166835. INT32 outvalue;
  166836. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  166837. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  166838. numpix = h_expand * v_expand;
  166839. numpix2 = numpix/2;
  166840. /* Expand input data enough to let all the output samples be generated
  166841. * by the standard loop. Special-casing padded output would be more
  166842. * efficient.
  166843. */
  166844. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166845. cinfo->image_width, output_cols * h_expand);
  166846. inrow = 0;
  166847. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166848. outptr = output_data[outrow];
  166849. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  166850. outcol++, outcol_h += h_expand) {
  166851. outvalue = 0;
  166852. for (v = 0; v < v_expand; v++) {
  166853. inptr = input_data[inrow+v] + outcol_h;
  166854. for (h = 0; h < h_expand; h++) {
  166855. outvalue += (INT32) GETJSAMPLE(*inptr++);
  166856. }
  166857. }
  166858. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  166859. }
  166860. inrow += v_expand;
  166861. }
  166862. }
  166863. /*
  166864. * Downsample pixel values of a single component.
  166865. * This version handles the special case of a full-size component,
  166866. * without smoothing.
  166867. */
  166868. METHODDEF(void)
  166869. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166870. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166871. {
  166872. /* Copy the data */
  166873. jcopy_sample_rows(input_data, 0, output_data, 0,
  166874. cinfo->max_v_samp_factor, cinfo->image_width);
  166875. /* Edge-expand */
  166876. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  166877. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  166878. }
  166879. /*
  166880. * Downsample pixel values of a single component.
  166881. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  166882. * without smoothing.
  166883. *
  166884. * A note about the "bias" calculations: when rounding fractional values to
  166885. * integer, we do not want to always round 0.5 up to the next integer.
  166886. * If we did that, we'd introduce a noticeable bias towards larger values.
  166887. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  166888. * alternate pixel locations (a simple ordered dither pattern).
  166889. */
  166890. METHODDEF(void)
  166891. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166892. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166893. {
  166894. int outrow;
  166895. JDIMENSION outcol;
  166896. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166897. register JSAMPROW inptr, outptr;
  166898. register int bias;
  166899. /* Expand input data enough to let all the output samples be generated
  166900. * by the standard loop. Special-casing padded output would be more
  166901. * efficient.
  166902. */
  166903. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166904. cinfo->image_width, output_cols * 2);
  166905. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166906. outptr = output_data[outrow];
  166907. inptr = input_data[outrow];
  166908. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  166909. for (outcol = 0; outcol < output_cols; outcol++) {
  166910. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  166911. + bias) >> 1);
  166912. bias ^= 1; /* 0=>1, 1=>0 */
  166913. inptr += 2;
  166914. }
  166915. }
  166916. }
  166917. /*
  166918. * Downsample pixel values of a single component.
  166919. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  166920. * without smoothing.
  166921. */
  166922. METHODDEF(void)
  166923. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166924. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166925. {
  166926. int inrow, outrow;
  166927. JDIMENSION outcol;
  166928. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166929. register JSAMPROW inptr0, inptr1, outptr;
  166930. register int bias;
  166931. /* Expand input data enough to let all the output samples be generated
  166932. * by the standard loop. Special-casing padded output would be more
  166933. * efficient.
  166934. */
  166935. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  166936. cinfo->image_width, output_cols * 2);
  166937. inrow = 0;
  166938. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166939. outptr = output_data[outrow];
  166940. inptr0 = input_data[inrow];
  166941. inptr1 = input_data[inrow+1];
  166942. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  166943. for (outcol = 0; outcol < output_cols; outcol++) {
  166944. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166945. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  166946. + bias) >> 2);
  166947. bias ^= 3; /* 1=>2, 2=>1 */
  166948. inptr0 += 2; inptr1 += 2;
  166949. }
  166950. inrow += 2;
  166951. }
  166952. }
  166953. #ifdef INPUT_SMOOTHING_SUPPORTED
  166954. /*
  166955. * Downsample pixel values of a single component.
  166956. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  166957. * with smoothing. One row of context is required.
  166958. */
  166959. METHODDEF(void)
  166960. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166961. JSAMPARRAY input_data, JSAMPARRAY output_data)
  166962. {
  166963. int inrow, outrow;
  166964. JDIMENSION colctr;
  166965. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  166966. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  166967. INT32 membersum, neighsum, memberscale, neighscale;
  166968. /* Expand input data enough to let all the output samples be generated
  166969. * by the standard loop. Special-casing padded output would be more
  166970. * efficient.
  166971. */
  166972. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  166973. cinfo->image_width, output_cols * 2);
  166974. /* We don't bother to form the individual "smoothed" input pixel values;
  166975. * we can directly compute the output which is the average of the four
  166976. * smoothed values. Each of the four member pixels contributes a fraction
  166977. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  166978. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  166979. * output. The four corner-adjacent neighbor pixels contribute a fraction
  166980. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  166981. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  166982. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  166983. * factors are scaled by 2^16 = 65536.
  166984. * Also recall that SF = smoothing_factor / 1024.
  166985. */
  166986. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  166987. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  166988. inrow = 0;
  166989. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  166990. outptr = output_data[outrow];
  166991. inptr0 = input_data[inrow];
  166992. inptr1 = input_data[inrow+1];
  166993. above_ptr = input_data[inrow-1];
  166994. below_ptr = input_data[inrow+2];
  166995. /* Special case for first column: pretend column -1 is same as column 0 */
  166996. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  166997. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  166998. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  166999. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  167000. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  167001. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  167002. neighsum += neighsum;
  167003. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  167004. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  167005. membersum = membersum * memberscale + neighsum * neighscale;
  167006. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167007. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  167008. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  167009. /* sum of pixels directly mapped to this output element */
  167010. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167011. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  167012. /* sum of edge-neighbor pixels */
  167013. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  167014. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  167015. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  167016. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  167017. /* The edge-neighbors count twice as much as corner-neighbors */
  167018. neighsum += neighsum;
  167019. /* Add in the corner-neighbors */
  167020. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  167021. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  167022. /* form final output scaled up by 2^16 */
  167023. membersum = membersum * memberscale + neighsum * neighscale;
  167024. /* round, descale and output it */
  167025. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167026. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  167027. }
  167028. /* Special case for last column */
  167029. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167030. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  167031. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  167032. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  167033. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  167034. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  167035. neighsum += neighsum;
  167036. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  167037. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  167038. membersum = membersum * memberscale + neighsum * neighscale;
  167039. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  167040. inrow += 2;
  167041. }
  167042. }
  167043. /*
  167044. * Downsample pixel values of a single component.
  167045. * This version handles the special case of a full-size component,
  167046. * with smoothing. One row of context is required.
  167047. */
  167048. METHODDEF(void)
  167049. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  167050. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167051. {
  167052. int outrow;
  167053. JDIMENSION colctr;
  167054. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167055. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  167056. INT32 membersum, neighsum, memberscale, neighscale;
  167057. int colsum, lastcolsum, nextcolsum;
  167058. /* Expand input data enough to let all the output samples be generated
  167059. * by the standard loop. Special-casing padded output would be more
  167060. * efficient.
  167061. */
  167062. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  167063. cinfo->image_width, output_cols);
  167064. /* Each of the eight neighbor pixels contributes a fraction SF to the
  167065. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  167066. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  167067. * Also recall that SF = smoothing_factor / 1024.
  167068. */
  167069. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  167070. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  167071. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167072. outptr = output_data[outrow];
  167073. inptr = input_data[outrow];
  167074. above_ptr = input_data[outrow-1];
  167075. below_ptr = input_data[outrow+1];
  167076. /* Special case for first column */
  167077. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  167078. GETJSAMPLE(*inptr);
  167079. membersum = GETJSAMPLE(*inptr++);
  167080. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  167081. GETJSAMPLE(*inptr);
  167082. neighsum = colsum + (colsum - membersum) + nextcolsum;
  167083. membersum = membersum * memberscale + neighsum * neighscale;
  167084. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167085. lastcolsum = colsum; colsum = nextcolsum;
  167086. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  167087. membersum = GETJSAMPLE(*inptr++);
  167088. above_ptr++; below_ptr++;
  167089. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  167090. GETJSAMPLE(*inptr);
  167091. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  167092. membersum = membersum * memberscale + neighsum * neighscale;
  167093. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167094. lastcolsum = colsum; colsum = nextcolsum;
  167095. }
  167096. /* Special case for last column */
  167097. membersum = GETJSAMPLE(*inptr);
  167098. neighsum = lastcolsum + (colsum - membersum) + colsum;
  167099. membersum = membersum * memberscale + neighsum * neighscale;
  167100. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  167101. }
  167102. }
  167103. #endif /* INPUT_SMOOTHING_SUPPORTED */
  167104. /*
  167105. * Module initialization routine for downsampling.
  167106. * Note that we must select a routine for each component.
  167107. */
  167108. GLOBAL(void)
  167109. jinit_downsampler (j_compress_ptr cinfo)
  167110. {
  167111. my_downsample_ptr downsample;
  167112. int ci;
  167113. jpeg_component_info * compptr;
  167114. boolean smoothok = TRUE;
  167115. downsample = (my_downsample_ptr)
  167116. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167117. SIZEOF(my_downsampler));
  167118. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  167119. downsample->pub.start_pass = start_pass_downsample;
  167120. downsample->pub.downsample = sep_downsample;
  167121. downsample->pub.need_context_rows = FALSE;
  167122. if (cinfo->CCIR601_sampling)
  167123. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  167124. /* Verify we can handle the sampling factors, and set up method pointers */
  167125. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167126. ci++, compptr++) {
  167127. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  167128. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  167129. #ifdef INPUT_SMOOTHING_SUPPORTED
  167130. if (cinfo->smoothing_factor) {
  167131. downsample->methods[ci] = fullsize_smooth_downsample;
  167132. downsample->pub.need_context_rows = TRUE;
  167133. } else
  167134. #endif
  167135. downsample->methods[ci] = fullsize_downsample;
  167136. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  167137. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  167138. smoothok = FALSE;
  167139. downsample->methods[ci] = h2v1_downsample;
  167140. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  167141. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  167142. #ifdef INPUT_SMOOTHING_SUPPORTED
  167143. if (cinfo->smoothing_factor) {
  167144. downsample->methods[ci] = h2v2_smooth_downsample;
  167145. downsample->pub.need_context_rows = TRUE;
  167146. } else
  167147. #endif
  167148. downsample->methods[ci] = h2v2_downsample;
  167149. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  167150. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  167151. smoothok = FALSE;
  167152. downsample->methods[ci] = int_downsample;
  167153. } else
  167154. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  167155. }
  167156. #ifdef INPUT_SMOOTHING_SUPPORTED
  167157. if (cinfo->smoothing_factor && !smoothok)
  167158. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  167159. #endif
  167160. }
  167161. /*** End of inlined file: jcsample.c ***/
  167162. /*** Start of inlined file: jctrans.c ***/
  167163. #define JPEG_INTERNALS
  167164. /* Forward declarations */
  167165. LOCAL(void) transencode_master_selection
  167166. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  167167. LOCAL(void) transencode_coef_controller
  167168. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  167169. /*
  167170. * Compression initialization for writing raw-coefficient data.
  167171. * Before calling this, all parameters and a data destination must be set up.
  167172. * Call jpeg_finish_compress() to actually write the data.
  167173. *
  167174. * The number of passed virtual arrays must match cinfo->num_components.
  167175. * Note that the virtual arrays need not be filled or even realized at
  167176. * the time write_coefficients is called; indeed, if the virtual arrays
  167177. * were requested from this compression object's memory manager, they
  167178. * typically will be realized during this routine and filled afterwards.
  167179. */
  167180. GLOBAL(void)
  167181. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  167182. {
  167183. if (cinfo->global_state != CSTATE_START)
  167184. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167185. /* Mark all tables to be written */
  167186. jpeg_suppress_tables(cinfo, FALSE);
  167187. /* (Re)initialize error mgr and destination modules */
  167188. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  167189. (*cinfo->dest->init_destination) (cinfo);
  167190. /* Perform master selection of active modules */
  167191. transencode_master_selection(cinfo, coef_arrays);
  167192. /* Wait for jpeg_finish_compress() call */
  167193. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  167194. cinfo->global_state = CSTATE_WRCOEFS;
  167195. }
  167196. /*
  167197. * Initialize the compression object with default parameters,
  167198. * then copy from the source object all parameters needed for lossless
  167199. * transcoding. Parameters that can be varied without loss (such as
  167200. * scan script and Huffman optimization) are left in their default states.
  167201. */
  167202. GLOBAL(void)
  167203. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  167204. j_compress_ptr dstinfo)
  167205. {
  167206. JQUANT_TBL ** qtblptr;
  167207. jpeg_component_info *incomp, *outcomp;
  167208. JQUANT_TBL *c_quant, *slot_quant;
  167209. int tblno, ci, coefi;
  167210. /* Safety check to ensure start_compress not called yet. */
  167211. if (dstinfo->global_state != CSTATE_START)
  167212. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  167213. /* Copy fundamental image dimensions */
  167214. dstinfo->image_width = srcinfo->image_width;
  167215. dstinfo->image_height = srcinfo->image_height;
  167216. dstinfo->input_components = srcinfo->num_components;
  167217. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  167218. /* Initialize all parameters to default values */
  167219. jpeg_set_defaults(dstinfo);
  167220. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  167221. * Fix it to get the right header markers for the image colorspace.
  167222. */
  167223. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  167224. dstinfo->data_precision = srcinfo->data_precision;
  167225. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  167226. /* Copy the source's quantization tables. */
  167227. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  167228. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  167229. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  167230. if (*qtblptr == NULL)
  167231. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  167232. MEMCOPY((*qtblptr)->quantval,
  167233. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  167234. SIZEOF((*qtblptr)->quantval));
  167235. (*qtblptr)->sent_table = FALSE;
  167236. }
  167237. }
  167238. /* Copy the source's per-component info.
  167239. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  167240. */
  167241. dstinfo->num_components = srcinfo->num_components;
  167242. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  167243. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  167244. MAX_COMPONENTS);
  167245. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  167246. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  167247. outcomp->component_id = incomp->component_id;
  167248. outcomp->h_samp_factor = incomp->h_samp_factor;
  167249. outcomp->v_samp_factor = incomp->v_samp_factor;
  167250. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  167251. /* Make sure saved quantization table for component matches the qtable
  167252. * slot. If not, the input file re-used this qtable slot.
  167253. * IJG encoder currently cannot duplicate this.
  167254. */
  167255. tblno = outcomp->quant_tbl_no;
  167256. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  167257. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  167258. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  167259. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  167260. c_quant = incomp->quant_table;
  167261. if (c_quant != NULL) {
  167262. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  167263. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  167264. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  167265. }
  167266. }
  167267. /* Note: we do not copy the source's Huffman table assignments;
  167268. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  167269. */
  167270. }
  167271. /* Also copy JFIF version and resolution information, if available.
  167272. * Strictly speaking this isn't "critical" info, but it's nearly
  167273. * always appropriate to copy it if available. In particular,
  167274. * if the application chooses to copy JFIF 1.02 extension markers from
  167275. * the source file, we need to copy the version to make sure we don't
  167276. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  167277. * We will *not*, however, copy version info from mislabeled "2.01" files.
  167278. */
  167279. if (srcinfo->saw_JFIF_marker) {
  167280. if (srcinfo->JFIF_major_version == 1) {
  167281. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  167282. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  167283. }
  167284. dstinfo->density_unit = srcinfo->density_unit;
  167285. dstinfo->X_density = srcinfo->X_density;
  167286. dstinfo->Y_density = srcinfo->Y_density;
  167287. }
  167288. }
  167289. /*
  167290. * Master selection of compression modules for transcoding.
  167291. * This substitutes for jcinit.c's initialization of the full compressor.
  167292. */
  167293. LOCAL(void)
  167294. transencode_master_selection (j_compress_ptr cinfo,
  167295. jvirt_barray_ptr * coef_arrays)
  167296. {
  167297. /* Although we don't actually use input_components for transcoding,
  167298. * jcmaster.c's initial_setup will complain if input_components is 0.
  167299. */
  167300. cinfo->input_components = 1;
  167301. /* Initialize master control (includes parameter checking/processing) */
  167302. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  167303. /* Entropy encoding: either Huffman or arithmetic coding. */
  167304. if (cinfo->arith_code) {
  167305. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  167306. } else {
  167307. if (cinfo->progressive_mode) {
  167308. #ifdef C_PROGRESSIVE_SUPPORTED
  167309. jinit_phuff_encoder(cinfo);
  167310. #else
  167311. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167312. #endif
  167313. } else
  167314. jinit_huff_encoder(cinfo);
  167315. }
  167316. /* We need a special coefficient buffer controller. */
  167317. transencode_coef_controller(cinfo, coef_arrays);
  167318. jinit_marker_writer(cinfo);
  167319. /* We can now tell the memory manager to allocate virtual arrays. */
  167320. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  167321. /* Write the datastream header (SOI, JFIF) immediately.
  167322. * Frame and scan headers are postponed till later.
  167323. * This lets application insert special markers after the SOI.
  167324. */
  167325. (*cinfo->marker->write_file_header) (cinfo);
  167326. }
  167327. /*
  167328. * The rest of this file is a special implementation of the coefficient
  167329. * buffer controller. This is similar to jccoefct.c, but it handles only
  167330. * output from presupplied virtual arrays. Furthermore, we generate any
  167331. * dummy padding blocks on-the-fly rather than expecting them to be present
  167332. * in the arrays.
  167333. */
  167334. /* Private buffer controller object */
  167335. typedef struct {
  167336. struct jpeg_c_coef_controller pub; /* public fields */
  167337. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  167338. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  167339. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  167340. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  167341. /* Virtual block array for each component. */
  167342. jvirt_barray_ptr * whole_image;
  167343. /* Workspace for constructing dummy blocks at right/bottom edges. */
  167344. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  167345. } my_coef_controller2;
  167346. typedef my_coef_controller2 * my_coef_ptr2;
  167347. LOCAL(void)
  167348. start_iMCU_row2 (j_compress_ptr cinfo)
  167349. /* Reset within-iMCU-row counters for a new row */
  167350. {
  167351. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167352. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  167353. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  167354. * But at the bottom of the image, process only what's left.
  167355. */
  167356. if (cinfo->comps_in_scan > 1) {
  167357. coef->MCU_rows_per_iMCU_row = 1;
  167358. } else {
  167359. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  167360. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  167361. else
  167362. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  167363. }
  167364. coef->mcu_ctr = 0;
  167365. coef->MCU_vert_offset = 0;
  167366. }
  167367. /*
  167368. * Initialize for a processing pass.
  167369. */
  167370. METHODDEF(void)
  167371. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  167372. {
  167373. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167374. if (pass_mode != JBUF_CRANK_DEST)
  167375. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167376. coef->iMCU_row_num = 0;
  167377. start_iMCU_row2(cinfo);
  167378. }
  167379. /*
  167380. * Process some data.
  167381. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  167382. * per call, ie, v_samp_factor block rows for each component in the scan.
  167383. * The data is obtained from the virtual arrays and fed to the entropy coder.
  167384. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  167385. *
  167386. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  167387. */
  167388. METHODDEF(boolean)
  167389. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE)
  167390. {
  167391. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167392. JDIMENSION MCU_col_num; /* index of current MCU within row */
  167393. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  167394. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  167395. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  167396. JDIMENSION start_col;
  167397. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  167398. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  167399. JBLOCKROW buffer_ptr;
  167400. jpeg_component_info *compptr;
  167401. /* Align the virtual buffers for the components used in this scan. */
  167402. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167403. compptr = cinfo->cur_comp_info[ci];
  167404. buffer[ci] = (*cinfo->mem->access_virt_barray)
  167405. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  167406. coef->iMCU_row_num * compptr->v_samp_factor,
  167407. (JDIMENSION) compptr->v_samp_factor, FALSE);
  167408. }
  167409. /* Loop to process one whole iMCU row */
  167410. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  167411. yoffset++) {
  167412. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  167413. MCU_col_num++) {
  167414. /* Construct list of pointers to DCT blocks belonging to this MCU */
  167415. blkn = 0; /* index of current DCT block within MCU */
  167416. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167417. compptr = cinfo->cur_comp_info[ci];
  167418. start_col = MCU_col_num * compptr->MCU_width;
  167419. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  167420. : compptr->last_col_width;
  167421. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  167422. if (coef->iMCU_row_num < last_iMCU_row ||
  167423. yindex+yoffset < compptr->last_row_height) {
  167424. /* Fill in pointers to real blocks in this row */
  167425. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  167426. for (xindex = 0; xindex < blockcnt; xindex++)
  167427. MCU_buffer[blkn++] = buffer_ptr++;
  167428. } else {
  167429. /* At bottom of image, need a whole row of dummy blocks */
  167430. xindex = 0;
  167431. }
  167432. /* Fill in any dummy blocks needed in this row.
  167433. * Dummy blocks are filled in the same way as in jccoefct.c:
  167434. * all zeroes in the AC entries, DC entries equal to previous
  167435. * block's DC value. The init routine has already zeroed the
  167436. * AC entries, so we need only set the DC entries correctly.
  167437. */
  167438. for (; xindex < compptr->MCU_width; xindex++) {
  167439. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  167440. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  167441. blkn++;
  167442. }
  167443. }
  167444. }
  167445. /* Try to write the MCU. */
  167446. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  167447. /* Suspension forced; update state counters and exit */
  167448. coef->MCU_vert_offset = yoffset;
  167449. coef->mcu_ctr = MCU_col_num;
  167450. return FALSE;
  167451. }
  167452. }
  167453. /* Completed an MCU row, but perhaps not an iMCU row */
  167454. coef->mcu_ctr = 0;
  167455. }
  167456. /* Completed the iMCU row, advance counters for next one */
  167457. coef->iMCU_row_num++;
  167458. start_iMCU_row2(cinfo);
  167459. return TRUE;
  167460. }
  167461. /*
  167462. * Initialize coefficient buffer controller.
  167463. *
  167464. * Each passed coefficient array must be the right size for that
  167465. * coefficient: width_in_blocks wide and height_in_blocks high,
  167466. * with unitheight at least v_samp_factor.
  167467. */
  167468. LOCAL(void)
  167469. transencode_coef_controller (j_compress_ptr cinfo,
  167470. jvirt_barray_ptr * coef_arrays)
  167471. {
  167472. my_coef_ptr2 coef;
  167473. JBLOCKROW buffer;
  167474. int i;
  167475. coef = (my_coef_ptr2)
  167476. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167477. SIZEOF(my_coef_controller2));
  167478. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  167479. coef->pub.start_pass = start_pass_coef2;
  167480. coef->pub.compress_data = compress_output2;
  167481. /* Save pointer to virtual arrays */
  167482. coef->whole_image = coef_arrays;
  167483. /* Allocate and pre-zero space for dummy DCT blocks. */
  167484. buffer = (JBLOCKROW)
  167485. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167486. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167487. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167488. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  167489. coef->dummy_buffer[i] = buffer + i;
  167490. }
  167491. }
  167492. /*** End of inlined file: jctrans.c ***/
  167493. /*** Start of inlined file: jdapistd.c ***/
  167494. #define JPEG_INTERNALS
  167495. /* Forward declarations */
  167496. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  167497. /*
  167498. * Decompression initialization.
  167499. * jpeg_read_header must be completed before calling this.
  167500. *
  167501. * If a multipass operating mode was selected, this will do all but the
  167502. * last pass, and thus may take a great deal of time.
  167503. *
  167504. * Returns FALSE if suspended. The return value need be inspected only if
  167505. * a suspending data source is used.
  167506. */
  167507. GLOBAL(boolean)
  167508. jpeg_start_decompress (j_decompress_ptr cinfo)
  167509. {
  167510. if (cinfo->global_state == DSTATE_READY) {
  167511. /* First call: initialize master control, select active modules */
  167512. jinit_master_decompress(cinfo);
  167513. if (cinfo->buffered_image) {
  167514. /* No more work here; expecting jpeg_start_output next */
  167515. cinfo->global_state = DSTATE_BUFIMAGE;
  167516. return TRUE;
  167517. }
  167518. cinfo->global_state = DSTATE_PRELOAD;
  167519. }
  167520. if (cinfo->global_state == DSTATE_PRELOAD) {
  167521. /* If file has multiple scans, absorb them all into the coef buffer */
  167522. if (cinfo->inputctl->has_multiple_scans) {
  167523. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167524. for (;;) {
  167525. int retcode;
  167526. /* Call progress monitor hook if present */
  167527. if (cinfo->progress != NULL)
  167528. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167529. /* Absorb some more input */
  167530. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167531. if (retcode == JPEG_SUSPENDED)
  167532. return FALSE;
  167533. if (retcode == JPEG_REACHED_EOI)
  167534. break;
  167535. /* Advance progress counter if appropriate */
  167536. if (cinfo->progress != NULL &&
  167537. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  167538. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  167539. /* jdmaster underestimated number of scans; ratchet up one scan */
  167540. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  167541. }
  167542. }
  167543. }
  167544. #else
  167545. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167546. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167547. }
  167548. cinfo->output_scan_number = cinfo->input_scan_number;
  167549. } else if (cinfo->global_state != DSTATE_PRESCAN)
  167550. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167551. /* Perform any dummy output passes, and set up for the final pass */
  167552. return output_pass_setup(cinfo);
  167553. }
  167554. /*
  167555. * Set up for an output pass, and perform any dummy pass(es) needed.
  167556. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  167557. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  167558. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  167559. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  167560. */
  167561. LOCAL(boolean)
  167562. output_pass_setup (j_decompress_ptr cinfo)
  167563. {
  167564. if (cinfo->global_state != DSTATE_PRESCAN) {
  167565. /* First call: do pass setup */
  167566. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167567. cinfo->output_scanline = 0;
  167568. cinfo->global_state = DSTATE_PRESCAN;
  167569. }
  167570. /* Loop over any required dummy passes */
  167571. while (cinfo->master->is_dummy_pass) {
  167572. #ifdef QUANT_2PASS_SUPPORTED
  167573. /* Crank through the dummy pass */
  167574. while (cinfo->output_scanline < cinfo->output_height) {
  167575. JDIMENSION last_scanline;
  167576. /* Call progress monitor hook if present */
  167577. if (cinfo->progress != NULL) {
  167578. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167579. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167580. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167581. }
  167582. /* Process some data */
  167583. last_scanline = cinfo->output_scanline;
  167584. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  167585. &cinfo->output_scanline, (JDIMENSION) 0);
  167586. if (cinfo->output_scanline == last_scanline)
  167587. return FALSE; /* No progress made, must suspend */
  167588. }
  167589. /* Finish up dummy pass, and set up for another one */
  167590. (*cinfo->master->finish_output_pass) (cinfo);
  167591. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167592. cinfo->output_scanline = 0;
  167593. #else
  167594. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167595. #endif /* QUANT_2PASS_SUPPORTED */
  167596. }
  167597. /* Ready for application to drive output pass through
  167598. * jpeg_read_scanlines or jpeg_read_raw_data.
  167599. */
  167600. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  167601. return TRUE;
  167602. }
  167603. /*
  167604. * Read some scanlines of data from the JPEG decompressor.
  167605. *
  167606. * The return value will be the number of lines actually read.
  167607. * This may be less than the number requested in several cases,
  167608. * including bottom of image, data source suspension, and operating
  167609. * modes that emit multiple scanlines at a time.
  167610. *
  167611. * Note: we warn about excess calls to jpeg_read_scanlines() since
  167612. * this likely signals an application programmer error. However,
  167613. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  167614. */
  167615. GLOBAL(JDIMENSION)
  167616. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  167617. JDIMENSION max_lines)
  167618. {
  167619. JDIMENSION row_ctr;
  167620. if (cinfo->global_state != DSTATE_SCANNING)
  167621. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167622. if (cinfo->output_scanline >= cinfo->output_height) {
  167623. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167624. return 0;
  167625. }
  167626. /* Call progress monitor hook if present */
  167627. if (cinfo->progress != NULL) {
  167628. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167629. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167630. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167631. }
  167632. /* Process some data */
  167633. row_ctr = 0;
  167634. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  167635. cinfo->output_scanline += row_ctr;
  167636. return row_ctr;
  167637. }
  167638. /*
  167639. * Alternate entry point to read raw data.
  167640. * Processes exactly one iMCU row per call, unless suspended.
  167641. */
  167642. GLOBAL(JDIMENSION)
  167643. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  167644. JDIMENSION max_lines)
  167645. {
  167646. JDIMENSION lines_per_iMCU_row;
  167647. if (cinfo->global_state != DSTATE_RAW_OK)
  167648. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167649. if (cinfo->output_scanline >= cinfo->output_height) {
  167650. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167651. return 0;
  167652. }
  167653. /* Call progress monitor hook if present */
  167654. if (cinfo->progress != NULL) {
  167655. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167656. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167657. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167658. }
  167659. /* Verify that at least one iMCU row can be returned. */
  167660. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  167661. if (max_lines < lines_per_iMCU_row)
  167662. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  167663. /* Decompress directly into user's buffer. */
  167664. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  167665. return 0; /* suspension forced, can do nothing more */
  167666. /* OK, we processed one iMCU row. */
  167667. cinfo->output_scanline += lines_per_iMCU_row;
  167668. return lines_per_iMCU_row;
  167669. }
  167670. /* Additional entry points for buffered-image mode. */
  167671. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167672. /*
  167673. * Initialize for an output pass in buffered-image mode.
  167674. */
  167675. GLOBAL(boolean)
  167676. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  167677. {
  167678. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  167679. cinfo->global_state != DSTATE_PRESCAN)
  167680. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167681. /* Limit scan number to valid range */
  167682. if (scan_number <= 0)
  167683. scan_number = 1;
  167684. if (cinfo->inputctl->eoi_reached &&
  167685. scan_number > cinfo->input_scan_number)
  167686. scan_number = cinfo->input_scan_number;
  167687. cinfo->output_scan_number = scan_number;
  167688. /* Perform any dummy output passes, and set up for the real pass */
  167689. return output_pass_setup(cinfo);
  167690. }
  167691. /*
  167692. * Finish up after an output pass in buffered-image mode.
  167693. *
  167694. * Returns FALSE if suspended. The return value need be inspected only if
  167695. * a suspending data source is used.
  167696. */
  167697. GLOBAL(boolean)
  167698. jpeg_finish_output (j_decompress_ptr cinfo)
  167699. {
  167700. if ((cinfo->global_state == DSTATE_SCANNING ||
  167701. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  167702. /* Terminate this pass. */
  167703. /* We do not require the whole pass to have been completed. */
  167704. (*cinfo->master->finish_output_pass) (cinfo);
  167705. cinfo->global_state = DSTATE_BUFPOST;
  167706. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  167707. /* BUFPOST = repeat call after a suspension, anything else is error */
  167708. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167709. }
  167710. /* Read markers looking for SOS or EOI */
  167711. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  167712. ! cinfo->inputctl->eoi_reached) {
  167713. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167714. return FALSE; /* Suspend, come back later */
  167715. }
  167716. cinfo->global_state = DSTATE_BUFIMAGE;
  167717. return TRUE;
  167718. }
  167719. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167720. /*** End of inlined file: jdapistd.c ***/
  167721. /*** Start of inlined file: jdapimin.c ***/
  167722. #define JPEG_INTERNALS
  167723. /*
  167724. * Initialization of a JPEG decompression object.
  167725. * The error manager must already be set up (in case memory manager fails).
  167726. */
  167727. GLOBAL(void)
  167728. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  167729. {
  167730. int i;
  167731. /* Guard against version mismatches between library and caller. */
  167732. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  167733. if (version != JPEG_LIB_VERSION)
  167734. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  167735. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  167736. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  167737. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  167738. /* For debugging purposes, we zero the whole master structure.
  167739. * But the application has already set the err pointer, and may have set
  167740. * client_data, so we have to save and restore those fields.
  167741. * Note: if application hasn't set client_data, tools like Purify may
  167742. * complain here.
  167743. */
  167744. {
  167745. struct jpeg_error_mgr * err = cinfo->err;
  167746. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  167747. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  167748. cinfo->err = err;
  167749. cinfo->client_data = client_data;
  167750. }
  167751. cinfo->is_decompressor = TRUE;
  167752. /* Initialize a memory manager instance for this object */
  167753. jinit_memory_mgr((j_common_ptr) cinfo);
  167754. /* Zero out pointers to permanent structures. */
  167755. cinfo->progress = NULL;
  167756. cinfo->src = NULL;
  167757. for (i = 0; i < NUM_QUANT_TBLS; i++)
  167758. cinfo->quant_tbl_ptrs[i] = NULL;
  167759. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  167760. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  167761. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  167762. }
  167763. /* Initialize marker processor so application can override methods
  167764. * for COM, APPn markers before calling jpeg_read_header.
  167765. */
  167766. cinfo->marker_list = NULL;
  167767. jinit_marker_reader(cinfo);
  167768. /* And initialize the overall input controller. */
  167769. jinit_input_controller(cinfo);
  167770. /* OK, I'm ready */
  167771. cinfo->global_state = DSTATE_START;
  167772. }
  167773. /*
  167774. * Destruction of a JPEG decompression object
  167775. */
  167776. GLOBAL(void)
  167777. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  167778. {
  167779. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  167780. }
  167781. /*
  167782. * Abort processing of a JPEG decompression operation,
  167783. * but don't destroy the object itself.
  167784. */
  167785. GLOBAL(void)
  167786. jpeg_abort_decompress (j_decompress_ptr cinfo)
  167787. {
  167788. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  167789. }
  167790. /*
  167791. * Set default decompression parameters.
  167792. */
  167793. LOCAL(void)
  167794. default_decompress_parms (j_decompress_ptr cinfo)
  167795. {
  167796. /* Guess the input colorspace, and set output colorspace accordingly. */
  167797. /* (Wish JPEG committee had provided a real way to specify this...) */
  167798. /* Note application may override our guesses. */
  167799. switch (cinfo->num_components) {
  167800. case 1:
  167801. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  167802. cinfo->out_color_space = JCS_GRAYSCALE;
  167803. break;
  167804. case 3:
  167805. if (cinfo->saw_JFIF_marker) {
  167806. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  167807. } else if (cinfo->saw_Adobe_marker) {
  167808. switch (cinfo->Adobe_transform) {
  167809. case 0:
  167810. cinfo->jpeg_color_space = JCS_RGB;
  167811. break;
  167812. case 1:
  167813. cinfo->jpeg_color_space = JCS_YCbCr;
  167814. break;
  167815. default:
  167816. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  167817. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  167818. break;
  167819. }
  167820. } else {
  167821. /* Saw no special markers, try to guess from the component IDs */
  167822. int cid0 = cinfo->comp_info[0].component_id;
  167823. int cid1 = cinfo->comp_info[1].component_id;
  167824. int cid2 = cinfo->comp_info[2].component_id;
  167825. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  167826. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  167827. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  167828. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  167829. else {
  167830. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  167831. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  167832. }
  167833. }
  167834. /* Always guess RGB is proper output colorspace. */
  167835. cinfo->out_color_space = JCS_RGB;
  167836. break;
  167837. case 4:
  167838. if (cinfo->saw_Adobe_marker) {
  167839. switch (cinfo->Adobe_transform) {
  167840. case 0:
  167841. cinfo->jpeg_color_space = JCS_CMYK;
  167842. break;
  167843. case 2:
  167844. cinfo->jpeg_color_space = JCS_YCCK;
  167845. break;
  167846. default:
  167847. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  167848. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  167849. break;
  167850. }
  167851. } else {
  167852. /* No special markers, assume straight CMYK. */
  167853. cinfo->jpeg_color_space = JCS_CMYK;
  167854. }
  167855. cinfo->out_color_space = JCS_CMYK;
  167856. break;
  167857. default:
  167858. cinfo->jpeg_color_space = JCS_UNKNOWN;
  167859. cinfo->out_color_space = JCS_UNKNOWN;
  167860. break;
  167861. }
  167862. /* Set defaults for other decompression parameters. */
  167863. cinfo->scale_num = 1; /* 1:1 scaling */
  167864. cinfo->scale_denom = 1;
  167865. cinfo->output_gamma = 1.0;
  167866. cinfo->buffered_image = FALSE;
  167867. cinfo->raw_data_out = FALSE;
  167868. cinfo->dct_method = JDCT_DEFAULT;
  167869. cinfo->do_fancy_upsampling = TRUE;
  167870. cinfo->do_block_smoothing = TRUE;
  167871. cinfo->quantize_colors = FALSE;
  167872. /* We set these in case application only sets quantize_colors. */
  167873. cinfo->dither_mode = JDITHER_FS;
  167874. #ifdef QUANT_2PASS_SUPPORTED
  167875. cinfo->two_pass_quantize = TRUE;
  167876. #else
  167877. cinfo->two_pass_quantize = FALSE;
  167878. #endif
  167879. cinfo->desired_number_of_colors = 256;
  167880. cinfo->colormap = NULL;
  167881. /* Initialize for no mode change in buffered-image mode. */
  167882. cinfo->enable_1pass_quant = FALSE;
  167883. cinfo->enable_external_quant = FALSE;
  167884. cinfo->enable_2pass_quant = FALSE;
  167885. }
  167886. /*
  167887. * Decompression startup: read start of JPEG datastream to see what's there.
  167888. * Need only initialize JPEG object and supply a data source before calling.
  167889. *
  167890. * This routine will read as far as the first SOS marker (ie, actual start of
  167891. * compressed data), and will save all tables and parameters in the JPEG
  167892. * object. It will also initialize the decompression parameters to default
  167893. * values, and finally return JPEG_HEADER_OK. On return, the application may
  167894. * adjust the decompression parameters and then call jpeg_start_decompress.
  167895. * (Or, if the application only wanted to determine the image parameters,
  167896. * the data need not be decompressed. In that case, call jpeg_abort or
  167897. * jpeg_destroy to release any temporary space.)
  167898. * If an abbreviated (tables only) datastream is presented, the routine will
  167899. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  167900. * re-use the JPEG object to read the abbreviated image datastream(s).
  167901. * It is unnecessary (but OK) to call jpeg_abort in this case.
  167902. * The JPEG_SUSPENDED return code only occurs if the data source module
  167903. * requests suspension of the decompressor. In this case the application
  167904. * should load more source data and then re-call jpeg_read_header to resume
  167905. * processing.
  167906. * If a non-suspending data source is used and require_image is TRUE, then the
  167907. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  167908. *
  167909. * This routine is now just a front end to jpeg_consume_input, with some
  167910. * extra error checking.
  167911. */
  167912. GLOBAL(int)
  167913. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  167914. {
  167915. int retcode;
  167916. if (cinfo->global_state != DSTATE_START &&
  167917. cinfo->global_state != DSTATE_INHEADER)
  167918. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167919. retcode = jpeg_consume_input(cinfo);
  167920. switch (retcode) {
  167921. case JPEG_REACHED_SOS:
  167922. retcode = JPEG_HEADER_OK;
  167923. break;
  167924. case JPEG_REACHED_EOI:
  167925. if (require_image) /* Complain if application wanted an image */
  167926. ERREXIT(cinfo, JERR_NO_IMAGE);
  167927. /* Reset to start state; it would be safer to require the application to
  167928. * call jpeg_abort, but we can't change it now for compatibility reasons.
  167929. * A side effect is to free any temporary memory (there shouldn't be any).
  167930. */
  167931. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  167932. retcode = JPEG_HEADER_TABLES_ONLY;
  167933. break;
  167934. case JPEG_SUSPENDED:
  167935. /* no work */
  167936. break;
  167937. }
  167938. return retcode;
  167939. }
  167940. /*
  167941. * Consume data in advance of what the decompressor requires.
  167942. * This can be called at any time once the decompressor object has
  167943. * been created and a data source has been set up.
  167944. *
  167945. * This routine is essentially a state machine that handles a couple
  167946. * of critical state-transition actions, namely initial setup and
  167947. * transition from header scanning to ready-for-start_decompress.
  167948. * All the actual input is done via the input controller's consume_input
  167949. * method.
  167950. */
  167951. GLOBAL(int)
  167952. jpeg_consume_input (j_decompress_ptr cinfo)
  167953. {
  167954. int retcode = JPEG_SUSPENDED;
  167955. /* NB: every possible DSTATE value should be listed in this switch */
  167956. switch (cinfo->global_state) {
  167957. case DSTATE_START:
  167958. /* Start-of-datastream actions: reset appropriate modules */
  167959. (*cinfo->inputctl->reset_input_controller) (cinfo);
  167960. /* Initialize application's data source module */
  167961. (*cinfo->src->init_source) (cinfo);
  167962. cinfo->global_state = DSTATE_INHEADER;
  167963. /*FALLTHROUGH*/
  167964. case DSTATE_INHEADER:
  167965. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167966. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  167967. /* Set up default parameters based on header data */
  167968. default_decompress_parms(cinfo);
  167969. /* Set global state: ready for start_decompress */
  167970. cinfo->global_state = DSTATE_READY;
  167971. }
  167972. break;
  167973. case DSTATE_READY:
  167974. /* Can't advance past first SOS until start_decompress is called */
  167975. retcode = JPEG_REACHED_SOS;
  167976. break;
  167977. case DSTATE_PRELOAD:
  167978. case DSTATE_PRESCAN:
  167979. case DSTATE_SCANNING:
  167980. case DSTATE_RAW_OK:
  167981. case DSTATE_BUFIMAGE:
  167982. case DSTATE_BUFPOST:
  167983. case DSTATE_STOPPING:
  167984. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167985. break;
  167986. default:
  167987. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167988. }
  167989. return retcode;
  167990. }
  167991. /*
  167992. * Have we finished reading the input file?
  167993. */
  167994. GLOBAL(boolean)
  167995. jpeg_input_complete (j_decompress_ptr cinfo)
  167996. {
  167997. /* Check for valid jpeg object */
  167998. if (cinfo->global_state < DSTATE_START ||
  167999. cinfo->global_state > DSTATE_STOPPING)
  168000. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168001. return cinfo->inputctl->eoi_reached;
  168002. }
  168003. /*
  168004. * Is there more than one scan?
  168005. */
  168006. GLOBAL(boolean)
  168007. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  168008. {
  168009. /* Only valid after jpeg_read_header completes */
  168010. if (cinfo->global_state < DSTATE_READY ||
  168011. cinfo->global_state > DSTATE_STOPPING)
  168012. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168013. return cinfo->inputctl->has_multiple_scans;
  168014. }
  168015. /*
  168016. * Finish JPEG decompression.
  168017. *
  168018. * This will normally just verify the file trailer and release temp storage.
  168019. *
  168020. * Returns FALSE if suspended. The return value need be inspected only if
  168021. * a suspending data source is used.
  168022. */
  168023. GLOBAL(boolean)
  168024. jpeg_finish_decompress (j_decompress_ptr cinfo)
  168025. {
  168026. if ((cinfo->global_state == DSTATE_SCANNING ||
  168027. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  168028. /* Terminate final pass of non-buffered mode */
  168029. if (cinfo->output_scanline < cinfo->output_height)
  168030. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  168031. (*cinfo->master->finish_output_pass) (cinfo);
  168032. cinfo->global_state = DSTATE_STOPPING;
  168033. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  168034. /* Finishing after a buffered-image operation */
  168035. cinfo->global_state = DSTATE_STOPPING;
  168036. } else if (cinfo->global_state != DSTATE_STOPPING) {
  168037. /* STOPPING = repeat call after a suspension, anything else is error */
  168038. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168039. }
  168040. /* Read until EOI */
  168041. while (! cinfo->inputctl->eoi_reached) {
  168042. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  168043. return FALSE; /* Suspend, come back later */
  168044. }
  168045. /* Do final cleanup */
  168046. (*cinfo->src->term_source) (cinfo);
  168047. /* We can use jpeg_abort to release memory and reset global_state */
  168048. jpeg_abort((j_common_ptr) cinfo);
  168049. return TRUE;
  168050. }
  168051. /*** End of inlined file: jdapimin.c ***/
  168052. /*** Start of inlined file: jdatasrc.c ***/
  168053. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  168054. /*** Start of inlined file: jerror.h ***/
  168055. /*
  168056. * To define the enum list of message codes, include this file without
  168057. * defining macro JMESSAGE. To create a message string table, include it
  168058. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  168059. */
  168060. #ifndef JMESSAGE
  168061. #ifndef JERROR_H
  168062. /* First time through, define the enum list */
  168063. #define JMAKE_ENUM_LIST
  168064. #else
  168065. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  168066. #define JMESSAGE(code,string)
  168067. #endif /* JERROR_H */
  168068. #endif /* JMESSAGE */
  168069. #ifdef JMAKE_ENUM_LIST
  168070. typedef enum {
  168071. #define JMESSAGE(code,string) code ,
  168072. #endif /* JMAKE_ENUM_LIST */
  168073. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  168074. /* For maintenance convenience, list is alphabetical by message code name */
  168075. JMESSAGE(JERR_ARITH_NOTIMPL,
  168076. "Sorry, there are legal restrictions on arithmetic coding")
  168077. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  168078. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  168079. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  168080. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  168081. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  168082. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  168083. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  168084. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  168085. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  168086. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  168087. JMESSAGE(JERR_BAD_LIB_VERSION,
  168088. "Wrong JPEG library version: library is %d, caller expects %d")
  168089. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  168090. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  168091. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  168092. JMESSAGE(JERR_BAD_PROGRESSION,
  168093. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  168094. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  168095. "Invalid progressive parameters at scan script entry %d")
  168096. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  168097. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  168098. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  168099. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  168100. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  168101. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  168102. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  168103. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  168104. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  168105. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  168106. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  168107. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  168108. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  168109. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  168110. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  168111. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  168112. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  168113. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  168114. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  168115. JMESSAGE(JERR_FILE_READ, "Input file read error")
  168116. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  168117. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  168118. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  168119. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  168120. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  168121. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  168122. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  168123. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  168124. "Cannot transcode due to multiple use of quantization table %d")
  168125. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  168126. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  168127. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  168128. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  168129. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  168130. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  168131. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  168132. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  168133. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  168134. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  168135. JMESSAGE(JERR_QUANT_COMPONENTS,
  168136. "Cannot quantize more than %d color components")
  168137. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  168138. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  168139. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  168140. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  168141. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  168142. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  168143. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  168144. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  168145. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  168146. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  168147. JMESSAGE(JERR_TFILE_WRITE,
  168148. "Write failed on temporary file --- out of disk space?")
  168149. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  168150. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  168151. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  168152. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  168153. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  168154. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  168155. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  168156. JMESSAGE(JMSG_VERSION, JVERSION)
  168157. JMESSAGE(JTRC_16BIT_TABLES,
  168158. "Caution: quantization tables are too coarse for baseline JPEG")
  168159. JMESSAGE(JTRC_ADOBE,
  168160. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  168161. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  168162. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  168163. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  168164. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  168165. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  168166. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  168167. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  168168. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  168169. JMESSAGE(JTRC_EOI, "End Of Image")
  168170. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  168171. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  168172. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  168173. "Warning: thumbnail image size does not match data length %u")
  168174. JMESSAGE(JTRC_JFIF_EXTENSION,
  168175. "JFIF extension marker: type 0x%02x, length %u")
  168176. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  168177. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  168178. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  168179. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  168180. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  168181. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  168182. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  168183. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  168184. JMESSAGE(JTRC_RST, "RST%d")
  168185. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  168186. "Smoothing not supported with nonstandard sampling ratios")
  168187. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  168188. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  168189. JMESSAGE(JTRC_SOI, "Start of Image")
  168190. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  168191. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  168192. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  168193. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  168194. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  168195. JMESSAGE(JTRC_THUMB_JPEG,
  168196. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  168197. JMESSAGE(JTRC_THUMB_PALETTE,
  168198. "JFIF extension marker: palette thumbnail image, length %u")
  168199. JMESSAGE(JTRC_THUMB_RGB,
  168200. "JFIF extension marker: RGB thumbnail image, length %u")
  168201. JMESSAGE(JTRC_UNKNOWN_IDS,
  168202. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  168203. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  168204. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  168205. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  168206. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  168207. "Inconsistent progression sequence for component %d coefficient %d")
  168208. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  168209. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  168210. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  168211. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  168212. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  168213. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  168214. JMESSAGE(JWRN_MUST_RESYNC,
  168215. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  168216. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  168217. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  168218. #ifdef JMAKE_ENUM_LIST
  168219. JMSG_LASTMSGCODE
  168220. } J_MESSAGE_CODE;
  168221. #undef JMAKE_ENUM_LIST
  168222. #endif /* JMAKE_ENUM_LIST */
  168223. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  168224. #undef JMESSAGE
  168225. #ifndef JERROR_H
  168226. #define JERROR_H
  168227. /* Macros to simplify using the error and trace message stuff */
  168228. /* The first parameter is either type of cinfo pointer */
  168229. /* Fatal errors (print message and exit) */
  168230. #define ERREXIT(cinfo,code) \
  168231. ((cinfo)->err->msg_code = (code), \
  168232. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168233. #define ERREXIT1(cinfo,code,p1) \
  168234. ((cinfo)->err->msg_code = (code), \
  168235. (cinfo)->err->msg_parm.i[0] = (p1), \
  168236. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168237. #define ERREXIT2(cinfo,code,p1,p2) \
  168238. ((cinfo)->err->msg_code = (code), \
  168239. (cinfo)->err->msg_parm.i[0] = (p1), \
  168240. (cinfo)->err->msg_parm.i[1] = (p2), \
  168241. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168242. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  168243. ((cinfo)->err->msg_code = (code), \
  168244. (cinfo)->err->msg_parm.i[0] = (p1), \
  168245. (cinfo)->err->msg_parm.i[1] = (p2), \
  168246. (cinfo)->err->msg_parm.i[2] = (p3), \
  168247. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168248. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  168249. ((cinfo)->err->msg_code = (code), \
  168250. (cinfo)->err->msg_parm.i[0] = (p1), \
  168251. (cinfo)->err->msg_parm.i[1] = (p2), \
  168252. (cinfo)->err->msg_parm.i[2] = (p3), \
  168253. (cinfo)->err->msg_parm.i[3] = (p4), \
  168254. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168255. #define ERREXITS(cinfo,code,str) \
  168256. ((cinfo)->err->msg_code = (code), \
  168257. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  168258. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168259. #define MAKESTMT(stuff) do { stuff } while (0)
  168260. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  168261. #define WARNMS(cinfo,code) \
  168262. ((cinfo)->err->msg_code = (code), \
  168263. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168264. #define WARNMS1(cinfo,code,p1) \
  168265. ((cinfo)->err->msg_code = (code), \
  168266. (cinfo)->err->msg_parm.i[0] = (p1), \
  168267. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168268. #define WARNMS2(cinfo,code,p1,p2) \
  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->emit_message) ((j_common_ptr) (cinfo), -1))
  168273. /* Informational/debugging messages */
  168274. #define TRACEMS(cinfo,lvl,code) \
  168275. ((cinfo)->err->msg_code = (code), \
  168276. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168277. #define TRACEMS1(cinfo,lvl,code,p1) \
  168278. ((cinfo)->err->msg_code = (code), \
  168279. (cinfo)->err->msg_parm.i[0] = (p1), \
  168280. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168281. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  168282. ((cinfo)->err->msg_code = (code), \
  168283. (cinfo)->err->msg_parm.i[0] = (p1), \
  168284. (cinfo)->err->msg_parm.i[1] = (p2), \
  168285. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168286. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  168287. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168288. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  168289. (cinfo)->err->msg_code = (code); \
  168290. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168291. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  168292. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168293. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168294. (cinfo)->err->msg_code = (code); \
  168295. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168296. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  168297. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168298. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168299. _mp[4] = (p5); \
  168300. (cinfo)->err->msg_code = (code); \
  168301. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168302. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  168303. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168304. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168305. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  168306. (cinfo)->err->msg_code = (code); \
  168307. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168308. #define TRACEMSS(cinfo,lvl,code,str) \
  168309. ((cinfo)->err->msg_code = (code), \
  168310. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  168311. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168312. #endif /* JERROR_H */
  168313. /*** End of inlined file: jerror.h ***/
  168314. /* Expanded data source object for stdio input */
  168315. typedef struct {
  168316. struct jpeg_source_mgr pub; /* public fields */
  168317. FILE * infile; /* source stream */
  168318. JOCTET * buffer; /* start of buffer */
  168319. boolean start_of_file; /* have we gotten any data yet? */
  168320. } my_source_mgr;
  168321. typedef my_source_mgr * my_src_ptr;
  168322. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  168323. /*
  168324. * Initialize source --- called by jpeg_read_header
  168325. * before any data is actually read.
  168326. */
  168327. METHODDEF(void)
  168328. init_source (j_decompress_ptr cinfo)
  168329. {
  168330. my_src_ptr src = (my_src_ptr) cinfo->src;
  168331. /* We reset the empty-input-file flag for each image,
  168332. * but we don't clear the input buffer.
  168333. * This is correct behavior for reading a series of images from one source.
  168334. */
  168335. src->start_of_file = TRUE;
  168336. }
  168337. /*
  168338. * Fill the input buffer --- called whenever buffer is emptied.
  168339. *
  168340. * In typical applications, this should read fresh data into the buffer
  168341. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  168342. * reset the pointer & count to the start of the buffer, and return TRUE
  168343. * indicating that the buffer has been reloaded. It is not necessary to
  168344. * fill the buffer entirely, only to obtain at least one more byte.
  168345. *
  168346. * There is no such thing as an EOF return. If the end of the file has been
  168347. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  168348. * the buffer. In most cases, generating a warning message and inserting a
  168349. * fake EOI marker is the best course of action --- this will allow the
  168350. * decompressor to output however much of the image is there. However,
  168351. * the resulting error message is misleading if the real problem is an empty
  168352. * input file, so we handle that case specially.
  168353. *
  168354. * In applications that need to be able to suspend compression due to input
  168355. * not being available yet, a FALSE return indicates that no more data can be
  168356. * obtained right now, but more may be forthcoming later. In this situation,
  168357. * the decompressor will return to its caller (with an indication of the
  168358. * number of scanlines it has read, if any). The application should resume
  168359. * decompression after it has loaded more data into the input buffer. Note
  168360. * that there are substantial restrictions on the use of suspension --- see
  168361. * the documentation.
  168362. *
  168363. * When suspending, the decompressor will back up to a convenient restart point
  168364. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  168365. * indicate where the restart point will be if the current call returns FALSE.
  168366. * Data beyond this point must be rescanned after resumption, so move it to
  168367. * the front of the buffer rather than discarding it.
  168368. */
  168369. METHODDEF(boolean)
  168370. fill_input_buffer (j_decompress_ptr cinfo)
  168371. {
  168372. my_src_ptr src = (my_src_ptr) cinfo->src;
  168373. size_t nbytes;
  168374. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  168375. if (nbytes <= 0) {
  168376. if (src->start_of_file) /* Treat empty input file as fatal error */
  168377. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  168378. WARNMS(cinfo, JWRN_JPEG_EOF);
  168379. /* Insert a fake EOI marker */
  168380. src->buffer[0] = (JOCTET) 0xFF;
  168381. src->buffer[1] = (JOCTET) JPEG_EOI;
  168382. nbytes = 2;
  168383. }
  168384. src->pub.next_input_byte = src->buffer;
  168385. src->pub.bytes_in_buffer = nbytes;
  168386. src->start_of_file = FALSE;
  168387. return TRUE;
  168388. }
  168389. /*
  168390. * Skip data --- used to skip over a potentially large amount of
  168391. * uninteresting data (such as an APPn marker).
  168392. *
  168393. * Writers of suspendable-input applications must note that skip_input_data
  168394. * is not granted the right to give a suspension return. If the skip extends
  168395. * beyond the data currently in the buffer, the buffer can be marked empty so
  168396. * that the next read will cause a fill_input_buffer call that can suspend.
  168397. * Arranging for additional bytes to be discarded before reloading the input
  168398. * buffer is the application writer's problem.
  168399. */
  168400. METHODDEF(void)
  168401. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  168402. {
  168403. my_src_ptr src = (my_src_ptr) cinfo->src;
  168404. /* Just a dumb implementation for now. Could use fseek() except
  168405. * it doesn't work on pipes. Not clear that being smart is worth
  168406. * any trouble anyway --- large skips are infrequent.
  168407. */
  168408. if (num_bytes > 0) {
  168409. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  168410. num_bytes -= (long) src->pub.bytes_in_buffer;
  168411. (void) fill_input_buffer(cinfo);
  168412. /* note we assume that fill_input_buffer will never return FALSE,
  168413. * so suspension need not be handled.
  168414. */
  168415. }
  168416. src->pub.next_input_byte += (size_t) num_bytes;
  168417. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  168418. }
  168419. }
  168420. /*
  168421. * An additional method that can be provided by data source modules is the
  168422. * resync_to_restart method for error recovery in the presence of RST markers.
  168423. * For the moment, this source module just uses the default resync method
  168424. * provided by the JPEG library. That method assumes that no backtracking
  168425. * is possible.
  168426. */
  168427. /*
  168428. * Terminate source --- called by jpeg_finish_decompress
  168429. * after all data has been read. Often a no-op.
  168430. *
  168431. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  168432. * application must deal with any cleanup that should happen even
  168433. * for error exit.
  168434. */
  168435. METHODDEF(void)
  168436. term_source (j_decompress_ptr)
  168437. {
  168438. /* no work necessary here */
  168439. }
  168440. /*
  168441. * Prepare for input from a stdio stream.
  168442. * The caller must have already opened the stream, and is responsible
  168443. * for closing it after finishing decompression.
  168444. */
  168445. GLOBAL(void)
  168446. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  168447. {
  168448. my_src_ptr src;
  168449. /* The source object and input buffer are made permanent so that a series
  168450. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  168451. * only before the first one. (If we discarded the buffer at the end of
  168452. * one image, we'd likely lose the start of the next one.)
  168453. * This makes it unsafe to use this manager and a different source
  168454. * manager serially with the same JPEG object. Caveat programmer.
  168455. */
  168456. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  168457. cinfo->src = (struct jpeg_source_mgr *)
  168458. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168459. SIZEOF(my_source_mgr));
  168460. src = (my_src_ptr) cinfo->src;
  168461. src->buffer = (JOCTET *)
  168462. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168463. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  168464. }
  168465. src = (my_src_ptr) cinfo->src;
  168466. src->pub.init_source = init_source;
  168467. src->pub.fill_input_buffer = fill_input_buffer;
  168468. src->pub.skip_input_data = skip_input_data;
  168469. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  168470. src->pub.term_source = term_source;
  168471. src->infile = infile;
  168472. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  168473. src->pub.next_input_byte = NULL; /* until buffer loaded */
  168474. }
  168475. /*** End of inlined file: jdatasrc.c ***/
  168476. /*** Start of inlined file: jdcoefct.c ***/
  168477. #define JPEG_INTERNALS
  168478. /* Block smoothing is only applicable for progressive JPEG, so: */
  168479. #ifndef D_PROGRESSIVE_SUPPORTED
  168480. #undef BLOCK_SMOOTHING_SUPPORTED
  168481. #endif
  168482. /* Private buffer controller object */
  168483. typedef struct {
  168484. struct jpeg_d_coef_controller pub; /* public fields */
  168485. /* These variables keep track of the current location of the input side. */
  168486. /* cinfo->input_iMCU_row is also used for this. */
  168487. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  168488. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  168489. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  168490. /* The output side's location is represented by cinfo->output_iMCU_row. */
  168491. /* In single-pass modes, it's sufficient to buffer just one MCU.
  168492. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  168493. * and let the entropy decoder write into that workspace each time.
  168494. * (On 80x86, the workspace is FAR even though it's not really very big;
  168495. * this is to keep the module interfaces unchanged when a large coefficient
  168496. * buffer is necessary.)
  168497. * In multi-pass modes, this array points to the current MCU's blocks
  168498. * within the virtual arrays; it is used only by the input side.
  168499. */
  168500. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  168501. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168502. /* In multi-pass modes, we need a virtual block array for each component. */
  168503. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  168504. #endif
  168505. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168506. /* When doing block smoothing, we latch coefficient Al values here */
  168507. int * coef_bits_latch;
  168508. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  168509. #endif
  168510. } my_coef_controller3;
  168511. typedef my_coef_controller3 * my_coef_ptr3;
  168512. /* Forward declarations */
  168513. METHODDEF(int) decompress_onepass
  168514. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168515. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168516. METHODDEF(int) decompress_data
  168517. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168518. #endif
  168519. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168520. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  168521. METHODDEF(int) decompress_smooth_data
  168522. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168523. #endif
  168524. LOCAL(void)
  168525. start_iMCU_row3 (j_decompress_ptr cinfo)
  168526. /* Reset within-iMCU-row counters for a new row (input side) */
  168527. {
  168528. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168529. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  168530. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  168531. * But at the bottom of the image, process only what's left.
  168532. */
  168533. if (cinfo->comps_in_scan > 1) {
  168534. coef->MCU_rows_per_iMCU_row = 1;
  168535. } else {
  168536. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  168537. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  168538. else
  168539. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  168540. }
  168541. coef->MCU_ctr = 0;
  168542. coef->MCU_vert_offset = 0;
  168543. }
  168544. /*
  168545. * Initialize for an input processing pass.
  168546. */
  168547. METHODDEF(void)
  168548. start_input_pass (j_decompress_ptr cinfo)
  168549. {
  168550. cinfo->input_iMCU_row = 0;
  168551. start_iMCU_row3(cinfo);
  168552. }
  168553. /*
  168554. * Initialize for an output processing pass.
  168555. */
  168556. METHODDEF(void)
  168557. start_output_pass (j_decompress_ptr cinfo)
  168558. {
  168559. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168560. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168561. /* If multipass, check to see whether to use block smoothing on this pass */
  168562. if (coef->pub.coef_arrays != NULL) {
  168563. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  168564. coef->pub.decompress_data = decompress_smooth_data;
  168565. else
  168566. coef->pub.decompress_data = decompress_data;
  168567. }
  168568. #endif
  168569. cinfo->output_iMCU_row = 0;
  168570. }
  168571. /*
  168572. * Decompress and return some data in the single-pass case.
  168573. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168574. * Input and output must run in lockstep since we have only a one-MCU buffer.
  168575. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168576. *
  168577. * NB: output_buf contains a plane for each component in image,
  168578. * which we index according to the component's SOF position.
  168579. */
  168580. METHODDEF(int)
  168581. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168582. {
  168583. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168584. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168585. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  168586. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168587. int blkn, ci, xindex, yindex, yoffset, useful_width;
  168588. JSAMPARRAY output_ptr;
  168589. JDIMENSION start_col, output_col;
  168590. jpeg_component_info *compptr;
  168591. inverse_DCT_method_ptr inverse_DCT;
  168592. /* Loop to process as much as one whole iMCU row */
  168593. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168594. yoffset++) {
  168595. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  168596. MCU_col_num++) {
  168597. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  168598. jzero_far((void FAR *) coef->MCU_buffer[0],
  168599. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  168600. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168601. /* Suspension forced; update state counters and exit */
  168602. coef->MCU_vert_offset = yoffset;
  168603. coef->MCU_ctr = MCU_col_num;
  168604. return JPEG_SUSPENDED;
  168605. }
  168606. /* Determine where data should go in output_buf and do the IDCT thing.
  168607. * We skip dummy blocks at the right and bottom edges (but blkn gets
  168608. * incremented past them!). Note the inner loop relies on having
  168609. * allocated the MCU_buffer[] blocks sequentially.
  168610. */
  168611. blkn = 0; /* index of current DCT block within MCU */
  168612. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168613. compptr = cinfo->cur_comp_info[ci];
  168614. /* Don't bother to IDCT an uninteresting component. */
  168615. if (! compptr->component_needed) {
  168616. blkn += compptr->MCU_blocks;
  168617. continue;
  168618. }
  168619. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  168620. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  168621. : compptr->last_col_width;
  168622. output_ptr = output_buf[compptr->component_index] +
  168623. yoffset * compptr->DCT_scaled_size;
  168624. start_col = MCU_col_num * compptr->MCU_sample_width;
  168625. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168626. if (cinfo->input_iMCU_row < last_iMCU_row ||
  168627. yoffset+yindex < compptr->last_row_height) {
  168628. output_col = start_col;
  168629. for (xindex = 0; xindex < useful_width; xindex++) {
  168630. (*inverse_DCT) (cinfo, compptr,
  168631. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  168632. output_ptr, output_col);
  168633. output_col += compptr->DCT_scaled_size;
  168634. }
  168635. }
  168636. blkn += compptr->MCU_width;
  168637. output_ptr += compptr->DCT_scaled_size;
  168638. }
  168639. }
  168640. }
  168641. /* Completed an MCU row, but perhaps not an iMCU row */
  168642. coef->MCU_ctr = 0;
  168643. }
  168644. /* Completed the iMCU row, advance counters for next one */
  168645. cinfo->output_iMCU_row++;
  168646. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168647. start_iMCU_row3(cinfo);
  168648. return JPEG_ROW_COMPLETED;
  168649. }
  168650. /* Completed the scan */
  168651. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168652. return JPEG_SCAN_COMPLETED;
  168653. }
  168654. /*
  168655. * Dummy consume-input routine for single-pass operation.
  168656. */
  168657. METHODDEF(int)
  168658. dummy_consume_data (j_decompress_ptr)
  168659. {
  168660. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  168661. }
  168662. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168663. /*
  168664. * Consume input data and store it in the full-image coefficient buffer.
  168665. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  168666. * ie, v_samp_factor block rows for each component in the scan.
  168667. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168668. */
  168669. METHODDEF(int)
  168670. consume_data (j_decompress_ptr cinfo)
  168671. {
  168672. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168673. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168674. int blkn, ci, xindex, yindex, yoffset;
  168675. JDIMENSION start_col;
  168676. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  168677. JBLOCKROW buffer_ptr;
  168678. jpeg_component_info *compptr;
  168679. /* Align the virtual buffers for the components used in this scan. */
  168680. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168681. compptr = cinfo->cur_comp_info[ci];
  168682. buffer[ci] = (*cinfo->mem->access_virt_barray)
  168683. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  168684. cinfo->input_iMCU_row * compptr->v_samp_factor,
  168685. (JDIMENSION) compptr->v_samp_factor, TRUE);
  168686. /* Note: entropy decoder expects buffer to be zeroed,
  168687. * but this is handled automatically by the memory manager
  168688. * because we requested a pre-zeroed array.
  168689. */
  168690. }
  168691. /* Loop to process one whole iMCU row */
  168692. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168693. yoffset++) {
  168694. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  168695. MCU_col_num++) {
  168696. /* Construct list of pointers to DCT blocks belonging to this MCU */
  168697. blkn = 0; /* index of current DCT block within MCU */
  168698. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168699. compptr = cinfo->cur_comp_info[ci];
  168700. start_col = MCU_col_num * compptr->MCU_width;
  168701. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168702. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  168703. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  168704. coef->MCU_buffer[blkn++] = buffer_ptr++;
  168705. }
  168706. }
  168707. }
  168708. /* Try to fetch the MCU. */
  168709. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168710. /* Suspension forced; update state counters and exit */
  168711. coef->MCU_vert_offset = yoffset;
  168712. coef->MCU_ctr = MCU_col_num;
  168713. return JPEG_SUSPENDED;
  168714. }
  168715. }
  168716. /* Completed an MCU row, but perhaps not an iMCU row */
  168717. coef->MCU_ctr = 0;
  168718. }
  168719. /* Completed the iMCU row, advance counters for next one */
  168720. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168721. start_iMCU_row3(cinfo);
  168722. return JPEG_ROW_COMPLETED;
  168723. }
  168724. /* Completed the scan */
  168725. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168726. return JPEG_SCAN_COMPLETED;
  168727. }
  168728. /*
  168729. * Decompress and return some data in the multi-pass case.
  168730. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168731. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168732. *
  168733. * NB: output_buf contains a plane for each component in image.
  168734. */
  168735. METHODDEF(int)
  168736. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168737. {
  168738. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168739. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168740. JDIMENSION block_num;
  168741. int ci, block_row, block_rows;
  168742. JBLOCKARRAY buffer;
  168743. JBLOCKROW buffer_ptr;
  168744. JSAMPARRAY output_ptr;
  168745. JDIMENSION output_col;
  168746. jpeg_component_info *compptr;
  168747. inverse_DCT_method_ptr inverse_DCT;
  168748. /* Force some input to be done if we are getting ahead of the input. */
  168749. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  168750. (cinfo->input_scan_number == cinfo->output_scan_number &&
  168751. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  168752. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168753. return JPEG_SUSPENDED;
  168754. }
  168755. /* OK, output from the virtual arrays. */
  168756. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168757. ci++, compptr++) {
  168758. /* Don't bother to IDCT an uninteresting component. */
  168759. if (! compptr->component_needed)
  168760. continue;
  168761. /* Align the virtual buffer for this component. */
  168762. buffer = (*cinfo->mem->access_virt_barray)
  168763. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168764. cinfo->output_iMCU_row * compptr->v_samp_factor,
  168765. (JDIMENSION) compptr->v_samp_factor, FALSE);
  168766. /* Count non-dummy DCT block rows in this iMCU row. */
  168767. if (cinfo->output_iMCU_row < last_iMCU_row)
  168768. block_rows = compptr->v_samp_factor;
  168769. else {
  168770. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168771. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168772. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168773. }
  168774. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168775. output_ptr = output_buf[ci];
  168776. /* Loop over all DCT blocks to be processed. */
  168777. for (block_row = 0; block_row < block_rows; block_row++) {
  168778. buffer_ptr = buffer[block_row];
  168779. output_col = 0;
  168780. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  168781. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  168782. output_ptr, output_col);
  168783. buffer_ptr++;
  168784. output_col += compptr->DCT_scaled_size;
  168785. }
  168786. output_ptr += compptr->DCT_scaled_size;
  168787. }
  168788. }
  168789. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  168790. return JPEG_ROW_COMPLETED;
  168791. return JPEG_SCAN_COMPLETED;
  168792. }
  168793. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  168794. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168795. /*
  168796. * This code applies interblock smoothing as described by section K.8
  168797. * of the JPEG standard: the first 5 AC coefficients are estimated from
  168798. * the DC values of a DCT block and its 8 neighboring blocks.
  168799. * We apply smoothing only for progressive JPEG decoding, and only if
  168800. * the coefficients it can estimate are not yet known to full precision.
  168801. */
  168802. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  168803. #define Q01_POS 1
  168804. #define Q10_POS 8
  168805. #define Q20_POS 16
  168806. #define Q11_POS 9
  168807. #define Q02_POS 2
  168808. /*
  168809. * Determine whether block smoothing is applicable and safe.
  168810. * We also latch the current states of the coef_bits[] entries for the
  168811. * AC coefficients; otherwise, if the input side of the decompressor
  168812. * advances into a new scan, we might think the coefficients are known
  168813. * more accurately than they really are.
  168814. */
  168815. LOCAL(boolean)
  168816. smoothing_ok (j_decompress_ptr cinfo)
  168817. {
  168818. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168819. boolean smoothing_useful = FALSE;
  168820. int ci, coefi;
  168821. jpeg_component_info *compptr;
  168822. JQUANT_TBL * qtable;
  168823. int * coef_bits;
  168824. int * coef_bits_latch;
  168825. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  168826. return FALSE;
  168827. /* Allocate latch area if not already done */
  168828. if (coef->coef_bits_latch == NULL)
  168829. coef->coef_bits_latch = (int *)
  168830. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168831. cinfo->num_components *
  168832. (SAVED_COEFS * SIZEOF(int)));
  168833. coef_bits_latch = coef->coef_bits_latch;
  168834. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168835. ci++, compptr++) {
  168836. /* All components' quantization values must already be latched. */
  168837. if ((qtable = compptr->quant_table) == NULL)
  168838. return FALSE;
  168839. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  168840. if (qtable->quantval[0] == 0 ||
  168841. qtable->quantval[Q01_POS] == 0 ||
  168842. qtable->quantval[Q10_POS] == 0 ||
  168843. qtable->quantval[Q20_POS] == 0 ||
  168844. qtable->quantval[Q11_POS] == 0 ||
  168845. qtable->quantval[Q02_POS] == 0)
  168846. return FALSE;
  168847. /* DC values must be at least partly known for all components. */
  168848. coef_bits = cinfo->coef_bits[ci];
  168849. if (coef_bits[0] < 0)
  168850. return FALSE;
  168851. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  168852. for (coefi = 1; coefi <= 5; coefi++) {
  168853. coef_bits_latch[coefi] = coef_bits[coefi];
  168854. if (coef_bits[coefi] != 0)
  168855. smoothing_useful = TRUE;
  168856. }
  168857. coef_bits_latch += SAVED_COEFS;
  168858. }
  168859. return smoothing_useful;
  168860. }
  168861. /*
  168862. * Variant of decompress_data for use when doing block smoothing.
  168863. */
  168864. METHODDEF(int)
  168865. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168866. {
  168867. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168868. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168869. JDIMENSION block_num, last_block_column;
  168870. int ci, block_row, block_rows, access_rows;
  168871. JBLOCKARRAY buffer;
  168872. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  168873. JSAMPARRAY output_ptr;
  168874. JDIMENSION output_col;
  168875. jpeg_component_info *compptr;
  168876. inverse_DCT_method_ptr inverse_DCT;
  168877. boolean first_row, last_row;
  168878. JBLOCK workspace;
  168879. int *coef_bits;
  168880. JQUANT_TBL *quanttbl;
  168881. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  168882. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  168883. int Al, pred;
  168884. /* Force some input to be done if we are getting ahead of the input. */
  168885. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  168886. ! cinfo->inputctl->eoi_reached) {
  168887. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  168888. /* If input is working on current scan, we ordinarily want it to
  168889. * have completed the current row. But if input scan is DC,
  168890. * we want it to keep one row ahead so that next block row's DC
  168891. * values are up to date.
  168892. */
  168893. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  168894. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  168895. break;
  168896. }
  168897. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168898. return JPEG_SUSPENDED;
  168899. }
  168900. /* OK, output from the virtual arrays. */
  168901. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168902. ci++, compptr++) {
  168903. /* Don't bother to IDCT an uninteresting component. */
  168904. if (! compptr->component_needed)
  168905. continue;
  168906. /* Count non-dummy DCT block rows in this iMCU row. */
  168907. if (cinfo->output_iMCU_row < last_iMCU_row) {
  168908. block_rows = compptr->v_samp_factor;
  168909. access_rows = block_rows * 2; /* this and next iMCU row */
  168910. last_row = FALSE;
  168911. } else {
  168912. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168913. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168914. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  168915. access_rows = block_rows; /* this iMCU row only */
  168916. last_row = TRUE;
  168917. }
  168918. /* Align the virtual buffer for this component. */
  168919. if (cinfo->output_iMCU_row > 0) {
  168920. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  168921. buffer = (*cinfo->mem->access_virt_barray)
  168922. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168923. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  168924. (JDIMENSION) access_rows, FALSE);
  168925. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  168926. first_row = FALSE;
  168927. } else {
  168928. buffer = (*cinfo->mem->access_virt_barray)
  168929. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168930. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  168931. first_row = TRUE;
  168932. }
  168933. /* Fetch component-dependent info */
  168934. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  168935. quanttbl = compptr->quant_table;
  168936. Q00 = quanttbl->quantval[0];
  168937. Q01 = quanttbl->quantval[Q01_POS];
  168938. Q10 = quanttbl->quantval[Q10_POS];
  168939. Q20 = quanttbl->quantval[Q20_POS];
  168940. Q11 = quanttbl->quantval[Q11_POS];
  168941. Q02 = quanttbl->quantval[Q02_POS];
  168942. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  168943. output_ptr = output_buf[ci];
  168944. /* Loop over all DCT blocks to be processed. */
  168945. for (block_row = 0; block_row < block_rows; block_row++) {
  168946. buffer_ptr = buffer[block_row];
  168947. if (first_row && block_row == 0)
  168948. prev_block_row = buffer_ptr;
  168949. else
  168950. prev_block_row = buffer[block_row-1];
  168951. if (last_row && block_row == block_rows-1)
  168952. next_block_row = buffer_ptr;
  168953. else
  168954. next_block_row = buffer[block_row+1];
  168955. /* We fetch the surrounding DC values using a sliding-register approach.
  168956. * Initialize all nine here so as to do the right thing on narrow pics.
  168957. */
  168958. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  168959. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  168960. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  168961. output_col = 0;
  168962. last_block_column = compptr->width_in_blocks - 1;
  168963. for (block_num = 0; block_num <= last_block_column; block_num++) {
  168964. /* Fetch current DCT block into workspace so we can modify it. */
  168965. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  168966. /* Update DC values */
  168967. if (block_num < last_block_column) {
  168968. DC3 = (int) prev_block_row[1][0];
  168969. DC6 = (int) buffer_ptr[1][0];
  168970. DC9 = (int) next_block_row[1][0];
  168971. }
  168972. /* Compute coefficient estimates per K.8.
  168973. * An estimate is applied only if coefficient is still zero,
  168974. * and is not known to be fully accurate.
  168975. */
  168976. /* AC01 */
  168977. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  168978. num = 36 * Q00 * (DC4 - DC6);
  168979. if (num >= 0) {
  168980. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  168981. if (Al > 0 && pred >= (1<<Al))
  168982. pred = (1<<Al)-1;
  168983. } else {
  168984. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  168985. if (Al > 0 && pred >= (1<<Al))
  168986. pred = (1<<Al)-1;
  168987. pred = -pred;
  168988. }
  168989. workspace[1] = (JCOEF) pred;
  168990. }
  168991. /* AC10 */
  168992. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  168993. num = 36 * Q00 * (DC2 - DC8);
  168994. if (num >= 0) {
  168995. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  168996. if (Al > 0 && pred >= (1<<Al))
  168997. pred = (1<<Al)-1;
  168998. } else {
  168999. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  169000. if (Al > 0 && pred >= (1<<Al))
  169001. pred = (1<<Al)-1;
  169002. pred = -pred;
  169003. }
  169004. workspace[8] = (JCOEF) pred;
  169005. }
  169006. /* AC20 */
  169007. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  169008. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  169009. if (num >= 0) {
  169010. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  169011. if (Al > 0 && pred >= (1<<Al))
  169012. pred = (1<<Al)-1;
  169013. } else {
  169014. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  169015. if (Al > 0 && pred >= (1<<Al))
  169016. pred = (1<<Al)-1;
  169017. pred = -pred;
  169018. }
  169019. workspace[16] = (JCOEF) pred;
  169020. }
  169021. /* AC11 */
  169022. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  169023. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  169024. if (num >= 0) {
  169025. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  169026. if (Al > 0 && pred >= (1<<Al))
  169027. pred = (1<<Al)-1;
  169028. } else {
  169029. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  169030. if (Al > 0 && pred >= (1<<Al))
  169031. pred = (1<<Al)-1;
  169032. pred = -pred;
  169033. }
  169034. workspace[9] = (JCOEF) pred;
  169035. }
  169036. /* AC02 */
  169037. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  169038. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  169039. if (num >= 0) {
  169040. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  169041. if (Al > 0 && pred >= (1<<Al))
  169042. pred = (1<<Al)-1;
  169043. } else {
  169044. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  169045. if (Al > 0 && pred >= (1<<Al))
  169046. pred = (1<<Al)-1;
  169047. pred = -pred;
  169048. }
  169049. workspace[2] = (JCOEF) pred;
  169050. }
  169051. /* OK, do the IDCT */
  169052. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  169053. output_ptr, output_col);
  169054. /* Advance for next column */
  169055. DC1 = DC2; DC2 = DC3;
  169056. DC4 = DC5; DC5 = DC6;
  169057. DC7 = DC8; DC8 = DC9;
  169058. buffer_ptr++, prev_block_row++, next_block_row++;
  169059. output_col += compptr->DCT_scaled_size;
  169060. }
  169061. output_ptr += compptr->DCT_scaled_size;
  169062. }
  169063. }
  169064. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  169065. return JPEG_ROW_COMPLETED;
  169066. return JPEG_SCAN_COMPLETED;
  169067. }
  169068. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  169069. /*
  169070. * Initialize coefficient buffer controller.
  169071. */
  169072. GLOBAL(void)
  169073. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  169074. {
  169075. my_coef_ptr3 coef;
  169076. coef = (my_coef_ptr3)
  169077. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169078. SIZEOF(my_coef_controller3));
  169079. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  169080. coef->pub.start_input_pass = start_input_pass;
  169081. coef->pub.start_output_pass = start_output_pass;
  169082. #ifdef BLOCK_SMOOTHING_SUPPORTED
  169083. coef->coef_bits_latch = NULL;
  169084. #endif
  169085. /* Create the coefficient buffer. */
  169086. if (need_full_buffer) {
  169087. #ifdef D_MULTISCAN_FILES_SUPPORTED
  169088. /* Allocate a full-image virtual array for each component, */
  169089. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  169090. /* Note we ask for a pre-zeroed array. */
  169091. int ci, access_rows;
  169092. jpeg_component_info *compptr;
  169093. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169094. ci++, compptr++) {
  169095. access_rows = compptr->v_samp_factor;
  169096. #ifdef BLOCK_SMOOTHING_SUPPORTED
  169097. /* If block smoothing could be used, need a bigger window */
  169098. if (cinfo->progressive_mode)
  169099. access_rows *= 3;
  169100. #endif
  169101. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  169102. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  169103. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  169104. (long) compptr->h_samp_factor),
  169105. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  169106. (long) compptr->v_samp_factor),
  169107. (JDIMENSION) access_rows);
  169108. }
  169109. coef->pub.consume_data = consume_data;
  169110. coef->pub.decompress_data = decompress_data;
  169111. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  169112. #else
  169113. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169114. #endif
  169115. } else {
  169116. /* We only need a single-MCU buffer. */
  169117. JBLOCKROW buffer;
  169118. int i;
  169119. buffer = (JBLOCKROW)
  169120. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169121. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  169122. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  169123. coef->MCU_buffer[i] = buffer + i;
  169124. }
  169125. coef->pub.consume_data = dummy_consume_data;
  169126. coef->pub.decompress_data = decompress_onepass;
  169127. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  169128. }
  169129. }
  169130. /*** End of inlined file: jdcoefct.c ***/
  169131. #undef FIX
  169132. /*** Start of inlined file: jdcolor.c ***/
  169133. #define JPEG_INTERNALS
  169134. /* Private subobject */
  169135. typedef struct {
  169136. struct jpeg_color_deconverter pub; /* public fields */
  169137. /* Private state for YCC->RGB conversion */
  169138. int * Cr_r_tab; /* => table for Cr to R conversion */
  169139. int * Cb_b_tab; /* => table for Cb to B conversion */
  169140. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  169141. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  169142. } my_color_deconverter2;
  169143. typedef my_color_deconverter2 * my_cconvert_ptr2;
  169144. /**************** YCbCr -> RGB conversion: most common case **************/
  169145. /*
  169146. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  169147. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  169148. * The conversion equations to be implemented are therefore
  169149. * R = Y + 1.40200 * Cr
  169150. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  169151. * B = Y + 1.77200 * Cb
  169152. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  169153. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  169154. *
  169155. * To avoid floating-point arithmetic, we represent the fractional constants
  169156. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  169157. * the products by 2^16, with appropriate rounding, to get the correct answer.
  169158. * Notice that Y, being an integral input, does not contribute any fraction
  169159. * so it need not participate in the rounding.
  169160. *
  169161. * For even more speed, we avoid doing any multiplications in the inner loop
  169162. * by precalculating the constants times Cb and Cr for all possible values.
  169163. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  169164. * for 12-bit samples it is still acceptable. It's not very reasonable for
  169165. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  169166. * colorspace anyway.
  169167. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  169168. * values for the G calculation are left scaled up, since we must add them
  169169. * together before rounding.
  169170. */
  169171. #define SCALEBITS 16 /* speediest right-shift on some machines */
  169172. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  169173. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  169174. /*
  169175. * Initialize tables for YCC->RGB colorspace conversion.
  169176. */
  169177. LOCAL(void)
  169178. build_ycc_rgb_table (j_decompress_ptr cinfo)
  169179. {
  169180. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169181. int i;
  169182. INT32 x;
  169183. SHIFT_TEMPS
  169184. cconvert->Cr_r_tab = (int *)
  169185. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169186. (MAXJSAMPLE+1) * SIZEOF(int));
  169187. cconvert->Cb_b_tab = (int *)
  169188. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169189. (MAXJSAMPLE+1) * SIZEOF(int));
  169190. cconvert->Cr_g_tab = (INT32 *)
  169191. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169192. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169193. cconvert->Cb_g_tab = (INT32 *)
  169194. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169195. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169196. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  169197. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  169198. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  169199. /* Cr=>R value is nearest int to 1.40200 * x */
  169200. cconvert->Cr_r_tab[i] = (int)
  169201. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  169202. /* Cb=>B value is nearest int to 1.77200 * x */
  169203. cconvert->Cb_b_tab[i] = (int)
  169204. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  169205. /* Cr=>G value is scaled-up -0.71414 * x */
  169206. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  169207. /* Cb=>G value is scaled-up -0.34414 * x */
  169208. /* We also add in ONE_HALF so that need not do it in inner loop */
  169209. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  169210. }
  169211. }
  169212. /*
  169213. * Convert some rows of samples to the output colorspace.
  169214. *
  169215. * Note that we change from noninterleaved, one-plane-per-component format
  169216. * to interleaved-pixel format. The output buffer is therefore three times
  169217. * as wide as the input buffer.
  169218. * A starting row offset is provided only for the input buffer. The caller
  169219. * can easily adjust the passed output_buf value to accommodate any row
  169220. * offset required on that side.
  169221. */
  169222. METHODDEF(void)
  169223. ycc_rgb_convert (j_decompress_ptr cinfo,
  169224. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169225. JSAMPARRAY output_buf, int num_rows)
  169226. {
  169227. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169228. register int y, cb, cr;
  169229. register JSAMPROW outptr;
  169230. register JSAMPROW inptr0, inptr1, inptr2;
  169231. register JDIMENSION col;
  169232. JDIMENSION num_cols = cinfo->output_width;
  169233. /* copy these pointers into registers if possible */
  169234. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169235. register int * Crrtab = cconvert->Cr_r_tab;
  169236. register int * Cbbtab = cconvert->Cb_b_tab;
  169237. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169238. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169239. SHIFT_TEMPS
  169240. while (--num_rows >= 0) {
  169241. inptr0 = input_buf[0][input_row];
  169242. inptr1 = input_buf[1][input_row];
  169243. inptr2 = input_buf[2][input_row];
  169244. input_row++;
  169245. outptr = *output_buf++;
  169246. for (col = 0; col < num_cols; col++) {
  169247. y = GETJSAMPLE(inptr0[col]);
  169248. cb = GETJSAMPLE(inptr1[col]);
  169249. cr = GETJSAMPLE(inptr2[col]);
  169250. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169251. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  169252. outptr[RGB_GREEN] = range_limit[y +
  169253. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169254. SCALEBITS))];
  169255. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  169256. outptr += RGB_PIXELSIZE;
  169257. }
  169258. }
  169259. }
  169260. /**************** Cases other than YCbCr -> RGB **************/
  169261. /*
  169262. * Color conversion for no colorspace change: just copy the data,
  169263. * converting from separate-planes to interleaved representation.
  169264. */
  169265. METHODDEF(void)
  169266. null_convert2 (j_decompress_ptr cinfo,
  169267. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169268. JSAMPARRAY output_buf, int num_rows)
  169269. {
  169270. register JSAMPROW inptr, outptr;
  169271. register JDIMENSION count;
  169272. register int num_components = cinfo->num_components;
  169273. JDIMENSION num_cols = cinfo->output_width;
  169274. int ci;
  169275. while (--num_rows >= 0) {
  169276. for (ci = 0; ci < num_components; ci++) {
  169277. inptr = input_buf[ci][input_row];
  169278. outptr = output_buf[0] + ci;
  169279. for (count = num_cols; count > 0; count--) {
  169280. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  169281. outptr += num_components;
  169282. }
  169283. }
  169284. input_row++;
  169285. output_buf++;
  169286. }
  169287. }
  169288. /*
  169289. * Color conversion for grayscale: just copy the data.
  169290. * This also works for YCbCr -> grayscale conversion, in which
  169291. * we just copy the Y (luminance) component and ignore chrominance.
  169292. */
  169293. METHODDEF(void)
  169294. grayscale_convert2 (j_decompress_ptr cinfo,
  169295. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169296. JSAMPARRAY output_buf, int num_rows)
  169297. {
  169298. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  169299. num_rows, cinfo->output_width);
  169300. }
  169301. /*
  169302. * Convert grayscale to RGB: just duplicate the graylevel three times.
  169303. * This is provided to support applications that don't want to cope
  169304. * with grayscale as a separate case.
  169305. */
  169306. METHODDEF(void)
  169307. gray_rgb_convert (j_decompress_ptr cinfo,
  169308. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169309. JSAMPARRAY output_buf, int num_rows)
  169310. {
  169311. register JSAMPROW inptr, outptr;
  169312. register JDIMENSION col;
  169313. JDIMENSION num_cols = cinfo->output_width;
  169314. while (--num_rows >= 0) {
  169315. inptr = input_buf[0][input_row++];
  169316. outptr = *output_buf++;
  169317. for (col = 0; col < num_cols; col++) {
  169318. /* We can dispense with GETJSAMPLE() here */
  169319. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  169320. outptr += RGB_PIXELSIZE;
  169321. }
  169322. }
  169323. }
  169324. /*
  169325. * Adobe-style YCCK->CMYK conversion.
  169326. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  169327. * conversion as above, while passing K (black) unchanged.
  169328. * We assume build_ycc_rgb_table has been called.
  169329. */
  169330. METHODDEF(void)
  169331. ycck_cmyk_convert (j_decompress_ptr cinfo,
  169332. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169333. JSAMPARRAY output_buf, int num_rows)
  169334. {
  169335. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169336. register int y, cb, cr;
  169337. register JSAMPROW outptr;
  169338. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  169339. register JDIMENSION col;
  169340. JDIMENSION num_cols = cinfo->output_width;
  169341. /* copy these pointers into registers if possible */
  169342. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169343. register int * Crrtab = cconvert->Cr_r_tab;
  169344. register int * Cbbtab = cconvert->Cb_b_tab;
  169345. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169346. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169347. SHIFT_TEMPS
  169348. while (--num_rows >= 0) {
  169349. inptr0 = input_buf[0][input_row];
  169350. inptr1 = input_buf[1][input_row];
  169351. inptr2 = input_buf[2][input_row];
  169352. inptr3 = input_buf[3][input_row];
  169353. input_row++;
  169354. outptr = *output_buf++;
  169355. for (col = 0; col < num_cols; col++) {
  169356. y = GETJSAMPLE(inptr0[col]);
  169357. cb = GETJSAMPLE(inptr1[col]);
  169358. cr = GETJSAMPLE(inptr2[col]);
  169359. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169360. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  169361. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  169362. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169363. SCALEBITS)))];
  169364. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  169365. /* K passes through unchanged */
  169366. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  169367. outptr += 4;
  169368. }
  169369. }
  169370. }
  169371. /*
  169372. * Empty method for start_pass.
  169373. */
  169374. METHODDEF(void)
  169375. start_pass_dcolor (j_decompress_ptr)
  169376. {
  169377. /* no work needed */
  169378. }
  169379. /*
  169380. * Module initialization routine for output colorspace conversion.
  169381. */
  169382. GLOBAL(void)
  169383. jinit_color_deconverter (j_decompress_ptr cinfo)
  169384. {
  169385. my_cconvert_ptr2 cconvert;
  169386. int ci;
  169387. cconvert = (my_cconvert_ptr2)
  169388. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169389. SIZEOF(my_color_deconverter2));
  169390. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  169391. cconvert->pub.start_pass = start_pass_dcolor;
  169392. /* Make sure num_components agrees with jpeg_color_space */
  169393. switch (cinfo->jpeg_color_space) {
  169394. case JCS_GRAYSCALE:
  169395. if (cinfo->num_components != 1)
  169396. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169397. break;
  169398. case JCS_RGB:
  169399. case JCS_YCbCr:
  169400. if (cinfo->num_components != 3)
  169401. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169402. break;
  169403. case JCS_CMYK:
  169404. case JCS_YCCK:
  169405. if (cinfo->num_components != 4)
  169406. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169407. break;
  169408. default: /* JCS_UNKNOWN can be anything */
  169409. if (cinfo->num_components < 1)
  169410. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169411. break;
  169412. }
  169413. /* Set out_color_components and conversion method based on requested space.
  169414. * Also clear the component_needed flags for any unused components,
  169415. * so that earlier pipeline stages can avoid useless computation.
  169416. */
  169417. switch (cinfo->out_color_space) {
  169418. case JCS_GRAYSCALE:
  169419. cinfo->out_color_components = 1;
  169420. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  169421. cinfo->jpeg_color_space == JCS_YCbCr) {
  169422. cconvert->pub.color_convert = grayscale_convert2;
  169423. /* For color->grayscale conversion, only the Y (0) component is needed */
  169424. for (ci = 1; ci < cinfo->num_components; ci++)
  169425. cinfo->comp_info[ci].component_needed = FALSE;
  169426. } else
  169427. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169428. break;
  169429. case JCS_RGB:
  169430. cinfo->out_color_components = RGB_PIXELSIZE;
  169431. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  169432. cconvert->pub.color_convert = ycc_rgb_convert;
  169433. build_ycc_rgb_table(cinfo);
  169434. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  169435. cconvert->pub.color_convert = gray_rgb_convert;
  169436. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  169437. cconvert->pub.color_convert = null_convert2;
  169438. } else
  169439. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169440. break;
  169441. case JCS_CMYK:
  169442. cinfo->out_color_components = 4;
  169443. if (cinfo->jpeg_color_space == JCS_YCCK) {
  169444. cconvert->pub.color_convert = ycck_cmyk_convert;
  169445. build_ycc_rgb_table(cinfo);
  169446. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  169447. cconvert->pub.color_convert = null_convert2;
  169448. } else
  169449. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169450. break;
  169451. default:
  169452. /* Permit null conversion to same output space */
  169453. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  169454. cinfo->out_color_components = cinfo->num_components;
  169455. cconvert->pub.color_convert = null_convert2;
  169456. } else /* unsupported non-null conversion */
  169457. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169458. break;
  169459. }
  169460. if (cinfo->quantize_colors)
  169461. cinfo->output_components = 1; /* single colormapped output component */
  169462. else
  169463. cinfo->output_components = cinfo->out_color_components;
  169464. }
  169465. /*** End of inlined file: jdcolor.c ***/
  169466. #undef FIX
  169467. /*** Start of inlined file: jddctmgr.c ***/
  169468. #define JPEG_INTERNALS
  169469. /*
  169470. * The decompressor input side (jdinput.c) saves away the appropriate
  169471. * quantization table for each component at the start of the first scan
  169472. * involving that component. (This is necessary in order to correctly
  169473. * decode files that reuse Q-table slots.)
  169474. * When we are ready to make an output pass, the saved Q-table is converted
  169475. * to a multiplier table that will actually be used by the IDCT routine.
  169476. * The multiplier table contents are IDCT-method-dependent. To support
  169477. * application changes in IDCT method between scans, we can remake the
  169478. * multiplier tables if necessary.
  169479. * In buffered-image mode, the first output pass may occur before any data
  169480. * has been seen for some components, and thus before their Q-tables have
  169481. * been saved away. To handle this case, multiplier tables are preset
  169482. * to zeroes; the result of the IDCT will be a neutral gray level.
  169483. */
  169484. /* Private subobject for this module */
  169485. typedef struct {
  169486. struct jpeg_inverse_dct pub; /* public fields */
  169487. /* This array contains the IDCT method code that each multiplier table
  169488. * is currently set up for, or -1 if it's not yet set up.
  169489. * The actual multiplier tables are pointed to by dct_table in the
  169490. * per-component comp_info structures.
  169491. */
  169492. int cur_method[MAX_COMPONENTS];
  169493. } my_idct_controller;
  169494. typedef my_idct_controller * my_idct_ptr;
  169495. /* Allocated multiplier tables: big enough for any supported variant */
  169496. typedef union {
  169497. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  169498. #ifdef DCT_IFAST_SUPPORTED
  169499. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  169500. #endif
  169501. #ifdef DCT_FLOAT_SUPPORTED
  169502. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  169503. #endif
  169504. } multiplier_table;
  169505. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  169506. * so be sure to compile that code if either ISLOW or SCALING is requested.
  169507. */
  169508. #ifdef DCT_ISLOW_SUPPORTED
  169509. #define PROVIDE_ISLOW_TABLES
  169510. #else
  169511. #ifdef IDCT_SCALING_SUPPORTED
  169512. #define PROVIDE_ISLOW_TABLES
  169513. #endif
  169514. #endif
  169515. /*
  169516. * Prepare for an output pass.
  169517. * Here we select the proper IDCT routine for each component and build
  169518. * a matching multiplier table.
  169519. */
  169520. METHODDEF(void)
  169521. start_pass (j_decompress_ptr cinfo)
  169522. {
  169523. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  169524. int ci, i;
  169525. jpeg_component_info *compptr;
  169526. int method = 0;
  169527. inverse_DCT_method_ptr method_ptr = NULL;
  169528. JQUANT_TBL * qtbl;
  169529. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169530. ci++, compptr++) {
  169531. /* Select the proper IDCT routine for this component's scaling */
  169532. switch (compptr->DCT_scaled_size) {
  169533. #ifdef IDCT_SCALING_SUPPORTED
  169534. case 1:
  169535. method_ptr = jpeg_idct_1x1;
  169536. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169537. break;
  169538. case 2:
  169539. method_ptr = jpeg_idct_2x2;
  169540. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169541. break;
  169542. case 4:
  169543. method_ptr = jpeg_idct_4x4;
  169544. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169545. break;
  169546. #endif
  169547. case DCTSIZE:
  169548. switch (cinfo->dct_method) {
  169549. #ifdef DCT_ISLOW_SUPPORTED
  169550. case JDCT_ISLOW:
  169551. method_ptr = jpeg_idct_islow;
  169552. method = JDCT_ISLOW;
  169553. break;
  169554. #endif
  169555. #ifdef DCT_IFAST_SUPPORTED
  169556. case JDCT_IFAST:
  169557. method_ptr = jpeg_idct_ifast;
  169558. method = JDCT_IFAST;
  169559. break;
  169560. #endif
  169561. #ifdef DCT_FLOAT_SUPPORTED
  169562. case JDCT_FLOAT:
  169563. method_ptr = jpeg_idct_float;
  169564. method = JDCT_FLOAT;
  169565. break;
  169566. #endif
  169567. default:
  169568. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169569. break;
  169570. }
  169571. break;
  169572. default:
  169573. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  169574. break;
  169575. }
  169576. idct->pub.inverse_DCT[ci] = method_ptr;
  169577. /* Create multiplier table from quant table.
  169578. * However, we can skip this if the component is uninteresting
  169579. * or if we already built the table. Also, if no quant table
  169580. * has yet been saved for the component, we leave the
  169581. * multiplier table all-zero; we'll be reading zeroes from the
  169582. * coefficient controller's buffer anyway.
  169583. */
  169584. if (! compptr->component_needed || idct->cur_method[ci] == method)
  169585. continue;
  169586. qtbl = compptr->quant_table;
  169587. if (qtbl == NULL) /* happens if no data yet for component */
  169588. continue;
  169589. idct->cur_method[ci] = method;
  169590. switch (method) {
  169591. #ifdef PROVIDE_ISLOW_TABLES
  169592. case JDCT_ISLOW:
  169593. {
  169594. /* For LL&M IDCT method, multipliers are equal to raw quantization
  169595. * coefficients, but are stored as ints to ensure access efficiency.
  169596. */
  169597. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169598. for (i = 0; i < DCTSIZE2; i++) {
  169599. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  169600. }
  169601. }
  169602. break;
  169603. #endif
  169604. #ifdef DCT_IFAST_SUPPORTED
  169605. case JDCT_IFAST:
  169606. {
  169607. /* For AA&N IDCT method, multipliers are equal to quantization
  169608. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169609. * scalefactor[0] = 1
  169610. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169611. * For integer operation, the multiplier table is to be scaled by
  169612. * IFAST_SCALE_BITS.
  169613. */
  169614. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  169615. #define CONST_BITS 14
  169616. static const INT16 aanscales[DCTSIZE2] = {
  169617. /* precomputed values scaled up by 14 bits */
  169618. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169619. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  169620. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  169621. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  169622. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169623. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  169624. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  169625. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  169626. };
  169627. SHIFT_TEMPS
  169628. for (i = 0; i < DCTSIZE2; i++) {
  169629. ifmtbl[i] = (IFAST_MULT_TYPE)
  169630. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  169631. (INT32) aanscales[i]),
  169632. CONST_BITS-IFAST_SCALE_BITS);
  169633. }
  169634. }
  169635. break;
  169636. #endif
  169637. #ifdef DCT_FLOAT_SUPPORTED
  169638. case JDCT_FLOAT:
  169639. {
  169640. /* For float AA&N IDCT method, multipliers are equal to quantization
  169641. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169642. * scalefactor[0] = 1
  169643. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169644. */
  169645. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  169646. int row, col;
  169647. static const double aanscalefactor[DCTSIZE] = {
  169648. 1.0, 1.387039845, 1.306562965, 1.175875602,
  169649. 1.0, 0.785694958, 0.541196100, 0.275899379
  169650. };
  169651. i = 0;
  169652. for (row = 0; row < DCTSIZE; row++) {
  169653. for (col = 0; col < DCTSIZE; col++) {
  169654. fmtbl[i] = (FLOAT_MULT_TYPE)
  169655. ((double) qtbl->quantval[i] *
  169656. aanscalefactor[row] * aanscalefactor[col]);
  169657. i++;
  169658. }
  169659. }
  169660. }
  169661. break;
  169662. #endif
  169663. default:
  169664. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169665. break;
  169666. }
  169667. }
  169668. }
  169669. /*
  169670. * Initialize IDCT manager.
  169671. */
  169672. GLOBAL(void)
  169673. jinit_inverse_dct (j_decompress_ptr cinfo)
  169674. {
  169675. my_idct_ptr idct;
  169676. int ci;
  169677. jpeg_component_info *compptr;
  169678. idct = (my_idct_ptr)
  169679. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169680. SIZEOF(my_idct_controller));
  169681. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  169682. idct->pub.start_pass = start_pass;
  169683. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169684. ci++, compptr++) {
  169685. /* Allocate and pre-zero a multiplier table for each component */
  169686. compptr->dct_table =
  169687. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169688. SIZEOF(multiplier_table));
  169689. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  169690. /* Mark multiplier table not yet set up for any method */
  169691. idct->cur_method[ci] = -1;
  169692. }
  169693. }
  169694. /*** End of inlined file: jddctmgr.c ***/
  169695. #undef CONST_BITS
  169696. #undef ASSIGN_STATE
  169697. /*** Start of inlined file: jdhuff.c ***/
  169698. #define JPEG_INTERNALS
  169699. /*** Start of inlined file: jdhuff.h ***/
  169700. /* Short forms of external names for systems with brain-damaged linkers. */
  169701. #ifndef __jdhuff_h__
  169702. #define __jdhuff_h__
  169703. #ifdef NEED_SHORT_EXTERNAL_NAMES
  169704. #define jpeg_make_d_derived_tbl jMkDDerived
  169705. #define jpeg_fill_bit_buffer jFilBitBuf
  169706. #define jpeg_huff_decode jHufDecode
  169707. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  169708. /* Derived data constructed for each Huffman table */
  169709. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  169710. typedef struct {
  169711. /* Basic tables: (element [0] of each array is unused) */
  169712. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  169713. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  169714. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  169715. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  169716. * the smallest code of length k; so given a code of length k, the
  169717. * corresponding symbol is huffval[code + valoffset[k]]
  169718. */
  169719. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  169720. JHUFF_TBL *pub;
  169721. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  169722. * the input data stream. If the next Huffman code is no more
  169723. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  169724. * the corresponding symbol directly from these tables.
  169725. */
  169726. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  169727. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  169728. } d_derived_tbl;
  169729. /* Expand a Huffman table definition into the derived format */
  169730. EXTERN(void) jpeg_make_d_derived_tbl
  169731. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  169732. d_derived_tbl ** pdtbl));
  169733. /*
  169734. * Fetching the next N bits from the input stream is a time-critical operation
  169735. * for the Huffman decoders. We implement it with a combination of inline
  169736. * macros and out-of-line subroutines. Note that N (the number of bits
  169737. * demanded at one time) never exceeds 15 for JPEG use.
  169738. *
  169739. * We read source bytes into get_buffer and dole out bits as needed.
  169740. * If get_buffer already contains enough bits, they are fetched in-line
  169741. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  169742. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  169743. * as full as possible (not just to the number of bits needed; this
  169744. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  169745. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  169746. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  169747. * at least the requested number of bits --- dummy zeroes are inserted if
  169748. * necessary.
  169749. */
  169750. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  169751. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  169752. /* If long is > 32 bits on your machine, and shifting/masking longs is
  169753. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  169754. * appropriately should be a win. Unfortunately we can't define the size
  169755. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  169756. * because not all machines measure sizeof in 8-bit bytes.
  169757. */
  169758. typedef struct { /* Bitreading state saved across MCUs */
  169759. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169760. int bits_left; /* # of unused bits in it */
  169761. } bitread_perm_state;
  169762. typedef struct { /* Bitreading working state within an MCU */
  169763. /* Current data source location */
  169764. /* We need a copy, rather than munging the original, in case of suspension */
  169765. const JOCTET * next_input_byte; /* => next byte to read from source */
  169766. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  169767. /* Bit input buffer --- note these values are kept in register variables,
  169768. * not in this struct, inside the inner loops.
  169769. */
  169770. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169771. int bits_left; /* # of unused bits in it */
  169772. /* Pointer needed by jpeg_fill_bit_buffer. */
  169773. j_decompress_ptr cinfo; /* back link to decompress master record */
  169774. } bitread_working_state;
  169775. /* Macros to declare and load/save bitread local variables. */
  169776. #define BITREAD_STATE_VARS \
  169777. register bit_buf_type get_buffer; \
  169778. register int bits_left; \
  169779. bitread_working_state br_state
  169780. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  169781. br_state.cinfo = cinfop; \
  169782. br_state.next_input_byte = cinfop->src->next_input_byte; \
  169783. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  169784. get_buffer = permstate.get_buffer; \
  169785. bits_left = permstate.bits_left;
  169786. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  169787. cinfop->src->next_input_byte = br_state.next_input_byte; \
  169788. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  169789. permstate.get_buffer = get_buffer; \
  169790. permstate.bits_left = bits_left
  169791. /*
  169792. * These macros provide the in-line portion of bit fetching.
  169793. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  169794. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  169795. * The variables get_buffer and bits_left are assumed to be locals,
  169796. * but the state struct might not be (jpeg_huff_decode needs this).
  169797. * CHECK_BIT_BUFFER(state,n,action);
  169798. * Ensure there are N bits in get_buffer; if suspend, take action.
  169799. * val = GET_BITS(n);
  169800. * Fetch next N bits.
  169801. * val = PEEK_BITS(n);
  169802. * Fetch next N bits without removing them from the buffer.
  169803. * DROP_BITS(n);
  169804. * Discard next N bits.
  169805. * The value N should be a simple variable, not an expression, because it
  169806. * is evaluated multiple times.
  169807. */
  169808. #define CHECK_BIT_BUFFER(state,nbits,action) \
  169809. { if (bits_left < (nbits)) { \
  169810. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  169811. { action; } \
  169812. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  169813. #define GET_BITS(nbits) \
  169814. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  169815. #define PEEK_BITS(nbits) \
  169816. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  169817. #define DROP_BITS(nbits) \
  169818. (bits_left -= (nbits))
  169819. /* Load up the bit buffer to a depth of at least nbits */
  169820. EXTERN(boolean) jpeg_fill_bit_buffer
  169821. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  169822. register int bits_left, int nbits));
  169823. /*
  169824. * Code for extracting next Huffman-coded symbol from input bit stream.
  169825. * Again, this is time-critical and we make the main paths be macros.
  169826. *
  169827. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  169828. * without looping. Usually, more than 95% of the Huffman codes will be 8
  169829. * or fewer bits long. The few overlength codes are handled with a loop,
  169830. * which need not be inline code.
  169831. *
  169832. * Notes about the HUFF_DECODE macro:
  169833. * 1. Near the end of the data segment, we may fail to get enough bits
  169834. * for a lookahead. In that case, we do it the hard way.
  169835. * 2. If the lookahead table contains no entry, the next code must be
  169836. * more than HUFF_LOOKAHEAD bits long.
  169837. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  169838. */
  169839. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  169840. { register int nb, look; \
  169841. if (bits_left < HUFF_LOOKAHEAD) { \
  169842. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  169843. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  169844. if (bits_left < HUFF_LOOKAHEAD) { \
  169845. nb = 1; goto slowlabel; \
  169846. } \
  169847. } \
  169848. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  169849. if ((nb = htbl->look_nbits[look]) != 0) { \
  169850. DROP_BITS(nb); \
  169851. result = htbl->look_sym[look]; \
  169852. } else { \
  169853. nb = HUFF_LOOKAHEAD+1; \
  169854. slowlabel: \
  169855. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  169856. { failaction; } \
  169857. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  169858. } \
  169859. }
  169860. /* Out-of-line case for Huffman code fetching */
  169861. EXTERN(int) jpeg_huff_decode
  169862. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  169863. register int bits_left, d_derived_tbl * htbl, int min_bits));
  169864. #endif
  169865. /*** End of inlined file: jdhuff.h ***/
  169866. /* Declarations shared with jdphuff.c */
  169867. /*
  169868. * Expanded entropy decoder object for Huffman decoding.
  169869. *
  169870. * The savable_state subrecord contains fields that change within an MCU,
  169871. * but must not be updated permanently until we complete the MCU.
  169872. */
  169873. typedef struct {
  169874. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  169875. } savable_state2;
  169876. /* This macro is to work around compilers with missing or broken
  169877. * structure assignment. You'll need to fix this code if you have
  169878. * such a compiler and you change MAX_COMPS_IN_SCAN.
  169879. */
  169880. #ifndef NO_STRUCT_ASSIGN
  169881. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  169882. #else
  169883. #if MAX_COMPS_IN_SCAN == 4
  169884. #define ASSIGN_STATE(dest,src) \
  169885. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  169886. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  169887. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  169888. (dest).last_dc_val[3] = (src).last_dc_val[3])
  169889. #endif
  169890. #endif
  169891. typedef struct {
  169892. struct jpeg_entropy_decoder pub; /* public fields */
  169893. /* These fields are loaded into local variables at start of each MCU.
  169894. * In case of suspension, we exit WITHOUT updating them.
  169895. */
  169896. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  169897. savable_state2 saved; /* Other state at start of MCU */
  169898. /* These fields are NOT loaded into local working state. */
  169899. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  169900. /* Pointers to derived tables (these workspaces have image lifespan) */
  169901. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  169902. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  169903. /* Precalculated info set up by start_pass for use in decode_mcu: */
  169904. /* Pointers to derived tables to be used for each block within an MCU */
  169905. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169906. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  169907. /* Whether we care about the DC and AC coefficient values for each block */
  169908. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  169909. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  169910. } huff_entropy_decoder2;
  169911. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  169912. /*
  169913. * Initialize for a Huffman-compressed scan.
  169914. */
  169915. METHODDEF(void)
  169916. start_pass_huff_decoder (j_decompress_ptr cinfo)
  169917. {
  169918. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  169919. int ci, blkn, dctbl, actbl;
  169920. jpeg_component_info * compptr;
  169921. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  169922. * This ought to be an error condition, but we make it a warning because
  169923. * there are some baseline files out there with all zeroes in these bytes.
  169924. */
  169925. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  169926. cinfo->Ah != 0 || cinfo->Al != 0)
  169927. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  169928. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169929. compptr = cinfo->cur_comp_info[ci];
  169930. dctbl = compptr->dc_tbl_no;
  169931. actbl = compptr->ac_tbl_no;
  169932. /* Compute derived values for Huffman tables */
  169933. /* We may do this more than once for a table, but it's not expensive */
  169934. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  169935. & entropy->dc_derived_tbls[dctbl]);
  169936. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  169937. & entropy->ac_derived_tbls[actbl]);
  169938. /* Initialize DC predictions to 0 */
  169939. entropy->saved.last_dc_val[ci] = 0;
  169940. }
  169941. /* Precalculate decoding info for each block in an MCU of this scan */
  169942. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  169943. ci = cinfo->MCU_membership[blkn];
  169944. compptr = cinfo->cur_comp_info[ci];
  169945. /* Precalculate which table to use for each block */
  169946. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  169947. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  169948. /* Decide whether we really care about the coefficient values */
  169949. if (compptr->component_needed) {
  169950. entropy->dc_needed[blkn] = TRUE;
  169951. /* we don't need the ACs if producing a 1/8th-size image */
  169952. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  169953. } else {
  169954. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  169955. }
  169956. }
  169957. /* Initialize bitread state variables */
  169958. entropy->bitstate.bits_left = 0;
  169959. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  169960. entropy->pub.insufficient_data = FALSE;
  169961. /* Initialize restart counter */
  169962. entropy->restarts_to_go = cinfo->restart_interval;
  169963. }
  169964. /*
  169965. * Compute the derived values for a Huffman table.
  169966. * This routine also performs some validation checks on the table.
  169967. *
  169968. * Note this is also used by jdphuff.c.
  169969. */
  169970. GLOBAL(void)
  169971. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  169972. d_derived_tbl ** pdtbl)
  169973. {
  169974. JHUFF_TBL *htbl;
  169975. d_derived_tbl *dtbl;
  169976. int p, i, l, si, numsymbols;
  169977. int lookbits, ctr;
  169978. char huffsize[257];
  169979. unsigned int huffcode[257];
  169980. unsigned int code;
  169981. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  169982. * paralleling the order of the symbols themselves in htbl->huffval[].
  169983. */
  169984. /* Find the input Huffman table */
  169985. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  169986. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  169987. htbl =
  169988. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  169989. if (htbl == NULL)
  169990. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  169991. /* Allocate a workspace if we haven't already done so. */
  169992. if (*pdtbl == NULL)
  169993. *pdtbl = (d_derived_tbl *)
  169994. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169995. SIZEOF(d_derived_tbl));
  169996. dtbl = *pdtbl;
  169997. dtbl->pub = htbl; /* fill in back link */
  169998. /* Figure C.1: make table of Huffman code length for each symbol */
  169999. p = 0;
  170000. for (l = 1; l <= 16; l++) {
  170001. i = (int) htbl->bits[l];
  170002. if (i < 0 || p + i > 256) /* protect against table overrun */
  170003. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170004. while (i--)
  170005. huffsize[p++] = (char) l;
  170006. }
  170007. huffsize[p] = 0;
  170008. numsymbols = p;
  170009. /* Figure C.2: generate the codes themselves */
  170010. /* We also validate that the counts represent a legal Huffman code tree. */
  170011. code = 0;
  170012. si = huffsize[0];
  170013. p = 0;
  170014. while (huffsize[p]) {
  170015. while (((int) huffsize[p]) == si) {
  170016. huffcode[p++] = code;
  170017. code++;
  170018. }
  170019. /* code is now 1 more than the last code used for codelength si; but
  170020. * it must still fit in si bits, since no code is allowed to be all ones.
  170021. */
  170022. if (((INT32) code) >= (((INT32) 1) << si))
  170023. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170024. code <<= 1;
  170025. si++;
  170026. }
  170027. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  170028. p = 0;
  170029. for (l = 1; l <= 16; l++) {
  170030. if (htbl->bits[l]) {
  170031. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  170032. * minus the minimum code of length l
  170033. */
  170034. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  170035. p += htbl->bits[l];
  170036. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  170037. } else {
  170038. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  170039. }
  170040. }
  170041. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  170042. /* Compute lookahead tables to speed up decoding.
  170043. * First we set all the table entries to 0, indicating "too long";
  170044. * then we iterate through the Huffman codes that are short enough and
  170045. * fill in all the entries that correspond to bit sequences starting
  170046. * with that code.
  170047. */
  170048. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  170049. p = 0;
  170050. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  170051. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  170052. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  170053. /* Generate left-justified code followed by all possible bit sequences */
  170054. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  170055. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  170056. dtbl->look_nbits[lookbits] = l;
  170057. dtbl->look_sym[lookbits] = htbl->huffval[p];
  170058. lookbits++;
  170059. }
  170060. }
  170061. }
  170062. /* Validate symbols as being reasonable.
  170063. * For AC tables, we make no check, but accept all byte values 0..255.
  170064. * For DC tables, we require the symbols to be in range 0..15.
  170065. * (Tighter bounds could be applied depending on the data depth and mode,
  170066. * but this is sufficient to ensure safe decoding.)
  170067. */
  170068. if (isDC) {
  170069. for (i = 0; i < numsymbols; i++) {
  170070. int sym = htbl->huffval[i];
  170071. if (sym < 0 || sym > 15)
  170072. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170073. }
  170074. }
  170075. }
  170076. /*
  170077. * Out-of-line code for bit fetching (shared with jdphuff.c).
  170078. * See jdhuff.h for info about usage.
  170079. * Note: current values of get_buffer and bits_left are passed as parameters,
  170080. * but are returned in the corresponding fields of the state struct.
  170081. *
  170082. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  170083. * of get_buffer to be used. (On machines with wider words, an even larger
  170084. * buffer could be used.) However, on some machines 32-bit shifts are
  170085. * quite slow and take time proportional to the number of places shifted.
  170086. * (This is true with most PC compilers, for instance.) In this case it may
  170087. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  170088. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  170089. */
  170090. #ifdef SLOW_SHIFT_32
  170091. #define MIN_GET_BITS 15 /* minimum allowable value */
  170092. #else
  170093. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  170094. #endif
  170095. GLOBAL(boolean)
  170096. jpeg_fill_bit_buffer (bitread_working_state * state,
  170097. register bit_buf_type get_buffer, register int bits_left,
  170098. int nbits)
  170099. /* Load up the bit buffer to a depth of at least nbits */
  170100. {
  170101. /* Copy heavily used state fields into locals (hopefully registers) */
  170102. register const JOCTET * next_input_byte = state->next_input_byte;
  170103. register size_t bytes_in_buffer = state->bytes_in_buffer;
  170104. j_decompress_ptr cinfo = state->cinfo;
  170105. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  170106. /* (It is assumed that no request will be for more than that many bits.) */
  170107. /* We fail to do so only if we hit a marker or are forced to suspend. */
  170108. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  170109. while (bits_left < MIN_GET_BITS) {
  170110. register int c;
  170111. /* Attempt to read a byte */
  170112. if (bytes_in_buffer == 0) {
  170113. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  170114. return FALSE;
  170115. next_input_byte = cinfo->src->next_input_byte;
  170116. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  170117. }
  170118. bytes_in_buffer--;
  170119. c = GETJOCTET(*next_input_byte++);
  170120. /* If it's 0xFF, check and discard stuffed zero byte */
  170121. if (c == 0xFF) {
  170122. /* Loop here to discard any padding FF's on terminating marker,
  170123. * so that we can save a valid unread_marker value. NOTE: we will
  170124. * accept multiple FF's followed by a 0 as meaning a single FF data
  170125. * byte. This data pattern is not valid according to the standard.
  170126. */
  170127. do {
  170128. if (bytes_in_buffer == 0) {
  170129. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  170130. return FALSE;
  170131. next_input_byte = cinfo->src->next_input_byte;
  170132. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  170133. }
  170134. bytes_in_buffer--;
  170135. c = GETJOCTET(*next_input_byte++);
  170136. } while (c == 0xFF);
  170137. if (c == 0) {
  170138. /* Found FF/00, which represents an FF data byte */
  170139. c = 0xFF;
  170140. } else {
  170141. /* Oops, it's actually a marker indicating end of compressed data.
  170142. * Save the marker code for later use.
  170143. * Fine point: it might appear that we should save the marker into
  170144. * bitread working state, not straight into permanent state. But
  170145. * once we have hit a marker, we cannot need to suspend within the
  170146. * current MCU, because we will read no more bytes from the data
  170147. * source. So it is OK to update permanent state right away.
  170148. */
  170149. cinfo->unread_marker = c;
  170150. /* See if we need to insert some fake zero bits. */
  170151. goto no_more_bytes;
  170152. }
  170153. }
  170154. /* OK, load c into get_buffer */
  170155. get_buffer = (get_buffer << 8) | c;
  170156. bits_left += 8;
  170157. } /* end while */
  170158. } else {
  170159. no_more_bytes:
  170160. /* We get here if we've read the marker that terminates the compressed
  170161. * data segment. There should be enough bits in the buffer register
  170162. * to satisfy the request; if so, no problem.
  170163. */
  170164. if (nbits > bits_left) {
  170165. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  170166. * the data stream, so that we can produce some kind of image.
  170167. * We use a nonvolatile flag to ensure that only one warning message
  170168. * appears per data segment.
  170169. */
  170170. if (! cinfo->entropy->insufficient_data) {
  170171. WARNMS(cinfo, JWRN_HIT_MARKER);
  170172. cinfo->entropy->insufficient_data = TRUE;
  170173. }
  170174. /* Fill the buffer with zero bits */
  170175. get_buffer <<= MIN_GET_BITS - bits_left;
  170176. bits_left = MIN_GET_BITS;
  170177. }
  170178. }
  170179. /* Unload the local registers */
  170180. state->next_input_byte = next_input_byte;
  170181. state->bytes_in_buffer = bytes_in_buffer;
  170182. state->get_buffer = get_buffer;
  170183. state->bits_left = bits_left;
  170184. return TRUE;
  170185. }
  170186. /*
  170187. * Out-of-line code for Huffman code decoding.
  170188. * See jdhuff.h for info about usage.
  170189. */
  170190. GLOBAL(int)
  170191. jpeg_huff_decode (bitread_working_state * state,
  170192. register bit_buf_type get_buffer, register int bits_left,
  170193. d_derived_tbl * htbl, int min_bits)
  170194. {
  170195. register int l = min_bits;
  170196. register INT32 code;
  170197. /* HUFF_DECODE has determined that the code is at least min_bits */
  170198. /* bits long, so fetch that many bits in one swoop. */
  170199. CHECK_BIT_BUFFER(*state, l, return -1);
  170200. code = GET_BITS(l);
  170201. /* Collect the rest of the Huffman code one bit at a time. */
  170202. /* This is per Figure F.16 in the JPEG spec. */
  170203. while (code > htbl->maxcode[l]) {
  170204. code <<= 1;
  170205. CHECK_BIT_BUFFER(*state, 1, return -1);
  170206. code |= GET_BITS(1);
  170207. l++;
  170208. }
  170209. /* Unload the local registers */
  170210. state->get_buffer = get_buffer;
  170211. state->bits_left = bits_left;
  170212. /* With garbage input we may reach the sentinel value l = 17. */
  170213. if (l > 16) {
  170214. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  170215. return 0; /* fake a zero as the safest result */
  170216. }
  170217. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  170218. }
  170219. /*
  170220. * Check for a restart marker & resynchronize decoder.
  170221. * Returns FALSE if must suspend.
  170222. */
  170223. LOCAL(boolean)
  170224. process_restart (j_decompress_ptr cinfo)
  170225. {
  170226. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170227. int ci;
  170228. /* Throw away any unused bits remaining in bit buffer; */
  170229. /* include any full bytes in next_marker's count of discarded bytes */
  170230. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  170231. entropy->bitstate.bits_left = 0;
  170232. /* Advance past the RSTn marker */
  170233. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  170234. return FALSE;
  170235. /* Re-initialize DC predictions to 0 */
  170236. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  170237. entropy->saved.last_dc_val[ci] = 0;
  170238. /* Reset restart counter */
  170239. entropy->restarts_to_go = cinfo->restart_interval;
  170240. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  170241. * against a marker. In that case we will end up treating the next data
  170242. * segment as empty, and we can avoid producing bogus output pixels by
  170243. * leaving the flag set.
  170244. */
  170245. if (cinfo->unread_marker == 0)
  170246. entropy->pub.insufficient_data = FALSE;
  170247. return TRUE;
  170248. }
  170249. /*
  170250. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  170251. * The coefficients are reordered from zigzag order into natural array order,
  170252. * but are not dequantized.
  170253. *
  170254. * The i'th block of the MCU is stored into the block pointed to by
  170255. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  170256. * (Wholesale zeroing is usually a little faster than retail...)
  170257. *
  170258. * Returns FALSE if data source requested suspension. In that case no
  170259. * changes have been made to permanent state. (Exception: some output
  170260. * coefficients may already have been assigned. This is harmless for
  170261. * this module, since we'll just re-assign them on the next call.)
  170262. */
  170263. METHODDEF(boolean)
  170264. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  170265. {
  170266. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170267. int blkn;
  170268. BITREAD_STATE_VARS;
  170269. savable_state2 state;
  170270. /* Process restart marker if needed; may have to suspend */
  170271. if (cinfo->restart_interval) {
  170272. if (entropy->restarts_to_go == 0)
  170273. if (! process_restart(cinfo))
  170274. return FALSE;
  170275. }
  170276. /* If we've run out of data, just leave the MCU set to zeroes.
  170277. * This way, we return uniform gray for the remainder of the segment.
  170278. */
  170279. if (! entropy->pub.insufficient_data) {
  170280. /* Load up working state */
  170281. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  170282. ASSIGN_STATE(state, entropy->saved);
  170283. /* Outer loop handles each block in the MCU */
  170284. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  170285. JBLOCKROW block = MCU_data[blkn];
  170286. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  170287. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  170288. register int s, k, r;
  170289. /* Decode a single block's worth of coefficients */
  170290. /* Section F.2.2.1: decode the DC coefficient difference */
  170291. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  170292. if (s) {
  170293. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170294. r = GET_BITS(s);
  170295. s = HUFF_EXTEND(r, s);
  170296. }
  170297. if (entropy->dc_needed[blkn]) {
  170298. /* Convert DC difference to actual value, update last_dc_val */
  170299. int ci = cinfo->MCU_membership[blkn];
  170300. s += state.last_dc_val[ci];
  170301. state.last_dc_val[ci] = s;
  170302. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  170303. (*block)[0] = (JCOEF) s;
  170304. }
  170305. if (entropy->ac_needed[blkn]) {
  170306. /* Section F.2.2.2: decode the AC coefficients */
  170307. /* Since zeroes are skipped, output area must be cleared beforehand */
  170308. for (k = 1; k < DCTSIZE2; k++) {
  170309. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  170310. r = s >> 4;
  170311. s &= 15;
  170312. if (s) {
  170313. k += r;
  170314. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170315. r = GET_BITS(s);
  170316. s = HUFF_EXTEND(r, s);
  170317. /* Output coefficient in natural (dezigzagged) order.
  170318. * Note: the extra entries in jpeg_natural_order[] will save us
  170319. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  170320. */
  170321. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  170322. } else {
  170323. if (r != 15)
  170324. break;
  170325. k += 15;
  170326. }
  170327. }
  170328. } else {
  170329. /* Section F.2.2.2: decode the AC coefficients */
  170330. /* In this path we just discard the values */
  170331. for (k = 1; k < DCTSIZE2; k++) {
  170332. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  170333. r = s >> 4;
  170334. s &= 15;
  170335. if (s) {
  170336. k += r;
  170337. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170338. DROP_BITS(s);
  170339. } else {
  170340. if (r != 15)
  170341. break;
  170342. k += 15;
  170343. }
  170344. }
  170345. }
  170346. }
  170347. /* Completed MCU, so update state */
  170348. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  170349. ASSIGN_STATE(entropy->saved, state);
  170350. }
  170351. /* Account for restart interval (no-op if not using restarts) */
  170352. entropy->restarts_to_go--;
  170353. return TRUE;
  170354. }
  170355. /*
  170356. * Module initialization routine for Huffman entropy decoding.
  170357. */
  170358. GLOBAL(void)
  170359. jinit_huff_decoder (j_decompress_ptr cinfo)
  170360. {
  170361. huff_entropy_ptr2 entropy;
  170362. int i;
  170363. entropy = (huff_entropy_ptr2)
  170364. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170365. SIZEOF(huff_entropy_decoder2));
  170366. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  170367. entropy->pub.start_pass = start_pass_huff_decoder;
  170368. entropy->pub.decode_mcu = decode_mcu;
  170369. /* Mark tables unallocated */
  170370. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  170371. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  170372. }
  170373. }
  170374. /*** End of inlined file: jdhuff.c ***/
  170375. /*** Start of inlined file: jdinput.c ***/
  170376. #define JPEG_INTERNALS
  170377. /* Private state */
  170378. typedef struct {
  170379. struct jpeg_input_controller pub; /* public fields */
  170380. boolean inheaders; /* TRUE until first SOS is reached */
  170381. } my_input_controller;
  170382. typedef my_input_controller * my_inputctl_ptr;
  170383. /* Forward declarations */
  170384. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  170385. /*
  170386. * Routines to calculate various quantities related to the size of the image.
  170387. */
  170388. LOCAL(void)
  170389. initial_setup2 (j_decompress_ptr cinfo)
  170390. /* Called once, when first SOS marker is reached */
  170391. {
  170392. int ci;
  170393. jpeg_component_info *compptr;
  170394. /* Make sure image isn't bigger than I can handle */
  170395. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  170396. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  170397. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  170398. /* For now, precision must match compiled-in value... */
  170399. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  170400. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  170401. /* Check that number of components won't exceed internal array sizes */
  170402. if (cinfo->num_components > MAX_COMPONENTS)
  170403. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  170404. MAX_COMPONENTS);
  170405. /* Compute maximum sampling factors; check factor validity */
  170406. cinfo->max_h_samp_factor = 1;
  170407. cinfo->max_v_samp_factor = 1;
  170408. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170409. ci++, compptr++) {
  170410. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  170411. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  170412. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  170413. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  170414. compptr->h_samp_factor);
  170415. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  170416. compptr->v_samp_factor);
  170417. }
  170418. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  170419. * In the full decompressor, this will be overridden by jdmaster.c;
  170420. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  170421. */
  170422. cinfo->min_DCT_scaled_size = DCTSIZE;
  170423. /* Compute dimensions of components */
  170424. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170425. ci++, compptr++) {
  170426. compptr->DCT_scaled_size = DCTSIZE;
  170427. /* Size in DCT blocks */
  170428. compptr->width_in_blocks = (JDIMENSION)
  170429. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170430. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  170431. compptr->height_in_blocks = (JDIMENSION)
  170432. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170433. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  170434. /* downsampled_width and downsampled_height will also be overridden by
  170435. * jdmaster.c if we are doing full decompression. The transcoder library
  170436. * doesn't use these values, but the calling application might.
  170437. */
  170438. /* Size in samples */
  170439. compptr->downsampled_width = (JDIMENSION)
  170440. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170441. (long) cinfo->max_h_samp_factor);
  170442. compptr->downsampled_height = (JDIMENSION)
  170443. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170444. (long) cinfo->max_v_samp_factor);
  170445. /* Mark component needed, until color conversion says otherwise */
  170446. compptr->component_needed = TRUE;
  170447. /* Mark no quantization table yet saved for component */
  170448. compptr->quant_table = NULL;
  170449. }
  170450. /* Compute number of fully interleaved MCU rows. */
  170451. cinfo->total_iMCU_rows = (JDIMENSION)
  170452. jdiv_round_up((long) cinfo->image_height,
  170453. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170454. /* Decide whether file contains multiple scans */
  170455. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  170456. cinfo->inputctl->has_multiple_scans = TRUE;
  170457. else
  170458. cinfo->inputctl->has_multiple_scans = FALSE;
  170459. }
  170460. LOCAL(void)
  170461. per_scan_setup2 (j_decompress_ptr cinfo)
  170462. /* Do computations that are needed before processing a JPEG scan */
  170463. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  170464. {
  170465. int ci, mcublks, tmp;
  170466. jpeg_component_info *compptr;
  170467. if (cinfo->comps_in_scan == 1) {
  170468. /* Noninterleaved (single-component) scan */
  170469. compptr = cinfo->cur_comp_info[0];
  170470. /* Overall image size in MCUs */
  170471. cinfo->MCUs_per_row = compptr->width_in_blocks;
  170472. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  170473. /* For noninterleaved scan, always one block per MCU */
  170474. compptr->MCU_width = 1;
  170475. compptr->MCU_height = 1;
  170476. compptr->MCU_blocks = 1;
  170477. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  170478. compptr->last_col_width = 1;
  170479. /* For noninterleaved scans, it is convenient to define last_row_height
  170480. * as the number of block rows present in the last iMCU row.
  170481. */
  170482. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  170483. if (tmp == 0) tmp = compptr->v_samp_factor;
  170484. compptr->last_row_height = tmp;
  170485. /* Prepare array describing MCU composition */
  170486. cinfo->blocks_in_MCU = 1;
  170487. cinfo->MCU_membership[0] = 0;
  170488. } else {
  170489. /* Interleaved (multi-component) scan */
  170490. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  170491. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  170492. MAX_COMPS_IN_SCAN);
  170493. /* Overall image size in MCUs */
  170494. cinfo->MCUs_per_row = (JDIMENSION)
  170495. jdiv_round_up((long) cinfo->image_width,
  170496. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  170497. cinfo->MCU_rows_in_scan = (JDIMENSION)
  170498. jdiv_round_up((long) cinfo->image_height,
  170499. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170500. cinfo->blocks_in_MCU = 0;
  170501. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170502. compptr = cinfo->cur_comp_info[ci];
  170503. /* Sampling factors give # of blocks of component in each MCU */
  170504. compptr->MCU_width = compptr->h_samp_factor;
  170505. compptr->MCU_height = compptr->v_samp_factor;
  170506. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  170507. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  170508. /* Figure number of non-dummy blocks in last MCU column & row */
  170509. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  170510. if (tmp == 0) tmp = compptr->MCU_width;
  170511. compptr->last_col_width = tmp;
  170512. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  170513. if (tmp == 0) tmp = compptr->MCU_height;
  170514. compptr->last_row_height = tmp;
  170515. /* Prepare array describing MCU composition */
  170516. mcublks = compptr->MCU_blocks;
  170517. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  170518. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  170519. while (mcublks-- > 0) {
  170520. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  170521. }
  170522. }
  170523. }
  170524. }
  170525. /*
  170526. * Save away a copy of the Q-table referenced by each component present
  170527. * in the current scan, unless already saved during a prior scan.
  170528. *
  170529. * In a multiple-scan JPEG file, the encoder could assign different components
  170530. * the same Q-table slot number, but change table definitions between scans
  170531. * so that each component uses a different Q-table. (The IJG encoder is not
  170532. * currently capable of doing this, but other encoders might.) Since we want
  170533. * to be able to dequantize all the components at the end of the file, this
  170534. * means that we have to save away the table actually used for each component.
  170535. * We do this by copying the table at the start of the first scan containing
  170536. * the component.
  170537. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  170538. * slot between scans of a component using that slot. If the encoder does so
  170539. * anyway, this decoder will simply use the Q-table values that were current
  170540. * at the start of the first scan for the component.
  170541. *
  170542. * The decompressor output side looks only at the saved quant tables,
  170543. * not at the current Q-table slots.
  170544. */
  170545. LOCAL(void)
  170546. latch_quant_tables (j_decompress_ptr cinfo)
  170547. {
  170548. int ci, qtblno;
  170549. jpeg_component_info *compptr;
  170550. JQUANT_TBL * qtbl;
  170551. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170552. compptr = cinfo->cur_comp_info[ci];
  170553. /* No work if we already saved Q-table for this component */
  170554. if (compptr->quant_table != NULL)
  170555. continue;
  170556. /* Make sure specified quantization table is present */
  170557. qtblno = compptr->quant_tbl_no;
  170558. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  170559. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  170560. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  170561. /* OK, save away the quantization table */
  170562. qtbl = (JQUANT_TBL *)
  170563. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170564. SIZEOF(JQUANT_TBL));
  170565. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  170566. compptr->quant_table = qtbl;
  170567. }
  170568. }
  170569. /*
  170570. * Initialize the input modules to read a scan of compressed data.
  170571. * The first call to this is done by jdmaster.c after initializing
  170572. * the entire decompressor (during jpeg_start_decompress).
  170573. * Subsequent calls come from consume_markers, below.
  170574. */
  170575. METHODDEF(void)
  170576. start_input_pass2 (j_decompress_ptr cinfo)
  170577. {
  170578. per_scan_setup2(cinfo);
  170579. latch_quant_tables(cinfo);
  170580. (*cinfo->entropy->start_pass) (cinfo);
  170581. (*cinfo->coef->start_input_pass) (cinfo);
  170582. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  170583. }
  170584. /*
  170585. * Finish up after inputting a compressed-data scan.
  170586. * This is called by the coefficient controller after it's read all
  170587. * the expected data of the scan.
  170588. */
  170589. METHODDEF(void)
  170590. finish_input_pass (j_decompress_ptr cinfo)
  170591. {
  170592. cinfo->inputctl->consume_input = consume_markers;
  170593. }
  170594. /*
  170595. * Read JPEG markers before, between, or after compressed-data scans.
  170596. * Change state as necessary when a new scan is reached.
  170597. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  170598. *
  170599. * The consume_input method pointer points either here or to the
  170600. * coefficient controller's consume_data routine, depending on whether
  170601. * we are reading a compressed data segment or inter-segment markers.
  170602. */
  170603. METHODDEF(int)
  170604. consume_markers (j_decompress_ptr cinfo)
  170605. {
  170606. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170607. int val;
  170608. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  170609. return JPEG_REACHED_EOI;
  170610. val = (*cinfo->marker->read_markers) (cinfo);
  170611. switch (val) {
  170612. case JPEG_REACHED_SOS: /* Found SOS */
  170613. if (inputctl->inheaders) { /* 1st SOS */
  170614. initial_setup2(cinfo);
  170615. inputctl->inheaders = FALSE;
  170616. /* Note: start_input_pass must be called by jdmaster.c
  170617. * before any more input can be consumed. jdapimin.c is
  170618. * responsible for enforcing this sequencing.
  170619. */
  170620. } else { /* 2nd or later SOS marker */
  170621. if (! inputctl->pub.has_multiple_scans)
  170622. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  170623. start_input_pass2(cinfo);
  170624. }
  170625. break;
  170626. case JPEG_REACHED_EOI: /* Found EOI */
  170627. inputctl->pub.eoi_reached = TRUE;
  170628. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  170629. if (cinfo->marker->saw_SOF)
  170630. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  170631. } else {
  170632. /* Prevent infinite loop in coef ctlr's decompress_data routine
  170633. * if user set output_scan_number larger than number of scans.
  170634. */
  170635. if (cinfo->output_scan_number > cinfo->input_scan_number)
  170636. cinfo->output_scan_number = cinfo->input_scan_number;
  170637. }
  170638. break;
  170639. case JPEG_SUSPENDED:
  170640. break;
  170641. }
  170642. return val;
  170643. }
  170644. /*
  170645. * Reset state to begin a fresh datastream.
  170646. */
  170647. METHODDEF(void)
  170648. reset_input_controller (j_decompress_ptr cinfo)
  170649. {
  170650. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170651. inputctl->pub.consume_input = consume_markers;
  170652. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170653. inputctl->pub.eoi_reached = FALSE;
  170654. inputctl->inheaders = TRUE;
  170655. /* Reset other modules */
  170656. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  170657. (*cinfo->marker->reset_marker_reader) (cinfo);
  170658. /* Reset progression state -- would be cleaner if entropy decoder did this */
  170659. cinfo->coef_bits = NULL;
  170660. }
  170661. /*
  170662. * Initialize the input controller module.
  170663. * This is called only once, when the decompression object is created.
  170664. */
  170665. GLOBAL(void)
  170666. jinit_input_controller (j_decompress_ptr cinfo)
  170667. {
  170668. my_inputctl_ptr inputctl;
  170669. /* Create subobject in permanent pool */
  170670. inputctl = (my_inputctl_ptr)
  170671. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  170672. SIZEOF(my_input_controller));
  170673. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  170674. /* Initialize method pointers */
  170675. inputctl->pub.consume_input = consume_markers;
  170676. inputctl->pub.reset_input_controller = reset_input_controller;
  170677. inputctl->pub.start_input_pass = start_input_pass2;
  170678. inputctl->pub.finish_input_pass = finish_input_pass;
  170679. /* Initialize state: can't use reset_input_controller since we don't
  170680. * want to try to reset other modules yet.
  170681. */
  170682. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170683. inputctl->pub.eoi_reached = FALSE;
  170684. inputctl->inheaders = TRUE;
  170685. }
  170686. /*** End of inlined file: jdinput.c ***/
  170687. /*** Start of inlined file: jdmainct.c ***/
  170688. #define JPEG_INTERNALS
  170689. /*
  170690. * In the current system design, the main buffer need never be a full-image
  170691. * buffer; any full-height buffers will be found inside the coefficient or
  170692. * postprocessing controllers. Nonetheless, the main controller is not
  170693. * trivial. Its responsibility is to provide context rows for upsampling/
  170694. * rescaling, and doing this in an efficient fashion is a bit tricky.
  170695. *
  170696. * Postprocessor input data is counted in "row groups". A row group
  170697. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  170698. * sample rows of each component. (We require DCT_scaled_size values to be
  170699. * chosen such that these numbers are integers. In practice DCT_scaled_size
  170700. * values will likely be powers of two, so we actually have the stronger
  170701. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  170702. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  170703. * row group (times any additional scale factor that the upsampler is
  170704. * applying).
  170705. *
  170706. * The coefficient controller will deliver data to us one iMCU row at a time;
  170707. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  170708. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  170709. * to one row of MCUs when the image is fully interleaved.) Note that the
  170710. * number of sample rows varies across components, but the number of row
  170711. * groups does not. Some garbage sample rows may be included in the last iMCU
  170712. * row at the bottom of the image.
  170713. *
  170714. * Depending on the vertical scaling algorithm used, the upsampler may need
  170715. * access to the sample row(s) above and below its current input row group.
  170716. * The upsampler is required to set need_context_rows TRUE at global selection
  170717. * time if so. When need_context_rows is FALSE, this controller can simply
  170718. * obtain one iMCU row at a time from the coefficient controller and dole it
  170719. * out as row groups to the postprocessor.
  170720. *
  170721. * When need_context_rows is TRUE, this controller guarantees that the buffer
  170722. * passed to postprocessing contains at least one row group's worth of samples
  170723. * above and below the row group(s) being processed. Note that the context
  170724. * rows "above" the first passed row group appear at negative row offsets in
  170725. * the passed buffer. At the top and bottom of the image, the required
  170726. * context rows are manufactured by duplicating the first or last real sample
  170727. * row; this avoids having special cases in the upsampling inner loops.
  170728. *
  170729. * The amount of context is fixed at one row group just because that's a
  170730. * convenient number for this controller to work with. The existing
  170731. * upsamplers really only need one sample row of context. An upsampler
  170732. * supporting arbitrary output rescaling might wish for more than one row
  170733. * group of context when shrinking the image; tough, we don't handle that.
  170734. * (This is justified by the assumption that downsizing will be handled mostly
  170735. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  170736. * the upsample step needn't be much less than one.)
  170737. *
  170738. * To provide the desired context, we have to retain the last two row groups
  170739. * of one iMCU row while reading in the next iMCU row. (The last row group
  170740. * can't be processed until we have another row group for its below-context,
  170741. * and so we have to save the next-to-last group too for its above-context.)
  170742. * We could do this most simply by copying data around in our buffer, but
  170743. * that'd be very slow. We can avoid copying any data by creating a rather
  170744. * strange pointer structure. Here's how it works. We allocate a workspace
  170745. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  170746. * of row groups per iMCU row). We create two sets of redundant pointers to
  170747. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  170748. * pointer lists look like this:
  170749. * M+1 M-1
  170750. * master pointer --> 0 master pointer --> 0
  170751. * 1 1
  170752. * ... ...
  170753. * M-3 M-3
  170754. * M-2 M
  170755. * M-1 M+1
  170756. * M M-2
  170757. * M+1 M-1
  170758. * 0 0
  170759. * We read alternate iMCU rows using each master pointer; thus the last two
  170760. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  170761. * The pointer lists are set up so that the required context rows appear to
  170762. * be adjacent to the proper places when we pass the pointer lists to the
  170763. * upsampler.
  170764. *
  170765. * The above pictures describe the normal state of the pointer lists.
  170766. * At top and bottom of the image, we diddle the pointer lists to duplicate
  170767. * the first or last sample row as necessary (this is cheaper than copying
  170768. * sample rows around).
  170769. *
  170770. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  170771. * situation each iMCU row provides only one row group so the buffering logic
  170772. * must be different (eg, we must read two iMCU rows before we can emit the
  170773. * first row group). For now, we simply do not support providing context
  170774. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  170775. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  170776. * want it quick and dirty, so a context-free upsampler is sufficient.
  170777. */
  170778. /* Private buffer controller object */
  170779. typedef struct {
  170780. struct jpeg_d_main_controller pub; /* public fields */
  170781. /* Pointer to allocated workspace (M or M+2 row groups). */
  170782. JSAMPARRAY buffer[MAX_COMPONENTS];
  170783. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  170784. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  170785. /* Remaining fields are only used in the context case. */
  170786. /* These are the master pointers to the funny-order pointer lists. */
  170787. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  170788. int whichptr; /* indicates which pointer set is now in use */
  170789. int context_state; /* process_data state machine status */
  170790. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  170791. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  170792. } my_main_controller4;
  170793. typedef my_main_controller4 * my_main_ptr4;
  170794. /* context_state values: */
  170795. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  170796. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  170797. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  170798. /* Forward declarations */
  170799. METHODDEF(void) process_data_simple_main2
  170800. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170801. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170802. METHODDEF(void) process_data_context_main
  170803. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170804. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170805. #ifdef QUANT_2PASS_SUPPORTED
  170806. METHODDEF(void) process_data_crank_post
  170807. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  170808. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  170809. #endif
  170810. LOCAL(void)
  170811. alloc_funny_pointers (j_decompress_ptr cinfo)
  170812. /* Allocate space for the funny pointer lists.
  170813. * This is done only once, not once per pass.
  170814. */
  170815. {
  170816. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170817. int ci, rgroup;
  170818. int M = cinfo->min_DCT_scaled_size;
  170819. jpeg_component_info *compptr;
  170820. JSAMPARRAY xbuf;
  170821. /* Get top-level space for component array pointers.
  170822. * We alloc both arrays with one call to save a few cycles.
  170823. */
  170824. main_->xbuffer[0] = (JSAMPIMAGE)
  170825. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170826. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  170827. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  170828. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170829. ci++, compptr++) {
  170830. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170831. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170832. /* Get space for pointer lists --- M+4 row groups in each list.
  170833. * We alloc both pointer lists with one call to save a few cycles.
  170834. */
  170835. xbuf = (JSAMPARRAY)
  170836. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170837. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  170838. xbuf += rgroup; /* want one row group at negative offsets */
  170839. main_->xbuffer[0][ci] = xbuf;
  170840. xbuf += rgroup * (M + 4);
  170841. main_->xbuffer[1][ci] = xbuf;
  170842. }
  170843. }
  170844. LOCAL(void)
  170845. make_funny_pointers (j_decompress_ptr cinfo)
  170846. /* Create the funny pointer lists discussed in the comments above.
  170847. * The actual workspace is already allocated (in main->buffer),
  170848. * and the space for the pointer lists is allocated too.
  170849. * This routine just fills in the curiously ordered lists.
  170850. * This will be repeated at the beginning of each pass.
  170851. */
  170852. {
  170853. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170854. int ci, i, rgroup;
  170855. int M = cinfo->min_DCT_scaled_size;
  170856. jpeg_component_info *compptr;
  170857. JSAMPARRAY buf, xbuf0, xbuf1;
  170858. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170859. ci++, compptr++) {
  170860. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170861. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170862. xbuf0 = main_->xbuffer[0][ci];
  170863. xbuf1 = main_->xbuffer[1][ci];
  170864. /* First copy the workspace pointers as-is */
  170865. buf = main_->buffer[ci];
  170866. for (i = 0; i < rgroup * (M + 2); i++) {
  170867. xbuf0[i] = xbuf1[i] = buf[i];
  170868. }
  170869. /* In the second list, put the last four row groups in swapped order */
  170870. for (i = 0; i < rgroup * 2; i++) {
  170871. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  170872. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  170873. }
  170874. /* The wraparound pointers at top and bottom will be filled later
  170875. * (see set_wraparound_pointers, below). Initially we want the "above"
  170876. * pointers to duplicate the first actual data line. This only needs
  170877. * to happen in xbuffer[0].
  170878. */
  170879. for (i = 0; i < rgroup; i++) {
  170880. xbuf0[i - rgroup] = xbuf0[0];
  170881. }
  170882. }
  170883. }
  170884. LOCAL(void)
  170885. set_wraparound_pointers (j_decompress_ptr cinfo)
  170886. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  170887. * This changes the pointer list state from top-of-image to the normal state.
  170888. */
  170889. {
  170890. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170891. int ci, i, rgroup;
  170892. int M = cinfo->min_DCT_scaled_size;
  170893. jpeg_component_info *compptr;
  170894. JSAMPARRAY xbuf0, xbuf1;
  170895. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170896. ci++, compptr++) {
  170897. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  170898. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  170899. xbuf0 = main_->xbuffer[0][ci];
  170900. xbuf1 = main_->xbuffer[1][ci];
  170901. for (i = 0; i < rgroup; i++) {
  170902. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  170903. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  170904. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  170905. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  170906. }
  170907. }
  170908. }
  170909. LOCAL(void)
  170910. set_bottom_pointers (j_decompress_ptr cinfo)
  170911. /* Change the pointer lists to duplicate the last sample row at the bottom
  170912. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  170913. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  170914. */
  170915. {
  170916. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170917. int ci, i, rgroup, iMCUheight, rows_left;
  170918. jpeg_component_info *compptr;
  170919. JSAMPARRAY xbuf;
  170920. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170921. ci++, compptr++) {
  170922. /* Count sample rows in one iMCU row and in one row group */
  170923. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  170924. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  170925. /* Count nondummy sample rows remaining for this component */
  170926. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  170927. if (rows_left == 0) rows_left = iMCUheight;
  170928. /* Count nondummy row groups. Should get same answer for each component,
  170929. * so we need only do it once.
  170930. */
  170931. if (ci == 0) {
  170932. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  170933. }
  170934. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  170935. * last partial rowgroup and ensures at least one full rowgroup of context.
  170936. */
  170937. xbuf = main_->xbuffer[main_->whichptr][ci];
  170938. for (i = 0; i < rgroup * 2; i++) {
  170939. xbuf[rows_left + i] = xbuf[rows_left-1];
  170940. }
  170941. }
  170942. }
  170943. /*
  170944. * Initialize for a processing pass.
  170945. */
  170946. METHODDEF(void)
  170947. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  170948. {
  170949. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170950. switch (pass_mode) {
  170951. case JBUF_PASS_THRU:
  170952. if (cinfo->upsample->need_context_rows) {
  170953. main_->pub.process_data = process_data_context_main;
  170954. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  170955. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  170956. main_->context_state = CTX_PREPARE_FOR_IMCU;
  170957. main_->iMCU_row_ctr = 0;
  170958. } else {
  170959. /* Simple case with no context needed */
  170960. main_->pub.process_data = process_data_simple_main2;
  170961. }
  170962. main_->buffer_full = FALSE; /* Mark buffer empty */
  170963. main_->rowgroup_ctr = 0;
  170964. break;
  170965. #ifdef QUANT_2PASS_SUPPORTED
  170966. case JBUF_CRANK_DEST:
  170967. /* For last pass of 2-pass quantization, just crank the postprocessor */
  170968. main_->pub.process_data = process_data_crank_post;
  170969. break;
  170970. #endif
  170971. default:
  170972. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  170973. break;
  170974. }
  170975. }
  170976. /*
  170977. * Process some data.
  170978. * This handles the simple case where no context is required.
  170979. */
  170980. METHODDEF(void)
  170981. process_data_simple_main2 (j_decompress_ptr cinfo,
  170982. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  170983. JDIMENSION out_rows_avail)
  170984. {
  170985. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  170986. JDIMENSION rowgroups_avail;
  170987. /* Read input data if we haven't filled the main buffer yet */
  170988. if (! main_->buffer_full) {
  170989. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  170990. return; /* suspension forced, can do nothing more */
  170991. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  170992. }
  170993. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  170994. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  170995. /* Note: at the bottom of the image, we may pass extra garbage row groups
  170996. * to the postprocessor. The postprocessor has to check for bottom
  170997. * of image anyway (at row resolution), so no point in us doing it too.
  170998. */
  170999. /* Feed the postprocessor */
  171000. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  171001. &main_->rowgroup_ctr, rowgroups_avail,
  171002. output_buf, out_row_ctr, out_rows_avail);
  171003. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  171004. if (main_->rowgroup_ctr >= rowgroups_avail) {
  171005. main_->buffer_full = FALSE;
  171006. main_->rowgroup_ctr = 0;
  171007. }
  171008. }
  171009. /*
  171010. * Process some data.
  171011. * This handles the case where context rows must be provided.
  171012. */
  171013. METHODDEF(void)
  171014. process_data_context_main (j_decompress_ptr cinfo,
  171015. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171016. JDIMENSION out_rows_avail)
  171017. {
  171018. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171019. /* Read input data if we haven't filled the main buffer yet */
  171020. if (! main_->buffer_full) {
  171021. if (! (*cinfo->coef->decompress_data) (cinfo,
  171022. main_->xbuffer[main_->whichptr]))
  171023. return; /* suspension forced, can do nothing more */
  171024. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  171025. main_->iMCU_row_ctr++; /* count rows received */
  171026. }
  171027. /* Postprocessor typically will not swallow all the input data it is handed
  171028. * in one call (due to filling the output buffer first). Must be prepared
  171029. * to exit and restart. This switch lets us keep track of how far we got.
  171030. * Note that each case falls through to the next on successful completion.
  171031. */
  171032. switch (main_->context_state) {
  171033. case CTX_POSTPONED_ROW:
  171034. /* Call postprocessor using previously set pointers for postponed row */
  171035. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  171036. &main_->rowgroup_ctr, main_->rowgroups_avail,
  171037. output_buf, out_row_ctr, out_rows_avail);
  171038. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  171039. return; /* Need to suspend */
  171040. main_->context_state = CTX_PREPARE_FOR_IMCU;
  171041. if (*out_row_ctr >= out_rows_avail)
  171042. return; /* Postprocessor exactly filled output buf */
  171043. /*FALLTHROUGH*/
  171044. case CTX_PREPARE_FOR_IMCU:
  171045. /* Prepare to process first M-1 row groups of this iMCU row */
  171046. main_->rowgroup_ctr = 0;
  171047. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  171048. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  171049. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  171050. */
  171051. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  171052. set_bottom_pointers(cinfo);
  171053. main_->context_state = CTX_PROCESS_IMCU;
  171054. /*FALLTHROUGH*/
  171055. case CTX_PROCESS_IMCU:
  171056. /* Call postprocessor using previously set pointers */
  171057. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  171058. &main_->rowgroup_ctr, main_->rowgroups_avail,
  171059. output_buf, out_row_ctr, out_rows_avail);
  171060. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  171061. return; /* Need to suspend */
  171062. /* After the first iMCU, change wraparound pointers to normal state */
  171063. if (main_->iMCU_row_ctr == 1)
  171064. set_wraparound_pointers(cinfo);
  171065. /* Prepare to load new iMCU row using other xbuffer list */
  171066. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  171067. main_->buffer_full = FALSE;
  171068. /* Still need to process last row group of this iMCU row, */
  171069. /* which is saved at index M+1 of the other xbuffer */
  171070. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  171071. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  171072. main_->context_state = CTX_POSTPONED_ROW;
  171073. }
  171074. }
  171075. /*
  171076. * Process some data.
  171077. * Final pass of two-pass quantization: just call the postprocessor.
  171078. * Source data will be the postprocessor controller's internal buffer.
  171079. */
  171080. #ifdef QUANT_2PASS_SUPPORTED
  171081. METHODDEF(void)
  171082. process_data_crank_post (j_decompress_ptr cinfo,
  171083. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171084. JDIMENSION out_rows_avail)
  171085. {
  171086. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  171087. (JDIMENSION *) NULL, (JDIMENSION) 0,
  171088. output_buf, out_row_ctr, out_rows_avail);
  171089. }
  171090. #endif /* QUANT_2PASS_SUPPORTED */
  171091. /*
  171092. * Initialize main buffer controller.
  171093. */
  171094. GLOBAL(void)
  171095. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  171096. {
  171097. my_main_ptr4 main_;
  171098. int ci, rgroup, ngroups;
  171099. jpeg_component_info *compptr;
  171100. main_ = (my_main_ptr4)
  171101. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171102. SIZEOF(my_main_controller4));
  171103. cinfo->main = (struct jpeg_d_main_controller *) main_;
  171104. main_->pub.start_pass = start_pass_main2;
  171105. if (need_full_buffer) /* shouldn't happen */
  171106. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  171107. /* Allocate the workspace.
  171108. * ngroups is the number of row groups we need.
  171109. */
  171110. if (cinfo->upsample->need_context_rows) {
  171111. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  171112. ERREXIT(cinfo, JERR_NOTIMPL);
  171113. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  171114. ngroups = cinfo->min_DCT_scaled_size + 2;
  171115. } else {
  171116. ngroups = cinfo->min_DCT_scaled_size;
  171117. }
  171118. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171119. ci++, compptr++) {
  171120. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171121. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171122. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  171123. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171124. compptr->width_in_blocks * compptr->DCT_scaled_size,
  171125. (JDIMENSION) (rgroup * ngroups));
  171126. }
  171127. }
  171128. /*** End of inlined file: jdmainct.c ***/
  171129. /*** Start of inlined file: jdmarker.c ***/
  171130. #define JPEG_INTERNALS
  171131. /* Private state */
  171132. typedef struct {
  171133. struct jpeg_marker_reader pub; /* public fields */
  171134. /* Application-overridable marker processing methods */
  171135. jpeg_marker_parser_method process_COM;
  171136. jpeg_marker_parser_method process_APPn[16];
  171137. /* Limit on marker data length to save for each marker type */
  171138. unsigned int length_limit_COM;
  171139. unsigned int length_limit_APPn[16];
  171140. /* Status of COM/APPn marker saving */
  171141. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  171142. unsigned int bytes_read; /* data bytes read so far in marker */
  171143. /* Note: cur_marker is not linked into marker_list until it's all read. */
  171144. } my_marker_reader;
  171145. typedef my_marker_reader * my_marker_ptr2;
  171146. /*
  171147. * Macros for fetching data from the data source module.
  171148. *
  171149. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  171150. * the current restart point; we update them only when we have reached a
  171151. * suitable place to restart if a suspension occurs.
  171152. */
  171153. /* Declare and initialize local copies of input pointer/count */
  171154. #define INPUT_VARS(cinfo) \
  171155. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  171156. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  171157. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  171158. /* Unload the local copies --- do this only at a restart boundary */
  171159. #define INPUT_SYNC(cinfo) \
  171160. ( datasrc->next_input_byte = next_input_byte, \
  171161. datasrc->bytes_in_buffer = bytes_in_buffer )
  171162. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  171163. #define INPUT_RELOAD(cinfo) \
  171164. ( next_input_byte = datasrc->next_input_byte, \
  171165. bytes_in_buffer = datasrc->bytes_in_buffer )
  171166. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  171167. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  171168. * but we must reload the local copies after a successful fill.
  171169. */
  171170. #define MAKE_BYTE_AVAIL(cinfo,action) \
  171171. if (bytes_in_buffer == 0) { \
  171172. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  171173. { action; } \
  171174. INPUT_RELOAD(cinfo); \
  171175. }
  171176. /* Read a byte into variable V.
  171177. * If must suspend, take the specified action (typically "return FALSE").
  171178. */
  171179. #define INPUT_BYTE(cinfo,V,action) \
  171180. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  171181. bytes_in_buffer--; \
  171182. V = GETJOCTET(*next_input_byte++); )
  171183. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  171184. * V should be declared unsigned int or perhaps INT32.
  171185. */
  171186. #define INPUT_2BYTES(cinfo,V,action) \
  171187. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  171188. bytes_in_buffer--; \
  171189. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  171190. MAKE_BYTE_AVAIL(cinfo,action); \
  171191. bytes_in_buffer--; \
  171192. V += GETJOCTET(*next_input_byte++); )
  171193. /*
  171194. * Routines to process JPEG markers.
  171195. *
  171196. * Entry condition: JPEG marker itself has been read and its code saved
  171197. * in cinfo->unread_marker; input restart point is just after the marker.
  171198. *
  171199. * Exit: if return TRUE, have read and processed any parameters, and have
  171200. * updated the restart point to point after the parameters.
  171201. * If return FALSE, was forced to suspend before reaching end of
  171202. * marker parameters; restart point has not been moved. Same routine
  171203. * will be called again after application supplies more input data.
  171204. *
  171205. * This approach to suspension assumes that all of a marker's parameters
  171206. * can fit into a single input bufferload. This should hold for "normal"
  171207. * markers. Some COM/APPn markers might have large parameter segments
  171208. * that might not fit. If we are simply dropping such a marker, we use
  171209. * skip_input_data to get past it, and thereby put the problem on the
  171210. * source manager's shoulders. If we are saving the marker's contents
  171211. * into memory, we use a slightly different convention: when forced to
  171212. * suspend, the marker processor updates the restart point to the end of
  171213. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  171214. * On resumption, cinfo->unread_marker still contains the marker code,
  171215. * but the data source will point to the next chunk of marker data.
  171216. * The marker processor must retain internal state to deal with this.
  171217. *
  171218. * Note that we don't bother to avoid duplicate trace messages if a
  171219. * suspension occurs within marker parameters. Other side effects
  171220. * require more care.
  171221. */
  171222. LOCAL(boolean)
  171223. get_soi (j_decompress_ptr cinfo)
  171224. /* Process an SOI marker */
  171225. {
  171226. int i;
  171227. TRACEMS(cinfo, 1, JTRC_SOI);
  171228. if (cinfo->marker->saw_SOI)
  171229. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  171230. /* Reset all parameters that are defined to be reset by SOI */
  171231. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  171232. cinfo->arith_dc_L[i] = 0;
  171233. cinfo->arith_dc_U[i] = 1;
  171234. cinfo->arith_ac_K[i] = 5;
  171235. }
  171236. cinfo->restart_interval = 0;
  171237. /* Set initial assumptions for colorspace etc */
  171238. cinfo->jpeg_color_space = JCS_UNKNOWN;
  171239. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  171240. cinfo->saw_JFIF_marker = FALSE;
  171241. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  171242. cinfo->JFIF_minor_version = 1;
  171243. cinfo->density_unit = 0;
  171244. cinfo->X_density = 1;
  171245. cinfo->Y_density = 1;
  171246. cinfo->saw_Adobe_marker = FALSE;
  171247. cinfo->Adobe_transform = 0;
  171248. cinfo->marker->saw_SOI = TRUE;
  171249. return TRUE;
  171250. }
  171251. LOCAL(boolean)
  171252. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  171253. /* Process a SOFn marker */
  171254. {
  171255. INT32 length;
  171256. int c, ci;
  171257. jpeg_component_info * compptr;
  171258. INPUT_VARS(cinfo);
  171259. cinfo->progressive_mode = is_prog;
  171260. cinfo->arith_code = is_arith;
  171261. INPUT_2BYTES(cinfo, length, return FALSE);
  171262. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  171263. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  171264. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  171265. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  171266. length -= 8;
  171267. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  171268. (int) cinfo->image_width, (int) cinfo->image_height,
  171269. cinfo->num_components);
  171270. if (cinfo->marker->saw_SOF)
  171271. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  171272. /* We don't support files in which the image height is initially specified */
  171273. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  171274. /* might as well have a general sanity check. */
  171275. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  171276. || cinfo->num_components <= 0)
  171277. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  171278. if (length != (cinfo->num_components * 3))
  171279. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171280. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  171281. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  171282. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171283. cinfo->num_components * SIZEOF(jpeg_component_info));
  171284. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171285. ci++, compptr++) {
  171286. compptr->component_index = ci;
  171287. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  171288. INPUT_BYTE(cinfo, c, return FALSE);
  171289. compptr->h_samp_factor = (c >> 4) & 15;
  171290. compptr->v_samp_factor = (c ) & 15;
  171291. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  171292. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  171293. compptr->component_id, compptr->h_samp_factor,
  171294. compptr->v_samp_factor, compptr->quant_tbl_no);
  171295. }
  171296. cinfo->marker->saw_SOF = TRUE;
  171297. INPUT_SYNC(cinfo);
  171298. return TRUE;
  171299. }
  171300. LOCAL(boolean)
  171301. get_sos (j_decompress_ptr cinfo)
  171302. /* Process a SOS marker */
  171303. {
  171304. INT32 length;
  171305. int i, ci, n, c, cc;
  171306. jpeg_component_info * compptr;
  171307. INPUT_VARS(cinfo);
  171308. if (! cinfo->marker->saw_SOF)
  171309. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  171310. INPUT_2BYTES(cinfo, length, return FALSE);
  171311. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  171312. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  171313. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  171314. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171315. cinfo->comps_in_scan = n;
  171316. /* Collect the component-spec parameters */
  171317. for (i = 0; i < n; i++) {
  171318. INPUT_BYTE(cinfo, cc, return FALSE);
  171319. INPUT_BYTE(cinfo, c, return FALSE);
  171320. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171321. ci++, compptr++) {
  171322. if (cc == compptr->component_id)
  171323. goto id_found;
  171324. }
  171325. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  171326. id_found:
  171327. cinfo->cur_comp_info[i] = compptr;
  171328. compptr->dc_tbl_no = (c >> 4) & 15;
  171329. compptr->ac_tbl_no = (c ) & 15;
  171330. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  171331. compptr->dc_tbl_no, compptr->ac_tbl_no);
  171332. }
  171333. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  171334. INPUT_BYTE(cinfo, c, return FALSE);
  171335. cinfo->Ss = c;
  171336. INPUT_BYTE(cinfo, c, return FALSE);
  171337. cinfo->Se = c;
  171338. INPUT_BYTE(cinfo, c, return FALSE);
  171339. cinfo->Ah = (c >> 4) & 15;
  171340. cinfo->Al = (c ) & 15;
  171341. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  171342. cinfo->Ah, cinfo->Al);
  171343. /* Prepare to scan data & restart markers */
  171344. cinfo->marker->next_restart_num = 0;
  171345. /* Count another SOS marker */
  171346. cinfo->input_scan_number++;
  171347. INPUT_SYNC(cinfo);
  171348. return TRUE;
  171349. }
  171350. #ifdef D_ARITH_CODING_SUPPORTED
  171351. LOCAL(boolean)
  171352. get_dac (j_decompress_ptr cinfo)
  171353. /* Process a DAC marker */
  171354. {
  171355. INT32 length;
  171356. int index, val;
  171357. INPUT_VARS(cinfo);
  171358. INPUT_2BYTES(cinfo, length, return FALSE);
  171359. length -= 2;
  171360. while (length > 0) {
  171361. INPUT_BYTE(cinfo, index, return FALSE);
  171362. INPUT_BYTE(cinfo, val, return FALSE);
  171363. length -= 2;
  171364. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  171365. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  171366. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  171367. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  171368. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  171369. } else { /* define DC table */
  171370. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  171371. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  171372. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  171373. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  171374. }
  171375. }
  171376. if (length != 0)
  171377. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171378. INPUT_SYNC(cinfo);
  171379. return TRUE;
  171380. }
  171381. #else /* ! D_ARITH_CODING_SUPPORTED */
  171382. #define get_dac(cinfo) skip_variable(cinfo)
  171383. #endif /* D_ARITH_CODING_SUPPORTED */
  171384. LOCAL(boolean)
  171385. get_dht (j_decompress_ptr cinfo)
  171386. /* Process a DHT marker */
  171387. {
  171388. INT32 length;
  171389. UINT8 bits[17];
  171390. UINT8 huffval[256];
  171391. int i, index, count;
  171392. JHUFF_TBL **htblptr;
  171393. INPUT_VARS(cinfo);
  171394. INPUT_2BYTES(cinfo, length, return FALSE);
  171395. length -= 2;
  171396. while (length > 16) {
  171397. INPUT_BYTE(cinfo, index, return FALSE);
  171398. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  171399. bits[0] = 0;
  171400. count = 0;
  171401. for (i = 1; i <= 16; i++) {
  171402. INPUT_BYTE(cinfo, bits[i], return FALSE);
  171403. count += bits[i];
  171404. }
  171405. length -= 1 + 16;
  171406. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171407. bits[1], bits[2], bits[3], bits[4],
  171408. bits[5], bits[6], bits[7], bits[8]);
  171409. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171410. bits[9], bits[10], bits[11], bits[12],
  171411. bits[13], bits[14], bits[15], bits[16]);
  171412. /* Here we just do minimal validation of the counts to avoid walking
  171413. * off the end of our table space. jdhuff.c will check more carefully.
  171414. */
  171415. if (count > 256 || ((INT32) count) > length)
  171416. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  171417. for (i = 0; i < count; i++)
  171418. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  171419. length -= count;
  171420. if (index & 0x10) { /* AC table definition */
  171421. index -= 0x10;
  171422. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  171423. } else { /* DC table definition */
  171424. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  171425. }
  171426. if (index < 0 || index >= NUM_HUFF_TBLS)
  171427. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  171428. if (*htblptr == NULL)
  171429. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  171430. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  171431. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  171432. }
  171433. if (length != 0)
  171434. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171435. INPUT_SYNC(cinfo);
  171436. return TRUE;
  171437. }
  171438. LOCAL(boolean)
  171439. get_dqt (j_decompress_ptr cinfo)
  171440. /* Process a DQT marker */
  171441. {
  171442. INT32 length;
  171443. int n, i, prec;
  171444. unsigned int tmp;
  171445. JQUANT_TBL *quant_ptr;
  171446. INPUT_VARS(cinfo);
  171447. INPUT_2BYTES(cinfo, length, return FALSE);
  171448. length -= 2;
  171449. while (length > 0) {
  171450. INPUT_BYTE(cinfo, n, return FALSE);
  171451. prec = n >> 4;
  171452. n &= 0x0F;
  171453. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  171454. if (n >= NUM_QUANT_TBLS)
  171455. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  171456. if (cinfo->quant_tbl_ptrs[n] == NULL)
  171457. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  171458. quant_ptr = cinfo->quant_tbl_ptrs[n];
  171459. for (i = 0; i < DCTSIZE2; i++) {
  171460. if (prec)
  171461. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171462. else
  171463. INPUT_BYTE(cinfo, tmp, return FALSE);
  171464. /* We convert the zigzag-order table to natural array order. */
  171465. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  171466. }
  171467. if (cinfo->err->trace_level >= 2) {
  171468. for (i = 0; i < DCTSIZE2; i += 8) {
  171469. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  171470. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  171471. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  171472. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  171473. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  171474. }
  171475. }
  171476. length -= DCTSIZE2+1;
  171477. if (prec) length -= DCTSIZE2;
  171478. }
  171479. if (length != 0)
  171480. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171481. INPUT_SYNC(cinfo);
  171482. return TRUE;
  171483. }
  171484. LOCAL(boolean)
  171485. get_dri (j_decompress_ptr cinfo)
  171486. /* Process a DRI marker */
  171487. {
  171488. INT32 length;
  171489. unsigned int tmp;
  171490. INPUT_VARS(cinfo);
  171491. INPUT_2BYTES(cinfo, length, return FALSE);
  171492. if (length != 4)
  171493. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171494. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171495. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  171496. cinfo->restart_interval = tmp;
  171497. INPUT_SYNC(cinfo);
  171498. return TRUE;
  171499. }
  171500. /*
  171501. * Routines for processing APPn and COM markers.
  171502. * These are either saved in memory or discarded, per application request.
  171503. * APP0 and APP14 are specially checked to see if they are
  171504. * JFIF and Adobe markers, respectively.
  171505. */
  171506. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  171507. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  171508. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  171509. LOCAL(void)
  171510. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171511. unsigned int datalen, INT32 remaining)
  171512. /* Examine first few bytes from an APP0.
  171513. * Take appropriate action if it is a JFIF marker.
  171514. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171515. */
  171516. {
  171517. INT32 totallen = (INT32) datalen + remaining;
  171518. if (datalen >= APP0_DATA_LEN &&
  171519. GETJOCTET(data[0]) == 0x4A &&
  171520. GETJOCTET(data[1]) == 0x46 &&
  171521. GETJOCTET(data[2]) == 0x49 &&
  171522. GETJOCTET(data[3]) == 0x46 &&
  171523. GETJOCTET(data[4]) == 0) {
  171524. /* Found JFIF APP0 marker: save info */
  171525. cinfo->saw_JFIF_marker = TRUE;
  171526. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  171527. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  171528. cinfo->density_unit = GETJOCTET(data[7]);
  171529. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  171530. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  171531. /* Check version.
  171532. * Major version must be 1, anything else signals an incompatible change.
  171533. * (We used to treat this as an error, but now it's a nonfatal warning,
  171534. * because some bozo at Hijaak couldn't read the spec.)
  171535. * Minor version should be 0..2, but process anyway if newer.
  171536. */
  171537. if (cinfo->JFIF_major_version != 1)
  171538. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  171539. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  171540. /* Generate trace messages */
  171541. TRACEMS5(cinfo, 1, JTRC_JFIF,
  171542. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  171543. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  171544. /* Validate thumbnail dimensions and issue appropriate messages */
  171545. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  171546. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  171547. GETJOCTET(data[12]), GETJOCTET(data[13]));
  171548. totallen -= APP0_DATA_LEN;
  171549. if (totallen !=
  171550. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  171551. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  171552. } else if (datalen >= 6 &&
  171553. GETJOCTET(data[0]) == 0x4A &&
  171554. GETJOCTET(data[1]) == 0x46 &&
  171555. GETJOCTET(data[2]) == 0x58 &&
  171556. GETJOCTET(data[3]) == 0x58 &&
  171557. GETJOCTET(data[4]) == 0) {
  171558. /* Found JFIF "JFXX" extension APP0 marker */
  171559. /* The library doesn't actually do anything with these,
  171560. * but we try to produce a helpful trace message.
  171561. */
  171562. switch (GETJOCTET(data[5])) {
  171563. case 0x10:
  171564. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  171565. break;
  171566. case 0x11:
  171567. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  171568. break;
  171569. case 0x13:
  171570. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  171571. break;
  171572. default:
  171573. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  171574. GETJOCTET(data[5]), (int) totallen);
  171575. break;
  171576. }
  171577. } else {
  171578. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  171579. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  171580. }
  171581. }
  171582. LOCAL(void)
  171583. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171584. unsigned int datalen, INT32 remaining)
  171585. /* Examine first few bytes from an APP14.
  171586. * Take appropriate action if it is an Adobe marker.
  171587. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171588. */
  171589. {
  171590. unsigned int version, flags0, flags1, transform;
  171591. if (datalen >= APP14_DATA_LEN &&
  171592. GETJOCTET(data[0]) == 0x41 &&
  171593. GETJOCTET(data[1]) == 0x64 &&
  171594. GETJOCTET(data[2]) == 0x6F &&
  171595. GETJOCTET(data[3]) == 0x62 &&
  171596. GETJOCTET(data[4]) == 0x65) {
  171597. /* Found Adobe APP14 marker */
  171598. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  171599. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  171600. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  171601. transform = GETJOCTET(data[11]);
  171602. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  171603. cinfo->saw_Adobe_marker = TRUE;
  171604. cinfo->Adobe_transform = (UINT8) transform;
  171605. } else {
  171606. /* Start of APP14 does not match "Adobe", or too short */
  171607. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  171608. }
  171609. }
  171610. METHODDEF(boolean)
  171611. get_interesting_appn (j_decompress_ptr cinfo)
  171612. /* Process an APP0 or APP14 marker without saving it */
  171613. {
  171614. INT32 length;
  171615. JOCTET b[APPN_DATA_LEN];
  171616. unsigned int i, numtoread;
  171617. INPUT_VARS(cinfo);
  171618. INPUT_2BYTES(cinfo, length, return FALSE);
  171619. length -= 2;
  171620. /* get the interesting part of the marker data */
  171621. if (length >= APPN_DATA_LEN)
  171622. numtoread = APPN_DATA_LEN;
  171623. else if (length > 0)
  171624. numtoread = (unsigned int) length;
  171625. else
  171626. numtoread = 0;
  171627. for (i = 0; i < numtoread; i++)
  171628. INPUT_BYTE(cinfo, b[i], return FALSE);
  171629. length -= numtoread;
  171630. /* process it */
  171631. switch (cinfo->unread_marker) {
  171632. case M_APP0:
  171633. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  171634. break;
  171635. case M_APP14:
  171636. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  171637. break;
  171638. default:
  171639. /* can't get here unless jpeg_save_markers chooses wrong processor */
  171640. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171641. break;
  171642. }
  171643. /* skip any remaining data -- could be lots */
  171644. INPUT_SYNC(cinfo);
  171645. if (length > 0)
  171646. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171647. return TRUE;
  171648. }
  171649. #ifdef SAVE_MARKERS_SUPPORTED
  171650. METHODDEF(boolean)
  171651. save_marker (j_decompress_ptr cinfo)
  171652. /* Save an APPn or COM marker into the marker list */
  171653. {
  171654. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171655. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  171656. unsigned int bytes_read, data_length;
  171657. JOCTET FAR * data;
  171658. INT32 length = 0;
  171659. INPUT_VARS(cinfo);
  171660. if (cur_marker == NULL) {
  171661. /* begin reading a marker */
  171662. INPUT_2BYTES(cinfo, length, return FALSE);
  171663. length -= 2;
  171664. if (length >= 0) { /* watch out for bogus length word */
  171665. /* figure out how much we want to save */
  171666. unsigned int limit;
  171667. if (cinfo->unread_marker == (int) M_COM)
  171668. limit = marker->length_limit_COM;
  171669. else
  171670. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  171671. if ((unsigned int) length < limit)
  171672. limit = (unsigned int) length;
  171673. /* allocate and initialize the marker item */
  171674. cur_marker = (jpeg_saved_marker_ptr)
  171675. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171676. SIZEOF(struct jpeg_marker_struct) + limit);
  171677. cur_marker->next = NULL;
  171678. cur_marker->marker = (UINT8) cinfo->unread_marker;
  171679. cur_marker->original_length = (unsigned int) length;
  171680. cur_marker->data_length = limit;
  171681. /* data area is just beyond the jpeg_marker_struct */
  171682. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  171683. marker->cur_marker = cur_marker;
  171684. marker->bytes_read = 0;
  171685. bytes_read = 0;
  171686. data_length = limit;
  171687. } else {
  171688. /* deal with bogus length word */
  171689. bytes_read = data_length = 0;
  171690. data = NULL;
  171691. }
  171692. } else {
  171693. /* resume reading a marker */
  171694. bytes_read = marker->bytes_read;
  171695. data_length = cur_marker->data_length;
  171696. data = cur_marker->data + bytes_read;
  171697. }
  171698. while (bytes_read < data_length) {
  171699. INPUT_SYNC(cinfo); /* move the restart point to here */
  171700. marker->bytes_read = bytes_read;
  171701. /* If there's not at least one byte in buffer, suspend */
  171702. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  171703. /* Copy bytes with reasonable rapidity */
  171704. while (bytes_read < data_length && bytes_in_buffer > 0) {
  171705. *data++ = *next_input_byte++;
  171706. bytes_in_buffer--;
  171707. bytes_read++;
  171708. }
  171709. }
  171710. /* Done reading what we want to read */
  171711. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  171712. /* Add new marker to end of list */
  171713. if (cinfo->marker_list == NULL) {
  171714. cinfo->marker_list = cur_marker;
  171715. } else {
  171716. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  171717. while (prev->next != NULL)
  171718. prev = prev->next;
  171719. prev->next = cur_marker;
  171720. }
  171721. /* Reset pointer & calc remaining data length */
  171722. data = cur_marker->data;
  171723. length = cur_marker->original_length - data_length;
  171724. }
  171725. /* Reset to initial state for next marker */
  171726. marker->cur_marker = NULL;
  171727. /* Process the marker if interesting; else just make a generic trace msg */
  171728. switch (cinfo->unread_marker) {
  171729. case M_APP0:
  171730. examine_app0(cinfo, data, data_length, length);
  171731. break;
  171732. case M_APP14:
  171733. examine_app14(cinfo, data, data_length, length);
  171734. break;
  171735. default:
  171736. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  171737. (int) (data_length + length));
  171738. break;
  171739. }
  171740. /* skip any remaining data -- could be lots */
  171741. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171742. if (length > 0)
  171743. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171744. return TRUE;
  171745. }
  171746. #endif /* SAVE_MARKERS_SUPPORTED */
  171747. METHODDEF(boolean)
  171748. skip_variable (j_decompress_ptr cinfo)
  171749. /* Skip over an unknown or uninteresting variable-length marker */
  171750. {
  171751. INT32 length;
  171752. INPUT_VARS(cinfo);
  171753. INPUT_2BYTES(cinfo, length, return FALSE);
  171754. length -= 2;
  171755. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  171756. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171757. if (length > 0)
  171758. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171759. return TRUE;
  171760. }
  171761. /*
  171762. * Find the next JPEG marker, save it in cinfo->unread_marker.
  171763. * Returns FALSE if had to suspend before reaching a marker;
  171764. * in that case cinfo->unread_marker is unchanged.
  171765. *
  171766. * Note that the result might not be a valid marker code,
  171767. * but it will never be 0 or FF.
  171768. */
  171769. LOCAL(boolean)
  171770. next_marker (j_decompress_ptr cinfo)
  171771. {
  171772. int c;
  171773. INPUT_VARS(cinfo);
  171774. for (;;) {
  171775. INPUT_BYTE(cinfo, c, return FALSE);
  171776. /* Skip any non-FF bytes.
  171777. * This may look a bit inefficient, but it will not occur in a valid file.
  171778. * We sync after each discarded byte so that a suspending data source
  171779. * can discard the byte from its buffer.
  171780. */
  171781. while (c != 0xFF) {
  171782. cinfo->marker->discarded_bytes++;
  171783. INPUT_SYNC(cinfo);
  171784. INPUT_BYTE(cinfo, c, return FALSE);
  171785. }
  171786. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  171787. * pad bytes, so don't count them in discarded_bytes. We assume there
  171788. * will not be so many consecutive FF bytes as to overflow a suspending
  171789. * data source's input buffer.
  171790. */
  171791. do {
  171792. INPUT_BYTE(cinfo, c, return FALSE);
  171793. } while (c == 0xFF);
  171794. if (c != 0)
  171795. break; /* found a valid marker, exit loop */
  171796. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  171797. * Discard it and loop back to try again.
  171798. */
  171799. cinfo->marker->discarded_bytes += 2;
  171800. INPUT_SYNC(cinfo);
  171801. }
  171802. if (cinfo->marker->discarded_bytes != 0) {
  171803. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  171804. cinfo->marker->discarded_bytes = 0;
  171805. }
  171806. cinfo->unread_marker = c;
  171807. INPUT_SYNC(cinfo);
  171808. return TRUE;
  171809. }
  171810. LOCAL(boolean)
  171811. first_marker (j_decompress_ptr cinfo)
  171812. /* Like next_marker, but used to obtain the initial SOI marker. */
  171813. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  171814. * we might well scan an entire input file before realizing it ain't JPEG.
  171815. * If an application wants to process non-JFIF files, it must seek to the
  171816. * SOI before calling the JPEG library.
  171817. */
  171818. {
  171819. int c, c2;
  171820. INPUT_VARS(cinfo);
  171821. INPUT_BYTE(cinfo, c, return FALSE);
  171822. INPUT_BYTE(cinfo, c2, return FALSE);
  171823. if (c != 0xFF || c2 != (int) M_SOI)
  171824. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  171825. cinfo->unread_marker = c2;
  171826. INPUT_SYNC(cinfo);
  171827. return TRUE;
  171828. }
  171829. /*
  171830. * Read markers until SOS or EOI.
  171831. *
  171832. * Returns same codes as are defined for jpeg_consume_input:
  171833. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  171834. */
  171835. METHODDEF(int)
  171836. read_markers (j_decompress_ptr cinfo)
  171837. {
  171838. /* Outer loop repeats once for each marker. */
  171839. for (;;) {
  171840. /* Collect the marker proper, unless we already did. */
  171841. /* NB: first_marker() enforces the requirement that SOI appear first. */
  171842. if (cinfo->unread_marker == 0) {
  171843. if (! cinfo->marker->saw_SOI) {
  171844. if (! first_marker(cinfo))
  171845. return JPEG_SUSPENDED;
  171846. } else {
  171847. if (! next_marker(cinfo))
  171848. return JPEG_SUSPENDED;
  171849. }
  171850. }
  171851. /* At this point cinfo->unread_marker contains the marker code and the
  171852. * input point is just past the marker proper, but before any parameters.
  171853. * A suspension will cause us to return with this state still true.
  171854. */
  171855. switch (cinfo->unread_marker) {
  171856. case M_SOI:
  171857. if (! get_soi(cinfo))
  171858. return JPEG_SUSPENDED;
  171859. break;
  171860. case M_SOF0: /* Baseline */
  171861. case M_SOF1: /* Extended sequential, Huffman */
  171862. if (! get_sof(cinfo, FALSE, FALSE))
  171863. return JPEG_SUSPENDED;
  171864. break;
  171865. case M_SOF2: /* Progressive, Huffman */
  171866. if (! get_sof(cinfo, TRUE, FALSE))
  171867. return JPEG_SUSPENDED;
  171868. break;
  171869. case M_SOF9: /* Extended sequential, arithmetic */
  171870. if (! get_sof(cinfo, FALSE, TRUE))
  171871. return JPEG_SUSPENDED;
  171872. break;
  171873. case M_SOF10: /* Progressive, arithmetic */
  171874. if (! get_sof(cinfo, TRUE, TRUE))
  171875. return JPEG_SUSPENDED;
  171876. break;
  171877. /* Currently unsupported SOFn types */
  171878. case M_SOF3: /* Lossless, Huffman */
  171879. case M_SOF5: /* Differential sequential, Huffman */
  171880. case M_SOF6: /* Differential progressive, Huffman */
  171881. case M_SOF7: /* Differential lossless, Huffman */
  171882. case M_JPG: /* Reserved for JPEG extensions */
  171883. case M_SOF11: /* Lossless, arithmetic */
  171884. case M_SOF13: /* Differential sequential, arithmetic */
  171885. case M_SOF14: /* Differential progressive, arithmetic */
  171886. case M_SOF15: /* Differential lossless, arithmetic */
  171887. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  171888. break;
  171889. case M_SOS:
  171890. if (! get_sos(cinfo))
  171891. return JPEG_SUSPENDED;
  171892. cinfo->unread_marker = 0; /* processed the marker */
  171893. return JPEG_REACHED_SOS;
  171894. case M_EOI:
  171895. TRACEMS(cinfo, 1, JTRC_EOI);
  171896. cinfo->unread_marker = 0; /* processed the marker */
  171897. return JPEG_REACHED_EOI;
  171898. case M_DAC:
  171899. if (! get_dac(cinfo))
  171900. return JPEG_SUSPENDED;
  171901. break;
  171902. case M_DHT:
  171903. if (! get_dht(cinfo))
  171904. return JPEG_SUSPENDED;
  171905. break;
  171906. case M_DQT:
  171907. if (! get_dqt(cinfo))
  171908. return JPEG_SUSPENDED;
  171909. break;
  171910. case M_DRI:
  171911. if (! get_dri(cinfo))
  171912. return JPEG_SUSPENDED;
  171913. break;
  171914. case M_APP0:
  171915. case M_APP1:
  171916. case M_APP2:
  171917. case M_APP3:
  171918. case M_APP4:
  171919. case M_APP5:
  171920. case M_APP6:
  171921. case M_APP7:
  171922. case M_APP8:
  171923. case M_APP9:
  171924. case M_APP10:
  171925. case M_APP11:
  171926. case M_APP12:
  171927. case M_APP13:
  171928. case M_APP14:
  171929. case M_APP15:
  171930. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  171931. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  171932. return JPEG_SUSPENDED;
  171933. break;
  171934. case M_COM:
  171935. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  171936. return JPEG_SUSPENDED;
  171937. break;
  171938. case M_RST0: /* these are all parameterless */
  171939. case M_RST1:
  171940. case M_RST2:
  171941. case M_RST3:
  171942. case M_RST4:
  171943. case M_RST5:
  171944. case M_RST6:
  171945. case M_RST7:
  171946. case M_TEM:
  171947. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  171948. break;
  171949. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  171950. if (! skip_variable(cinfo))
  171951. return JPEG_SUSPENDED;
  171952. break;
  171953. default: /* must be DHP, EXP, JPGn, or RESn */
  171954. /* For now, we treat the reserved markers as fatal errors since they are
  171955. * likely to be used to signal incompatible JPEG Part 3 extensions.
  171956. * Once the JPEG 3 version-number marker is well defined, this code
  171957. * ought to change!
  171958. */
  171959. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171960. break;
  171961. }
  171962. /* Successfully processed marker, so reset state variable */
  171963. cinfo->unread_marker = 0;
  171964. } /* end loop */
  171965. }
  171966. /*
  171967. * Read a restart marker, which is expected to appear next in the datastream;
  171968. * if the marker is not there, take appropriate recovery action.
  171969. * Returns FALSE if suspension is required.
  171970. *
  171971. * This is called by the entropy decoder after it has read an appropriate
  171972. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  171973. * has already read a marker from the data source. Under normal conditions
  171974. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  171975. * it holds a marker which the decoder will be unable to read past.
  171976. */
  171977. METHODDEF(boolean)
  171978. read_restart_marker (j_decompress_ptr cinfo)
  171979. {
  171980. /* Obtain a marker unless we already did. */
  171981. /* Note that next_marker will complain if it skips any data. */
  171982. if (cinfo->unread_marker == 0) {
  171983. if (! next_marker(cinfo))
  171984. return FALSE;
  171985. }
  171986. if (cinfo->unread_marker ==
  171987. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  171988. /* Normal case --- swallow the marker and let entropy decoder continue */
  171989. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  171990. cinfo->unread_marker = 0;
  171991. } else {
  171992. /* Uh-oh, the restart markers have been messed up. */
  171993. /* Let the data source manager determine how to resync. */
  171994. if (! (*cinfo->src->resync_to_restart) (cinfo,
  171995. cinfo->marker->next_restart_num))
  171996. return FALSE;
  171997. }
  171998. /* Update next-restart state */
  171999. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  172000. return TRUE;
  172001. }
  172002. /*
  172003. * This is the default resync_to_restart method for data source managers
  172004. * to use if they don't have any better approach. Some data source managers
  172005. * may be able to back up, or may have additional knowledge about the data
  172006. * which permits a more intelligent recovery strategy; such managers would
  172007. * presumably supply their own resync method.
  172008. *
  172009. * read_restart_marker calls resync_to_restart if it finds a marker other than
  172010. * the restart marker it was expecting. (This code is *not* used unless
  172011. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  172012. * the marker code actually found (might be anything, except 0 or FF).
  172013. * The desired restart marker number (0..7) is passed as a parameter.
  172014. * This routine is supposed to apply whatever error recovery strategy seems
  172015. * appropriate in order to position the input stream to the next data segment.
  172016. * Note that cinfo->unread_marker is treated as a marker appearing before
  172017. * the current data-source input point; usually it should be reset to zero
  172018. * before returning.
  172019. * Returns FALSE if suspension is required.
  172020. *
  172021. * This implementation is substantially constrained by wanting to treat the
  172022. * input as a data stream; this means we can't back up. Therefore, we have
  172023. * only the following actions to work with:
  172024. * 1. Simply discard the marker and let the entropy decoder resume at next
  172025. * byte of file.
  172026. * 2. Read forward until we find another marker, discarding intervening
  172027. * data. (In theory we could look ahead within the current bufferload,
  172028. * without having to discard data if we don't find the desired marker.
  172029. * This idea is not implemented here, in part because it makes behavior
  172030. * dependent on buffer size and chance buffer-boundary positions.)
  172031. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  172032. * This will cause the entropy decoder to process an empty data segment,
  172033. * inserting dummy zeroes, and then we will reprocess the marker.
  172034. *
  172035. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  172036. * appropriate if the found marker is a future restart marker (indicating
  172037. * that we have missed the desired restart marker, probably because it got
  172038. * corrupted).
  172039. * We apply #2 or #3 if the found marker is a restart marker no more than
  172040. * two counts behind or ahead of the expected one. We also apply #2 if the
  172041. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  172042. * If the found marker is a restart marker more than 2 counts away, we do #1
  172043. * (too much risk that the marker is erroneous; with luck we will be able to
  172044. * resync at some future point).
  172045. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  172046. * overrunning the end of a scan. An implementation limited to single-scan
  172047. * files might find it better to apply #2 for markers other than EOI, since
  172048. * any other marker would have to be bogus data in that case.
  172049. */
  172050. GLOBAL(boolean)
  172051. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  172052. {
  172053. int marker = cinfo->unread_marker;
  172054. int action = 1;
  172055. /* Always put up a warning. */
  172056. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  172057. /* Outer loop handles repeated decision after scanning forward. */
  172058. for (;;) {
  172059. if (marker < (int) M_SOF0)
  172060. action = 2; /* invalid marker */
  172061. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  172062. action = 3; /* valid non-restart marker */
  172063. else {
  172064. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  172065. marker == ((int) M_RST0 + ((desired+2) & 7)))
  172066. action = 3; /* one of the next two expected restarts */
  172067. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  172068. marker == ((int) M_RST0 + ((desired-2) & 7)))
  172069. action = 2; /* a prior restart, so advance */
  172070. else
  172071. action = 1; /* desired restart or too far away */
  172072. }
  172073. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  172074. switch (action) {
  172075. case 1:
  172076. /* Discard marker and let entropy decoder resume processing. */
  172077. cinfo->unread_marker = 0;
  172078. return TRUE;
  172079. case 2:
  172080. /* Scan to the next marker, and repeat the decision loop. */
  172081. if (! next_marker(cinfo))
  172082. return FALSE;
  172083. marker = cinfo->unread_marker;
  172084. break;
  172085. case 3:
  172086. /* Return without advancing past this marker. */
  172087. /* Entropy decoder will be forced to process an empty segment. */
  172088. return TRUE;
  172089. }
  172090. } /* end loop */
  172091. }
  172092. /*
  172093. * Reset marker processing state to begin a fresh datastream.
  172094. */
  172095. METHODDEF(void)
  172096. reset_marker_reader (j_decompress_ptr cinfo)
  172097. {
  172098. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172099. cinfo->comp_info = NULL; /* until allocated by get_sof */
  172100. cinfo->input_scan_number = 0; /* no SOS seen yet */
  172101. cinfo->unread_marker = 0; /* no pending marker */
  172102. marker->pub.saw_SOI = FALSE; /* set internal state too */
  172103. marker->pub.saw_SOF = FALSE;
  172104. marker->pub.discarded_bytes = 0;
  172105. marker->cur_marker = NULL;
  172106. }
  172107. /*
  172108. * Initialize the marker reader module.
  172109. * This is called only once, when the decompression object is created.
  172110. */
  172111. GLOBAL(void)
  172112. jinit_marker_reader (j_decompress_ptr cinfo)
  172113. {
  172114. my_marker_ptr2 marker;
  172115. int i;
  172116. /* Create subobject in permanent pool */
  172117. marker = (my_marker_ptr2)
  172118. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  172119. SIZEOF(my_marker_reader));
  172120. cinfo->marker = (struct jpeg_marker_reader *) marker;
  172121. /* Initialize public method pointers */
  172122. marker->pub.reset_marker_reader = reset_marker_reader;
  172123. marker->pub.read_markers = read_markers;
  172124. marker->pub.read_restart_marker = read_restart_marker;
  172125. /* Initialize COM/APPn processing.
  172126. * By default, we examine and then discard APP0 and APP14,
  172127. * but simply discard COM and all other APPn.
  172128. */
  172129. marker->process_COM = skip_variable;
  172130. marker->length_limit_COM = 0;
  172131. for (i = 0; i < 16; i++) {
  172132. marker->process_APPn[i] = skip_variable;
  172133. marker->length_limit_APPn[i] = 0;
  172134. }
  172135. marker->process_APPn[0] = get_interesting_appn;
  172136. marker->process_APPn[14] = get_interesting_appn;
  172137. /* Reset marker processing state */
  172138. reset_marker_reader(cinfo);
  172139. }
  172140. /*
  172141. * Control saving of COM and APPn markers into marker_list.
  172142. */
  172143. #ifdef SAVE_MARKERS_SUPPORTED
  172144. GLOBAL(void)
  172145. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  172146. unsigned int length_limit)
  172147. {
  172148. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172149. long maxlength;
  172150. jpeg_marker_parser_method processor;
  172151. /* Length limit mustn't be larger than what we can allocate
  172152. * (should only be a concern in a 16-bit environment).
  172153. */
  172154. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  172155. if (((long) length_limit) > maxlength)
  172156. length_limit = (unsigned int) maxlength;
  172157. /* Choose processor routine to use.
  172158. * APP0/APP14 have special requirements.
  172159. */
  172160. if (length_limit) {
  172161. processor = save_marker;
  172162. /* If saving APP0/APP14, save at least enough for our internal use. */
  172163. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  172164. length_limit = APP0_DATA_LEN;
  172165. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  172166. length_limit = APP14_DATA_LEN;
  172167. } else {
  172168. processor = skip_variable;
  172169. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  172170. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  172171. processor = get_interesting_appn;
  172172. }
  172173. if (marker_code == (int) M_COM) {
  172174. marker->process_COM = processor;
  172175. marker->length_limit_COM = length_limit;
  172176. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  172177. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  172178. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  172179. } else
  172180. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  172181. }
  172182. #endif /* SAVE_MARKERS_SUPPORTED */
  172183. /*
  172184. * Install a special processing method for COM or APPn markers.
  172185. */
  172186. GLOBAL(void)
  172187. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  172188. jpeg_marker_parser_method routine)
  172189. {
  172190. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172191. if (marker_code == (int) M_COM)
  172192. marker->process_COM = routine;
  172193. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  172194. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  172195. else
  172196. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  172197. }
  172198. /*** End of inlined file: jdmarker.c ***/
  172199. /*** Start of inlined file: jdmaster.c ***/
  172200. #define JPEG_INTERNALS
  172201. /* Private state */
  172202. typedef struct {
  172203. struct jpeg_decomp_master pub; /* public fields */
  172204. int pass_number; /* # of passes completed */
  172205. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  172206. /* Saved references to initialized quantizer modules,
  172207. * in case we need to switch modes.
  172208. */
  172209. struct jpeg_color_quantizer * quantizer_1pass;
  172210. struct jpeg_color_quantizer * quantizer_2pass;
  172211. } my_decomp_master;
  172212. typedef my_decomp_master * my_master_ptr6;
  172213. /*
  172214. * Determine whether merged upsample/color conversion should be used.
  172215. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  172216. */
  172217. LOCAL(boolean)
  172218. use_merged_upsample (j_decompress_ptr cinfo)
  172219. {
  172220. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172221. /* Merging is the equivalent of plain box-filter upsampling */
  172222. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  172223. return FALSE;
  172224. /* jdmerge.c only supports YCC=>RGB color conversion */
  172225. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  172226. cinfo->out_color_space != JCS_RGB ||
  172227. cinfo->out_color_components != RGB_PIXELSIZE)
  172228. return FALSE;
  172229. /* and it only handles 2h1v or 2h2v sampling ratios */
  172230. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  172231. cinfo->comp_info[1].h_samp_factor != 1 ||
  172232. cinfo->comp_info[2].h_samp_factor != 1 ||
  172233. cinfo->comp_info[0].v_samp_factor > 2 ||
  172234. cinfo->comp_info[1].v_samp_factor != 1 ||
  172235. cinfo->comp_info[2].v_samp_factor != 1)
  172236. return FALSE;
  172237. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  172238. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  172239. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  172240. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  172241. return FALSE;
  172242. /* ??? also need to test for upsample-time rescaling, when & if supported */
  172243. return TRUE; /* by golly, it'll work... */
  172244. #else
  172245. return FALSE;
  172246. #endif
  172247. }
  172248. /*
  172249. * Compute output image dimensions and related values.
  172250. * NOTE: this is exported for possible use by application.
  172251. * Hence it mustn't do anything that can't be done twice.
  172252. * Also note that it may be called before the master module is initialized!
  172253. */
  172254. GLOBAL(void)
  172255. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  172256. /* Do computations that are needed before master selection phase */
  172257. {
  172258. #ifdef IDCT_SCALING_SUPPORTED
  172259. int ci;
  172260. jpeg_component_info *compptr;
  172261. #endif
  172262. /* Prevent application from calling me at wrong times */
  172263. if (cinfo->global_state != DSTATE_READY)
  172264. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172265. #ifdef IDCT_SCALING_SUPPORTED
  172266. /* Compute actual output image dimensions and DCT scaling choices. */
  172267. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  172268. /* Provide 1/8 scaling */
  172269. cinfo->output_width = (JDIMENSION)
  172270. jdiv_round_up((long) cinfo->image_width, 8L);
  172271. cinfo->output_height = (JDIMENSION)
  172272. jdiv_round_up((long) cinfo->image_height, 8L);
  172273. cinfo->min_DCT_scaled_size = 1;
  172274. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  172275. /* Provide 1/4 scaling */
  172276. cinfo->output_width = (JDIMENSION)
  172277. jdiv_round_up((long) cinfo->image_width, 4L);
  172278. cinfo->output_height = (JDIMENSION)
  172279. jdiv_round_up((long) cinfo->image_height, 4L);
  172280. cinfo->min_DCT_scaled_size = 2;
  172281. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  172282. /* Provide 1/2 scaling */
  172283. cinfo->output_width = (JDIMENSION)
  172284. jdiv_round_up((long) cinfo->image_width, 2L);
  172285. cinfo->output_height = (JDIMENSION)
  172286. jdiv_round_up((long) cinfo->image_height, 2L);
  172287. cinfo->min_DCT_scaled_size = 4;
  172288. } else {
  172289. /* Provide 1/1 scaling */
  172290. cinfo->output_width = cinfo->image_width;
  172291. cinfo->output_height = cinfo->image_height;
  172292. cinfo->min_DCT_scaled_size = DCTSIZE;
  172293. }
  172294. /* In selecting the actual DCT scaling for each component, we try to
  172295. * scale up the chroma components via IDCT scaling rather than upsampling.
  172296. * This saves time if the upsampler gets to use 1:1 scaling.
  172297. * Note this code assumes that the supported DCT scalings are powers of 2.
  172298. */
  172299. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172300. ci++, compptr++) {
  172301. int ssize = cinfo->min_DCT_scaled_size;
  172302. while (ssize < DCTSIZE &&
  172303. (compptr->h_samp_factor * ssize * 2 <=
  172304. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  172305. (compptr->v_samp_factor * ssize * 2 <=
  172306. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  172307. ssize = ssize * 2;
  172308. }
  172309. compptr->DCT_scaled_size = ssize;
  172310. }
  172311. /* Recompute downsampled dimensions of components;
  172312. * application needs to know these if using raw downsampled data.
  172313. */
  172314. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172315. ci++, compptr++) {
  172316. /* Size in samples, after IDCT scaling */
  172317. compptr->downsampled_width = (JDIMENSION)
  172318. jdiv_round_up((long) cinfo->image_width *
  172319. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  172320. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  172321. compptr->downsampled_height = (JDIMENSION)
  172322. jdiv_round_up((long) cinfo->image_height *
  172323. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  172324. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  172325. }
  172326. #else /* !IDCT_SCALING_SUPPORTED */
  172327. /* Hardwire it to "no scaling" */
  172328. cinfo->output_width = cinfo->image_width;
  172329. cinfo->output_height = cinfo->image_height;
  172330. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  172331. * and has computed unscaled downsampled_width and downsampled_height.
  172332. */
  172333. #endif /* IDCT_SCALING_SUPPORTED */
  172334. /* Report number of components in selected colorspace. */
  172335. /* Probably this should be in the color conversion module... */
  172336. switch (cinfo->out_color_space) {
  172337. case JCS_GRAYSCALE:
  172338. cinfo->out_color_components = 1;
  172339. break;
  172340. case JCS_RGB:
  172341. #if RGB_PIXELSIZE != 3
  172342. cinfo->out_color_components = RGB_PIXELSIZE;
  172343. break;
  172344. #endif /* else share code with YCbCr */
  172345. case JCS_YCbCr:
  172346. cinfo->out_color_components = 3;
  172347. break;
  172348. case JCS_CMYK:
  172349. case JCS_YCCK:
  172350. cinfo->out_color_components = 4;
  172351. break;
  172352. default: /* else must be same colorspace as in file */
  172353. cinfo->out_color_components = cinfo->num_components;
  172354. break;
  172355. }
  172356. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  172357. cinfo->out_color_components);
  172358. /* See if upsampler will want to emit more than one row at a time */
  172359. if (use_merged_upsample(cinfo))
  172360. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  172361. else
  172362. cinfo->rec_outbuf_height = 1;
  172363. }
  172364. /*
  172365. * Several decompression processes need to range-limit values to the range
  172366. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  172367. * due to noise introduced by quantization, roundoff error, etc. These
  172368. * processes are inner loops and need to be as fast as possible. On most
  172369. * machines, particularly CPUs with pipelines or instruction prefetch,
  172370. * a (subscript-check-less) C table lookup
  172371. * x = sample_range_limit[x];
  172372. * is faster than explicit tests
  172373. * if (x < 0) x = 0;
  172374. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  172375. * These processes all use a common table prepared by the routine below.
  172376. *
  172377. * For most steps we can mathematically guarantee that the initial value
  172378. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  172379. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  172380. * limiting step (just after the IDCT), a wildly out-of-range value is
  172381. * possible if the input data is corrupt. To avoid any chance of indexing
  172382. * off the end of memory and getting a bad-pointer trap, we perform the
  172383. * post-IDCT limiting thus:
  172384. * x = range_limit[x & MASK];
  172385. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  172386. * samples. Under normal circumstances this is more than enough range and
  172387. * a correct output will be generated; with bogus input data the mask will
  172388. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  172389. * For the post-IDCT step, we want to convert the data from signed to unsigned
  172390. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  172391. * So the post-IDCT limiting table ends up looking like this:
  172392. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  172393. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172394. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172395. * 0,1,...,CENTERJSAMPLE-1
  172396. * Negative inputs select values from the upper half of the table after
  172397. * masking.
  172398. *
  172399. * We can save some space by overlapping the start of the post-IDCT table
  172400. * with the simpler range limiting table. The post-IDCT table begins at
  172401. * sample_range_limit + CENTERJSAMPLE.
  172402. *
  172403. * Note that the table is allocated in near data space on PCs; it's small
  172404. * enough and used often enough to justify this.
  172405. */
  172406. LOCAL(void)
  172407. prepare_range_limit_table (j_decompress_ptr cinfo)
  172408. /* Allocate and fill in the sample_range_limit table */
  172409. {
  172410. JSAMPLE * table;
  172411. int i;
  172412. table = (JSAMPLE *)
  172413. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172414. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172415. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  172416. cinfo->sample_range_limit = table;
  172417. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  172418. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  172419. /* Main part of "simple" table: limit[x] = x */
  172420. for (i = 0; i <= MAXJSAMPLE; i++)
  172421. table[i] = (JSAMPLE) i;
  172422. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  172423. /* End of simple table, rest of first half of post-IDCT table */
  172424. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  172425. table[i] = MAXJSAMPLE;
  172426. /* Second half of post-IDCT table */
  172427. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  172428. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172429. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  172430. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  172431. }
  172432. /*
  172433. * Master selection of decompression modules.
  172434. * This is done once at jpeg_start_decompress time. We determine
  172435. * which modules will be used and give them appropriate initialization calls.
  172436. * We also initialize the decompressor input side to begin consuming data.
  172437. *
  172438. * Since jpeg_read_header has finished, we know what is in the SOF
  172439. * and (first) SOS markers. We also have all the application parameter
  172440. * settings.
  172441. */
  172442. LOCAL(void)
  172443. master_selection (j_decompress_ptr cinfo)
  172444. {
  172445. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172446. boolean use_c_buffer;
  172447. long samplesperrow;
  172448. JDIMENSION jd_samplesperrow;
  172449. /* Initialize dimensions and other stuff */
  172450. jpeg_calc_output_dimensions(cinfo);
  172451. prepare_range_limit_table(cinfo);
  172452. /* Width of an output scanline must be representable as JDIMENSION. */
  172453. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  172454. jd_samplesperrow = (JDIMENSION) samplesperrow;
  172455. if ((long) jd_samplesperrow != samplesperrow)
  172456. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  172457. /* Initialize my private state */
  172458. master->pass_number = 0;
  172459. master->using_merged_upsample = use_merged_upsample(cinfo);
  172460. /* Color quantizer selection */
  172461. master->quantizer_1pass = NULL;
  172462. master->quantizer_2pass = NULL;
  172463. /* No mode changes if not using buffered-image mode. */
  172464. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  172465. cinfo->enable_1pass_quant = FALSE;
  172466. cinfo->enable_external_quant = FALSE;
  172467. cinfo->enable_2pass_quant = FALSE;
  172468. }
  172469. if (cinfo->quantize_colors) {
  172470. if (cinfo->raw_data_out)
  172471. ERREXIT(cinfo, JERR_NOTIMPL);
  172472. /* 2-pass quantizer only works in 3-component color space. */
  172473. if (cinfo->out_color_components != 3) {
  172474. cinfo->enable_1pass_quant = TRUE;
  172475. cinfo->enable_external_quant = FALSE;
  172476. cinfo->enable_2pass_quant = FALSE;
  172477. cinfo->colormap = NULL;
  172478. } else if (cinfo->colormap != NULL) {
  172479. cinfo->enable_external_quant = TRUE;
  172480. } else if (cinfo->two_pass_quantize) {
  172481. cinfo->enable_2pass_quant = TRUE;
  172482. } else {
  172483. cinfo->enable_1pass_quant = TRUE;
  172484. }
  172485. if (cinfo->enable_1pass_quant) {
  172486. #ifdef QUANT_1PASS_SUPPORTED
  172487. jinit_1pass_quantizer(cinfo);
  172488. master->quantizer_1pass = cinfo->cquantize;
  172489. #else
  172490. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172491. #endif
  172492. }
  172493. /* We use the 2-pass code to map to external colormaps. */
  172494. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  172495. #ifdef QUANT_2PASS_SUPPORTED
  172496. jinit_2pass_quantizer(cinfo);
  172497. master->quantizer_2pass = cinfo->cquantize;
  172498. #else
  172499. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172500. #endif
  172501. }
  172502. /* If both quantizers are initialized, the 2-pass one is left active;
  172503. * this is necessary for starting with quantization to an external map.
  172504. */
  172505. }
  172506. /* Post-processing: in particular, color conversion first */
  172507. if (! cinfo->raw_data_out) {
  172508. if (master->using_merged_upsample) {
  172509. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172510. jinit_merged_upsampler(cinfo); /* does color conversion too */
  172511. #else
  172512. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172513. #endif
  172514. } else {
  172515. jinit_color_deconverter(cinfo);
  172516. jinit_upsampler(cinfo);
  172517. }
  172518. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  172519. }
  172520. /* Inverse DCT */
  172521. jinit_inverse_dct(cinfo);
  172522. /* Entropy decoding: either Huffman or arithmetic coding. */
  172523. if (cinfo->arith_code) {
  172524. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  172525. } else {
  172526. if (cinfo->progressive_mode) {
  172527. #ifdef D_PROGRESSIVE_SUPPORTED
  172528. jinit_phuff_decoder(cinfo);
  172529. #else
  172530. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172531. #endif
  172532. } else
  172533. jinit_huff_decoder(cinfo);
  172534. }
  172535. /* Initialize principal buffer controllers. */
  172536. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  172537. jinit_d_coef_controller(cinfo, use_c_buffer);
  172538. if (! cinfo->raw_data_out)
  172539. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  172540. /* We can now tell the memory manager to allocate virtual arrays. */
  172541. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  172542. /* Initialize input side of decompressor to consume first scan. */
  172543. (*cinfo->inputctl->start_input_pass) (cinfo);
  172544. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172545. /* If jpeg_start_decompress will read the whole file, initialize
  172546. * progress monitoring appropriately. The input step is counted
  172547. * as one pass.
  172548. */
  172549. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  172550. cinfo->inputctl->has_multiple_scans) {
  172551. int nscans;
  172552. /* Estimate number of scans to set pass_limit. */
  172553. if (cinfo->progressive_mode) {
  172554. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  172555. nscans = 2 + 3 * cinfo->num_components;
  172556. } else {
  172557. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  172558. nscans = cinfo->num_components;
  172559. }
  172560. cinfo->progress->pass_counter = 0L;
  172561. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  172562. cinfo->progress->completed_passes = 0;
  172563. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  172564. /* Count the input pass as done */
  172565. master->pass_number++;
  172566. }
  172567. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172568. }
  172569. /*
  172570. * Per-pass setup.
  172571. * This is called at the beginning of each output pass. We determine which
  172572. * modules will be active during this pass and give them appropriate
  172573. * start_pass calls. We also set is_dummy_pass to indicate whether this
  172574. * is a "real" output pass or a dummy pass for color quantization.
  172575. * (In the latter case, jdapistd.c will crank the pass to completion.)
  172576. */
  172577. METHODDEF(void)
  172578. prepare_for_output_pass (j_decompress_ptr cinfo)
  172579. {
  172580. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172581. if (master->pub.is_dummy_pass) {
  172582. #ifdef QUANT_2PASS_SUPPORTED
  172583. /* Final pass of 2-pass quantization */
  172584. master->pub.is_dummy_pass = FALSE;
  172585. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  172586. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  172587. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  172588. #else
  172589. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172590. #endif /* QUANT_2PASS_SUPPORTED */
  172591. } else {
  172592. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  172593. /* Select new quantization method */
  172594. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  172595. cinfo->cquantize = master->quantizer_2pass;
  172596. master->pub.is_dummy_pass = TRUE;
  172597. } else if (cinfo->enable_1pass_quant) {
  172598. cinfo->cquantize = master->quantizer_1pass;
  172599. } else {
  172600. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172601. }
  172602. }
  172603. (*cinfo->idct->start_pass) (cinfo);
  172604. (*cinfo->coef->start_output_pass) (cinfo);
  172605. if (! cinfo->raw_data_out) {
  172606. if (! master->using_merged_upsample)
  172607. (*cinfo->cconvert->start_pass) (cinfo);
  172608. (*cinfo->upsample->start_pass) (cinfo);
  172609. if (cinfo->quantize_colors)
  172610. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  172611. (*cinfo->post->start_pass) (cinfo,
  172612. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  172613. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  172614. }
  172615. }
  172616. /* Set up progress monitor's pass info if present */
  172617. if (cinfo->progress != NULL) {
  172618. cinfo->progress->completed_passes = master->pass_number;
  172619. cinfo->progress->total_passes = master->pass_number +
  172620. (master->pub.is_dummy_pass ? 2 : 1);
  172621. /* In buffered-image mode, we assume one more output pass if EOI not
  172622. * yet reached, but no more passes if EOI has been reached.
  172623. */
  172624. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  172625. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  172626. }
  172627. }
  172628. }
  172629. /*
  172630. * Finish up at end of an output pass.
  172631. */
  172632. METHODDEF(void)
  172633. finish_output_pass (j_decompress_ptr cinfo)
  172634. {
  172635. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172636. if (cinfo->quantize_colors)
  172637. (*cinfo->cquantize->finish_pass) (cinfo);
  172638. master->pass_number++;
  172639. }
  172640. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172641. /*
  172642. * Switch to a new external colormap between output passes.
  172643. */
  172644. GLOBAL(void)
  172645. jpeg_new_colormap (j_decompress_ptr cinfo)
  172646. {
  172647. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172648. /* Prevent application from calling me at wrong times */
  172649. if (cinfo->global_state != DSTATE_BUFIMAGE)
  172650. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172651. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  172652. cinfo->colormap != NULL) {
  172653. /* Select 2-pass quantizer for external colormap use */
  172654. cinfo->cquantize = master->quantizer_2pass;
  172655. /* Notify quantizer of colormap change */
  172656. (*cinfo->cquantize->new_color_map) (cinfo);
  172657. master->pub.is_dummy_pass = FALSE; /* just in case */
  172658. } else
  172659. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172660. }
  172661. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172662. /*
  172663. * Initialize master decompression control and select active modules.
  172664. * This is performed at the start of jpeg_start_decompress.
  172665. */
  172666. GLOBAL(void)
  172667. jinit_master_decompress (j_decompress_ptr cinfo)
  172668. {
  172669. my_master_ptr6 master;
  172670. master = (my_master_ptr6)
  172671. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172672. SIZEOF(my_decomp_master));
  172673. cinfo->master = (struct jpeg_decomp_master *) master;
  172674. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  172675. master->pub.finish_output_pass = finish_output_pass;
  172676. master->pub.is_dummy_pass = FALSE;
  172677. master_selection(cinfo);
  172678. }
  172679. /*** End of inlined file: jdmaster.c ***/
  172680. #undef FIX
  172681. /*** Start of inlined file: jdmerge.c ***/
  172682. #define JPEG_INTERNALS
  172683. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172684. /* Private subobject */
  172685. typedef struct {
  172686. struct jpeg_upsampler pub; /* public fields */
  172687. /* Pointer to routine to do actual upsampling/conversion of one row group */
  172688. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  172689. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172690. JSAMPARRAY output_buf));
  172691. /* Private state for YCC->RGB conversion */
  172692. int * Cr_r_tab; /* => table for Cr to R conversion */
  172693. int * Cb_b_tab; /* => table for Cb to B conversion */
  172694. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  172695. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  172696. /* For 2:1 vertical sampling, we produce two output rows at a time.
  172697. * We need a "spare" row buffer to hold the second output row if the
  172698. * application provides just a one-row buffer; we also use the spare
  172699. * to discard the dummy last row if the image height is odd.
  172700. */
  172701. JSAMPROW spare_row;
  172702. boolean spare_full; /* T if spare buffer is occupied */
  172703. JDIMENSION out_row_width; /* samples per output row */
  172704. JDIMENSION rows_to_go; /* counts rows remaining in image */
  172705. } my_upsampler;
  172706. typedef my_upsampler * my_upsample_ptr;
  172707. #define SCALEBITS 16 /* speediest right-shift on some machines */
  172708. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  172709. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  172710. /*
  172711. * Initialize tables for YCC->RGB colorspace conversion.
  172712. * This is taken directly from jdcolor.c; see that file for more info.
  172713. */
  172714. LOCAL(void)
  172715. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  172716. {
  172717. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172718. int i;
  172719. INT32 x;
  172720. SHIFT_TEMPS
  172721. upsample->Cr_r_tab = (int *)
  172722. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172723. (MAXJSAMPLE+1) * SIZEOF(int));
  172724. upsample->Cb_b_tab = (int *)
  172725. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172726. (MAXJSAMPLE+1) * SIZEOF(int));
  172727. upsample->Cr_g_tab = (INT32 *)
  172728. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172729. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172730. upsample->Cb_g_tab = (INT32 *)
  172731. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172732. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172733. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  172734. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  172735. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  172736. /* Cr=>R value is nearest int to 1.40200 * x */
  172737. upsample->Cr_r_tab[i] = (int)
  172738. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  172739. /* Cb=>B value is nearest int to 1.77200 * x */
  172740. upsample->Cb_b_tab[i] = (int)
  172741. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  172742. /* Cr=>G value is scaled-up -0.71414 * x */
  172743. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  172744. /* Cb=>G value is scaled-up -0.34414 * x */
  172745. /* We also add in ONE_HALF so that need not do it in inner loop */
  172746. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  172747. }
  172748. }
  172749. /*
  172750. * Initialize for an upsampling pass.
  172751. */
  172752. METHODDEF(void)
  172753. start_pass_merged_upsample (j_decompress_ptr cinfo)
  172754. {
  172755. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172756. /* Mark the spare buffer empty */
  172757. upsample->spare_full = FALSE;
  172758. /* Initialize total-height counter for detecting bottom of image */
  172759. upsample->rows_to_go = cinfo->output_height;
  172760. }
  172761. /*
  172762. * Control routine to do upsampling (and color conversion).
  172763. *
  172764. * The control routine just handles the row buffering considerations.
  172765. */
  172766. METHODDEF(void)
  172767. merged_2v_upsample (j_decompress_ptr cinfo,
  172768. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172769. JDIMENSION,
  172770. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172771. JDIMENSION out_rows_avail)
  172772. /* 2:1 vertical sampling case: may need a spare row. */
  172773. {
  172774. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172775. JSAMPROW work_ptrs[2];
  172776. JDIMENSION num_rows; /* number of rows returned to caller */
  172777. if (upsample->spare_full) {
  172778. /* If we have a spare row saved from a previous cycle, just return it. */
  172779. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  172780. 1, upsample->out_row_width);
  172781. num_rows = 1;
  172782. upsample->spare_full = FALSE;
  172783. } else {
  172784. /* Figure number of rows to return to caller. */
  172785. num_rows = 2;
  172786. /* Not more than the distance to the end of the image. */
  172787. if (num_rows > upsample->rows_to_go)
  172788. num_rows = upsample->rows_to_go;
  172789. /* And not more than what the client can accept: */
  172790. out_rows_avail -= *out_row_ctr;
  172791. if (num_rows > out_rows_avail)
  172792. num_rows = out_rows_avail;
  172793. /* Create output pointer array for upsampler. */
  172794. work_ptrs[0] = output_buf[*out_row_ctr];
  172795. if (num_rows > 1) {
  172796. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  172797. } else {
  172798. work_ptrs[1] = upsample->spare_row;
  172799. upsample->spare_full = TRUE;
  172800. }
  172801. /* Now do the upsampling. */
  172802. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  172803. }
  172804. /* Adjust counts */
  172805. *out_row_ctr += num_rows;
  172806. upsample->rows_to_go -= num_rows;
  172807. /* When the buffer is emptied, declare this input row group consumed */
  172808. if (! upsample->spare_full)
  172809. (*in_row_group_ctr)++;
  172810. }
  172811. METHODDEF(void)
  172812. merged_1v_upsample (j_decompress_ptr cinfo,
  172813. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172814. JDIMENSION,
  172815. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172816. JDIMENSION)
  172817. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  172818. {
  172819. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172820. /* Just do the upsampling. */
  172821. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  172822. output_buf + *out_row_ctr);
  172823. /* Adjust counts */
  172824. (*out_row_ctr)++;
  172825. (*in_row_group_ctr)++;
  172826. }
  172827. /*
  172828. * These are the routines invoked by the control routines to do
  172829. * the actual upsampling/conversion. One row group is processed per call.
  172830. *
  172831. * Note: since we may be writing directly into application-supplied buffers,
  172832. * we have to be honest about the output width; we can't assume the buffer
  172833. * has been rounded up to an even width.
  172834. */
  172835. /*
  172836. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  172837. */
  172838. METHODDEF(void)
  172839. h2v1_merged_upsample (j_decompress_ptr cinfo,
  172840. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172841. JSAMPARRAY output_buf)
  172842. {
  172843. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172844. register int y, cred, cgreen, cblue;
  172845. int cb, cr;
  172846. register JSAMPROW outptr;
  172847. JSAMPROW inptr0, inptr1, inptr2;
  172848. JDIMENSION col;
  172849. /* copy these pointers into registers if possible */
  172850. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  172851. int * Crrtab = upsample->Cr_r_tab;
  172852. int * Cbbtab = upsample->Cb_b_tab;
  172853. INT32 * Crgtab = upsample->Cr_g_tab;
  172854. INT32 * Cbgtab = upsample->Cb_g_tab;
  172855. SHIFT_TEMPS
  172856. inptr0 = input_buf[0][in_row_group_ctr];
  172857. inptr1 = input_buf[1][in_row_group_ctr];
  172858. inptr2 = input_buf[2][in_row_group_ctr];
  172859. outptr = output_buf[0];
  172860. /* Loop for each pair of output pixels */
  172861. for (col = cinfo->output_width >> 1; col > 0; col--) {
  172862. /* Do the chroma part of the calculation */
  172863. cb = GETJSAMPLE(*inptr1++);
  172864. cr = GETJSAMPLE(*inptr2++);
  172865. cred = Crrtab[cr];
  172866. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172867. cblue = Cbbtab[cb];
  172868. /* Fetch 2 Y values and emit 2 pixels */
  172869. y = GETJSAMPLE(*inptr0++);
  172870. outptr[RGB_RED] = range_limit[y + cred];
  172871. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172872. outptr[RGB_BLUE] = range_limit[y + cblue];
  172873. outptr += RGB_PIXELSIZE;
  172874. y = GETJSAMPLE(*inptr0++);
  172875. outptr[RGB_RED] = range_limit[y + cred];
  172876. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172877. outptr[RGB_BLUE] = range_limit[y + cblue];
  172878. outptr += RGB_PIXELSIZE;
  172879. }
  172880. /* If image width is odd, do the last output column separately */
  172881. if (cinfo->output_width & 1) {
  172882. cb = GETJSAMPLE(*inptr1);
  172883. cr = GETJSAMPLE(*inptr2);
  172884. cred = Crrtab[cr];
  172885. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172886. cblue = Cbbtab[cb];
  172887. y = GETJSAMPLE(*inptr0);
  172888. outptr[RGB_RED] = range_limit[y + cred];
  172889. outptr[RGB_GREEN] = range_limit[y + cgreen];
  172890. outptr[RGB_BLUE] = range_limit[y + cblue];
  172891. }
  172892. }
  172893. /*
  172894. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  172895. */
  172896. METHODDEF(void)
  172897. h2v2_merged_upsample (j_decompress_ptr cinfo,
  172898. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172899. JSAMPARRAY output_buf)
  172900. {
  172901. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172902. register int y, cred, cgreen, cblue;
  172903. int cb, cr;
  172904. register JSAMPROW outptr0, outptr1;
  172905. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  172906. JDIMENSION col;
  172907. /* copy these pointers into registers if possible */
  172908. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  172909. int * Crrtab = upsample->Cr_r_tab;
  172910. int * Cbbtab = upsample->Cb_b_tab;
  172911. INT32 * Crgtab = upsample->Cr_g_tab;
  172912. INT32 * Cbgtab = upsample->Cb_g_tab;
  172913. SHIFT_TEMPS
  172914. inptr00 = input_buf[0][in_row_group_ctr*2];
  172915. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  172916. inptr1 = input_buf[1][in_row_group_ctr];
  172917. inptr2 = input_buf[2][in_row_group_ctr];
  172918. outptr0 = output_buf[0];
  172919. outptr1 = output_buf[1];
  172920. /* Loop for each group of output pixels */
  172921. for (col = cinfo->output_width >> 1; col > 0; col--) {
  172922. /* Do the chroma part of the calculation */
  172923. cb = GETJSAMPLE(*inptr1++);
  172924. cr = GETJSAMPLE(*inptr2++);
  172925. cred = Crrtab[cr];
  172926. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172927. cblue = Cbbtab[cb];
  172928. /* Fetch 4 Y values and emit 4 pixels */
  172929. y = GETJSAMPLE(*inptr00++);
  172930. outptr0[RGB_RED] = range_limit[y + cred];
  172931. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172932. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172933. outptr0 += RGB_PIXELSIZE;
  172934. y = GETJSAMPLE(*inptr00++);
  172935. outptr0[RGB_RED] = range_limit[y + cred];
  172936. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172937. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172938. outptr0 += RGB_PIXELSIZE;
  172939. y = GETJSAMPLE(*inptr01++);
  172940. outptr1[RGB_RED] = range_limit[y + cred];
  172941. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172942. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172943. outptr1 += RGB_PIXELSIZE;
  172944. y = GETJSAMPLE(*inptr01++);
  172945. outptr1[RGB_RED] = range_limit[y + cred];
  172946. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172947. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172948. outptr1 += RGB_PIXELSIZE;
  172949. }
  172950. /* If image width is odd, do the last output column separately */
  172951. if (cinfo->output_width & 1) {
  172952. cb = GETJSAMPLE(*inptr1);
  172953. cr = GETJSAMPLE(*inptr2);
  172954. cred = Crrtab[cr];
  172955. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  172956. cblue = Cbbtab[cb];
  172957. y = GETJSAMPLE(*inptr00);
  172958. outptr0[RGB_RED] = range_limit[y + cred];
  172959. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  172960. outptr0[RGB_BLUE] = range_limit[y + cblue];
  172961. y = GETJSAMPLE(*inptr01);
  172962. outptr1[RGB_RED] = range_limit[y + cred];
  172963. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  172964. outptr1[RGB_BLUE] = range_limit[y + cblue];
  172965. }
  172966. }
  172967. /*
  172968. * Module initialization routine for merged upsampling/color conversion.
  172969. *
  172970. * NB: this is called under the conditions determined by use_merged_upsample()
  172971. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  172972. * of this module; no safety checks are made here.
  172973. */
  172974. GLOBAL(void)
  172975. jinit_merged_upsampler (j_decompress_ptr cinfo)
  172976. {
  172977. my_upsample_ptr upsample;
  172978. upsample = (my_upsample_ptr)
  172979. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172980. SIZEOF(my_upsampler));
  172981. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  172982. upsample->pub.start_pass = start_pass_merged_upsample;
  172983. upsample->pub.need_context_rows = FALSE;
  172984. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  172985. if (cinfo->max_v_samp_factor == 2) {
  172986. upsample->pub.upsample = merged_2v_upsample;
  172987. upsample->upmethod = h2v2_merged_upsample;
  172988. /* Allocate a spare row buffer */
  172989. upsample->spare_row = (JSAMPROW)
  172990. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172991. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  172992. } else {
  172993. upsample->pub.upsample = merged_1v_upsample;
  172994. upsample->upmethod = h2v1_merged_upsample;
  172995. /* No spare row needed */
  172996. upsample->spare_row = NULL;
  172997. }
  172998. build_ycc_rgb_table2(cinfo);
  172999. }
  173000. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  173001. /*** End of inlined file: jdmerge.c ***/
  173002. #undef ASSIGN_STATE
  173003. /*** Start of inlined file: jdphuff.c ***/
  173004. #define JPEG_INTERNALS
  173005. #ifdef D_PROGRESSIVE_SUPPORTED
  173006. /*
  173007. * Expanded entropy decoder object for progressive Huffman decoding.
  173008. *
  173009. * The savable_state subrecord contains fields that change within an MCU,
  173010. * but must not be updated permanently until we complete the MCU.
  173011. */
  173012. typedef struct {
  173013. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  173014. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  173015. } savable_state3;
  173016. /* This macro is to work around compilers with missing or broken
  173017. * structure assignment. You'll need to fix this code if you have
  173018. * such a compiler and you change MAX_COMPS_IN_SCAN.
  173019. */
  173020. #ifndef NO_STRUCT_ASSIGN
  173021. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  173022. #else
  173023. #if MAX_COMPS_IN_SCAN == 4
  173024. #define ASSIGN_STATE(dest,src) \
  173025. ((dest).EOBRUN = (src).EOBRUN, \
  173026. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  173027. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  173028. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  173029. (dest).last_dc_val[3] = (src).last_dc_val[3])
  173030. #endif
  173031. #endif
  173032. typedef struct {
  173033. struct jpeg_entropy_decoder pub; /* public fields */
  173034. /* These fields are loaded into local variables at start of each MCU.
  173035. * In case of suspension, we exit WITHOUT updating them.
  173036. */
  173037. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  173038. savable_state3 saved; /* Other state at start of MCU */
  173039. /* These fields are NOT loaded into local working state. */
  173040. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  173041. /* Pointers to derived tables (these workspaces have image lifespan) */
  173042. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  173043. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  173044. } phuff_entropy_decoder;
  173045. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  173046. /* Forward declarations */
  173047. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  173048. JBLOCKROW *MCU_data));
  173049. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  173050. JBLOCKROW *MCU_data));
  173051. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  173052. JBLOCKROW *MCU_data));
  173053. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  173054. JBLOCKROW *MCU_data));
  173055. /*
  173056. * Initialize for a Huffman-compressed scan.
  173057. */
  173058. METHODDEF(void)
  173059. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  173060. {
  173061. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173062. boolean is_DC_band, bad;
  173063. int ci, coefi, tbl;
  173064. int *coef_bit_ptr;
  173065. jpeg_component_info * compptr;
  173066. is_DC_band = (cinfo->Ss == 0);
  173067. /* Validate scan parameters */
  173068. bad = FALSE;
  173069. if (is_DC_band) {
  173070. if (cinfo->Se != 0)
  173071. bad = TRUE;
  173072. } else {
  173073. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  173074. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  173075. bad = TRUE;
  173076. /* AC scans may have only one component */
  173077. if (cinfo->comps_in_scan != 1)
  173078. bad = TRUE;
  173079. }
  173080. if (cinfo->Ah != 0) {
  173081. /* Successive approximation refinement scan: must have Al = Ah-1. */
  173082. if (cinfo->Al != cinfo->Ah-1)
  173083. bad = TRUE;
  173084. }
  173085. if (cinfo->Al > 13) /* need not check for < 0 */
  173086. bad = TRUE;
  173087. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  173088. * but the spec doesn't say so, and we try to be liberal about what we
  173089. * accept. Note: large Al values could result in out-of-range DC
  173090. * coefficients during early scans, leading to bizarre displays due to
  173091. * overflows in the IDCT math. But we won't crash.
  173092. */
  173093. if (bad)
  173094. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  173095. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  173096. /* Update progression status, and verify that scan order is legal.
  173097. * Note that inter-scan inconsistencies are treated as warnings
  173098. * not fatal errors ... not clear if this is right way to behave.
  173099. */
  173100. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  173101. int cindex = cinfo->cur_comp_info[ci]->component_index;
  173102. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  173103. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  173104. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  173105. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  173106. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  173107. if (cinfo->Ah != expected)
  173108. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  173109. coef_bit_ptr[coefi] = cinfo->Al;
  173110. }
  173111. }
  173112. /* Select MCU decoding routine */
  173113. if (cinfo->Ah == 0) {
  173114. if (is_DC_band)
  173115. entropy->pub.decode_mcu = decode_mcu_DC_first;
  173116. else
  173117. entropy->pub.decode_mcu = decode_mcu_AC_first;
  173118. } else {
  173119. if (is_DC_band)
  173120. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  173121. else
  173122. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  173123. }
  173124. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  173125. compptr = cinfo->cur_comp_info[ci];
  173126. /* Make sure requested tables are present, and compute derived tables.
  173127. * We may build same derived table more than once, but it's not expensive.
  173128. */
  173129. if (is_DC_band) {
  173130. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  173131. tbl = compptr->dc_tbl_no;
  173132. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  173133. & entropy->derived_tbls[tbl]);
  173134. }
  173135. } else {
  173136. tbl = compptr->ac_tbl_no;
  173137. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  173138. & entropy->derived_tbls[tbl]);
  173139. /* remember the single active table */
  173140. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  173141. }
  173142. /* Initialize DC predictions to 0 */
  173143. entropy->saved.last_dc_val[ci] = 0;
  173144. }
  173145. /* Initialize bitread state variables */
  173146. entropy->bitstate.bits_left = 0;
  173147. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  173148. entropy->pub.insufficient_data = FALSE;
  173149. /* Initialize private state variables */
  173150. entropy->saved.EOBRUN = 0;
  173151. /* Initialize restart counter */
  173152. entropy->restarts_to_go = cinfo->restart_interval;
  173153. }
  173154. /*
  173155. * Check for a restart marker & resynchronize decoder.
  173156. * Returns FALSE if must suspend.
  173157. */
  173158. LOCAL(boolean)
  173159. process_restartp (j_decompress_ptr cinfo)
  173160. {
  173161. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173162. int ci;
  173163. /* Throw away any unused bits remaining in bit buffer; */
  173164. /* include any full bytes in next_marker's count of discarded bytes */
  173165. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  173166. entropy->bitstate.bits_left = 0;
  173167. /* Advance past the RSTn marker */
  173168. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  173169. return FALSE;
  173170. /* Re-initialize DC predictions to 0 */
  173171. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  173172. entropy->saved.last_dc_val[ci] = 0;
  173173. /* Re-init EOB run count, too */
  173174. entropy->saved.EOBRUN = 0;
  173175. /* Reset restart counter */
  173176. entropy->restarts_to_go = cinfo->restart_interval;
  173177. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  173178. * against a marker. In that case we will end up treating the next data
  173179. * segment as empty, and we can avoid producing bogus output pixels by
  173180. * leaving the flag set.
  173181. */
  173182. if (cinfo->unread_marker == 0)
  173183. entropy->pub.insufficient_data = FALSE;
  173184. return TRUE;
  173185. }
  173186. /*
  173187. * Huffman MCU decoding.
  173188. * Each of these routines decodes and returns one MCU's worth of
  173189. * Huffman-compressed coefficients.
  173190. * The coefficients are reordered from zigzag order into natural array order,
  173191. * but are not dequantized.
  173192. *
  173193. * The i'th block of the MCU is stored into the block pointed to by
  173194. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  173195. *
  173196. * We return FALSE if data source requested suspension. In that case no
  173197. * changes have been made to permanent state. (Exception: some output
  173198. * coefficients may already have been assigned. This is harmless for
  173199. * spectral selection, since we'll just re-assign them on the next call.
  173200. * Successive approximation AC refinement has to be more careful, however.)
  173201. */
  173202. /*
  173203. * MCU decoding for DC initial scan (either spectral selection,
  173204. * or first pass of successive approximation).
  173205. */
  173206. METHODDEF(boolean)
  173207. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173208. {
  173209. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173210. int Al = cinfo->Al;
  173211. register int s, r;
  173212. int blkn, ci;
  173213. JBLOCKROW block;
  173214. BITREAD_STATE_VARS;
  173215. savable_state3 state;
  173216. d_derived_tbl * tbl;
  173217. jpeg_component_info * compptr;
  173218. /* Process restart marker if needed; may have to suspend */
  173219. if (cinfo->restart_interval) {
  173220. if (entropy->restarts_to_go == 0)
  173221. if (! process_restartp(cinfo))
  173222. return FALSE;
  173223. }
  173224. /* If we've run out of data, just leave the MCU set to zeroes.
  173225. * This way, we return uniform gray for the remainder of the segment.
  173226. */
  173227. if (! entropy->pub.insufficient_data) {
  173228. /* Load up working state */
  173229. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173230. ASSIGN_STATE(state, entropy->saved);
  173231. /* Outer loop handles each block in the MCU */
  173232. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173233. block = MCU_data[blkn];
  173234. ci = cinfo->MCU_membership[blkn];
  173235. compptr = cinfo->cur_comp_info[ci];
  173236. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  173237. /* Decode a single block's worth of coefficients */
  173238. /* Section F.2.2.1: decode the DC coefficient difference */
  173239. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  173240. if (s) {
  173241. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  173242. r = GET_BITS(s);
  173243. s = HUFF_EXTEND(r, s);
  173244. }
  173245. /* Convert DC difference to actual value, update last_dc_val */
  173246. s += state.last_dc_val[ci];
  173247. state.last_dc_val[ci] = s;
  173248. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  173249. (*block)[0] = (JCOEF) (s << Al);
  173250. }
  173251. /* Completed MCU, so update state */
  173252. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173253. ASSIGN_STATE(entropy->saved, state);
  173254. }
  173255. /* Account for restart interval (no-op if not using restarts) */
  173256. entropy->restarts_to_go--;
  173257. return TRUE;
  173258. }
  173259. /*
  173260. * MCU decoding for AC initial scan (either spectral selection,
  173261. * or first pass of successive approximation).
  173262. */
  173263. METHODDEF(boolean)
  173264. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173265. {
  173266. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173267. int Se = cinfo->Se;
  173268. int Al = cinfo->Al;
  173269. register int s, k, r;
  173270. unsigned int EOBRUN;
  173271. JBLOCKROW block;
  173272. BITREAD_STATE_VARS;
  173273. d_derived_tbl * tbl;
  173274. /* Process restart marker if needed; may have to suspend */
  173275. if (cinfo->restart_interval) {
  173276. if (entropy->restarts_to_go == 0)
  173277. if (! process_restartp(cinfo))
  173278. return FALSE;
  173279. }
  173280. /* If we've run out of data, just leave the MCU set to zeroes.
  173281. * This way, we return uniform gray for the remainder of the segment.
  173282. */
  173283. if (! entropy->pub.insufficient_data) {
  173284. /* Load up working state.
  173285. * We can avoid loading/saving bitread state if in an EOB run.
  173286. */
  173287. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173288. /* There is always only one block per MCU */
  173289. if (EOBRUN > 0) /* if it's a band of zeroes... */
  173290. EOBRUN--; /* ...process it now (we do nothing) */
  173291. else {
  173292. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173293. block = MCU_data[0];
  173294. tbl = entropy->ac_derived_tbl;
  173295. for (k = cinfo->Ss; k <= Se; k++) {
  173296. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  173297. r = s >> 4;
  173298. s &= 15;
  173299. if (s) {
  173300. k += r;
  173301. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  173302. r = GET_BITS(s);
  173303. s = HUFF_EXTEND(r, s);
  173304. /* Scale and output coefficient in natural (dezigzagged) order */
  173305. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  173306. } else {
  173307. if (r == 15) { /* ZRL */
  173308. k += 15; /* skip 15 zeroes in band */
  173309. } else { /* EOBr, run length is 2^r + appended bits */
  173310. EOBRUN = 1 << r;
  173311. if (r) { /* EOBr, r > 0 */
  173312. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  173313. r = GET_BITS(r);
  173314. EOBRUN += r;
  173315. }
  173316. EOBRUN--; /* this band is processed at this moment */
  173317. break; /* force end-of-band */
  173318. }
  173319. }
  173320. }
  173321. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173322. }
  173323. /* Completed MCU, so update state */
  173324. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173325. }
  173326. /* Account for restart interval (no-op if not using restarts) */
  173327. entropy->restarts_to_go--;
  173328. return TRUE;
  173329. }
  173330. /*
  173331. * MCU decoding for DC successive approximation refinement scan.
  173332. * Note: we assume such scans can be multi-component, although the spec
  173333. * is not very clear on the point.
  173334. */
  173335. METHODDEF(boolean)
  173336. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173337. {
  173338. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173339. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173340. int blkn;
  173341. JBLOCKROW block;
  173342. BITREAD_STATE_VARS;
  173343. /* Process restart marker if needed; may have to suspend */
  173344. if (cinfo->restart_interval) {
  173345. if (entropy->restarts_to_go == 0)
  173346. if (! process_restartp(cinfo))
  173347. return FALSE;
  173348. }
  173349. /* Not worth the cycles to check insufficient_data here,
  173350. * since we will not change the data anyway if we read zeroes.
  173351. */
  173352. /* Load up working state */
  173353. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173354. /* Outer loop handles each block in the MCU */
  173355. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173356. block = MCU_data[blkn];
  173357. /* Encoded data is simply the next bit of the two's-complement DC value */
  173358. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  173359. if (GET_BITS(1))
  173360. (*block)[0] |= p1;
  173361. /* Note: since we use |=, repeating the assignment later is safe */
  173362. }
  173363. /* Completed MCU, so update state */
  173364. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173365. /* Account for restart interval (no-op if not using restarts) */
  173366. entropy->restarts_to_go--;
  173367. return TRUE;
  173368. }
  173369. /*
  173370. * MCU decoding for AC successive approximation refinement scan.
  173371. */
  173372. METHODDEF(boolean)
  173373. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173374. {
  173375. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173376. int Se = cinfo->Se;
  173377. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173378. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  173379. register int s, k, r;
  173380. unsigned int EOBRUN;
  173381. JBLOCKROW block;
  173382. JCOEFPTR thiscoef;
  173383. BITREAD_STATE_VARS;
  173384. d_derived_tbl * tbl;
  173385. int num_newnz;
  173386. int newnz_pos[DCTSIZE2];
  173387. /* Process restart marker if needed; may have to suspend */
  173388. if (cinfo->restart_interval) {
  173389. if (entropy->restarts_to_go == 0)
  173390. if (! process_restartp(cinfo))
  173391. return FALSE;
  173392. }
  173393. /* If we've run out of data, don't modify the MCU.
  173394. */
  173395. if (! entropy->pub.insufficient_data) {
  173396. /* Load up working state */
  173397. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173398. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173399. /* There is always only one block per MCU */
  173400. block = MCU_data[0];
  173401. tbl = entropy->ac_derived_tbl;
  173402. /* If we are forced to suspend, we must undo the assignments to any newly
  173403. * nonzero coefficients in the block, because otherwise we'd get confused
  173404. * next time about which coefficients were already nonzero.
  173405. * But we need not undo addition of bits to already-nonzero coefficients;
  173406. * instead, we can test the current bit to see if we already did it.
  173407. */
  173408. num_newnz = 0;
  173409. /* initialize coefficient loop counter to start of band */
  173410. k = cinfo->Ss;
  173411. if (EOBRUN == 0) {
  173412. for (; k <= Se; k++) {
  173413. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  173414. r = s >> 4;
  173415. s &= 15;
  173416. if (s) {
  173417. if (s != 1) /* size of new coef should always be 1 */
  173418. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  173419. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173420. if (GET_BITS(1))
  173421. s = p1; /* newly nonzero coef is positive */
  173422. else
  173423. s = m1; /* newly nonzero coef is negative */
  173424. } else {
  173425. if (r != 15) {
  173426. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  173427. if (r) {
  173428. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  173429. r = GET_BITS(r);
  173430. EOBRUN += r;
  173431. }
  173432. break; /* rest of block is handled by EOB logic */
  173433. }
  173434. /* note s = 0 for processing ZRL */
  173435. }
  173436. /* Advance over already-nonzero coefs and r still-zero coefs,
  173437. * appending correction bits to the nonzeroes. A correction bit is 1
  173438. * if the absolute value of the coefficient must be increased.
  173439. */
  173440. do {
  173441. thiscoef = *block + jpeg_natural_order[k];
  173442. if (*thiscoef != 0) {
  173443. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173444. if (GET_BITS(1)) {
  173445. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  173446. if (*thiscoef >= 0)
  173447. *thiscoef += p1;
  173448. else
  173449. *thiscoef += m1;
  173450. }
  173451. }
  173452. } else {
  173453. if (--r < 0)
  173454. break; /* reached target zero coefficient */
  173455. }
  173456. k++;
  173457. } while (k <= Se);
  173458. if (s) {
  173459. int pos = jpeg_natural_order[k];
  173460. /* Output newly nonzero coefficient */
  173461. (*block)[pos] = (JCOEF) s;
  173462. /* Remember its position in case we have to suspend */
  173463. newnz_pos[num_newnz++] = pos;
  173464. }
  173465. }
  173466. }
  173467. if (EOBRUN > 0) {
  173468. /* Scan any remaining coefficient positions after the end-of-band
  173469. * (the last newly nonzero coefficient, if any). Append a correction
  173470. * bit to each already-nonzero coefficient. A correction bit is 1
  173471. * if the absolute value of the coefficient must be increased.
  173472. */
  173473. for (; k <= Se; k++) {
  173474. thiscoef = *block + jpeg_natural_order[k];
  173475. if (*thiscoef != 0) {
  173476. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173477. if (GET_BITS(1)) {
  173478. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  173479. if (*thiscoef >= 0)
  173480. *thiscoef += p1;
  173481. else
  173482. *thiscoef += m1;
  173483. }
  173484. }
  173485. }
  173486. }
  173487. /* Count one block completed in EOB run */
  173488. EOBRUN--;
  173489. }
  173490. /* Completed MCU, so update state */
  173491. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173492. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173493. }
  173494. /* Account for restart interval (no-op if not using restarts) */
  173495. entropy->restarts_to_go--;
  173496. return TRUE;
  173497. undoit:
  173498. /* Re-zero any output coefficients that we made newly nonzero */
  173499. while (num_newnz > 0)
  173500. (*block)[newnz_pos[--num_newnz]] = 0;
  173501. return FALSE;
  173502. }
  173503. /*
  173504. * Module initialization routine for progressive Huffman entropy decoding.
  173505. */
  173506. GLOBAL(void)
  173507. jinit_phuff_decoder (j_decompress_ptr cinfo)
  173508. {
  173509. phuff_entropy_ptr2 entropy;
  173510. int *coef_bit_ptr;
  173511. int ci, i;
  173512. entropy = (phuff_entropy_ptr2)
  173513. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173514. SIZEOF(phuff_entropy_decoder));
  173515. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  173516. entropy->pub.start_pass = start_pass_phuff_decoder;
  173517. /* Mark derived tables unallocated */
  173518. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  173519. entropy->derived_tbls[i] = NULL;
  173520. }
  173521. /* Create progression status table */
  173522. cinfo->coef_bits = (int (*)[DCTSIZE2])
  173523. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173524. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  173525. coef_bit_ptr = & cinfo->coef_bits[0][0];
  173526. for (ci = 0; ci < cinfo->num_components; ci++)
  173527. for (i = 0; i < DCTSIZE2; i++)
  173528. *coef_bit_ptr++ = -1;
  173529. }
  173530. #endif /* D_PROGRESSIVE_SUPPORTED */
  173531. /*** End of inlined file: jdphuff.c ***/
  173532. /*** Start of inlined file: jdpostct.c ***/
  173533. #define JPEG_INTERNALS
  173534. /* Private buffer controller object */
  173535. typedef struct {
  173536. struct jpeg_d_post_controller pub; /* public fields */
  173537. /* Color quantization source buffer: this holds output data from
  173538. * the upsample/color conversion step to be passed to the quantizer.
  173539. * For two-pass color quantization, we need a full-image buffer;
  173540. * for one-pass operation, a strip buffer is sufficient.
  173541. */
  173542. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  173543. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  173544. JDIMENSION strip_height; /* buffer size in rows */
  173545. /* for two-pass mode only: */
  173546. JDIMENSION starting_row; /* row # of first row in current strip */
  173547. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  173548. } my_post_controller;
  173549. typedef my_post_controller * my_post_ptr;
  173550. /* Forward declarations */
  173551. METHODDEF(void) post_process_1pass
  173552. JPP((j_decompress_ptr cinfo,
  173553. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173554. JDIMENSION in_row_groups_avail,
  173555. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173556. JDIMENSION out_rows_avail));
  173557. #ifdef QUANT_2PASS_SUPPORTED
  173558. METHODDEF(void) post_process_prepass
  173559. JPP((j_decompress_ptr cinfo,
  173560. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173561. JDIMENSION in_row_groups_avail,
  173562. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173563. JDIMENSION out_rows_avail));
  173564. METHODDEF(void) post_process_2pass
  173565. JPP((j_decompress_ptr cinfo,
  173566. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173567. JDIMENSION in_row_groups_avail,
  173568. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173569. JDIMENSION out_rows_avail));
  173570. #endif
  173571. /*
  173572. * Initialize for a processing pass.
  173573. */
  173574. METHODDEF(void)
  173575. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  173576. {
  173577. my_post_ptr post = (my_post_ptr) cinfo->post;
  173578. switch (pass_mode) {
  173579. case JBUF_PASS_THRU:
  173580. if (cinfo->quantize_colors) {
  173581. /* Single-pass processing with color quantization. */
  173582. post->pub.post_process_data = post_process_1pass;
  173583. /* We could be doing buffered-image output before starting a 2-pass
  173584. * color quantization; in that case, jinit_d_post_controller did not
  173585. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  173586. */
  173587. if (post->buffer == NULL) {
  173588. post->buffer = (*cinfo->mem->access_virt_sarray)
  173589. ((j_common_ptr) cinfo, post->whole_image,
  173590. (JDIMENSION) 0, post->strip_height, TRUE);
  173591. }
  173592. } else {
  173593. /* For single-pass processing without color quantization,
  173594. * I have no work to do; just call the upsampler directly.
  173595. */
  173596. post->pub.post_process_data = cinfo->upsample->upsample;
  173597. }
  173598. break;
  173599. #ifdef QUANT_2PASS_SUPPORTED
  173600. case JBUF_SAVE_AND_PASS:
  173601. /* First pass of 2-pass quantization */
  173602. if (post->whole_image == NULL)
  173603. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173604. post->pub.post_process_data = post_process_prepass;
  173605. break;
  173606. case JBUF_CRANK_DEST:
  173607. /* Second pass of 2-pass quantization */
  173608. if (post->whole_image == NULL)
  173609. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173610. post->pub.post_process_data = post_process_2pass;
  173611. break;
  173612. #endif /* QUANT_2PASS_SUPPORTED */
  173613. default:
  173614. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173615. break;
  173616. }
  173617. post->starting_row = post->next_row = 0;
  173618. }
  173619. /*
  173620. * Process some data in the one-pass (strip buffer) case.
  173621. * This is used for color precision reduction as well as one-pass quantization.
  173622. */
  173623. METHODDEF(void)
  173624. post_process_1pass (j_decompress_ptr cinfo,
  173625. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173626. JDIMENSION in_row_groups_avail,
  173627. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173628. JDIMENSION out_rows_avail)
  173629. {
  173630. my_post_ptr post = (my_post_ptr) cinfo->post;
  173631. JDIMENSION num_rows, max_rows;
  173632. /* Fill the buffer, but not more than what we can dump out in one go. */
  173633. /* Note we rely on the upsampler to detect bottom of image. */
  173634. max_rows = out_rows_avail - *out_row_ctr;
  173635. if (max_rows > post->strip_height)
  173636. max_rows = post->strip_height;
  173637. num_rows = 0;
  173638. (*cinfo->upsample->upsample) (cinfo,
  173639. input_buf, in_row_group_ctr, in_row_groups_avail,
  173640. post->buffer, &num_rows, max_rows);
  173641. /* Quantize and emit data. */
  173642. (*cinfo->cquantize->color_quantize) (cinfo,
  173643. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  173644. *out_row_ctr += num_rows;
  173645. }
  173646. #ifdef QUANT_2PASS_SUPPORTED
  173647. /*
  173648. * Process some data in the first pass of 2-pass quantization.
  173649. */
  173650. METHODDEF(void)
  173651. post_process_prepass (j_decompress_ptr cinfo,
  173652. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173653. JDIMENSION in_row_groups_avail,
  173654. JSAMPARRAY, JDIMENSION *out_row_ctr,
  173655. JDIMENSION)
  173656. {
  173657. my_post_ptr post = (my_post_ptr) cinfo->post;
  173658. JDIMENSION old_next_row, num_rows;
  173659. /* Reposition virtual buffer if at start of strip. */
  173660. if (post->next_row == 0) {
  173661. post->buffer = (*cinfo->mem->access_virt_sarray)
  173662. ((j_common_ptr) cinfo, post->whole_image,
  173663. post->starting_row, post->strip_height, TRUE);
  173664. }
  173665. /* Upsample some data (up to a strip height's worth). */
  173666. old_next_row = post->next_row;
  173667. (*cinfo->upsample->upsample) (cinfo,
  173668. input_buf, in_row_group_ctr, in_row_groups_avail,
  173669. post->buffer, &post->next_row, post->strip_height);
  173670. /* Allow quantizer to scan new data. No data is emitted, */
  173671. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  173672. if (post->next_row > old_next_row) {
  173673. num_rows = post->next_row - old_next_row;
  173674. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  173675. (JSAMPARRAY) NULL, (int) num_rows);
  173676. *out_row_ctr += num_rows;
  173677. }
  173678. /* Advance if we filled the strip. */
  173679. if (post->next_row >= post->strip_height) {
  173680. post->starting_row += post->strip_height;
  173681. post->next_row = 0;
  173682. }
  173683. }
  173684. /*
  173685. * Process some data in the second pass of 2-pass quantization.
  173686. */
  173687. METHODDEF(void)
  173688. post_process_2pass (j_decompress_ptr cinfo,
  173689. JSAMPIMAGE, JDIMENSION *,
  173690. JDIMENSION,
  173691. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173692. JDIMENSION out_rows_avail)
  173693. {
  173694. my_post_ptr post = (my_post_ptr) cinfo->post;
  173695. JDIMENSION num_rows, max_rows;
  173696. /* Reposition virtual buffer if at start of strip. */
  173697. if (post->next_row == 0) {
  173698. post->buffer = (*cinfo->mem->access_virt_sarray)
  173699. ((j_common_ptr) cinfo, post->whole_image,
  173700. post->starting_row, post->strip_height, FALSE);
  173701. }
  173702. /* Determine number of rows to emit. */
  173703. num_rows = post->strip_height - post->next_row; /* available in strip */
  173704. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  173705. if (num_rows > max_rows)
  173706. num_rows = max_rows;
  173707. /* We have to check bottom of image here, can't depend on upsampler. */
  173708. max_rows = cinfo->output_height - post->starting_row;
  173709. if (num_rows > max_rows)
  173710. num_rows = max_rows;
  173711. /* Quantize and emit data. */
  173712. (*cinfo->cquantize->color_quantize) (cinfo,
  173713. post->buffer + post->next_row, output_buf + *out_row_ctr,
  173714. (int) num_rows);
  173715. *out_row_ctr += num_rows;
  173716. /* Advance if we filled the strip. */
  173717. post->next_row += num_rows;
  173718. if (post->next_row >= post->strip_height) {
  173719. post->starting_row += post->strip_height;
  173720. post->next_row = 0;
  173721. }
  173722. }
  173723. #endif /* QUANT_2PASS_SUPPORTED */
  173724. /*
  173725. * Initialize postprocessing controller.
  173726. */
  173727. GLOBAL(void)
  173728. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  173729. {
  173730. my_post_ptr post;
  173731. post = (my_post_ptr)
  173732. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173733. SIZEOF(my_post_controller));
  173734. cinfo->post = (struct jpeg_d_post_controller *) post;
  173735. post->pub.start_pass = start_pass_dpost;
  173736. post->whole_image = NULL; /* flag for no virtual arrays */
  173737. post->buffer = NULL; /* flag for no strip buffer */
  173738. /* Create the quantization buffer, if needed */
  173739. if (cinfo->quantize_colors) {
  173740. /* The buffer strip height is max_v_samp_factor, which is typically
  173741. * an efficient number of rows for upsampling to return.
  173742. * (In the presence of output rescaling, we might want to be smarter?)
  173743. */
  173744. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  173745. if (need_full_buffer) {
  173746. /* Two-pass color quantization: need full-image storage. */
  173747. /* We round up the number of rows to a multiple of the strip height. */
  173748. #ifdef QUANT_2PASS_SUPPORTED
  173749. post->whole_image = (*cinfo->mem->request_virt_sarray)
  173750. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  173751. cinfo->output_width * cinfo->out_color_components,
  173752. (JDIMENSION) jround_up((long) cinfo->output_height,
  173753. (long) post->strip_height),
  173754. post->strip_height);
  173755. #else
  173756. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173757. #endif /* QUANT_2PASS_SUPPORTED */
  173758. } else {
  173759. /* One-pass color quantization: just make a strip buffer. */
  173760. post->buffer = (*cinfo->mem->alloc_sarray)
  173761. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173762. cinfo->output_width * cinfo->out_color_components,
  173763. post->strip_height);
  173764. }
  173765. }
  173766. }
  173767. /*** End of inlined file: jdpostct.c ***/
  173768. #undef FIX
  173769. /*** Start of inlined file: jdsample.c ***/
  173770. #define JPEG_INTERNALS
  173771. /* Pointer to routine to upsample a single component */
  173772. typedef JMETHOD(void, upsample1_ptr,
  173773. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173774. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  173775. /* Private subobject */
  173776. typedef struct {
  173777. struct jpeg_upsampler pub; /* public fields */
  173778. /* Color conversion buffer. When using separate upsampling and color
  173779. * conversion steps, this buffer holds one upsampled row group until it
  173780. * has been color converted and output.
  173781. * Note: we do not allocate any storage for component(s) which are full-size,
  173782. * ie do not need rescaling. The corresponding entry of color_buf[] is
  173783. * simply set to point to the input data array, thereby avoiding copying.
  173784. */
  173785. JSAMPARRAY color_buf[MAX_COMPONENTS];
  173786. /* Per-component upsampling method pointers */
  173787. upsample1_ptr methods[MAX_COMPONENTS];
  173788. int next_row_out; /* counts rows emitted from color_buf */
  173789. JDIMENSION rows_to_go; /* counts rows remaining in image */
  173790. /* Height of an input row group for each component. */
  173791. int rowgroup_height[MAX_COMPONENTS];
  173792. /* These arrays save pixel expansion factors so that int_expand need not
  173793. * recompute them each time. They are unused for other upsampling methods.
  173794. */
  173795. UINT8 h_expand[MAX_COMPONENTS];
  173796. UINT8 v_expand[MAX_COMPONENTS];
  173797. } my_upsampler2;
  173798. typedef my_upsampler2 * my_upsample_ptr2;
  173799. /*
  173800. * Initialize for an upsampling pass.
  173801. */
  173802. METHODDEF(void)
  173803. start_pass_upsample (j_decompress_ptr cinfo)
  173804. {
  173805. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173806. /* Mark the conversion buffer empty */
  173807. upsample->next_row_out = cinfo->max_v_samp_factor;
  173808. /* Initialize total-height counter for detecting bottom of image */
  173809. upsample->rows_to_go = cinfo->output_height;
  173810. }
  173811. /*
  173812. * Control routine to do upsampling (and color conversion).
  173813. *
  173814. * In this version we upsample each component independently.
  173815. * We upsample one row group into the conversion buffer, then apply
  173816. * color conversion a row at a time.
  173817. */
  173818. METHODDEF(void)
  173819. sep_upsample (j_decompress_ptr cinfo,
  173820. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173821. JDIMENSION,
  173822. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173823. JDIMENSION out_rows_avail)
  173824. {
  173825. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173826. int ci;
  173827. jpeg_component_info * compptr;
  173828. JDIMENSION num_rows;
  173829. /* Fill the conversion buffer, if it's empty */
  173830. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  173831. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  173832. ci++, compptr++) {
  173833. /* Invoke per-component upsample method. Notice we pass a POINTER
  173834. * to color_buf[ci], so that fullsize_upsample can change it.
  173835. */
  173836. (*upsample->methods[ci]) (cinfo, compptr,
  173837. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  173838. upsample->color_buf + ci);
  173839. }
  173840. upsample->next_row_out = 0;
  173841. }
  173842. /* Color-convert and emit rows */
  173843. /* How many we have in the buffer: */
  173844. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  173845. /* Not more than the distance to the end of the image. Need this test
  173846. * in case the image height is not a multiple of max_v_samp_factor:
  173847. */
  173848. if (num_rows > upsample->rows_to_go)
  173849. num_rows = upsample->rows_to_go;
  173850. /* And not more than what the client can accept: */
  173851. out_rows_avail -= *out_row_ctr;
  173852. if (num_rows > out_rows_avail)
  173853. num_rows = out_rows_avail;
  173854. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  173855. (JDIMENSION) upsample->next_row_out,
  173856. output_buf + *out_row_ctr,
  173857. (int) num_rows);
  173858. /* Adjust counts */
  173859. *out_row_ctr += num_rows;
  173860. upsample->rows_to_go -= num_rows;
  173861. upsample->next_row_out += num_rows;
  173862. /* When the buffer is emptied, declare this input row group consumed */
  173863. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  173864. (*in_row_group_ctr)++;
  173865. }
  173866. /*
  173867. * These are the routines invoked by sep_upsample to upsample pixel values
  173868. * of a single component. One row group is processed per call.
  173869. */
  173870. /*
  173871. * For full-size components, we just make color_buf[ci] point at the
  173872. * input buffer, and thus avoid copying any data. Note that this is
  173873. * safe only because sep_upsample doesn't declare the input row group
  173874. * "consumed" until we are done color converting and emitting it.
  173875. */
  173876. METHODDEF(void)
  173877. fullsize_upsample (j_decompress_ptr, jpeg_component_info *,
  173878. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173879. {
  173880. *output_data_ptr = input_data;
  173881. }
  173882. /*
  173883. * This is a no-op version used for "uninteresting" components.
  173884. * These components will not be referenced by color conversion.
  173885. */
  173886. METHODDEF(void)
  173887. noop_upsample (j_decompress_ptr, jpeg_component_info *,
  173888. JSAMPARRAY, JSAMPARRAY * output_data_ptr)
  173889. {
  173890. *output_data_ptr = NULL; /* safety check */
  173891. }
  173892. /*
  173893. * This version handles any integral sampling ratios.
  173894. * This is not used for typical JPEG files, so it need not be fast.
  173895. * Nor, for that matter, is it particularly accurate: the algorithm is
  173896. * simple replication of the input pixel onto the corresponding output
  173897. * pixels. The hi-falutin sampling literature refers to this as a
  173898. * "box filter". A box filter tends to introduce visible artifacts,
  173899. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  173900. * you would be well advised to improve this code.
  173901. */
  173902. METHODDEF(void)
  173903. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  173904. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173905. {
  173906. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  173907. JSAMPARRAY output_data = *output_data_ptr;
  173908. register JSAMPROW inptr, outptr;
  173909. register JSAMPLE invalue;
  173910. register int h;
  173911. JSAMPROW outend;
  173912. int h_expand, v_expand;
  173913. int inrow, outrow;
  173914. h_expand = upsample->h_expand[compptr->component_index];
  173915. v_expand = upsample->v_expand[compptr->component_index];
  173916. inrow = outrow = 0;
  173917. while (outrow < cinfo->max_v_samp_factor) {
  173918. /* Generate one output row with proper horizontal expansion */
  173919. inptr = input_data[inrow];
  173920. outptr = output_data[outrow];
  173921. outend = outptr + cinfo->output_width;
  173922. while (outptr < outend) {
  173923. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173924. for (h = h_expand; h > 0; h--) {
  173925. *outptr++ = invalue;
  173926. }
  173927. }
  173928. /* Generate any additional output rows by duplicating the first one */
  173929. if (v_expand > 1) {
  173930. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  173931. v_expand-1, cinfo->output_width);
  173932. }
  173933. inrow++;
  173934. outrow += v_expand;
  173935. }
  173936. }
  173937. /*
  173938. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  173939. * It's still a box filter.
  173940. */
  173941. METHODDEF(void)
  173942. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  173943. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173944. {
  173945. JSAMPARRAY output_data = *output_data_ptr;
  173946. register JSAMPROW inptr, outptr;
  173947. register JSAMPLE invalue;
  173948. JSAMPROW outend;
  173949. int inrow;
  173950. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  173951. inptr = input_data[inrow];
  173952. outptr = output_data[inrow];
  173953. outend = outptr + cinfo->output_width;
  173954. while (outptr < outend) {
  173955. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173956. *outptr++ = invalue;
  173957. *outptr++ = invalue;
  173958. }
  173959. }
  173960. }
  173961. /*
  173962. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  173963. * It's still a box filter.
  173964. */
  173965. METHODDEF(void)
  173966. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  173967. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  173968. {
  173969. JSAMPARRAY output_data = *output_data_ptr;
  173970. register JSAMPROW inptr, outptr;
  173971. register JSAMPLE invalue;
  173972. JSAMPROW outend;
  173973. int inrow, outrow;
  173974. inrow = outrow = 0;
  173975. while (outrow < cinfo->max_v_samp_factor) {
  173976. inptr = input_data[inrow];
  173977. outptr = output_data[outrow];
  173978. outend = outptr + cinfo->output_width;
  173979. while (outptr < outend) {
  173980. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  173981. *outptr++ = invalue;
  173982. *outptr++ = invalue;
  173983. }
  173984. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  173985. 1, cinfo->output_width);
  173986. inrow++;
  173987. outrow += 2;
  173988. }
  173989. }
  173990. /*
  173991. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  173992. *
  173993. * The upsampling algorithm is linear interpolation between pixel centers,
  173994. * also known as a "triangle filter". This is a good compromise between
  173995. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  173996. * of the way between input pixel centers.
  173997. *
  173998. * A note about the "bias" calculations: when rounding fractional values to
  173999. * integer, we do not want to always round 0.5 up to the next integer.
  174000. * If we did that, we'd introduce a noticeable bias towards larger values.
  174001. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  174002. * alternate pixel locations (a simple ordered dither pattern).
  174003. */
  174004. METHODDEF(void)
  174005. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174006. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174007. {
  174008. JSAMPARRAY output_data = *output_data_ptr;
  174009. register JSAMPROW inptr, outptr;
  174010. register int invalue;
  174011. register JDIMENSION colctr;
  174012. int inrow;
  174013. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  174014. inptr = input_data[inrow];
  174015. outptr = output_data[inrow];
  174016. /* Special case for first column */
  174017. invalue = GETJSAMPLE(*inptr++);
  174018. *outptr++ = (JSAMPLE) invalue;
  174019. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  174020. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  174021. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  174022. invalue = GETJSAMPLE(*inptr++) * 3;
  174023. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  174024. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  174025. }
  174026. /* Special case for last column */
  174027. invalue = GETJSAMPLE(*inptr);
  174028. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  174029. *outptr++ = (JSAMPLE) invalue;
  174030. }
  174031. }
  174032. /*
  174033. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  174034. * Again a triangle filter; see comments for h2v1 case, above.
  174035. *
  174036. * It is OK for us to reference the adjacent input rows because we demanded
  174037. * context from the main buffer controller (see initialization code).
  174038. */
  174039. METHODDEF(void)
  174040. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174041. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174042. {
  174043. JSAMPARRAY output_data = *output_data_ptr;
  174044. register JSAMPROW inptr0, inptr1, outptr;
  174045. #if BITS_IN_JSAMPLE == 8
  174046. register int thiscolsum, lastcolsum, nextcolsum;
  174047. #else
  174048. register INT32 thiscolsum, lastcolsum, nextcolsum;
  174049. #endif
  174050. register JDIMENSION colctr;
  174051. int inrow, outrow, v;
  174052. inrow = outrow = 0;
  174053. while (outrow < cinfo->max_v_samp_factor) {
  174054. for (v = 0; v < 2; v++) {
  174055. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  174056. inptr0 = input_data[inrow];
  174057. if (v == 0) /* next nearest is row above */
  174058. inptr1 = input_data[inrow-1];
  174059. else /* next nearest is row below */
  174060. inptr1 = input_data[inrow+1];
  174061. outptr = output_data[outrow++];
  174062. /* Special case for first column */
  174063. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174064. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174065. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  174066. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  174067. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  174068. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  174069. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  174070. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  174071. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174072. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  174073. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  174074. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  174075. }
  174076. /* Special case for last column */
  174077. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  174078. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  174079. }
  174080. inrow++;
  174081. }
  174082. }
  174083. /*
  174084. * Module initialization routine for upsampling.
  174085. */
  174086. GLOBAL(void)
  174087. jinit_upsampler (j_decompress_ptr cinfo)
  174088. {
  174089. my_upsample_ptr2 upsample;
  174090. int ci;
  174091. jpeg_component_info * compptr;
  174092. boolean need_buffer, do_fancy;
  174093. int h_in_group, v_in_group, h_out_group, v_out_group;
  174094. upsample = (my_upsample_ptr2)
  174095. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174096. SIZEOF(my_upsampler2));
  174097. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  174098. upsample->pub.start_pass = start_pass_upsample;
  174099. upsample->pub.upsample = sep_upsample;
  174100. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  174101. if (cinfo->CCIR601_sampling) /* this isn't supported */
  174102. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  174103. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  174104. * so don't ask for it.
  174105. */
  174106. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  174107. /* Verify we can handle the sampling factors, select per-component methods,
  174108. * and create storage as needed.
  174109. */
  174110. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  174111. ci++, compptr++) {
  174112. /* Compute size of an "input group" after IDCT scaling. This many samples
  174113. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  174114. */
  174115. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  174116. cinfo->min_DCT_scaled_size;
  174117. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  174118. cinfo->min_DCT_scaled_size;
  174119. h_out_group = cinfo->max_h_samp_factor;
  174120. v_out_group = cinfo->max_v_samp_factor;
  174121. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  174122. need_buffer = TRUE;
  174123. if (! compptr->component_needed) {
  174124. /* Don't bother to upsample an uninteresting component. */
  174125. upsample->methods[ci] = noop_upsample;
  174126. need_buffer = FALSE;
  174127. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  174128. /* Fullsize components can be processed without any work. */
  174129. upsample->methods[ci] = fullsize_upsample;
  174130. need_buffer = FALSE;
  174131. } else if (h_in_group * 2 == h_out_group &&
  174132. v_in_group == v_out_group) {
  174133. /* Special cases for 2h1v upsampling */
  174134. if (do_fancy && compptr->downsampled_width > 2)
  174135. upsample->methods[ci] = h2v1_fancy_upsample;
  174136. else
  174137. upsample->methods[ci] = h2v1_upsample;
  174138. } else if (h_in_group * 2 == h_out_group &&
  174139. v_in_group * 2 == v_out_group) {
  174140. /* Special cases for 2h2v upsampling */
  174141. if (do_fancy && compptr->downsampled_width > 2) {
  174142. upsample->methods[ci] = h2v2_fancy_upsample;
  174143. upsample->pub.need_context_rows = TRUE;
  174144. } else
  174145. upsample->methods[ci] = h2v2_upsample;
  174146. } else if ((h_out_group % h_in_group) == 0 &&
  174147. (v_out_group % v_in_group) == 0) {
  174148. /* Generic integral-factors upsampling method */
  174149. upsample->methods[ci] = int_upsample;
  174150. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  174151. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  174152. } else
  174153. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  174154. if (need_buffer) {
  174155. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  174156. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174157. (JDIMENSION) jround_up((long) cinfo->output_width,
  174158. (long) cinfo->max_h_samp_factor),
  174159. (JDIMENSION) cinfo->max_v_samp_factor);
  174160. }
  174161. }
  174162. }
  174163. /*** End of inlined file: jdsample.c ***/
  174164. /*** Start of inlined file: jdtrans.c ***/
  174165. #define JPEG_INTERNALS
  174166. /* Forward declarations */
  174167. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  174168. /*
  174169. * Read the coefficient arrays from a JPEG file.
  174170. * jpeg_read_header must be completed before calling this.
  174171. *
  174172. * The entire image is read into a set of virtual coefficient-block arrays,
  174173. * one per component. The return value is a pointer to the array of
  174174. * virtual-array descriptors. These can be manipulated directly via the
  174175. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  174176. * To release the memory occupied by the virtual arrays, call
  174177. * jpeg_finish_decompress() when done with the data.
  174178. *
  174179. * An alternative usage is to simply obtain access to the coefficient arrays
  174180. * during a buffered-image-mode decompression operation. This is allowed
  174181. * after any jpeg_finish_output() call. The arrays can be accessed until
  174182. * jpeg_finish_decompress() is called. (Note that any call to the library
  174183. * may reposition the arrays, so don't rely on access_virt_barray() results
  174184. * to stay valid across library calls.)
  174185. *
  174186. * Returns NULL if suspended. This case need be checked only if
  174187. * a suspending data source is used.
  174188. */
  174189. GLOBAL(jvirt_barray_ptr *)
  174190. jpeg_read_coefficients (j_decompress_ptr cinfo)
  174191. {
  174192. if (cinfo->global_state == DSTATE_READY) {
  174193. /* First call: initialize active modules */
  174194. transdecode_master_selection(cinfo);
  174195. cinfo->global_state = DSTATE_RDCOEFS;
  174196. }
  174197. if (cinfo->global_state == DSTATE_RDCOEFS) {
  174198. /* Absorb whole file into the coef buffer */
  174199. for (;;) {
  174200. int retcode;
  174201. /* Call progress monitor hook if present */
  174202. if (cinfo->progress != NULL)
  174203. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  174204. /* Absorb some more input */
  174205. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  174206. if (retcode == JPEG_SUSPENDED)
  174207. return NULL;
  174208. if (retcode == JPEG_REACHED_EOI)
  174209. break;
  174210. /* Advance progress counter if appropriate */
  174211. if (cinfo->progress != NULL &&
  174212. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  174213. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  174214. /* startup underestimated number of scans; ratchet up one scan */
  174215. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  174216. }
  174217. }
  174218. }
  174219. /* Set state so that jpeg_finish_decompress does the right thing */
  174220. cinfo->global_state = DSTATE_STOPPING;
  174221. }
  174222. /* At this point we should be in state DSTATE_STOPPING if being used
  174223. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  174224. * to the coefficients during a full buffered-image-mode decompression.
  174225. */
  174226. if ((cinfo->global_state == DSTATE_STOPPING ||
  174227. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  174228. return cinfo->coef->coef_arrays;
  174229. }
  174230. /* Oops, improper usage */
  174231. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  174232. return NULL; /* keep compiler happy */
  174233. }
  174234. /*
  174235. * Master selection of decompression modules for transcoding.
  174236. * This substitutes for jdmaster.c's initialization of the full decompressor.
  174237. */
  174238. LOCAL(void)
  174239. transdecode_master_selection (j_decompress_ptr cinfo)
  174240. {
  174241. /* This is effectively a buffered-image operation. */
  174242. cinfo->buffered_image = TRUE;
  174243. /* Entropy decoding: either Huffman or arithmetic coding. */
  174244. if (cinfo->arith_code) {
  174245. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  174246. } else {
  174247. if (cinfo->progressive_mode) {
  174248. #ifdef D_PROGRESSIVE_SUPPORTED
  174249. jinit_phuff_decoder(cinfo);
  174250. #else
  174251. ERREXIT(cinfo, JERR_NOT_COMPILED);
  174252. #endif
  174253. } else
  174254. jinit_huff_decoder(cinfo);
  174255. }
  174256. /* Always get a full-image coefficient buffer. */
  174257. jinit_d_coef_controller(cinfo, TRUE);
  174258. /* We can now tell the memory manager to allocate virtual arrays. */
  174259. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  174260. /* Initialize input side of decompressor to consume first scan. */
  174261. (*cinfo->inputctl->start_input_pass) (cinfo);
  174262. /* Initialize progress monitoring. */
  174263. if (cinfo->progress != NULL) {
  174264. int nscans;
  174265. /* Estimate number of scans to set pass_limit. */
  174266. if (cinfo->progressive_mode) {
  174267. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  174268. nscans = 2 + 3 * cinfo->num_components;
  174269. } else if (cinfo->inputctl->has_multiple_scans) {
  174270. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  174271. nscans = cinfo->num_components;
  174272. } else {
  174273. nscans = 1;
  174274. }
  174275. cinfo->progress->pass_counter = 0L;
  174276. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  174277. cinfo->progress->completed_passes = 0;
  174278. cinfo->progress->total_passes = 1;
  174279. }
  174280. }
  174281. /*** End of inlined file: jdtrans.c ***/
  174282. /*** Start of inlined file: jfdctflt.c ***/
  174283. #define JPEG_INTERNALS
  174284. #ifdef DCT_FLOAT_SUPPORTED
  174285. /*
  174286. * This module is specialized to the case DCTSIZE = 8.
  174287. */
  174288. #if DCTSIZE != 8
  174289. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174290. #endif
  174291. /*
  174292. * Perform the forward DCT on one block of samples.
  174293. */
  174294. GLOBAL(void)
  174295. jpeg_fdct_float (FAST_FLOAT * data)
  174296. {
  174297. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174298. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174299. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  174300. FAST_FLOAT *dataptr;
  174301. int ctr;
  174302. /* Pass 1: process rows. */
  174303. dataptr = data;
  174304. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174305. tmp0 = dataptr[0] + dataptr[7];
  174306. tmp7 = dataptr[0] - dataptr[7];
  174307. tmp1 = dataptr[1] + dataptr[6];
  174308. tmp6 = dataptr[1] - dataptr[6];
  174309. tmp2 = dataptr[2] + dataptr[5];
  174310. tmp5 = dataptr[2] - dataptr[5];
  174311. tmp3 = dataptr[3] + dataptr[4];
  174312. tmp4 = dataptr[3] - dataptr[4];
  174313. /* Even part */
  174314. tmp10 = tmp0 + tmp3; /* phase 2 */
  174315. tmp13 = tmp0 - tmp3;
  174316. tmp11 = tmp1 + tmp2;
  174317. tmp12 = tmp1 - tmp2;
  174318. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174319. dataptr[4] = tmp10 - tmp11;
  174320. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174321. dataptr[2] = tmp13 + z1; /* phase 5 */
  174322. dataptr[6] = tmp13 - z1;
  174323. /* Odd part */
  174324. tmp10 = tmp4 + tmp5; /* phase 2 */
  174325. tmp11 = tmp5 + tmp6;
  174326. tmp12 = tmp6 + tmp7;
  174327. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174328. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174329. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174330. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174331. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174332. z11 = tmp7 + z3; /* phase 5 */
  174333. z13 = tmp7 - z3;
  174334. dataptr[5] = z13 + z2; /* phase 6 */
  174335. dataptr[3] = z13 - z2;
  174336. dataptr[1] = z11 + z4;
  174337. dataptr[7] = z11 - z4;
  174338. dataptr += DCTSIZE; /* advance pointer to next row */
  174339. }
  174340. /* Pass 2: process columns. */
  174341. dataptr = data;
  174342. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174343. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174344. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174345. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174346. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174347. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174348. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174349. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174350. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174351. /* Even part */
  174352. tmp10 = tmp0 + tmp3; /* phase 2 */
  174353. tmp13 = tmp0 - tmp3;
  174354. tmp11 = tmp1 + tmp2;
  174355. tmp12 = tmp1 - tmp2;
  174356. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174357. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174358. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174359. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174360. dataptr[DCTSIZE*6] = tmp13 - z1;
  174361. /* Odd part */
  174362. tmp10 = tmp4 + tmp5; /* phase 2 */
  174363. tmp11 = tmp5 + tmp6;
  174364. tmp12 = tmp6 + tmp7;
  174365. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174366. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174367. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174368. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174369. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174370. z11 = tmp7 + z3; /* phase 5 */
  174371. z13 = tmp7 - z3;
  174372. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174373. dataptr[DCTSIZE*3] = z13 - z2;
  174374. dataptr[DCTSIZE*1] = z11 + z4;
  174375. dataptr[DCTSIZE*7] = z11 - z4;
  174376. dataptr++; /* advance pointer to next column */
  174377. }
  174378. }
  174379. #endif /* DCT_FLOAT_SUPPORTED */
  174380. /*** End of inlined file: jfdctflt.c ***/
  174381. /*** Start of inlined file: jfdctint.c ***/
  174382. #define JPEG_INTERNALS
  174383. #ifdef DCT_ISLOW_SUPPORTED
  174384. /*
  174385. * This module is specialized to the case DCTSIZE = 8.
  174386. */
  174387. #if DCTSIZE != 8
  174388. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174389. #endif
  174390. /*
  174391. * The poop on this scaling stuff is as follows:
  174392. *
  174393. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  174394. * larger than the true DCT outputs. The final outputs are therefore
  174395. * a factor of N larger than desired; since N=8 this can be cured by
  174396. * a simple right shift at the end of the algorithm. The advantage of
  174397. * this arrangement is that we save two multiplications per 1-D DCT,
  174398. * because the y0 and y4 outputs need not be divided by sqrt(N).
  174399. * In the IJG code, this factor of 8 is removed by the quantization step
  174400. * (in jcdctmgr.c), NOT in this module.
  174401. *
  174402. * We have to do addition and subtraction of the integer inputs, which
  174403. * is no problem, and multiplication by fractional constants, which is
  174404. * a problem to do in integer arithmetic. We multiply all the constants
  174405. * by CONST_SCALE and convert them to integer constants (thus retaining
  174406. * CONST_BITS bits of precision in the constants). After doing a
  174407. * multiplication we have to divide the product by CONST_SCALE, with proper
  174408. * rounding, to produce the correct output. This division can be done
  174409. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  174410. * as long as possible so that partial sums can be added together with
  174411. * full fractional precision.
  174412. *
  174413. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  174414. * they are represented to better-than-integral precision. These outputs
  174415. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  174416. * with the recommended scaling. (For 12-bit sample data, the intermediate
  174417. * array is INT32 anyway.)
  174418. *
  174419. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  174420. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  174421. * shows that the values given below are the most effective.
  174422. */
  174423. #if BITS_IN_JSAMPLE == 8
  174424. #define CONST_BITS 13
  174425. #define PASS1_BITS 2
  174426. #else
  174427. #define CONST_BITS 13
  174428. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174429. #endif
  174430. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174431. * causing a lot of useless floating-point operations at run time.
  174432. * To get around this we use the following pre-calculated constants.
  174433. * If you change CONST_BITS you may want to add appropriate values.
  174434. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174435. */
  174436. #if CONST_BITS == 13
  174437. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  174438. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  174439. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  174440. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174441. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174442. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  174443. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  174444. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174445. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  174446. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  174447. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174448. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  174449. #else
  174450. #define FIX_0_298631336 FIX(0.298631336)
  174451. #define FIX_0_390180644 FIX(0.390180644)
  174452. #define FIX_0_541196100 FIX(0.541196100)
  174453. #define FIX_0_765366865 FIX(0.765366865)
  174454. #define FIX_0_899976223 FIX(0.899976223)
  174455. #define FIX_1_175875602 FIX(1.175875602)
  174456. #define FIX_1_501321110 FIX(1.501321110)
  174457. #define FIX_1_847759065 FIX(1.847759065)
  174458. #define FIX_1_961570560 FIX(1.961570560)
  174459. #define FIX_2_053119869 FIX(2.053119869)
  174460. #define FIX_2_562915447 FIX(2.562915447)
  174461. #define FIX_3_072711026 FIX(3.072711026)
  174462. #endif
  174463. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174464. * For 8-bit samples with the recommended scaling, all the variable
  174465. * and constant values involved are no more than 16 bits wide, so a
  174466. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174467. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174468. */
  174469. #if BITS_IN_JSAMPLE == 8
  174470. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174471. #else
  174472. #define MULTIPLY(var,const) ((var) * (const))
  174473. #endif
  174474. /*
  174475. * Perform the forward DCT on one block of samples.
  174476. */
  174477. GLOBAL(void)
  174478. jpeg_fdct_islow (DCTELEM * data)
  174479. {
  174480. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174481. INT32 tmp10, tmp11, tmp12, tmp13;
  174482. INT32 z1, z2, z3, z4, z5;
  174483. DCTELEM *dataptr;
  174484. int ctr;
  174485. SHIFT_TEMPS
  174486. /* Pass 1: process rows. */
  174487. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  174488. /* furthermore, we scale the results by 2**PASS1_BITS. */
  174489. dataptr = data;
  174490. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174491. tmp0 = dataptr[0] + dataptr[7];
  174492. tmp7 = dataptr[0] - dataptr[7];
  174493. tmp1 = dataptr[1] + dataptr[6];
  174494. tmp6 = dataptr[1] - dataptr[6];
  174495. tmp2 = dataptr[2] + dataptr[5];
  174496. tmp5 = dataptr[2] - dataptr[5];
  174497. tmp3 = dataptr[3] + dataptr[4];
  174498. tmp4 = dataptr[3] - dataptr[4];
  174499. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174500. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174501. */
  174502. tmp10 = tmp0 + tmp3;
  174503. tmp13 = tmp0 - tmp3;
  174504. tmp11 = tmp1 + tmp2;
  174505. tmp12 = tmp1 - tmp2;
  174506. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  174507. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  174508. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174509. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174510. CONST_BITS-PASS1_BITS);
  174511. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174512. CONST_BITS-PASS1_BITS);
  174513. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174514. * cK represents cos(K*pi/16).
  174515. * i0..i3 in the paper are tmp4..tmp7 here.
  174516. */
  174517. z1 = tmp4 + tmp7;
  174518. z2 = tmp5 + tmp6;
  174519. z3 = tmp4 + tmp6;
  174520. z4 = tmp5 + tmp7;
  174521. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174522. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174523. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174524. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174525. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174526. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174527. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174528. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174529. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174530. z3 += z5;
  174531. z4 += z5;
  174532. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  174533. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  174534. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  174535. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  174536. dataptr += DCTSIZE; /* advance pointer to next row */
  174537. }
  174538. /* Pass 2: process columns.
  174539. * We remove the PASS1_BITS scaling, but leave the results scaled up
  174540. * by an overall factor of 8.
  174541. */
  174542. dataptr = data;
  174543. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174544. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174545. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174546. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174547. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174548. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174549. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174550. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174551. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174552. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174553. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174554. */
  174555. tmp10 = tmp0 + tmp3;
  174556. tmp13 = tmp0 - tmp3;
  174557. tmp11 = tmp1 + tmp2;
  174558. tmp12 = tmp1 - tmp2;
  174559. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  174560. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  174561. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174562. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174563. CONST_BITS+PASS1_BITS);
  174564. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174565. CONST_BITS+PASS1_BITS);
  174566. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174567. * cK represents cos(K*pi/16).
  174568. * i0..i3 in the paper are tmp4..tmp7 here.
  174569. */
  174570. z1 = tmp4 + tmp7;
  174571. z2 = tmp5 + tmp6;
  174572. z3 = tmp4 + tmp6;
  174573. z4 = tmp5 + tmp7;
  174574. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174575. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174576. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174577. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174578. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174579. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174580. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174581. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174582. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174583. z3 += z5;
  174584. z4 += z5;
  174585. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  174586. CONST_BITS+PASS1_BITS);
  174587. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  174588. CONST_BITS+PASS1_BITS);
  174589. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  174590. CONST_BITS+PASS1_BITS);
  174591. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  174592. CONST_BITS+PASS1_BITS);
  174593. dataptr++; /* advance pointer to next column */
  174594. }
  174595. }
  174596. #endif /* DCT_ISLOW_SUPPORTED */
  174597. /*** End of inlined file: jfdctint.c ***/
  174598. #undef CONST_BITS
  174599. #undef MULTIPLY
  174600. #undef FIX_0_541196100
  174601. /*** Start of inlined file: jfdctfst.c ***/
  174602. #define JPEG_INTERNALS
  174603. #ifdef DCT_IFAST_SUPPORTED
  174604. /*
  174605. * This module is specialized to the case DCTSIZE = 8.
  174606. */
  174607. #if DCTSIZE != 8
  174608. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174609. #endif
  174610. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174611. * see jfdctint.c for more details. However, we choose to descale
  174612. * (right shift) multiplication products as soon as they are formed,
  174613. * rather than carrying additional fractional bits into subsequent additions.
  174614. * This compromises accuracy slightly, but it lets us save a few shifts.
  174615. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174616. * everywhere except in the multiplications proper; this saves a good deal
  174617. * of work on 16-bit-int machines.
  174618. *
  174619. * Again to save a few shifts, the intermediate results between pass 1 and
  174620. * pass 2 are not upscaled, but are represented only to integral precision.
  174621. *
  174622. * A final compromise is to represent the multiplicative constants to only
  174623. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174624. * machines, and may also reduce the cost of multiplication (since there
  174625. * are fewer one-bits in the constants).
  174626. */
  174627. #define CONST_BITS 8
  174628. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174629. * causing a lot of useless floating-point operations at run time.
  174630. * To get around this we use the following pre-calculated constants.
  174631. * If you change CONST_BITS you may want to add appropriate values.
  174632. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174633. */
  174634. #if CONST_BITS == 8
  174635. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  174636. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  174637. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  174638. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  174639. #else
  174640. #define FIX_0_382683433 FIX(0.382683433)
  174641. #define FIX_0_541196100 FIX(0.541196100)
  174642. #define FIX_0_707106781 FIX(0.707106781)
  174643. #define FIX_1_306562965 FIX(1.306562965)
  174644. #endif
  174645. /* We can gain a little more speed, with a further compromise in accuracy,
  174646. * by omitting the addition in a descaling shift. This yields an incorrectly
  174647. * rounded result half the time...
  174648. */
  174649. #ifndef USE_ACCURATE_ROUNDING
  174650. #undef DESCALE
  174651. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174652. #endif
  174653. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174654. * descale to yield a DCTELEM result.
  174655. */
  174656. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174657. /*
  174658. * Perform the forward DCT on one block of samples.
  174659. */
  174660. GLOBAL(void)
  174661. jpeg_fdct_ifast (DCTELEM * data)
  174662. {
  174663. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174664. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174665. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  174666. DCTELEM *dataptr;
  174667. int ctr;
  174668. SHIFT_TEMPS
  174669. /* Pass 1: process rows. */
  174670. dataptr = data;
  174671. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174672. tmp0 = dataptr[0] + dataptr[7];
  174673. tmp7 = dataptr[0] - dataptr[7];
  174674. tmp1 = dataptr[1] + dataptr[6];
  174675. tmp6 = dataptr[1] - dataptr[6];
  174676. tmp2 = dataptr[2] + dataptr[5];
  174677. tmp5 = dataptr[2] - dataptr[5];
  174678. tmp3 = dataptr[3] + dataptr[4];
  174679. tmp4 = dataptr[3] - dataptr[4];
  174680. /* Even part */
  174681. tmp10 = tmp0 + tmp3; /* phase 2 */
  174682. tmp13 = tmp0 - tmp3;
  174683. tmp11 = tmp1 + tmp2;
  174684. tmp12 = tmp1 - tmp2;
  174685. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174686. dataptr[4] = tmp10 - tmp11;
  174687. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174688. dataptr[2] = tmp13 + z1; /* phase 5 */
  174689. dataptr[6] = tmp13 - z1;
  174690. /* Odd part */
  174691. tmp10 = tmp4 + tmp5; /* phase 2 */
  174692. tmp11 = tmp5 + tmp6;
  174693. tmp12 = tmp6 + tmp7;
  174694. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174695. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174696. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174697. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174698. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174699. z11 = tmp7 + z3; /* phase 5 */
  174700. z13 = tmp7 - z3;
  174701. dataptr[5] = z13 + z2; /* phase 6 */
  174702. dataptr[3] = z13 - z2;
  174703. dataptr[1] = z11 + z4;
  174704. dataptr[7] = z11 - z4;
  174705. dataptr += DCTSIZE; /* advance pointer to next row */
  174706. }
  174707. /* Pass 2: process columns. */
  174708. dataptr = data;
  174709. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174710. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174711. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174712. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174713. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174714. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174715. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174716. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174717. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174718. /* Even part */
  174719. tmp10 = tmp0 + tmp3; /* phase 2 */
  174720. tmp13 = tmp0 - tmp3;
  174721. tmp11 = tmp1 + tmp2;
  174722. tmp12 = tmp1 - tmp2;
  174723. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174724. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174725. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174726. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174727. dataptr[DCTSIZE*6] = tmp13 - z1;
  174728. /* Odd part */
  174729. tmp10 = tmp4 + tmp5; /* phase 2 */
  174730. tmp11 = tmp5 + tmp6;
  174731. tmp12 = tmp6 + tmp7;
  174732. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174733. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174734. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174735. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174736. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174737. z11 = tmp7 + z3; /* phase 5 */
  174738. z13 = tmp7 - z3;
  174739. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174740. dataptr[DCTSIZE*3] = z13 - z2;
  174741. dataptr[DCTSIZE*1] = z11 + z4;
  174742. dataptr[DCTSIZE*7] = z11 - z4;
  174743. dataptr++; /* advance pointer to next column */
  174744. }
  174745. }
  174746. #endif /* DCT_IFAST_SUPPORTED */
  174747. /*** End of inlined file: jfdctfst.c ***/
  174748. #undef FIX_0_541196100
  174749. /*** Start of inlined file: jidctflt.c ***/
  174750. #define JPEG_INTERNALS
  174751. #ifdef DCT_FLOAT_SUPPORTED
  174752. /*
  174753. * This module is specialized to the case DCTSIZE = 8.
  174754. */
  174755. #if DCTSIZE != 8
  174756. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174757. #endif
  174758. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174759. * entry; produce a float result.
  174760. */
  174761. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  174762. /*
  174763. * Perform dequantization and inverse DCT on one block of coefficients.
  174764. */
  174765. GLOBAL(void)
  174766. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174767. JCOEFPTR coef_block,
  174768. JSAMPARRAY output_buf, JDIMENSION output_col)
  174769. {
  174770. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174771. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174772. FAST_FLOAT z5, z10, z11, z12, z13;
  174773. JCOEFPTR inptr;
  174774. FLOAT_MULT_TYPE * quantptr;
  174775. FAST_FLOAT * wsptr;
  174776. JSAMPROW outptr;
  174777. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  174778. int ctr;
  174779. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  174780. SHIFT_TEMPS
  174781. /* Pass 1: process columns from input, store into work array. */
  174782. inptr = coef_block;
  174783. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  174784. wsptr = workspace;
  174785. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  174786. /* Due to quantization, we will usually find that many of the input
  174787. * coefficients are zero, especially the AC terms. We can exploit this
  174788. * by short-circuiting the IDCT calculation for any column in which all
  174789. * the AC terms are zero. In that case each output is equal to the
  174790. * DC coefficient (with scale factor as needed).
  174791. * With typical images and quantization tables, half or more of the
  174792. * column DCT calculations can be simplified this way.
  174793. */
  174794. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  174795. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  174796. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  174797. inptr[DCTSIZE*7] == 0) {
  174798. /* AC terms all zero */
  174799. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174800. wsptr[DCTSIZE*0] = dcval;
  174801. wsptr[DCTSIZE*1] = dcval;
  174802. wsptr[DCTSIZE*2] = dcval;
  174803. wsptr[DCTSIZE*3] = dcval;
  174804. wsptr[DCTSIZE*4] = dcval;
  174805. wsptr[DCTSIZE*5] = dcval;
  174806. wsptr[DCTSIZE*6] = dcval;
  174807. wsptr[DCTSIZE*7] = dcval;
  174808. inptr++; /* advance pointers to next column */
  174809. quantptr++;
  174810. wsptr++;
  174811. continue;
  174812. }
  174813. /* Even part */
  174814. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  174815. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  174816. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  174817. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  174818. tmp10 = tmp0 + tmp2; /* phase 3 */
  174819. tmp11 = tmp0 - tmp2;
  174820. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  174821. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  174822. tmp0 = tmp10 + tmp13; /* phase 2 */
  174823. tmp3 = tmp10 - tmp13;
  174824. tmp1 = tmp11 + tmp12;
  174825. tmp2 = tmp11 - tmp12;
  174826. /* Odd part */
  174827. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  174828. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  174829. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  174830. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  174831. z13 = tmp6 + tmp5; /* phase 6 */
  174832. z10 = tmp6 - tmp5;
  174833. z11 = tmp4 + tmp7;
  174834. z12 = tmp4 - tmp7;
  174835. tmp7 = z11 + z13; /* phase 5 */
  174836. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  174837. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  174838. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174839. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174840. tmp6 = tmp12 - tmp7; /* phase 2 */
  174841. tmp5 = tmp11 - tmp6;
  174842. tmp4 = tmp10 + tmp5;
  174843. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  174844. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  174845. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  174846. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  174847. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  174848. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  174849. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  174850. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  174851. inptr++; /* advance pointers to next column */
  174852. quantptr++;
  174853. wsptr++;
  174854. }
  174855. /* Pass 2: process rows from work array, store into output array. */
  174856. /* Note that we must descale the results by a factor of 8 == 2**3. */
  174857. wsptr = workspace;
  174858. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  174859. outptr = output_buf[ctr] + output_col;
  174860. /* Rows of zeroes can be exploited in the same way as we did with columns.
  174861. * However, the column calculation has created many nonzero AC terms, so
  174862. * the simplification applies less often (typically 5% to 10% of the time).
  174863. * And testing floats for zero is relatively expensive, so we don't bother.
  174864. */
  174865. /* Even part */
  174866. tmp10 = wsptr[0] + wsptr[4];
  174867. tmp11 = wsptr[0] - wsptr[4];
  174868. tmp13 = wsptr[2] + wsptr[6];
  174869. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  174870. tmp0 = tmp10 + tmp13;
  174871. tmp3 = tmp10 - tmp13;
  174872. tmp1 = tmp11 + tmp12;
  174873. tmp2 = tmp11 - tmp12;
  174874. /* Odd part */
  174875. z13 = wsptr[5] + wsptr[3];
  174876. z10 = wsptr[5] - wsptr[3];
  174877. z11 = wsptr[1] + wsptr[7];
  174878. z12 = wsptr[1] - wsptr[7];
  174879. tmp7 = z11 + z13;
  174880. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  174881. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  174882. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  174883. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  174884. tmp6 = tmp12 - tmp7;
  174885. tmp5 = tmp11 - tmp6;
  174886. tmp4 = tmp10 + tmp5;
  174887. /* Final output stage: scale down by a factor of 8 and range-limit */
  174888. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  174889. & RANGE_MASK];
  174890. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  174891. & RANGE_MASK];
  174892. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  174893. & RANGE_MASK];
  174894. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  174895. & RANGE_MASK];
  174896. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  174897. & RANGE_MASK];
  174898. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  174899. & RANGE_MASK];
  174900. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  174901. & RANGE_MASK];
  174902. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  174903. & RANGE_MASK];
  174904. wsptr += DCTSIZE; /* advance pointer to next row */
  174905. }
  174906. }
  174907. #endif /* DCT_FLOAT_SUPPORTED */
  174908. /*** End of inlined file: jidctflt.c ***/
  174909. #undef CONST_BITS
  174910. #undef FIX_1_847759065
  174911. #undef MULTIPLY
  174912. #undef DEQUANTIZE
  174913. #undef DESCALE
  174914. /*** Start of inlined file: jidctfst.c ***/
  174915. #define JPEG_INTERNALS
  174916. #ifdef DCT_IFAST_SUPPORTED
  174917. /*
  174918. * This module is specialized to the case DCTSIZE = 8.
  174919. */
  174920. #if DCTSIZE != 8
  174921. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174922. #endif
  174923. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174924. * see jidctint.c for more details. However, we choose to descale
  174925. * (right shift) multiplication products as soon as they are formed,
  174926. * rather than carrying additional fractional bits into subsequent additions.
  174927. * This compromises accuracy slightly, but it lets us save a few shifts.
  174928. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174929. * everywhere except in the multiplications proper; this saves a good deal
  174930. * of work on 16-bit-int machines.
  174931. *
  174932. * The dequantized coefficients are not integers because the AA&N scaling
  174933. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  174934. * so that the first and second IDCT rounds have the same input scaling.
  174935. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  174936. * avoid a descaling shift; this compromises accuracy rather drastically
  174937. * for small quantization table entries, but it saves a lot of shifts.
  174938. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  174939. * so we use a much larger scaling factor to preserve accuracy.
  174940. *
  174941. * A final compromise is to represent the multiplicative constants to only
  174942. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174943. * machines, and may also reduce the cost of multiplication (since there
  174944. * are fewer one-bits in the constants).
  174945. */
  174946. #if BITS_IN_JSAMPLE == 8
  174947. #define CONST_BITS 8
  174948. #define PASS1_BITS 2
  174949. #else
  174950. #define CONST_BITS 8
  174951. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174952. #endif
  174953. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174954. * causing a lot of useless floating-point operations at run time.
  174955. * To get around this we use the following pre-calculated constants.
  174956. * If you change CONST_BITS you may want to add appropriate values.
  174957. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174958. */
  174959. #if CONST_BITS == 8
  174960. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  174961. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  174962. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  174963. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  174964. #else
  174965. #define FIX_1_082392200 FIX(1.082392200)
  174966. #define FIX_1_414213562 FIX(1.414213562)
  174967. #define FIX_1_847759065 FIX(1.847759065)
  174968. #define FIX_2_613125930 FIX(2.613125930)
  174969. #endif
  174970. /* We can gain a little more speed, with a further compromise in accuracy,
  174971. * by omitting the addition in a descaling shift. This yields an incorrectly
  174972. * rounded result half the time...
  174973. */
  174974. #ifndef USE_ACCURATE_ROUNDING
  174975. #undef DESCALE
  174976. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174977. #endif
  174978. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174979. * descale to yield a DCTELEM result.
  174980. */
  174981. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174982. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174983. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  174984. * multiplication will do. For 12-bit data, the multiplier table is
  174985. * declared INT32, so a 32-bit multiply will be used.
  174986. */
  174987. #if BITS_IN_JSAMPLE == 8
  174988. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  174989. #else
  174990. #define DEQUANTIZE(coef,quantval) \
  174991. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  174992. #endif
  174993. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  174994. * We assume that int right shift is unsigned if INT32 right shift is.
  174995. */
  174996. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  174997. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  174998. #if BITS_IN_JSAMPLE == 8
  174999. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  175000. #else
  175001. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  175002. #endif
  175003. #define IRIGHT_SHIFT(x,shft) \
  175004. ((ishift_temp = (x)) < 0 ? \
  175005. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  175006. (ishift_temp >> (shft)))
  175007. #else
  175008. #define ISHIFT_TEMPS
  175009. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  175010. #endif
  175011. #ifdef USE_ACCURATE_ROUNDING
  175012. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  175013. #else
  175014. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  175015. #endif
  175016. /*
  175017. * Perform dequantization and inverse DCT on one block of coefficients.
  175018. */
  175019. GLOBAL(void)
  175020. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175021. JCOEFPTR coef_block,
  175022. JSAMPARRAY output_buf, JDIMENSION output_col)
  175023. {
  175024. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  175025. DCTELEM tmp10, tmp11, tmp12, tmp13;
  175026. DCTELEM z5, z10, z11, z12, z13;
  175027. JCOEFPTR inptr;
  175028. IFAST_MULT_TYPE * quantptr;
  175029. int * wsptr;
  175030. JSAMPROW outptr;
  175031. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175032. int ctr;
  175033. int workspace[DCTSIZE2]; /* buffers data between passes */
  175034. SHIFT_TEMPS /* for DESCALE */
  175035. ISHIFT_TEMPS /* for IDESCALE */
  175036. /* Pass 1: process columns from input, store into work array. */
  175037. inptr = coef_block;
  175038. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  175039. wsptr = workspace;
  175040. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  175041. /* Due to quantization, we will usually find that many of the input
  175042. * coefficients are zero, especially the AC terms. We can exploit this
  175043. * by short-circuiting the IDCT calculation for any column in which all
  175044. * the AC terms are zero. In that case each output is equal to the
  175045. * DC coefficient (with scale factor as needed).
  175046. * With typical images and quantization tables, half or more of the
  175047. * column DCT calculations can be simplified this way.
  175048. */
  175049. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175050. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  175051. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  175052. inptr[DCTSIZE*7] == 0) {
  175053. /* AC terms all zero */
  175054. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175055. wsptr[DCTSIZE*0] = dcval;
  175056. wsptr[DCTSIZE*1] = dcval;
  175057. wsptr[DCTSIZE*2] = dcval;
  175058. wsptr[DCTSIZE*3] = dcval;
  175059. wsptr[DCTSIZE*4] = dcval;
  175060. wsptr[DCTSIZE*5] = dcval;
  175061. wsptr[DCTSIZE*6] = dcval;
  175062. wsptr[DCTSIZE*7] = dcval;
  175063. inptr++; /* advance pointers to next column */
  175064. quantptr++;
  175065. wsptr++;
  175066. continue;
  175067. }
  175068. /* Even part */
  175069. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175070. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175071. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175072. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175073. tmp10 = tmp0 + tmp2; /* phase 3 */
  175074. tmp11 = tmp0 - tmp2;
  175075. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  175076. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  175077. tmp0 = tmp10 + tmp13; /* phase 2 */
  175078. tmp3 = tmp10 - tmp13;
  175079. tmp1 = tmp11 + tmp12;
  175080. tmp2 = tmp11 - tmp12;
  175081. /* Odd part */
  175082. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175083. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175084. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175085. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175086. z13 = tmp6 + tmp5; /* phase 6 */
  175087. z10 = tmp6 - tmp5;
  175088. z11 = tmp4 + tmp7;
  175089. z12 = tmp4 - tmp7;
  175090. tmp7 = z11 + z13; /* phase 5 */
  175091. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  175092. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  175093. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  175094. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  175095. tmp6 = tmp12 - tmp7; /* phase 2 */
  175096. tmp5 = tmp11 - tmp6;
  175097. tmp4 = tmp10 + tmp5;
  175098. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  175099. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  175100. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  175101. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  175102. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  175103. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  175104. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  175105. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  175106. inptr++; /* advance pointers to next column */
  175107. quantptr++;
  175108. wsptr++;
  175109. }
  175110. /* Pass 2: process rows from work array, store into output array. */
  175111. /* Note that we must descale the results by a factor of 8 == 2**3, */
  175112. /* and also undo the PASS1_BITS scaling. */
  175113. wsptr = workspace;
  175114. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175115. outptr = output_buf[ctr] + output_col;
  175116. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175117. * However, the column calculation has created many nonzero AC terms, so
  175118. * the simplification applies less often (typically 5% to 10% of the time).
  175119. * On machines with very fast multiplication, it's possible that the
  175120. * test takes more time than it's worth. In that case this section
  175121. * may be commented out.
  175122. */
  175123. #ifndef NO_ZERO_ROW_TEST
  175124. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  175125. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175126. /* AC terms all zero */
  175127. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  175128. & RANGE_MASK];
  175129. outptr[0] = dcval;
  175130. outptr[1] = dcval;
  175131. outptr[2] = dcval;
  175132. outptr[3] = dcval;
  175133. outptr[4] = dcval;
  175134. outptr[5] = dcval;
  175135. outptr[6] = dcval;
  175136. outptr[7] = dcval;
  175137. wsptr += DCTSIZE; /* advance pointer to next row */
  175138. continue;
  175139. }
  175140. #endif
  175141. /* Even part */
  175142. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  175143. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  175144. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  175145. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  175146. - tmp13;
  175147. tmp0 = tmp10 + tmp13;
  175148. tmp3 = tmp10 - tmp13;
  175149. tmp1 = tmp11 + tmp12;
  175150. tmp2 = tmp11 - tmp12;
  175151. /* Odd part */
  175152. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  175153. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  175154. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  175155. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  175156. tmp7 = z11 + z13; /* phase 5 */
  175157. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  175158. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  175159. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  175160. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  175161. tmp6 = tmp12 - tmp7; /* phase 2 */
  175162. tmp5 = tmp11 - tmp6;
  175163. tmp4 = tmp10 + tmp5;
  175164. /* Final output stage: scale down by a factor of 8 and range-limit */
  175165. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  175166. & RANGE_MASK];
  175167. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  175168. & RANGE_MASK];
  175169. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  175170. & RANGE_MASK];
  175171. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  175172. & RANGE_MASK];
  175173. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  175174. & RANGE_MASK];
  175175. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  175176. & RANGE_MASK];
  175177. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  175178. & RANGE_MASK];
  175179. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  175180. & RANGE_MASK];
  175181. wsptr += DCTSIZE; /* advance pointer to next row */
  175182. }
  175183. }
  175184. #endif /* DCT_IFAST_SUPPORTED */
  175185. /*** End of inlined file: jidctfst.c ***/
  175186. #undef CONST_BITS
  175187. #undef FIX_1_847759065
  175188. #undef MULTIPLY
  175189. #undef DEQUANTIZE
  175190. /*** Start of inlined file: jidctint.c ***/
  175191. #define JPEG_INTERNALS
  175192. #ifdef DCT_ISLOW_SUPPORTED
  175193. /*
  175194. * This module is specialized to the case DCTSIZE = 8.
  175195. */
  175196. #if DCTSIZE != 8
  175197. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175198. #endif
  175199. /*
  175200. * The poop on this scaling stuff is as follows:
  175201. *
  175202. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  175203. * larger than the true IDCT outputs. The final outputs are therefore
  175204. * a factor of N larger than desired; since N=8 this can be cured by
  175205. * a simple right shift at the end of the algorithm. The advantage of
  175206. * this arrangement is that we save two multiplications per 1-D IDCT,
  175207. * because the y0 and y4 inputs need not be divided by sqrt(N).
  175208. *
  175209. * We have to do addition and subtraction of the integer inputs, which
  175210. * is no problem, and multiplication by fractional constants, which is
  175211. * a problem to do in integer arithmetic. We multiply all the constants
  175212. * by CONST_SCALE and convert them to integer constants (thus retaining
  175213. * CONST_BITS bits of precision in the constants). After doing a
  175214. * multiplication we have to divide the product by CONST_SCALE, with proper
  175215. * rounding, to produce the correct output. This division can be done
  175216. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  175217. * as long as possible so that partial sums can be added together with
  175218. * full fractional precision.
  175219. *
  175220. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  175221. * they are represented to better-than-integral precision. These outputs
  175222. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  175223. * with the recommended scaling. (To scale up 12-bit sample data further, an
  175224. * intermediate INT32 array would be needed.)
  175225. *
  175226. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  175227. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  175228. * shows that the values given below are the most effective.
  175229. */
  175230. #if BITS_IN_JSAMPLE == 8
  175231. #define CONST_BITS 13
  175232. #define PASS1_BITS 2
  175233. #else
  175234. #define CONST_BITS 13
  175235. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175236. #endif
  175237. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175238. * causing a lot of useless floating-point operations at run time.
  175239. * To get around this we use the following pre-calculated constants.
  175240. * If you change CONST_BITS you may want to add appropriate values.
  175241. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175242. */
  175243. #if CONST_BITS == 13
  175244. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  175245. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  175246. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  175247. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175248. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175249. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  175250. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  175251. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175252. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  175253. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  175254. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175255. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  175256. #else
  175257. #define FIX_0_298631336 FIX(0.298631336)
  175258. #define FIX_0_390180644 FIX(0.390180644)
  175259. #define FIX_0_541196100 FIX(0.541196100)
  175260. #define FIX_0_765366865 FIX(0.765366865)
  175261. #define FIX_0_899976223 FIX(0.899976223)
  175262. #define FIX_1_175875602 FIX(1.175875602)
  175263. #define FIX_1_501321110 FIX(1.501321110)
  175264. #define FIX_1_847759065 FIX(1.847759065)
  175265. #define FIX_1_961570560 FIX(1.961570560)
  175266. #define FIX_2_053119869 FIX(2.053119869)
  175267. #define FIX_2_562915447 FIX(2.562915447)
  175268. #define FIX_3_072711026 FIX(3.072711026)
  175269. #endif
  175270. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175271. * For 8-bit samples with the recommended scaling, all the variable
  175272. * and constant values involved are no more than 16 bits wide, so a
  175273. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175274. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175275. */
  175276. #if BITS_IN_JSAMPLE == 8
  175277. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175278. #else
  175279. #define MULTIPLY(var,const) ((var) * (const))
  175280. #endif
  175281. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175282. * entry; produce an int result. In this module, both inputs and result
  175283. * are 16 bits or less, so either int or short multiply will work.
  175284. */
  175285. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175286. /*
  175287. * Perform dequantization and inverse DCT on one block of coefficients.
  175288. */
  175289. GLOBAL(void)
  175290. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175291. JCOEFPTR coef_block,
  175292. JSAMPARRAY output_buf, JDIMENSION output_col)
  175293. {
  175294. INT32 tmp0, tmp1, tmp2, tmp3;
  175295. INT32 tmp10, tmp11, tmp12, tmp13;
  175296. INT32 z1, z2, z3, z4, z5;
  175297. JCOEFPTR inptr;
  175298. ISLOW_MULT_TYPE * quantptr;
  175299. int * wsptr;
  175300. JSAMPROW outptr;
  175301. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175302. int ctr;
  175303. int workspace[DCTSIZE2]; /* buffers data between passes */
  175304. SHIFT_TEMPS
  175305. /* Pass 1: process columns from input, store into work array. */
  175306. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  175307. /* furthermore, we scale the results by 2**PASS1_BITS. */
  175308. inptr = coef_block;
  175309. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175310. wsptr = workspace;
  175311. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  175312. /* Due to quantization, we will usually find that many of the input
  175313. * coefficients are zero, especially the AC terms. We can exploit this
  175314. * by short-circuiting the IDCT calculation for any column in which all
  175315. * the AC terms are zero. In that case each output is equal to the
  175316. * DC coefficient (with scale factor as needed).
  175317. * With typical images and quantization tables, half or more of the
  175318. * column DCT calculations can be simplified this way.
  175319. */
  175320. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175321. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  175322. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  175323. inptr[DCTSIZE*7] == 0) {
  175324. /* AC terms all zero */
  175325. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175326. wsptr[DCTSIZE*0] = dcval;
  175327. wsptr[DCTSIZE*1] = dcval;
  175328. wsptr[DCTSIZE*2] = dcval;
  175329. wsptr[DCTSIZE*3] = dcval;
  175330. wsptr[DCTSIZE*4] = dcval;
  175331. wsptr[DCTSIZE*5] = dcval;
  175332. wsptr[DCTSIZE*6] = dcval;
  175333. wsptr[DCTSIZE*7] = dcval;
  175334. inptr++; /* advance pointers to next column */
  175335. quantptr++;
  175336. wsptr++;
  175337. continue;
  175338. }
  175339. /* Even part: reverse the even part of the forward DCT. */
  175340. /* The rotator is sqrt(2)*c(-6). */
  175341. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175342. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175343. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175344. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175345. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175346. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175347. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175348. tmp0 = (z2 + z3) << CONST_BITS;
  175349. tmp1 = (z2 - z3) << CONST_BITS;
  175350. tmp10 = tmp0 + tmp3;
  175351. tmp13 = tmp0 - tmp3;
  175352. tmp11 = tmp1 + tmp2;
  175353. tmp12 = tmp1 - tmp2;
  175354. /* Odd part per figure 8; the matrix is unitary and hence its
  175355. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175356. */
  175357. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175358. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175359. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175360. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175361. z1 = tmp0 + tmp3;
  175362. z2 = tmp1 + tmp2;
  175363. z3 = tmp0 + tmp2;
  175364. z4 = tmp1 + tmp3;
  175365. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175366. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175367. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175368. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175369. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175370. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175371. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175372. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175373. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175374. z3 += z5;
  175375. z4 += z5;
  175376. tmp0 += z1 + z3;
  175377. tmp1 += z2 + z4;
  175378. tmp2 += z2 + z3;
  175379. tmp3 += z1 + z4;
  175380. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175381. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  175382. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  175383. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  175384. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  175385. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  175386. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  175387. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  175388. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  175389. inptr++; /* advance pointers to next column */
  175390. quantptr++;
  175391. wsptr++;
  175392. }
  175393. /* Pass 2: process rows from work array, store into output array. */
  175394. /* Note that we must descale the results by a factor of 8 == 2**3, */
  175395. /* and also undo the PASS1_BITS scaling. */
  175396. wsptr = workspace;
  175397. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175398. outptr = output_buf[ctr] + output_col;
  175399. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175400. * However, the column calculation has created many nonzero AC terms, so
  175401. * the simplification applies less often (typically 5% to 10% of the time).
  175402. * On machines with very fast multiplication, it's possible that the
  175403. * test takes more time than it's worth. In that case this section
  175404. * may be commented out.
  175405. */
  175406. #ifndef NO_ZERO_ROW_TEST
  175407. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  175408. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175409. /* AC terms all zero */
  175410. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175411. & RANGE_MASK];
  175412. outptr[0] = dcval;
  175413. outptr[1] = dcval;
  175414. outptr[2] = dcval;
  175415. outptr[3] = dcval;
  175416. outptr[4] = dcval;
  175417. outptr[5] = dcval;
  175418. outptr[6] = dcval;
  175419. outptr[7] = dcval;
  175420. wsptr += DCTSIZE; /* advance pointer to next row */
  175421. continue;
  175422. }
  175423. #endif
  175424. /* Even part: reverse the even part of the forward DCT. */
  175425. /* The rotator is sqrt(2)*c(-6). */
  175426. z2 = (INT32) wsptr[2];
  175427. z3 = (INT32) wsptr[6];
  175428. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175429. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175430. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175431. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  175432. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  175433. tmp10 = tmp0 + tmp3;
  175434. tmp13 = tmp0 - tmp3;
  175435. tmp11 = tmp1 + tmp2;
  175436. tmp12 = tmp1 - tmp2;
  175437. /* Odd part per figure 8; the matrix is unitary and hence its
  175438. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175439. */
  175440. tmp0 = (INT32) wsptr[7];
  175441. tmp1 = (INT32) wsptr[5];
  175442. tmp2 = (INT32) wsptr[3];
  175443. tmp3 = (INT32) wsptr[1];
  175444. z1 = tmp0 + tmp3;
  175445. z2 = tmp1 + tmp2;
  175446. z3 = tmp0 + tmp2;
  175447. z4 = tmp1 + tmp3;
  175448. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175449. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175450. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175451. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175452. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175453. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175454. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175455. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175456. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175457. z3 += z5;
  175458. z4 += z5;
  175459. tmp0 += z1 + z3;
  175460. tmp1 += z2 + z4;
  175461. tmp2 += z2 + z3;
  175462. tmp3 += z1 + z4;
  175463. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175464. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  175465. CONST_BITS+PASS1_BITS+3)
  175466. & RANGE_MASK];
  175467. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  175468. CONST_BITS+PASS1_BITS+3)
  175469. & RANGE_MASK];
  175470. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  175471. CONST_BITS+PASS1_BITS+3)
  175472. & RANGE_MASK];
  175473. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  175474. CONST_BITS+PASS1_BITS+3)
  175475. & RANGE_MASK];
  175476. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  175477. CONST_BITS+PASS1_BITS+3)
  175478. & RANGE_MASK];
  175479. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  175480. CONST_BITS+PASS1_BITS+3)
  175481. & RANGE_MASK];
  175482. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  175483. CONST_BITS+PASS1_BITS+3)
  175484. & RANGE_MASK];
  175485. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  175486. CONST_BITS+PASS1_BITS+3)
  175487. & RANGE_MASK];
  175488. wsptr += DCTSIZE; /* advance pointer to next row */
  175489. }
  175490. }
  175491. #endif /* DCT_ISLOW_SUPPORTED */
  175492. /*** End of inlined file: jidctint.c ***/
  175493. /*** Start of inlined file: jidctred.c ***/
  175494. #define JPEG_INTERNALS
  175495. #ifdef IDCT_SCALING_SUPPORTED
  175496. /*
  175497. * This module is specialized to the case DCTSIZE = 8.
  175498. */
  175499. #if DCTSIZE != 8
  175500. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175501. #endif
  175502. /* Scaling is the same as in jidctint.c. */
  175503. #if BITS_IN_JSAMPLE == 8
  175504. #define CONST_BITS 13
  175505. #define PASS1_BITS 2
  175506. #else
  175507. #define CONST_BITS 13
  175508. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175509. #endif
  175510. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175511. * causing a lot of useless floating-point operations at run time.
  175512. * To get around this we use the following pre-calculated constants.
  175513. * If you change CONST_BITS you may want to add appropriate values.
  175514. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175515. */
  175516. #if CONST_BITS == 13
  175517. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  175518. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  175519. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  175520. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  175521. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175522. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  175523. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175524. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  175525. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  175526. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  175527. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175528. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  175529. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175530. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  175531. #else
  175532. #define FIX_0_211164243 FIX(0.211164243)
  175533. #define FIX_0_509795579 FIX(0.509795579)
  175534. #define FIX_0_601344887 FIX(0.601344887)
  175535. #define FIX_0_720959822 FIX(0.720959822)
  175536. #define FIX_0_765366865 FIX(0.765366865)
  175537. #define FIX_0_850430095 FIX(0.850430095)
  175538. #define FIX_0_899976223 FIX(0.899976223)
  175539. #define FIX_1_061594337 FIX(1.061594337)
  175540. #define FIX_1_272758580 FIX(1.272758580)
  175541. #define FIX_1_451774981 FIX(1.451774981)
  175542. #define FIX_1_847759065 FIX(1.847759065)
  175543. #define FIX_2_172734803 FIX(2.172734803)
  175544. #define FIX_2_562915447 FIX(2.562915447)
  175545. #define FIX_3_624509785 FIX(3.624509785)
  175546. #endif
  175547. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175548. * For 8-bit samples with the recommended scaling, all the variable
  175549. * and constant values involved are no more than 16 bits wide, so a
  175550. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175551. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175552. */
  175553. #if BITS_IN_JSAMPLE == 8
  175554. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175555. #else
  175556. #define MULTIPLY(var,const) ((var) * (const))
  175557. #endif
  175558. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175559. * entry; produce an int result. In this module, both inputs and result
  175560. * are 16 bits or less, so either int or short multiply will work.
  175561. */
  175562. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175563. /*
  175564. * Perform dequantization and inverse DCT on one block of coefficients,
  175565. * producing a reduced-size 4x4 output block.
  175566. */
  175567. GLOBAL(void)
  175568. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175569. JCOEFPTR coef_block,
  175570. JSAMPARRAY output_buf, JDIMENSION output_col)
  175571. {
  175572. INT32 tmp0, tmp2, tmp10, tmp12;
  175573. INT32 z1, z2, z3, z4;
  175574. JCOEFPTR inptr;
  175575. ISLOW_MULT_TYPE * quantptr;
  175576. int * wsptr;
  175577. JSAMPROW outptr;
  175578. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175579. int ctr;
  175580. int workspace[DCTSIZE*4]; /* buffers data between passes */
  175581. SHIFT_TEMPS
  175582. /* Pass 1: process columns from input, store into work array. */
  175583. inptr = coef_block;
  175584. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175585. wsptr = workspace;
  175586. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175587. /* Don't bother to process column 4, because second pass won't use it */
  175588. if (ctr == DCTSIZE-4)
  175589. continue;
  175590. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175591. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  175592. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  175593. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  175594. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175595. wsptr[DCTSIZE*0] = dcval;
  175596. wsptr[DCTSIZE*1] = dcval;
  175597. wsptr[DCTSIZE*2] = dcval;
  175598. wsptr[DCTSIZE*3] = dcval;
  175599. continue;
  175600. }
  175601. /* Even part */
  175602. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175603. tmp0 <<= (CONST_BITS+1);
  175604. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175605. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175606. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  175607. tmp10 = tmp0 + tmp2;
  175608. tmp12 = tmp0 - tmp2;
  175609. /* Odd part */
  175610. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175611. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175612. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175613. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175614. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175615. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175616. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175617. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175618. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175619. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175620. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175621. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175622. /* Final output stage */
  175623. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  175624. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  175625. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  175626. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  175627. }
  175628. /* Pass 2: process 4 rows from work array, store into output array. */
  175629. wsptr = workspace;
  175630. for (ctr = 0; ctr < 4; ctr++) {
  175631. outptr = output_buf[ctr] + output_col;
  175632. /* It's not clear whether a zero row test is worthwhile here ... */
  175633. #ifndef NO_ZERO_ROW_TEST
  175634. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  175635. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175636. /* AC terms all zero */
  175637. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175638. & RANGE_MASK];
  175639. outptr[0] = dcval;
  175640. outptr[1] = dcval;
  175641. outptr[2] = dcval;
  175642. outptr[3] = dcval;
  175643. wsptr += DCTSIZE; /* advance pointer to next row */
  175644. continue;
  175645. }
  175646. #endif
  175647. /* Even part */
  175648. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  175649. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  175650. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  175651. tmp10 = tmp0 + tmp2;
  175652. tmp12 = tmp0 - tmp2;
  175653. /* Odd part */
  175654. z1 = (INT32) wsptr[7];
  175655. z2 = (INT32) wsptr[5];
  175656. z3 = (INT32) wsptr[3];
  175657. z4 = (INT32) wsptr[1];
  175658. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175659. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175660. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175661. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175662. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175663. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175664. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175665. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175666. /* Final output stage */
  175667. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  175668. CONST_BITS+PASS1_BITS+3+1)
  175669. & RANGE_MASK];
  175670. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  175671. CONST_BITS+PASS1_BITS+3+1)
  175672. & RANGE_MASK];
  175673. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  175674. CONST_BITS+PASS1_BITS+3+1)
  175675. & RANGE_MASK];
  175676. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  175677. CONST_BITS+PASS1_BITS+3+1)
  175678. & RANGE_MASK];
  175679. wsptr += DCTSIZE; /* advance pointer to next row */
  175680. }
  175681. }
  175682. /*
  175683. * Perform dequantization and inverse DCT on one block of coefficients,
  175684. * producing a reduced-size 2x2 output block.
  175685. */
  175686. GLOBAL(void)
  175687. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175688. JCOEFPTR coef_block,
  175689. JSAMPARRAY output_buf, JDIMENSION output_col)
  175690. {
  175691. INT32 tmp0, tmp10, z1;
  175692. JCOEFPTR inptr;
  175693. ISLOW_MULT_TYPE * quantptr;
  175694. int * wsptr;
  175695. JSAMPROW outptr;
  175696. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175697. int ctr;
  175698. int workspace[DCTSIZE*2]; /* buffers data between passes */
  175699. SHIFT_TEMPS
  175700. /* Pass 1: process columns from input, store into work array. */
  175701. inptr = coef_block;
  175702. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175703. wsptr = workspace;
  175704. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175705. /* Don't bother to process columns 2,4,6 */
  175706. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  175707. continue;
  175708. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  175709. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  175710. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  175711. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175712. wsptr[DCTSIZE*0] = dcval;
  175713. wsptr[DCTSIZE*1] = dcval;
  175714. continue;
  175715. }
  175716. /* Even part */
  175717. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175718. tmp10 = z1 << (CONST_BITS+2);
  175719. /* Odd part */
  175720. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175721. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  175722. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175723. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  175724. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175725. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  175726. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175727. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175728. /* Final output stage */
  175729. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  175730. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  175731. }
  175732. /* Pass 2: process 2 rows from work array, store into output array. */
  175733. wsptr = workspace;
  175734. for (ctr = 0; ctr < 2; ctr++) {
  175735. outptr = output_buf[ctr] + output_col;
  175736. /* It's not clear whether a zero row test is worthwhile here ... */
  175737. #ifndef NO_ZERO_ROW_TEST
  175738. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  175739. /* AC terms all zero */
  175740. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175741. & RANGE_MASK];
  175742. outptr[0] = dcval;
  175743. outptr[1] = dcval;
  175744. wsptr += DCTSIZE; /* advance pointer to next row */
  175745. continue;
  175746. }
  175747. #endif
  175748. /* Even part */
  175749. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  175750. /* Odd part */
  175751. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  175752. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  175753. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  175754. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175755. /* Final output stage */
  175756. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  175757. CONST_BITS+PASS1_BITS+3+2)
  175758. & RANGE_MASK];
  175759. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  175760. CONST_BITS+PASS1_BITS+3+2)
  175761. & RANGE_MASK];
  175762. wsptr += DCTSIZE; /* advance pointer to next row */
  175763. }
  175764. }
  175765. /*
  175766. * Perform dequantization and inverse DCT on one block of coefficients,
  175767. * producing a reduced-size 1x1 output block.
  175768. */
  175769. GLOBAL(void)
  175770. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175771. JCOEFPTR coef_block,
  175772. JSAMPARRAY output_buf, JDIMENSION output_col)
  175773. {
  175774. int dcval;
  175775. ISLOW_MULT_TYPE * quantptr;
  175776. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175777. SHIFT_TEMPS
  175778. /* We hardly need an inverse DCT routine for this: just take the
  175779. * average pixel value, which is one-eighth of the DC coefficient.
  175780. */
  175781. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175782. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  175783. dcval = (int) DESCALE((INT32) dcval, 3);
  175784. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  175785. }
  175786. #endif /* IDCT_SCALING_SUPPORTED */
  175787. /*** End of inlined file: jidctred.c ***/
  175788. /*** Start of inlined file: jmemmgr.c ***/
  175789. #define JPEG_INTERNALS
  175790. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  175791. /*** Start of inlined file: jmemsys.h ***/
  175792. #ifndef __jmemsys_h__
  175793. #define __jmemsys_h__
  175794. /* Short forms of external names for systems with brain-damaged linkers. */
  175795. #ifdef NEED_SHORT_EXTERNAL_NAMES
  175796. #define jpeg_get_small jGetSmall
  175797. #define jpeg_free_small jFreeSmall
  175798. #define jpeg_get_large jGetLarge
  175799. #define jpeg_free_large jFreeLarge
  175800. #define jpeg_mem_available jMemAvail
  175801. #define jpeg_open_backing_store jOpenBackStore
  175802. #define jpeg_mem_init jMemInit
  175803. #define jpeg_mem_term jMemTerm
  175804. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  175805. /*
  175806. * These two functions are used to allocate and release small chunks of
  175807. * memory. (Typically the total amount requested through jpeg_get_small is
  175808. * no more than 20K or so; this will be requested in chunks of a few K each.)
  175809. * Behavior should be the same as for the standard library functions malloc
  175810. * and free; in particular, jpeg_get_small must return NULL on failure.
  175811. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  175812. * size of the object being freed, just in case it's needed.
  175813. * On an 80x86 machine using small-data memory model, these manage near heap.
  175814. */
  175815. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  175816. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  175817. size_t sizeofobject));
  175818. /*
  175819. * These two functions are used to allocate and release large chunks of
  175820. * memory (up to the total free space designated by jpeg_mem_available).
  175821. * The interface is the same as above, except that on an 80x86 machine,
  175822. * far pointers are used. On most other machines these are identical to
  175823. * the jpeg_get/free_small routines; but we keep them separate anyway,
  175824. * in case a different allocation strategy is desirable for large chunks.
  175825. */
  175826. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  175827. size_t sizeofobject));
  175828. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  175829. size_t sizeofobject));
  175830. /*
  175831. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  175832. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  175833. * matter, but that case should never come into play). This macro is needed
  175834. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  175835. * On those machines, we expect that jconfig.h will provide a proper value.
  175836. * On machines with 32-bit flat address spaces, any large constant may be used.
  175837. *
  175838. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  175839. * size_t and will be a multiple of sizeof(align_type).
  175840. */
  175841. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  175842. #define MAX_ALLOC_CHUNK 1000000000L
  175843. #endif
  175844. /*
  175845. * This routine computes the total space still available for allocation by
  175846. * jpeg_get_large. If more space than this is needed, backing store will be
  175847. * used. NOTE: any memory already allocated must not be counted.
  175848. *
  175849. * There is a minimum space requirement, corresponding to the minimum
  175850. * feasible buffer sizes; jmemmgr.c will request that much space even if
  175851. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  175852. * all working storage in memory, is also passed in case it is useful.
  175853. * Finally, the total space already allocated is passed. If no better
  175854. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  175855. * is often a suitable calculation.
  175856. *
  175857. * It is OK for jpeg_mem_available to underestimate the space available
  175858. * (that'll just lead to more backing-store access than is really necessary).
  175859. * However, an overestimate will lead to failure. Hence it's wise to subtract
  175860. * a slop factor from the true available space. 5% should be enough.
  175861. *
  175862. * On machines with lots of virtual memory, any large constant may be returned.
  175863. * Conversely, zero may be returned to always use the minimum amount of memory.
  175864. */
  175865. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  175866. long min_bytes_needed,
  175867. long max_bytes_needed,
  175868. long already_allocated));
  175869. /*
  175870. * This structure holds whatever state is needed to access a single
  175871. * backing-store object. The read/write/close method pointers are called
  175872. * by jmemmgr.c to manipulate the backing-store object; all other fields
  175873. * are private to the system-dependent backing store routines.
  175874. */
  175875. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  175876. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  175877. typedef unsigned short XMSH; /* type of extended-memory handles */
  175878. typedef unsigned short EMSH; /* type of expanded-memory handles */
  175879. typedef union {
  175880. short file_handle; /* DOS file handle if it's a temp file */
  175881. XMSH xms_handle; /* handle if it's a chunk of XMS */
  175882. EMSH ems_handle; /* handle if it's a chunk of EMS */
  175883. } handle_union;
  175884. #endif /* USE_MSDOS_MEMMGR */
  175885. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  175886. #include <Files.h>
  175887. #endif /* USE_MAC_MEMMGR */
  175888. //typedef struct backing_store_struct * backing_store_ptr;
  175889. typedef struct backing_store_struct {
  175890. /* Methods for reading/writing/closing this backing-store object */
  175891. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  175892. struct backing_store_struct *info,
  175893. void FAR * buffer_address,
  175894. long file_offset, long byte_count));
  175895. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  175896. struct backing_store_struct *info,
  175897. void FAR * buffer_address,
  175898. long file_offset, long byte_count));
  175899. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  175900. struct backing_store_struct *info));
  175901. /* Private fields for system-dependent backing-store management */
  175902. #ifdef USE_MSDOS_MEMMGR
  175903. /* For the MS-DOS manager (jmemdos.c), we need: */
  175904. handle_union handle; /* reference to backing-store storage object */
  175905. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175906. #else
  175907. #ifdef USE_MAC_MEMMGR
  175908. /* For the Mac manager (jmemmac.c), we need: */
  175909. short temp_file; /* file reference number to temp file */
  175910. FSSpec tempSpec; /* the FSSpec for the temp file */
  175911. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  175912. #else
  175913. /* For a typical implementation with temp files, we need: */
  175914. FILE * temp_file; /* stdio reference to temp file */
  175915. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  175916. #endif
  175917. #endif
  175918. } backing_store_info;
  175919. /*
  175920. * Initial opening of a backing-store object. This must fill in the
  175921. * read/write/close pointers in the object. The read/write routines
  175922. * may take an error exit if the specified maximum file size is exceeded.
  175923. * (If jpeg_mem_available always returns a large value, this routine can
  175924. * just take an error exit.)
  175925. */
  175926. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  175927. struct backing_store_struct *info,
  175928. long total_bytes_needed));
  175929. /*
  175930. * These routines take care of any system-dependent initialization and
  175931. * cleanup required. jpeg_mem_init will be called before anything is
  175932. * allocated (and, therefore, nothing in cinfo is of use except the error
  175933. * manager pointer). It should return a suitable default value for
  175934. * max_memory_to_use; this may subsequently be overridden by the surrounding
  175935. * application. (Note that max_memory_to_use is only important if
  175936. * jpeg_mem_available chooses to consult it ... no one else will.)
  175937. * jpeg_mem_term may assume that all requested memory has been freed and that
  175938. * all opened backing-store objects have been closed.
  175939. */
  175940. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  175941. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  175942. #endif
  175943. /*** End of inlined file: jmemsys.h ***/
  175944. /* import the system-dependent declarations */
  175945. #ifndef NO_GETENV
  175946. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  175947. extern char * getenv JPP((const char * name));
  175948. #endif
  175949. #endif
  175950. /*
  175951. * Some important notes:
  175952. * The allocation routines provided here must never return NULL.
  175953. * They should exit to error_exit if unsuccessful.
  175954. *
  175955. * It's not a good idea to try to merge the sarray and barray routines,
  175956. * even though they are textually almost the same, because samples are
  175957. * usually stored as bytes while coefficients are shorts or ints. Thus,
  175958. * in machines where byte pointers have a different representation from
  175959. * word pointers, the resulting machine code could not be the same.
  175960. */
  175961. /*
  175962. * Many machines require storage alignment: longs must start on 4-byte
  175963. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  175964. * always returns pointers that are multiples of the worst-case alignment
  175965. * requirement, and we had better do so too.
  175966. * There isn't any really portable way to determine the worst-case alignment
  175967. * requirement. This module assumes that the alignment requirement is
  175968. * multiples of sizeof(ALIGN_TYPE).
  175969. * By default, we define ALIGN_TYPE as double. This is necessary on some
  175970. * workstations (where doubles really do need 8-byte alignment) and will work
  175971. * fine on nearly everything. If your machine has lesser alignment needs,
  175972. * you can save a few bytes by making ALIGN_TYPE smaller.
  175973. * The only place I know of where this will NOT work is certain Macintosh
  175974. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  175975. * Doing 10-byte alignment is counterproductive because longwords won't be
  175976. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  175977. * such a compiler.
  175978. */
  175979. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  175980. #define ALIGN_TYPE double
  175981. #endif
  175982. /*
  175983. * We allocate objects from "pools", where each pool is gotten with a single
  175984. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  175985. * overhead within a pool, except for alignment padding. Each pool has a
  175986. * header with a link to the next pool of the same class.
  175987. * Small and large pool headers are identical except that the latter's
  175988. * link pointer must be FAR on 80x86 machines.
  175989. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  175990. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  175991. * of the alignment requirement of ALIGN_TYPE.
  175992. */
  175993. typedef union small_pool_struct * small_pool_ptr;
  175994. typedef union small_pool_struct {
  175995. struct {
  175996. small_pool_ptr next; /* next in list of pools */
  175997. size_t bytes_used; /* how many bytes already used within pool */
  175998. size_t bytes_left; /* bytes still available in this pool */
  175999. } hdr;
  176000. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  176001. } small_pool_hdr;
  176002. typedef union large_pool_struct FAR * large_pool_ptr;
  176003. typedef union large_pool_struct {
  176004. struct {
  176005. large_pool_ptr next; /* next in list of pools */
  176006. size_t bytes_used; /* how many bytes already used within pool */
  176007. size_t bytes_left; /* bytes still available in this pool */
  176008. } hdr;
  176009. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  176010. } large_pool_hdr;
  176011. /*
  176012. * Here is the full definition of a memory manager object.
  176013. */
  176014. typedef struct {
  176015. struct jpeg_memory_mgr pub; /* public fields */
  176016. /* Each pool identifier (lifetime class) names a linked list of pools. */
  176017. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  176018. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  176019. /* Since we only have one lifetime class of virtual arrays, only one
  176020. * linked list is necessary (for each datatype). Note that the virtual
  176021. * array control blocks being linked together are actually stored somewhere
  176022. * in the small-pool list.
  176023. */
  176024. jvirt_sarray_ptr virt_sarray_list;
  176025. jvirt_barray_ptr virt_barray_list;
  176026. /* This counts total space obtained from jpeg_get_small/large */
  176027. long total_space_allocated;
  176028. /* alloc_sarray and alloc_barray set this value for use by virtual
  176029. * array routines.
  176030. */
  176031. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  176032. } my_memory_mgr;
  176033. typedef my_memory_mgr * my_mem_ptr;
  176034. /*
  176035. * The control blocks for virtual arrays.
  176036. * Note that these blocks are allocated in the "small" pool area.
  176037. * System-dependent info for the associated backing store (if any) is hidden
  176038. * inside the backing_store_info struct.
  176039. */
  176040. struct jvirt_sarray_control {
  176041. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  176042. JDIMENSION rows_in_array; /* total virtual array height */
  176043. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  176044. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  176045. JDIMENSION rows_in_mem; /* height of memory buffer */
  176046. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  176047. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  176048. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  176049. boolean pre_zero; /* pre-zero mode requested? */
  176050. boolean dirty; /* do current buffer contents need written? */
  176051. boolean b_s_open; /* is backing-store data valid? */
  176052. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  176053. backing_store_info b_s_info; /* System-dependent control info */
  176054. };
  176055. struct jvirt_barray_control {
  176056. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  176057. JDIMENSION rows_in_array; /* total virtual array height */
  176058. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  176059. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  176060. JDIMENSION rows_in_mem; /* height of memory buffer */
  176061. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  176062. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  176063. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  176064. boolean pre_zero; /* pre-zero mode requested? */
  176065. boolean dirty; /* do current buffer contents need written? */
  176066. boolean b_s_open; /* is backing-store data valid? */
  176067. jvirt_barray_ptr next; /* link to next virtual barray control block */
  176068. backing_store_info b_s_info; /* System-dependent control info */
  176069. };
  176070. #ifdef MEM_STATS /* optional extra stuff for statistics */
  176071. LOCAL(void)
  176072. print_mem_stats (j_common_ptr cinfo, int pool_id)
  176073. {
  176074. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176075. small_pool_ptr shdr_ptr;
  176076. large_pool_ptr lhdr_ptr;
  176077. /* Since this is only a debugging stub, we can cheat a little by using
  176078. * fprintf directly rather than going through the trace message code.
  176079. * This is helpful because message parm array can't handle longs.
  176080. */
  176081. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  176082. pool_id, mem->total_space_allocated);
  176083. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  176084. lhdr_ptr = lhdr_ptr->hdr.next) {
  176085. fprintf(stderr, " Large chunk used %ld\n",
  176086. (long) lhdr_ptr->hdr.bytes_used);
  176087. }
  176088. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  176089. shdr_ptr = shdr_ptr->hdr.next) {
  176090. fprintf(stderr, " Small chunk used %ld free %ld\n",
  176091. (long) shdr_ptr->hdr.bytes_used,
  176092. (long) shdr_ptr->hdr.bytes_left);
  176093. }
  176094. }
  176095. #endif /* MEM_STATS */
  176096. LOCAL(void)
  176097. out_of_memory (j_common_ptr cinfo, int which)
  176098. /* Report an out-of-memory error and stop execution */
  176099. /* If we compiled MEM_STATS support, report alloc requests before dying */
  176100. {
  176101. #ifdef MEM_STATS
  176102. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  176103. #endif
  176104. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  176105. }
  176106. /*
  176107. * Allocation of "small" objects.
  176108. *
  176109. * For these, we use pooled storage. When a new pool must be created,
  176110. * we try to get enough space for the current request plus a "slop" factor,
  176111. * where the slop will be the amount of leftover space in the new pool.
  176112. * The speed vs. space tradeoff is largely determined by the slop values.
  176113. * A different slop value is provided for each pool class (lifetime),
  176114. * and we also distinguish the first pool of a class from later ones.
  176115. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  176116. * machines, but may be too small if longs are 64 bits or more.
  176117. */
  176118. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  176119. {
  176120. 1600, /* first PERMANENT pool */
  176121. 16000 /* first IMAGE pool */
  176122. };
  176123. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  176124. {
  176125. 0, /* additional PERMANENT pools */
  176126. 5000 /* additional IMAGE pools */
  176127. };
  176128. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  176129. METHODDEF(void *)
  176130. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  176131. /* Allocate a "small" object */
  176132. {
  176133. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176134. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  176135. char * data_ptr;
  176136. size_t odd_bytes, min_request, slop;
  176137. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  176138. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  176139. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  176140. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  176141. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  176142. if (odd_bytes > 0)
  176143. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  176144. /* See if space is available in any existing pool */
  176145. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176146. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176147. prev_hdr_ptr = NULL;
  176148. hdr_ptr = mem->small_list[pool_id];
  176149. while (hdr_ptr != NULL) {
  176150. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  176151. break; /* found pool with enough space */
  176152. prev_hdr_ptr = hdr_ptr;
  176153. hdr_ptr = hdr_ptr->hdr.next;
  176154. }
  176155. /* Time to make a new pool? */
  176156. if (hdr_ptr == NULL) {
  176157. /* min_request is what we need now, slop is what will be leftover */
  176158. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  176159. if (prev_hdr_ptr == NULL) /* first pool in class? */
  176160. slop = first_pool_slop[pool_id];
  176161. else
  176162. slop = extra_pool_slop[pool_id];
  176163. /* Don't ask for more than MAX_ALLOC_CHUNK */
  176164. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  176165. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  176166. /* Try to get space, if fail reduce slop and try again */
  176167. for (;;) {
  176168. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  176169. if (hdr_ptr != NULL)
  176170. break;
  176171. slop /= 2;
  176172. if (slop < MIN_SLOP) /* give up when it gets real small */
  176173. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  176174. }
  176175. mem->total_space_allocated += min_request + slop;
  176176. /* Success, initialize the new pool header and add to end of list */
  176177. hdr_ptr->hdr.next = NULL;
  176178. hdr_ptr->hdr.bytes_used = 0;
  176179. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  176180. if (prev_hdr_ptr == NULL) /* first pool in class? */
  176181. mem->small_list[pool_id] = hdr_ptr;
  176182. else
  176183. prev_hdr_ptr->hdr.next = hdr_ptr;
  176184. }
  176185. /* OK, allocate the object from the current pool */
  176186. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  176187. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  176188. hdr_ptr->hdr.bytes_used += sizeofobject;
  176189. hdr_ptr->hdr.bytes_left -= sizeofobject;
  176190. return (void *) data_ptr;
  176191. }
  176192. /*
  176193. * Allocation of "large" objects.
  176194. *
  176195. * The external semantics of these are the same as "small" objects,
  176196. * except that FAR pointers are used on 80x86. However the pool
  176197. * management heuristics are quite different. We assume that each
  176198. * request is large enough that it may as well be passed directly to
  176199. * jpeg_get_large; the pool management just links everything together
  176200. * so that we can free it all on demand.
  176201. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  176202. * structures. The routines that create these structures (see below)
  176203. * deliberately bunch rows together to ensure a large request size.
  176204. */
  176205. METHODDEF(void FAR *)
  176206. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  176207. /* Allocate a "large" object */
  176208. {
  176209. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176210. large_pool_ptr hdr_ptr;
  176211. size_t odd_bytes;
  176212. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  176213. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  176214. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  176215. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  176216. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  176217. if (odd_bytes > 0)
  176218. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  176219. /* Always make a new pool */
  176220. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176221. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176222. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  176223. SIZEOF(large_pool_hdr));
  176224. if (hdr_ptr == NULL)
  176225. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  176226. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  176227. /* Success, initialize the new pool header and add to list */
  176228. hdr_ptr->hdr.next = mem->large_list[pool_id];
  176229. /* We maintain space counts in each pool header for statistical purposes,
  176230. * even though they are not needed for allocation.
  176231. */
  176232. hdr_ptr->hdr.bytes_used = sizeofobject;
  176233. hdr_ptr->hdr.bytes_left = 0;
  176234. mem->large_list[pool_id] = hdr_ptr;
  176235. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  176236. }
  176237. /*
  176238. * Creation of 2-D sample arrays.
  176239. * The pointers are in near heap, the samples themselves in FAR heap.
  176240. *
  176241. * To minimize allocation overhead and to allow I/O of large contiguous
  176242. * blocks, we allocate the sample rows in groups of as many rows as possible
  176243. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  176244. * NB: the virtual array control routines, later in this file, know about
  176245. * this chunking of rows. The rowsperchunk value is left in the mem manager
  176246. * object so that it can be saved away if this sarray is the workspace for
  176247. * a virtual array.
  176248. */
  176249. METHODDEF(JSAMPARRAY)
  176250. alloc_sarray (j_common_ptr cinfo, int pool_id,
  176251. JDIMENSION samplesperrow, JDIMENSION numrows)
  176252. /* Allocate a 2-D sample array */
  176253. {
  176254. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176255. JSAMPARRAY result;
  176256. JSAMPROW workspace;
  176257. JDIMENSION rowsperchunk, currow, i;
  176258. long ltemp;
  176259. /* Calculate max # of rows allowed in one allocation chunk */
  176260. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  176261. ((long) samplesperrow * SIZEOF(JSAMPLE));
  176262. if (ltemp <= 0)
  176263. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  176264. if (ltemp < (long) numrows)
  176265. rowsperchunk = (JDIMENSION) ltemp;
  176266. else
  176267. rowsperchunk = numrows;
  176268. mem->last_rowsperchunk = rowsperchunk;
  176269. /* Get space for row pointers (small object) */
  176270. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  176271. (size_t) (numrows * SIZEOF(JSAMPROW)));
  176272. /* Get the rows themselves (large objects) */
  176273. currow = 0;
  176274. while (currow < numrows) {
  176275. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  176276. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  176277. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  176278. * SIZEOF(JSAMPLE)));
  176279. for (i = rowsperchunk; i > 0; i--) {
  176280. result[currow++] = workspace;
  176281. workspace += samplesperrow;
  176282. }
  176283. }
  176284. return result;
  176285. }
  176286. /*
  176287. * Creation of 2-D coefficient-block arrays.
  176288. * This is essentially the same as the code for sample arrays, above.
  176289. */
  176290. METHODDEF(JBLOCKARRAY)
  176291. alloc_barray (j_common_ptr cinfo, int pool_id,
  176292. JDIMENSION blocksperrow, JDIMENSION numrows)
  176293. /* Allocate a 2-D coefficient-block array */
  176294. {
  176295. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176296. JBLOCKARRAY result;
  176297. JBLOCKROW workspace;
  176298. JDIMENSION rowsperchunk, currow, i;
  176299. long ltemp;
  176300. /* Calculate max # of rows allowed in one allocation chunk */
  176301. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  176302. ((long) blocksperrow * SIZEOF(JBLOCK));
  176303. if (ltemp <= 0)
  176304. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  176305. if (ltemp < (long) numrows)
  176306. rowsperchunk = (JDIMENSION) ltemp;
  176307. else
  176308. rowsperchunk = numrows;
  176309. mem->last_rowsperchunk = rowsperchunk;
  176310. /* Get space for row pointers (small object) */
  176311. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  176312. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  176313. /* Get the rows themselves (large objects) */
  176314. currow = 0;
  176315. while (currow < numrows) {
  176316. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  176317. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  176318. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  176319. * SIZEOF(JBLOCK)));
  176320. for (i = rowsperchunk; i > 0; i--) {
  176321. result[currow++] = workspace;
  176322. workspace += blocksperrow;
  176323. }
  176324. }
  176325. return result;
  176326. }
  176327. /*
  176328. * About virtual array management:
  176329. *
  176330. * The above "normal" array routines are only used to allocate strip buffers
  176331. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  176332. * are handled as "virtual" arrays. The array is still accessed a strip at a
  176333. * time, but the memory manager must save the whole array for repeated
  176334. * accesses. The intended implementation is that there is a strip buffer in
  176335. * memory (as high as is possible given the desired memory limit), plus a
  176336. * backing file that holds the rest of the array.
  176337. *
  176338. * The request_virt_array routines are told the total size of the image and
  176339. * the maximum number of rows that will be accessed at once. The in-memory
  176340. * buffer must be at least as large as the maxaccess value.
  176341. *
  176342. * The request routines create control blocks but not the in-memory buffers.
  176343. * That is postponed until realize_virt_arrays is called. At that time the
  176344. * total amount of space needed is known (approximately, anyway), so free
  176345. * memory can be divided up fairly.
  176346. *
  176347. * The access_virt_array routines are responsible for making a specific strip
  176348. * area accessible (after reading or writing the backing file, if necessary).
  176349. * Note that the access routines are told whether the caller intends to modify
  176350. * the accessed strip; during a read-only pass this saves having to rewrite
  176351. * data to disk. The access routines are also responsible for pre-zeroing
  176352. * any newly accessed rows, if pre-zeroing was requested.
  176353. *
  176354. * In current usage, the access requests are usually for nonoverlapping
  176355. * strips; that is, successive access start_row numbers differ by exactly
  176356. * num_rows = maxaccess. This means we can get good performance with simple
  176357. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  176358. * of the access height; then there will never be accesses across bufferload
  176359. * boundaries. The code will still work with overlapping access requests,
  176360. * but it doesn't handle bufferload overlaps very efficiently.
  176361. */
  176362. METHODDEF(jvirt_sarray_ptr)
  176363. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176364. JDIMENSION samplesperrow, JDIMENSION numrows,
  176365. JDIMENSION maxaccess)
  176366. /* Request a virtual 2-D sample array */
  176367. {
  176368. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176369. jvirt_sarray_ptr result;
  176370. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176371. if (pool_id != JPOOL_IMAGE)
  176372. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176373. /* get control block */
  176374. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  176375. SIZEOF(struct jvirt_sarray_control));
  176376. result->mem_buffer = NULL; /* marks array not yet realized */
  176377. result->rows_in_array = numrows;
  176378. result->samplesperrow = samplesperrow;
  176379. result->maxaccess = maxaccess;
  176380. result->pre_zero = pre_zero;
  176381. result->b_s_open = FALSE; /* no associated backing-store object */
  176382. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  176383. mem->virt_sarray_list = result;
  176384. return result;
  176385. }
  176386. METHODDEF(jvirt_barray_ptr)
  176387. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176388. JDIMENSION blocksperrow, JDIMENSION numrows,
  176389. JDIMENSION maxaccess)
  176390. /* Request a virtual 2-D coefficient-block array */
  176391. {
  176392. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176393. jvirt_barray_ptr result;
  176394. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176395. if (pool_id != JPOOL_IMAGE)
  176396. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176397. /* get control block */
  176398. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  176399. SIZEOF(struct jvirt_barray_control));
  176400. result->mem_buffer = NULL; /* marks array not yet realized */
  176401. result->rows_in_array = numrows;
  176402. result->blocksperrow = blocksperrow;
  176403. result->maxaccess = maxaccess;
  176404. result->pre_zero = pre_zero;
  176405. result->b_s_open = FALSE; /* no associated backing-store object */
  176406. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  176407. mem->virt_barray_list = result;
  176408. return result;
  176409. }
  176410. METHODDEF(void)
  176411. realize_virt_arrays (j_common_ptr cinfo)
  176412. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  176413. {
  176414. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176415. long space_per_minheight, maximum_space, avail_mem;
  176416. long minheights, max_minheights;
  176417. jvirt_sarray_ptr sptr;
  176418. jvirt_barray_ptr bptr;
  176419. /* Compute the minimum space needed (maxaccess rows in each buffer)
  176420. * and the maximum space needed (full image height in each buffer).
  176421. * These may be of use to the system-dependent jpeg_mem_available routine.
  176422. */
  176423. space_per_minheight = 0;
  176424. maximum_space = 0;
  176425. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176426. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176427. space_per_minheight += (long) sptr->maxaccess *
  176428. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176429. maximum_space += (long) sptr->rows_in_array *
  176430. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176431. }
  176432. }
  176433. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176434. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176435. space_per_minheight += (long) bptr->maxaccess *
  176436. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176437. maximum_space += (long) bptr->rows_in_array *
  176438. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176439. }
  176440. }
  176441. if (space_per_minheight <= 0)
  176442. return; /* no unrealized arrays, no work */
  176443. /* Determine amount of memory to actually use; this is system-dependent. */
  176444. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  176445. mem->total_space_allocated);
  176446. /* If the maximum space needed is available, make all the buffers full
  176447. * height; otherwise parcel it out with the same number of minheights
  176448. * in each buffer.
  176449. */
  176450. if (avail_mem >= maximum_space)
  176451. max_minheights = 1000000000L;
  176452. else {
  176453. max_minheights = avail_mem / space_per_minheight;
  176454. /* If there doesn't seem to be enough space, try to get the minimum
  176455. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  176456. */
  176457. if (max_minheights <= 0)
  176458. max_minheights = 1;
  176459. }
  176460. /* Allocate the in-memory buffers and initialize backing store as needed. */
  176461. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176462. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176463. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  176464. if (minheights <= max_minheights) {
  176465. /* This buffer fits in memory */
  176466. sptr->rows_in_mem = sptr->rows_in_array;
  176467. } else {
  176468. /* It doesn't fit in memory, create backing store. */
  176469. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  176470. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  176471. (long) sptr->rows_in_array *
  176472. (long) sptr->samplesperrow *
  176473. (long) SIZEOF(JSAMPLE));
  176474. sptr->b_s_open = TRUE;
  176475. }
  176476. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  176477. sptr->samplesperrow, sptr->rows_in_mem);
  176478. sptr->rowsperchunk = mem->last_rowsperchunk;
  176479. sptr->cur_start_row = 0;
  176480. sptr->first_undef_row = 0;
  176481. sptr->dirty = FALSE;
  176482. }
  176483. }
  176484. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176485. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176486. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  176487. if (minheights <= max_minheights) {
  176488. /* This buffer fits in memory */
  176489. bptr->rows_in_mem = bptr->rows_in_array;
  176490. } else {
  176491. /* It doesn't fit in memory, create backing store. */
  176492. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  176493. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  176494. (long) bptr->rows_in_array *
  176495. (long) bptr->blocksperrow *
  176496. (long) SIZEOF(JBLOCK));
  176497. bptr->b_s_open = TRUE;
  176498. }
  176499. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  176500. bptr->blocksperrow, bptr->rows_in_mem);
  176501. bptr->rowsperchunk = mem->last_rowsperchunk;
  176502. bptr->cur_start_row = 0;
  176503. bptr->first_undef_row = 0;
  176504. bptr->dirty = FALSE;
  176505. }
  176506. }
  176507. }
  176508. LOCAL(void)
  176509. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  176510. /* Do backing store read or write of a virtual sample array */
  176511. {
  176512. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176513. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176514. file_offset = ptr->cur_start_row * bytesperrow;
  176515. /* Loop to read or write each allocation chunk in mem_buffer */
  176516. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176517. /* One chunk, but check for short chunk at end of buffer */
  176518. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176519. /* Transfer no more than is currently defined */
  176520. thisrow = (long) ptr->cur_start_row + i;
  176521. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176522. /* Transfer no more than fits in file */
  176523. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176524. if (rows <= 0) /* this chunk might be past end of file! */
  176525. break;
  176526. byte_count = rows * bytesperrow;
  176527. if (writing)
  176528. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176529. (void FAR *) ptr->mem_buffer[i],
  176530. file_offset, byte_count);
  176531. else
  176532. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176533. (void FAR *) ptr->mem_buffer[i],
  176534. file_offset, byte_count);
  176535. file_offset += byte_count;
  176536. }
  176537. }
  176538. LOCAL(void)
  176539. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  176540. /* Do backing store read or write of a virtual coefficient-block array */
  176541. {
  176542. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176543. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  176544. file_offset = ptr->cur_start_row * bytesperrow;
  176545. /* Loop to read or write each allocation chunk in mem_buffer */
  176546. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176547. /* One chunk, but check for short chunk at end of buffer */
  176548. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176549. /* Transfer no more than is currently defined */
  176550. thisrow = (long) ptr->cur_start_row + i;
  176551. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176552. /* Transfer no more than fits in file */
  176553. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176554. if (rows <= 0) /* this chunk might be past end of file! */
  176555. break;
  176556. byte_count = rows * bytesperrow;
  176557. if (writing)
  176558. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176559. (void FAR *) ptr->mem_buffer[i],
  176560. file_offset, byte_count);
  176561. else
  176562. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176563. (void FAR *) ptr->mem_buffer[i],
  176564. file_offset, byte_count);
  176565. file_offset += byte_count;
  176566. }
  176567. }
  176568. METHODDEF(JSAMPARRAY)
  176569. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  176570. JDIMENSION start_row, JDIMENSION num_rows,
  176571. boolean writable)
  176572. /* Access the part of a virtual sample array starting at start_row */
  176573. /* and extending for num_rows rows. writable is true if */
  176574. /* caller intends to modify the accessed area. */
  176575. {
  176576. JDIMENSION end_row = start_row + num_rows;
  176577. JDIMENSION undef_row;
  176578. /* debugging check */
  176579. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176580. ptr->mem_buffer == NULL)
  176581. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176582. /* Make the desired part of the virtual array accessible */
  176583. if (start_row < ptr->cur_start_row ||
  176584. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176585. if (! ptr->b_s_open)
  176586. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176587. /* Flush old buffer contents if necessary */
  176588. if (ptr->dirty) {
  176589. do_sarray_io(cinfo, ptr, TRUE);
  176590. ptr->dirty = FALSE;
  176591. }
  176592. /* Decide what part of virtual array to access.
  176593. * Algorithm: if target address > current window, assume forward scan,
  176594. * load starting at target address. If target address < current window,
  176595. * assume backward scan, load so that target area is top of window.
  176596. * Note that when switching from forward write to forward read, will have
  176597. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176598. */
  176599. if (start_row > ptr->cur_start_row) {
  176600. ptr->cur_start_row = start_row;
  176601. } else {
  176602. /* use long arithmetic here to avoid overflow & unsigned problems */
  176603. long ltemp;
  176604. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176605. if (ltemp < 0)
  176606. ltemp = 0; /* don't fall off front end of file */
  176607. ptr->cur_start_row = (JDIMENSION) ltemp;
  176608. }
  176609. /* Read in the selected part of the array.
  176610. * During the initial write pass, we will do no actual read
  176611. * because the selected part is all undefined.
  176612. */
  176613. do_sarray_io(cinfo, ptr, FALSE);
  176614. }
  176615. /* Ensure the accessed part of the array is defined; prezero if needed.
  176616. * To improve locality of access, we only prezero the part of the array
  176617. * that the caller is about to access, not the entire in-memory array.
  176618. */
  176619. if (ptr->first_undef_row < end_row) {
  176620. if (ptr->first_undef_row < start_row) {
  176621. if (writable) /* writer skipped over a section of array */
  176622. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176623. undef_row = start_row; /* but reader is allowed to read ahead */
  176624. } else {
  176625. undef_row = ptr->first_undef_row;
  176626. }
  176627. if (writable)
  176628. ptr->first_undef_row = end_row;
  176629. if (ptr->pre_zero) {
  176630. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176631. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176632. end_row -= ptr->cur_start_row;
  176633. while (undef_row < end_row) {
  176634. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176635. undef_row++;
  176636. }
  176637. } else {
  176638. if (! writable) /* reader looking at undefined data */
  176639. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176640. }
  176641. }
  176642. /* Flag the buffer dirty if caller will write in it */
  176643. if (writable)
  176644. ptr->dirty = TRUE;
  176645. /* Return address of proper part of the buffer */
  176646. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176647. }
  176648. METHODDEF(JBLOCKARRAY)
  176649. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  176650. JDIMENSION start_row, JDIMENSION num_rows,
  176651. boolean writable)
  176652. /* Access the part of a virtual block array starting at start_row */
  176653. /* and extending for num_rows rows. writable is true if */
  176654. /* caller intends to modify the accessed area. */
  176655. {
  176656. JDIMENSION end_row = start_row + num_rows;
  176657. JDIMENSION undef_row;
  176658. /* debugging check */
  176659. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176660. ptr->mem_buffer == NULL)
  176661. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176662. /* Make the desired part of the virtual array accessible */
  176663. if (start_row < ptr->cur_start_row ||
  176664. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176665. if (! ptr->b_s_open)
  176666. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176667. /* Flush old buffer contents if necessary */
  176668. if (ptr->dirty) {
  176669. do_barray_io(cinfo, ptr, TRUE);
  176670. ptr->dirty = FALSE;
  176671. }
  176672. /* Decide what part of virtual array to access.
  176673. * Algorithm: if target address > current window, assume forward scan,
  176674. * load starting at target address. If target address < current window,
  176675. * assume backward scan, load so that target area is top of window.
  176676. * Note that when switching from forward write to forward read, will have
  176677. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176678. */
  176679. if (start_row > ptr->cur_start_row) {
  176680. ptr->cur_start_row = start_row;
  176681. } else {
  176682. /* use long arithmetic here to avoid overflow & unsigned problems */
  176683. long ltemp;
  176684. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176685. if (ltemp < 0)
  176686. ltemp = 0; /* don't fall off front end of file */
  176687. ptr->cur_start_row = (JDIMENSION) ltemp;
  176688. }
  176689. /* Read in the selected part of the array.
  176690. * During the initial write pass, we will do no actual read
  176691. * because the selected part is all undefined.
  176692. */
  176693. do_barray_io(cinfo, ptr, FALSE);
  176694. }
  176695. /* Ensure the accessed part of the array is defined; prezero if needed.
  176696. * To improve locality of access, we only prezero the part of the array
  176697. * that the caller is about to access, not the entire in-memory array.
  176698. */
  176699. if (ptr->first_undef_row < end_row) {
  176700. if (ptr->first_undef_row < start_row) {
  176701. if (writable) /* writer skipped over a section of array */
  176702. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176703. undef_row = start_row; /* but reader is allowed to read ahead */
  176704. } else {
  176705. undef_row = ptr->first_undef_row;
  176706. }
  176707. if (writable)
  176708. ptr->first_undef_row = end_row;
  176709. if (ptr->pre_zero) {
  176710. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  176711. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176712. end_row -= ptr->cur_start_row;
  176713. while (undef_row < end_row) {
  176714. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176715. undef_row++;
  176716. }
  176717. } else {
  176718. if (! writable) /* reader looking at undefined data */
  176719. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176720. }
  176721. }
  176722. /* Flag the buffer dirty if caller will write in it */
  176723. if (writable)
  176724. ptr->dirty = TRUE;
  176725. /* Return address of proper part of the buffer */
  176726. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176727. }
  176728. /*
  176729. * Release all objects belonging to a specified pool.
  176730. */
  176731. METHODDEF(void)
  176732. free_pool (j_common_ptr cinfo, int pool_id)
  176733. {
  176734. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176735. small_pool_ptr shdr_ptr;
  176736. large_pool_ptr lhdr_ptr;
  176737. size_t space_freed;
  176738. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176739. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176740. #ifdef MEM_STATS
  176741. if (cinfo->err->trace_level > 1)
  176742. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  176743. #endif
  176744. /* If freeing IMAGE pool, close any virtual arrays first */
  176745. if (pool_id == JPOOL_IMAGE) {
  176746. jvirt_sarray_ptr sptr;
  176747. jvirt_barray_ptr bptr;
  176748. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176749. if (sptr->b_s_open) { /* there may be no backing store */
  176750. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  176751. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  176752. }
  176753. }
  176754. mem->virt_sarray_list = NULL;
  176755. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176756. if (bptr->b_s_open) { /* there may be no backing store */
  176757. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  176758. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  176759. }
  176760. }
  176761. mem->virt_barray_list = NULL;
  176762. }
  176763. /* Release large objects */
  176764. lhdr_ptr = mem->large_list[pool_id];
  176765. mem->large_list[pool_id] = NULL;
  176766. while (lhdr_ptr != NULL) {
  176767. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  176768. space_freed = lhdr_ptr->hdr.bytes_used +
  176769. lhdr_ptr->hdr.bytes_left +
  176770. SIZEOF(large_pool_hdr);
  176771. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  176772. mem->total_space_allocated -= space_freed;
  176773. lhdr_ptr = next_lhdr_ptr;
  176774. }
  176775. /* Release small objects */
  176776. shdr_ptr = mem->small_list[pool_id];
  176777. mem->small_list[pool_id] = NULL;
  176778. while (shdr_ptr != NULL) {
  176779. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  176780. space_freed = shdr_ptr->hdr.bytes_used +
  176781. shdr_ptr->hdr.bytes_left +
  176782. SIZEOF(small_pool_hdr);
  176783. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  176784. mem->total_space_allocated -= space_freed;
  176785. shdr_ptr = next_shdr_ptr;
  176786. }
  176787. }
  176788. /*
  176789. * Close up shop entirely.
  176790. * Note that this cannot be called unless cinfo->mem is non-NULL.
  176791. */
  176792. METHODDEF(void)
  176793. self_destruct (j_common_ptr cinfo)
  176794. {
  176795. int pool;
  176796. /* Close all backing store, release all memory.
  176797. * Releasing pools in reverse order might help avoid fragmentation
  176798. * with some (brain-damaged) malloc libraries.
  176799. */
  176800. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176801. free_pool(cinfo, pool);
  176802. }
  176803. /* Release the memory manager control block too. */
  176804. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  176805. cinfo->mem = NULL; /* ensures I will be called only once */
  176806. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176807. }
  176808. /*
  176809. * Memory manager initialization.
  176810. * When this is called, only the error manager pointer is valid in cinfo!
  176811. */
  176812. GLOBAL(void)
  176813. jinit_memory_mgr (j_common_ptr cinfo)
  176814. {
  176815. my_mem_ptr mem;
  176816. long max_to_use;
  176817. int pool;
  176818. size_t test_mac;
  176819. cinfo->mem = NULL; /* for safety if init fails */
  176820. /* Check for configuration errors.
  176821. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  176822. * doesn't reflect any real hardware alignment requirement.
  176823. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  176824. * in common if and only if X is a power of 2, ie has only one one-bit.
  176825. * Some compilers may give an "unreachable code" warning here; ignore it.
  176826. */
  176827. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  176828. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  176829. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  176830. * a multiple of SIZEOF(ALIGN_TYPE).
  176831. * Again, an "unreachable code" warning may be ignored here.
  176832. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  176833. */
  176834. test_mac = (size_t) MAX_ALLOC_CHUNK;
  176835. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  176836. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  176837. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  176838. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  176839. /* Attempt to allocate memory manager's control block */
  176840. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  176841. if (mem == NULL) {
  176842. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  176843. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  176844. }
  176845. /* OK, fill in the method pointers */
  176846. mem->pub.alloc_small = alloc_small;
  176847. mem->pub.alloc_large = alloc_large;
  176848. mem->pub.alloc_sarray = alloc_sarray;
  176849. mem->pub.alloc_barray = alloc_barray;
  176850. mem->pub.request_virt_sarray = request_virt_sarray;
  176851. mem->pub.request_virt_barray = request_virt_barray;
  176852. mem->pub.realize_virt_arrays = realize_virt_arrays;
  176853. mem->pub.access_virt_sarray = access_virt_sarray;
  176854. mem->pub.access_virt_barray = access_virt_barray;
  176855. mem->pub.free_pool = free_pool;
  176856. mem->pub.self_destruct = self_destruct;
  176857. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  176858. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  176859. /* Initialize working state */
  176860. mem->pub.max_memory_to_use = max_to_use;
  176861. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  176862. mem->small_list[pool] = NULL;
  176863. mem->large_list[pool] = NULL;
  176864. }
  176865. mem->virt_sarray_list = NULL;
  176866. mem->virt_barray_list = NULL;
  176867. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  176868. /* Declare ourselves open for business */
  176869. cinfo->mem = & mem->pub;
  176870. /* Check for an environment variable JPEGMEM; if found, override the
  176871. * default max_memory setting from jpeg_mem_init. Note that the
  176872. * surrounding application may again override this value.
  176873. * If your system doesn't support getenv(), define NO_GETENV to disable
  176874. * this feature.
  176875. */
  176876. #ifndef NO_GETENV
  176877. { char * memenv;
  176878. if ((memenv = getenv("JPEGMEM")) != NULL) {
  176879. char ch = 'x';
  176880. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  176881. if (ch == 'm' || ch == 'M')
  176882. max_to_use *= 1000L;
  176883. mem->pub.max_memory_to_use = max_to_use * 1000L;
  176884. }
  176885. }
  176886. }
  176887. #endif
  176888. }
  176889. /*** End of inlined file: jmemmgr.c ***/
  176890. /*** Start of inlined file: jmemnobs.c ***/
  176891. #define JPEG_INTERNALS
  176892. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  176893. extern void * malloc JPP((size_t size));
  176894. extern void free JPP((void *ptr));
  176895. #endif
  176896. /*
  176897. * Memory allocation and freeing are controlled by the regular library
  176898. * routines malloc() and free().
  176899. */
  176900. GLOBAL(void *)
  176901. jpeg_get_small (j_common_ptr , size_t sizeofobject)
  176902. {
  176903. return (void *) malloc(sizeofobject);
  176904. }
  176905. GLOBAL(void)
  176906. jpeg_free_small (j_common_ptr , void * object, size_t)
  176907. {
  176908. free(object);
  176909. }
  176910. /*
  176911. * "Large" objects are treated the same as "small" ones.
  176912. * NB: although we include FAR keywords in the routine declarations,
  176913. * this file won't actually work in 80x86 small/medium model; at least,
  176914. * you probably won't be able to process useful-size images in only 64KB.
  176915. */
  176916. GLOBAL(void FAR *)
  176917. jpeg_get_large (j_common_ptr, size_t sizeofobject)
  176918. {
  176919. return (void FAR *) malloc(sizeofobject);
  176920. }
  176921. GLOBAL(void)
  176922. jpeg_free_large (j_common_ptr, void FAR * object, size_t)
  176923. {
  176924. free(object);
  176925. }
  176926. /*
  176927. * This routine computes the total memory space available for allocation.
  176928. * Here we always say, "we got all you want bud!"
  176929. */
  176930. GLOBAL(long)
  176931. jpeg_mem_available (j_common_ptr, long,
  176932. long max_bytes_needed, long)
  176933. {
  176934. return max_bytes_needed;
  176935. }
  176936. /*
  176937. * Backing store (temporary file) management.
  176938. * Since jpeg_mem_available always promised the moon,
  176939. * this should never be called and we can just error out.
  176940. */
  176941. GLOBAL(void)
  176942. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *,
  176943. long )
  176944. {
  176945. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  176946. }
  176947. /*
  176948. * These routines take care of any system-dependent initialization and
  176949. * cleanup required. Here, there isn't any.
  176950. */
  176951. GLOBAL(long)
  176952. jpeg_mem_init (j_common_ptr)
  176953. {
  176954. return 0; /* just set max_memory_to_use to 0 */
  176955. }
  176956. GLOBAL(void)
  176957. jpeg_mem_term (j_common_ptr)
  176958. {
  176959. /* no work */
  176960. }
  176961. /*** End of inlined file: jmemnobs.c ***/
  176962. /*** Start of inlined file: jquant1.c ***/
  176963. #define JPEG_INTERNALS
  176964. #ifdef QUANT_1PASS_SUPPORTED
  176965. /*
  176966. * The main purpose of 1-pass quantization is to provide a fast, if not very
  176967. * high quality, colormapped output capability. A 2-pass quantizer usually
  176968. * gives better visual quality; however, for quantized grayscale output this
  176969. * quantizer is perfectly adequate. Dithering is highly recommended with this
  176970. * quantizer, though you can turn it off if you really want to.
  176971. *
  176972. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  176973. * image. We use a map consisting of all combinations of Ncolors[i] color
  176974. * values for the i'th component. The Ncolors[] values are chosen so that
  176975. * their product, the total number of colors, is no more than that requested.
  176976. * (In most cases, the product will be somewhat less.)
  176977. *
  176978. * Since the colormap is orthogonal, the representative value for each color
  176979. * component can be determined without considering the other components;
  176980. * then these indexes can be combined into a colormap index by a standard
  176981. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  176982. * can be precalculated and stored in the lookup table colorindex[].
  176983. * colorindex[i][j] maps pixel value j in component i to the nearest
  176984. * representative value (grid plane) for that component; this index is
  176985. * multiplied by the array stride for component i, so that the
  176986. * index of the colormap entry closest to a given pixel value is just
  176987. * sum( colorindex[component-number][pixel-component-value] )
  176988. * Aside from being fast, this scheme allows for variable spacing between
  176989. * representative values with no additional lookup cost.
  176990. *
  176991. * If gamma correction has been applied in color conversion, it might be wise
  176992. * to adjust the color grid spacing so that the representative colors are
  176993. * equidistant in linear space. At this writing, gamma correction is not
  176994. * implemented by jdcolor, so nothing is done here.
  176995. */
  176996. /* Declarations for ordered dithering.
  176997. *
  176998. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  176999. * dithering is described in many references, for instance Dale Schumacher's
  177000. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  177001. * In place of Schumacher's comparisons against a "threshold" value, we add a
  177002. * "dither" value to the input pixel and then round the result to the nearest
  177003. * output value. The dither value is equivalent to (0.5 - threshold) times
  177004. * the distance between output values. For ordered dithering, we assume that
  177005. * the output colors are equally spaced; if not, results will probably be
  177006. * worse, since the dither may be too much or too little at a given point.
  177007. *
  177008. * The normal calculation would be to form pixel value + dither, range-limit
  177009. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  177010. * We can skip the separate range-limiting step by extending the colorindex
  177011. * table in both directions.
  177012. */
  177013. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  177014. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  177015. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  177016. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  177017. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  177018. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  177019. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  177020. /* Bayer's order-4 dither array. Generated by the code given in
  177021. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  177022. * The values in this array must range from 0 to ODITHER_CELLS-1.
  177023. */
  177024. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  177025. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  177026. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  177027. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  177028. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  177029. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  177030. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  177031. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  177032. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  177033. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  177034. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  177035. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  177036. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  177037. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  177038. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  177039. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  177040. };
  177041. /* Declarations for Floyd-Steinberg dithering.
  177042. *
  177043. * Errors are accumulated into the array fserrors[], at a resolution of
  177044. * 1/16th of a pixel count. The error at a given pixel is propagated
  177045. * to its not-yet-processed neighbors using the standard F-S fractions,
  177046. * ... (here) 7/16
  177047. * 3/16 5/16 1/16
  177048. * We work left-to-right on even rows, right-to-left on odd rows.
  177049. *
  177050. * We can get away with a single array (holding one row's worth of errors)
  177051. * by using it to store the current row's errors at pixel columns not yet
  177052. * processed, but the next row's errors at columns already processed. We
  177053. * need only a few extra variables to hold the errors immediately around the
  177054. * current column. (If we are lucky, those variables are in registers, but
  177055. * even if not, they're probably cheaper to access than array elements are.)
  177056. *
  177057. * The fserrors[] array is indexed [component#][position].
  177058. * We provide (#columns + 2) entries per component; the extra entry at each
  177059. * end saves us from special-casing the first and last pixels.
  177060. *
  177061. * Note: on a wide image, we might not have enough room in a PC's near data
  177062. * segment to hold the error array; so it is allocated with alloc_large.
  177063. */
  177064. #if BITS_IN_JSAMPLE == 8
  177065. typedef INT16 FSERROR; /* 16 bits should be enough */
  177066. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  177067. #else
  177068. typedef INT32 FSERROR; /* may need more than 16 bits */
  177069. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  177070. #endif
  177071. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  177072. /* Private subobject */
  177073. #define MAX_Q_COMPS 4 /* max components I can handle */
  177074. typedef struct {
  177075. struct jpeg_color_quantizer pub; /* public fields */
  177076. /* Initially allocated colormap is saved here */
  177077. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  177078. int sv_actual; /* number of entries in use */
  177079. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  177080. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  177081. * premultiplied as described above. Since colormap indexes must fit into
  177082. * JSAMPLEs, the entries of this array will too.
  177083. */
  177084. boolean is_padded; /* is the colorindex padded for odither? */
  177085. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  177086. /* Variables for ordered dithering */
  177087. int row_index; /* cur row's vertical index in dither matrix */
  177088. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  177089. /* Variables for Floyd-Steinberg dithering */
  177090. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  177091. boolean on_odd_row; /* flag to remember which row we are on */
  177092. } my_cquantizer;
  177093. typedef my_cquantizer * my_cquantize_ptr;
  177094. /*
  177095. * Policy-making subroutines for create_colormap and create_colorindex.
  177096. * These routines determine the colormap to be used. The rest of the module
  177097. * only assumes that the colormap is orthogonal.
  177098. *
  177099. * * select_ncolors decides how to divvy up the available colors
  177100. * among the components.
  177101. * * output_value defines the set of representative values for a component.
  177102. * * largest_input_value defines the mapping from input values to
  177103. * representative values for a component.
  177104. * Note that the latter two routines may impose different policies for
  177105. * different components, though this is not currently done.
  177106. */
  177107. LOCAL(int)
  177108. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  177109. /* Determine allocation of desired colors to components, */
  177110. /* and fill in Ncolors[] array to indicate choice. */
  177111. /* Return value is total number of colors (product of Ncolors[] values). */
  177112. {
  177113. int nc = cinfo->out_color_components; /* number of color components */
  177114. int max_colors = cinfo->desired_number_of_colors;
  177115. int total_colors, iroot, i, j;
  177116. boolean changed;
  177117. long temp;
  177118. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  177119. /* We can allocate at least the nc'th root of max_colors per component. */
  177120. /* Compute floor(nc'th root of max_colors). */
  177121. iroot = 1;
  177122. do {
  177123. iroot++;
  177124. temp = iroot; /* set temp = iroot ** nc */
  177125. for (i = 1; i < nc; i++)
  177126. temp *= iroot;
  177127. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  177128. iroot--; /* now iroot = floor(root) */
  177129. /* Must have at least 2 color values per component */
  177130. if (iroot < 2)
  177131. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  177132. /* Initialize to iroot color values for each component */
  177133. total_colors = 1;
  177134. for (i = 0; i < nc; i++) {
  177135. Ncolors[i] = iroot;
  177136. total_colors *= iroot;
  177137. }
  177138. /* We may be able to increment the count for one or more components without
  177139. * exceeding max_colors, though we know not all can be incremented.
  177140. * Sometimes, the first component can be incremented more than once!
  177141. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  177142. * In RGB colorspace, try to increment G first, then R, then B.
  177143. */
  177144. do {
  177145. changed = FALSE;
  177146. for (i = 0; i < nc; i++) {
  177147. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  177148. /* calculate new total_colors if Ncolors[j] is incremented */
  177149. temp = total_colors / Ncolors[j];
  177150. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  177151. if (temp > (long) max_colors)
  177152. break; /* won't fit, done with this pass */
  177153. Ncolors[j]++; /* OK, apply the increment */
  177154. total_colors = (int) temp;
  177155. changed = TRUE;
  177156. }
  177157. } while (changed);
  177158. return total_colors;
  177159. }
  177160. LOCAL(int)
  177161. output_value (j_decompress_ptr, int, int j, int maxj)
  177162. /* Return j'th output value, where j will range from 0 to maxj */
  177163. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  177164. {
  177165. /* We always provide values 0 and MAXJSAMPLE for each component;
  177166. * any additional values are equally spaced between these limits.
  177167. * (Forcing the upper and lower values to the limits ensures that
  177168. * dithering can't produce a color outside the selected gamut.)
  177169. */
  177170. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  177171. }
  177172. LOCAL(int)
  177173. largest_input_value (j_decompress_ptr, int, int j, int maxj)
  177174. /* Return largest input value that should map to j'th output value */
  177175. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  177176. {
  177177. /* Breakpoints are halfway between values returned by output_value */
  177178. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  177179. }
  177180. /*
  177181. * Create the colormap.
  177182. */
  177183. LOCAL(void)
  177184. create_colormap (j_decompress_ptr cinfo)
  177185. {
  177186. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177187. JSAMPARRAY colormap; /* Created colormap */
  177188. int total_colors; /* Number of distinct output colors */
  177189. int i,j,k, nci, blksize, blkdist, ptr, val;
  177190. /* Select number of colors for each component */
  177191. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  177192. /* Report selected color counts */
  177193. if (cinfo->out_color_components == 3)
  177194. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  177195. total_colors, cquantize->Ncolors[0],
  177196. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  177197. else
  177198. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  177199. /* Allocate and fill in the colormap. */
  177200. /* The colors are ordered in the map in standard row-major order, */
  177201. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  177202. colormap = (*cinfo->mem->alloc_sarray)
  177203. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177204. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  177205. /* blksize is number of adjacent repeated entries for a component */
  177206. /* blkdist is distance between groups of identical entries for a component */
  177207. blkdist = total_colors;
  177208. for (i = 0; i < cinfo->out_color_components; i++) {
  177209. /* fill in colormap entries for i'th color component */
  177210. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177211. blksize = blkdist / nci;
  177212. for (j = 0; j < nci; j++) {
  177213. /* Compute j'th output value (out of nci) for component */
  177214. val = output_value(cinfo, i, j, nci-1);
  177215. /* Fill in all colormap entries that have this value of this component */
  177216. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  177217. /* fill in blksize entries beginning at ptr */
  177218. for (k = 0; k < blksize; k++)
  177219. colormap[i][ptr+k] = (JSAMPLE) val;
  177220. }
  177221. }
  177222. blkdist = blksize; /* blksize of this color is blkdist of next */
  177223. }
  177224. /* Save the colormap in private storage,
  177225. * where it will survive color quantization mode changes.
  177226. */
  177227. cquantize->sv_colormap = colormap;
  177228. cquantize->sv_actual = total_colors;
  177229. }
  177230. /*
  177231. * Create the color index table.
  177232. */
  177233. LOCAL(void)
  177234. create_colorindex (j_decompress_ptr cinfo)
  177235. {
  177236. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177237. JSAMPROW indexptr;
  177238. int i,j,k, nci, blksize, val, pad;
  177239. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  177240. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  177241. * This is not necessary in the other dithering modes. However, we
  177242. * flag whether it was done in case user changes dithering mode.
  177243. */
  177244. if (cinfo->dither_mode == JDITHER_ORDERED) {
  177245. pad = MAXJSAMPLE*2;
  177246. cquantize->is_padded = TRUE;
  177247. } else {
  177248. pad = 0;
  177249. cquantize->is_padded = FALSE;
  177250. }
  177251. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  177252. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177253. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  177254. (JDIMENSION) cinfo->out_color_components);
  177255. /* blksize is number of adjacent repeated entries for a component */
  177256. blksize = cquantize->sv_actual;
  177257. for (i = 0; i < cinfo->out_color_components; i++) {
  177258. /* fill in colorindex entries for i'th color component */
  177259. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177260. blksize = blksize / nci;
  177261. /* adjust colorindex pointers to provide padding at negative indexes. */
  177262. if (pad)
  177263. cquantize->colorindex[i] += MAXJSAMPLE;
  177264. /* in loop, val = index of current output value, */
  177265. /* and k = largest j that maps to current val */
  177266. indexptr = cquantize->colorindex[i];
  177267. val = 0;
  177268. k = largest_input_value(cinfo, i, 0, nci-1);
  177269. for (j = 0; j <= MAXJSAMPLE; j++) {
  177270. while (j > k) /* advance val if past boundary */
  177271. k = largest_input_value(cinfo, i, ++val, nci-1);
  177272. /* premultiply so that no multiplication needed in main processing */
  177273. indexptr[j] = (JSAMPLE) (val * blksize);
  177274. }
  177275. /* Pad at both ends if necessary */
  177276. if (pad)
  177277. for (j = 1; j <= MAXJSAMPLE; j++) {
  177278. indexptr[-j] = indexptr[0];
  177279. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  177280. }
  177281. }
  177282. }
  177283. /*
  177284. * Create an ordered-dither array for a component having ncolors
  177285. * distinct output values.
  177286. */
  177287. LOCAL(ODITHER_MATRIX_PTR)
  177288. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  177289. {
  177290. ODITHER_MATRIX_PTR odither;
  177291. int j,k;
  177292. INT32 num,den;
  177293. odither = (ODITHER_MATRIX_PTR)
  177294. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177295. SIZEOF(ODITHER_MATRIX));
  177296. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  177297. * Hence the dither value for the matrix cell with fill order f
  177298. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  177299. * On 16-bit-int machine, be careful to avoid overflow.
  177300. */
  177301. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  177302. for (j = 0; j < ODITHER_SIZE; j++) {
  177303. for (k = 0; k < ODITHER_SIZE; k++) {
  177304. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  177305. * MAXJSAMPLE;
  177306. /* Ensure round towards zero despite C's lack of consistency
  177307. * about rounding negative values in integer division...
  177308. */
  177309. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  177310. }
  177311. }
  177312. return odither;
  177313. }
  177314. /*
  177315. * Create the ordered-dither tables.
  177316. * Components having the same number of representative colors may
  177317. * share a dither table.
  177318. */
  177319. LOCAL(void)
  177320. create_odither_tables (j_decompress_ptr cinfo)
  177321. {
  177322. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177323. ODITHER_MATRIX_PTR odither;
  177324. int i, j, nci;
  177325. for (i = 0; i < cinfo->out_color_components; i++) {
  177326. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177327. odither = NULL; /* search for matching prior component */
  177328. for (j = 0; j < i; j++) {
  177329. if (nci == cquantize->Ncolors[j]) {
  177330. odither = cquantize->odither[j];
  177331. break;
  177332. }
  177333. }
  177334. if (odither == NULL) /* need a new table? */
  177335. odither = make_odither_array(cinfo, nci);
  177336. cquantize->odither[i] = odither;
  177337. }
  177338. }
  177339. /*
  177340. * Map some rows of pixels to the output colormapped representation.
  177341. */
  177342. METHODDEF(void)
  177343. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177344. JSAMPARRAY output_buf, int num_rows)
  177345. /* General case, no dithering */
  177346. {
  177347. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177348. JSAMPARRAY colorindex = cquantize->colorindex;
  177349. register int pixcode, ci;
  177350. register JSAMPROW ptrin, ptrout;
  177351. int row;
  177352. JDIMENSION col;
  177353. JDIMENSION width = cinfo->output_width;
  177354. register int nc = cinfo->out_color_components;
  177355. for (row = 0; row < num_rows; row++) {
  177356. ptrin = input_buf[row];
  177357. ptrout = output_buf[row];
  177358. for (col = width; col > 0; col--) {
  177359. pixcode = 0;
  177360. for (ci = 0; ci < nc; ci++) {
  177361. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  177362. }
  177363. *ptrout++ = (JSAMPLE) pixcode;
  177364. }
  177365. }
  177366. }
  177367. METHODDEF(void)
  177368. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177369. JSAMPARRAY output_buf, int num_rows)
  177370. /* Fast path for out_color_components==3, no dithering */
  177371. {
  177372. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177373. register int pixcode;
  177374. register JSAMPROW ptrin, ptrout;
  177375. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177376. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177377. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177378. int row;
  177379. JDIMENSION col;
  177380. JDIMENSION width = cinfo->output_width;
  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 = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  177386. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  177387. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  177388. *ptrout++ = (JSAMPLE) pixcode;
  177389. }
  177390. }
  177391. }
  177392. METHODDEF(void)
  177393. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177394. JSAMPARRAY output_buf, int num_rows)
  177395. /* General case, with ordered dithering */
  177396. {
  177397. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177398. register JSAMPROW input_ptr;
  177399. register JSAMPROW output_ptr;
  177400. JSAMPROW colorindex_ci;
  177401. int * dither; /* points to active row of dither matrix */
  177402. int row_index, col_index; /* current indexes into dither matrix */
  177403. int nc = cinfo->out_color_components;
  177404. int ci;
  177405. int row;
  177406. JDIMENSION col;
  177407. JDIMENSION width = cinfo->output_width;
  177408. for (row = 0; row < num_rows; row++) {
  177409. /* Initialize output values to 0 so can process components separately */
  177410. jzero_far((void FAR *) output_buf[row],
  177411. (size_t) (width * SIZEOF(JSAMPLE)));
  177412. row_index = cquantize->row_index;
  177413. for (ci = 0; ci < nc; ci++) {
  177414. input_ptr = input_buf[row] + ci;
  177415. output_ptr = output_buf[row];
  177416. colorindex_ci = cquantize->colorindex[ci];
  177417. dither = cquantize->odither[ci][row_index];
  177418. col_index = 0;
  177419. for (col = width; col > 0; col--) {
  177420. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  177421. * select output value, accumulate into output code for this pixel.
  177422. * Range-limiting need not be done explicitly, as we have extended
  177423. * the colorindex table to produce the right answers for out-of-range
  177424. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  177425. * required amount of padding.
  177426. */
  177427. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  177428. input_ptr += nc;
  177429. output_ptr++;
  177430. col_index = (col_index + 1) & ODITHER_MASK;
  177431. }
  177432. }
  177433. /* Advance row index for next row */
  177434. row_index = (row_index + 1) & ODITHER_MASK;
  177435. cquantize->row_index = row_index;
  177436. }
  177437. }
  177438. METHODDEF(void)
  177439. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177440. JSAMPARRAY output_buf, int num_rows)
  177441. /* Fast path for out_color_components==3, with ordered dithering */
  177442. {
  177443. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177444. register int pixcode;
  177445. register JSAMPROW input_ptr;
  177446. register JSAMPROW output_ptr;
  177447. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177448. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177449. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177450. int * dither0; /* points to active row of dither matrix */
  177451. int * dither1;
  177452. int * dither2;
  177453. int row_index, col_index; /* current indexes into dither matrix */
  177454. int row;
  177455. JDIMENSION col;
  177456. JDIMENSION width = cinfo->output_width;
  177457. for (row = 0; row < num_rows; row++) {
  177458. row_index = cquantize->row_index;
  177459. input_ptr = input_buf[row];
  177460. output_ptr = output_buf[row];
  177461. dither0 = cquantize->odither[0][row_index];
  177462. dither1 = cquantize->odither[1][row_index];
  177463. dither2 = cquantize->odither[2][row_index];
  177464. col_index = 0;
  177465. for (col = width; col > 0; col--) {
  177466. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  177467. dither0[col_index]]);
  177468. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  177469. dither1[col_index]]);
  177470. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  177471. dither2[col_index]]);
  177472. *output_ptr++ = (JSAMPLE) pixcode;
  177473. col_index = (col_index + 1) & ODITHER_MASK;
  177474. }
  177475. row_index = (row_index + 1) & ODITHER_MASK;
  177476. cquantize->row_index = row_index;
  177477. }
  177478. }
  177479. METHODDEF(void)
  177480. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177481. JSAMPARRAY output_buf, int num_rows)
  177482. /* General case, with Floyd-Steinberg dithering */
  177483. {
  177484. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177485. register LOCFSERROR cur; /* current error or pixel value */
  177486. LOCFSERROR belowerr; /* error for pixel below cur */
  177487. LOCFSERROR bpreverr; /* error for below/prev col */
  177488. LOCFSERROR bnexterr; /* error for below/next col */
  177489. LOCFSERROR delta;
  177490. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  177491. register JSAMPROW input_ptr;
  177492. register JSAMPROW output_ptr;
  177493. JSAMPROW colorindex_ci;
  177494. JSAMPROW colormap_ci;
  177495. int pixcode;
  177496. int nc = cinfo->out_color_components;
  177497. int dir; /* 1 for left-to-right, -1 for right-to-left */
  177498. int dirnc; /* dir * nc */
  177499. int ci;
  177500. int row;
  177501. JDIMENSION col;
  177502. JDIMENSION width = cinfo->output_width;
  177503. JSAMPLE *range_limit = cinfo->sample_range_limit;
  177504. SHIFT_TEMPS
  177505. for (row = 0; row < num_rows; row++) {
  177506. /* Initialize output values to 0 so can process components separately */
  177507. jzero_far((void FAR *) output_buf[row],
  177508. (size_t) (width * SIZEOF(JSAMPLE)));
  177509. for (ci = 0; ci < nc; ci++) {
  177510. input_ptr = input_buf[row] + ci;
  177511. output_ptr = output_buf[row];
  177512. if (cquantize->on_odd_row) {
  177513. /* work right to left in this row */
  177514. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  177515. output_ptr += width-1;
  177516. dir = -1;
  177517. dirnc = -nc;
  177518. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  177519. } else {
  177520. /* work left to right in this row */
  177521. dir = 1;
  177522. dirnc = nc;
  177523. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  177524. }
  177525. colorindex_ci = cquantize->colorindex[ci];
  177526. colormap_ci = cquantize->sv_colormap[ci];
  177527. /* Preset error values: no error propagated to first pixel from left */
  177528. cur = 0;
  177529. /* and no error propagated to row below yet */
  177530. belowerr = bpreverr = 0;
  177531. for (col = width; col > 0; col--) {
  177532. /* cur holds the error propagated from the previous pixel on the
  177533. * current line. Add the error propagated from the previous line
  177534. * to form the complete error correction term for this pixel, and
  177535. * round the error term (which is expressed * 16) to an integer.
  177536. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  177537. * for either sign of the error value.
  177538. * Note: errorptr points to *previous* column's array entry.
  177539. */
  177540. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  177541. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  177542. * The maximum error is +- MAXJSAMPLE; this sets the required size
  177543. * of the range_limit array.
  177544. */
  177545. cur += GETJSAMPLE(*input_ptr);
  177546. cur = GETJSAMPLE(range_limit[cur]);
  177547. /* Select output value, accumulate into output code for this pixel */
  177548. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  177549. *output_ptr += (JSAMPLE) pixcode;
  177550. /* Compute actual representation error at this pixel */
  177551. /* Note: we can do this even though we don't have the final */
  177552. /* pixel code, because the colormap is orthogonal. */
  177553. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  177554. /* Compute error fractions to be propagated to adjacent pixels.
  177555. * Add these into the running sums, and simultaneously shift the
  177556. * next-line error sums left by 1 column.
  177557. */
  177558. bnexterr = cur;
  177559. delta = cur * 2;
  177560. cur += delta; /* form error * 3 */
  177561. errorptr[0] = (FSERROR) (bpreverr + cur);
  177562. cur += delta; /* form error * 5 */
  177563. bpreverr = belowerr + cur;
  177564. belowerr = bnexterr;
  177565. cur += delta; /* form error * 7 */
  177566. /* At this point cur contains the 7/16 error value to be propagated
  177567. * to the next pixel on the current line, and all the errors for the
  177568. * next line have been shifted over. We are therefore ready to move on.
  177569. */
  177570. input_ptr += dirnc; /* advance input ptr to next column */
  177571. output_ptr += dir; /* advance output ptr to next column */
  177572. errorptr += dir; /* advance errorptr to current column */
  177573. }
  177574. /* Post-loop cleanup: we must unload the final error value into the
  177575. * final fserrors[] entry. Note we need not unload belowerr because
  177576. * it is for the dummy column before or after the actual array.
  177577. */
  177578. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  177579. }
  177580. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  177581. }
  177582. }
  177583. /*
  177584. * Allocate workspace for Floyd-Steinberg errors.
  177585. */
  177586. LOCAL(void)
  177587. alloc_fs_workspace (j_decompress_ptr cinfo)
  177588. {
  177589. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177590. size_t arraysize;
  177591. int i;
  177592. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177593. for (i = 0; i < cinfo->out_color_components; i++) {
  177594. cquantize->fserrors[i] = (FSERRPTR)
  177595. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  177596. }
  177597. }
  177598. /*
  177599. * Initialize for one-pass color quantization.
  177600. */
  177601. METHODDEF(void)
  177602. start_pass_1_quant (j_decompress_ptr cinfo, boolean)
  177603. {
  177604. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177605. size_t arraysize;
  177606. int i;
  177607. /* Install my colormap. */
  177608. cinfo->colormap = cquantize->sv_colormap;
  177609. cinfo->actual_number_of_colors = cquantize->sv_actual;
  177610. /* Initialize for desired dithering mode. */
  177611. switch (cinfo->dither_mode) {
  177612. case JDITHER_NONE:
  177613. if (cinfo->out_color_components == 3)
  177614. cquantize->pub.color_quantize = color_quantize3;
  177615. else
  177616. cquantize->pub.color_quantize = color_quantize;
  177617. break;
  177618. case JDITHER_ORDERED:
  177619. if (cinfo->out_color_components == 3)
  177620. cquantize->pub.color_quantize = quantize3_ord_dither;
  177621. else
  177622. cquantize->pub.color_quantize = quantize_ord_dither;
  177623. cquantize->row_index = 0; /* initialize state for ordered dither */
  177624. /* If user changed to ordered dither from another mode,
  177625. * we must recreate the color index table with padding.
  177626. * This will cost extra space, but probably isn't very likely.
  177627. */
  177628. if (! cquantize->is_padded)
  177629. create_colorindex(cinfo);
  177630. /* Create ordered-dither tables if we didn't already. */
  177631. if (cquantize->odither[0] == NULL)
  177632. create_odither_tables(cinfo);
  177633. break;
  177634. case JDITHER_FS:
  177635. cquantize->pub.color_quantize = quantize_fs_dither;
  177636. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  177637. /* Allocate Floyd-Steinberg workspace if didn't already. */
  177638. if (cquantize->fserrors[0] == NULL)
  177639. alloc_fs_workspace(cinfo);
  177640. /* Initialize the propagated errors to zero. */
  177641. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177642. for (i = 0; i < cinfo->out_color_components; i++)
  177643. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  177644. break;
  177645. default:
  177646. ERREXIT(cinfo, JERR_NOT_COMPILED);
  177647. break;
  177648. }
  177649. }
  177650. /*
  177651. * Finish up at the end of the pass.
  177652. */
  177653. METHODDEF(void)
  177654. finish_pass_1_quant (j_decompress_ptr)
  177655. {
  177656. /* no work in 1-pass case */
  177657. }
  177658. /*
  177659. * Switch to a new external colormap between output passes.
  177660. * Shouldn't get to this module!
  177661. */
  177662. METHODDEF(void)
  177663. new_color_map_1_quant (j_decompress_ptr cinfo)
  177664. {
  177665. ERREXIT(cinfo, JERR_MODE_CHANGE);
  177666. }
  177667. /*
  177668. * Module initialization routine for 1-pass color quantization.
  177669. */
  177670. GLOBAL(void)
  177671. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  177672. {
  177673. my_cquantize_ptr cquantize;
  177674. cquantize = (my_cquantize_ptr)
  177675. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177676. SIZEOF(my_cquantizer));
  177677. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  177678. cquantize->pub.start_pass = start_pass_1_quant;
  177679. cquantize->pub.finish_pass = finish_pass_1_quant;
  177680. cquantize->pub.new_color_map = new_color_map_1_quant;
  177681. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  177682. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  177683. /* Make sure my internal arrays won't overflow */
  177684. if (cinfo->out_color_components > MAX_Q_COMPS)
  177685. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  177686. /* Make sure colormap indexes can be represented by JSAMPLEs */
  177687. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  177688. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  177689. /* Create the colormap and color index table. */
  177690. create_colormap(cinfo);
  177691. create_colorindex(cinfo);
  177692. /* Allocate Floyd-Steinberg workspace now if requested.
  177693. * We do this now since it is FAR storage and may affect the memory
  177694. * manager's space calculations. If the user changes to FS dither
  177695. * mode in a later pass, we will allocate the space then, and will
  177696. * possibly overrun the max_memory_to_use setting.
  177697. */
  177698. if (cinfo->dither_mode == JDITHER_FS)
  177699. alloc_fs_workspace(cinfo);
  177700. }
  177701. #endif /* QUANT_1PASS_SUPPORTED */
  177702. /*** End of inlined file: jquant1.c ***/
  177703. /*** Start of inlined file: jquant2.c ***/
  177704. #define JPEG_INTERNALS
  177705. #ifdef QUANT_2PASS_SUPPORTED
  177706. /*
  177707. * This module implements the well-known Heckbert paradigm for color
  177708. * quantization. Most of the ideas used here can be traced back to
  177709. * Heckbert's seminal paper
  177710. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  177711. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  177712. *
  177713. * In the first pass over the image, we accumulate a histogram showing the
  177714. * usage count of each possible color. To keep the histogram to a reasonable
  177715. * size, we reduce the precision of the input; typical practice is to retain
  177716. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  177717. * in the same histogram cell.
  177718. *
  177719. * Next, the color-selection step begins with a box representing the whole
  177720. * color space, and repeatedly splits the "largest" remaining box until we
  177721. * have as many boxes as desired colors. Then the mean color in each
  177722. * remaining box becomes one of the possible output colors.
  177723. *
  177724. * The second pass over the image maps each input pixel to the closest output
  177725. * color (optionally after applying a Floyd-Steinberg dithering correction).
  177726. * This mapping is logically trivial, but making it go fast enough requires
  177727. * considerable care.
  177728. *
  177729. * Heckbert-style quantizers vary a good deal in their policies for choosing
  177730. * the "largest" box and deciding where to cut it. The particular policies
  177731. * used here have proved out well in experimental comparisons, but better ones
  177732. * may yet be found.
  177733. *
  177734. * In earlier versions of the IJG code, this module quantized in YCbCr color
  177735. * space, processing the raw upsampled data without a color conversion step.
  177736. * This allowed the color conversion math to be done only once per colormap
  177737. * entry, not once per pixel. However, that optimization precluded other
  177738. * useful optimizations (such as merging color conversion with upsampling)
  177739. * and it also interfered with desired capabilities such as quantizing to an
  177740. * externally-supplied colormap. We have therefore abandoned that approach.
  177741. * The present code works in the post-conversion color space, typically RGB.
  177742. *
  177743. * To improve the visual quality of the results, we actually work in scaled
  177744. * RGB space, giving G distances more weight than R, and R in turn more than
  177745. * B. To do everything in integer math, we must use integer scale factors.
  177746. * The 2/3/1 scale factors used here correspond loosely to the relative
  177747. * weights of the colors in the NTSC grayscale equation.
  177748. * If you want to use this code to quantize a non-RGB color space, you'll
  177749. * probably need to change these scale factors.
  177750. */
  177751. #define R_SCALE 2 /* scale R distances by this much */
  177752. #define G_SCALE 3 /* scale G distances by this much */
  177753. #define B_SCALE 1 /* and B by this much */
  177754. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  177755. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  177756. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  177757. * you'll get compile errors until you extend this logic. In that case
  177758. * you'll probably want to tweak the histogram sizes too.
  177759. */
  177760. #if RGB_RED == 0
  177761. #define C0_SCALE R_SCALE
  177762. #endif
  177763. #if RGB_BLUE == 0
  177764. #define C0_SCALE B_SCALE
  177765. #endif
  177766. #if RGB_GREEN == 1
  177767. #define C1_SCALE G_SCALE
  177768. #endif
  177769. #if RGB_RED == 2
  177770. #define C2_SCALE R_SCALE
  177771. #endif
  177772. #if RGB_BLUE == 2
  177773. #define C2_SCALE B_SCALE
  177774. #endif
  177775. /*
  177776. * First we have the histogram data structure and routines for creating it.
  177777. *
  177778. * The number of bits of precision can be adjusted by changing these symbols.
  177779. * We recommend keeping 6 bits for G and 5 each for R and B.
  177780. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  177781. * better results; if you are short of memory, 5 bits all around will save
  177782. * some space but degrade the results.
  177783. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  177784. * (preferably unsigned long) for each cell. In practice this is overkill;
  177785. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  177786. * and clamping those that do overflow to the maximum value will give close-
  177787. * enough results. This reduces the recommended histogram size from 256Kb
  177788. * to 128Kb, which is a useful savings on PC-class machines.
  177789. * (In the second pass the histogram space is re-used for pixel mapping data;
  177790. * in that capacity, each cell must be able to store zero to the number of
  177791. * desired colors. 16 bits/cell is plenty for that too.)
  177792. * Since the JPEG code is intended to run in small memory model on 80x86
  177793. * machines, we can't just allocate the histogram in one chunk. Instead
  177794. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  177795. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  177796. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  177797. * on 80x86 machines, the pointer row is in near memory but the actual
  177798. * arrays are in far memory (same arrangement as we use for image arrays).
  177799. */
  177800. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  177801. /* These will do the right thing for either R,G,B or B,G,R color order,
  177802. * but you may not like the results for other color orders.
  177803. */
  177804. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  177805. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  177806. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  177807. /* Number of elements along histogram axes. */
  177808. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  177809. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  177810. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  177811. /* These are the amounts to shift an input value to get a histogram index. */
  177812. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  177813. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  177814. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  177815. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  177816. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  177817. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  177818. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  177819. typedef hist2d * hist3d; /* type for top-level pointer */
  177820. /* Declarations for Floyd-Steinberg dithering.
  177821. *
  177822. * Errors are accumulated into the array fserrors[], at a resolution of
  177823. * 1/16th of a pixel count. The error at a given pixel is propagated
  177824. * to its not-yet-processed neighbors using the standard F-S fractions,
  177825. * ... (here) 7/16
  177826. * 3/16 5/16 1/16
  177827. * We work left-to-right on even rows, right-to-left on odd rows.
  177828. *
  177829. * We can get away with a single array (holding one row's worth of errors)
  177830. * by using it to store the current row's errors at pixel columns not yet
  177831. * processed, but the next row's errors at columns already processed. We
  177832. * need only a few extra variables to hold the errors immediately around the
  177833. * current column. (If we are lucky, those variables are in registers, but
  177834. * even if not, they're probably cheaper to access than array elements are.)
  177835. *
  177836. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  177837. * each end saves us from special-casing the first and last pixels.
  177838. * Each entry is three values long, one value for each color component.
  177839. *
  177840. * Note: on a wide image, we might not have enough room in a PC's near data
  177841. * segment to hold the error array; so it is allocated with alloc_large.
  177842. */
  177843. #if BITS_IN_JSAMPLE == 8
  177844. typedef INT16 FSERROR; /* 16 bits should be enough */
  177845. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  177846. #else
  177847. typedef INT32 FSERROR; /* may need more than 16 bits */
  177848. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  177849. #endif
  177850. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  177851. /* Private subobject */
  177852. typedef struct {
  177853. struct jpeg_color_quantizer pub; /* public fields */
  177854. /* Space for the eventually created colormap is stashed here */
  177855. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  177856. int desired; /* desired # of colors = size of colormap */
  177857. /* Variables for accumulating image statistics */
  177858. hist3d histogram; /* pointer to the histogram */
  177859. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  177860. /* Variables for Floyd-Steinberg dithering */
  177861. FSERRPTR fserrors; /* accumulated errors */
  177862. boolean on_odd_row; /* flag to remember which row we are on */
  177863. int * error_limiter; /* table for clamping the applied error */
  177864. } my_cquantizer2;
  177865. typedef my_cquantizer2 * my_cquantize_ptr2;
  177866. /*
  177867. * Prescan some rows of pixels.
  177868. * In this module the prescan simply updates the histogram, which has been
  177869. * initialized to zeroes by start_pass.
  177870. * An output_buf parameter is required by the method signature, but no data
  177871. * is actually output (in fact the buffer controller is probably passing a
  177872. * NULL pointer).
  177873. */
  177874. METHODDEF(void)
  177875. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177876. JSAMPARRAY, int num_rows)
  177877. {
  177878. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177879. register JSAMPROW ptr;
  177880. register histptr histp;
  177881. register hist3d histogram = cquantize->histogram;
  177882. int row;
  177883. JDIMENSION col;
  177884. JDIMENSION width = cinfo->output_width;
  177885. for (row = 0; row < num_rows; row++) {
  177886. ptr = input_buf[row];
  177887. for (col = width; col > 0; col--) {
  177888. /* get pixel value and index into the histogram */
  177889. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  177890. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  177891. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  177892. /* increment, check for overflow and undo increment if so. */
  177893. if (++(*histp) <= 0)
  177894. (*histp)--;
  177895. ptr += 3;
  177896. }
  177897. }
  177898. }
  177899. /*
  177900. * Next we have the really interesting routines: selection of a colormap
  177901. * given the completed histogram.
  177902. * These routines work with a list of "boxes", each representing a rectangular
  177903. * subset of the input color space (to histogram precision).
  177904. */
  177905. typedef struct {
  177906. /* The bounds of the box (inclusive); expressed as histogram indexes */
  177907. int c0min, c0max;
  177908. int c1min, c1max;
  177909. int c2min, c2max;
  177910. /* The volume (actually 2-norm) of the box */
  177911. INT32 volume;
  177912. /* The number of nonzero histogram cells within this box */
  177913. long colorcount;
  177914. } box;
  177915. typedef box * boxptr;
  177916. LOCAL(boxptr)
  177917. find_biggest_color_pop (boxptr boxlist, int numboxes)
  177918. /* Find the splittable box with the largest color population */
  177919. /* Returns NULL if no splittable boxes remain */
  177920. {
  177921. register boxptr boxp;
  177922. register int i;
  177923. register long maxc = 0;
  177924. boxptr which = NULL;
  177925. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  177926. if (boxp->colorcount > maxc && boxp->volume > 0) {
  177927. which = boxp;
  177928. maxc = boxp->colorcount;
  177929. }
  177930. }
  177931. return which;
  177932. }
  177933. LOCAL(boxptr)
  177934. find_biggest_volume (boxptr boxlist, int numboxes)
  177935. /* Find the splittable box with the largest (scaled) volume */
  177936. /* Returns NULL if no splittable boxes remain */
  177937. {
  177938. register boxptr boxp;
  177939. register int i;
  177940. register INT32 maxv = 0;
  177941. boxptr which = NULL;
  177942. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  177943. if (boxp->volume > maxv) {
  177944. which = boxp;
  177945. maxv = boxp->volume;
  177946. }
  177947. }
  177948. return which;
  177949. }
  177950. LOCAL(void)
  177951. update_box (j_decompress_ptr cinfo, boxptr boxp)
  177952. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  177953. /* and recompute its volume and population */
  177954. {
  177955. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  177956. hist3d histogram = cquantize->histogram;
  177957. histptr histp;
  177958. int c0,c1,c2;
  177959. int c0min,c0max,c1min,c1max,c2min,c2max;
  177960. INT32 dist0,dist1,dist2;
  177961. long ccount;
  177962. c0min = boxp->c0min; c0max = boxp->c0max;
  177963. c1min = boxp->c1min; c1max = boxp->c1max;
  177964. c2min = boxp->c2min; c2max = boxp->c2max;
  177965. if (c0max > c0min)
  177966. for (c0 = c0min; c0 <= c0max; c0++)
  177967. for (c1 = c1min; c1 <= c1max; c1++) {
  177968. histp = & histogram[c0][c1][c2min];
  177969. for (c2 = c2min; c2 <= c2max; c2++)
  177970. if (*histp++ != 0) {
  177971. boxp->c0min = c0min = c0;
  177972. goto have_c0min;
  177973. }
  177974. }
  177975. have_c0min:
  177976. if (c0max > c0min)
  177977. for (c0 = c0max; c0 >= c0min; c0--)
  177978. for (c1 = c1min; c1 <= c1max; c1++) {
  177979. histp = & histogram[c0][c1][c2min];
  177980. for (c2 = c2min; c2 <= c2max; c2++)
  177981. if (*histp++ != 0) {
  177982. boxp->c0max = c0max = c0;
  177983. goto have_c0max;
  177984. }
  177985. }
  177986. have_c0max:
  177987. if (c1max > c1min)
  177988. for (c1 = c1min; c1 <= c1max; c1++)
  177989. for (c0 = c0min; c0 <= c0max; c0++) {
  177990. histp = & histogram[c0][c1][c2min];
  177991. for (c2 = c2min; c2 <= c2max; c2++)
  177992. if (*histp++ != 0) {
  177993. boxp->c1min = c1min = c1;
  177994. goto have_c1min;
  177995. }
  177996. }
  177997. have_c1min:
  177998. if (c1max > c1min)
  177999. for (c1 = c1max; c1 >= c1min; c1--)
  178000. for (c0 = c0min; c0 <= c0max; c0++) {
  178001. histp = & histogram[c0][c1][c2min];
  178002. for (c2 = c2min; c2 <= c2max; c2++)
  178003. if (*histp++ != 0) {
  178004. boxp->c1max = c1max = c1;
  178005. goto have_c1max;
  178006. }
  178007. }
  178008. have_c1max:
  178009. if (c2max > c2min)
  178010. for (c2 = c2min; c2 <= c2max; c2++)
  178011. for (c0 = c0min; c0 <= c0max; c0++) {
  178012. histp = & histogram[c0][c1min][c2];
  178013. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  178014. if (*histp != 0) {
  178015. boxp->c2min = c2min = c2;
  178016. goto have_c2min;
  178017. }
  178018. }
  178019. have_c2min:
  178020. if (c2max > c2min)
  178021. for (c2 = c2max; c2 >= c2min; c2--)
  178022. for (c0 = c0min; c0 <= c0max; c0++) {
  178023. histp = & histogram[c0][c1min][c2];
  178024. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  178025. if (*histp != 0) {
  178026. boxp->c2max = c2max = c2;
  178027. goto have_c2max;
  178028. }
  178029. }
  178030. have_c2max:
  178031. /* Update box volume.
  178032. * We use 2-norm rather than real volume here; this biases the method
  178033. * against making long narrow boxes, and it has the side benefit that
  178034. * a box is splittable iff norm > 0.
  178035. * Since the differences are expressed in histogram-cell units,
  178036. * we have to shift back to JSAMPLE units to get consistent distances;
  178037. * after which, we scale according to the selected distance scale factors.
  178038. */
  178039. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  178040. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  178041. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  178042. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  178043. /* Now scan remaining volume of box and compute population */
  178044. ccount = 0;
  178045. for (c0 = c0min; c0 <= c0max; c0++)
  178046. for (c1 = c1min; c1 <= c1max; c1++) {
  178047. histp = & histogram[c0][c1][c2min];
  178048. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  178049. if (*histp != 0) {
  178050. ccount++;
  178051. }
  178052. }
  178053. boxp->colorcount = ccount;
  178054. }
  178055. LOCAL(int)
  178056. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  178057. int desired_colors)
  178058. /* Repeatedly select and split the largest box until we have enough boxes */
  178059. {
  178060. int n,lb;
  178061. int c0,c1,c2,cmax;
  178062. register boxptr b1,b2;
  178063. while (numboxes < desired_colors) {
  178064. /* Select box to split.
  178065. * Current algorithm: by population for first half, then by volume.
  178066. */
  178067. if (numboxes*2 <= desired_colors) {
  178068. b1 = find_biggest_color_pop(boxlist, numboxes);
  178069. } else {
  178070. b1 = find_biggest_volume(boxlist, numboxes);
  178071. }
  178072. if (b1 == NULL) /* no splittable boxes left! */
  178073. break;
  178074. b2 = &boxlist[numboxes]; /* where new box will go */
  178075. /* Copy the color bounds to the new box. */
  178076. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  178077. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  178078. /* Choose which axis to split the box on.
  178079. * Current algorithm: longest scaled axis.
  178080. * See notes in update_box about scaling distances.
  178081. */
  178082. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  178083. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  178084. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  178085. /* We want to break any ties in favor of green, then red, blue last.
  178086. * This code does the right thing for R,G,B or B,G,R color orders only.
  178087. */
  178088. #if RGB_RED == 0
  178089. cmax = c1; n = 1;
  178090. if (c0 > cmax) { cmax = c0; n = 0; }
  178091. if (c2 > cmax) { n = 2; }
  178092. #else
  178093. cmax = c1; n = 1;
  178094. if (c2 > cmax) { cmax = c2; n = 2; }
  178095. if (c0 > cmax) { n = 0; }
  178096. #endif
  178097. /* Choose split point along selected axis, and update box bounds.
  178098. * Current algorithm: split at halfway point.
  178099. * (Since the box has been shrunk to minimum volume,
  178100. * any split will produce two nonempty subboxes.)
  178101. * Note that lb value is max for lower box, so must be < old max.
  178102. */
  178103. switch (n) {
  178104. case 0:
  178105. lb = (b1->c0max + b1->c0min) / 2;
  178106. b1->c0max = lb;
  178107. b2->c0min = lb+1;
  178108. break;
  178109. case 1:
  178110. lb = (b1->c1max + b1->c1min) / 2;
  178111. b1->c1max = lb;
  178112. b2->c1min = lb+1;
  178113. break;
  178114. case 2:
  178115. lb = (b1->c2max + b1->c2min) / 2;
  178116. b1->c2max = lb;
  178117. b2->c2min = lb+1;
  178118. break;
  178119. }
  178120. /* Update stats for boxes */
  178121. update_box(cinfo, b1);
  178122. update_box(cinfo, b2);
  178123. numboxes++;
  178124. }
  178125. return numboxes;
  178126. }
  178127. LOCAL(void)
  178128. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  178129. /* Compute representative color for a box, put it in colormap[icolor] */
  178130. {
  178131. /* Current algorithm: mean weighted by pixels (not colors) */
  178132. /* Note it is important to get the rounding correct! */
  178133. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178134. hist3d histogram = cquantize->histogram;
  178135. histptr histp;
  178136. int c0,c1,c2;
  178137. int c0min,c0max,c1min,c1max,c2min,c2max;
  178138. long count;
  178139. long total = 0;
  178140. long c0total = 0;
  178141. long c1total = 0;
  178142. long c2total = 0;
  178143. c0min = boxp->c0min; c0max = boxp->c0max;
  178144. c1min = boxp->c1min; c1max = boxp->c1max;
  178145. c2min = boxp->c2min; c2max = boxp->c2max;
  178146. for (c0 = c0min; c0 <= c0max; c0++)
  178147. for (c1 = c1min; c1 <= c1max; c1++) {
  178148. histp = & histogram[c0][c1][c2min];
  178149. for (c2 = c2min; c2 <= c2max; c2++) {
  178150. if ((count = *histp++) != 0) {
  178151. total += count;
  178152. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  178153. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  178154. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  178155. }
  178156. }
  178157. }
  178158. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  178159. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  178160. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  178161. }
  178162. LOCAL(void)
  178163. select_colors (j_decompress_ptr cinfo, int desired_colors)
  178164. /* Master routine for color selection */
  178165. {
  178166. boxptr boxlist;
  178167. int numboxes;
  178168. int i;
  178169. /* Allocate workspace for box list */
  178170. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  178171. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  178172. /* Initialize one box containing whole space */
  178173. numboxes = 1;
  178174. boxlist[0].c0min = 0;
  178175. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  178176. boxlist[0].c1min = 0;
  178177. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  178178. boxlist[0].c2min = 0;
  178179. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  178180. /* Shrink it to actually-used volume and set its statistics */
  178181. update_box(cinfo, & boxlist[0]);
  178182. /* Perform median-cut to produce final box list */
  178183. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  178184. /* Compute the representative color for each box, fill colormap */
  178185. for (i = 0; i < numboxes; i++)
  178186. compute_color(cinfo, & boxlist[i], i);
  178187. cinfo->actual_number_of_colors = numboxes;
  178188. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  178189. }
  178190. /*
  178191. * These routines are concerned with the time-critical task of mapping input
  178192. * colors to the nearest color in the selected colormap.
  178193. *
  178194. * We re-use the histogram space as an "inverse color map", essentially a
  178195. * cache for the results of nearest-color searches. All colors within a
  178196. * histogram cell will be mapped to the same colormap entry, namely the one
  178197. * closest to the cell's center. This may not be quite the closest entry to
  178198. * the actual input color, but it's almost as good. A zero in the cache
  178199. * indicates we haven't found the nearest color for that cell yet; the array
  178200. * is cleared to zeroes before starting the mapping pass. When we find the
  178201. * nearest color for a cell, its colormap index plus one is recorded in the
  178202. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  178203. * when they need to use an unfilled entry in the cache.
  178204. *
  178205. * Our method of efficiently finding nearest colors is based on the "locally
  178206. * sorted search" idea described by Heckbert and on the incremental distance
  178207. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  178208. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  178209. * the distances from a given colormap entry to each cell of the histogram can
  178210. * be computed quickly using an incremental method: the differences between
  178211. * distances to adjacent cells themselves differ by a constant. This allows a
  178212. * fairly fast implementation of the "brute force" approach of computing the
  178213. * distance from every colormap entry to every histogram cell. Unfortunately,
  178214. * it needs a work array to hold the best-distance-so-far for each histogram
  178215. * cell (because the inner loop has to be over cells, not colormap entries).
  178216. * The work array elements have to be INT32s, so the work array would need
  178217. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  178218. *
  178219. * To get around these problems, we apply Thomas' method to compute the
  178220. * nearest colors for only the cells within a small subbox of the histogram.
  178221. * The work array need be only as big as the subbox, so the memory usage
  178222. * problem is solved. Furthermore, we need not fill subboxes that are never
  178223. * referenced in pass2; many images use only part of the color gamut, so a
  178224. * fair amount of work is saved. An additional advantage of this
  178225. * approach is that we can apply Heckbert's locality criterion to quickly
  178226. * eliminate colormap entries that are far away from the subbox; typically
  178227. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  178228. * and we need not compute their distances to individual cells in the subbox.
  178229. * The speed of this approach is heavily influenced by the subbox size: too
  178230. * small means too much overhead, too big loses because Heckbert's criterion
  178231. * can't eliminate as many colormap entries. Empirically the best subbox
  178232. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  178233. *
  178234. * Thomas' article also describes a refined method which is asymptotically
  178235. * faster than the brute-force method, but it is also far more complex and
  178236. * cannot efficiently be applied to small subboxes. It is therefore not
  178237. * useful for programs intended to be portable to DOS machines. On machines
  178238. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  178239. * refined method might be faster than the present code --- but then again,
  178240. * it might not be any faster, and it's certainly more complicated.
  178241. */
  178242. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  178243. #define BOX_C0_LOG (HIST_C0_BITS-3)
  178244. #define BOX_C1_LOG (HIST_C1_BITS-3)
  178245. #define BOX_C2_LOG (HIST_C2_BITS-3)
  178246. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  178247. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  178248. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  178249. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  178250. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  178251. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  178252. /*
  178253. * The next three routines implement inverse colormap filling. They could
  178254. * all be folded into one big routine, but splitting them up this way saves
  178255. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  178256. * and may allow some compilers to produce better code by registerizing more
  178257. * inner-loop variables.
  178258. */
  178259. LOCAL(int)
  178260. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178261. JSAMPLE colorlist[])
  178262. /* Locate the colormap entries close enough to an update box to be candidates
  178263. * for the nearest entry to some cell(s) in the update box. The update box
  178264. * is specified by the center coordinates of its first cell. The number of
  178265. * candidate colormap entries is returned, and their colormap indexes are
  178266. * placed in colorlist[].
  178267. * This routine uses Heckbert's "locally sorted search" criterion to select
  178268. * the colors that need further consideration.
  178269. */
  178270. {
  178271. int numcolors = cinfo->actual_number_of_colors;
  178272. int maxc0, maxc1, maxc2;
  178273. int centerc0, centerc1, centerc2;
  178274. int i, x, ncolors;
  178275. INT32 minmaxdist, min_dist, max_dist, tdist;
  178276. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  178277. /* Compute true coordinates of update box's upper corner and center.
  178278. * Actually we compute the coordinates of the center of the upper-corner
  178279. * histogram cell, which are the upper bounds of the volume we care about.
  178280. * Note that since ">>" rounds down, the "center" values may be closer to
  178281. * min than to max; hence comparisons to them must be "<=", not "<".
  178282. */
  178283. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  178284. centerc0 = (minc0 + maxc0) >> 1;
  178285. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  178286. centerc1 = (minc1 + maxc1) >> 1;
  178287. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  178288. centerc2 = (minc2 + maxc2) >> 1;
  178289. /* For each color in colormap, find:
  178290. * 1. its minimum squared-distance to any point in the update box
  178291. * (zero if color is within update box);
  178292. * 2. its maximum squared-distance to any point in the update box.
  178293. * Both of these can be found by considering only the corners of the box.
  178294. * We save the minimum distance for each color in mindist[];
  178295. * only the smallest maximum distance is of interest.
  178296. */
  178297. minmaxdist = 0x7FFFFFFFL;
  178298. for (i = 0; i < numcolors; i++) {
  178299. /* We compute the squared-c0-distance term, then add in the other two. */
  178300. x = GETJSAMPLE(cinfo->colormap[0][i]);
  178301. if (x < minc0) {
  178302. tdist = (x - minc0) * C0_SCALE;
  178303. min_dist = tdist*tdist;
  178304. tdist = (x - maxc0) * C0_SCALE;
  178305. max_dist = tdist*tdist;
  178306. } else if (x > maxc0) {
  178307. tdist = (x - maxc0) * C0_SCALE;
  178308. min_dist = tdist*tdist;
  178309. tdist = (x - minc0) * C0_SCALE;
  178310. max_dist = tdist*tdist;
  178311. } else {
  178312. /* within cell range so no contribution to min_dist */
  178313. min_dist = 0;
  178314. if (x <= centerc0) {
  178315. tdist = (x - maxc0) * C0_SCALE;
  178316. max_dist = tdist*tdist;
  178317. } else {
  178318. tdist = (x - minc0) * C0_SCALE;
  178319. max_dist = tdist*tdist;
  178320. }
  178321. }
  178322. x = GETJSAMPLE(cinfo->colormap[1][i]);
  178323. if (x < minc1) {
  178324. tdist = (x - minc1) * C1_SCALE;
  178325. min_dist += tdist*tdist;
  178326. tdist = (x - maxc1) * C1_SCALE;
  178327. max_dist += tdist*tdist;
  178328. } else if (x > maxc1) {
  178329. tdist = (x - maxc1) * C1_SCALE;
  178330. min_dist += tdist*tdist;
  178331. tdist = (x - minc1) * C1_SCALE;
  178332. max_dist += tdist*tdist;
  178333. } else {
  178334. /* within cell range so no contribution to min_dist */
  178335. if (x <= centerc1) {
  178336. tdist = (x - maxc1) * C1_SCALE;
  178337. max_dist += tdist*tdist;
  178338. } else {
  178339. tdist = (x - minc1) * C1_SCALE;
  178340. max_dist += tdist*tdist;
  178341. }
  178342. }
  178343. x = GETJSAMPLE(cinfo->colormap[2][i]);
  178344. if (x < minc2) {
  178345. tdist = (x - minc2) * C2_SCALE;
  178346. min_dist += tdist*tdist;
  178347. tdist = (x - maxc2) * C2_SCALE;
  178348. max_dist += tdist*tdist;
  178349. } else if (x > maxc2) {
  178350. tdist = (x - maxc2) * C2_SCALE;
  178351. min_dist += tdist*tdist;
  178352. tdist = (x - minc2) * C2_SCALE;
  178353. max_dist += tdist*tdist;
  178354. } else {
  178355. /* within cell range so no contribution to min_dist */
  178356. if (x <= centerc2) {
  178357. tdist = (x - maxc2) * C2_SCALE;
  178358. max_dist += tdist*tdist;
  178359. } else {
  178360. tdist = (x - minc2) * C2_SCALE;
  178361. max_dist += tdist*tdist;
  178362. }
  178363. }
  178364. mindist[i] = min_dist; /* save away the results */
  178365. if (max_dist < minmaxdist)
  178366. minmaxdist = max_dist;
  178367. }
  178368. /* Now we know that no cell in the update box is more than minmaxdist
  178369. * away from some colormap entry. Therefore, only colors that are
  178370. * within minmaxdist of some part of the box need be considered.
  178371. */
  178372. ncolors = 0;
  178373. for (i = 0; i < numcolors; i++) {
  178374. if (mindist[i] <= minmaxdist)
  178375. colorlist[ncolors++] = (JSAMPLE) i;
  178376. }
  178377. return ncolors;
  178378. }
  178379. LOCAL(void)
  178380. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178381. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  178382. /* Find the closest colormap entry for each cell in the update box,
  178383. * given the list of candidate colors prepared by find_nearby_colors.
  178384. * Return the indexes of the closest entries in the bestcolor[] array.
  178385. * This routine uses Thomas' incremental distance calculation method to
  178386. * find the distance from a colormap entry to successive cells in the box.
  178387. */
  178388. {
  178389. int ic0, ic1, ic2;
  178390. int i, icolor;
  178391. register INT32 * bptr; /* pointer into bestdist[] array */
  178392. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178393. INT32 dist0, dist1; /* initial distance values */
  178394. register INT32 dist2; /* current distance in inner loop */
  178395. INT32 xx0, xx1; /* distance increments */
  178396. register INT32 xx2;
  178397. INT32 inc0, inc1, inc2; /* initial values for increments */
  178398. /* This array holds the distance to the nearest-so-far color for each cell */
  178399. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178400. /* Initialize best-distance for each cell of the update box */
  178401. bptr = bestdist;
  178402. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  178403. *bptr++ = 0x7FFFFFFFL;
  178404. /* For each color selected by find_nearby_colors,
  178405. * compute its distance to the center of each cell in the box.
  178406. * If that's less than best-so-far, update best distance and color number.
  178407. */
  178408. /* Nominal steps between cell centers ("x" in Thomas article) */
  178409. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  178410. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  178411. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  178412. for (i = 0; i < numcolors; i++) {
  178413. icolor = GETJSAMPLE(colorlist[i]);
  178414. /* Compute (square of) distance from minc0/c1/c2 to this color */
  178415. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  178416. dist0 = inc0*inc0;
  178417. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  178418. dist0 += inc1*inc1;
  178419. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  178420. dist0 += inc2*inc2;
  178421. /* Form the initial difference increments */
  178422. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  178423. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  178424. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  178425. /* Now loop over all cells in box, updating distance per Thomas method */
  178426. bptr = bestdist;
  178427. cptr = bestcolor;
  178428. xx0 = inc0;
  178429. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  178430. dist1 = dist0;
  178431. xx1 = inc1;
  178432. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  178433. dist2 = dist1;
  178434. xx2 = inc2;
  178435. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  178436. if (dist2 < *bptr) {
  178437. *bptr = dist2;
  178438. *cptr = (JSAMPLE) icolor;
  178439. }
  178440. dist2 += xx2;
  178441. xx2 += 2 * STEP_C2 * STEP_C2;
  178442. bptr++;
  178443. cptr++;
  178444. }
  178445. dist1 += xx1;
  178446. xx1 += 2 * STEP_C1 * STEP_C1;
  178447. }
  178448. dist0 += xx0;
  178449. xx0 += 2 * STEP_C0 * STEP_C0;
  178450. }
  178451. }
  178452. }
  178453. LOCAL(void)
  178454. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  178455. /* Fill the inverse-colormap entries in the update box that contains */
  178456. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  178457. /* we can fill as many others as we wish.) */
  178458. {
  178459. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178460. hist3d histogram = cquantize->histogram;
  178461. int minc0, minc1, minc2; /* lower left corner of update box */
  178462. int ic0, ic1, ic2;
  178463. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178464. register histptr cachep; /* pointer into main cache array */
  178465. /* This array lists the candidate colormap indexes. */
  178466. JSAMPLE colorlist[MAXNUMCOLORS];
  178467. int numcolors; /* number of candidate colors */
  178468. /* This array holds the actually closest colormap index for each cell. */
  178469. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178470. /* Convert cell coordinates to update box ID */
  178471. c0 >>= BOX_C0_LOG;
  178472. c1 >>= BOX_C1_LOG;
  178473. c2 >>= BOX_C2_LOG;
  178474. /* Compute true coordinates of update box's origin corner.
  178475. * Actually we compute the coordinates of the center of the corner
  178476. * histogram cell, which are the lower bounds of the volume we care about.
  178477. */
  178478. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  178479. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  178480. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  178481. /* Determine which colormap entries are close enough to be candidates
  178482. * for the nearest entry to some cell in the update box.
  178483. */
  178484. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  178485. /* Determine the actually nearest colors. */
  178486. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  178487. bestcolor);
  178488. /* Save the best color numbers (plus 1) in the main cache array */
  178489. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  178490. c1 <<= BOX_C1_LOG;
  178491. c2 <<= BOX_C2_LOG;
  178492. cptr = bestcolor;
  178493. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  178494. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  178495. cachep = & histogram[c0+ic0][c1+ic1][c2];
  178496. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  178497. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  178498. }
  178499. }
  178500. }
  178501. }
  178502. /*
  178503. * Map some rows of pixels to the output colormapped representation.
  178504. */
  178505. METHODDEF(void)
  178506. pass2_no_dither (j_decompress_ptr cinfo,
  178507. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178508. /* This version performs no dithering */
  178509. {
  178510. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178511. hist3d histogram = cquantize->histogram;
  178512. register JSAMPROW inptr, outptr;
  178513. register histptr cachep;
  178514. register int c0, c1, c2;
  178515. int row;
  178516. JDIMENSION col;
  178517. JDIMENSION width = cinfo->output_width;
  178518. for (row = 0; row < num_rows; row++) {
  178519. inptr = input_buf[row];
  178520. outptr = output_buf[row];
  178521. for (col = width; col > 0; col--) {
  178522. /* get pixel value and index into the cache */
  178523. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  178524. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  178525. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  178526. cachep = & histogram[c0][c1][c2];
  178527. /* If we have not seen this color before, find nearest colormap entry */
  178528. /* and update the cache */
  178529. if (*cachep == 0)
  178530. fill_inverse_cmap(cinfo, c0,c1,c2);
  178531. /* Now emit the colormap index for this cell */
  178532. *outptr++ = (JSAMPLE) (*cachep - 1);
  178533. }
  178534. }
  178535. }
  178536. METHODDEF(void)
  178537. pass2_fs_dither (j_decompress_ptr cinfo,
  178538. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178539. /* This version performs Floyd-Steinberg dithering */
  178540. {
  178541. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178542. hist3d histogram = cquantize->histogram;
  178543. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  178544. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  178545. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  178546. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  178547. JSAMPROW inptr; /* => current input pixel */
  178548. JSAMPROW outptr; /* => current output pixel */
  178549. histptr cachep;
  178550. int dir; /* +1 or -1 depending on direction */
  178551. int dir3; /* 3*dir, for advancing inptr & errorptr */
  178552. int row;
  178553. JDIMENSION col;
  178554. JDIMENSION width = cinfo->output_width;
  178555. JSAMPLE *range_limit = cinfo->sample_range_limit;
  178556. int *error_limit = cquantize->error_limiter;
  178557. JSAMPROW colormap0 = cinfo->colormap[0];
  178558. JSAMPROW colormap1 = cinfo->colormap[1];
  178559. JSAMPROW colormap2 = cinfo->colormap[2];
  178560. SHIFT_TEMPS
  178561. for (row = 0; row < num_rows; row++) {
  178562. inptr = input_buf[row];
  178563. outptr = output_buf[row];
  178564. if (cquantize->on_odd_row) {
  178565. /* work right to left in this row */
  178566. inptr += (width-1) * 3; /* so point to rightmost pixel */
  178567. outptr += width-1;
  178568. dir = -1;
  178569. dir3 = -3;
  178570. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  178571. cquantize->on_odd_row = FALSE; /* flip for next time */
  178572. } else {
  178573. /* work left to right in this row */
  178574. dir = 1;
  178575. dir3 = 3;
  178576. errorptr = cquantize->fserrors; /* => entry before first real column */
  178577. cquantize->on_odd_row = TRUE; /* flip for next time */
  178578. }
  178579. /* Preset error values: no error propagated to first pixel from left */
  178580. cur0 = cur1 = cur2 = 0;
  178581. /* and no error propagated to row below yet */
  178582. belowerr0 = belowerr1 = belowerr2 = 0;
  178583. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  178584. for (col = width; col > 0; col--) {
  178585. /* curN holds the error propagated from the previous pixel on the
  178586. * current line. Add the error propagated from the previous line
  178587. * to form the complete error correction term for this pixel, and
  178588. * round the error term (which is expressed * 16) to an integer.
  178589. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  178590. * for either sign of the error value.
  178591. * Note: errorptr points to *previous* column's array entry.
  178592. */
  178593. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  178594. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  178595. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  178596. /* Limit the error using transfer function set by init_error_limit.
  178597. * See comments with init_error_limit for rationale.
  178598. */
  178599. cur0 = error_limit[cur0];
  178600. cur1 = error_limit[cur1];
  178601. cur2 = error_limit[cur2];
  178602. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  178603. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  178604. * this sets the required size of the range_limit array.
  178605. */
  178606. cur0 += GETJSAMPLE(inptr[0]);
  178607. cur1 += GETJSAMPLE(inptr[1]);
  178608. cur2 += GETJSAMPLE(inptr[2]);
  178609. cur0 = GETJSAMPLE(range_limit[cur0]);
  178610. cur1 = GETJSAMPLE(range_limit[cur1]);
  178611. cur2 = GETJSAMPLE(range_limit[cur2]);
  178612. /* Index into the cache with adjusted pixel value */
  178613. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  178614. /* If we have not seen this color before, find nearest colormap */
  178615. /* entry and update the cache */
  178616. if (*cachep == 0)
  178617. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  178618. /* Now emit the colormap index for this cell */
  178619. { register int pixcode = *cachep - 1;
  178620. *outptr = (JSAMPLE) pixcode;
  178621. /* Compute representation error for this pixel */
  178622. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  178623. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  178624. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  178625. }
  178626. /* Compute error fractions to be propagated to adjacent pixels.
  178627. * Add these into the running sums, and simultaneously shift the
  178628. * next-line error sums left by 1 column.
  178629. */
  178630. { register LOCFSERROR bnexterr, delta;
  178631. bnexterr = cur0; /* Process component 0 */
  178632. delta = cur0 * 2;
  178633. cur0 += delta; /* form error * 3 */
  178634. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  178635. cur0 += delta; /* form error * 5 */
  178636. bpreverr0 = belowerr0 + cur0;
  178637. belowerr0 = bnexterr;
  178638. cur0 += delta; /* form error * 7 */
  178639. bnexterr = cur1; /* Process component 1 */
  178640. delta = cur1 * 2;
  178641. cur1 += delta; /* form error * 3 */
  178642. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  178643. cur1 += delta; /* form error * 5 */
  178644. bpreverr1 = belowerr1 + cur1;
  178645. belowerr1 = bnexterr;
  178646. cur1 += delta; /* form error * 7 */
  178647. bnexterr = cur2; /* Process component 2 */
  178648. delta = cur2 * 2;
  178649. cur2 += delta; /* form error * 3 */
  178650. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  178651. cur2 += delta; /* form error * 5 */
  178652. bpreverr2 = belowerr2 + cur2;
  178653. belowerr2 = bnexterr;
  178654. cur2 += delta; /* form error * 7 */
  178655. }
  178656. /* At this point curN contains the 7/16 error value to be propagated
  178657. * to the next pixel on the current line, and all the errors for the
  178658. * next line have been shifted over. We are therefore ready to move on.
  178659. */
  178660. inptr += dir3; /* Advance pixel pointers to next column */
  178661. outptr += dir;
  178662. errorptr += dir3; /* advance errorptr to current column */
  178663. }
  178664. /* Post-loop cleanup: we must unload the final error values into the
  178665. * final fserrors[] entry. Note we need not unload belowerrN because
  178666. * it is for the dummy column before or after the actual array.
  178667. */
  178668. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  178669. errorptr[1] = (FSERROR) bpreverr1;
  178670. errorptr[2] = (FSERROR) bpreverr2;
  178671. }
  178672. }
  178673. /*
  178674. * Initialize the error-limiting transfer function (lookup table).
  178675. * The raw F-S error computation can potentially compute error values of up to
  178676. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  178677. * much less, otherwise obviously wrong pixels will be created. (Typical
  178678. * effects include weird fringes at color-area boundaries, isolated bright
  178679. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  178680. * is to ensure that the "corners" of the color cube are allocated as output
  178681. * colors; then repeated errors in the same direction cannot cause cascading
  178682. * error buildup. However, that only prevents the error from getting
  178683. * completely out of hand; Aaron Giles reports that error limiting improves
  178684. * the results even with corner colors allocated.
  178685. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  178686. * well, but the smoother transfer function used below is even better. Thanks
  178687. * to Aaron Giles for this idea.
  178688. */
  178689. LOCAL(void)
  178690. init_error_limit (j_decompress_ptr cinfo)
  178691. /* Allocate and fill in the error_limiter table */
  178692. {
  178693. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178694. int * table;
  178695. int in, out;
  178696. table = (int *) (*cinfo->mem->alloc_small)
  178697. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  178698. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  178699. cquantize->error_limiter = table;
  178700. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  178701. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  178702. out = 0;
  178703. for (in = 0; in < STEPSIZE; in++, out++) {
  178704. table[in] = out; table[-in] = -out;
  178705. }
  178706. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  178707. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  178708. table[in] = out; table[-in] = -out;
  178709. }
  178710. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  178711. for (; in <= MAXJSAMPLE; in++) {
  178712. table[in] = out; table[-in] = -out;
  178713. }
  178714. #undef STEPSIZE
  178715. }
  178716. /*
  178717. * Finish up at the end of each pass.
  178718. */
  178719. METHODDEF(void)
  178720. finish_pass1 (j_decompress_ptr cinfo)
  178721. {
  178722. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178723. /* Select the representative colors and fill in cinfo->colormap */
  178724. cinfo->colormap = cquantize->sv_colormap;
  178725. select_colors(cinfo, cquantize->desired);
  178726. /* Force next pass to zero the color index table */
  178727. cquantize->needs_zeroed = TRUE;
  178728. }
  178729. METHODDEF(void)
  178730. finish_pass2 (j_decompress_ptr)
  178731. {
  178732. /* no work */
  178733. }
  178734. /*
  178735. * Initialize for each processing pass.
  178736. */
  178737. METHODDEF(void)
  178738. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  178739. {
  178740. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178741. hist3d histogram = cquantize->histogram;
  178742. int i;
  178743. /* Only F-S dithering or no dithering is supported. */
  178744. /* If user asks for ordered dither, give him F-S. */
  178745. if (cinfo->dither_mode != JDITHER_NONE)
  178746. cinfo->dither_mode = JDITHER_FS;
  178747. if (is_pre_scan) {
  178748. /* Set up method pointers */
  178749. cquantize->pub.color_quantize = prescan_quantize;
  178750. cquantize->pub.finish_pass = finish_pass1;
  178751. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  178752. } else {
  178753. /* Set up method pointers */
  178754. if (cinfo->dither_mode == JDITHER_FS)
  178755. cquantize->pub.color_quantize = pass2_fs_dither;
  178756. else
  178757. cquantize->pub.color_quantize = pass2_no_dither;
  178758. cquantize->pub.finish_pass = finish_pass2;
  178759. /* Make sure color count is acceptable */
  178760. i = cinfo->actual_number_of_colors;
  178761. if (i < 1)
  178762. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  178763. if (i > MAXNUMCOLORS)
  178764. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178765. if (cinfo->dither_mode == JDITHER_FS) {
  178766. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  178767. (3 * SIZEOF(FSERROR)));
  178768. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  178769. if (cquantize->fserrors == NULL)
  178770. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178771. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  178772. /* Initialize the propagated errors to zero. */
  178773. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  178774. /* Make the error-limit table if we didn't already. */
  178775. if (cquantize->error_limiter == NULL)
  178776. init_error_limit(cinfo);
  178777. cquantize->on_odd_row = FALSE;
  178778. }
  178779. }
  178780. /* Zero the histogram or inverse color map, if necessary */
  178781. if (cquantize->needs_zeroed) {
  178782. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178783. jzero_far((void FAR *) histogram[i],
  178784. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178785. }
  178786. cquantize->needs_zeroed = FALSE;
  178787. }
  178788. }
  178789. /*
  178790. * Switch to a new external colormap between output passes.
  178791. */
  178792. METHODDEF(void)
  178793. new_color_map_2_quant (j_decompress_ptr cinfo)
  178794. {
  178795. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178796. /* Reset the inverse color map */
  178797. cquantize->needs_zeroed = TRUE;
  178798. }
  178799. /*
  178800. * Module initialization routine for 2-pass color quantization.
  178801. */
  178802. GLOBAL(void)
  178803. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  178804. {
  178805. my_cquantize_ptr2 cquantize;
  178806. int i;
  178807. cquantize = (my_cquantize_ptr2)
  178808. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178809. SIZEOF(my_cquantizer2));
  178810. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  178811. cquantize->pub.start_pass = start_pass_2_quant;
  178812. cquantize->pub.new_color_map = new_color_map_2_quant;
  178813. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  178814. cquantize->error_limiter = NULL;
  178815. /* Make sure jdmaster didn't give me a case I can't handle */
  178816. if (cinfo->out_color_components != 3)
  178817. ERREXIT(cinfo, JERR_NOTIMPL);
  178818. /* Allocate the histogram/inverse colormap storage */
  178819. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  178820. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  178821. for (i = 0; i < HIST_C0_ELEMS; i++) {
  178822. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  178823. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178824. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  178825. }
  178826. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  178827. /* Allocate storage for the completed colormap, if required.
  178828. * We do this now since it is FAR storage and may affect
  178829. * the memory manager's space calculations.
  178830. */
  178831. if (cinfo->enable_2pass_quant) {
  178832. /* Make sure color count is acceptable */
  178833. int desired = cinfo->desired_number_of_colors;
  178834. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  178835. if (desired < 8)
  178836. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  178837. /* Make sure colormap indexes can be represented by JSAMPLEs */
  178838. if (desired > MAXNUMCOLORS)
  178839. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178840. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  178841. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  178842. cquantize->desired = desired;
  178843. } else
  178844. cquantize->sv_colormap = NULL;
  178845. /* Only F-S dithering or no dithering is supported. */
  178846. /* If user asks for ordered dither, give him F-S. */
  178847. if (cinfo->dither_mode != JDITHER_NONE)
  178848. cinfo->dither_mode = JDITHER_FS;
  178849. /* Allocate Floyd-Steinberg workspace if necessary.
  178850. * This isn't really needed until pass 2, but again it is FAR storage.
  178851. * Although we will cope with a later change in dither_mode,
  178852. * we do not promise to honor max_memory_to_use if dither_mode changes.
  178853. */
  178854. if (cinfo->dither_mode == JDITHER_FS) {
  178855. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178856. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178857. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  178858. /* Might as well create the error-limiting table too. */
  178859. init_error_limit(cinfo);
  178860. }
  178861. }
  178862. #endif /* QUANT_2PASS_SUPPORTED */
  178863. /*** End of inlined file: jquant2.c ***/
  178864. /*** Start of inlined file: jutils.c ***/
  178865. #define JPEG_INTERNALS
  178866. /*
  178867. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  178868. * of a DCT block read in natural order (left to right, top to bottom).
  178869. */
  178870. #if 0 /* This table is not actually needed in v6a */
  178871. const int jpeg_zigzag_order[DCTSIZE2] = {
  178872. 0, 1, 5, 6, 14, 15, 27, 28,
  178873. 2, 4, 7, 13, 16, 26, 29, 42,
  178874. 3, 8, 12, 17, 25, 30, 41, 43,
  178875. 9, 11, 18, 24, 31, 40, 44, 53,
  178876. 10, 19, 23, 32, 39, 45, 52, 54,
  178877. 20, 22, 33, 38, 46, 51, 55, 60,
  178878. 21, 34, 37, 47, 50, 56, 59, 61,
  178879. 35, 36, 48, 49, 57, 58, 62, 63
  178880. };
  178881. #endif
  178882. /*
  178883. * jpeg_natural_order[i] is the natural-order position of the i'th element
  178884. * of zigzag order.
  178885. *
  178886. * When reading corrupted data, the Huffman decoders could attempt
  178887. * to reference an entry beyond the end of this array (if the decoded
  178888. * zero run length reaches past the end of the block). To prevent
  178889. * wild stores without adding an inner-loop test, we put some extra
  178890. * "63"s after the real entries. This will cause the extra coefficient
  178891. * to be stored in location 63 of the block, not somewhere random.
  178892. * The worst case would be a run-length of 15, which means we need 16
  178893. * fake entries.
  178894. */
  178895. const int jpeg_natural_order[DCTSIZE2+16] = {
  178896. 0, 1, 8, 16, 9, 2, 3, 10,
  178897. 17, 24, 32, 25, 18, 11, 4, 5,
  178898. 12, 19, 26, 33, 40, 48, 41, 34,
  178899. 27, 20, 13, 6, 7, 14, 21, 28,
  178900. 35, 42, 49, 56, 57, 50, 43, 36,
  178901. 29, 22, 15, 23, 30, 37, 44, 51,
  178902. 58, 59, 52, 45, 38, 31, 39, 46,
  178903. 53, 60, 61, 54, 47, 55, 62, 63,
  178904. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  178905. 63, 63, 63, 63, 63, 63, 63, 63
  178906. };
  178907. /*
  178908. * Arithmetic utilities
  178909. */
  178910. GLOBAL(long)
  178911. jdiv_round_up (long a, long b)
  178912. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  178913. /* Assumes a >= 0, b > 0 */
  178914. {
  178915. return (a + b - 1L) / b;
  178916. }
  178917. GLOBAL(long)
  178918. jround_up (long a, long b)
  178919. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  178920. /* Assumes a >= 0, b > 0 */
  178921. {
  178922. a += b - 1L;
  178923. return a - (a % b);
  178924. }
  178925. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  178926. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  178927. * are FAR and we're assuming a small-pointer memory model. However, some
  178928. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  178929. * in the small-model libraries. These will be used if USE_FMEM is defined.
  178930. * Otherwise, the routines below do it the hard way. (The performance cost
  178931. * is not all that great, because these routines aren't very heavily used.)
  178932. */
  178933. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  178934. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  178935. #define FMEMZERO(target,size) MEMZERO(target,size)
  178936. #else /* 80x86 case, define if we can */
  178937. #ifdef USE_FMEM
  178938. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  178939. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  178940. #endif
  178941. #endif
  178942. GLOBAL(void)
  178943. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  178944. JSAMPARRAY output_array, int dest_row,
  178945. int num_rows, JDIMENSION num_cols)
  178946. /* Copy some rows of samples from one place to another.
  178947. * num_rows rows are copied from input_array[source_row++]
  178948. * to output_array[dest_row++]; these areas may overlap for duplication.
  178949. * The source and destination arrays must be at least as wide as num_cols.
  178950. */
  178951. {
  178952. register JSAMPROW inptr, outptr;
  178953. #ifdef FMEMCOPY
  178954. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  178955. #else
  178956. register JDIMENSION count;
  178957. #endif
  178958. register int row;
  178959. input_array += source_row;
  178960. output_array += dest_row;
  178961. for (row = num_rows; row > 0; row--) {
  178962. inptr = *input_array++;
  178963. outptr = *output_array++;
  178964. #ifdef FMEMCOPY
  178965. FMEMCOPY(outptr, inptr, count);
  178966. #else
  178967. for (count = num_cols; count > 0; count--)
  178968. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  178969. #endif
  178970. }
  178971. }
  178972. GLOBAL(void)
  178973. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  178974. JDIMENSION num_blocks)
  178975. /* Copy a row of coefficient blocks from one place to another. */
  178976. {
  178977. #ifdef FMEMCOPY
  178978. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  178979. #else
  178980. register JCOEFPTR inptr, outptr;
  178981. register long count;
  178982. inptr = (JCOEFPTR) input_row;
  178983. outptr = (JCOEFPTR) output_row;
  178984. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  178985. *outptr++ = *inptr++;
  178986. }
  178987. #endif
  178988. }
  178989. GLOBAL(void)
  178990. jzero_far (void FAR * target, size_t bytestozero)
  178991. /* Zero out a chunk of FAR memory. */
  178992. /* This might be sample-array data, block-array data, or alloc_large data. */
  178993. {
  178994. #ifdef FMEMZERO
  178995. FMEMZERO(target, bytestozero);
  178996. #else
  178997. register char FAR * ptr = (char FAR *) target;
  178998. register size_t count;
  178999. for (count = bytestozero; count > 0; count--) {
  179000. *ptr++ = 0;
  179001. }
  179002. #endif
  179003. }
  179004. /*** End of inlined file: jutils.c ***/
  179005. /*** Start of inlined file: transupp.c ***/
  179006. /* Although this file really shouldn't have access to the library internals,
  179007. * it's helpful to let it call jround_up() and jcopy_block_row().
  179008. */
  179009. #define JPEG_INTERNALS
  179010. /*** Start of inlined file: transupp.h ***/
  179011. /* If you happen not to want the image transform support, disable it here */
  179012. #ifndef TRANSFORMS_SUPPORTED
  179013. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  179014. #endif
  179015. /* Short forms of external names for systems with brain-damaged linkers. */
  179016. #ifdef NEED_SHORT_EXTERNAL_NAMES
  179017. #define jtransform_request_workspace jTrRequest
  179018. #define jtransform_adjust_parameters jTrAdjust
  179019. #define jtransform_execute_transformation jTrExec
  179020. #define jcopy_markers_setup jCMrkSetup
  179021. #define jcopy_markers_execute jCMrkExec
  179022. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  179023. /*
  179024. * Codes for supported types of image transformations.
  179025. */
  179026. typedef enum {
  179027. JXFORM_NONE, /* no transformation */
  179028. JXFORM_FLIP_H, /* horizontal flip */
  179029. JXFORM_FLIP_V, /* vertical flip */
  179030. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  179031. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  179032. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  179033. JXFORM_ROT_180, /* 180-degree rotation */
  179034. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  179035. } JXFORM_CODE;
  179036. /*
  179037. * Although rotating and flipping data expressed as DCT coefficients is not
  179038. * hard, there is an asymmetry in the JPEG format specification for images
  179039. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  179040. * image edges are padded out to the next iMCU boundary with junk data; but
  179041. * no padding is possible at the top and left edges. If we were to flip
  179042. * the whole image including the pad data, then pad garbage would become
  179043. * visible at the top and/or left, and real pixels would disappear into the
  179044. * pad margins --- perhaps permanently, since encoders & decoders may not
  179045. * bother to preserve DCT blocks that appear to be completely outside the
  179046. * nominal image area. So, we have to exclude any partial iMCUs from the
  179047. * basic transformation.
  179048. *
  179049. * Transpose is the only transformation that can handle partial iMCUs at the
  179050. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  179051. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  179052. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  179053. * The other transforms are defined as combinations of these basic transforms
  179054. * and process edge blocks in a way that preserves the equivalence.
  179055. *
  179056. * The "trim" option causes untransformable partial iMCUs to be dropped;
  179057. * this is not strictly lossless, but it usually gives the best-looking
  179058. * result for odd-size images. Note that when this option is active,
  179059. * the expected mathematical equivalences between the transforms may not hold.
  179060. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  179061. * followed by -rot 180 -trim trims both edges.)
  179062. *
  179063. * We also offer a "force to grayscale" option, which simply discards the
  179064. * chrominance channels of a YCbCr image. This is lossless in the sense that
  179065. * the luminance channel is preserved exactly. It's not the same kind of
  179066. * thing as the rotate/flip transformations, but it's convenient to handle it
  179067. * as part of this package, mainly because the transformation routines have to
  179068. * be aware of the option to know how many components to work on.
  179069. */
  179070. typedef struct {
  179071. /* Options: set by caller */
  179072. JXFORM_CODE transform; /* image transform operator */
  179073. boolean trim; /* if TRUE, trim partial MCUs as needed */
  179074. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  179075. /* Internal workspace: caller should not touch these */
  179076. int num_components; /* # of components in workspace */
  179077. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  179078. } jpeg_transform_info;
  179079. #if TRANSFORMS_SUPPORTED
  179080. /* Request any required workspace */
  179081. EXTERN(void) jtransform_request_workspace
  179082. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  179083. /* Adjust output image parameters */
  179084. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  179085. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179086. jvirt_barray_ptr *src_coef_arrays,
  179087. jpeg_transform_info *info));
  179088. /* Execute the actual transformation, if any */
  179089. EXTERN(void) jtransform_execute_transformation
  179090. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179091. jvirt_barray_ptr *src_coef_arrays,
  179092. jpeg_transform_info *info));
  179093. #endif /* TRANSFORMS_SUPPORTED */
  179094. /*
  179095. * Support for copying optional markers from source to destination file.
  179096. */
  179097. typedef enum {
  179098. JCOPYOPT_NONE, /* copy no optional markers */
  179099. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  179100. JCOPYOPT_ALL /* copy all optional markers */
  179101. } JCOPY_OPTION;
  179102. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  179103. /* Setup decompression object to save desired markers in memory */
  179104. EXTERN(void) jcopy_markers_setup
  179105. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  179106. /* Copy markers saved in the given source object to the destination object */
  179107. EXTERN(void) jcopy_markers_execute
  179108. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179109. JCOPY_OPTION option));
  179110. /*** End of inlined file: transupp.h ***/
  179111. /* My own external interface */
  179112. #if TRANSFORMS_SUPPORTED
  179113. /*
  179114. * Lossless image transformation routines. These routines work on DCT
  179115. * coefficient arrays and thus do not require any lossy decompression
  179116. * or recompression of the image.
  179117. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  179118. *
  179119. * Horizontal flipping is done in-place, using a single top-to-bottom
  179120. * pass through the virtual source array. It will thus be much the
  179121. * fastest option for images larger than main memory.
  179122. *
  179123. * The other routines require a set of destination virtual arrays, so they
  179124. * need twice as much memory as jpegtran normally does. The destination
  179125. * arrays are always written in normal scan order (top to bottom) because
  179126. * the virtual array manager expects this. The source arrays will be scanned
  179127. * in the corresponding order, which means multiple passes through the source
  179128. * arrays for most of the transforms. That could result in much thrashing
  179129. * if the image is larger than main memory.
  179130. *
  179131. * Some notes about the operating environment of the individual transform
  179132. * routines:
  179133. * 1. Both the source and destination virtual arrays are allocated from the
  179134. * source JPEG object, and therefore should be manipulated by calling the
  179135. * source's memory manager.
  179136. * 2. The destination's component count should be used. It may be smaller
  179137. * than the source's when forcing to grayscale.
  179138. * 3. Likewise the destination's sampling factors should be used. When
  179139. * forcing to grayscale the destination's sampling factors will be all 1,
  179140. * and we may as well take that as the effective iMCU size.
  179141. * 4. When "trim" is in effect, the destination's dimensions will be the
  179142. * trimmed values but the source's will be untrimmed.
  179143. * 5. All the routines assume that the source and destination buffers are
  179144. * padded out to a full iMCU boundary. This is true, although for the
  179145. * source buffer it is an undocumented property of jdcoefct.c.
  179146. * Notes 2,3,4 boil down to this: generally we should use the destination's
  179147. * dimensions and ignore the source's.
  179148. */
  179149. LOCAL(void)
  179150. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179151. jvirt_barray_ptr *src_coef_arrays)
  179152. /* Horizontal flip; done in-place, so no separate dest array is required */
  179153. {
  179154. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  179155. int ci, k, offset_y;
  179156. JBLOCKARRAY buffer;
  179157. JCOEFPTR ptr1, ptr2;
  179158. JCOEF temp1, temp2;
  179159. jpeg_component_info *compptr;
  179160. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  179161. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  179162. * mirroring by changing the signs of odd-numbered columns.
  179163. * Partial iMCUs at the right edge are left untouched.
  179164. */
  179165. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179166. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179167. compptr = dstinfo->comp_info + ci;
  179168. comp_width = MCU_cols * compptr->h_samp_factor;
  179169. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  179170. blk_y += compptr->v_samp_factor) {
  179171. buffer = (*srcinfo->mem->access_virt_barray)
  179172. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  179173. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179174. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179175. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  179176. ptr1 = buffer[offset_y][blk_x];
  179177. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  179178. /* this unrolled loop doesn't need to know which row it's on... */
  179179. for (k = 0; k < DCTSIZE2; k += 2) {
  179180. temp1 = *ptr1; /* swap even column */
  179181. temp2 = *ptr2;
  179182. *ptr1++ = temp2;
  179183. *ptr2++ = temp1;
  179184. temp1 = *ptr1; /* swap odd column with sign change */
  179185. temp2 = *ptr2;
  179186. *ptr1++ = -temp2;
  179187. *ptr2++ = -temp1;
  179188. }
  179189. }
  179190. }
  179191. }
  179192. }
  179193. }
  179194. LOCAL(void)
  179195. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179196. jvirt_barray_ptr *src_coef_arrays,
  179197. jvirt_barray_ptr *dst_coef_arrays)
  179198. /* Vertical flip */
  179199. {
  179200. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  179201. int ci, i, j, offset_y;
  179202. JBLOCKARRAY src_buffer, dst_buffer;
  179203. JBLOCKROW src_row_ptr, dst_row_ptr;
  179204. JCOEFPTR src_ptr, dst_ptr;
  179205. jpeg_component_info *compptr;
  179206. /* We output into a separate array because we can't touch different
  179207. * rows of the source virtual array simultaneously. Otherwise, this
  179208. * is a pretty straightforward analog of horizontal flip.
  179209. * Within a DCT block, vertical mirroring is done by changing the signs
  179210. * of odd-numbered rows.
  179211. * Partial iMCUs at the bottom edge are copied verbatim.
  179212. */
  179213. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179214. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179215. compptr = dstinfo->comp_info + ci;
  179216. comp_height = MCU_rows * compptr->v_samp_factor;
  179217. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179218. dst_blk_y += compptr->v_samp_factor) {
  179219. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179220. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179221. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179222. if (dst_blk_y < comp_height) {
  179223. /* Row is within the mirrorable area. */
  179224. src_buffer = (*srcinfo->mem->access_virt_barray)
  179225. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179226. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179227. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179228. } else {
  179229. /* Bottom-edge blocks will be copied verbatim. */
  179230. src_buffer = (*srcinfo->mem->access_virt_barray)
  179231. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179232. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179233. }
  179234. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179235. if (dst_blk_y < comp_height) {
  179236. /* Row is within the mirrorable area. */
  179237. dst_row_ptr = dst_buffer[offset_y];
  179238. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179239. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179240. dst_blk_x++) {
  179241. dst_ptr = dst_row_ptr[dst_blk_x];
  179242. src_ptr = src_row_ptr[dst_blk_x];
  179243. for (i = 0; i < DCTSIZE; i += 2) {
  179244. /* copy even row */
  179245. for (j = 0; j < DCTSIZE; j++)
  179246. *dst_ptr++ = *src_ptr++;
  179247. /* copy odd row with sign change */
  179248. for (j = 0; j < DCTSIZE; j++)
  179249. *dst_ptr++ = - *src_ptr++;
  179250. }
  179251. }
  179252. } else {
  179253. /* Just copy row verbatim. */
  179254. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  179255. compptr->width_in_blocks);
  179256. }
  179257. }
  179258. }
  179259. }
  179260. }
  179261. LOCAL(void)
  179262. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179263. jvirt_barray_ptr *src_coef_arrays,
  179264. jvirt_barray_ptr *dst_coef_arrays)
  179265. /* Transpose source into destination */
  179266. {
  179267. JDIMENSION dst_blk_x, dst_blk_y;
  179268. int ci, i, j, offset_x, offset_y;
  179269. JBLOCKARRAY src_buffer, dst_buffer;
  179270. JCOEFPTR src_ptr, dst_ptr;
  179271. jpeg_component_info *compptr;
  179272. /* Transposing pixels within a block just requires transposing the
  179273. * DCT coefficients.
  179274. * Partial iMCUs at the edges require no special treatment; we simply
  179275. * process all the available DCT blocks for every component.
  179276. */
  179277. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179278. compptr = dstinfo->comp_info + ci;
  179279. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179280. dst_blk_y += compptr->v_samp_factor) {
  179281. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179282. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179283. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179284. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179285. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179286. dst_blk_x += compptr->h_samp_factor) {
  179287. src_buffer = (*srcinfo->mem->access_virt_barray)
  179288. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179289. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179290. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179291. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179292. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179293. for (i = 0; i < DCTSIZE; i++)
  179294. for (j = 0; j < DCTSIZE; j++)
  179295. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179296. }
  179297. }
  179298. }
  179299. }
  179300. }
  179301. }
  179302. LOCAL(void)
  179303. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179304. jvirt_barray_ptr *src_coef_arrays,
  179305. jvirt_barray_ptr *dst_coef_arrays)
  179306. /* 90 degree rotation is equivalent to
  179307. * 1. Transposing the image;
  179308. * 2. Horizontal mirroring.
  179309. * These two steps are merged into a single processing routine.
  179310. */
  179311. {
  179312. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  179313. int ci, i, j, offset_x, offset_y;
  179314. JBLOCKARRAY src_buffer, dst_buffer;
  179315. JCOEFPTR src_ptr, dst_ptr;
  179316. jpeg_component_info *compptr;
  179317. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179318. * at the (output) right edge properly. They just get transposed and
  179319. * not mirrored.
  179320. */
  179321. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179322. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179323. compptr = dstinfo->comp_info + ci;
  179324. comp_width = MCU_cols * compptr->h_samp_factor;
  179325. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179326. dst_blk_y += compptr->v_samp_factor) {
  179327. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179328. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179329. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179330. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179331. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179332. dst_blk_x += compptr->h_samp_factor) {
  179333. src_buffer = (*srcinfo->mem->access_virt_barray)
  179334. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179335. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179336. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179337. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179338. if (dst_blk_x < comp_width) {
  179339. /* Block is within the mirrorable area. */
  179340. dst_ptr = dst_buffer[offset_y]
  179341. [comp_width - dst_blk_x - offset_x - 1];
  179342. for (i = 0; i < DCTSIZE; i++) {
  179343. for (j = 0; j < DCTSIZE; j++)
  179344. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179345. i++;
  179346. for (j = 0; j < DCTSIZE; j++)
  179347. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179348. }
  179349. } else {
  179350. /* Edge blocks are transposed but not mirrored. */
  179351. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179352. for (i = 0; i < DCTSIZE; i++)
  179353. for (j = 0; j < DCTSIZE; j++)
  179354. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179355. }
  179356. }
  179357. }
  179358. }
  179359. }
  179360. }
  179361. }
  179362. LOCAL(void)
  179363. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179364. jvirt_barray_ptr *src_coef_arrays,
  179365. jvirt_barray_ptr *dst_coef_arrays)
  179366. /* 270 degree rotation is equivalent to
  179367. * 1. Horizontal mirroring;
  179368. * 2. Transposing the image.
  179369. * These two steps are merged into a single processing routine.
  179370. */
  179371. {
  179372. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  179373. int ci, i, j, offset_x, offset_y;
  179374. JBLOCKARRAY src_buffer, dst_buffer;
  179375. JCOEFPTR src_ptr, dst_ptr;
  179376. jpeg_component_info *compptr;
  179377. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179378. * at the (output) bottom edge properly. They just get transposed and
  179379. * not mirrored.
  179380. */
  179381. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179382. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179383. compptr = dstinfo->comp_info + ci;
  179384. comp_height = MCU_rows * compptr->v_samp_factor;
  179385. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179386. dst_blk_y += compptr->v_samp_factor) {
  179387. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179388. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179389. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179390. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179391. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179392. dst_blk_x += compptr->h_samp_factor) {
  179393. src_buffer = (*srcinfo->mem->access_virt_barray)
  179394. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179395. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179396. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179397. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179398. if (dst_blk_y < comp_height) {
  179399. /* Block is within the mirrorable area. */
  179400. src_ptr = src_buffer[offset_x]
  179401. [comp_height - dst_blk_y - offset_y - 1];
  179402. for (i = 0; i < DCTSIZE; i++) {
  179403. for (j = 0; j < DCTSIZE; j++) {
  179404. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179405. j++;
  179406. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179407. }
  179408. }
  179409. } else {
  179410. /* Edge blocks are transposed but not mirrored. */
  179411. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179412. for (i = 0; i < DCTSIZE; i++)
  179413. for (j = 0; j < DCTSIZE; j++)
  179414. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179415. }
  179416. }
  179417. }
  179418. }
  179419. }
  179420. }
  179421. }
  179422. LOCAL(void)
  179423. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179424. jvirt_barray_ptr *src_coef_arrays,
  179425. jvirt_barray_ptr *dst_coef_arrays)
  179426. /* 180 degree rotation is equivalent to
  179427. * 1. Vertical mirroring;
  179428. * 2. Horizontal mirroring.
  179429. * These two steps are merged into a single processing routine.
  179430. */
  179431. {
  179432. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179433. int ci, i, j, offset_y;
  179434. JBLOCKARRAY src_buffer, dst_buffer;
  179435. JBLOCKROW src_row_ptr, dst_row_ptr;
  179436. JCOEFPTR src_ptr, dst_ptr;
  179437. jpeg_component_info *compptr;
  179438. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179439. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179440. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179441. compptr = dstinfo->comp_info + ci;
  179442. comp_width = MCU_cols * compptr->h_samp_factor;
  179443. comp_height = MCU_rows * compptr->v_samp_factor;
  179444. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179445. dst_blk_y += compptr->v_samp_factor) {
  179446. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179447. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179448. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179449. if (dst_blk_y < comp_height) {
  179450. /* Row is within the vertically mirrorable area. */
  179451. src_buffer = (*srcinfo->mem->access_virt_barray)
  179452. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179453. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179454. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179455. } else {
  179456. /* Bottom-edge rows are only mirrored horizontally. */
  179457. src_buffer = (*srcinfo->mem->access_virt_barray)
  179458. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179459. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179460. }
  179461. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179462. if (dst_blk_y < comp_height) {
  179463. /* Row is within the mirrorable area. */
  179464. dst_row_ptr = dst_buffer[offset_y];
  179465. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179466. /* Process the blocks that can be mirrored both ways. */
  179467. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179468. dst_ptr = dst_row_ptr[dst_blk_x];
  179469. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179470. for (i = 0; i < DCTSIZE; i += 2) {
  179471. /* For even row, negate every odd column. */
  179472. for (j = 0; j < DCTSIZE; j += 2) {
  179473. *dst_ptr++ = *src_ptr++;
  179474. *dst_ptr++ = - *src_ptr++;
  179475. }
  179476. /* For odd row, negate every even column. */
  179477. for (j = 0; j < DCTSIZE; j += 2) {
  179478. *dst_ptr++ = - *src_ptr++;
  179479. *dst_ptr++ = *src_ptr++;
  179480. }
  179481. }
  179482. }
  179483. /* Any remaining right-edge blocks are only mirrored vertically. */
  179484. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179485. dst_ptr = dst_row_ptr[dst_blk_x];
  179486. src_ptr = src_row_ptr[dst_blk_x];
  179487. for (i = 0; i < DCTSIZE; i += 2) {
  179488. for (j = 0; j < DCTSIZE; j++)
  179489. *dst_ptr++ = *src_ptr++;
  179490. for (j = 0; j < DCTSIZE; j++)
  179491. *dst_ptr++ = - *src_ptr++;
  179492. }
  179493. }
  179494. } else {
  179495. /* Remaining rows are just mirrored horizontally. */
  179496. dst_row_ptr = dst_buffer[offset_y];
  179497. src_row_ptr = src_buffer[offset_y];
  179498. /* Process the blocks that can be mirrored. */
  179499. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179500. dst_ptr = dst_row_ptr[dst_blk_x];
  179501. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179502. for (i = 0; i < DCTSIZE2; i += 2) {
  179503. *dst_ptr++ = *src_ptr++;
  179504. *dst_ptr++ = - *src_ptr++;
  179505. }
  179506. }
  179507. /* Any remaining right-edge blocks are only copied. */
  179508. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179509. dst_ptr = dst_row_ptr[dst_blk_x];
  179510. src_ptr = src_row_ptr[dst_blk_x];
  179511. for (i = 0; i < DCTSIZE2; i++)
  179512. *dst_ptr++ = *src_ptr++;
  179513. }
  179514. }
  179515. }
  179516. }
  179517. }
  179518. }
  179519. LOCAL(void)
  179520. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179521. jvirt_barray_ptr *src_coef_arrays,
  179522. jvirt_barray_ptr *dst_coef_arrays)
  179523. /* Transverse transpose is equivalent to
  179524. * 1. 180 degree rotation;
  179525. * 2. Transposition;
  179526. * or
  179527. * 1. Horizontal mirroring;
  179528. * 2. Transposition;
  179529. * 3. Horizontal mirroring.
  179530. * These steps are merged into a single processing routine.
  179531. */
  179532. {
  179533. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179534. int ci, i, j, offset_x, offset_y;
  179535. JBLOCKARRAY src_buffer, dst_buffer;
  179536. JCOEFPTR src_ptr, dst_ptr;
  179537. jpeg_component_info *compptr;
  179538. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179539. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179540. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179541. compptr = dstinfo->comp_info + ci;
  179542. comp_width = MCU_cols * compptr->h_samp_factor;
  179543. comp_height = MCU_rows * compptr->v_samp_factor;
  179544. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179545. dst_blk_y += compptr->v_samp_factor) {
  179546. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179547. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179548. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179549. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179550. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179551. dst_blk_x += compptr->h_samp_factor) {
  179552. src_buffer = (*srcinfo->mem->access_virt_barray)
  179553. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179554. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179555. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179556. if (dst_blk_y < comp_height) {
  179557. src_ptr = src_buffer[offset_x]
  179558. [comp_height - dst_blk_y - offset_y - 1];
  179559. if (dst_blk_x < comp_width) {
  179560. /* Block is within the mirrorable area. */
  179561. dst_ptr = dst_buffer[offset_y]
  179562. [comp_width - dst_blk_x - offset_x - 1];
  179563. for (i = 0; i < DCTSIZE; i++) {
  179564. for (j = 0; j < DCTSIZE; j++) {
  179565. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179566. j++;
  179567. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179568. }
  179569. i++;
  179570. for (j = 0; j < DCTSIZE; j++) {
  179571. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179572. j++;
  179573. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179574. }
  179575. }
  179576. } else {
  179577. /* Right-edge blocks are mirrored in y only */
  179578. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179579. for (i = 0; i < DCTSIZE; i++) {
  179580. for (j = 0; j < DCTSIZE; j++) {
  179581. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179582. j++;
  179583. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179584. }
  179585. }
  179586. }
  179587. } else {
  179588. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179589. if (dst_blk_x < comp_width) {
  179590. /* Bottom-edge blocks are mirrored in x only */
  179591. dst_ptr = dst_buffer[offset_y]
  179592. [comp_width - dst_blk_x - offset_x - 1];
  179593. for (i = 0; i < DCTSIZE; i++) {
  179594. for (j = 0; j < DCTSIZE; j++)
  179595. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179596. i++;
  179597. for (j = 0; j < DCTSIZE; j++)
  179598. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179599. }
  179600. } else {
  179601. /* At lower right corner, just transpose, no mirroring */
  179602. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179603. for (i = 0; i < DCTSIZE; i++)
  179604. for (j = 0; j < DCTSIZE; j++)
  179605. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179606. }
  179607. }
  179608. }
  179609. }
  179610. }
  179611. }
  179612. }
  179613. }
  179614. /* Request any required workspace.
  179615. *
  179616. * We allocate the workspace virtual arrays from the source decompression
  179617. * object, so that all the arrays (both the original data and the workspace)
  179618. * will be taken into account while making memory management decisions.
  179619. * Hence, this routine must be called after jpeg_read_header (which reads
  179620. * the image dimensions) and before jpeg_read_coefficients (which realizes
  179621. * the source's virtual arrays).
  179622. */
  179623. GLOBAL(void)
  179624. jtransform_request_workspace (j_decompress_ptr srcinfo,
  179625. jpeg_transform_info *info)
  179626. {
  179627. jvirt_barray_ptr *coef_arrays = NULL;
  179628. jpeg_component_info *compptr;
  179629. int ci;
  179630. if (info->force_grayscale &&
  179631. srcinfo->jpeg_color_space == JCS_YCbCr &&
  179632. srcinfo->num_components == 3) {
  179633. /* We'll only process the first component */
  179634. info->num_components = 1;
  179635. } else {
  179636. /* Process all the components */
  179637. info->num_components = srcinfo->num_components;
  179638. }
  179639. switch (info->transform) {
  179640. case JXFORM_NONE:
  179641. case JXFORM_FLIP_H:
  179642. /* Don't need a workspace array */
  179643. break;
  179644. case JXFORM_FLIP_V:
  179645. case JXFORM_ROT_180:
  179646. /* Need workspace arrays having same dimensions as source image.
  179647. * Note that we allocate arrays padded out to the next iMCU boundary,
  179648. * so that transform routines need not worry about missing edge blocks.
  179649. */
  179650. coef_arrays = (jvirt_barray_ptr *)
  179651. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179652. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179653. for (ci = 0; ci < info->num_components; ci++) {
  179654. compptr = srcinfo->comp_info + ci;
  179655. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179656. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179657. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179658. (long) compptr->h_samp_factor),
  179659. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179660. (long) compptr->v_samp_factor),
  179661. (JDIMENSION) compptr->v_samp_factor);
  179662. }
  179663. break;
  179664. case JXFORM_TRANSPOSE:
  179665. case JXFORM_TRANSVERSE:
  179666. case JXFORM_ROT_90:
  179667. case JXFORM_ROT_270:
  179668. /* Need workspace arrays having transposed dimensions.
  179669. * Note that we allocate arrays padded out to the next iMCU boundary,
  179670. * so that transform routines need not worry about missing edge blocks.
  179671. */
  179672. coef_arrays = (jvirt_barray_ptr *)
  179673. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179674. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179675. for (ci = 0; ci < info->num_components; ci++) {
  179676. compptr = srcinfo->comp_info + ci;
  179677. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179678. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179679. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179680. (long) compptr->v_samp_factor),
  179681. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179682. (long) compptr->h_samp_factor),
  179683. (JDIMENSION) compptr->h_samp_factor);
  179684. }
  179685. break;
  179686. }
  179687. info->workspace_coef_arrays = coef_arrays;
  179688. }
  179689. /* Transpose destination image parameters */
  179690. LOCAL(void)
  179691. transpose_critical_parameters (j_compress_ptr dstinfo)
  179692. {
  179693. int tblno, i, j, ci, itemp;
  179694. jpeg_component_info *compptr;
  179695. JQUANT_TBL *qtblptr;
  179696. JDIMENSION dtemp;
  179697. UINT16 qtemp;
  179698. /* Transpose basic image dimensions */
  179699. dtemp = dstinfo->image_width;
  179700. dstinfo->image_width = dstinfo->image_height;
  179701. dstinfo->image_height = dtemp;
  179702. /* Transpose sampling factors */
  179703. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179704. compptr = dstinfo->comp_info + ci;
  179705. itemp = compptr->h_samp_factor;
  179706. compptr->h_samp_factor = compptr->v_samp_factor;
  179707. compptr->v_samp_factor = itemp;
  179708. }
  179709. /* Transpose quantization tables */
  179710. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  179711. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  179712. if (qtblptr != NULL) {
  179713. for (i = 0; i < DCTSIZE; i++) {
  179714. for (j = 0; j < i; j++) {
  179715. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  179716. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  179717. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  179718. }
  179719. }
  179720. }
  179721. }
  179722. }
  179723. /* Trim off any partial iMCUs on the indicated destination edge */
  179724. LOCAL(void)
  179725. trim_right_edge (j_compress_ptr dstinfo)
  179726. {
  179727. int ci, max_h_samp_factor;
  179728. JDIMENSION MCU_cols;
  179729. /* We have to compute max_h_samp_factor ourselves,
  179730. * because it hasn't been set yet in the destination
  179731. * (and we don't want to use the source's value).
  179732. */
  179733. max_h_samp_factor = 1;
  179734. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179735. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  179736. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  179737. }
  179738. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  179739. if (MCU_cols > 0) /* can't trim to 0 pixels */
  179740. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  179741. }
  179742. LOCAL(void)
  179743. trim_bottom_edge (j_compress_ptr dstinfo)
  179744. {
  179745. int ci, max_v_samp_factor;
  179746. JDIMENSION MCU_rows;
  179747. /* We have to compute max_v_samp_factor ourselves,
  179748. * because it hasn't been set yet in the destination
  179749. * (and we don't want to use the source's value).
  179750. */
  179751. max_v_samp_factor = 1;
  179752. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179753. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  179754. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  179755. }
  179756. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  179757. if (MCU_rows > 0) /* can't trim to 0 pixels */
  179758. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  179759. }
  179760. /* Adjust output image parameters as needed.
  179761. *
  179762. * This must be called after jpeg_copy_critical_parameters()
  179763. * and before jpeg_write_coefficients().
  179764. *
  179765. * The return value is the set of virtual coefficient arrays to be written
  179766. * (either the ones allocated by jtransform_request_workspace, or the
  179767. * original source data arrays). The caller will need to pass this value
  179768. * to jpeg_write_coefficients().
  179769. */
  179770. GLOBAL(jvirt_barray_ptr *)
  179771. jtransform_adjust_parameters (j_decompress_ptr,
  179772. j_compress_ptr dstinfo,
  179773. jvirt_barray_ptr *src_coef_arrays,
  179774. jpeg_transform_info *info)
  179775. {
  179776. /* If force-to-grayscale is requested, adjust destination parameters */
  179777. if (info->force_grayscale) {
  179778. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  179779. * properly. Among other things, the target h_samp_factor & v_samp_factor
  179780. * will get set to 1, which typically won't match the source.
  179781. * In fact we do this even if the source is already grayscale; that
  179782. * provides an easy way of coercing a grayscale JPEG with funny sampling
  179783. * factors to the customary 1,1. (Some decoders fail on other factors.)
  179784. */
  179785. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  179786. dstinfo->num_components == 3) ||
  179787. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  179788. dstinfo->num_components == 1)) {
  179789. /* We have to preserve the source's quantization table number. */
  179790. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  179791. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  179792. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  179793. } else {
  179794. /* Sorry, can't do it */
  179795. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  179796. }
  179797. }
  179798. /* Correct the destination's image dimensions etc if necessary */
  179799. switch (info->transform) {
  179800. case JXFORM_NONE:
  179801. /* Nothing to do */
  179802. break;
  179803. case JXFORM_FLIP_H:
  179804. if (info->trim)
  179805. trim_right_edge(dstinfo);
  179806. break;
  179807. case JXFORM_FLIP_V:
  179808. if (info->trim)
  179809. trim_bottom_edge(dstinfo);
  179810. break;
  179811. case JXFORM_TRANSPOSE:
  179812. transpose_critical_parameters(dstinfo);
  179813. /* transpose does NOT have to trim anything */
  179814. break;
  179815. case JXFORM_TRANSVERSE:
  179816. transpose_critical_parameters(dstinfo);
  179817. if (info->trim) {
  179818. trim_right_edge(dstinfo);
  179819. trim_bottom_edge(dstinfo);
  179820. }
  179821. break;
  179822. case JXFORM_ROT_90:
  179823. transpose_critical_parameters(dstinfo);
  179824. if (info->trim)
  179825. trim_right_edge(dstinfo);
  179826. break;
  179827. case JXFORM_ROT_180:
  179828. if (info->trim) {
  179829. trim_right_edge(dstinfo);
  179830. trim_bottom_edge(dstinfo);
  179831. }
  179832. break;
  179833. case JXFORM_ROT_270:
  179834. transpose_critical_parameters(dstinfo);
  179835. if (info->trim)
  179836. trim_bottom_edge(dstinfo);
  179837. break;
  179838. }
  179839. /* Return the appropriate output data set */
  179840. if (info->workspace_coef_arrays != NULL)
  179841. return info->workspace_coef_arrays;
  179842. return src_coef_arrays;
  179843. }
  179844. /* Execute the actual transformation, if any.
  179845. *
  179846. * This must be called *after* jpeg_write_coefficients, because it depends
  179847. * on jpeg_write_coefficients to have computed subsidiary values such as
  179848. * the per-component width and height fields in the destination object.
  179849. *
  179850. * Note that some transformations will modify the source data arrays!
  179851. */
  179852. GLOBAL(void)
  179853. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  179854. j_compress_ptr dstinfo,
  179855. jvirt_barray_ptr *src_coef_arrays,
  179856. jpeg_transform_info *info)
  179857. {
  179858. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  179859. switch (info->transform) {
  179860. case JXFORM_NONE:
  179861. break;
  179862. case JXFORM_FLIP_H:
  179863. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  179864. break;
  179865. case JXFORM_FLIP_V:
  179866. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179867. break;
  179868. case JXFORM_TRANSPOSE:
  179869. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179870. break;
  179871. case JXFORM_TRANSVERSE:
  179872. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179873. break;
  179874. case JXFORM_ROT_90:
  179875. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179876. break;
  179877. case JXFORM_ROT_180:
  179878. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179879. break;
  179880. case JXFORM_ROT_270:
  179881. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  179882. break;
  179883. }
  179884. }
  179885. #endif /* TRANSFORMS_SUPPORTED */
  179886. /* Setup decompression object to save desired markers in memory.
  179887. * This must be called before jpeg_read_header() to have the desired effect.
  179888. */
  179889. GLOBAL(void)
  179890. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  179891. {
  179892. #ifdef SAVE_MARKERS_SUPPORTED
  179893. int m;
  179894. /* Save comments except under NONE option */
  179895. if (option != JCOPYOPT_NONE) {
  179896. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  179897. }
  179898. /* Save all types of APPn markers iff ALL option */
  179899. if (option == JCOPYOPT_ALL) {
  179900. for (m = 0; m < 16; m++)
  179901. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  179902. }
  179903. #endif /* SAVE_MARKERS_SUPPORTED */
  179904. }
  179905. /* Copy markers saved in the given source object to the destination object.
  179906. * This should be called just after jpeg_start_compress() or
  179907. * jpeg_write_coefficients().
  179908. * Note that those routines will have written the SOI, and also the
  179909. * JFIF APP0 or Adobe APP14 markers if selected.
  179910. */
  179911. GLOBAL(void)
  179912. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179913. JCOPY_OPTION)
  179914. {
  179915. jpeg_saved_marker_ptr marker;
  179916. /* In the current implementation, we don't actually need to examine the
  179917. * option flag here; we just copy everything that got saved.
  179918. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  179919. * if the encoder library already wrote one.
  179920. */
  179921. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  179922. if (dstinfo->write_JFIF_header &&
  179923. marker->marker == JPEG_APP0 &&
  179924. marker->data_length >= 5 &&
  179925. GETJOCTET(marker->data[0]) == 0x4A &&
  179926. GETJOCTET(marker->data[1]) == 0x46 &&
  179927. GETJOCTET(marker->data[2]) == 0x49 &&
  179928. GETJOCTET(marker->data[3]) == 0x46 &&
  179929. GETJOCTET(marker->data[4]) == 0)
  179930. continue; /* reject duplicate JFIF */
  179931. if (dstinfo->write_Adobe_marker &&
  179932. marker->marker == JPEG_APP0+14 &&
  179933. marker->data_length >= 5 &&
  179934. GETJOCTET(marker->data[0]) == 0x41 &&
  179935. GETJOCTET(marker->data[1]) == 0x64 &&
  179936. GETJOCTET(marker->data[2]) == 0x6F &&
  179937. GETJOCTET(marker->data[3]) == 0x62 &&
  179938. GETJOCTET(marker->data[4]) == 0x65)
  179939. continue; /* reject duplicate Adobe */
  179940. #ifdef NEED_FAR_POINTERS
  179941. /* We could use jpeg_write_marker if the data weren't FAR... */
  179942. {
  179943. unsigned int i;
  179944. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  179945. for (i = 0; i < marker->data_length; i++)
  179946. jpeg_write_m_byte(dstinfo, marker->data[i]);
  179947. }
  179948. #else
  179949. jpeg_write_marker(dstinfo, marker->marker,
  179950. marker->data, marker->data_length);
  179951. #endif
  179952. }
  179953. }
  179954. /*** End of inlined file: transupp.c ***/
  179955. #else
  179956. #define JPEG_INTERNALS
  179957. #undef FAR
  179958. #include <jpeglib.h>
  179959. #endif
  179960. }
  179961. #undef max
  179962. #undef min
  179963. #if JUCE_MSVC
  179964. #pragma warning (pop)
  179965. #endif
  179966. BEGIN_JUCE_NAMESPACE
  179967. namespace JPEGHelpers
  179968. {
  179969. using namespace jpeglibNamespace;
  179970. #if ! JUCE_MSVC
  179971. using jpeglibNamespace::boolean;
  179972. #endif
  179973. struct JPEGDecodingFailure {};
  179974. static void fatalErrorHandler (j_common_ptr)
  179975. {
  179976. throw JPEGDecodingFailure();
  179977. }
  179978. static void silentErrorCallback1 (j_common_ptr) {}
  179979. static void silentErrorCallback2 (j_common_ptr, int) {}
  179980. static void silentErrorCallback3 (j_common_ptr, char*) {}
  179981. static void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  179982. {
  179983. zerostruct (err);
  179984. err.error_exit = fatalErrorHandler;
  179985. err.emit_message = silentErrorCallback2;
  179986. err.output_message = silentErrorCallback1;
  179987. err.format_message = silentErrorCallback3;
  179988. err.reset_error_mgr = silentErrorCallback1;
  179989. }
  179990. static void dummyCallback1 (j_decompress_ptr)
  179991. {
  179992. }
  179993. static void jpegSkip (j_decompress_ptr decompStruct, long num)
  179994. {
  179995. decompStruct->src->next_input_byte += num;
  179996. num = jmin (num, (long) decompStruct->src->bytes_in_buffer);
  179997. decompStruct->src->bytes_in_buffer -= num;
  179998. }
  179999. static boolean jpegFill (j_decompress_ptr)
  180000. {
  180001. return 0;
  180002. }
  180003. static const int jpegBufferSize = 512;
  180004. struct JuceJpegDest : public jpeg_destination_mgr
  180005. {
  180006. OutputStream* output;
  180007. char* buffer;
  180008. };
  180009. static void jpegWriteInit (j_compress_ptr)
  180010. {
  180011. }
  180012. static void jpegWriteTerminate (j_compress_ptr cinfo)
  180013. {
  180014. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  180015. const size_t numToWrite = jpegBufferSize - dest->free_in_buffer;
  180016. dest->output->write (dest->buffer, (int) numToWrite);
  180017. }
  180018. static boolean jpegWriteFlush (j_compress_ptr cinfo)
  180019. {
  180020. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  180021. const int numToWrite = jpegBufferSize;
  180022. dest->next_output_byte = reinterpret_cast <JOCTET*> (dest->buffer);
  180023. dest->free_in_buffer = jpegBufferSize;
  180024. return dest->output->write (dest->buffer, numToWrite);
  180025. }
  180026. }
  180027. JPEGImageFormat::JPEGImageFormat()
  180028. : quality (-1.0f)
  180029. {
  180030. }
  180031. JPEGImageFormat::~JPEGImageFormat() {}
  180032. void JPEGImageFormat::setQuality (const float newQuality)
  180033. {
  180034. quality = newQuality;
  180035. }
  180036. const String JPEGImageFormat::getFormatName()
  180037. {
  180038. return "JPEG";
  180039. }
  180040. bool JPEGImageFormat::canUnderstand (InputStream& in)
  180041. {
  180042. const int bytesNeeded = 10;
  180043. uint8 header [bytesNeeded];
  180044. if (in.read (header, bytesNeeded) == bytesNeeded)
  180045. {
  180046. return header[0] == 0xff
  180047. && header[1] == 0xd8
  180048. && header[2] == 0xff
  180049. && (header[3] == 0xe0 || header[3] == 0xe1);
  180050. }
  180051. return false;
  180052. }
  180053. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  180054. const Image juce_loadWithCoreImage (InputStream& input);
  180055. #endif
  180056. const Image JPEGImageFormat::decodeImage (InputStream& in)
  180057. {
  180058. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  180059. return juce_loadWithCoreImage (in);
  180060. #else
  180061. using namespace jpeglibNamespace;
  180062. using namespace JPEGHelpers;
  180063. MemoryOutputStream mb;
  180064. mb.writeFromInputStream (in, -1);
  180065. Image image;
  180066. if (mb.getDataSize() > 16)
  180067. {
  180068. struct jpeg_decompress_struct jpegDecompStruct;
  180069. struct jpeg_error_mgr jerr;
  180070. setupSilentErrorHandler (jerr);
  180071. jpegDecompStruct.err = &jerr;
  180072. jpeg_create_decompress (&jpegDecompStruct);
  180073. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  180074. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  180075. jpegDecompStruct.src->init_source = dummyCallback1;
  180076. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  180077. jpegDecompStruct.src->skip_input_data = jpegSkip;
  180078. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  180079. jpegDecompStruct.src->term_source = dummyCallback1;
  180080. jpegDecompStruct.src->next_input_byte = static_cast <const unsigned char*> (mb.getData());
  180081. jpegDecompStruct.src->bytes_in_buffer = mb.getDataSize();
  180082. try
  180083. {
  180084. jpeg_read_header (&jpegDecompStruct, TRUE);
  180085. jpeg_calc_output_dimensions (&jpegDecompStruct);
  180086. const int width = jpegDecompStruct.output_width;
  180087. const int height = jpegDecompStruct.output_height;
  180088. jpegDecompStruct.out_color_space = JCS_RGB;
  180089. JSAMPARRAY buffer
  180090. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  180091. JPOOL_IMAGE,
  180092. width * 3, 1);
  180093. if (jpeg_start_decompress (&jpegDecompStruct))
  180094. {
  180095. image = Image (Image::RGB, width, height, false);
  180096. const bool hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  180097. const Image::BitmapData destData (image, true);
  180098. for (int y = 0; y < height; ++y)
  180099. {
  180100. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  180101. const uint8* src = *buffer;
  180102. uint8* dest = destData.getLinePointer (y);
  180103. if (hasAlphaChan)
  180104. {
  180105. for (int i = width; --i >= 0;)
  180106. {
  180107. ((PixelARGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  180108. ((PixelARGB*) dest)->premultiply();
  180109. dest += destData.pixelStride;
  180110. src += 3;
  180111. }
  180112. }
  180113. else
  180114. {
  180115. for (int i = width; --i >= 0;)
  180116. {
  180117. ((PixelRGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  180118. dest += destData.pixelStride;
  180119. src += 3;
  180120. }
  180121. }
  180122. }
  180123. jpeg_finish_decompress (&jpegDecompStruct);
  180124. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  180125. }
  180126. jpeg_destroy_decompress (&jpegDecompStruct);
  180127. }
  180128. catch (...)
  180129. {}
  180130. }
  180131. return image;
  180132. #endif
  180133. }
  180134. bool JPEGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  180135. {
  180136. using namespace jpeglibNamespace;
  180137. using namespace JPEGHelpers;
  180138. if (image.hasAlphaChannel())
  180139. {
  180140. // this method could fill the background in white and still save the image..
  180141. jassertfalse;
  180142. return true;
  180143. }
  180144. struct jpeg_compress_struct jpegCompStruct;
  180145. struct jpeg_error_mgr jerr;
  180146. setupSilentErrorHandler (jerr);
  180147. jpegCompStruct.err = &jerr;
  180148. jpeg_create_compress (&jpegCompStruct);
  180149. JuceJpegDest dest;
  180150. jpegCompStruct.dest = &dest;
  180151. dest.output = &out;
  180152. HeapBlock <char> tempBuffer (jpegBufferSize);
  180153. dest.buffer = tempBuffer;
  180154. dest.next_output_byte = (JOCTET*) dest.buffer;
  180155. dest.free_in_buffer = jpegBufferSize;
  180156. dest.init_destination = jpegWriteInit;
  180157. dest.empty_output_buffer = jpegWriteFlush;
  180158. dest.term_destination = jpegWriteTerminate;
  180159. jpegCompStruct.image_width = image.getWidth();
  180160. jpegCompStruct.image_height = image.getHeight();
  180161. jpegCompStruct.input_components = 3;
  180162. jpegCompStruct.in_color_space = JCS_RGB;
  180163. jpegCompStruct.write_JFIF_header = 1;
  180164. jpegCompStruct.X_density = 72;
  180165. jpegCompStruct.Y_density = 72;
  180166. jpeg_set_defaults (&jpegCompStruct);
  180167. jpegCompStruct.dct_method = JDCT_FLOAT;
  180168. jpegCompStruct.optimize_coding = 1;
  180169. //jpegCompStruct.smoothing_factor = 10;
  180170. if (quality < 0.0f)
  180171. quality = 0.85f;
  180172. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundToInt (quality * 100.0f)), TRUE);
  180173. jpeg_start_compress (&jpegCompStruct, TRUE);
  180174. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  180175. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  180176. JPOOL_IMAGE, strideBytes, 1);
  180177. const Image::BitmapData srcData (image, false);
  180178. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  180179. {
  180180. const uint8* src = srcData.getLinePointer (jpegCompStruct.next_scanline);
  180181. uint8* dst = *buffer;
  180182. for (int i = jpegCompStruct.image_width; --i >= 0;)
  180183. {
  180184. *dst++ = ((const PixelRGB*) src)->getRed();
  180185. *dst++ = ((const PixelRGB*) src)->getGreen();
  180186. *dst++ = ((const PixelRGB*) src)->getBlue();
  180187. src += srcData.pixelStride;
  180188. }
  180189. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  180190. }
  180191. jpeg_finish_compress (&jpegCompStruct);
  180192. jpeg_destroy_compress (&jpegCompStruct);
  180193. out.flush();
  180194. return true;
  180195. }
  180196. END_JUCE_NAMESPACE
  180197. /*** End of inlined file: juce_JPEGLoader.cpp ***/
  180198. /*** Start of inlined file: juce_PNGLoader.cpp ***/
  180199. #if JUCE_MSVC
  180200. #pragma warning (push)
  180201. #pragma warning (disable: 4390 4611)
  180202. #endif
  180203. namespace zlibNamespace
  180204. {
  180205. #if JUCE_INCLUDE_ZLIB_CODE
  180206. #undef OS_CODE
  180207. #undef fdopen
  180208. #undef OS_CODE
  180209. #else
  180210. #include <zlib.h>
  180211. #endif
  180212. }
  180213. namespace pnglibNamespace
  180214. {
  180215. using namespace zlibNamespace;
  180216. #if JUCE_INCLUDE_PNGLIB_CODE
  180217. #if _MSC_VER != 1310
  180218. using ::calloc; // (causes conflict in VS.NET 2003)
  180219. using ::malloc;
  180220. using ::free;
  180221. #endif
  180222. using ::abs;
  180223. #define PNG_INTERNAL
  180224. #define NO_DUMMY_DECL
  180225. #define PNG_SETJMP_NOT_SUPPORTED
  180226. /*** Start of inlined file: png.h ***/
  180227. /* png.h - header file for PNG reference library
  180228. *
  180229. * libpng version 1.2.21 - October 4, 2007
  180230. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180231. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180232. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180233. *
  180234. * Authors and maintainers:
  180235. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  180236. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  180237. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  180238. * See also "Contributing Authors", below.
  180239. *
  180240. * Note about libpng version numbers:
  180241. *
  180242. * Due to various miscommunications, unforeseen code incompatibilities
  180243. * and occasional factors outside the authors' control, version numbering
  180244. * on the library has not always been consistent and straightforward.
  180245. * The following table summarizes matters since version 0.89c, which was
  180246. * the first widely used release:
  180247. *
  180248. * source png.h png.h shared-lib
  180249. * version string int version
  180250. * ------- ------ ----- ----------
  180251. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  180252. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  180253. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  180254. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  180255. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  180256. * 0.97c 0.97 97 2.0.97
  180257. * 0.98 0.98 98 2.0.98
  180258. * 0.99 0.99 98 2.0.99
  180259. * 0.99a-m 0.99 99 2.0.99
  180260. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  180261. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  180262. * 1.0.1 png.h string is 10001 2.1.0
  180263. * 1.0.1a-e identical to the 10002 from here on, the shared library
  180264. * 1.0.2 source version) 10002 is 2.V where V is the source code
  180265. * 1.0.2a-b 10003 version, except as noted.
  180266. * 1.0.3 10003
  180267. * 1.0.3a-d 10004
  180268. * 1.0.4 10004
  180269. * 1.0.4a-f 10005
  180270. * 1.0.5 (+ 2 patches) 10005
  180271. * 1.0.5a-d 10006
  180272. * 1.0.5e-r 10100 (not source compatible)
  180273. * 1.0.5s-v 10006 (not binary compatible)
  180274. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  180275. * 1.0.6d-f 10007 (still binary incompatible)
  180276. * 1.0.6g 10007
  180277. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  180278. * 1.0.6i 10007 10.6i
  180279. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  180280. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  180281. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  180282. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  180283. * 1.0.7 1 10007 (still compatible)
  180284. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  180285. * 1.0.8rc1 1 10008 2.1.0.8rc1
  180286. * 1.0.8 1 10008 2.1.0.8
  180287. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  180288. * 1.0.9rc1 1 10009 2.1.0.9rc1
  180289. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  180290. * 1.0.9rc2 1 10009 2.1.0.9rc2
  180291. * 1.0.9 1 10009 2.1.0.9
  180292. * 1.0.10beta1 1 10010 2.1.0.10beta1
  180293. * 1.0.10rc1 1 10010 2.1.0.10rc1
  180294. * 1.0.10 1 10010 2.1.0.10
  180295. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  180296. * 1.0.11rc1 1 10011 2.1.0.11rc1
  180297. * 1.0.11 1 10011 2.1.0.11
  180298. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  180299. * 1.0.12rc1 2 10012 2.1.0.12rc1
  180300. * 1.0.12 2 10012 2.1.0.12
  180301. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  180302. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  180303. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  180304. * 1.2.0rc1 3 10200 3.1.2.0rc1
  180305. * 1.2.0 3 10200 3.1.2.0
  180306. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  180307. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  180308. * 1.2.1 3 10201 3.1.2.1
  180309. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  180310. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  180311. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  180312. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  180313. * 1.0.13 10 10013 10.so.0.1.0.13
  180314. * 1.2.2 12 10202 12.so.0.1.2.2
  180315. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  180316. * 1.2.3 12 10203 12.so.0.1.2.3
  180317. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  180318. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  180319. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  180320. * 1.0.14 10 10014 10.so.0.1.0.14
  180321. * 1.2.4 13 10204 12.so.0.1.2.4
  180322. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  180323. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  180324. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  180325. * 1.0.15 10 10015 10.so.0.1.0.15
  180326. * 1.2.5 13 10205 12.so.0.1.2.5
  180327. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  180328. * 1.0.16 10 10016 10.so.0.1.0.16
  180329. * 1.2.6 13 10206 12.so.0.1.2.6
  180330. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  180331. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  180332. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  180333. * 1.0.17 10 10017 10.so.0.1.0.17
  180334. * 1.2.7 13 10207 12.so.0.1.2.7
  180335. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  180336. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  180337. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  180338. * 1.0.18 10 10018 10.so.0.1.0.18
  180339. * 1.2.8 13 10208 12.so.0.1.2.8
  180340. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  180341. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  180342. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  180343. * 1.2.9 13 10209 12.so.0.9[.0]
  180344. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  180345. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  180346. * 1.2.10 13 10210 12.so.0.10[.0]
  180347. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  180348. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  180349. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  180350. * 1.0.19 10 10019 10.so.0.19[.0]
  180351. * 1.2.11 13 10211 12.so.0.11[.0]
  180352. * 1.0.20 10 10020 10.so.0.20[.0]
  180353. * 1.2.12 13 10212 12.so.0.12[.0]
  180354. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  180355. * 1.0.21 10 10021 10.so.0.21[.0]
  180356. * 1.2.13 13 10213 12.so.0.13[.0]
  180357. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  180358. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  180359. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  180360. * 1.0.22 10 10022 10.so.0.22[.0]
  180361. * 1.2.14 13 10214 12.so.0.14[.0]
  180362. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  180363. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  180364. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  180365. * 1.0.23 10 10023 10.so.0.23[.0]
  180366. * 1.2.15 13 10215 12.so.0.15[.0]
  180367. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  180368. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  180369. * 1.0.24 10 10024 10.so.0.24[.0]
  180370. * 1.2.16 13 10216 12.so.0.16[.0]
  180371. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  180372. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  180373. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  180374. * 1.0.25 10 10025 10.so.0.25[.0]
  180375. * 1.2.17 13 10217 12.so.0.17[.0]
  180376. * 1.0.26 10 10026 10.so.0.26[.0]
  180377. * 1.2.18 13 10218 12.so.0.18[.0]
  180378. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  180379. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  180380. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  180381. * 1.0.27 10 10027 10.so.0.27[.0]
  180382. * 1.2.19 13 10219 12.so.0.19[.0]
  180383. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  180384. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  180385. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  180386. * 1.0.28 10 10028 10.so.0.28[.0]
  180387. * 1.2.20 13 10220 12.so.0.20[.0]
  180388. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  180389. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  180390. * 1.0.29 10 10029 10.so.0.29[.0]
  180391. * 1.2.21 13 10221 12.so.0.21[.0]
  180392. *
  180393. * Henceforth the source version will match the shared-library major
  180394. * and minor numbers; the shared-library major version number will be
  180395. * used for changes in backward compatibility, as it is intended. The
  180396. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  180397. * for applications, is an unsigned integer of the form xyyzz corresponding
  180398. * to the source version x.y.z (leading zeros in y and z). Beta versions
  180399. * were given the previous public release number plus a letter, until
  180400. * version 1.0.6j; from then on they were given the upcoming public
  180401. * release number plus "betaNN" or "rcN".
  180402. *
  180403. * Binary incompatibility exists only when applications make direct access
  180404. * to the info_ptr or png_ptr members through png.h, and the compiled
  180405. * application is loaded with a different version of the library.
  180406. *
  180407. * DLLNUM will change each time there are forward or backward changes
  180408. * in binary compatibility (e.g., when a new feature is added).
  180409. *
  180410. * See libpng.txt or libpng.3 for more information. The PNG specification
  180411. * is available as a W3C Recommendation and as an ISO Specification,
  180412. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  180413. */
  180414. /*
  180415. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  180416. *
  180417. * If you modify libpng you may insert additional notices immediately following
  180418. * this sentence.
  180419. *
  180420. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  180421. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  180422. * distributed according to the same disclaimer and license as libpng-1.2.5
  180423. * with the following individual added to the list of Contributing Authors:
  180424. *
  180425. * Cosmin Truta
  180426. *
  180427. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  180428. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  180429. * distributed according to the same disclaimer and license as libpng-1.0.6
  180430. * with the following individuals added to the list of Contributing Authors:
  180431. *
  180432. * Simon-Pierre Cadieux
  180433. * Eric S. Raymond
  180434. * Gilles Vollant
  180435. *
  180436. * and with the following additions to the disclaimer:
  180437. *
  180438. * There is no warranty against interference with your enjoyment of the
  180439. * library or against infringement. There is no warranty that our
  180440. * efforts or the library will fulfill any of your particular purposes
  180441. * or needs. This library is provided with all faults, and the entire
  180442. * risk of satisfactory quality, performance, accuracy, and effort is with
  180443. * the user.
  180444. *
  180445. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  180446. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  180447. * distributed according to the same disclaimer and license as libpng-0.96,
  180448. * with the following individuals added to the list of Contributing Authors:
  180449. *
  180450. * Tom Lane
  180451. * Glenn Randers-Pehrson
  180452. * Willem van Schaik
  180453. *
  180454. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  180455. * Copyright (c) 1996, 1997 Andreas Dilger
  180456. * Distributed according to the same disclaimer and license as libpng-0.88,
  180457. * with the following individuals added to the list of Contributing Authors:
  180458. *
  180459. * John Bowler
  180460. * Kevin Bracey
  180461. * Sam Bushell
  180462. * Magnus Holmgren
  180463. * Greg Roelofs
  180464. * Tom Tanner
  180465. *
  180466. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  180467. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  180468. *
  180469. * For the purposes of this copyright and license, "Contributing Authors"
  180470. * is defined as the following set of individuals:
  180471. *
  180472. * Andreas Dilger
  180473. * Dave Martindale
  180474. * Guy Eric Schalnat
  180475. * Paul Schmidt
  180476. * Tim Wegner
  180477. *
  180478. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  180479. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  180480. * including, without limitation, the warranties of merchantability and of
  180481. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  180482. * assume no liability for direct, indirect, incidental, special, exemplary,
  180483. * or consequential damages, which may result from the use of the PNG
  180484. * Reference Library, even if advised of the possibility of such damage.
  180485. *
  180486. * Permission is hereby granted to use, copy, modify, and distribute this
  180487. * source code, or portions hereof, for any purpose, without fee, subject
  180488. * to the following restrictions:
  180489. *
  180490. * 1. The origin of this source code must not be misrepresented.
  180491. *
  180492. * 2. Altered versions must be plainly marked as such and
  180493. * must not be misrepresented as being the original source.
  180494. *
  180495. * 3. This Copyright notice may not be removed or altered from
  180496. * any source or altered source distribution.
  180497. *
  180498. * The Contributing Authors and Group 42, Inc. specifically permit, without
  180499. * fee, and encourage the use of this source code as a component to
  180500. * supporting the PNG file format in commercial products. If you use this
  180501. * source code in a product, acknowledgment is not required but would be
  180502. * appreciated.
  180503. */
  180504. /*
  180505. * A "png_get_copyright" function is available, for convenient use in "about"
  180506. * boxes and the like:
  180507. *
  180508. * printf("%s",png_get_copyright(NULL));
  180509. *
  180510. * Also, the PNG logo (in PNG format, of course) is supplied in the
  180511. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  180512. */
  180513. /*
  180514. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  180515. * certification mark of the Open Source Initiative.
  180516. */
  180517. /*
  180518. * The contributing authors would like to thank all those who helped
  180519. * with testing, bug fixes, and patience. This wouldn't have been
  180520. * possible without all of you.
  180521. *
  180522. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  180523. */
  180524. /*
  180525. * Y2K compliance in libpng:
  180526. * =========================
  180527. *
  180528. * October 4, 2007
  180529. *
  180530. * Since the PNG Development group is an ad-hoc body, we can't make
  180531. * an official declaration.
  180532. *
  180533. * This is your unofficial assurance that libpng from version 0.71 and
  180534. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  180535. * versions were also Y2K compliant.
  180536. *
  180537. * Libpng only has three year fields. One is a 2-byte unsigned integer
  180538. * that will hold years up to 65535. The other two hold the date in text
  180539. * format, and will hold years up to 9999.
  180540. *
  180541. * The integer is
  180542. * "png_uint_16 year" in png_time_struct.
  180543. *
  180544. * The strings are
  180545. * "png_charp time_buffer" in png_struct and
  180546. * "near_time_buffer", which is a local character string in png.c.
  180547. *
  180548. * There are seven time-related functions:
  180549. * png.c: png_convert_to_rfc_1123() in png.c
  180550. * (formerly png_convert_to_rfc_1152() in error)
  180551. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  180552. * png_convert_from_time_t() in pngwrite.c
  180553. * png_get_tIME() in pngget.c
  180554. * png_handle_tIME() in pngrutil.c, called in pngread.c
  180555. * png_set_tIME() in pngset.c
  180556. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  180557. *
  180558. * All handle dates properly in a Y2K environment. The
  180559. * png_convert_from_time_t() function calls gmtime() to convert from system
  180560. * clock time, which returns (year - 1900), which we properly convert to
  180561. * the full 4-digit year. There is a possibility that applications using
  180562. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  180563. * function, or that they are incorrectly passing only a 2-digit year
  180564. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  180565. * but this is not under our control. The libpng documentation has always
  180566. * stated that it works with 4-digit years, and the APIs have been
  180567. * documented as such.
  180568. *
  180569. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  180570. * integer to hold the year, and can hold years as large as 65535.
  180571. *
  180572. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  180573. * no date-related code.
  180574. *
  180575. * Glenn Randers-Pehrson
  180576. * libpng maintainer
  180577. * PNG Development Group
  180578. */
  180579. #ifndef PNG_H
  180580. #define PNG_H
  180581. /* This is not the place to learn how to use libpng. The file libpng.txt
  180582. * describes how to use libpng, and the file example.c summarizes it
  180583. * with some code on which to build. This file is useful for looking
  180584. * at the actual function definitions and structure components.
  180585. */
  180586. /* Version information for png.h - this should match the version in png.c */
  180587. #define PNG_LIBPNG_VER_STRING "1.2.21"
  180588. #define PNG_HEADER_VERSION_STRING \
  180589. " libpng version 1.2.21 - October 4, 2007\n"
  180590. #define PNG_LIBPNG_VER_SONUM 0
  180591. #define PNG_LIBPNG_VER_DLLNUM 13
  180592. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  180593. #define PNG_LIBPNG_VER_MAJOR 1
  180594. #define PNG_LIBPNG_VER_MINOR 2
  180595. #define PNG_LIBPNG_VER_RELEASE 21
  180596. /* This should match the numeric part of the final component of
  180597. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  180598. #define PNG_LIBPNG_VER_BUILD 0
  180599. /* Release Status */
  180600. #define PNG_LIBPNG_BUILD_ALPHA 1
  180601. #define PNG_LIBPNG_BUILD_BETA 2
  180602. #define PNG_LIBPNG_BUILD_RC 3
  180603. #define PNG_LIBPNG_BUILD_STABLE 4
  180604. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  180605. /* Release-Specific Flags */
  180606. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  180607. PNG_LIBPNG_BUILD_STABLE only */
  180608. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  180609. PNG_LIBPNG_BUILD_SPECIAL */
  180610. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  180611. PNG_LIBPNG_BUILD_PRIVATE */
  180612. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  180613. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  180614. * We must not include leading zeros.
  180615. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  180616. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  180617. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  180618. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  180619. #ifndef PNG_VERSION_INFO_ONLY
  180620. /* include the compression library's header */
  180621. #endif
  180622. /* include all user configurable info, including optional assembler routines */
  180623. /*** Start of inlined file: pngconf.h ***/
  180624. /* pngconf.h - machine configurable file for libpng
  180625. *
  180626. * libpng version 1.2.21 - October 4, 2007
  180627. * For conditions of distribution and use, see copyright notice in png.h
  180628. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180629. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180630. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180631. */
  180632. /* Any machine specific code is near the front of this file, so if you
  180633. * are configuring libpng for a machine, you may want to read the section
  180634. * starting here down to where it starts to typedef png_color, png_text,
  180635. * and png_info.
  180636. */
  180637. #ifndef PNGCONF_H
  180638. #define PNGCONF_H
  180639. #define PNG_1_2_X
  180640. // These are some Juce config settings that should remove any unnecessary code bloat..
  180641. #define PNG_NO_STDIO 1
  180642. #define PNG_DEBUG 0
  180643. #define PNG_NO_WARNINGS 1
  180644. #define PNG_NO_ERROR_TEXT 1
  180645. #define PNG_NO_ERROR_NUMBERS 1
  180646. #define PNG_NO_USER_MEM 1
  180647. #define PNG_NO_READ_iCCP 1
  180648. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  180649. #define PNG_NO_READ_USER_CHUNKS 1
  180650. #define PNG_NO_READ_iTXt 1
  180651. #define PNG_NO_READ_sCAL 1
  180652. #define PNG_NO_READ_sPLT 1
  180653. #define png_error(a, b) png_err(a)
  180654. #define png_warning(a, b)
  180655. #define png_chunk_error(a, b) png_err(a)
  180656. #define png_chunk_warning(a, b)
  180657. /*
  180658. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  180659. * includes the resource compiler for Windows DLL configurations.
  180660. */
  180661. #ifdef PNG_USER_CONFIG
  180662. # ifndef PNG_USER_PRIVATEBUILD
  180663. # define PNG_USER_PRIVATEBUILD
  180664. # endif
  180665. #include "pngusr.h"
  180666. #endif
  180667. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  180668. #ifdef PNG_CONFIGURE_LIBPNG
  180669. #ifdef HAVE_CONFIG_H
  180670. #include "config.h"
  180671. #endif
  180672. #endif
  180673. /*
  180674. * Added at libpng-1.2.8
  180675. *
  180676. * If you create a private DLL you need to define in "pngusr.h" the followings:
  180677. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  180678. * the DLL was built>
  180679. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  180680. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  180681. * distinguish your DLL from those of the official release. These
  180682. * correspond to the trailing letters that come after the version
  180683. * number and must match your private DLL name>
  180684. * e.g. // private DLL "libpng13gx.dll"
  180685. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  180686. *
  180687. * The following macros are also at your disposal if you want to complete the
  180688. * DLL VERSIONINFO structure.
  180689. * - PNG_USER_VERSIONINFO_COMMENTS
  180690. * - PNG_USER_VERSIONINFO_COMPANYNAME
  180691. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  180692. */
  180693. #ifdef __STDC__
  180694. #ifdef SPECIALBUILD
  180695. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  180696. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  180697. #endif
  180698. #ifdef PRIVATEBUILD
  180699. # pragma message("PRIVATEBUILD is deprecated.\
  180700. Use PNG_USER_PRIVATEBUILD instead.")
  180701. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  180702. #endif
  180703. #endif /* __STDC__ */
  180704. #ifndef PNG_VERSION_INFO_ONLY
  180705. /* End of material added to libpng-1.2.8 */
  180706. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  180707. Restored at libpng-1.2.21 */
  180708. # define PNG_WARN_UNINITIALIZED_ROW 1
  180709. /* End of material added at libpng-1.2.19/1.2.21 */
  180710. /* This is the size of the compression buffer, and thus the size of
  180711. * an IDAT chunk. Make this whatever size you feel is best for your
  180712. * machine. One of these will be allocated per png_struct. When this
  180713. * is full, it writes the data to the disk, and does some other
  180714. * calculations. Making this an extremely small size will slow
  180715. * the library down, but you may want to experiment to determine
  180716. * where it becomes significant, if you are concerned with memory
  180717. * usage. Note that zlib allocates at least 32Kb also. For readers,
  180718. * this describes the size of the buffer available to read the data in.
  180719. * Unless this gets smaller than the size of a row (compressed),
  180720. * it should not make much difference how big this is.
  180721. */
  180722. #ifndef PNG_ZBUF_SIZE
  180723. # define PNG_ZBUF_SIZE 8192
  180724. #endif
  180725. /* Enable if you want a write-only libpng */
  180726. #ifndef PNG_NO_READ_SUPPORTED
  180727. # define PNG_READ_SUPPORTED
  180728. #endif
  180729. /* Enable if you want a read-only libpng */
  180730. #ifndef PNG_NO_WRITE_SUPPORTED
  180731. # define PNG_WRITE_SUPPORTED
  180732. #endif
  180733. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  180734. support PNGs that are embedded in MNG datastreams */
  180735. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  180736. # ifndef PNG_MNG_FEATURES_SUPPORTED
  180737. # define PNG_MNG_FEATURES_SUPPORTED
  180738. # endif
  180739. #endif
  180740. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  180741. # ifndef PNG_FLOATING_POINT_SUPPORTED
  180742. # define PNG_FLOATING_POINT_SUPPORTED
  180743. # endif
  180744. #endif
  180745. /* If you are running on a machine where you cannot allocate more
  180746. * than 64K of memory at once, uncomment this. While libpng will not
  180747. * normally need that much memory in a chunk (unless you load up a very
  180748. * large file), zlib needs to know how big of a chunk it can use, and
  180749. * libpng thus makes sure to check any memory allocation to verify it
  180750. * will fit into memory.
  180751. #define PNG_MAX_MALLOC_64K
  180752. */
  180753. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  180754. # define PNG_MAX_MALLOC_64K
  180755. #endif
  180756. /* Special munging to support doing things the 'cygwin' way:
  180757. * 'Normal' png-on-win32 defines/defaults:
  180758. * PNG_BUILD_DLL -- building dll
  180759. * PNG_USE_DLL -- building an application, linking to dll
  180760. * (no define) -- building static library, or building an
  180761. * application and linking to the static lib
  180762. * 'Cygwin' defines/defaults:
  180763. * PNG_BUILD_DLL -- (ignored) building the dll
  180764. * (no define) -- (ignored) building an application, linking to the dll
  180765. * PNG_STATIC -- (ignored) building the static lib, or building an
  180766. * application that links to the static lib.
  180767. * ALL_STATIC -- (ignored) building various static libs, or building an
  180768. * application that links to the static libs.
  180769. * Thus,
  180770. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  180771. * this bit of #ifdefs will define the 'correct' config variables based on
  180772. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  180773. * unnecessary.
  180774. *
  180775. * Also, the precedence order is:
  180776. * ALL_STATIC (since we can't #undef something outside our namespace)
  180777. * PNG_BUILD_DLL
  180778. * PNG_STATIC
  180779. * (nothing) == PNG_USE_DLL
  180780. *
  180781. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  180782. * of auto-import in binutils, we no longer need to worry about
  180783. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  180784. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  180785. * to __declspec() stuff. However, we DO need to worry about
  180786. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  180787. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  180788. */
  180789. #if defined(__CYGWIN__)
  180790. # if defined(ALL_STATIC)
  180791. # if defined(PNG_BUILD_DLL)
  180792. # undef PNG_BUILD_DLL
  180793. # endif
  180794. # if defined(PNG_USE_DLL)
  180795. # undef PNG_USE_DLL
  180796. # endif
  180797. # if defined(PNG_DLL)
  180798. # undef PNG_DLL
  180799. # endif
  180800. # if !defined(PNG_STATIC)
  180801. # define PNG_STATIC
  180802. # endif
  180803. # else
  180804. # if defined (PNG_BUILD_DLL)
  180805. # if defined(PNG_STATIC)
  180806. # undef PNG_STATIC
  180807. # endif
  180808. # if defined(PNG_USE_DLL)
  180809. # undef PNG_USE_DLL
  180810. # endif
  180811. # if !defined(PNG_DLL)
  180812. # define PNG_DLL
  180813. # endif
  180814. # else
  180815. # if defined(PNG_STATIC)
  180816. # if defined(PNG_USE_DLL)
  180817. # undef PNG_USE_DLL
  180818. # endif
  180819. # if defined(PNG_DLL)
  180820. # undef PNG_DLL
  180821. # endif
  180822. # else
  180823. # if !defined(PNG_USE_DLL)
  180824. # define PNG_USE_DLL
  180825. # endif
  180826. # if !defined(PNG_DLL)
  180827. # define PNG_DLL
  180828. # endif
  180829. # endif
  180830. # endif
  180831. # endif
  180832. #endif
  180833. /* This protects us against compilers that run on a windowing system
  180834. * and thus don't have or would rather us not use the stdio types:
  180835. * stdin, stdout, and stderr. The only one currently used is stderr
  180836. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  180837. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  180838. * will also prevent these, plus will prevent the entire set of stdio
  180839. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  180840. * unless (PNG_DEBUG > 0) has been #defined.
  180841. *
  180842. * #define PNG_NO_CONSOLE_IO
  180843. * #define PNG_NO_STDIO
  180844. */
  180845. #if defined(_WIN32_WCE)
  180846. # include <windows.h>
  180847. /* Console I/O functions are not supported on WindowsCE */
  180848. # define PNG_NO_CONSOLE_IO
  180849. # ifdef PNG_DEBUG
  180850. # undef PNG_DEBUG
  180851. # endif
  180852. #endif
  180853. #ifdef PNG_BUILD_DLL
  180854. # ifndef PNG_CONSOLE_IO_SUPPORTED
  180855. # ifndef PNG_NO_CONSOLE_IO
  180856. # define PNG_NO_CONSOLE_IO
  180857. # endif
  180858. # endif
  180859. #endif
  180860. # ifdef PNG_NO_STDIO
  180861. # ifndef PNG_NO_CONSOLE_IO
  180862. # define PNG_NO_CONSOLE_IO
  180863. # endif
  180864. # ifdef PNG_DEBUG
  180865. # if (PNG_DEBUG > 0)
  180866. # include <stdio.h>
  180867. # endif
  180868. # endif
  180869. # else
  180870. # if !defined(_WIN32_WCE)
  180871. /* "stdio.h" functions are not supported on WindowsCE */
  180872. # include <stdio.h>
  180873. # endif
  180874. # endif
  180875. /* This macro protects us against machines that don't have function
  180876. * prototypes (ie K&R style headers). If your compiler does not handle
  180877. * function prototypes, define this macro and use the included ansi2knr.
  180878. * I've always been able to use _NO_PROTO as the indicator, but you may
  180879. * need to drag the empty declaration out in front of here, or change the
  180880. * ifdef to suit your own needs.
  180881. */
  180882. #ifndef PNGARG
  180883. #ifdef OF /* zlib prototype munger */
  180884. # define PNGARG(arglist) OF(arglist)
  180885. #else
  180886. #ifdef _NO_PROTO
  180887. # define PNGARG(arglist) ()
  180888. # ifndef PNG_TYPECAST_NULL
  180889. # define PNG_TYPECAST_NULL
  180890. # endif
  180891. #else
  180892. # define PNGARG(arglist) arglist
  180893. #endif /* _NO_PROTO */
  180894. #endif /* OF */
  180895. #endif /* PNGARG */
  180896. /* Try to determine if we are compiling on a Mac. Note that testing for
  180897. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  180898. * on non-Mac platforms.
  180899. */
  180900. #ifndef MACOS
  180901. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  180902. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  180903. # define MACOS
  180904. # endif
  180905. #endif
  180906. /* enough people need this for various reasons to include it here */
  180907. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  180908. # include <sys/types.h>
  180909. #endif
  180910. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  180911. # define PNG_SETJMP_SUPPORTED
  180912. #endif
  180913. #ifdef PNG_SETJMP_SUPPORTED
  180914. /* This is an attempt to force a single setjmp behaviour on Linux. If
  180915. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  180916. */
  180917. # ifdef __linux__
  180918. # ifdef _BSD_SOURCE
  180919. # define PNG_SAVE_BSD_SOURCE
  180920. # undef _BSD_SOURCE
  180921. # endif
  180922. # ifdef _SETJMP_H
  180923. /* If you encounter a compiler error here, see the explanation
  180924. * near the end of INSTALL.
  180925. */
  180926. __png.h__ already includes setjmp.h;
  180927. __dont__ include it again.;
  180928. # endif
  180929. # endif /* __linux__ */
  180930. /* include setjmp.h for error handling */
  180931. # include <setjmp.h>
  180932. # ifdef __linux__
  180933. # ifdef PNG_SAVE_BSD_SOURCE
  180934. # define _BSD_SOURCE
  180935. # undef PNG_SAVE_BSD_SOURCE
  180936. # endif
  180937. # endif /* __linux__ */
  180938. #endif /* PNG_SETJMP_SUPPORTED */
  180939. #ifdef BSD
  180940. #if ! JUCE_MAC
  180941. # include <strings.h>
  180942. #endif
  180943. #else
  180944. # include <string.h>
  180945. #endif
  180946. /* Other defines for things like memory and the like can go here. */
  180947. #ifdef PNG_INTERNAL
  180948. #include <stdlib.h>
  180949. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  180950. * aren't usually used outside the library (as far as I know), so it is
  180951. * debatable if they should be exported at all. In the future, when it is
  180952. * possible to have run-time registry of chunk-handling functions, some of
  180953. * these will be made available again.
  180954. #define PNG_EXTERN extern
  180955. */
  180956. #define PNG_EXTERN
  180957. /* Other defines specific to compilers can go here. Try to keep
  180958. * them inside an appropriate ifdef/endif pair for portability.
  180959. */
  180960. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  180961. # if defined(MACOS)
  180962. /* We need to check that <math.h> hasn't already been included earlier
  180963. * as it seems it doesn't agree with <fp.h>, yet we should really use
  180964. * <fp.h> if possible.
  180965. */
  180966. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  180967. # include <fp.h>
  180968. # endif
  180969. # else
  180970. # include <math.h>
  180971. # endif
  180972. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  180973. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  180974. * MATH=68881
  180975. */
  180976. # include <m68881.h>
  180977. # endif
  180978. #endif
  180979. /* Codewarrior on NT has linking problems without this. */
  180980. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  180981. # define PNG_ALWAYS_EXTERN
  180982. #endif
  180983. /* This provides the non-ANSI (far) memory allocation routines. */
  180984. #if defined(__TURBOC__) && defined(__MSDOS__)
  180985. # include <mem.h>
  180986. # include <alloc.h>
  180987. #endif
  180988. /* I have no idea why is this necessary... */
  180989. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  180990. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  180991. # include <malloc.h>
  180992. #endif
  180993. /* This controls how fine the dithering gets. As this allocates
  180994. * a largish chunk of memory (32K), those who are not as concerned
  180995. * with dithering quality can decrease some or all of these.
  180996. */
  180997. #ifndef PNG_DITHER_RED_BITS
  180998. # define PNG_DITHER_RED_BITS 5
  180999. #endif
  181000. #ifndef PNG_DITHER_GREEN_BITS
  181001. # define PNG_DITHER_GREEN_BITS 5
  181002. #endif
  181003. #ifndef PNG_DITHER_BLUE_BITS
  181004. # define PNG_DITHER_BLUE_BITS 5
  181005. #endif
  181006. /* This controls how fine the gamma correction becomes when you
  181007. * are only interested in 8 bits anyway. Increasing this value
  181008. * results in more memory being used, and more pow() functions
  181009. * being called to fill in the gamma tables. Don't set this value
  181010. * less then 8, and even that may not work (I haven't tested it).
  181011. */
  181012. #ifndef PNG_MAX_GAMMA_8
  181013. # define PNG_MAX_GAMMA_8 11
  181014. #endif
  181015. /* This controls how much a difference in gamma we can tolerate before
  181016. * we actually start doing gamma conversion.
  181017. */
  181018. #ifndef PNG_GAMMA_THRESHOLD
  181019. # define PNG_GAMMA_THRESHOLD 0.05
  181020. #endif
  181021. #endif /* PNG_INTERNAL */
  181022. /* The following uses const char * instead of char * for error
  181023. * and warning message functions, so some compilers won't complain.
  181024. * If you do not want to use const, define PNG_NO_CONST here.
  181025. */
  181026. #ifndef PNG_NO_CONST
  181027. # define PNG_CONST const
  181028. #else
  181029. # define PNG_CONST
  181030. #endif
  181031. /* The following defines give you the ability to remove code from the
  181032. * library that you will not be using. I wish I could figure out how to
  181033. * automate this, but I can't do that without making it seriously hard
  181034. * on the users. So if you are not using an ability, change the #define
  181035. * to and #undef, and that part of the library will not be compiled. If
  181036. * your linker can't find a function, you may want to make sure the
  181037. * ability is defined here. Some of these depend upon some others being
  181038. * defined. I haven't figured out all the interactions here, so you may
  181039. * have to experiment awhile to get everything to compile. If you are
  181040. * creating or using a shared library, you probably shouldn't touch this,
  181041. * as it will affect the size of the structures, and this will cause bad
  181042. * things to happen if the library and/or application ever change.
  181043. */
  181044. /* Any features you will not be using can be undef'ed here */
  181045. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  181046. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  181047. * on the compile line, then pick and choose which ones to define without
  181048. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  181049. * if you only want to have a png-compliant reader/writer but don't need
  181050. * any of the extra transformations. This saves about 80 kbytes in a
  181051. * typical installation of the library. (PNG_NO_* form added in version
  181052. * 1.0.1c, for consistency)
  181053. */
  181054. /* The size of the png_text structure changed in libpng-1.0.6 when
  181055. * iTXt support was added. iTXt support was turned off by default through
  181056. * libpng-1.2.x, to support old apps that malloc the png_text structure
  181057. * instead of calling png_set_text() and letting libpng malloc it. It
  181058. * was turned on by default in libpng-1.3.0.
  181059. */
  181060. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181061. # ifndef PNG_NO_iTXt_SUPPORTED
  181062. # define PNG_NO_iTXt_SUPPORTED
  181063. # endif
  181064. # ifndef PNG_NO_READ_iTXt
  181065. # define PNG_NO_READ_iTXt
  181066. # endif
  181067. # ifndef PNG_NO_WRITE_iTXt
  181068. # define PNG_NO_WRITE_iTXt
  181069. # endif
  181070. #endif
  181071. #if !defined(PNG_NO_iTXt_SUPPORTED)
  181072. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  181073. # define PNG_READ_iTXt
  181074. # endif
  181075. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  181076. # define PNG_WRITE_iTXt
  181077. # endif
  181078. #endif
  181079. /* The following support, added after version 1.0.0, can be turned off here en
  181080. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  181081. * with old applications that require the length of png_struct and png_info
  181082. * to remain unchanged.
  181083. */
  181084. #ifdef PNG_LEGACY_SUPPORTED
  181085. # define PNG_NO_FREE_ME
  181086. # define PNG_NO_READ_UNKNOWN_CHUNKS
  181087. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  181088. # define PNG_NO_READ_USER_CHUNKS
  181089. # define PNG_NO_READ_iCCP
  181090. # define PNG_NO_WRITE_iCCP
  181091. # define PNG_NO_READ_iTXt
  181092. # define PNG_NO_WRITE_iTXt
  181093. # define PNG_NO_READ_sCAL
  181094. # define PNG_NO_WRITE_sCAL
  181095. # define PNG_NO_READ_sPLT
  181096. # define PNG_NO_WRITE_sPLT
  181097. # define PNG_NO_INFO_IMAGE
  181098. # define PNG_NO_READ_RGB_TO_GRAY
  181099. # define PNG_NO_READ_USER_TRANSFORM
  181100. # define PNG_NO_WRITE_USER_TRANSFORM
  181101. # define PNG_NO_USER_MEM
  181102. # define PNG_NO_READ_EMPTY_PLTE
  181103. # define PNG_NO_MNG_FEATURES
  181104. # define PNG_NO_FIXED_POINT_SUPPORTED
  181105. #endif
  181106. /* Ignore attempt to turn off both floating and fixed point support */
  181107. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  181108. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  181109. # define PNG_FIXED_POINT_SUPPORTED
  181110. #endif
  181111. #ifndef PNG_NO_FREE_ME
  181112. # define PNG_FREE_ME_SUPPORTED
  181113. #endif
  181114. #if defined(PNG_READ_SUPPORTED)
  181115. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  181116. !defined(PNG_NO_READ_TRANSFORMS)
  181117. # define PNG_READ_TRANSFORMS_SUPPORTED
  181118. #endif
  181119. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  181120. # ifndef PNG_NO_READ_EXPAND
  181121. # define PNG_READ_EXPAND_SUPPORTED
  181122. # endif
  181123. # ifndef PNG_NO_READ_SHIFT
  181124. # define PNG_READ_SHIFT_SUPPORTED
  181125. # endif
  181126. # ifndef PNG_NO_READ_PACK
  181127. # define PNG_READ_PACK_SUPPORTED
  181128. # endif
  181129. # ifndef PNG_NO_READ_BGR
  181130. # define PNG_READ_BGR_SUPPORTED
  181131. # endif
  181132. # ifndef PNG_NO_READ_SWAP
  181133. # define PNG_READ_SWAP_SUPPORTED
  181134. # endif
  181135. # ifndef PNG_NO_READ_PACKSWAP
  181136. # define PNG_READ_PACKSWAP_SUPPORTED
  181137. # endif
  181138. # ifndef PNG_NO_READ_INVERT
  181139. # define PNG_READ_INVERT_SUPPORTED
  181140. # endif
  181141. # ifndef PNG_NO_READ_DITHER
  181142. # define PNG_READ_DITHER_SUPPORTED
  181143. # endif
  181144. # ifndef PNG_NO_READ_BACKGROUND
  181145. # define PNG_READ_BACKGROUND_SUPPORTED
  181146. # endif
  181147. # ifndef PNG_NO_READ_16_TO_8
  181148. # define PNG_READ_16_TO_8_SUPPORTED
  181149. # endif
  181150. # ifndef PNG_NO_READ_FILLER
  181151. # define PNG_READ_FILLER_SUPPORTED
  181152. # endif
  181153. # ifndef PNG_NO_READ_GAMMA
  181154. # define PNG_READ_GAMMA_SUPPORTED
  181155. # endif
  181156. # ifndef PNG_NO_READ_GRAY_TO_RGB
  181157. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  181158. # endif
  181159. # ifndef PNG_NO_READ_SWAP_ALPHA
  181160. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  181161. # endif
  181162. # ifndef PNG_NO_READ_INVERT_ALPHA
  181163. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  181164. # endif
  181165. # ifndef PNG_NO_READ_STRIP_ALPHA
  181166. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  181167. # endif
  181168. # ifndef PNG_NO_READ_USER_TRANSFORM
  181169. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  181170. # endif
  181171. # ifndef PNG_NO_READ_RGB_TO_GRAY
  181172. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  181173. # endif
  181174. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  181175. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  181176. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  181177. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  181178. #endif /* about interlacing capability! You'll */
  181179. /* still have interlacing unless you change the following line: */
  181180. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  181181. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  181182. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  181183. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  181184. # endif
  181185. #endif
  181186. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181187. /* Deprecated, will be removed from version 2.0.0.
  181188. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  181189. #ifndef PNG_NO_READ_EMPTY_PLTE
  181190. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  181191. #endif
  181192. #endif
  181193. #endif /* PNG_READ_SUPPORTED */
  181194. #if defined(PNG_WRITE_SUPPORTED)
  181195. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  181196. !defined(PNG_NO_WRITE_TRANSFORMS)
  181197. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  181198. #endif
  181199. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  181200. # ifndef PNG_NO_WRITE_SHIFT
  181201. # define PNG_WRITE_SHIFT_SUPPORTED
  181202. # endif
  181203. # ifndef PNG_NO_WRITE_PACK
  181204. # define PNG_WRITE_PACK_SUPPORTED
  181205. # endif
  181206. # ifndef PNG_NO_WRITE_BGR
  181207. # define PNG_WRITE_BGR_SUPPORTED
  181208. # endif
  181209. # ifndef PNG_NO_WRITE_SWAP
  181210. # define PNG_WRITE_SWAP_SUPPORTED
  181211. # endif
  181212. # ifndef PNG_NO_WRITE_PACKSWAP
  181213. # define PNG_WRITE_PACKSWAP_SUPPORTED
  181214. # endif
  181215. # ifndef PNG_NO_WRITE_INVERT
  181216. # define PNG_WRITE_INVERT_SUPPORTED
  181217. # endif
  181218. # ifndef PNG_NO_WRITE_FILLER
  181219. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  181220. # endif
  181221. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  181222. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  181223. # endif
  181224. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  181225. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  181226. # endif
  181227. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  181228. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  181229. # endif
  181230. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  181231. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  181232. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  181233. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  181234. encoders, but can cause trouble
  181235. if left undefined */
  181236. #endif
  181237. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  181238. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  181239. defined(PNG_FLOATING_POINT_SUPPORTED)
  181240. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  181241. #endif
  181242. #ifndef PNG_NO_WRITE_FLUSH
  181243. # define PNG_WRITE_FLUSH_SUPPORTED
  181244. #endif
  181245. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181246. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  181247. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  181248. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  181249. #endif
  181250. #endif
  181251. #endif /* PNG_WRITE_SUPPORTED */
  181252. #ifndef PNG_1_0_X
  181253. # ifndef PNG_NO_ERROR_NUMBERS
  181254. # define PNG_ERROR_NUMBERS_SUPPORTED
  181255. # endif
  181256. #endif /* PNG_1_0_X */
  181257. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  181258. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  181259. # ifndef PNG_NO_USER_TRANSFORM_PTR
  181260. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  181261. # endif
  181262. #endif
  181263. #ifndef PNG_NO_STDIO
  181264. # define PNG_TIME_RFC1123_SUPPORTED
  181265. #endif
  181266. /* This adds extra functions in pngget.c for accessing data from the
  181267. * info pointer (added in version 0.99)
  181268. * png_get_image_width()
  181269. * png_get_image_height()
  181270. * png_get_bit_depth()
  181271. * png_get_color_type()
  181272. * png_get_compression_type()
  181273. * png_get_filter_type()
  181274. * png_get_interlace_type()
  181275. * png_get_pixel_aspect_ratio()
  181276. * png_get_pixels_per_meter()
  181277. * png_get_x_offset_pixels()
  181278. * png_get_y_offset_pixels()
  181279. * png_get_x_offset_microns()
  181280. * png_get_y_offset_microns()
  181281. */
  181282. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  181283. # define PNG_EASY_ACCESS_SUPPORTED
  181284. #endif
  181285. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  181286. * and removed from version 1.2.20. The following will be removed
  181287. * from libpng-1.4.0
  181288. */
  181289. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  181290. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  181291. # define PNG_OPTIMIZED_CODE_SUPPORTED
  181292. # endif
  181293. #endif
  181294. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  181295. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  181296. # define PNG_ASSEMBLER_CODE_SUPPORTED
  181297. # endif
  181298. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  181299. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  181300. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181301. # define PNG_NO_MMX_CODE
  181302. # endif
  181303. # endif
  181304. # if defined(__APPLE__)
  181305. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181306. # define PNG_NO_MMX_CODE
  181307. # endif
  181308. # endif
  181309. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  181310. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181311. # define PNG_NO_MMX_CODE
  181312. # endif
  181313. # endif
  181314. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181315. # define PNG_MMX_CODE_SUPPORTED
  181316. # endif
  181317. #endif
  181318. /* end of obsolete code to be removed from libpng-1.4.0 */
  181319. #if !defined(PNG_1_0_X)
  181320. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  181321. # define PNG_USER_MEM_SUPPORTED
  181322. #endif
  181323. #endif /* PNG_1_0_X */
  181324. /* Added at libpng-1.2.6 */
  181325. #if !defined(PNG_1_0_X)
  181326. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  181327. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  181328. # define PNG_SET_USER_LIMITS_SUPPORTED
  181329. #endif
  181330. #endif
  181331. #endif /* PNG_1_0_X */
  181332. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  181333. * how large, set these limits to 0x7fffffffL
  181334. */
  181335. #ifndef PNG_USER_WIDTH_MAX
  181336. # define PNG_USER_WIDTH_MAX 1000000L
  181337. #endif
  181338. #ifndef PNG_USER_HEIGHT_MAX
  181339. # define PNG_USER_HEIGHT_MAX 1000000L
  181340. #endif
  181341. /* These are currently experimental features, define them if you want */
  181342. /* very little testing */
  181343. /*
  181344. #ifdef PNG_READ_SUPPORTED
  181345. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181346. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181347. # endif
  181348. #endif
  181349. */
  181350. /* This is only for PowerPC big-endian and 680x0 systems */
  181351. /* some testing */
  181352. /*
  181353. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  181354. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  181355. #endif
  181356. */
  181357. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  181358. /*
  181359. #define PNG_NO_POINTER_INDEXING
  181360. */
  181361. /* These functions are turned off by default, as they will be phased out. */
  181362. /*
  181363. #define PNG_USELESS_TESTS_SUPPORTED
  181364. #define PNG_CORRECT_PALETTE_SUPPORTED
  181365. */
  181366. /* Any chunks you are not interested in, you can undef here. The
  181367. * ones that allocate memory may be expecially important (hIST,
  181368. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  181369. * a bit smaller.
  181370. */
  181371. #if defined(PNG_READ_SUPPORTED) && \
  181372. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181373. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  181374. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181375. #endif
  181376. #if defined(PNG_WRITE_SUPPORTED) && \
  181377. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181378. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  181379. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181380. #endif
  181381. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181382. #ifdef PNG_NO_READ_TEXT
  181383. # define PNG_NO_READ_iTXt
  181384. # define PNG_NO_READ_tEXt
  181385. # define PNG_NO_READ_zTXt
  181386. #endif
  181387. #ifndef PNG_NO_READ_bKGD
  181388. # define PNG_READ_bKGD_SUPPORTED
  181389. # define PNG_bKGD_SUPPORTED
  181390. #endif
  181391. #ifndef PNG_NO_READ_cHRM
  181392. # define PNG_READ_cHRM_SUPPORTED
  181393. # define PNG_cHRM_SUPPORTED
  181394. #endif
  181395. #ifndef PNG_NO_READ_gAMA
  181396. # define PNG_READ_gAMA_SUPPORTED
  181397. # define PNG_gAMA_SUPPORTED
  181398. #endif
  181399. #ifndef PNG_NO_READ_hIST
  181400. # define PNG_READ_hIST_SUPPORTED
  181401. # define PNG_hIST_SUPPORTED
  181402. #endif
  181403. #ifndef PNG_NO_READ_iCCP
  181404. # define PNG_READ_iCCP_SUPPORTED
  181405. # define PNG_iCCP_SUPPORTED
  181406. #endif
  181407. #ifndef PNG_NO_READ_iTXt
  181408. # ifndef PNG_READ_iTXt_SUPPORTED
  181409. # define PNG_READ_iTXt_SUPPORTED
  181410. # endif
  181411. # ifndef PNG_iTXt_SUPPORTED
  181412. # define PNG_iTXt_SUPPORTED
  181413. # endif
  181414. #endif
  181415. #ifndef PNG_NO_READ_oFFs
  181416. # define PNG_READ_oFFs_SUPPORTED
  181417. # define PNG_oFFs_SUPPORTED
  181418. #endif
  181419. #ifndef PNG_NO_READ_pCAL
  181420. # define PNG_READ_pCAL_SUPPORTED
  181421. # define PNG_pCAL_SUPPORTED
  181422. #endif
  181423. #ifndef PNG_NO_READ_sCAL
  181424. # define PNG_READ_sCAL_SUPPORTED
  181425. # define PNG_sCAL_SUPPORTED
  181426. #endif
  181427. #ifndef PNG_NO_READ_pHYs
  181428. # define PNG_READ_pHYs_SUPPORTED
  181429. # define PNG_pHYs_SUPPORTED
  181430. #endif
  181431. #ifndef PNG_NO_READ_sBIT
  181432. # define PNG_READ_sBIT_SUPPORTED
  181433. # define PNG_sBIT_SUPPORTED
  181434. #endif
  181435. #ifndef PNG_NO_READ_sPLT
  181436. # define PNG_READ_sPLT_SUPPORTED
  181437. # define PNG_sPLT_SUPPORTED
  181438. #endif
  181439. #ifndef PNG_NO_READ_sRGB
  181440. # define PNG_READ_sRGB_SUPPORTED
  181441. # define PNG_sRGB_SUPPORTED
  181442. #endif
  181443. #ifndef PNG_NO_READ_tEXt
  181444. # define PNG_READ_tEXt_SUPPORTED
  181445. # define PNG_tEXt_SUPPORTED
  181446. #endif
  181447. #ifndef PNG_NO_READ_tIME
  181448. # define PNG_READ_tIME_SUPPORTED
  181449. # define PNG_tIME_SUPPORTED
  181450. #endif
  181451. #ifndef PNG_NO_READ_tRNS
  181452. # define PNG_READ_tRNS_SUPPORTED
  181453. # define PNG_tRNS_SUPPORTED
  181454. #endif
  181455. #ifndef PNG_NO_READ_zTXt
  181456. # define PNG_READ_zTXt_SUPPORTED
  181457. # define PNG_zTXt_SUPPORTED
  181458. #endif
  181459. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  181460. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  181461. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181462. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181463. # endif
  181464. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181465. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181466. # endif
  181467. #endif
  181468. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  181469. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  181470. # define PNG_READ_USER_CHUNKS_SUPPORTED
  181471. # define PNG_USER_CHUNKS_SUPPORTED
  181472. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  181473. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  181474. # endif
  181475. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  181476. # undef PNG_NO_HANDLE_AS_UNKNOWN
  181477. # endif
  181478. #endif
  181479. #ifndef PNG_NO_READ_OPT_PLTE
  181480. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  181481. #endif /* optional PLTE chunk in RGB and RGBA images */
  181482. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  181483. defined(PNG_READ_zTXt_SUPPORTED)
  181484. # define PNG_READ_TEXT_SUPPORTED
  181485. # define PNG_TEXT_SUPPORTED
  181486. #endif
  181487. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  181488. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181489. #ifdef PNG_NO_WRITE_TEXT
  181490. # define PNG_NO_WRITE_iTXt
  181491. # define PNG_NO_WRITE_tEXt
  181492. # define PNG_NO_WRITE_zTXt
  181493. #endif
  181494. #ifndef PNG_NO_WRITE_bKGD
  181495. # define PNG_WRITE_bKGD_SUPPORTED
  181496. # ifndef PNG_bKGD_SUPPORTED
  181497. # define PNG_bKGD_SUPPORTED
  181498. # endif
  181499. #endif
  181500. #ifndef PNG_NO_WRITE_cHRM
  181501. # define PNG_WRITE_cHRM_SUPPORTED
  181502. # ifndef PNG_cHRM_SUPPORTED
  181503. # define PNG_cHRM_SUPPORTED
  181504. # endif
  181505. #endif
  181506. #ifndef PNG_NO_WRITE_gAMA
  181507. # define PNG_WRITE_gAMA_SUPPORTED
  181508. # ifndef PNG_gAMA_SUPPORTED
  181509. # define PNG_gAMA_SUPPORTED
  181510. # endif
  181511. #endif
  181512. #ifndef PNG_NO_WRITE_hIST
  181513. # define PNG_WRITE_hIST_SUPPORTED
  181514. # ifndef PNG_hIST_SUPPORTED
  181515. # define PNG_hIST_SUPPORTED
  181516. # endif
  181517. #endif
  181518. #ifndef PNG_NO_WRITE_iCCP
  181519. # define PNG_WRITE_iCCP_SUPPORTED
  181520. # ifndef PNG_iCCP_SUPPORTED
  181521. # define PNG_iCCP_SUPPORTED
  181522. # endif
  181523. #endif
  181524. #ifndef PNG_NO_WRITE_iTXt
  181525. # ifndef PNG_WRITE_iTXt_SUPPORTED
  181526. # define PNG_WRITE_iTXt_SUPPORTED
  181527. # endif
  181528. # ifndef PNG_iTXt_SUPPORTED
  181529. # define PNG_iTXt_SUPPORTED
  181530. # endif
  181531. #endif
  181532. #ifndef PNG_NO_WRITE_oFFs
  181533. # define PNG_WRITE_oFFs_SUPPORTED
  181534. # ifndef PNG_oFFs_SUPPORTED
  181535. # define PNG_oFFs_SUPPORTED
  181536. # endif
  181537. #endif
  181538. #ifndef PNG_NO_WRITE_pCAL
  181539. # define PNG_WRITE_pCAL_SUPPORTED
  181540. # ifndef PNG_pCAL_SUPPORTED
  181541. # define PNG_pCAL_SUPPORTED
  181542. # endif
  181543. #endif
  181544. #ifndef PNG_NO_WRITE_sCAL
  181545. # define PNG_WRITE_sCAL_SUPPORTED
  181546. # ifndef PNG_sCAL_SUPPORTED
  181547. # define PNG_sCAL_SUPPORTED
  181548. # endif
  181549. #endif
  181550. #ifndef PNG_NO_WRITE_pHYs
  181551. # define PNG_WRITE_pHYs_SUPPORTED
  181552. # ifndef PNG_pHYs_SUPPORTED
  181553. # define PNG_pHYs_SUPPORTED
  181554. # endif
  181555. #endif
  181556. #ifndef PNG_NO_WRITE_sBIT
  181557. # define PNG_WRITE_sBIT_SUPPORTED
  181558. # ifndef PNG_sBIT_SUPPORTED
  181559. # define PNG_sBIT_SUPPORTED
  181560. # endif
  181561. #endif
  181562. #ifndef PNG_NO_WRITE_sPLT
  181563. # define PNG_WRITE_sPLT_SUPPORTED
  181564. # ifndef PNG_sPLT_SUPPORTED
  181565. # define PNG_sPLT_SUPPORTED
  181566. # endif
  181567. #endif
  181568. #ifndef PNG_NO_WRITE_sRGB
  181569. # define PNG_WRITE_sRGB_SUPPORTED
  181570. # ifndef PNG_sRGB_SUPPORTED
  181571. # define PNG_sRGB_SUPPORTED
  181572. # endif
  181573. #endif
  181574. #ifndef PNG_NO_WRITE_tEXt
  181575. # define PNG_WRITE_tEXt_SUPPORTED
  181576. # ifndef PNG_tEXt_SUPPORTED
  181577. # define PNG_tEXt_SUPPORTED
  181578. # endif
  181579. #endif
  181580. #ifndef PNG_NO_WRITE_tIME
  181581. # define PNG_WRITE_tIME_SUPPORTED
  181582. # ifndef PNG_tIME_SUPPORTED
  181583. # define PNG_tIME_SUPPORTED
  181584. # endif
  181585. #endif
  181586. #ifndef PNG_NO_WRITE_tRNS
  181587. # define PNG_WRITE_tRNS_SUPPORTED
  181588. # ifndef PNG_tRNS_SUPPORTED
  181589. # define PNG_tRNS_SUPPORTED
  181590. # endif
  181591. #endif
  181592. #ifndef PNG_NO_WRITE_zTXt
  181593. # define PNG_WRITE_zTXt_SUPPORTED
  181594. # ifndef PNG_zTXt_SUPPORTED
  181595. # define PNG_zTXt_SUPPORTED
  181596. # endif
  181597. #endif
  181598. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  181599. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  181600. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181601. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181602. # endif
  181603. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181604. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181605. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181606. # endif
  181607. # endif
  181608. #endif
  181609. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  181610. defined(PNG_WRITE_zTXt_SUPPORTED)
  181611. # define PNG_WRITE_TEXT_SUPPORTED
  181612. # ifndef PNG_TEXT_SUPPORTED
  181613. # define PNG_TEXT_SUPPORTED
  181614. # endif
  181615. #endif
  181616. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  181617. /* Turn this off to disable png_read_png() and
  181618. * png_write_png() and leave the row_pointers member
  181619. * out of the info structure.
  181620. */
  181621. #ifndef PNG_NO_INFO_IMAGE
  181622. # define PNG_INFO_IMAGE_SUPPORTED
  181623. #endif
  181624. /* need the time information for reading tIME chunks */
  181625. #if defined(PNG_tIME_SUPPORTED)
  181626. # if !defined(_WIN32_WCE)
  181627. /* "time.h" functions are not supported on WindowsCE */
  181628. # include <time.h>
  181629. # endif
  181630. #endif
  181631. /* Some typedefs to get us started. These should be safe on most of the
  181632. * common platforms. The typedefs should be at least as large as the
  181633. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  181634. * don't have to be exactly that size. Some compilers dislike passing
  181635. * unsigned shorts as function parameters, so you may be better off using
  181636. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  181637. * want to have unsigned int for png_uint_32 instead of unsigned long.
  181638. */
  181639. typedef unsigned long png_uint_32;
  181640. typedef long png_int_32;
  181641. typedef unsigned short png_uint_16;
  181642. typedef short png_int_16;
  181643. typedef unsigned char png_byte;
  181644. /* This is usually size_t. It is typedef'ed just in case you need it to
  181645. change (I'm not sure if you will or not, so I thought I'd be safe) */
  181646. #ifdef PNG_SIZE_T
  181647. typedef PNG_SIZE_T png_size_t;
  181648. # define png_sizeof(x) png_convert_size(sizeof (x))
  181649. #else
  181650. typedef size_t png_size_t;
  181651. # define png_sizeof(x) sizeof (x)
  181652. #endif
  181653. /* The following is needed for medium model support. It cannot be in the
  181654. * PNG_INTERNAL section. Needs modification for other compilers besides
  181655. * MSC. Model independent support declares all arrays and pointers to be
  181656. * large using the far keyword. The zlib version used must also support
  181657. * model independent data. As of version zlib 1.0.4, the necessary changes
  181658. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  181659. * changes that are needed. (Tim Wegner)
  181660. */
  181661. /* Separate compiler dependencies (problem here is that zlib.h always
  181662. defines FAR. (SJT) */
  181663. #ifdef __BORLANDC__
  181664. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  181665. # define LDATA 1
  181666. # else
  181667. # define LDATA 0
  181668. # endif
  181669. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  181670. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  181671. # define PNG_MAX_MALLOC_64K
  181672. # if (LDATA != 1)
  181673. # ifndef FAR
  181674. # define FAR __far
  181675. # endif
  181676. # define USE_FAR_KEYWORD
  181677. # endif /* LDATA != 1 */
  181678. /* Possibly useful for moving data out of default segment.
  181679. * Uncomment it if you want. Could also define FARDATA as
  181680. * const if your compiler supports it. (SJT)
  181681. # define FARDATA FAR
  181682. */
  181683. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  181684. #endif /* __BORLANDC__ */
  181685. /* Suggest testing for specific compiler first before testing for
  181686. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  181687. * making reliance oncertain keywords suspect. (SJT)
  181688. */
  181689. /* MSC Medium model */
  181690. #if defined(FAR)
  181691. # if defined(M_I86MM)
  181692. # define USE_FAR_KEYWORD
  181693. # define FARDATA FAR
  181694. # include <dos.h>
  181695. # endif
  181696. #endif
  181697. /* SJT: default case */
  181698. #ifndef FAR
  181699. # define FAR
  181700. #endif
  181701. /* At this point FAR is always defined */
  181702. #ifndef FARDATA
  181703. # define FARDATA
  181704. #endif
  181705. /* Typedef for floating-point numbers that are converted
  181706. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  181707. typedef png_int_32 png_fixed_point;
  181708. /* Add typedefs for pointers */
  181709. typedef void FAR * png_voidp;
  181710. typedef png_byte FAR * png_bytep;
  181711. typedef png_uint_32 FAR * png_uint_32p;
  181712. typedef png_int_32 FAR * png_int_32p;
  181713. typedef png_uint_16 FAR * png_uint_16p;
  181714. typedef png_int_16 FAR * png_int_16p;
  181715. typedef PNG_CONST char FAR * png_const_charp;
  181716. typedef char FAR * png_charp;
  181717. typedef png_fixed_point FAR * png_fixed_point_p;
  181718. #ifndef PNG_NO_STDIO
  181719. #if defined(_WIN32_WCE)
  181720. typedef HANDLE png_FILE_p;
  181721. #else
  181722. typedef FILE * png_FILE_p;
  181723. #endif
  181724. #endif
  181725. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181726. typedef double FAR * png_doublep;
  181727. #endif
  181728. /* Pointers to pointers; i.e. arrays */
  181729. typedef png_byte FAR * FAR * png_bytepp;
  181730. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  181731. typedef png_int_32 FAR * FAR * png_int_32pp;
  181732. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  181733. typedef png_int_16 FAR * FAR * png_int_16pp;
  181734. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  181735. typedef char FAR * FAR * png_charpp;
  181736. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  181737. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181738. typedef double FAR * FAR * png_doublepp;
  181739. #endif
  181740. /* Pointers to pointers to pointers; i.e., pointer to array */
  181741. typedef char FAR * FAR * FAR * png_charppp;
  181742. #if 0
  181743. /* SPC - Is this stuff deprecated? */
  181744. /* It'll be removed as of libpng-1.3.0 - GR-P */
  181745. /* libpng typedefs for types in zlib. If zlib changes
  181746. * or another compression library is used, then change these.
  181747. * Eliminates need to change all the source files.
  181748. */
  181749. typedef charf * png_zcharp;
  181750. typedef charf * FAR * png_zcharpp;
  181751. typedef z_stream FAR * png_zstreamp;
  181752. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  181753. /*
  181754. * Define PNG_BUILD_DLL if the module being built is a Windows
  181755. * LIBPNG DLL.
  181756. *
  181757. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  181758. * It is equivalent to Microsoft predefined macro _DLL that is
  181759. * automatically defined when you compile using the share
  181760. * version of the CRT (C Run-Time library)
  181761. *
  181762. * The cygwin mods make this behavior a little different:
  181763. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  181764. * Define PNG_STATIC if you are building a static library for use with cygwin,
  181765. * -or- if you are building an application that you want to link to the
  181766. * static library.
  181767. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  181768. * the other flags is defined.
  181769. */
  181770. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  181771. # define PNG_DLL
  181772. #endif
  181773. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  181774. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  181775. * command-line override
  181776. */
  181777. #if defined(__CYGWIN__)
  181778. # if !defined(PNG_STATIC)
  181779. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181780. # undef PNG_USE_GLOBAL_ARRAYS
  181781. # endif
  181782. # if !defined(PNG_USE_LOCAL_ARRAYS)
  181783. # define PNG_USE_LOCAL_ARRAYS
  181784. # endif
  181785. # else
  181786. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  181787. # if defined(PNG_USE_GLOBAL_ARRAYS)
  181788. # undef PNG_USE_GLOBAL_ARRAYS
  181789. # endif
  181790. # endif
  181791. # endif
  181792. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181793. # define PNG_USE_LOCAL_ARRAYS
  181794. # endif
  181795. #endif
  181796. /* Do not use global arrays (helps with building DLL's)
  181797. * They are no longer used in libpng itself, since version 1.0.5c,
  181798. * but might be required for some pre-1.0.5c applications.
  181799. */
  181800. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  181801. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  181802. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  181803. # define PNG_USE_LOCAL_ARRAYS
  181804. # else
  181805. # define PNG_USE_GLOBAL_ARRAYS
  181806. # endif
  181807. #endif
  181808. #if defined(__CYGWIN__)
  181809. # undef PNGAPI
  181810. # define PNGAPI __cdecl
  181811. # undef PNG_IMPEXP
  181812. # define PNG_IMPEXP
  181813. #endif
  181814. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  181815. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  181816. * Don't ignore those warnings; you must also reset the default calling
  181817. * convention in your compiler to match your PNGAPI, and you must build
  181818. * zlib and your applications the same way you build libpng.
  181819. */
  181820. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  181821. # ifndef PNG_NO_MODULEDEF
  181822. # define PNG_NO_MODULEDEF
  181823. # endif
  181824. #endif
  181825. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  181826. # define PNG_IMPEXP
  181827. #endif
  181828. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  181829. (( defined(_Windows) || defined(_WINDOWS) || \
  181830. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  181831. # ifndef PNGAPI
  181832. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  181833. # define PNGAPI __cdecl
  181834. # else
  181835. # define PNGAPI _cdecl
  181836. # endif
  181837. # endif
  181838. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  181839. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  181840. # define PNG_IMPEXP
  181841. # endif
  181842. # if !defined(PNG_IMPEXP)
  181843. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  181844. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  181845. /* Borland/Microsoft */
  181846. # if defined(_MSC_VER) || defined(__BORLANDC__)
  181847. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  181848. # define PNG_EXPORT PNG_EXPORT_TYPE1
  181849. # else
  181850. # define PNG_EXPORT PNG_EXPORT_TYPE2
  181851. # if defined(PNG_BUILD_DLL)
  181852. # define PNG_IMPEXP __export
  181853. # else
  181854. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  181855. VC++ */
  181856. # endif /* Exists in Borland C++ for
  181857. C++ classes (== huge) */
  181858. # endif
  181859. # endif
  181860. # if !defined(PNG_IMPEXP)
  181861. # if defined(PNG_BUILD_DLL)
  181862. # define PNG_IMPEXP __declspec(dllexport)
  181863. # else
  181864. # define PNG_IMPEXP __declspec(dllimport)
  181865. # endif
  181866. # endif
  181867. # endif /* PNG_IMPEXP */
  181868. #else /* !(DLL || non-cygwin WINDOWS) */
  181869. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  181870. # ifndef PNGAPI
  181871. # define PNGAPI _System
  181872. # endif
  181873. # else
  181874. # if 0 /* ... other platforms, with other meanings */
  181875. # endif
  181876. # endif
  181877. #endif
  181878. #ifndef PNGAPI
  181879. # define PNGAPI
  181880. #endif
  181881. #ifndef PNG_IMPEXP
  181882. # define PNG_IMPEXP
  181883. #endif
  181884. #ifdef PNG_BUILDSYMS
  181885. # ifndef PNG_EXPORT
  181886. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  181887. # endif
  181888. # ifdef PNG_USE_GLOBAL_ARRAYS
  181889. # ifndef PNG_EXPORT_VAR
  181890. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  181891. # endif
  181892. # endif
  181893. #endif
  181894. #ifndef PNG_EXPORT
  181895. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  181896. #endif
  181897. #ifdef PNG_USE_GLOBAL_ARRAYS
  181898. # ifndef PNG_EXPORT_VAR
  181899. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  181900. # endif
  181901. #endif
  181902. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  181903. * functions that are passed far data must be model independent.
  181904. */
  181905. #ifndef PNG_ABORT
  181906. # define PNG_ABORT() abort()
  181907. #endif
  181908. #ifdef PNG_SETJMP_SUPPORTED
  181909. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  181910. #else
  181911. # define png_jmpbuf(png_ptr) \
  181912. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  181913. #endif
  181914. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  181915. /* use this to make far-to-near assignments */
  181916. # define CHECK 1
  181917. # define NOCHECK 0
  181918. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  181919. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  181920. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  181921. # define png_strcpy _fstrcpy
  181922. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  181923. # define png_strlen _fstrlen
  181924. # define png_memcmp _fmemcmp /* SJT: added */
  181925. # define png_memcpy _fmemcpy
  181926. # define png_memset _fmemset
  181927. #else /* use the usual functions */
  181928. # define CVT_PTR(ptr) (ptr)
  181929. # define CVT_PTR_NOCHECK(ptr) (ptr)
  181930. # ifndef PNG_NO_SNPRINTF
  181931. # ifdef _MSC_VER
  181932. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  181933. # define png_snprintf2 _snprintf
  181934. # define png_snprintf6 _snprintf
  181935. # else
  181936. # define png_snprintf snprintf /* Added to v 1.2.19 */
  181937. # define png_snprintf2 snprintf
  181938. # define png_snprintf6 snprintf
  181939. # endif
  181940. # else
  181941. /* You don't have or don't want to use snprintf(). Caution: Using
  181942. * sprintf instead of snprintf exposes your application to accidental
  181943. * or malevolent buffer overflows. If you don't have snprintf()
  181944. * as a general rule you should provide one (you can get one from
  181945. * Portable OpenSSH). */
  181946. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  181947. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  181948. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  181949. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  181950. # endif
  181951. # define png_strcpy strcpy
  181952. # define png_strncpy strncpy /* Added to v 1.2.6 */
  181953. # define png_strlen strlen
  181954. # define png_memcmp memcmp /* SJT: added */
  181955. # define png_memcpy memcpy
  181956. # define png_memset memset
  181957. #endif
  181958. /* End of memory model independent support */
  181959. /* Just a little check that someone hasn't tried to define something
  181960. * contradictory.
  181961. */
  181962. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  181963. # undef PNG_ZBUF_SIZE
  181964. # define PNG_ZBUF_SIZE 65536L
  181965. #endif
  181966. /* Added at libpng-1.2.8 */
  181967. #endif /* PNG_VERSION_INFO_ONLY */
  181968. #endif /* PNGCONF_H */
  181969. /*** End of inlined file: pngconf.h ***/
  181970. #ifdef _MSC_VER
  181971. #pragma warning (disable: 4996 4100)
  181972. #endif
  181973. /*
  181974. * Added at libpng-1.2.8 */
  181975. /* Ref MSDN: Private as priority over Special
  181976. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  181977. * procedures. If this value is given, the StringFileInfo block must
  181978. * contain a PrivateBuild string.
  181979. *
  181980. * VS_FF_SPECIALBUILD File *was* built by the original company using
  181981. * standard release procedures but is a variation of the standard
  181982. * file of the same version number. If this value is given, the
  181983. * StringFileInfo block must contain a SpecialBuild string.
  181984. */
  181985. #if defined(PNG_USER_PRIVATEBUILD)
  181986. # define PNG_LIBPNG_BUILD_TYPE \
  181987. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  181988. #else
  181989. # if defined(PNG_LIBPNG_SPECIALBUILD)
  181990. # define PNG_LIBPNG_BUILD_TYPE \
  181991. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  181992. # else
  181993. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  181994. # endif
  181995. #endif
  181996. #ifndef PNG_VERSION_INFO_ONLY
  181997. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  181998. #ifdef __cplusplus
  181999. //extern "C" {
  182000. #endif /* __cplusplus */
  182001. /* This file is arranged in several sections. The first section contains
  182002. * structure and type definitions. The second section contains the external
  182003. * library functions, while the third has the internal library functions,
  182004. * which applications aren't expected to use directly.
  182005. */
  182006. #ifndef PNG_NO_TYPECAST_NULL
  182007. #define int_p_NULL (int *)NULL
  182008. #define png_bytep_NULL (png_bytep)NULL
  182009. #define png_bytepp_NULL (png_bytepp)NULL
  182010. #define png_doublep_NULL (png_doublep)NULL
  182011. #define png_error_ptr_NULL (png_error_ptr)NULL
  182012. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  182013. #define png_free_ptr_NULL (png_free_ptr)NULL
  182014. #define png_infopp_NULL (png_infopp)NULL
  182015. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  182016. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  182017. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  182018. #define png_structp_NULL (png_structp)NULL
  182019. #define png_uint_16p_NULL (png_uint_16p)NULL
  182020. #define png_voidp_NULL (png_voidp)NULL
  182021. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  182022. #else
  182023. #define int_p_NULL NULL
  182024. #define png_bytep_NULL NULL
  182025. #define png_bytepp_NULL NULL
  182026. #define png_doublep_NULL NULL
  182027. #define png_error_ptr_NULL NULL
  182028. #define png_flush_ptr_NULL NULL
  182029. #define png_free_ptr_NULL NULL
  182030. #define png_infopp_NULL NULL
  182031. #define png_malloc_ptr_NULL NULL
  182032. #define png_read_status_ptr_NULL NULL
  182033. #define png_rw_ptr_NULL NULL
  182034. #define png_structp_NULL NULL
  182035. #define png_uint_16p_NULL NULL
  182036. #define png_voidp_NULL NULL
  182037. #define png_write_status_ptr_NULL NULL
  182038. #endif
  182039. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  182040. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  182041. /* Version information for C files, stored in png.c. This had better match
  182042. * the version above.
  182043. */
  182044. #ifdef PNG_USE_GLOBAL_ARRAYS
  182045. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  182046. /* need room for 99.99.99beta99z */
  182047. #else
  182048. #define png_libpng_ver png_get_header_ver(NULL)
  182049. #endif
  182050. #ifdef PNG_USE_GLOBAL_ARRAYS
  182051. /* This was removed in version 1.0.5c */
  182052. /* Structures to facilitate easy interlacing. See png.c for more details */
  182053. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  182054. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  182055. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  182056. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  182057. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  182058. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  182059. /* This isn't currently used. If you need it, see png.c for more details.
  182060. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  182061. */
  182062. #endif
  182063. #endif /* PNG_NO_EXTERN */
  182064. /* Three color definitions. The order of the red, green, and blue, (and the
  182065. * exact size) is not important, although the size of the fields need to
  182066. * be png_byte or png_uint_16 (as defined below).
  182067. */
  182068. typedef struct png_color_struct
  182069. {
  182070. png_byte red;
  182071. png_byte green;
  182072. png_byte blue;
  182073. } png_color;
  182074. typedef png_color FAR * png_colorp;
  182075. typedef png_color FAR * FAR * png_colorpp;
  182076. typedef struct png_color_16_struct
  182077. {
  182078. png_byte index; /* used for palette files */
  182079. png_uint_16 red; /* for use in red green blue files */
  182080. png_uint_16 green;
  182081. png_uint_16 blue;
  182082. png_uint_16 gray; /* for use in grayscale files */
  182083. } png_color_16;
  182084. typedef png_color_16 FAR * png_color_16p;
  182085. typedef png_color_16 FAR * FAR * png_color_16pp;
  182086. typedef struct png_color_8_struct
  182087. {
  182088. png_byte red; /* for use in red green blue files */
  182089. png_byte green;
  182090. png_byte blue;
  182091. png_byte gray; /* for use in grayscale files */
  182092. png_byte alpha; /* for alpha channel files */
  182093. } png_color_8;
  182094. typedef png_color_8 FAR * png_color_8p;
  182095. typedef png_color_8 FAR * FAR * png_color_8pp;
  182096. /*
  182097. * The following two structures are used for the in-core representation
  182098. * of sPLT chunks.
  182099. */
  182100. typedef struct png_sPLT_entry_struct
  182101. {
  182102. png_uint_16 red;
  182103. png_uint_16 green;
  182104. png_uint_16 blue;
  182105. png_uint_16 alpha;
  182106. png_uint_16 frequency;
  182107. } png_sPLT_entry;
  182108. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  182109. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  182110. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  182111. * occupy the LSB of their respective members, and the MSB of each member
  182112. * is zero-filled. The frequency member always occupies the full 16 bits.
  182113. */
  182114. typedef struct png_sPLT_struct
  182115. {
  182116. png_charp name; /* palette name */
  182117. png_byte depth; /* depth of palette samples */
  182118. png_sPLT_entryp entries; /* palette entries */
  182119. png_int_32 nentries; /* number of palette entries */
  182120. } png_sPLT_t;
  182121. typedef png_sPLT_t FAR * png_sPLT_tp;
  182122. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  182123. #ifdef PNG_TEXT_SUPPORTED
  182124. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  182125. * and whether that contents is compressed or not. The "key" field
  182126. * points to a regular zero-terminated C string. The "text", "lang", and
  182127. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  182128. * However, the * structure returned by png_get_text() will always contain
  182129. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  182130. * so they can be safely used in printf() and other string-handling functions.
  182131. */
  182132. typedef struct png_text_struct
  182133. {
  182134. int compression; /* compression value:
  182135. -1: tEXt, none
  182136. 0: zTXt, deflate
  182137. 1: iTXt, none
  182138. 2: iTXt, deflate */
  182139. png_charp key; /* keyword, 1-79 character description of "text" */
  182140. png_charp text; /* comment, may be an empty string (ie "")
  182141. or a NULL pointer */
  182142. png_size_t text_length; /* length of the text string */
  182143. #ifdef PNG_iTXt_SUPPORTED
  182144. png_size_t itxt_length; /* length of the itxt string */
  182145. png_charp lang; /* language code, 0-79 characters
  182146. or a NULL pointer */
  182147. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  182148. chars or a NULL pointer */
  182149. #endif
  182150. } png_text;
  182151. typedef png_text FAR * png_textp;
  182152. typedef png_text FAR * FAR * png_textpp;
  182153. #endif
  182154. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  182155. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  182156. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  182157. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  182158. #define PNG_TEXT_COMPRESSION_NONE -1
  182159. #define PNG_TEXT_COMPRESSION_zTXt 0
  182160. #define PNG_ITXT_COMPRESSION_NONE 1
  182161. #define PNG_ITXT_COMPRESSION_zTXt 2
  182162. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  182163. /* png_time is a way to hold the time in an machine independent way.
  182164. * Two conversions are provided, both from time_t and struct tm. There
  182165. * is no portable way to convert to either of these structures, as far
  182166. * as I know. If you know of a portable way, send it to me. As a side
  182167. * note - PNG has always been Year 2000 compliant!
  182168. */
  182169. typedef struct png_time_struct
  182170. {
  182171. png_uint_16 year; /* full year, as in, 1995 */
  182172. png_byte month; /* month of year, 1 - 12 */
  182173. png_byte day; /* day of month, 1 - 31 */
  182174. png_byte hour; /* hour of day, 0 - 23 */
  182175. png_byte minute; /* minute of hour, 0 - 59 */
  182176. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  182177. } png_time;
  182178. typedef png_time FAR * png_timep;
  182179. typedef png_time FAR * FAR * png_timepp;
  182180. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182181. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  182182. * no specific support. The idea is that we can use this to queue
  182183. * up private chunks for output even though the library doesn't actually
  182184. * know about their semantics.
  182185. */
  182186. typedef struct png_unknown_chunk_t
  182187. {
  182188. png_byte name[5];
  182189. png_byte *data;
  182190. png_size_t size;
  182191. /* libpng-using applications should NOT directly modify this byte. */
  182192. png_byte location; /* mode of operation at read time */
  182193. }
  182194. png_unknown_chunk;
  182195. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  182196. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  182197. #endif
  182198. /* png_info is a structure that holds the information in a PNG file so
  182199. * that the application can find out the characteristics of the image.
  182200. * If you are reading the file, this structure will tell you what is
  182201. * in the PNG file. If you are writing the file, fill in the information
  182202. * you want to put into the PNG file, then call png_write_info().
  182203. * The names chosen should be very close to the PNG specification, so
  182204. * consult that document for information about the meaning of each field.
  182205. *
  182206. * With libpng < 0.95, it was only possible to directly set and read the
  182207. * the values in the png_info_struct, which meant that the contents and
  182208. * order of the values had to remain fixed. With libpng 0.95 and later,
  182209. * however, there are now functions that abstract the contents of
  182210. * png_info_struct from the application, so this makes it easier to use
  182211. * libpng with dynamic libraries, and even makes it possible to use
  182212. * libraries that don't have all of the libpng ancillary chunk-handing
  182213. * functionality.
  182214. *
  182215. * In any case, the order of the parameters in png_info_struct should NOT
  182216. * be changed for as long as possible to keep compatibility with applications
  182217. * that use the old direct-access method with png_info_struct.
  182218. *
  182219. * The following members may have allocated storage attached that should be
  182220. * cleaned up before the structure is discarded: palette, trans, text,
  182221. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  182222. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  182223. * are automatically freed when the info structure is deallocated, if they were
  182224. * allocated internally by libpng. This behavior can be changed by means
  182225. * of the png_data_freer() function.
  182226. *
  182227. * More allocation details: all the chunk-reading functions that
  182228. * change these members go through the corresponding png_set_*
  182229. * functions. A function to clear these members is available: see
  182230. * png_free_data(). The png_set_* functions do not depend on being
  182231. * able to point info structure members to any of the storage they are
  182232. * passed (they make their own copies), EXCEPT that the png_set_text
  182233. * functions use the same storage passed to them in the text_ptr or
  182234. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  182235. * functions do not make their own copies.
  182236. */
  182237. typedef struct png_info_struct
  182238. {
  182239. /* the following are necessary for every PNG file */
  182240. png_uint_32 width; /* width of image in pixels (from IHDR) */
  182241. png_uint_32 height; /* height of image in pixels (from IHDR) */
  182242. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  182243. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  182244. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  182245. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  182246. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  182247. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  182248. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  182249. /* The following three should have been named *_method not *_type */
  182250. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  182251. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  182252. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182253. /* The following is informational only on read, and not used on writes. */
  182254. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  182255. png_byte pixel_depth; /* number of bits per pixel */
  182256. png_byte spare_byte; /* to align the data, and for future use */
  182257. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  182258. /* The rest of the data is optional. If you are reading, check the
  182259. * valid field to see if the information in these are valid. If you
  182260. * are writing, set the valid field to those chunks you want written,
  182261. * and initialize the appropriate fields below.
  182262. */
  182263. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  182264. /* The gAMA chunk describes the gamma characteristics of the system
  182265. * on which the image was created, normally in the range [1.0, 2.5].
  182266. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  182267. */
  182268. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  182269. #endif
  182270. #if defined(PNG_sRGB_SUPPORTED)
  182271. /* GR-P, 0.96a */
  182272. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  182273. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  182274. #endif
  182275. #if defined(PNG_TEXT_SUPPORTED)
  182276. /* The tEXt, and zTXt chunks contain human-readable textual data in
  182277. * uncompressed, compressed, and optionally compressed forms, respectively.
  182278. * The data in "text" is an array of pointers to uncompressed,
  182279. * null-terminated C strings. Each chunk has a keyword that describes the
  182280. * textual data contained in that chunk. Keywords are not required to be
  182281. * unique, and the text string may be empty. Any number of text chunks may
  182282. * be in an image.
  182283. */
  182284. int num_text; /* number of comments read/to write */
  182285. int max_text; /* current size of text array */
  182286. png_textp text; /* array of comments read/to write */
  182287. #endif /* PNG_TEXT_SUPPORTED */
  182288. #if defined(PNG_tIME_SUPPORTED)
  182289. /* The tIME chunk holds the last time the displayed image data was
  182290. * modified. See the png_time struct for the contents of this struct.
  182291. */
  182292. png_time mod_time;
  182293. #endif
  182294. #if defined(PNG_sBIT_SUPPORTED)
  182295. /* The sBIT chunk specifies the number of significant high-order bits
  182296. * in the pixel data. Values are in the range [1, bit_depth], and are
  182297. * only specified for the channels in the pixel data. The contents of
  182298. * the low-order bits is not specified. Data is valid if
  182299. * (valid & PNG_INFO_sBIT) is non-zero.
  182300. */
  182301. png_color_8 sig_bit; /* significant bits in color channels */
  182302. #endif
  182303. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  182304. defined(PNG_READ_BACKGROUND_SUPPORTED)
  182305. /* The tRNS chunk supplies transparency data for paletted images and
  182306. * other image types that don't need a full alpha channel. There are
  182307. * "num_trans" transparency values for a paletted image, stored in the
  182308. * same order as the palette colors, starting from index 0. Values
  182309. * for the data are in the range [0, 255], ranging from fully transparent
  182310. * to fully opaque, respectively. For non-paletted images, there is a
  182311. * single color specified that should be treated as fully transparent.
  182312. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  182313. */
  182314. png_bytep trans; /* transparent values for paletted image */
  182315. png_color_16 trans_values; /* transparent color for non-palette image */
  182316. #endif
  182317. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182318. /* The bKGD chunk gives the suggested image background color if the
  182319. * display program does not have its own background color and the image
  182320. * is needs to composited onto a background before display. The colors
  182321. * in "background" are normally in the same color space/depth as the
  182322. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  182323. */
  182324. png_color_16 background;
  182325. #endif
  182326. #if defined(PNG_oFFs_SUPPORTED)
  182327. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  182328. * and downwards from the top-left corner of the display, page, or other
  182329. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  182330. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  182331. */
  182332. png_int_32 x_offset; /* x offset on page */
  182333. png_int_32 y_offset; /* y offset on page */
  182334. png_byte offset_unit_type; /* offset units type */
  182335. #endif
  182336. #if defined(PNG_pHYs_SUPPORTED)
  182337. /* The pHYs chunk gives the physical pixel density of the image for
  182338. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  182339. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  182340. */
  182341. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  182342. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  182343. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  182344. #endif
  182345. #if defined(PNG_hIST_SUPPORTED)
  182346. /* The hIST chunk contains the relative frequency or importance of the
  182347. * various palette entries, so that a viewer can intelligently select a
  182348. * reduced-color palette, if required. Data is an array of "num_palette"
  182349. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  182350. * is non-zero.
  182351. */
  182352. png_uint_16p hist;
  182353. #endif
  182354. #ifdef PNG_cHRM_SUPPORTED
  182355. /* The cHRM chunk describes the CIE color characteristics of the monitor
  182356. * on which the PNG was created. This data allows the viewer to do gamut
  182357. * mapping of the input image to ensure that the viewer sees the same
  182358. * colors in the image as the creator. Values are in the range
  182359. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  182360. */
  182361. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182362. float x_white;
  182363. float y_white;
  182364. float x_red;
  182365. float y_red;
  182366. float x_green;
  182367. float y_green;
  182368. float x_blue;
  182369. float y_blue;
  182370. #endif
  182371. #endif
  182372. #if defined(PNG_pCAL_SUPPORTED)
  182373. /* The pCAL chunk describes a transformation between the stored pixel
  182374. * values and original physical data values used to create the image.
  182375. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  182376. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  182377. * (possibly non-linear) transformation function given by "pcal_type"
  182378. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  182379. * defines below, and the PNG-Group's PNG extensions document for a
  182380. * complete description of the transformations and how they should be
  182381. * implemented, and for a description of the ASCII parameter strings.
  182382. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  182383. */
  182384. png_charp pcal_purpose; /* pCAL chunk description string */
  182385. png_int_32 pcal_X0; /* minimum value */
  182386. png_int_32 pcal_X1; /* maximum value */
  182387. png_charp pcal_units; /* Latin-1 string giving physical units */
  182388. png_charpp pcal_params; /* ASCII strings containing parameter values */
  182389. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  182390. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  182391. #endif
  182392. /* New members added in libpng-1.0.6 */
  182393. #ifdef PNG_FREE_ME_SUPPORTED
  182394. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182395. #endif
  182396. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182397. /* storage for unknown chunks that the library doesn't recognize. */
  182398. png_unknown_chunkp unknown_chunks;
  182399. png_size_t unknown_chunks_num;
  182400. #endif
  182401. #if defined(PNG_iCCP_SUPPORTED)
  182402. /* iCCP chunk data. */
  182403. png_charp iccp_name; /* profile name */
  182404. png_charp iccp_profile; /* International Color Consortium profile data */
  182405. /* Note to maintainer: should be png_bytep */
  182406. png_uint_32 iccp_proflen; /* ICC profile data length */
  182407. png_byte iccp_compression; /* Always zero */
  182408. #endif
  182409. #if defined(PNG_sPLT_SUPPORTED)
  182410. /* data on sPLT chunks (there may be more than one). */
  182411. png_sPLT_tp splt_palettes;
  182412. png_uint_32 splt_palettes_num;
  182413. #endif
  182414. #if defined(PNG_sCAL_SUPPORTED)
  182415. /* The sCAL chunk describes the actual physical dimensions of the
  182416. * subject matter of the graphic. The chunk contains a unit specification
  182417. * a byte value, and two ASCII strings representing floating-point
  182418. * values. The values are width and height corresponsing to one pixel
  182419. * in the image. This external representation is converted to double
  182420. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  182421. */
  182422. png_byte scal_unit; /* unit of physical scale */
  182423. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182424. double scal_pixel_width; /* width of one pixel */
  182425. double scal_pixel_height; /* height of one pixel */
  182426. #endif
  182427. #ifdef PNG_FIXED_POINT_SUPPORTED
  182428. png_charp scal_s_width; /* string containing height */
  182429. png_charp scal_s_height; /* string containing width */
  182430. #endif
  182431. #endif
  182432. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182433. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  182434. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  182435. png_bytepp row_pointers; /* the image bits */
  182436. #endif
  182437. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  182438. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  182439. #endif
  182440. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  182441. png_fixed_point int_x_white;
  182442. png_fixed_point int_y_white;
  182443. png_fixed_point int_x_red;
  182444. png_fixed_point int_y_red;
  182445. png_fixed_point int_x_green;
  182446. png_fixed_point int_y_green;
  182447. png_fixed_point int_x_blue;
  182448. png_fixed_point int_y_blue;
  182449. #endif
  182450. } png_info;
  182451. typedef png_info FAR * png_infop;
  182452. typedef png_info FAR * FAR * png_infopp;
  182453. /* Maximum positive integer used in PNG is (2^31)-1 */
  182454. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  182455. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  182456. #define PNG_SIZE_MAX ((png_size_t)(-1))
  182457. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182458. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  182459. #define PNG_MAX_UINT PNG_UINT_31_MAX
  182460. #endif
  182461. /* These describe the color_type field in png_info. */
  182462. /* color type masks */
  182463. #define PNG_COLOR_MASK_PALETTE 1
  182464. #define PNG_COLOR_MASK_COLOR 2
  182465. #define PNG_COLOR_MASK_ALPHA 4
  182466. /* color types. Note that not all combinations are legal */
  182467. #define PNG_COLOR_TYPE_GRAY 0
  182468. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  182469. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  182470. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  182471. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  182472. /* aliases */
  182473. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  182474. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  182475. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  182476. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  182477. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  182478. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  182479. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  182480. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  182481. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  182482. /* These are for the interlacing type. These values should NOT be changed. */
  182483. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  182484. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  182485. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  182486. /* These are for the oFFs chunk. These values should NOT be changed. */
  182487. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  182488. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  182489. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  182490. /* These are for the pCAL chunk. These values should NOT be changed. */
  182491. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  182492. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  182493. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  182494. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  182495. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  182496. /* These are for the sCAL chunk. These values should NOT be changed. */
  182497. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  182498. #define PNG_SCALE_METER 1 /* meters per pixel */
  182499. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  182500. #define PNG_SCALE_LAST 3 /* Not a valid value */
  182501. /* These are for the pHYs chunk. These values should NOT be changed. */
  182502. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  182503. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  182504. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  182505. /* These are for the sRGB chunk. These values should NOT be changed. */
  182506. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  182507. #define PNG_sRGB_INTENT_RELATIVE 1
  182508. #define PNG_sRGB_INTENT_SATURATION 2
  182509. #define PNG_sRGB_INTENT_ABSOLUTE 3
  182510. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  182511. /* This is for text chunks */
  182512. #define PNG_KEYWORD_MAX_LENGTH 79
  182513. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  182514. #define PNG_MAX_PALETTE_LENGTH 256
  182515. /* These determine if an ancillary chunk's data has been successfully read
  182516. * from the PNG header, or if the application has filled in the corresponding
  182517. * data in the info_struct to be written into the output file. The values
  182518. * of the PNG_INFO_<chunk> defines should NOT be changed.
  182519. */
  182520. #define PNG_INFO_gAMA 0x0001
  182521. #define PNG_INFO_sBIT 0x0002
  182522. #define PNG_INFO_cHRM 0x0004
  182523. #define PNG_INFO_PLTE 0x0008
  182524. #define PNG_INFO_tRNS 0x0010
  182525. #define PNG_INFO_bKGD 0x0020
  182526. #define PNG_INFO_hIST 0x0040
  182527. #define PNG_INFO_pHYs 0x0080
  182528. #define PNG_INFO_oFFs 0x0100
  182529. #define PNG_INFO_tIME 0x0200
  182530. #define PNG_INFO_pCAL 0x0400
  182531. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  182532. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  182533. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  182534. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  182535. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  182536. /* This is used for the transformation routines, as some of them
  182537. * change these values for the row. It also should enable using
  182538. * the routines for other purposes.
  182539. */
  182540. typedef struct png_row_info_struct
  182541. {
  182542. png_uint_32 width; /* width of row */
  182543. png_uint_32 rowbytes; /* number of bytes in row */
  182544. png_byte color_type; /* color type of row */
  182545. png_byte bit_depth; /* bit depth of row */
  182546. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  182547. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  182548. } png_row_info;
  182549. typedef png_row_info FAR * png_row_infop;
  182550. typedef png_row_info FAR * FAR * png_row_infopp;
  182551. /* These are the function types for the I/O functions and for the functions
  182552. * that allow the user to override the default I/O functions with his or her
  182553. * own. The png_error_ptr type should match that of user-supplied warning
  182554. * and error functions, while the png_rw_ptr type should match that of the
  182555. * user read/write data functions.
  182556. */
  182557. typedef struct png_struct_def png_struct;
  182558. typedef png_struct FAR * png_structp;
  182559. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  182560. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  182561. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  182562. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  182563. int));
  182564. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  182565. int));
  182566. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182567. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  182568. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  182569. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  182570. png_uint_32, int));
  182571. #endif
  182572. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182573. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182574. defined(PNG_LEGACY_SUPPORTED)
  182575. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  182576. png_row_infop, png_bytep));
  182577. #endif
  182578. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182579. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  182580. #endif
  182581. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182582. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  182583. #endif
  182584. /* Transform masks for the high-level interface */
  182585. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  182586. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  182587. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  182588. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  182589. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  182590. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  182591. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  182592. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  182593. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  182594. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  182595. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  182596. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  182597. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  182598. /* Flags for MNG supported features */
  182599. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  182600. #define PNG_FLAG_MNG_FILTER_64 0x04
  182601. #define PNG_ALL_MNG_FEATURES 0x05
  182602. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  182603. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  182604. /* The structure that holds the information to read and write PNG files.
  182605. * The only people who need to care about what is inside of this are the
  182606. * people who will be modifying the library for their own special needs.
  182607. * It should NOT be accessed directly by an application, except to store
  182608. * the jmp_buf.
  182609. */
  182610. struct png_struct_def
  182611. {
  182612. #ifdef PNG_SETJMP_SUPPORTED
  182613. jmp_buf jmpbuf; /* used in png_error */
  182614. #endif
  182615. png_error_ptr error_fn; /* function for printing errors and aborting */
  182616. png_error_ptr warning_fn; /* function for printing warnings */
  182617. png_voidp error_ptr; /* user supplied struct for error functions */
  182618. png_rw_ptr write_data_fn; /* function for writing output data */
  182619. png_rw_ptr read_data_fn; /* function for reading input data */
  182620. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  182621. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  182622. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  182623. #endif
  182624. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182625. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  182626. #endif
  182627. /* These were added in libpng-1.0.2 */
  182628. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  182629. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182630. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182631. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  182632. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  182633. png_byte user_transform_channels; /* channels in user transformed pixels */
  182634. #endif
  182635. #endif
  182636. png_uint_32 mode; /* tells us where we are in the PNG file */
  182637. png_uint_32 flags; /* flags indicating various things to libpng */
  182638. png_uint_32 transformations; /* which transformations to perform */
  182639. z_stream zstream; /* pointer to decompression structure (below) */
  182640. png_bytep zbuf; /* buffer for zlib */
  182641. png_size_t zbuf_size; /* size of zbuf */
  182642. int zlib_level; /* holds zlib compression level */
  182643. int zlib_method; /* holds zlib compression method */
  182644. int zlib_window_bits; /* holds zlib compression window bits */
  182645. int zlib_mem_level; /* holds zlib compression memory level */
  182646. int zlib_strategy; /* holds zlib compression strategy */
  182647. png_uint_32 width; /* width of image in pixels */
  182648. png_uint_32 height; /* height of image in pixels */
  182649. png_uint_32 num_rows; /* number of rows in current pass */
  182650. png_uint_32 usr_width; /* width of row at start of write */
  182651. png_uint_32 rowbytes; /* size of row in bytes */
  182652. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  182653. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  182654. png_uint_32 row_number; /* current row in interlace pass */
  182655. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  182656. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  182657. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  182658. png_bytep up_row; /* buffer to save "up" row when filtering */
  182659. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  182660. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  182661. png_row_info row_info; /* used for transformation routines */
  182662. png_uint_32 idat_size; /* current IDAT size for read */
  182663. png_uint_32 crc; /* current chunk CRC value */
  182664. png_colorp palette; /* palette from the input file */
  182665. png_uint_16 num_palette; /* number of color entries in palette */
  182666. png_uint_16 num_trans; /* number of transparency values */
  182667. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  182668. png_byte compression; /* file compression type (always 0) */
  182669. png_byte filter; /* file filter type (always 0) */
  182670. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182671. png_byte pass; /* current interlace pass (0 - 6) */
  182672. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  182673. png_byte color_type; /* color type of file */
  182674. png_byte bit_depth; /* bit depth of file */
  182675. png_byte usr_bit_depth; /* bit depth of users row */
  182676. png_byte pixel_depth; /* number of bits per pixel */
  182677. png_byte channels; /* number of channels in file */
  182678. png_byte usr_channels; /* channels at start of write */
  182679. png_byte sig_bytes; /* magic bytes read/written from start of file */
  182680. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182681. #ifdef PNG_LEGACY_SUPPORTED
  182682. png_byte filler; /* filler byte for pixel expansion */
  182683. #else
  182684. png_uint_16 filler; /* filler bytes for pixel expansion */
  182685. #endif
  182686. #endif
  182687. #if defined(PNG_bKGD_SUPPORTED)
  182688. png_byte background_gamma_type;
  182689. # ifdef PNG_FLOATING_POINT_SUPPORTED
  182690. float background_gamma;
  182691. # endif
  182692. png_color_16 background; /* background color in screen gamma space */
  182693. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182694. png_color_16 background_1; /* background normalized to gamma 1.0 */
  182695. #endif
  182696. #endif /* PNG_bKGD_SUPPORTED */
  182697. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  182698. png_flush_ptr output_flush_fn;/* Function for flushing output */
  182699. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  182700. png_uint_32 flush_rows; /* number of rows written since last flush */
  182701. #endif
  182702. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182703. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  182704. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182705. float gamma; /* file gamma value */
  182706. float screen_gamma; /* screen gamma value (display_exponent) */
  182707. #endif
  182708. #endif
  182709. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182710. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  182711. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  182712. png_bytep gamma_to_1; /* converts from file to 1.0 */
  182713. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  182714. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  182715. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  182716. #endif
  182717. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  182718. png_color_8 sig_bit; /* significant bits in each available channel */
  182719. #endif
  182720. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182721. png_color_8 shift; /* shift for significant bit tranformation */
  182722. #endif
  182723. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  182724. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182725. png_bytep trans; /* transparency values for paletted files */
  182726. png_color_16 trans_values; /* transparency values for non-paletted files */
  182727. #endif
  182728. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  182729. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  182730. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182731. png_progressive_info_ptr info_fn; /* called after header data fully read */
  182732. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  182733. png_progressive_end_ptr end_fn; /* called after image is complete */
  182734. png_bytep save_buffer_ptr; /* current location in save_buffer */
  182735. png_bytep save_buffer; /* buffer for previously read data */
  182736. png_bytep current_buffer_ptr; /* current location in current_buffer */
  182737. png_bytep current_buffer; /* buffer for recently used data */
  182738. png_uint_32 push_length; /* size of current input chunk */
  182739. png_uint_32 skip_length; /* bytes to skip in input data */
  182740. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  182741. png_size_t save_buffer_max; /* total size of save_buffer */
  182742. png_size_t buffer_size; /* total amount of available input data */
  182743. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  182744. int process_mode; /* what push library is currently doing */
  182745. int cur_palette; /* current push library palette index */
  182746. # if defined(PNG_TEXT_SUPPORTED)
  182747. png_size_t current_text_size; /* current size of text input data */
  182748. png_size_t current_text_left; /* how much text left to read in input */
  182749. png_charp current_text; /* current text chunk buffer */
  182750. png_charp current_text_ptr; /* current location in current_text */
  182751. # endif /* PNG_TEXT_SUPPORTED */
  182752. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  182753. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  182754. /* for the Borland special 64K segment handler */
  182755. png_bytepp offset_table_ptr;
  182756. png_bytep offset_table;
  182757. png_uint_16 offset_table_number;
  182758. png_uint_16 offset_table_count;
  182759. png_uint_16 offset_table_count_free;
  182760. #endif
  182761. #if defined(PNG_READ_DITHER_SUPPORTED)
  182762. png_bytep palette_lookup; /* lookup table for dithering */
  182763. png_bytep dither_index; /* index translation for palette files */
  182764. #endif
  182765. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  182766. png_uint_16p hist; /* histogram */
  182767. #endif
  182768. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  182769. png_byte heuristic_method; /* heuristic for row filter selection */
  182770. png_byte num_prev_filters; /* number of weights for previous rows */
  182771. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  182772. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  182773. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  182774. png_uint_16p filter_costs; /* relative filter calculation cost */
  182775. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  182776. #endif
  182777. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182778. png_charp time_buffer; /* String to hold RFC 1123 time text */
  182779. #endif
  182780. /* New members added in libpng-1.0.6 */
  182781. #ifdef PNG_FREE_ME_SUPPORTED
  182782. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182783. #endif
  182784. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182785. png_voidp user_chunk_ptr;
  182786. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  182787. #endif
  182788. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182789. int num_chunk_list;
  182790. png_bytep chunk_list;
  182791. #endif
  182792. /* New members added in libpng-1.0.3 */
  182793. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182794. png_byte rgb_to_gray_status;
  182795. /* These were changed from png_byte in libpng-1.0.6 */
  182796. png_uint_16 rgb_to_gray_red_coeff;
  182797. png_uint_16 rgb_to_gray_green_coeff;
  182798. png_uint_16 rgb_to_gray_blue_coeff;
  182799. #endif
  182800. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  182801. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  182802. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  182803. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  182804. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  182805. #ifdef PNG_1_0_X
  182806. png_byte mng_features_permitted;
  182807. #else
  182808. png_uint_32 mng_features_permitted;
  182809. #endif /* PNG_1_0_X */
  182810. #endif
  182811. /* New member added in libpng-1.0.7 */
  182812. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182813. png_fixed_point int_gamma;
  182814. #endif
  182815. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  182816. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  182817. png_byte filter_type;
  182818. #endif
  182819. #if defined(PNG_1_0_X)
  182820. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  182821. png_uint_32 row_buf_size;
  182822. #endif
  182823. /* New members added in libpng-1.2.0 */
  182824. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  182825. # if !defined(PNG_1_0_X)
  182826. # if defined(PNG_MMX_CODE_SUPPORTED)
  182827. png_byte mmx_bitdepth_threshold;
  182828. png_uint_32 mmx_rowbytes_threshold;
  182829. # endif
  182830. png_uint_32 asm_flags;
  182831. # endif
  182832. #endif
  182833. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  182834. #ifdef PNG_USER_MEM_SUPPORTED
  182835. png_voidp mem_ptr; /* user supplied struct for mem functions */
  182836. png_malloc_ptr malloc_fn; /* function for allocating memory */
  182837. png_free_ptr free_fn; /* function for freeing memory */
  182838. #endif
  182839. /* New member added in libpng-1.0.13 and 1.2.0 */
  182840. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  182841. #if defined(PNG_READ_DITHER_SUPPORTED)
  182842. /* The following three members were added at version 1.0.14 and 1.2.4 */
  182843. png_bytep dither_sort; /* working sort array */
  182844. png_bytep index_to_palette; /* where the original index currently is */
  182845. /* in the palette */
  182846. png_bytep palette_to_index; /* which original index points to this */
  182847. /* palette color */
  182848. #endif
  182849. /* New members added in libpng-1.0.16 and 1.2.6 */
  182850. png_byte compression_type;
  182851. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  182852. png_uint_32 user_width_max;
  182853. png_uint_32 user_height_max;
  182854. #endif
  182855. /* New member added in libpng-1.0.25 and 1.2.17 */
  182856. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182857. /* storage for unknown chunk that the library doesn't recognize. */
  182858. png_unknown_chunk unknown_chunk;
  182859. #endif
  182860. };
  182861. /* This triggers a compiler error in png.c, if png.c and png.h
  182862. * do not agree upon the version number.
  182863. */
  182864. typedef png_structp version_1_2_21;
  182865. typedef png_struct FAR * FAR * png_structpp;
  182866. /* Here are the function definitions most commonly used. This is not
  182867. * the place to find out how to use libpng. See libpng.txt for the
  182868. * full explanation, see example.c for the summary. This just provides
  182869. * a simple one line description of the use of each function.
  182870. */
  182871. /* Returns the version number of the library */
  182872. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  182873. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  182874. * Handling more than 8 bytes from the beginning of the file is an error.
  182875. */
  182876. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  182877. int num_bytes));
  182878. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  182879. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  182880. * signature, and non-zero otherwise. Having num_to_check == 0 or
  182881. * start > 7 will always fail (ie return non-zero).
  182882. */
  182883. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  182884. png_size_t num_to_check));
  182885. /* Simple signature checking function. This is the same as calling
  182886. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  182887. */
  182888. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  182889. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  182890. extern PNG_EXPORT(png_structp,png_create_read_struct)
  182891. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182892. png_error_ptr error_fn, png_error_ptr warn_fn));
  182893. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  182894. extern PNG_EXPORT(png_structp,png_create_write_struct)
  182895. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182896. png_error_ptr error_fn, png_error_ptr warn_fn));
  182897. #ifdef PNG_WRITE_SUPPORTED
  182898. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  182899. PNGARG((png_structp png_ptr));
  182900. #endif
  182901. #ifdef PNG_WRITE_SUPPORTED
  182902. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  182903. PNGARG((png_structp png_ptr, png_uint_32 size));
  182904. #endif
  182905. /* Reset the compression stream */
  182906. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  182907. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  182908. #ifdef PNG_USER_MEM_SUPPORTED
  182909. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  182910. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182911. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182912. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182913. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  182914. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  182915. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  182916. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  182917. #endif
  182918. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  182919. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  182920. png_bytep chunk_name, png_bytep data, png_size_t length));
  182921. /* Write the start of a PNG chunk - length and chunk name. */
  182922. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  182923. png_bytep chunk_name, png_uint_32 length));
  182924. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  182925. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  182926. png_bytep data, png_size_t length));
  182927. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  182928. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  182929. /* Allocate and initialize the info structure */
  182930. extern PNG_EXPORT(png_infop,png_create_info_struct)
  182931. PNGARG((png_structp png_ptr));
  182932. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182933. /* Initialize the info structure (old interface - DEPRECATED) */
  182934. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  182935. #undef png_info_init
  182936. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  182937. png_sizeof(png_info));
  182938. #endif
  182939. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  182940. png_size_t png_info_struct_size));
  182941. /* Writes all the PNG information before the image. */
  182942. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  182943. png_infop info_ptr));
  182944. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  182945. png_infop info_ptr));
  182946. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  182947. /* read the information before the actual image data. */
  182948. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  182949. png_infop info_ptr));
  182950. #endif
  182951. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  182952. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  182953. PNGARG((png_structp png_ptr, png_timep ptime));
  182954. #endif
  182955. #if !defined(_WIN32_WCE)
  182956. /* "time.h" functions are not supported on WindowsCE */
  182957. #if defined(PNG_WRITE_tIME_SUPPORTED)
  182958. /* convert from a struct tm to png_time */
  182959. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  182960. struct tm FAR * ttime));
  182961. /* convert from time_t to png_time. Uses gmtime() */
  182962. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  182963. time_t ttime));
  182964. #endif /* PNG_WRITE_tIME_SUPPORTED */
  182965. #endif /* _WIN32_WCE */
  182966. #if defined(PNG_READ_EXPAND_SUPPORTED)
  182967. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  182968. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  182969. #if !defined(PNG_1_0_X)
  182970. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  182971. png_ptr));
  182972. #endif
  182973. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  182974. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  182975. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182976. /* Deprecated */
  182977. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  182978. #endif
  182979. #endif
  182980. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  182981. /* Use blue, green, red order for pixels. */
  182982. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  182983. #endif
  182984. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  182985. /* Expand the grayscale to 24-bit RGB if necessary. */
  182986. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  182987. #endif
  182988. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  182989. /* Reduce RGB to grayscale. */
  182990. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182991. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  182992. int error_action, double red, double green ));
  182993. #endif
  182994. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  182995. int error_action, png_fixed_point red, png_fixed_point green ));
  182996. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  182997. png_ptr));
  182998. #endif
  182999. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  183000. png_colorp palette));
  183001. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  183002. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  183003. #endif
  183004. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  183005. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  183006. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  183007. #endif
  183008. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  183009. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  183010. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  183011. #endif
  183012. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  183013. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  183014. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  183015. png_uint_32 filler, int flags));
  183016. /* The values of the PNG_FILLER_ defines should NOT be changed */
  183017. #define PNG_FILLER_BEFORE 0
  183018. #define PNG_FILLER_AFTER 1
  183019. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  183020. #if !defined(PNG_1_0_X)
  183021. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  183022. png_uint_32 filler, int flags));
  183023. #endif
  183024. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  183025. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  183026. /* Swap bytes in 16-bit depth files. */
  183027. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  183028. #endif
  183029. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  183030. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  183031. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  183032. #endif
  183033. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  183034. /* Swap packing order of pixels in bytes. */
  183035. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  183036. #endif
  183037. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  183038. /* Converts files to legal bit depths. */
  183039. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  183040. png_color_8p true_bits));
  183041. #endif
  183042. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  183043. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  183044. /* Have the code handle the interlacing. Returns the number of passes. */
  183045. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  183046. #endif
  183047. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  183048. /* Invert monochrome files */
  183049. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  183050. #endif
  183051. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  183052. /* Handle alpha and tRNS by replacing with a background color. */
  183053. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183054. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  183055. png_color_16p background_color, int background_gamma_code,
  183056. int need_expand, double background_gamma));
  183057. #endif
  183058. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  183059. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  183060. #define PNG_BACKGROUND_GAMMA_FILE 2
  183061. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  183062. #endif
  183063. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  183064. /* strip the second byte of information from a 16-bit depth file. */
  183065. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  183066. #endif
  183067. #if defined(PNG_READ_DITHER_SUPPORTED)
  183068. /* Turn on dithering, and reduce the palette to the number of colors available. */
  183069. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  183070. png_colorp palette, int num_palette, int maximum_colors,
  183071. png_uint_16p histogram, int full_dither));
  183072. #endif
  183073. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183074. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  183075. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183076. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  183077. double screen_gamma, double default_file_gamma));
  183078. #endif
  183079. #endif
  183080. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183081. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  183082. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  183083. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  183084. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  183085. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  183086. int empty_plte_permitted));
  183087. #endif
  183088. #endif
  183089. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183090. /* Set how many lines between output flushes - 0 for no flushing */
  183091. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  183092. /* Flush the current PNG output buffer */
  183093. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  183094. #endif
  183095. /* optional update palette with requested transformations */
  183096. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  183097. /* optional call to update the users info structure */
  183098. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  183099. png_infop info_ptr));
  183100. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183101. /* read one or more rows of image data. */
  183102. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  183103. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  183104. #endif
  183105. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183106. /* read a row of data. */
  183107. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  183108. png_bytep row,
  183109. png_bytep display_row));
  183110. #endif
  183111. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183112. /* read the whole image into memory at once. */
  183113. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  183114. png_bytepp image));
  183115. #endif
  183116. /* write a row of image data */
  183117. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  183118. png_bytep row));
  183119. /* write a few rows of image data */
  183120. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  183121. png_bytepp row, png_uint_32 num_rows));
  183122. /* write the image data */
  183123. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  183124. png_bytepp image));
  183125. /* writes the end of the PNG file. */
  183126. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  183127. png_infop info_ptr));
  183128. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183129. /* read the end of the PNG file. */
  183130. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  183131. png_infop info_ptr));
  183132. #endif
  183133. /* free any memory associated with the png_info_struct */
  183134. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  183135. png_infopp info_ptr_ptr));
  183136. /* free any memory associated with the png_struct and the png_info_structs */
  183137. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  183138. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  183139. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  183140. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  183141. png_infop end_info_ptr));
  183142. /* free any memory associated with the png_struct and the png_info_structs */
  183143. extern PNG_EXPORT(void,png_destroy_write_struct)
  183144. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  183145. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  183146. extern void png_write_destroy PNGARG((png_structp png_ptr));
  183147. /* set the libpng method of handling chunk CRC errors */
  183148. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  183149. int crit_action, int ancil_action));
  183150. /* Values for png_set_crc_action() to say how to handle CRC errors in
  183151. * ancillary and critical chunks, and whether to use the data contained
  183152. * therein. Note that it is impossible to "discard" data in a critical
  183153. * chunk. For versions prior to 0.90, the action was always error/quit,
  183154. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  183155. * chunks is warn/discard. These values should NOT be changed.
  183156. *
  183157. * value action:critical action:ancillary
  183158. */
  183159. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  183160. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  183161. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  183162. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  183163. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  183164. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  183165. /* These functions give the user control over the scan-line filtering in
  183166. * libpng and the compression methods used by zlib. These functions are
  183167. * mainly useful for testing, as the defaults should work with most users.
  183168. * Those users who are tight on memory or want faster performance at the
  183169. * expense of compression can modify them. See the compression library
  183170. * header file (zlib.h) for an explination of the compression functions.
  183171. */
  183172. /* set the filtering method(s) used by libpng. Currently, the only valid
  183173. * value for "method" is 0.
  183174. */
  183175. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  183176. int filters));
  183177. /* Flags for png_set_filter() to say which filters to use. The flags
  183178. * are chosen so that they don't conflict with real filter types
  183179. * below, in case they are supplied instead of the #defined constants.
  183180. * These values should NOT be changed.
  183181. */
  183182. #define PNG_NO_FILTERS 0x00
  183183. #define PNG_FILTER_NONE 0x08
  183184. #define PNG_FILTER_SUB 0x10
  183185. #define PNG_FILTER_UP 0x20
  183186. #define PNG_FILTER_AVG 0x40
  183187. #define PNG_FILTER_PAETH 0x80
  183188. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  183189. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  183190. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  183191. * These defines should NOT be changed.
  183192. */
  183193. #define PNG_FILTER_VALUE_NONE 0
  183194. #define PNG_FILTER_VALUE_SUB 1
  183195. #define PNG_FILTER_VALUE_UP 2
  183196. #define PNG_FILTER_VALUE_AVG 3
  183197. #define PNG_FILTER_VALUE_PAETH 4
  183198. #define PNG_FILTER_VALUE_LAST 5
  183199. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  183200. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  183201. * defines, either the default (minimum-sum-of-absolute-differences), or
  183202. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  183203. *
  183204. * Weights are factors >= 1.0, indicating how important it is to keep the
  183205. * filter type consistent between rows. Larger numbers mean the current
  183206. * filter is that many times as likely to be the same as the "num_weights"
  183207. * previous filters. This is cumulative for each previous row with a weight.
  183208. * There needs to be "num_weights" values in "filter_weights", or it can be
  183209. * NULL if the weights aren't being specified. Weights have no influence on
  183210. * the selection of the first row filter. Well chosen weights can (in theory)
  183211. * improve the compression for a given image.
  183212. *
  183213. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  183214. * filter type. Higher costs indicate more decoding expense, and are
  183215. * therefore less likely to be selected over a filter with lower computational
  183216. * costs. There needs to be a value in "filter_costs" for each valid filter
  183217. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  183218. * setting the costs. Costs try to improve the speed of decompression without
  183219. * unduly increasing the compressed image size.
  183220. *
  183221. * A negative weight or cost indicates the default value is to be used, and
  183222. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  183223. * The default values for both weights and costs are currently 1.0, but may
  183224. * change if good general weighting/cost heuristics can be found. If both
  183225. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  183226. * to the UNWEIGHTED method, but with added encoding time/computation.
  183227. */
  183228. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183229. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  183230. int heuristic_method, int num_weights, png_doublep filter_weights,
  183231. png_doublep filter_costs));
  183232. #endif
  183233. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  183234. /* Heuristic used for row filter selection. These defines should NOT be
  183235. * changed.
  183236. */
  183237. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  183238. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  183239. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  183240. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  183241. /* Set the library compression level. Currently, valid values range from
  183242. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  183243. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  183244. * shown that zlib compression levels 3-6 usually perform as well as level 9
  183245. * for PNG images, and do considerably fewer caclulations. In the future,
  183246. * these values may not correspond directly to the zlib compression levels.
  183247. */
  183248. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  183249. int level));
  183250. extern PNG_EXPORT(void,png_set_compression_mem_level)
  183251. PNGARG((png_structp png_ptr, int mem_level));
  183252. extern PNG_EXPORT(void,png_set_compression_strategy)
  183253. PNGARG((png_structp png_ptr, int strategy));
  183254. extern PNG_EXPORT(void,png_set_compression_window_bits)
  183255. PNGARG((png_structp png_ptr, int window_bits));
  183256. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  183257. int method));
  183258. /* These next functions are called for input/output, memory, and error
  183259. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  183260. * and call standard C I/O routines such as fread(), fwrite(), and
  183261. * fprintf(). These functions can be made to use other I/O routines
  183262. * at run time for those applications that need to handle I/O in a
  183263. * different manner by calling png_set_???_fn(). See libpng.txt for
  183264. * more information.
  183265. */
  183266. #if !defined(PNG_NO_STDIO)
  183267. /* Initialize the input/output for the PNG file to the default functions. */
  183268. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  183269. #endif
  183270. /* Replace the (error and abort), and warning functions with user
  183271. * supplied functions. If no messages are to be printed you must still
  183272. * write and use replacement functions. The replacement error_fn should
  183273. * still do a longjmp to the last setjmp location if you are using this
  183274. * method of error handling. If error_fn or warning_fn is NULL, the
  183275. * default function will be used.
  183276. */
  183277. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  183278. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  183279. /* Return the user pointer associated with the error functions */
  183280. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  183281. /* Replace the default data output functions with a user supplied one(s).
  183282. * If buffered output is not used, then output_flush_fn can be set to NULL.
  183283. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  183284. * output_flush_fn will be ignored (and thus can be NULL).
  183285. */
  183286. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  183287. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  183288. /* Replace the default data input function with a user supplied one. */
  183289. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  183290. png_voidp io_ptr, png_rw_ptr read_data_fn));
  183291. /* Return the user pointer associated with the I/O functions */
  183292. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  183293. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  183294. png_read_status_ptr read_row_fn));
  183295. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  183296. png_write_status_ptr write_row_fn));
  183297. #ifdef PNG_USER_MEM_SUPPORTED
  183298. /* Replace the default memory allocation functions with user supplied one(s). */
  183299. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  183300. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  183301. /* Return the user pointer associated with the memory functions */
  183302. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  183303. #endif
  183304. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183305. defined(PNG_LEGACY_SUPPORTED)
  183306. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  183307. png_ptr, png_user_transform_ptr read_user_transform_fn));
  183308. #endif
  183309. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183310. defined(PNG_LEGACY_SUPPORTED)
  183311. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  183312. png_ptr, png_user_transform_ptr write_user_transform_fn));
  183313. #endif
  183314. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183315. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183316. defined(PNG_LEGACY_SUPPORTED)
  183317. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  183318. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  183319. int user_transform_channels));
  183320. /* Return the user pointer associated with the user transform functions */
  183321. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  183322. PNGARG((png_structp png_ptr));
  183323. #endif
  183324. #ifdef PNG_USER_CHUNKS_SUPPORTED
  183325. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  183326. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  183327. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  183328. png_ptr));
  183329. #endif
  183330. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183331. /* Sets the function callbacks for the push reader, and a pointer to a
  183332. * user-defined structure available to the callback functions.
  183333. */
  183334. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  183335. png_voidp progressive_ptr,
  183336. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  183337. png_progressive_end_ptr end_fn));
  183338. /* returns the user pointer associated with the push read functions */
  183339. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  183340. PNGARG((png_structp png_ptr));
  183341. /* function to be called when data becomes available */
  183342. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  183343. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  183344. /* function that combines rows. Not very much different than the
  183345. * png_combine_row() call. Is this even used?????
  183346. */
  183347. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  183348. png_bytep old_row, png_bytep new_row));
  183349. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  183350. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  183351. png_uint_32 size));
  183352. #if defined(PNG_1_0_X)
  183353. # define png_malloc_warn png_malloc
  183354. #else
  183355. /* Added at libpng version 1.2.4 */
  183356. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  183357. png_uint_32 size));
  183358. #endif
  183359. /* frees a pointer allocated by png_malloc() */
  183360. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  183361. #if defined(PNG_1_0_X)
  183362. /* Function to allocate memory for zlib. */
  183363. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  183364. uInt size));
  183365. /* Function to free memory for zlib */
  183366. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  183367. #endif
  183368. /* Free data that was allocated internally */
  183369. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  183370. png_infop info_ptr, png_uint_32 free_me, int num));
  183371. #ifdef PNG_FREE_ME_SUPPORTED
  183372. /* Reassign responsibility for freeing existing data, whether allocated
  183373. * by libpng or by the application */
  183374. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  183375. png_infop info_ptr, int freer, png_uint_32 mask));
  183376. #endif
  183377. /* assignments for png_data_freer */
  183378. #define PNG_DESTROY_WILL_FREE_DATA 1
  183379. #define PNG_SET_WILL_FREE_DATA 1
  183380. #define PNG_USER_WILL_FREE_DATA 2
  183381. /* Flags for png_ptr->free_me and info_ptr->free_me */
  183382. #define PNG_FREE_HIST 0x0008
  183383. #define PNG_FREE_ICCP 0x0010
  183384. #define PNG_FREE_SPLT 0x0020
  183385. #define PNG_FREE_ROWS 0x0040
  183386. #define PNG_FREE_PCAL 0x0080
  183387. #define PNG_FREE_SCAL 0x0100
  183388. #define PNG_FREE_UNKN 0x0200
  183389. #define PNG_FREE_LIST 0x0400
  183390. #define PNG_FREE_PLTE 0x1000
  183391. #define PNG_FREE_TRNS 0x2000
  183392. #define PNG_FREE_TEXT 0x4000
  183393. #define PNG_FREE_ALL 0x7fff
  183394. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  183395. #ifdef PNG_USER_MEM_SUPPORTED
  183396. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  183397. png_uint_32 size));
  183398. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  183399. png_voidp ptr));
  183400. #endif
  183401. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  183402. png_voidp s1, png_voidp s2, png_uint_32 size));
  183403. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  183404. png_voidp s1, int value, png_uint_32 size));
  183405. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  183406. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  183407. int check));
  183408. #endif /* USE_FAR_KEYWORD */
  183409. #ifndef PNG_NO_ERROR_TEXT
  183410. /* Fatal error in PNG image of libpng - can't continue */
  183411. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  183412. png_const_charp error_message));
  183413. /* The same, but the chunk name is prepended to the error string. */
  183414. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  183415. png_const_charp error_message));
  183416. #else
  183417. /* Fatal error in PNG image of libpng - can't continue */
  183418. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  183419. #endif
  183420. #ifndef PNG_NO_WARNINGS
  183421. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  183422. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  183423. png_const_charp warning_message));
  183424. #ifdef PNG_READ_SUPPORTED
  183425. /* Non-fatal error in libpng, chunk name is prepended to message. */
  183426. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  183427. png_const_charp warning_message));
  183428. #endif /* PNG_READ_SUPPORTED */
  183429. #endif /* PNG_NO_WARNINGS */
  183430. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  183431. * Similarly, the png_get_<chunk> calls are used to read values from the
  183432. * png_info_struct, either storing the parameters in the passed variables, or
  183433. * setting pointers into the png_info_struct where the data is stored. The
  183434. * png_get_<chunk> functions return a non-zero value if the data was available
  183435. * in info_ptr, or return zero and do not change any of the parameters if the
  183436. * data was not available.
  183437. *
  183438. * These functions should be used instead of directly accessing png_info
  183439. * to avoid problems with future changes in the size and internal layout of
  183440. * png_info_struct.
  183441. */
  183442. /* Returns "flag" if chunk data is valid in info_ptr. */
  183443. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  183444. png_infop info_ptr, png_uint_32 flag));
  183445. /* Returns number of bytes needed to hold a transformed row. */
  183446. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  183447. png_infop info_ptr));
  183448. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183449. /* Returns row_pointers, which is an array of pointers to scanlines that was
  183450. returned from png_read_png(). */
  183451. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  183452. png_infop info_ptr));
  183453. /* Set row_pointers, which is an array of pointers to scanlines for use
  183454. by png_write_png(). */
  183455. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  183456. png_infop info_ptr, png_bytepp row_pointers));
  183457. #endif
  183458. /* Returns number of color channels in image. */
  183459. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  183460. png_infop info_ptr));
  183461. #ifdef PNG_EASY_ACCESS_SUPPORTED
  183462. /* Returns image width in pixels. */
  183463. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  183464. png_ptr, png_infop info_ptr));
  183465. /* Returns image height in pixels. */
  183466. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  183467. png_ptr, png_infop info_ptr));
  183468. /* Returns image bit_depth. */
  183469. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  183470. png_ptr, png_infop info_ptr));
  183471. /* Returns image color_type. */
  183472. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  183473. png_ptr, png_infop info_ptr));
  183474. /* Returns image filter_type. */
  183475. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  183476. png_ptr, png_infop info_ptr));
  183477. /* Returns image interlace_type. */
  183478. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  183479. png_ptr, png_infop info_ptr));
  183480. /* Returns image compression_type. */
  183481. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  183482. png_ptr, png_infop info_ptr));
  183483. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  183484. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  183485. png_ptr, png_infop info_ptr));
  183486. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  183487. png_ptr, png_infop info_ptr));
  183488. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  183489. png_ptr, png_infop info_ptr));
  183490. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  183491. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183492. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  183493. png_ptr, png_infop info_ptr));
  183494. #endif
  183495. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  183496. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  183497. png_ptr, png_infop info_ptr));
  183498. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  183499. png_ptr, png_infop info_ptr));
  183500. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  183501. png_ptr, png_infop info_ptr));
  183502. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  183503. png_ptr, png_infop info_ptr));
  183504. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  183505. /* Returns pointer to signature string read from PNG header */
  183506. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  183507. png_infop info_ptr));
  183508. #if defined(PNG_bKGD_SUPPORTED)
  183509. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  183510. png_infop info_ptr, png_color_16p *background));
  183511. #endif
  183512. #if defined(PNG_bKGD_SUPPORTED)
  183513. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  183514. png_infop info_ptr, png_color_16p background));
  183515. #endif
  183516. #if defined(PNG_cHRM_SUPPORTED)
  183517. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183518. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  183519. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  183520. double *red_y, double *green_x, double *green_y, double *blue_x,
  183521. double *blue_y));
  183522. #endif
  183523. #ifdef PNG_FIXED_POINT_SUPPORTED
  183524. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  183525. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  183526. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  183527. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  183528. *int_blue_x, png_fixed_point *int_blue_y));
  183529. #endif
  183530. #endif
  183531. #if defined(PNG_cHRM_SUPPORTED)
  183532. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183533. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  183534. png_infop info_ptr, double white_x, double white_y, double red_x,
  183535. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  183536. #endif
  183537. #ifdef PNG_FIXED_POINT_SUPPORTED
  183538. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  183539. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  183540. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  183541. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  183542. png_fixed_point int_blue_y));
  183543. #endif
  183544. #endif
  183545. #if defined(PNG_gAMA_SUPPORTED)
  183546. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183547. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  183548. png_infop info_ptr, double *file_gamma));
  183549. #endif
  183550. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  183551. png_infop info_ptr, png_fixed_point *int_file_gamma));
  183552. #endif
  183553. #if defined(PNG_gAMA_SUPPORTED)
  183554. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183555. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  183556. png_infop info_ptr, double file_gamma));
  183557. #endif
  183558. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  183559. png_infop info_ptr, png_fixed_point int_file_gamma));
  183560. #endif
  183561. #if defined(PNG_hIST_SUPPORTED)
  183562. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  183563. png_infop info_ptr, png_uint_16p *hist));
  183564. #endif
  183565. #if defined(PNG_hIST_SUPPORTED)
  183566. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  183567. png_infop info_ptr, png_uint_16p hist));
  183568. #endif
  183569. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  183570. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  183571. int *bit_depth, int *color_type, int *interlace_method,
  183572. int *compression_method, int *filter_method));
  183573. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  183574. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  183575. int color_type, int interlace_method, int compression_method,
  183576. int filter_method));
  183577. #if defined(PNG_oFFs_SUPPORTED)
  183578. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  183579. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  183580. int *unit_type));
  183581. #endif
  183582. #if defined(PNG_oFFs_SUPPORTED)
  183583. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  183584. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  183585. int unit_type));
  183586. #endif
  183587. #if defined(PNG_pCAL_SUPPORTED)
  183588. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  183589. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  183590. int *type, int *nparams, png_charp *units, png_charpp *params));
  183591. #endif
  183592. #if defined(PNG_pCAL_SUPPORTED)
  183593. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  183594. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  183595. int type, int nparams, png_charp units, png_charpp params));
  183596. #endif
  183597. #if defined(PNG_pHYs_SUPPORTED)
  183598. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  183599. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  183600. #endif
  183601. #if defined(PNG_pHYs_SUPPORTED)
  183602. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  183603. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  183604. #endif
  183605. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  183606. png_infop info_ptr, png_colorp *palette, int *num_palette));
  183607. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  183608. png_infop info_ptr, png_colorp palette, int num_palette));
  183609. #if defined(PNG_sBIT_SUPPORTED)
  183610. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  183611. png_infop info_ptr, png_color_8p *sig_bit));
  183612. #endif
  183613. #if defined(PNG_sBIT_SUPPORTED)
  183614. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  183615. png_infop info_ptr, png_color_8p sig_bit));
  183616. #endif
  183617. #if defined(PNG_sRGB_SUPPORTED)
  183618. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  183619. png_infop info_ptr, int *intent));
  183620. #endif
  183621. #if defined(PNG_sRGB_SUPPORTED)
  183622. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  183623. png_infop info_ptr, int intent));
  183624. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  183625. png_infop info_ptr, int intent));
  183626. #endif
  183627. #if defined(PNG_iCCP_SUPPORTED)
  183628. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  183629. png_infop info_ptr, png_charpp name, int *compression_type,
  183630. png_charpp profile, png_uint_32 *proflen));
  183631. /* Note to maintainer: profile should be png_bytepp */
  183632. #endif
  183633. #if defined(PNG_iCCP_SUPPORTED)
  183634. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  183635. png_infop info_ptr, png_charp name, int compression_type,
  183636. png_charp profile, png_uint_32 proflen));
  183637. /* Note to maintainer: profile should be png_bytep */
  183638. #endif
  183639. #if defined(PNG_sPLT_SUPPORTED)
  183640. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  183641. png_infop info_ptr, png_sPLT_tpp entries));
  183642. #endif
  183643. #if defined(PNG_sPLT_SUPPORTED)
  183644. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  183645. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  183646. #endif
  183647. #if defined(PNG_TEXT_SUPPORTED)
  183648. /* png_get_text also returns the number of text chunks in *num_text */
  183649. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  183650. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  183651. #endif
  183652. /*
  183653. * Note while png_set_text() will accept a structure whose text,
  183654. * language, and translated keywords are NULL pointers, the structure
  183655. * returned by png_get_text will always contain regular
  183656. * zero-terminated C strings. They might be empty strings but
  183657. * they will never be NULL pointers.
  183658. */
  183659. #if defined(PNG_TEXT_SUPPORTED)
  183660. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  183661. png_infop info_ptr, png_textp text_ptr, int num_text));
  183662. #endif
  183663. #if defined(PNG_tIME_SUPPORTED)
  183664. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  183665. png_infop info_ptr, png_timep *mod_time));
  183666. #endif
  183667. #if defined(PNG_tIME_SUPPORTED)
  183668. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  183669. png_infop info_ptr, png_timep mod_time));
  183670. #endif
  183671. #if defined(PNG_tRNS_SUPPORTED)
  183672. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  183673. png_infop info_ptr, png_bytep *trans, int *num_trans,
  183674. png_color_16p *trans_values));
  183675. #endif
  183676. #if defined(PNG_tRNS_SUPPORTED)
  183677. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  183678. png_infop info_ptr, png_bytep trans, int num_trans,
  183679. png_color_16p trans_values));
  183680. #endif
  183681. #if defined(PNG_tRNS_SUPPORTED)
  183682. #endif
  183683. #if defined(PNG_sCAL_SUPPORTED)
  183684. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183685. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  183686. png_infop info_ptr, int *unit, double *width, double *height));
  183687. #else
  183688. #ifdef PNG_FIXED_POINT_SUPPORTED
  183689. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  183690. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  183691. #endif
  183692. #endif
  183693. #endif /* PNG_sCAL_SUPPORTED */
  183694. #if defined(PNG_sCAL_SUPPORTED)
  183695. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183696. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  183697. png_infop info_ptr, int unit, double width, double height));
  183698. #else
  183699. #ifdef PNG_FIXED_POINT_SUPPORTED
  183700. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  183701. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  183702. #endif
  183703. #endif
  183704. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  183705. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183706. /* provide a list of chunks and how they are to be handled, if the built-in
  183707. handling or default unknown chunk handling is not desired. Any chunks not
  183708. listed will be handled in the default manner. The IHDR and IEND chunks
  183709. must not be listed.
  183710. keep = 0: follow default behaviour
  183711. = 1: do not keep
  183712. = 2: keep only if safe-to-copy
  183713. = 3: keep even if unsafe-to-copy
  183714. */
  183715. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  183716. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  183717. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  183718. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  183719. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  183720. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  183721. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  183722. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  183723. #endif
  183724. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  183725. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  183726. chunk_name));
  183727. #endif
  183728. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  183729. If you need to turn it off for a chunk that your application has freed,
  183730. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  183731. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  183732. png_infop info_ptr, int mask));
  183733. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183734. /* The "params" pointer is currently not used and is for future expansion. */
  183735. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  183736. png_infop info_ptr,
  183737. int transforms,
  183738. png_voidp params));
  183739. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  183740. png_infop info_ptr,
  183741. int transforms,
  183742. png_voidp params));
  183743. #endif
  183744. /* Define PNG_DEBUG at compile time for debugging information. Higher
  183745. * numbers for PNG_DEBUG mean more debugging information. This has
  183746. * only been added since version 0.95 so it is not implemented throughout
  183747. * libpng yet, but more support will be added as needed.
  183748. */
  183749. #ifdef PNG_DEBUG
  183750. #if (PNG_DEBUG > 0)
  183751. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  183752. #include <crtdbg.h>
  183753. #if (PNG_DEBUG > 1)
  183754. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  183755. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  183756. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  183757. #endif
  183758. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  183759. #ifndef PNG_DEBUG_FILE
  183760. #define PNG_DEBUG_FILE stderr
  183761. #endif /* PNG_DEBUG_FILE */
  183762. #if (PNG_DEBUG > 1)
  183763. #define png_debug(l,m) \
  183764. { \
  183765. int num_tabs=l; \
  183766. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183767. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  183768. }
  183769. #define png_debug1(l,m,p1) \
  183770. { \
  183771. int num_tabs=l; \
  183772. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183773. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  183774. }
  183775. #define png_debug2(l,m,p1,p2) \
  183776. { \
  183777. int num_tabs=l; \
  183778. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183779. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  183780. }
  183781. #endif /* (PNG_DEBUG > 1) */
  183782. #endif /* _MSC_VER */
  183783. #endif /* (PNG_DEBUG > 0) */
  183784. #endif /* PNG_DEBUG */
  183785. #ifndef png_debug
  183786. #define png_debug(l, m)
  183787. #endif
  183788. #ifndef png_debug1
  183789. #define png_debug1(l, m, p1)
  183790. #endif
  183791. #ifndef png_debug2
  183792. #define png_debug2(l, m, p1, p2)
  183793. #endif
  183794. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  183795. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  183796. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  183797. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  183798. #ifdef PNG_MNG_FEATURES_SUPPORTED
  183799. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  183800. png_ptr, png_uint_32 mng_features_permitted));
  183801. #endif
  183802. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  183803. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  183804. #define PNG_HANDLE_CHUNK_NEVER 1
  183805. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  183806. #define PNG_HANDLE_CHUNK_ALWAYS 3
  183807. /* Added to version 1.2.0 */
  183808. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  183809. #if defined(PNG_MMX_CODE_SUPPORTED)
  183810. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  183811. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  183812. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  183813. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  183814. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  183815. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  183816. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  183817. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  183818. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  183819. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  183820. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  183821. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  183822. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  183823. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  183824. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  183825. #define PNG_MMX_WRITE_FLAGS ( 0 )
  183826. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  183827. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  183828. | PNG_MMX_READ_FLAGS \
  183829. | PNG_MMX_WRITE_FLAGS )
  183830. #define PNG_SELECT_READ 1
  183831. #define PNG_SELECT_WRITE 2
  183832. #endif /* PNG_MMX_CODE_SUPPORTED */
  183833. #if !defined(PNG_1_0_X)
  183834. /* pngget.c */
  183835. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  183836. PNGARG((int flag_select, int *compilerID));
  183837. /* pngget.c */
  183838. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  183839. PNGARG((int flag_select));
  183840. /* pngget.c */
  183841. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  183842. PNGARG((png_structp png_ptr));
  183843. /* pngget.c */
  183844. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  183845. PNGARG((png_structp png_ptr));
  183846. /* pngget.c */
  183847. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  183848. PNGARG((png_structp png_ptr));
  183849. /* pngset.c */
  183850. extern PNG_EXPORT(void,png_set_asm_flags)
  183851. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  183852. /* pngset.c */
  183853. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  183854. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  183855. png_uint_32 mmx_rowbytes_threshold));
  183856. #endif /* PNG_1_0_X */
  183857. #if !defined(PNG_1_0_X)
  183858. /* png.c, pnggccrd.c, or pngvcrd.c */
  183859. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  183860. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  183861. /* Strip the prepended error numbers ("#nnn ") from error and warning
  183862. * messages before passing them to the error or warning handler. */
  183863. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  183864. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  183865. png_ptr, png_uint_32 strip_mode));
  183866. #endif
  183867. #endif /* PNG_1_0_X */
  183868. /* Added at libpng-1.2.6 */
  183869. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  183870. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  183871. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  183872. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  183873. png_ptr));
  183874. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  183875. png_ptr));
  183876. #endif
  183877. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  183878. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  183879. /* With these routines we avoid an integer divide, which will be slower on
  183880. * most machines. However, it does take more operations than the corresponding
  183881. * divide method, so it may be slower on a few RISC systems. There are two
  183882. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  183883. *
  183884. * Note that the rounding factors are NOT supposed to be the same! 128 and
  183885. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  183886. * standard method.
  183887. *
  183888. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  183889. */
  183890. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  183891. # define png_composite(composite, fg, alpha, bg) \
  183892. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  183893. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  183894. (png_uint_16)(alpha)) + (png_uint_16)128); \
  183895. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  183896. # define png_composite_16(composite, fg, alpha, bg) \
  183897. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  183898. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  183899. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  183900. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  183901. #else /* standard method using integer division */
  183902. # define png_composite(composite, fg, alpha, bg) \
  183903. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  183904. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  183905. (png_uint_16)127) / 255)
  183906. # define png_composite_16(composite, fg, alpha, bg) \
  183907. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  183908. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  183909. (png_uint_32)32767) / (png_uint_32)65535L)
  183910. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  183911. /* Inline macros to do direct reads of bytes from the input buffer. These
  183912. * require that you are using an architecture that uses PNG byte ordering
  183913. * (MSB first) and supports unaligned data storage. I think that PowerPC
  183914. * in big-endian mode and 680x0 are the only ones that will support this.
  183915. * The x86 line of processors definitely do not. The png_get_int_32()
  183916. * routine also assumes we are using two's complement format for negative
  183917. * values, which is almost certainly true.
  183918. */
  183919. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  183920. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  183921. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  183922. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  183923. #else
  183924. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  183925. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  183926. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  183927. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  183928. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  183929. PNGARG((png_structp png_ptr, png_bytep buf));
  183930. /* No png_get_int_16 -- may be added if there's a real need for it. */
  183931. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  183932. */
  183933. extern PNG_EXPORT(void,png_save_uint_32)
  183934. PNGARG((png_bytep buf, png_uint_32 i));
  183935. extern PNG_EXPORT(void,png_save_int_32)
  183936. PNGARG((png_bytep buf, png_int_32 i));
  183937. /* Place a 16-bit number into a buffer in PNG byte order.
  183938. * The parameter is declared unsigned int, not png_uint_16,
  183939. * just to avoid potential problems on pre-ANSI C compilers.
  183940. */
  183941. extern PNG_EXPORT(void,png_save_uint_16)
  183942. PNGARG((png_bytep buf, unsigned int i));
  183943. /* No png_save_int_16 -- may be added if there's a real need for it. */
  183944. /* ************************************************************************* */
  183945. /* These next functions are used internally in the code. They generally
  183946. * shouldn't be used unless you are writing code to add or replace some
  183947. * functionality in libpng. More information about most functions can
  183948. * be found in the files where the functions are located.
  183949. */
  183950. /* Various modes of operation, that are visible to applications because
  183951. * they are used for unknown chunk location.
  183952. */
  183953. #define PNG_HAVE_IHDR 0x01
  183954. #define PNG_HAVE_PLTE 0x02
  183955. #define PNG_HAVE_IDAT 0x04
  183956. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  183957. #define PNG_HAVE_IEND 0x10
  183958. #if defined(PNG_INTERNAL)
  183959. /* More modes of operation. Note that after an init, mode is set to
  183960. * zero automatically when the structure is created.
  183961. */
  183962. #define PNG_HAVE_gAMA 0x20
  183963. #define PNG_HAVE_cHRM 0x40
  183964. #define PNG_HAVE_sRGB 0x80
  183965. #define PNG_HAVE_CHUNK_HEADER 0x100
  183966. #define PNG_WROTE_tIME 0x200
  183967. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  183968. #define PNG_BACKGROUND_IS_GRAY 0x800
  183969. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  183970. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  183971. /* flags for the transformations the PNG library does on the image data */
  183972. #define PNG_BGR 0x0001
  183973. #define PNG_INTERLACE 0x0002
  183974. #define PNG_PACK 0x0004
  183975. #define PNG_SHIFT 0x0008
  183976. #define PNG_SWAP_BYTES 0x0010
  183977. #define PNG_INVERT_MONO 0x0020
  183978. #define PNG_DITHER 0x0040
  183979. #define PNG_BACKGROUND 0x0080
  183980. #define PNG_BACKGROUND_EXPAND 0x0100
  183981. /* 0x0200 unused */
  183982. #define PNG_16_TO_8 0x0400
  183983. #define PNG_RGBA 0x0800
  183984. #define PNG_EXPAND 0x1000
  183985. #define PNG_GAMMA 0x2000
  183986. #define PNG_GRAY_TO_RGB 0x4000
  183987. #define PNG_FILLER 0x8000L
  183988. #define PNG_PACKSWAP 0x10000L
  183989. #define PNG_SWAP_ALPHA 0x20000L
  183990. #define PNG_STRIP_ALPHA 0x40000L
  183991. #define PNG_INVERT_ALPHA 0x80000L
  183992. #define PNG_USER_TRANSFORM 0x100000L
  183993. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  183994. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  183995. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  183996. /* 0x800000L Unused */
  183997. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  183998. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  183999. /* 0x4000000L unused */
  184000. /* 0x8000000L unused */
  184001. /* 0x10000000L unused */
  184002. /* 0x20000000L unused */
  184003. /* 0x40000000L unused */
  184004. /* flags for png_create_struct */
  184005. #define PNG_STRUCT_PNG 0x0001
  184006. #define PNG_STRUCT_INFO 0x0002
  184007. /* Scaling factor for filter heuristic weighting calculations */
  184008. #define PNG_WEIGHT_SHIFT 8
  184009. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  184010. #define PNG_COST_SHIFT 3
  184011. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  184012. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  184013. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  184014. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  184015. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  184016. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  184017. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  184018. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  184019. #define PNG_FLAG_ROW_INIT 0x0040
  184020. #define PNG_FLAG_FILLER_AFTER 0x0080
  184021. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  184022. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  184023. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  184024. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  184025. #define PNG_FLAG_FREE_PLTE 0x1000
  184026. #define PNG_FLAG_FREE_TRNS 0x2000
  184027. #define PNG_FLAG_FREE_HIST 0x4000
  184028. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  184029. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  184030. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  184031. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  184032. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  184033. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  184034. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  184035. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  184036. /* 0x800000L unused */
  184037. /* 0x1000000L unused */
  184038. /* 0x2000000L unused */
  184039. /* 0x4000000L unused */
  184040. /* 0x8000000L unused */
  184041. /* 0x10000000L unused */
  184042. /* 0x20000000L unused */
  184043. /* 0x40000000L unused */
  184044. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  184045. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  184046. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  184047. PNG_FLAG_CRC_CRITICAL_IGNORE)
  184048. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  184049. PNG_FLAG_CRC_CRITICAL_MASK)
  184050. /* save typing and make code easier to understand */
  184051. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  184052. abs((int)((c1).green) - (int)((c2).green)) + \
  184053. abs((int)((c1).blue) - (int)((c2).blue)))
  184054. /* Added to libpng-1.2.6 JB */
  184055. #define PNG_ROWBYTES(pixel_bits, width) \
  184056. ((pixel_bits) >= 8 ? \
  184057. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  184058. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  184059. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  184060. ideal-delta..ideal+delta. Each argument is evaluated twice.
  184061. "ideal" and "delta" should be constants, normally simple
  184062. integers, "value" a variable. Added to libpng-1.2.6 JB */
  184063. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  184064. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  184065. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  184066. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  184067. /* place to hold the signature string for a PNG file. */
  184068. #ifdef PNG_USE_GLOBAL_ARRAYS
  184069. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  184070. #else
  184071. #endif
  184072. #endif /* PNG_NO_EXTERN */
  184073. /* Constant strings for known chunk types. If you need to add a chunk,
  184074. * define the name here, and add an invocation of the macro in png.c and
  184075. * wherever it's needed.
  184076. */
  184077. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  184078. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  184079. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  184080. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  184081. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  184082. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  184083. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  184084. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  184085. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  184086. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  184087. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  184088. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  184089. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  184090. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  184091. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  184092. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  184093. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  184094. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  184095. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  184096. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  184097. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  184098. #ifdef PNG_USE_GLOBAL_ARRAYS
  184099. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  184100. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  184101. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  184102. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  184103. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  184104. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  184105. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  184106. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  184107. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  184108. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  184109. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  184110. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  184111. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  184112. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  184113. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  184114. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  184115. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  184116. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  184117. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  184118. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  184119. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  184120. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184121. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184122. /* Initialize png_ptr struct for reading, and allocate any other memory.
  184123. * (old interface - DEPRECATED - use png_create_read_struct instead).
  184124. */
  184125. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  184126. #undef png_read_init
  184127. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  184128. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  184129. #endif
  184130. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  184131. png_const_charp user_png_ver, png_size_t png_struct_size));
  184132. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184133. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  184134. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  184135. png_info_size));
  184136. #endif
  184137. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184138. /* Initialize png_ptr struct for writing, and allocate any other memory.
  184139. * (old interface - DEPRECATED - use png_create_write_struct instead).
  184140. */
  184141. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  184142. #undef png_write_init
  184143. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  184144. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  184145. #endif
  184146. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  184147. png_const_charp user_png_ver, png_size_t png_struct_size));
  184148. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  184149. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  184150. png_info_size));
  184151. /* Allocate memory for an internal libpng struct */
  184152. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  184153. /* Free memory from internal libpng struct */
  184154. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  184155. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  184156. malloc_fn, png_voidp mem_ptr));
  184157. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  184158. png_free_ptr free_fn, png_voidp mem_ptr));
  184159. /* Free any memory that info_ptr points to and reset struct. */
  184160. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  184161. png_infop info_ptr));
  184162. #ifndef PNG_1_0_X
  184163. /* Function to allocate memory for zlib. */
  184164. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  184165. /* Function to free memory for zlib */
  184166. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  184167. #ifdef PNG_SIZE_T
  184168. /* Function to convert a sizeof an item to png_sizeof item */
  184169. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  184170. #endif
  184171. /* Next four functions are used internally as callbacks. PNGAPI is required
  184172. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  184173. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  184174. png_bytep data, png_size_t length));
  184175. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184176. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  184177. png_bytep buffer, png_size_t length));
  184178. #endif
  184179. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  184180. png_bytep data, png_size_t length));
  184181. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184182. #if !defined(PNG_NO_STDIO)
  184183. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  184184. #endif
  184185. #endif
  184186. #else /* PNG_1_0_X */
  184187. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184188. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  184189. png_bytep buffer, png_size_t length));
  184190. #endif
  184191. #endif /* PNG_1_0_X */
  184192. /* Reset the CRC variable */
  184193. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  184194. /* Write the "data" buffer to whatever output you are using. */
  184195. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  184196. png_size_t length));
  184197. /* Read data from whatever input you are using into the "data" buffer */
  184198. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  184199. png_size_t length));
  184200. /* Read bytes into buf, and update png_ptr->crc */
  184201. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  184202. png_size_t length));
  184203. /* Decompress data in a chunk that uses compression */
  184204. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  184205. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  184206. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  184207. int comp_type, png_charp chunkdata, png_size_t chunklength,
  184208. png_size_t prefix_length, png_size_t *data_length));
  184209. #endif
  184210. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  184211. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  184212. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  184213. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  184214. /* Calculate the CRC over a section of data. Note that we are only
  184215. * passing a maximum of 64K on systems that have this as a memory limit,
  184216. * since this is the maximum buffer size we can specify.
  184217. */
  184218. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  184219. png_size_t length));
  184220. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184221. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  184222. #endif
  184223. /* simple function to write the signature */
  184224. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  184225. /* write various chunks */
  184226. /* Write the IHDR chunk, and update the png_struct with the necessary
  184227. * information.
  184228. */
  184229. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  184230. png_uint_32 height,
  184231. int bit_depth, int color_type, int compression_method, int filter_method,
  184232. int interlace_method));
  184233. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  184234. png_uint_32 num_pal));
  184235. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  184236. png_size_t length));
  184237. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  184238. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  184239. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184240. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  184241. #endif
  184242. #ifdef PNG_FIXED_POINT_SUPPORTED
  184243. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  184244. file_gamma));
  184245. #endif
  184246. #endif
  184247. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  184248. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  184249. int color_type));
  184250. #endif
  184251. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  184252. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184253. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  184254. double white_x, double white_y,
  184255. double red_x, double red_y, double green_x, double green_y,
  184256. double blue_x, double blue_y));
  184257. #endif
  184258. #ifdef PNG_FIXED_POINT_SUPPORTED
  184259. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  184260. png_fixed_point int_white_x, png_fixed_point int_white_y,
  184261. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  184262. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  184263. png_fixed_point int_blue_y));
  184264. #endif
  184265. #endif
  184266. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  184267. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  184268. int intent));
  184269. #endif
  184270. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  184271. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  184272. png_charp name, int compression_type,
  184273. png_charp profile, int proflen));
  184274. /* Note to maintainer: profile should be png_bytep */
  184275. #endif
  184276. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  184277. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  184278. png_sPLT_tp palette));
  184279. #endif
  184280. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  184281. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  184282. png_color_16p values, int number, int color_type));
  184283. #endif
  184284. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  184285. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  184286. png_color_16p values, int color_type));
  184287. #endif
  184288. #if defined(PNG_WRITE_hIST_SUPPORTED)
  184289. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  184290. int num_hist));
  184291. #endif
  184292. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  184293. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  184294. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  184295. png_charp key, png_charpp new_key));
  184296. #endif
  184297. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  184298. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  184299. png_charp text, png_size_t text_len));
  184300. #endif
  184301. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  184302. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  184303. png_charp text, png_size_t text_len, int compression));
  184304. #endif
  184305. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  184306. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  184307. int compression, png_charp key, png_charp lang, png_charp lang_key,
  184308. png_charp text));
  184309. #endif
  184310. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  184311. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  184312. png_infop info_ptr, png_textp text_ptr, int num_text));
  184313. #endif
  184314. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  184315. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  184316. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  184317. #endif
  184318. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  184319. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  184320. png_int_32 X0, png_int_32 X1, int type, int nparams,
  184321. png_charp units, png_charpp params));
  184322. #endif
  184323. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  184324. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  184325. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  184326. int unit_type));
  184327. #endif
  184328. #if defined(PNG_WRITE_tIME_SUPPORTED)
  184329. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  184330. png_timep mod_time));
  184331. #endif
  184332. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  184333. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  184334. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  184335. int unit, double width, double height));
  184336. #else
  184337. #ifdef PNG_FIXED_POINT_SUPPORTED
  184338. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  184339. int unit, png_charp width, png_charp height));
  184340. #endif
  184341. #endif
  184342. #endif
  184343. /* Called when finished processing a row of data */
  184344. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  184345. /* Internal use only. Called before first row of data */
  184346. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  184347. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184348. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  184349. #endif
  184350. /* combine a row of data, dealing with alpha, etc. if requested */
  184351. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  184352. int mask));
  184353. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  184354. /* expand an interlaced row */
  184355. /* OLD pre-1.0.9 interface:
  184356. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  184357. png_bytep row, int pass, png_uint_32 transformations));
  184358. */
  184359. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  184360. #endif
  184361. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  184362. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  184363. /* grab pixels out of a row for an interlaced pass */
  184364. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  184365. png_bytep row, int pass));
  184366. #endif
  184367. /* unfilter a row */
  184368. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  184369. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  184370. /* Choose the best filter to use and filter the row data */
  184371. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  184372. png_row_infop row_info));
  184373. /* Write out the filtered row. */
  184374. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  184375. png_bytep filtered_row));
  184376. /* finish a row while reading, dealing with interlacing passes, etc. */
  184377. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  184378. /* initialize the row buffers, etc. */
  184379. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  184380. /* optional call to update the users info structure */
  184381. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  184382. png_infop info_ptr));
  184383. /* these are the functions that do the transformations */
  184384. #if defined(PNG_READ_FILLER_SUPPORTED)
  184385. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  184386. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  184387. #endif
  184388. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  184389. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  184390. png_bytep row));
  184391. #endif
  184392. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  184393. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  184394. png_bytep row));
  184395. #endif
  184396. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  184397. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  184398. png_bytep row));
  184399. #endif
  184400. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  184401. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  184402. png_bytep row));
  184403. #endif
  184404. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  184405. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  184406. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  184407. png_bytep row, png_uint_32 flags));
  184408. #endif
  184409. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  184410. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  184411. #endif
  184412. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  184413. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  184414. #endif
  184415. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  184416. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  184417. row_info, png_bytep row));
  184418. #endif
  184419. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  184420. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  184421. png_bytep row));
  184422. #endif
  184423. #if defined(PNG_READ_PACK_SUPPORTED)
  184424. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  184425. #endif
  184426. #if defined(PNG_READ_SHIFT_SUPPORTED)
  184427. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  184428. png_color_8p sig_bits));
  184429. #endif
  184430. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  184431. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  184432. #endif
  184433. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  184434. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  184435. #endif
  184436. #if defined(PNG_READ_DITHER_SUPPORTED)
  184437. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  184438. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  184439. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  184440. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  184441. png_colorp palette, int num_palette));
  184442. # endif
  184443. #endif
  184444. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  184445. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  184446. #endif
  184447. #if defined(PNG_WRITE_PACK_SUPPORTED)
  184448. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  184449. png_bytep row, png_uint_32 bit_depth));
  184450. #endif
  184451. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  184452. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  184453. png_color_8p bit_depth));
  184454. #endif
  184455. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184456. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184457. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184458. png_color_16p trans_values, png_color_16p background,
  184459. png_color_16p background_1,
  184460. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  184461. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  184462. png_uint_16pp gamma_16_to_1, int gamma_shift));
  184463. #else
  184464. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184465. png_color_16p trans_values, png_color_16p background));
  184466. #endif
  184467. #endif
  184468. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184469. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  184470. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  184471. int gamma_shift));
  184472. #endif
  184473. #if defined(PNG_READ_EXPAND_SUPPORTED)
  184474. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  184475. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  184476. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  184477. png_bytep row, png_color_16p trans_value));
  184478. #endif
  184479. /* The following decodes the appropriate chunks, and does error correction,
  184480. * then calls the appropriate callback for the chunk if it is valid.
  184481. */
  184482. /* decode the IHDR chunk */
  184483. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  184484. png_uint_32 length));
  184485. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  184486. png_uint_32 length));
  184487. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  184488. png_uint_32 length));
  184489. #if defined(PNG_READ_bKGD_SUPPORTED)
  184490. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  184491. png_uint_32 length));
  184492. #endif
  184493. #if defined(PNG_READ_cHRM_SUPPORTED)
  184494. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  184495. png_uint_32 length));
  184496. #endif
  184497. #if defined(PNG_READ_gAMA_SUPPORTED)
  184498. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  184499. png_uint_32 length));
  184500. #endif
  184501. #if defined(PNG_READ_hIST_SUPPORTED)
  184502. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  184503. png_uint_32 length));
  184504. #endif
  184505. #if defined(PNG_READ_iCCP_SUPPORTED)
  184506. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  184507. png_uint_32 length));
  184508. #endif /* PNG_READ_iCCP_SUPPORTED */
  184509. #if defined(PNG_READ_iTXt_SUPPORTED)
  184510. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184511. png_uint_32 length));
  184512. #endif
  184513. #if defined(PNG_READ_oFFs_SUPPORTED)
  184514. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184515. png_uint_32 length));
  184516. #endif
  184517. #if defined(PNG_READ_pCAL_SUPPORTED)
  184518. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184519. png_uint_32 length));
  184520. #endif
  184521. #if defined(PNG_READ_pHYs_SUPPORTED)
  184522. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184523. png_uint_32 length));
  184524. #endif
  184525. #if defined(PNG_READ_sBIT_SUPPORTED)
  184526. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184527. png_uint_32 length));
  184528. #endif
  184529. #if defined(PNG_READ_sCAL_SUPPORTED)
  184530. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184531. png_uint_32 length));
  184532. #endif
  184533. #if defined(PNG_READ_sPLT_SUPPORTED)
  184534. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184535. png_uint_32 length));
  184536. #endif /* PNG_READ_sPLT_SUPPORTED */
  184537. #if defined(PNG_READ_sRGB_SUPPORTED)
  184538. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  184539. png_uint_32 length));
  184540. #endif
  184541. #if defined(PNG_READ_tEXt_SUPPORTED)
  184542. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184543. png_uint_32 length));
  184544. #endif
  184545. #if defined(PNG_READ_tIME_SUPPORTED)
  184546. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  184547. png_uint_32 length));
  184548. #endif
  184549. #if defined(PNG_READ_tRNS_SUPPORTED)
  184550. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  184551. png_uint_32 length));
  184552. #endif
  184553. #if defined(PNG_READ_zTXt_SUPPORTED)
  184554. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184555. png_uint_32 length));
  184556. #endif
  184557. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  184558. png_infop info_ptr, png_uint_32 length));
  184559. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  184560. png_bytep chunk_name));
  184561. /* handle the transformations for reading and writing */
  184562. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  184563. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  184564. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  184565. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184566. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  184567. png_infop info_ptr));
  184568. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  184569. png_infop info_ptr));
  184570. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  184571. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  184572. png_uint_32 length));
  184573. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  184574. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  184575. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  184576. png_bytep buffer, png_size_t buffer_length));
  184577. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  184578. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  184579. png_bytep buffer, png_size_t buffer_length));
  184580. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  184581. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  184582. png_infop info_ptr, png_uint_32 length));
  184583. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  184584. png_infop info_ptr));
  184585. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  184586. png_infop info_ptr));
  184587. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  184588. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  184589. png_infop info_ptr));
  184590. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  184591. png_infop info_ptr));
  184592. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  184593. #if defined(PNG_READ_tEXt_SUPPORTED)
  184594. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  184595. png_infop info_ptr, png_uint_32 length));
  184596. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  184597. png_infop info_ptr));
  184598. #endif
  184599. #if defined(PNG_READ_zTXt_SUPPORTED)
  184600. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  184601. png_infop info_ptr, png_uint_32 length));
  184602. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  184603. png_infop info_ptr));
  184604. #endif
  184605. #if defined(PNG_READ_iTXt_SUPPORTED)
  184606. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  184607. png_infop info_ptr, png_uint_32 length));
  184608. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  184609. png_infop info_ptr));
  184610. #endif
  184611. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  184612. #ifdef PNG_MNG_FEATURES_SUPPORTED
  184613. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  184614. png_bytep row));
  184615. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  184616. png_bytep row));
  184617. #endif
  184618. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184619. #if defined(PNG_MMX_CODE_SUPPORTED)
  184620. /* png.c */ /* PRIVATE */
  184621. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  184622. #endif
  184623. #endif
  184624. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  184625. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  184626. png_infop info_ptr));
  184627. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  184628. png_infop info_ptr));
  184629. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  184630. png_infop info_ptr));
  184631. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  184632. png_infop info_ptr));
  184633. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  184634. png_infop info_ptr));
  184635. #if defined(PNG_pHYs_SUPPORTED)
  184636. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  184637. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  184638. #endif /* PNG_pHYs_SUPPORTED */
  184639. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  184640. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  184641. #endif /* PNG_INTERNAL */
  184642. #ifdef __cplusplus
  184643. //}
  184644. #endif
  184645. #endif /* PNG_VERSION_INFO_ONLY */
  184646. /* do not put anything past this line */
  184647. #endif /* PNG_H */
  184648. /*** End of inlined file: png.h ***/
  184649. #define PNG_NO_EXTERN
  184650. /*** Start of inlined file: png.c ***/
  184651. /* png.c - location for general purpose libpng functions
  184652. *
  184653. * Last changed in libpng 1.2.21 [October 4, 2007]
  184654. * For conditions of distribution and use, see copyright notice in png.h
  184655. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184656. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184657. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184658. */
  184659. #define PNG_INTERNAL
  184660. #define PNG_NO_EXTERN
  184661. /* Generate a compiler error if there is an old png.h in the search path. */
  184662. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  184663. /* Version information for C files. This had better match the version
  184664. * string defined in png.h. */
  184665. #ifdef PNG_USE_GLOBAL_ARRAYS
  184666. /* png_libpng_ver was changed to a function in version 1.0.5c */
  184667. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  184668. #ifdef PNG_READ_SUPPORTED
  184669. /* png_sig was changed to a function in version 1.0.5c */
  184670. /* Place to hold the signature string for a PNG file. */
  184671. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184672. #endif /* PNG_READ_SUPPORTED */
  184673. /* Invoke global declarations for constant strings for known chunk types */
  184674. PNG_IHDR;
  184675. PNG_IDAT;
  184676. PNG_IEND;
  184677. PNG_PLTE;
  184678. PNG_bKGD;
  184679. PNG_cHRM;
  184680. PNG_gAMA;
  184681. PNG_hIST;
  184682. PNG_iCCP;
  184683. PNG_iTXt;
  184684. PNG_oFFs;
  184685. PNG_pCAL;
  184686. PNG_sCAL;
  184687. PNG_pHYs;
  184688. PNG_sBIT;
  184689. PNG_sPLT;
  184690. PNG_sRGB;
  184691. PNG_tEXt;
  184692. PNG_tIME;
  184693. PNG_tRNS;
  184694. PNG_zTXt;
  184695. #ifdef PNG_READ_SUPPORTED
  184696. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  184697. /* start of interlace block */
  184698. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  184699. /* offset to next interlace block */
  184700. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  184701. /* start of interlace block in the y direction */
  184702. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  184703. /* offset to next interlace block in the y direction */
  184704. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  184705. /* Height of interlace block. This is not currently used - if you need
  184706. * it, uncomment it here and in png.h
  184707. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  184708. */
  184709. /* Mask to determine which pixels are valid in a pass */
  184710. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  184711. /* Mask to determine which pixels to overwrite while displaying */
  184712. PNG_CONST int FARDATA png_pass_dsp_mask[]
  184713. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  184714. #endif /* PNG_READ_SUPPORTED */
  184715. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184716. /* Tells libpng that we have already handled the first "num_bytes" bytes
  184717. * of the PNG file signature. If the PNG data is embedded into another
  184718. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  184719. * or write any of the magic bytes before it starts on the IHDR.
  184720. */
  184721. #ifdef PNG_READ_SUPPORTED
  184722. void PNGAPI
  184723. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  184724. {
  184725. if(png_ptr == NULL) return;
  184726. png_debug(1, "in png_set_sig_bytes\n");
  184727. if (num_bytes > 8)
  184728. png_error(png_ptr, "Too many bytes for PNG signature.");
  184729. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  184730. }
  184731. /* Checks whether the supplied bytes match the PNG signature. We allow
  184732. * checking less than the full 8-byte signature so that those apps that
  184733. * already read the first few bytes of a file to determine the file type
  184734. * can simply check the remaining bytes for extra assurance. Returns
  184735. * an integer less than, equal to, or greater than zero if sig is found,
  184736. * respectively, to be less than, to match, or be greater than the correct
  184737. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  184738. */
  184739. int PNGAPI
  184740. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  184741. {
  184742. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184743. if (num_to_check > 8)
  184744. num_to_check = 8;
  184745. else if (num_to_check < 1)
  184746. return (-1);
  184747. if (start > 7)
  184748. return (-1);
  184749. if (start + num_to_check > 8)
  184750. num_to_check = 8 - start;
  184751. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  184752. }
  184753. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184754. /* (Obsolete) function to check signature bytes. It does not allow one
  184755. * to check a partial signature. This function might be removed in the
  184756. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  184757. */
  184758. int PNGAPI
  184759. png_check_sig(png_bytep sig, int num)
  184760. {
  184761. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  184762. }
  184763. #endif
  184764. #endif /* PNG_READ_SUPPORTED */
  184765. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184766. /* Function to allocate memory for zlib and clear it to 0. */
  184767. #ifdef PNG_1_0_X
  184768. voidpf PNGAPI
  184769. #else
  184770. voidpf /* private */
  184771. #endif
  184772. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  184773. {
  184774. png_voidp ptr;
  184775. png_structp p=(png_structp)png_ptr;
  184776. png_uint_32 save_flags=p->flags;
  184777. png_uint_32 num_bytes;
  184778. if(png_ptr == NULL) return (NULL);
  184779. if (items > PNG_UINT_32_MAX/size)
  184780. {
  184781. png_warning (p, "Potential overflow in png_zalloc()");
  184782. return (NULL);
  184783. }
  184784. num_bytes = (png_uint_32)items * size;
  184785. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  184786. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  184787. p->flags=save_flags;
  184788. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  184789. if (ptr == NULL)
  184790. return ((voidpf)ptr);
  184791. if (num_bytes > (png_uint_32)0x8000L)
  184792. {
  184793. png_memset(ptr, 0, (png_size_t)0x8000L);
  184794. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  184795. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  184796. }
  184797. else
  184798. {
  184799. png_memset(ptr, 0, (png_size_t)num_bytes);
  184800. }
  184801. #endif
  184802. return ((voidpf)ptr);
  184803. }
  184804. /* function to free memory for zlib */
  184805. #ifdef PNG_1_0_X
  184806. void PNGAPI
  184807. #else
  184808. void /* private */
  184809. #endif
  184810. png_zfree(voidpf png_ptr, voidpf ptr)
  184811. {
  184812. png_free((png_structp)png_ptr, (png_voidp)ptr);
  184813. }
  184814. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  184815. * in case CRC is > 32 bits to leave the top bits 0.
  184816. */
  184817. void /* PRIVATE */
  184818. png_reset_crc(png_structp png_ptr)
  184819. {
  184820. png_ptr->crc = crc32(0, Z_NULL, 0);
  184821. }
  184822. /* Calculate the CRC over a section of data. We can only pass as
  184823. * much data to this routine as the largest single buffer size. We
  184824. * also check that this data will actually be used before going to the
  184825. * trouble of calculating it.
  184826. */
  184827. void /* PRIVATE */
  184828. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  184829. {
  184830. int need_crc = 1;
  184831. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  184832. {
  184833. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  184834. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  184835. need_crc = 0;
  184836. }
  184837. else /* critical */
  184838. {
  184839. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  184840. need_crc = 0;
  184841. }
  184842. if (need_crc)
  184843. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  184844. }
  184845. /* Allocate the memory for an info_struct for the application. We don't
  184846. * really need the png_ptr, but it could potentially be useful in the
  184847. * future. This should be used in favour of malloc(png_sizeof(png_info))
  184848. * and png_info_init() so that applications that want to use a shared
  184849. * libpng don't have to be recompiled if png_info changes size.
  184850. */
  184851. png_infop PNGAPI
  184852. png_create_info_struct(png_structp png_ptr)
  184853. {
  184854. png_infop info_ptr;
  184855. png_debug(1, "in png_create_info_struct\n");
  184856. if(png_ptr == NULL) return (NULL);
  184857. #ifdef PNG_USER_MEM_SUPPORTED
  184858. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  184859. png_ptr->malloc_fn, png_ptr->mem_ptr);
  184860. #else
  184861. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  184862. #endif
  184863. if (info_ptr != NULL)
  184864. png_info_init_3(&info_ptr, png_sizeof(png_info));
  184865. return (info_ptr);
  184866. }
  184867. /* This function frees the memory associated with a single info struct.
  184868. * Normally, one would use either png_destroy_read_struct() or
  184869. * png_destroy_write_struct() to free an info struct, but this may be
  184870. * useful for some applications.
  184871. */
  184872. void PNGAPI
  184873. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  184874. {
  184875. png_infop info_ptr = NULL;
  184876. if(png_ptr == NULL) return;
  184877. png_debug(1, "in png_destroy_info_struct\n");
  184878. if (info_ptr_ptr != NULL)
  184879. info_ptr = *info_ptr_ptr;
  184880. if (info_ptr != NULL)
  184881. {
  184882. png_info_destroy(png_ptr, info_ptr);
  184883. #ifdef PNG_USER_MEM_SUPPORTED
  184884. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  184885. png_ptr->mem_ptr);
  184886. #else
  184887. png_destroy_struct((png_voidp)info_ptr);
  184888. #endif
  184889. *info_ptr_ptr = NULL;
  184890. }
  184891. }
  184892. /* Initialize the info structure. This is now an internal function (0.89)
  184893. * and applications using it are urged to use png_create_info_struct()
  184894. * instead.
  184895. */
  184896. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184897. #undef png_info_init
  184898. void PNGAPI
  184899. png_info_init(png_infop info_ptr)
  184900. {
  184901. /* We only come here via pre-1.0.12-compiled applications */
  184902. png_info_init_3(&info_ptr, 0);
  184903. }
  184904. #endif
  184905. void PNGAPI
  184906. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  184907. {
  184908. png_infop info_ptr = *ptr_ptr;
  184909. if(info_ptr == NULL) return;
  184910. png_debug(1, "in png_info_init_3\n");
  184911. if(png_sizeof(png_info) > png_info_struct_size)
  184912. {
  184913. png_destroy_struct(info_ptr);
  184914. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  184915. *ptr_ptr = info_ptr;
  184916. }
  184917. /* set everything to 0 */
  184918. png_memset(info_ptr, 0, png_sizeof (png_info));
  184919. }
  184920. #ifdef PNG_FREE_ME_SUPPORTED
  184921. void PNGAPI
  184922. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  184923. int freer, png_uint_32 mask)
  184924. {
  184925. png_debug(1, "in png_data_freer\n");
  184926. if (png_ptr == NULL || info_ptr == NULL)
  184927. return;
  184928. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  184929. info_ptr->free_me |= mask;
  184930. else if(freer == PNG_USER_WILL_FREE_DATA)
  184931. info_ptr->free_me &= ~mask;
  184932. else
  184933. png_warning(png_ptr,
  184934. "Unknown freer parameter in png_data_freer.");
  184935. }
  184936. #endif
  184937. void PNGAPI
  184938. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  184939. int num)
  184940. {
  184941. png_debug(1, "in png_free_data\n");
  184942. if (png_ptr == NULL || info_ptr == NULL)
  184943. return;
  184944. #if defined(PNG_TEXT_SUPPORTED)
  184945. /* free text item num or (if num == -1) all text items */
  184946. #ifdef PNG_FREE_ME_SUPPORTED
  184947. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  184948. #else
  184949. if (mask & PNG_FREE_TEXT)
  184950. #endif
  184951. {
  184952. if (num != -1)
  184953. {
  184954. if (info_ptr->text && info_ptr->text[num].key)
  184955. {
  184956. png_free(png_ptr, info_ptr->text[num].key);
  184957. info_ptr->text[num].key = NULL;
  184958. }
  184959. }
  184960. else
  184961. {
  184962. int i;
  184963. for (i = 0; i < info_ptr->num_text; i++)
  184964. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  184965. png_free(png_ptr, info_ptr->text);
  184966. info_ptr->text = NULL;
  184967. info_ptr->num_text=0;
  184968. }
  184969. }
  184970. #endif
  184971. #if defined(PNG_tRNS_SUPPORTED)
  184972. /* free any tRNS entry */
  184973. #ifdef PNG_FREE_ME_SUPPORTED
  184974. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  184975. #else
  184976. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  184977. #endif
  184978. {
  184979. png_free(png_ptr, info_ptr->trans);
  184980. info_ptr->valid &= ~PNG_INFO_tRNS;
  184981. #ifndef PNG_FREE_ME_SUPPORTED
  184982. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  184983. #endif
  184984. info_ptr->trans = NULL;
  184985. }
  184986. #endif
  184987. #if defined(PNG_sCAL_SUPPORTED)
  184988. /* free any sCAL entry */
  184989. #ifdef PNG_FREE_ME_SUPPORTED
  184990. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  184991. #else
  184992. if (mask & PNG_FREE_SCAL)
  184993. #endif
  184994. {
  184995. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  184996. png_free(png_ptr, info_ptr->scal_s_width);
  184997. png_free(png_ptr, info_ptr->scal_s_height);
  184998. info_ptr->scal_s_width = NULL;
  184999. info_ptr->scal_s_height = NULL;
  185000. #endif
  185001. info_ptr->valid &= ~PNG_INFO_sCAL;
  185002. }
  185003. #endif
  185004. #if defined(PNG_pCAL_SUPPORTED)
  185005. /* free any pCAL entry */
  185006. #ifdef PNG_FREE_ME_SUPPORTED
  185007. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  185008. #else
  185009. if (mask & PNG_FREE_PCAL)
  185010. #endif
  185011. {
  185012. png_free(png_ptr, info_ptr->pcal_purpose);
  185013. png_free(png_ptr, info_ptr->pcal_units);
  185014. info_ptr->pcal_purpose = NULL;
  185015. info_ptr->pcal_units = NULL;
  185016. if (info_ptr->pcal_params != NULL)
  185017. {
  185018. int i;
  185019. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  185020. {
  185021. png_free(png_ptr, info_ptr->pcal_params[i]);
  185022. info_ptr->pcal_params[i]=NULL;
  185023. }
  185024. png_free(png_ptr, info_ptr->pcal_params);
  185025. info_ptr->pcal_params = NULL;
  185026. }
  185027. info_ptr->valid &= ~PNG_INFO_pCAL;
  185028. }
  185029. #endif
  185030. #if defined(PNG_iCCP_SUPPORTED)
  185031. /* free any iCCP entry */
  185032. #ifdef PNG_FREE_ME_SUPPORTED
  185033. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  185034. #else
  185035. if (mask & PNG_FREE_ICCP)
  185036. #endif
  185037. {
  185038. png_free(png_ptr, info_ptr->iccp_name);
  185039. png_free(png_ptr, info_ptr->iccp_profile);
  185040. info_ptr->iccp_name = NULL;
  185041. info_ptr->iccp_profile = NULL;
  185042. info_ptr->valid &= ~PNG_INFO_iCCP;
  185043. }
  185044. #endif
  185045. #if defined(PNG_sPLT_SUPPORTED)
  185046. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  185047. #ifdef PNG_FREE_ME_SUPPORTED
  185048. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  185049. #else
  185050. if (mask & PNG_FREE_SPLT)
  185051. #endif
  185052. {
  185053. if (num != -1)
  185054. {
  185055. if(info_ptr->splt_palettes)
  185056. {
  185057. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  185058. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  185059. info_ptr->splt_palettes[num].name = NULL;
  185060. info_ptr->splt_palettes[num].entries = NULL;
  185061. }
  185062. }
  185063. else
  185064. {
  185065. if(info_ptr->splt_palettes_num)
  185066. {
  185067. int i;
  185068. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  185069. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  185070. png_free(png_ptr, info_ptr->splt_palettes);
  185071. info_ptr->splt_palettes = NULL;
  185072. info_ptr->splt_palettes_num = 0;
  185073. }
  185074. info_ptr->valid &= ~PNG_INFO_sPLT;
  185075. }
  185076. }
  185077. #endif
  185078. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185079. if(png_ptr->unknown_chunk.data)
  185080. {
  185081. png_free(png_ptr, png_ptr->unknown_chunk.data);
  185082. png_ptr->unknown_chunk.data = NULL;
  185083. }
  185084. #ifdef PNG_FREE_ME_SUPPORTED
  185085. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  185086. #else
  185087. if (mask & PNG_FREE_UNKN)
  185088. #endif
  185089. {
  185090. if (num != -1)
  185091. {
  185092. if(info_ptr->unknown_chunks)
  185093. {
  185094. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  185095. info_ptr->unknown_chunks[num].data = NULL;
  185096. }
  185097. }
  185098. else
  185099. {
  185100. int i;
  185101. if(info_ptr->unknown_chunks_num)
  185102. {
  185103. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  185104. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  185105. png_free(png_ptr, info_ptr->unknown_chunks);
  185106. info_ptr->unknown_chunks = NULL;
  185107. info_ptr->unknown_chunks_num = 0;
  185108. }
  185109. }
  185110. }
  185111. #endif
  185112. #if defined(PNG_hIST_SUPPORTED)
  185113. /* free any hIST entry */
  185114. #ifdef PNG_FREE_ME_SUPPORTED
  185115. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  185116. #else
  185117. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  185118. #endif
  185119. {
  185120. png_free(png_ptr, info_ptr->hist);
  185121. info_ptr->hist = NULL;
  185122. info_ptr->valid &= ~PNG_INFO_hIST;
  185123. #ifndef PNG_FREE_ME_SUPPORTED
  185124. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  185125. #endif
  185126. }
  185127. #endif
  185128. /* free any PLTE entry that was internally allocated */
  185129. #ifdef PNG_FREE_ME_SUPPORTED
  185130. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  185131. #else
  185132. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  185133. #endif
  185134. {
  185135. png_zfree(png_ptr, info_ptr->palette);
  185136. info_ptr->palette = NULL;
  185137. info_ptr->valid &= ~PNG_INFO_PLTE;
  185138. #ifndef PNG_FREE_ME_SUPPORTED
  185139. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  185140. #endif
  185141. info_ptr->num_palette = 0;
  185142. }
  185143. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185144. /* free any image bits attached to the info structure */
  185145. #ifdef PNG_FREE_ME_SUPPORTED
  185146. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  185147. #else
  185148. if (mask & PNG_FREE_ROWS)
  185149. #endif
  185150. {
  185151. if(info_ptr->row_pointers)
  185152. {
  185153. int row;
  185154. for (row = 0; row < (int)info_ptr->height; row++)
  185155. {
  185156. png_free(png_ptr, info_ptr->row_pointers[row]);
  185157. info_ptr->row_pointers[row]=NULL;
  185158. }
  185159. png_free(png_ptr, info_ptr->row_pointers);
  185160. info_ptr->row_pointers=NULL;
  185161. }
  185162. info_ptr->valid &= ~PNG_INFO_IDAT;
  185163. }
  185164. #endif
  185165. #ifdef PNG_FREE_ME_SUPPORTED
  185166. if(num == -1)
  185167. info_ptr->free_me &= ~mask;
  185168. else
  185169. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  185170. #endif
  185171. }
  185172. /* This is an internal routine to free any memory that the info struct is
  185173. * pointing to before re-using it or freeing the struct itself. Recall
  185174. * that png_free() checks for NULL pointers for us.
  185175. */
  185176. void /* PRIVATE */
  185177. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  185178. {
  185179. png_debug(1, "in png_info_destroy\n");
  185180. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  185181. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185182. if (png_ptr->num_chunk_list)
  185183. {
  185184. png_free(png_ptr, png_ptr->chunk_list);
  185185. png_ptr->chunk_list=NULL;
  185186. png_ptr->num_chunk_list=0;
  185187. }
  185188. #endif
  185189. png_info_init_3(&info_ptr, png_sizeof(png_info));
  185190. }
  185191. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185192. /* This function returns a pointer to the io_ptr associated with the user
  185193. * functions. The application should free any memory associated with this
  185194. * pointer before png_write_destroy() or png_read_destroy() are called.
  185195. */
  185196. png_voidp PNGAPI
  185197. png_get_io_ptr(png_structp png_ptr)
  185198. {
  185199. if(png_ptr == NULL) return (NULL);
  185200. return (png_ptr->io_ptr);
  185201. }
  185202. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185203. #if !defined(PNG_NO_STDIO)
  185204. /* Initialize the default input/output functions for the PNG file. If you
  185205. * use your own read or write routines, you can call either png_set_read_fn()
  185206. * or png_set_write_fn() instead of png_init_io(). If you have defined
  185207. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  185208. * necessarily available.
  185209. */
  185210. void PNGAPI
  185211. png_init_io(png_structp png_ptr, png_FILE_p fp)
  185212. {
  185213. png_debug(1, "in png_init_io\n");
  185214. if(png_ptr == NULL) return;
  185215. png_ptr->io_ptr = (png_voidp)fp;
  185216. }
  185217. #endif
  185218. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  185219. /* Convert the supplied time into an RFC 1123 string suitable for use in
  185220. * a "Creation Time" or other text-based time string.
  185221. */
  185222. png_charp PNGAPI
  185223. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  185224. {
  185225. static PNG_CONST char short_months[12][4] =
  185226. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  185227. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  185228. if(png_ptr == NULL) return (NULL);
  185229. if (png_ptr->time_buffer == NULL)
  185230. {
  185231. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  185232. png_sizeof(char)));
  185233. }
  185234. #if defined(_WIN32_WCE)
  185235. {
  185236. wchar_t time_buf[29];
  185237. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  185238. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185239. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185240. ptime->second % 61);
  185241. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  185242. NULL, NULL);
  185243. }
  185244. #else
  185245. #ifdef USE_FAR_KEYWORD
  185246. {
  185247. char near_time_buf[29];
  185248. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  185249. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185250. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185251. ptime->second % 61);
  185252. png_memcpy(png_ptr->time_buffer, near_time_buf,
  185253. 29*png_sizeof(char));
  185254. }
  185255. #else
  185256. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  185257. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185258. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185259. ptime->second % 61);
  185260. #endif
  185261. #endif /* _WIN32_WCE */
  185262. return ((png_charp)png_ptr->time_buffer);
  185263. }
  185264. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  185265. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185266. png_charp PNGAPI
  185267. png_get_copyright(png_structp png_ptr)
  185268. {
  185269. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185270. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  185271. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  185272. Copyright (c) 1996-1997 Andreas Dilger\n\
  185273. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  185274. }
  185275. /* The following return the library version as a short string in the
  185276. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  185277. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  185278. * is defined in png.h.
  185279. * Note: now there is no difference between png_get_libpng_ver() and
  185280. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  185281. * it is guaranteed that png.c uses the correct version of png.h.
  185282. */
  185283. png_charp PNGAPI
  185284. png_get_libpng_ver(png_structp png_ptr)
  185285. {
  185286. /* Version of *.c files used when building libpng */
  185287. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185288. return ((png_charp) PNG_LIBPNG_VER_STRING);
  185289. }
  185290. png_charp PNGAPI
  185291. png_get_header_ver(png_structp png_ptr)
  185292. {
  185293. /* Version of *.h files used when building libpng */
  185294. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185295. return ((png_charp) PNG_LIBPNG_VER_STRING);
  185296. }
  185297. png_charp PNGAPI
  185298. png_get_header_version(png_structp png_ptr)
  185299. {
  185300. /* Returns longer string containing both version and date */
  185301. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185302. return ((png_charp) PNG_HEADER_VERSION_STRING
  185303. #ifndef PNG_READ_SUPPORTED
  185304. " (NO READ SUPPORT)"
  185305. #endif
  185306. "\n");
  185307. }
  185308. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185309. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  185310. int PNGAPI
  185311. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  185312. {
  185313. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  185314. int i;
  185315. png_bytep p;
  185316. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  185317. return 0;
  185318. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  185319. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  185320. if (!png_memcmp(chunk_name, p, 4))
  185321. return ((int)*(p+4));
  185322. return 0;
  185323. }
  185324. #endif
  185325. /* This function, added to libpng-1.0.6g, is untested. */
  185326. int PNGAPI
  185327. png_reset_zstream(png_structp png_ptr)
  185328. {
  185329. if (png_ptr == NULL) return Z_STREAM_ERROR;
  185330. return (inflateReset(&png_ptr->zstream));
  185331. }
  185332. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185333. /* This function was added to libpng-1.0.7 */
  185334. png_uint_32 PNGAPI
  185335. png_access_version_number(void)
  185336. {
  185337. /* Version of *.c files used when building libpng */
  185338. return((png_uint_32) PNG_LIBPNG_VER);
  185339. }
  185340. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  185341. #if !defined(PNG_1_0_X)
  185342. /* this function was added to libpng 1.2.0 */
  185343. int PNGAPI
  185344. png_mmx_support(void)
  185345. {
  185346. /* obsolete, to be removed from libpng-1.4.0 */
  185347. return -1;
  185348. }
  185349. #endif /* PNG_1_0_X */
  185350. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  185351. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185352. #ifdef PNG_SIZE_T
  185353. /* Added at libpng version 1.2.6 */
  185354. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  185355. png_size_t PNGAPI
  185356. png_convert_size(size_t size)
  185357. {
  185358. if (size > (png_size_t)-1)
  185359. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  185360. return ((png_size_t)size);
  185361. }
  185362. #endif /* PNG_SIZE_T */
  185363. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185364. /*** End of inlined file: png.c ***/
  185365. /*** Start of inlined file: pngerror.c ***/
  185366. /* pngerror.c - stub functions for i/o and memory allocation
  185367. *
  185368. * Last changed in libpng 1.2.20 October 4, 2007
  185369. * For conditions of distribution and use, see copyright notice in png.h
  185370. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185371. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185372. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185373. *
  185374. * This file provides a location for all error handling. Users who
  185375. * need special error handling are expected to write replacement functions
  185376. * and use png_set_error_fn() to use those functions. See the instructions
  185377. * at each function.
  185378. */
  185379. #define PNG_INTERNAL
  185380. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185381. static void /* PRIVATE */
  185382. png_default_error PNGARG((png_structp png_ptr,
  185383. png_const_charp error_message));
  185384. #ifndef PNG_NO_WARNINGS
  185385. static void /* PRIVATE */
  185386. png_default_warning PNGARG((png_structp png_ptr,
  185387. png_const_charp warning_message));
  185388. #endif /* PNG_NO_WARNINGS */
  185389. /* This function is called whenever there is a fatal error. This function
  185390. * should not be changed. If there is a need to handle errors differently,
  185391. * you should supply a replacement error function and use png_set_error_fn()
  185392. * to replace the error function at run-time.
  185393. */
  185394. #ifndef PNG_NO_ERROR_TEXT
  185395. void PNGAPI
  185396. png_error(png_structp png_ptr, png_const_charp error_message)
  185397. {
  185398. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185399. char msg[16];
  185400. if (png_ptr != NULL)
  185401. {
  185402. if (png_ptr->flags&
  185403. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185404. {
  185405. if (*error_message == '#')
  185406. {
  185407. int offset;
  185408. for (offset=1; offset<15; offset++)
  185409. if (*(error_message+offset) == ' ')
  185410. break;
  185411. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185412. {
  185413. int i;
  185414. for (i=0; i<offset-1; i++)
  185415. msg[i]=error_message[i+1];
  185416. msg[i]='\0';
  185417. error_message=msg;
  185418. }
  185419. else
  185420. error_message+=offset;
  185421. }
  185422. else
  185423. {
  185424. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185425. {
  185426. msg[0]='0';
  185427. msg[1]='\0';
  185428. error_message=msg;
  185429. }
  185430. }
  185431. }
  185432. }
  185433. #endif
  185434. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185435. (*(png_ptr->error_fn))(png_ptr, error_message);
  185436. /* If the custom handler doesn't exist, or if it returns,
  185437. use the default handler, which will not return. */
  185438. png_default_error(png_ptr, error_message);
  185439. }
  185440. #else
  185441. void PNGAPI
  185442. png_err(png_structp png_ptr)
  185443. {
  185444. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185445. (*(png_ptr->error_fn))(png_ptr, '\0');
  185446. /* If the custom handler doesn't exist, or if it returns,
  185447. use the default handler, which will not return. */
  185448. png_default_error(png_ptr, '\0');
  185449. }
  185450. #endif /* PNG_NO_ERROR_TEXT */
  185451. #ifndef PNG_NO_WARNINGS
  185452. /* This function is called whenever there is a non-fatal error. This function
  185453. * should not be changed. If there is a need to handle warnings differently,
  185454. * you should supply a replacement warning function and use
  185455. * png_set_error_fn() to replace the warning function at run-time.
  185456. */
  185457. void PNGAPI
  185458. png_warning(png_structp png_ptr, png_const_charp warning_message)
  185459. {
  185460. int offset = 0;
  185461. if (png_ptr != NULL)
  185462. {
  185463. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185464. if (png_ptr->flags&
  185465. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185466. #endif
  185467. {
  185468. if (*warning_message == '#')
  185469. {
  185470. for (offset=1; offset<15; offset++)
  185471. if (*(warning_message+offset) == ' ')
  185472. break;
  185473. }
  185474. }
  185475. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  185476. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  185477. }
  185478. else
  185479. png_default_warning(png_ptr, warning_message+offset);
  185480. }
  185481. #endif /* PNG_NO_WARNINGS */
  185482. /* These utilities are used internally to build an error message that relates
  185483. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  185484. * this is used to prefix the message. The message is limited in length
  185485. * to 63 bytes, the name characters are output as hex digits wrapped in []
  185486. * if the character is invalid.
  185487. */
  185488. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  185489. /*static PNG_CONST char png_digit[16] = {
  185490. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  185491. 'A', 'B', 'C', 'D', 'E', 'F'
  185492. };*/
  185493. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  185494. static void /* PRIVATE */
  185495. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  185496. error_message)
  185497. {
  185498. int iout = 0, iin = 0;
  185499. while (iin < 4)
  185500. {
  185501. int c = png_ptr->chunk_name[iin++];
  185502. if (isnonalpha(c))
  185503. {
  185504. buffer[iout++] = '[';
  185505. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  185506. buffer[iout++] = png_digit[c & 0x0f];
  185507. buffer[iout++] = ']';
  185508. }
  185509. else
  185510. {
  185511. buffer[iout++] = (png_byte)c;
  185512. }
  185513. }
  185514. if (error_message == NULL)
  185515. buffer[iout] = 0;
  185516. else
  185517. {
  185518. buffer[iout++] = ':';
  185519. buffer[iout++] = ' ';
  185520. png_strncpy(buffer+iout, error_message, 63);
  185521. buffer[iout+63] = 0;
  185522. }
  185523. }
  185524. #ifdef PNG_READ_SUPPORTED
  185525. void PNGAPI
  185526. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  185527. {
  185528. char msg[18+64];
  185529. if (png_ptr == NULL)
  185530. png_error(png_ptr, error_message);
  185531. else
  185532. {
  185533. png_format_buffer(png_ptr, msg, error_message);
  185534. png_error(png_ptr, msg);
  185535. }
  185536. }
  185537. #endif /* PNG_READ_SUPPORTED */
  185538. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  185539. #ifndef PNG_NO_WARNINGS
  185540. void PNGAPI
  185541. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  185542. {
  185543. char msg[18+64];
  185544. if (png_ptr == NULL)
  185545. png_warning(png_ptr, warning_message);
  185546. else
  185547. {
  185548. png_format_buffer(png_ptr, msg, warning_message);
  185549. png_warning(png_ptr, msg);
  185550. }
  185551. }
  185552. #endif /* PNG_NO_WARNINGS */
  185553. /* This is the default error handling function. Note that replacements for
  185554. * this function MUST NOT RETURN, or the program will likely crash. This
  185555. * function is used by default, or if the program supplies NULL for the
  185556. * error function pointer in png_set_error_fn().
  185557. */
  185558. static void /* PRIVATE */
  185559. png_default_error(png_structp, png_const_charp error_message)
  185560. {
  185561. #ifndef PNG_NO_CONSOLE_IO
  185562. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185563. if (*error_message == '#')
  185564. {
  185565. int offset;
  185566. char error_number[16];
  185567. for (offset=0; offset<15; offset++)
  185568. {
  185569. error_number[offset] = *(error_message+offset+1);
  185570. if (*(error_message+offset) == ' ')
  185571. break;
  185572. }
  185573. if((offset > 1) && (offset < 15))
  185574. {
  185575. error_number[offset-1]='\0';
  185576. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  185577. error_message+offset);
  185578. }
  185579. else
  185580. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  185581. }
  185582. else
  185583. #endif
  185584. fprintf(stderr, "libpng error: %s\n", error_message);
  185585. #endif
  185586. #ifdef PNG_SETJMP_SUPPORTED
  185587. if (png_ptr)
  185588. {
  185589. # ifdef USE_FAR_KEYWORD
  185590. {
  185591. jmp_buf jmpbuf;
  185592. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  185593. longjmp(jmpbuf, 1);
  185594. }
  185595. # else
  185596. longjmp(png_ptr->jmpbuf, 1);
  185597. # endif
  185598. }
  185599. #else
  185600. PNG_ABORT();
  185601. #endif
  185602. #ifdef PNG_NO_CONSOLE_IO
  185603. error_message = error_message; /* make compiler happy */
  185604. #endif
  185605. }
  185606. #ifndef PNG_NO_WARNINGS
  185607. /* This function is called when there is a warning, but the library thinks
  185608. * it can continue anyway. Replacement functions don't have to do anything
  185609. * here if you don't want them to. In the default configuration, png_ptr is
  185610. * not used, but it is passed in case it may be useful.
  185611. */
  185612. static void /* PRIVATE */
  185613. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  185614. {
  185615. #ifndef PNG_NO_CONSOLE_IO
  185616. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185617. if (*warning_message == '#')
  185618. {
  185619. int offset;
  185620. char warning_number[16];
  185621. for (offset=0; offset<15; offset++)
  185622. {
  185623. warning_number[offset]=*(warning_message+offset+1);
  185624. if (*(warning_message+offset) == ' ')
  185625. break;
  185626. }
  185627. if((offset > 1) && (offset < 15))
  185628. {
  185629. warning_number[offset-1]='\0';
  185630. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  185631. warning_message+offset);
  185632. }
  185633. else
  185634. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185635. }
  185636. else
  185637. # endif
  185638. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185639. #else
  185640. warning_message = warning_message; /* make compiler happy */
  185641. #endif
  185642. png_ptr = png_ptr; /* make compiler happy */
  185643. }
  185644. #endif /* PNG_NO_WARNINGS */
  185645. /* This function is called when the application wants to use another method
  185646. * of handling errors and warnings. Note that the error function MUST NOT
  185647. * return to the calling routine or serious problems will occur. The return
  185648. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  185649. */
  185650. void PNGAPI
  185651. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  185652. png_error_ptr error_fn, png_error_ptr warning_fn)
  185653. {
  185654. if (png_ptr == NULL)
  185655. return;
  185656. png_ptr->error_ptr = error_ptr;
  185657. png_ptr->error_fn = error_fn;
  185658. png_ptr->warning_fn = warning_fn;
  185659. }
  185660. /* This function returns a pointer to the error_ptr associated with the user
  185661. * functions. The application should free any memory associated with this
  185662. * pointer before png_write_destroy and png_read_destroy are called.
  185663. */
  185664. png_voidp PNGAPI
  185665. png_get_error_ptr(png_structp png_ptr)
  185666. {
  185667. if (png_ptr == NULL)
  185668. return NULL;
  185669. return ((png_voidp)png_ptr->error_ptr);
  185670. }
  185671. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185672. void PNGAPI
  185673. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  185674. {
  185675. if(png_ptr != NULL)
  185676. {
  185677. png_ptr->flags &=
  185678. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  185679. }
  185680. }
  185681. #endif
  185682. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  185683. /*** End of inlined file: pngerror.c ***/
  185684. /*** Start of inlined file: pngget.c ***/
  185685. /* pngget.c - retrieval of values from info struct
  185686. *
  185687. * Last changed in libpng 1.2.15 January 5, 2007
  185688. * For conditions of distribution and use, see copyright notice in png.h
  185689. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185690. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185691. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185692. */
  185693. #define PNG_INTERNAL
  185694. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185695. png_uint_32 PNGAPI
  185696. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  185697. {
  185698. if (png_ptr != NULL && info_ptr != NULL)
  185699. return(info_ptr->valid & flag);
  185700. else
  185701. return(0);
  185702. }
  185703. png_uint_32 PNGAPI
  185704. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  185705. {
  185706. if (png_ptr != NULL && info_ptr != NULL)
  185707. return(info_ptr->rowbytes);
  185708. else
  185709. return(0);
  185710. }
  185711. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185712. png_bytepp PNGAPI
  185713. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  185714. {
  185715. if (png_ptr != NULL && info_ptr != NULL)
  185716. return(info_ptr->row_pointers);
  185717. else
  185718. return(0);
  185719. }
  185720. #endif
  185721. #ifdef PNG_EASY_ACCESS_SUPPORTED
  185722. /* easy access to info, added in libpng-0.99 */
  185723. png_uint_32 PNGAPI
  185724. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  185725. {
  185726. if (png_ptr != NULL && info_ptr != NULL)
  185727. {
  185728. return info_ptr->width;
  185729. }
  185730. return (0);
  185731. }
  185732. png_uint_32 PNGAPI
  185733. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  185734. {
  185735. if (png_ptr != NULL && info_ptr != NULL)
  185736. {
  185737. return info_ptr->height;
  185738. }
  185739. return (0);
  185740. }
  185741. png_byte PNGAPI
  185742. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  185743. {
  185744. if (png_ptr != NULL && info_ptr != NULL)
  185745. {
  185746. return info_ptr->bit_depth;
  185747. }
  185748. return (0);
  185749. }
  185750. png_byte PNGAPI
  185751. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  185752. {
  185753. if (png_ptr != NULL && info_ptr != NULL)
  185754. {
  185755. return info_ptr->color_type;
  185756. }
  185757. return (0);
  185758. }
  185759. png_byte PNGAPI
  185760. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  185761. {
  185762. if (png_ptr != NULL && info_ptr != NULL)
  185763. {
  185764. return info_ptr->filter_type;
  185765. }
  185766. return (0);
  185767. }
  185768. png_byte PNGAPI
  185769. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  185770. {
  185771. if (png_ptr != NULL && info_ptr != NULL)
  185772. {
  185773. return info_ptr->interlace_type;
  185774. }
  185775. return (0);
  185776. }
  185777. png_byte PNGAPI
  185778. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  185779. {
  185780. if (png_ptr != NULL && info_ptr != NULL)
  185781. {
  185782. return info_ptr->compression_type;
  185783. }
  185784. return (0);
  185785. }
  185786. png_uint_32 PNGAPI
  185787. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185788. {
  185789. if (png_ptr != NULL && info_ptr != NULL)
  185790. #if defined(PNG_pHYs_SUPPORTED)
  185791. if (info_ptr->valid & PNG_INFO_pHYs)
  185792. {
  185793. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  185794. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185795. return (0);
  185796. else return (info_ptr->x_pixels_per_unit);
  185797. }
  185798. #else
  185799. return (0);
  185800. #endif
  185801. return (0);
  185802. }
  185803. png_uint_32 PNGAPI
  185804. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185805. {
  185806. if (png_ptr != NULL && info_ptr != NULL)
  185807. #if defined(PNG_pHYs_SUPPORTED)
  185808. if (info_ptr->valid & PNG_INFO_pHYs)
  185809. {
  185810. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  185811. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  185812. return (0);
  185813. else return (info_ptr->y_pixels_per_unit);
  185814. }
  185815. #else
  185816. return (0);
  185817. #endif
  185818. return (0);
  185819. }
  185820. png_uint_32 PNGAPI
  185821. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  185822. {
  185823. if (png_ptr != NULL && info_ptr != NULL)
  185824. #if defined(PNG_pHYs_SUPPORTED)
  185825. if (info_ptr->valid & PNG_INFO_pHYs)
  185826. {
  185827. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  185828. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  185829. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  185830. return (0);
  185831. else return (info_ptr->x_pixels_per_unit);
  185832. }
  185833. #else
  185834. return (0);
  185835. #endif
  185836. return (0);
  185837. }
  185838. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185839. float PNGAPI
  185840. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  185841. {
  185842. if (png_ptr != NULL && info_ptr != NULL)
  185843. #if defined(PNG_pHYs_SUPPORTED)
  185844. if (info_ptr->valid & PNG_INFO_pHYs)
  185845. {
  185846. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  185847. if (info_ptr->x_pixels_per_unit == 0)
  185848. return ((float)0.0);
  185849. else
  185850. return ((float)((float)info_ptr->y_pixels_per_unit
  185851. /(float)info_ptr->x_pixels_per_unit));
  185852. }
  185853. #else
  185854. return (0.0);
  185855. #endif
  185856. return ((float)0.0);
  185857. }
  185858. #endif
  185859. png_int_32 PNGAPI
  185860. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  185861. {
  185862. if (png_ptr != NULL && info_ptr != NULL)
  185863. #if defined(PNG_oFFs_SUPPORTED)
  185864. if (info_ptr->valid & PNG_INFO_oFFs)
  185865. {
  185866. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  185867. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  185868. return (0);
  185869. else return (info_ptr->x_offset);
  185870. }
  185871. #else
  185872. return (0);
  185873. #endif
  185874. return (0);
  185875. }
  185876. png_int_32 PNGAPI
  185877. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  185878. {
  185879. if (png_ptr != NULL && info_ptr != NULL)
  185880. #if defined(PNG_oFFs_SUPPORTED)
  185881. if (info_ptr->valid & PNG_INFO_oFFs)
  185882. {
  185883. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  185884. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  185885. return (0);
  185886. else return (info_ptr->y_offset);
  185887. }
  185888. #else
  185889. return (0);
  185890. #endif
  185891. return (0);
  185892. }
  185893. png_int_32 PNGAPI
  185894. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  185895. {
  185896. if (png_ptr != NULL && info_ptr != NULL)
  185897. #if defined(PNG_oFFs_SUPPORTED)
  185898. if (info_ptr->valid & PNG_INFO_oFFs)
  185899. {
  185900. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  185901. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185902. return (0);
  185903. else return (info_ptr->x_offset);
  185904. }
  185905. #else
  185906. return (0);
  185907. #endif
  185908. return (0);
  185909. }
  185910. png_int_32 PNGAPI
  185911. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  185912. {
  185913. if (png_ptr != NULL && info_ptr != NULL)
  185914. #if defined(PNG_oFFs_SUPPORTED)
  185915. if (info_ptr->valid & PNG_INFO_oFFs)
  185916. {
  185917. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  185918. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  185919. return (0);
  185920. else return (info_ptr->y_offset);
  185921. }
  185922. #else
  185923. return (0);
  185924. #endif
  185925. return (0);
  185926. }
  185927. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  185928. png_uint_32 PNGAPI
  185929. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185930. {
  185931. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  185932. *.0254 +.5));
  185933. }
  185934. png_uint_32 PNGAPI
  185935. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185936. {
  185937. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  185938. *.0254 +.5));
  185939. }
  185940. png_uint_32 PNGAPI
  185941. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  185942. {
  185943. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  185944. *.0254 +.5));
  185945. }
  185946. float PNGAPI
  185947. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  185948. {
  185949. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  185950. *.00003937);
  185951. }
  185952. float PNGAPI
  185953. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  185954. {
  185955. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  185956. *.00003937);
  185957. }
  185958. #if defined(PNG_pHYs_SUPPORTED)
  185959. png_uint_32 PNGAPI
  185960. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  185961. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  185962. {
  185963. png_uint_32 retval = 0;
  185964. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  185965. {
  185966. png_debug1(1, "in %s retrieval function\n", "pHYs");
  185967. if (res_x != NULL)
  185968. {
  185969. *res_x = info_ptr->x_pixels_per_unit;
  185970. retval |= PNG_INFO_pHYs;
  185971. }
  185972. if (res_y != NULL)
  185973. {
  185974. *res_y = info_ptr->y_pixels_per_unit;
  185975. retval |= PNG_INFO_pHYs;
  185976. }
  185977. if (unit_type != NULL)
  185978. {
  185979. *unit_type = (int)info_ptr->phys_unit_type;
  185980. retval |= PNG_INFO_pHYs;
  185981. if(*unit_type == 1)
  185982. {
  185983. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  185984. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  185985. }
  185986. }
  185987. }
  185988. return (retval);
  185989. }
  185990. #endif /* PNG_pHYs_SUPPORTED */
  185991. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  185992. /* png_get_channels really belongs in here, too, but it's been around longer */
  185993. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  185994. png_byte PNGAPI
  185995. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  185996. {
  185997. if (png_ptr != NULL && info_ptr != NULL)
  185998. return(info_ptr->channels);
  185999. else
  186000. return (0);
  186001. }
  186002. png_bytep PNGAPI
  186003. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  186004. {
  186005. if (png_ptr != NULL && info_ptr != NULL)
  186006. return(info_ptr->signature);
  186007. else
  186008. return (NULL);
  186009. }
  186010. #if defined(PNG_bKGD_SUPPORTED)
  186011. png_uint_32 PNGAPI
  186012. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  186013. png_color_16p *background)
  186014. {
  186015. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  186016. && background != NULL)
  186017. {
  186018. png_debug1(1, "in %s retrieval function\n", "bKGD");
  186019. *background = &(info_ptr->background);
  186020. return (PNG_INFO_bKGD);
  186021. }
  186022. return (0);
  186023. }
  186024. #endif
  186025. #if defined(PNG_cHRM_SUPPORTED)
  186026. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186027. png_uint_32 PNGAPI
  186028. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  186029. double *white_x, double *white_y, double *red_x, double *red_y,
  186030. double *green_x, double *green_y, double *blue_x, double *blue_y)
  186031. {
  186032. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  186033. {
  186034. png_debug1(1, "in %s retrieval function\n", "cHRM");
  186035. if (white_x != NULL)
  186036. *white_x = (double)info_ptr->x_white;
  186037. if (white_y != NULL)
  186038. *white_y = (double)info_ptr->y_white;
  186039. if (red_x != NULL)
  186040. *red_x = (double)info_ptr->x_red;
  186041. if (red_y != NULL)
  186042. *red_y = (double)info_ptr->y_red;
  186043. if (green_x != NULL)
  186044. *green_x = (double)info_ptr->x_green;
  186045. if (green_y != NULL)
  186046. *green_y = (double)info_ptr->y_green;
  186047. if (blue_x != NULL)
  186048. *blue_x = (double)info_ptr->x_blue;
  186049. if (blue_y != NULL)
  186050. *blue_y = (double)info_ptr->y_blue;
  186051. return (PNG_INFO_cHRM);
  186052. }
  186053. return (0);
  186054. }
  186055. #endif
  186056. #ifdef PNG_FIXED_POINT_SUPPORTED
  186057. png_uint_32 PNGAPI
  186058. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  186059. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  186060. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  186061. png_fixed_point *blue_x, png_fixed_point *blue_y)
  186062. {
  186063. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  186064. {
  186065. png_debug1(1, "in %s retrieval function\n", "cHRM");
  186066. if (white_x != NULL)
  186067. *white_x = info_ptr->int_x_white;
  186068. if (white_y != NULL)
  186069. *white_y = info_ptr->int_y_white;
  186070. if (red_x != NULL)
  186071. *red_x = info_ptr->int_x_red;
  186072. if (red_y != NULL)
  186073. *red_y = info_ptr->int_y_red;
  186074. if (green_x != NULL)
  186075. *green_x = info_ptr->int_x_green;
  186076. if (green_y != NULL)
  186077. *green_y = info_ptr->int_y_green;
  186078. if (blue_x != NULL)
  186079. *blue_x = info_ptr->int_x_blue;
  186080. if (blue_y != NULL)
  186081. *blue_y = info_ptr->int_y_blue;
  186082. return (PNG_INFO_cHRM);
  186083. }
  186084. return (0);
  186085. }
  186086. #endif
  186087. #endif
  186088. #if defined(PNG_gAMA_SUPPORTED)
  186089. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186090. png_uint_32 PNGAPI
  186091. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  186092. {
  186093. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  186094. && file_gamma != NULL)
  186095. {
  186096. png_debug1(1, "in %s retrieval function\n", "gAMA");
  186097. *file_gamma = (double)info_ptr->gamma;
  186098. return (PNG_INFO_gAMA);
  186099. }
  186100. return (0);
  186101. }
  186102. #endif
  186103. #ifdef PNG_FIXED_POINT_SUPPORTED
  186104. png_uint_32 PNGAPI
  186105. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  186106. png_fixed_point *int_file_gamma)
  186107. {
  186108. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  186109. && int_file_gamma != NULL)
  186110. {
  186111. png_debug1(1, "in %s retrieval function\n", "gAMA");
  186112. *int_file_gamma = info_ptr->int_gamma;
  186113. return (PNG_INFO_gAMA);
  186114. }
  186115. return (0);
  186116. }
  186117. #endif
  186118. #endif
  186119. #if defined(PNG_sRGB_SUPPORTED)
  186120. png_uint_32 PNGAPI
  186121. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  186122. {
  186123. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  186124. && file_srgb_intent != NULL)
  186125. {
  186126. png_debug1(1, "in %s retrieval function\n", "sRGB");
  186127. *file_srgb_intent = (int)info_ptr->srgb_intent;
  186128. return (PNG_INFO_sRGB);
  186129. }
  186130. return (0);
  186131. }
  186132. #endif
  186133. #if defined(PNG_iCCP_SUPPORTED)
  186134. png_uint_32 PNGAPI
  186135. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  186136. png_charpp name, int *compression_type,
  186137. png_charpp profile, png_uint_32 *proflen)
  186138. {
  186139. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  186140. && name != NULL && profile != NULL && proflen != NULL)
  186141. {
  186142. png_debug1(1, "in %s retrieval function\n", "iCCP");
  186143. *name = info_ptr->iccp_name;
  186144. *profile = info_ptr->iccp_profile;
  186145. /* compression_type is a dummy so the API won't have to change
  186146. if we introduce multiple compression types later. */
  186147. *proflen = (int)info_ptr->iccp_proflen;
  186148. *compression_type = (int)info_ptr->iccp_compression;
  186149. return (PNG_INFO_iCCP);
  186150. }
  186151. return (0);
  186152. }
  186153. #endif
  186154. #if defined(PNG_sPLT_SUPPORTED)
  186155. png_uint_32 PNGAPI
  186156. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  186157. png_sPLT_tpp spalettes)
  186158. {
  186159. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  186160. {
  186161. *spalettes = info_ptr->splt_palettes;
  186162. return ((png_uint_32)info_ptr->splt_palettes_num);
  186163. }
  186164. return (0);
  186165. }
  186166. #endif
  186167. #if defined(PNG_hIST_SUPPORTED)
  186168. png_uint_32 PNGAPI
  186169. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  186170. {
  186171. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  186172. && hist != NULL)
  186173. {
  186174. png_debug1(1, "in %s retrieval function\n", "hIST");
  186175. *hist = info_ptr->hist;
  186176. return (PNG_INFO_hIST);
  186177. }
  186178. return (0);
  186179. }
  186180. #endif
  186181. png_uint_32 PNGAPI
  186182. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  186183. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  186184. int *color_type, int *interlace_type, int *compression_type,
  186185. int *filter_type)
  186186. {
  186187. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  186188. bit_depth != NULL && color_type != NULL)
  186189. {
  186190. png_debug1(1, "in %s retrieval function\n", "IHDR");
  186191. *width = info_ptr->width;
  186192. *height = info_ptr->height;
  186193. *bit_depth = info_ptr->bit_depth;
  186194. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  186195. png_error(png_ptr, "Invalid bit depth");
  186196. *color_type = info_ptr->color_type;
  186197. if (info_ptr->color_type > 6)
  186198. png_error(png_ptr, "Invalid color type");
  186199. if (compression_type != NULL)
  186200. *compression_type = info_ptr->compression_type;
  186201. if (filter_type != NULL)
  186202. *filter_type = info_ptr->filter_type;
  186203. if (interlace_type != NULL)
  186204. *interlace_type = info_ptr->interlace_type;
  186205. /* check for potential overflow of rowbytes */
  186206. if (*width == 0 || *width > PNG_UINT_31_MAX)
  186207. png_error(png_ptr, "Invalid image width");
  186208. if (*height == 0 || *height > PNG_UINT_31_MAX)
  186209. png_error(png_ptr, "Invalid image height");
  186210. if (info_ptr->width > (PNG_UINT_32_MAX
  186211. >> 3) /* 8-byte RGBA pixels */
  186212. - 64 /* bigrowbuf hack */
  186213. - 1 /* filter byte */
  186214. - 7*8 /* rounding of width to multiple of 8 pixels */
  186215. - 8) /* extra max_pixel_depth pad */
  186216. {
  186217. png_warning(png_ptr,
  186218. "Width too large for libpng to process image data.");
  186219. }
  186220. return (1);
  186221. }
  186222. return (0);
  186223. }
  186224. #if defined(PNG_oFFs_SUPPORTED)
  186225. png_uint_32 PNGAPI
  186226. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  186227. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  186228. {
  186229. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  186230. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  186231. {
  186232. png_debug1(1, "in %s retrieval function\n", "oFFs");
  186233. *offset_x = info_ptr->x_offset;
  186234. *offset_y = info_ptr->y_offset;
  186235. *unit_type = (int)info_ptr->offset_unit_type;
  186236. return (PNG_INFO_oFFs);
  186237. }
  186238. return (0);
  186239. }
  186240. #endif
  186241. #if defined(PNG_pCAL_SUPPORTED)
  186242. png_uint_32 PNGAPI
  186243. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  186244. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  186245. png_charp *units, png_charpp *params)
  186246. {
  186247. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  186248. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  186249. nparams != NULL && units != NULL && params != NULL)
  186250. {
  186251. png_debug1(1, "in %s retrieval function\n", "pCAL");
  186252. *purpose = info_ptr->pcal_purpose;
  186253. *X0 = info_ptr->pcal_X0;
  186254. *X1 = info_ptr->pcal_X1;
  186255. *type = (int)info_ptr->pcal_type;
  186256. *nparams = (int)info_ptr->pcal_nparams;
  186257. *units = info_ptr->pcal_units;
  186258. *params = info_ptr->pcal_params;
  186259. return (PNG_INFO_pCAL);
  186260. }
  186261. return (0);
  186262. }
  186263. #endif
  186264. #if defined(PNG_sCAL_SUPPORTED)
  186265. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186266. png_uint_32 PNGAPI
  186267. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  186268. int *unit, double *width, double *height)
  186269. {
  186270. if (png_ptr != NULL && info_ptr != NULL &&
  186271. (info_ptr->valid & PNG_INFO_sCAL))
  186272. {
  186273. *unit = info_ptr->scal_unit;
  186274. *width = info_ptr->scal_pixel_width;
  186275. *height = info_ptr->scal_pixel_height;
  186276. return (PNG_INFO_sCAL);
  186277. }
  186278. return(0);
  186279. }
  186280. #else
  186281. #ifdef PNG_FIXED_POINT_SUPPORTED
  186282. png_uint_32 PNGAPI
  186283. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  186284. int *unit, png_charpp width, png_charpp height)
  186285. {
  186286. if (png_ptr != NULL && info_ptr != NULL &&
  186287. (info_ptr->valid & PNG_INFO_sCAL))
  186288. {
  186289. *unit = info_ptr->scal_unit;
  186290. *width = info_ptr->scal_s_width;
  186291. *height = info_ptr->scal_s_height;
  186292. return (PNG_INFO_sCAL);
  186293. }
  186294. return(0);
  186295. }
  186296. #endif
  186297. #endif
  186298. #endif
  186299. #if defined(PNG_pHYs_SUPPORTED)
  186300. png_uint_32 PNGAPI
  186301. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  186302. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  186303. {
  186304. png_uint_32 retval = 0;
  186305. if (png_ptr != NULL && info_ptr != NULL &&
  186306. (info_ptr->valid & PNG_INFO_pHYs))
  186307. {
  186308. png_debug1(1, "in %s retrieval function\n", "pHYs");
  186309. if (res_x != NULL)
  186310. {
  186311. *res_x = info_ptr->x_pixels_per_unit;
  186312. retval |= PNG_INFO_pHYs;
  186313. }
  186314. if (res_y != NULL)
  186315. {
  186316. *res_y = info_ptr->y_pixels_per_unit;
  186317. retval |= PNG_INFO_pHYs;
  186318. }
  186319. if (unit_type != NULL)
  186320. {
  186321. *unit_type = (int)info_ptr->phys_unit_type;
  186322. retval |= PNG_INFO_pHYs;
  186323. }
  186324. }
  186325. return (retval);
  186326. }
  186327. #endif
  186328. png_uint_32 PNGAPI
  186329. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  186330. int *num_palette)
  186331. {
  186332. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  186333. && palette != NULL)
  186334. {
  186335. png_debug1(1, "in %s retrieval function\n", "PLTE");
  186336. *palette = info_ptr->palette;
  186337. *num_palette = info_ptr->num_palette;
  186338. png_debug1(3, "num_palette = %d\n", *num_palette);
  186339. return (PNG_INFO_PLTE);
  186340. }
  186341. return (0);
  186342. }
  186343. #if defined(PNG_sBIT_SUPPORTED)
  186344. png_uint_32 PNGAPI
  186345. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  186346. {
  186347. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  186348. && sig_bit != NULL)
  186349. {
  186350. png_debug1(1, "in %s retrieval function\n", "sBIT");
  186351. *sig_bit = &(info_ptr->sig_bit);
  186352. return (PNG_INFO_sBIT);
  186353. }
  186354. return (0);
  186355. }
  186356. #endif
  186357. #if defined(PNG_TEXT_SUPPORTED)
  186358. png_uint_32 PNGAPI
  186359. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  186360. int *num_text)
  186361. {
  186362. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  186363. {
  186364. png_debug1(1, "in %s retrieval function\n",
  186365. (png_ptr->chunk_name[0] == '\0' ? "text"
  186366. : (png_const_charp)png_ptr->chunk_name));
  186367. if (text_ptr != NULL)
  186368. *text_ptr = info_ptr->text;
  186369. if (num_text != NULL)
  186370. *num_text = info_ptr->num_text;
  186371. return ((png_uint_32)info_ptr->num_text);
  186372. }
  186373. if (num_text != NULL)
  186374. *num_text = 0;
  186375. return(0);
  186376. }
  186377. #endif
  186378. #if defined(PNG_tIME_SUPPORTED)
  186379. png_uint_32 PNGAPI
  186380. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  186381. {
  186382. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  186383. && mod_time != NULL)
  186384. {
  186385. png_debug1(1, "in %s retrieval function\n", "tIME");
  186386. *mod_time = &(info_ptr->mod_time);
  186387. return (PNG_INFO_tIME);
  186388. }
  186389. return (0);
  186390. }
  186391. #endif
  186392. #if defined(PNG_tRNS_SUPPORTED)
  186393. png_uint_32 PNGAPI
  186394. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  186395. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  186396. {
  186397. png_uint_32 retval = 0;
  186398. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  186399. {
  186400. png_debug1(1, "in %s retrieval function\n", "tRNS");
  186401. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186402. {
  186403. if (trans != NULL)
  186404. {
  186405. *trans = info_ptr->trans;
  186406. retval |= PNG_INFO_tRNS;
  186407. }
  186408. if (trans_values != NULL)
  186409. *trans_values = &(info_ptr->trans_values);
  186410. }
  186411. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  186412. {
  186413. if (trans_values != NULL)
  186414. {
  186415. *trans_values = &(info_ptr->trans_values);
  186416. retval |= PNG_INFO_tRNS;
  186417. }
  186418. if(trans != NULL)
  186419. *trans = NULL;
  186420. }
  186421. if(num_trans != NULL)
  186422. {
  186423. *num_trans = info_ptr->num_trans;
  186424. retval |= PNG_INFO_tRNS;
  186425. }
  186426. }
  186427. return (retval);
  186428. }
  186429. #endif
  186430. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  186431. png_uint_32 PNGAPI
  186432. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  186433. png_unknown_chunkpp unknowns)
  186434. {
  186435. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  186436. {
  186437. *unknowns = info_ptr->unknown_chunks;
  186438. return ((png_uint_32)info_ptr->unknown_chunks_num);
  186439. }
  186440. return (0);
  186441. }
  186442. #endif
  186443. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  186444. png_byte PNGAPI
  186445. png_get_rgb_to_gray_status (png_structp png_ptr)
  186446. {
  186447. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  186448. }
  186449. #endif
  186450. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  186451. png_voidp PNGAPI
  186452. png_get_user_chunk_ptr(png_structp png_ptr)
  186453. {
  186454. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  186455. }
  186456. #endif
  186457. #ifdef PNG_WRITE_SUPPORTED
  186458. png_uint_32 PNGAPI
  186459. png_get_compression_buffer_size(png_structp png_ptr)
  186460. {
  186461. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  186462. }
  186463. #endif
  186464. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  186465. #ifndef PNG_1_0_X
  186466. /* this function was added to libpng 1.2.0 and should exist by default */
  186467. png_uint_32 PNGAPI
  186468. png_get_asm_flags (png_structp png_ptr)
  186469. {
  186470. /* obsolete, to be removed from libpng-1.4.0 */
  186471. return (png_ptr? 0L: 0L);
  186472. }
  186473. /* this function was added to libpng 1.2.0 and should exist by default */
  186474. png_uint_32 PNGAPI
  186475. png_get_asm_flagmask (int flag_select)
  186476. {
  186477. /* obsolete, to be removed from libpng-1.4.0 */
  186478. flag_select=flag_select;
  186479. return 0L;
  186480. }
  186481. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  186482. /* this function was added to libpng 1.2.0 */
  186483. png_uint_32 PNGAPI
  186484. png_get_mmx_flagmask (int flag_select, int *compilerID)
  186485. {
  186486. /* obsolete, to be removed from libpng-1.4.0 */
  186487. flag_select=flag_select;
  186488. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  186489. return 0L;
  186490. }
  186491. /* this function was added to libpng 1.2.0 */
  186492. png_byte PNGAPI
  186493. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  186494. {
  186495. /* obsolete, to be removed from libpng-1.4.0 */
  186496. return (png_ptr? 0: 0);
  186497. }
  186498. /* this function was added to libpng 1.2.0 */
  186499. png_uint_32 PNGAPI
  186500. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  186501. {
  186502. /* obsolete, to be removed from libpng-1.4.0 */
  186503. return (png_ptr? 0L: 0L);
  186504. }
  186505. #endif /* ?PNG_1_0_X */
  186506. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  186507. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186508. /* these functions were added to libpng 1.2.6 */
  186509. png_uint_32 PNGAPI
  186510. png_get_user_width_max (png_structp png_ptr)
  186511. {
  186512. return (png_ptr? png_ptr->user_width_max : 0);
  186513. }
  186514. png_uint_32 PNGAPI
  186515. png_get_user_height_max (png_structp png_ptr)
  186516. {
  186517. return (png_ptr? png_ptr->user_height_max : 0);
  186518. }
  186519. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  186520. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  186521. /*** End of inlined file: pngget.c ***/
  186522. /*** Start of inlined file: pngmem.c ***/
  186523. /* pngmem.c - stub functions for memory allocation
  186524. *
  186525. * Last changed in libpng 1.2.13 November 13, 2006
  186526. * For conditions of distribution and use, see copyright notice in png.h
  186527. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  186528. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186529. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186530. *
  186531. * This file provides a location for all memory allocation. Users who
  186532. * need special memory handling are expected to supply replacement
  186533. * functions for png_malloc() and png_free(), and to use
  186534. * png_create_read_struct_2() and png_create_write_struct_2() to
  186535. * identify the replacement functions.
  186536. */
  186537. #define PNG_INTERNAL
  186538. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  186539. /* Borland DOS special memory handler */
  186540. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  186541. /* if you change this, be sure to change the one in png.h also */
  186542. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  186543. by a single call to calloc() if this is thought to improve performance. */
  186544. png_voidp /* PRIVATE */
  186545. png_create_struct(int type)
  186546. {
  186547. #ifdef PNG_USER_MEM_SUPPORTED
  186548. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186549. }
  186550. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  186551. png_voidp /* PRIVATE */
  186552. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186553. {
  186554. #endif /* PNG_USER_MEM_SUPPORTED */
  186555. png_size_t size;
  186556. png_voidp struct_ptr;
  186557. if (type == PNG_STRUCT_INFO)
  186558. size = png_sizeof(png_info);
  186559. else if (type == PNG_STRUCT_PNG)
  186560. size = png_sizeof(png_struct);
  186561. else
  186562. return (png_get_copyright(NULL));
  186563. #ifdef PNG_USER_MEM_SUPPORTED
  186564. if(malloc_fn != NULL)
  186565. {
  186566. png_struct dummy_struct;
  186567. png_structp png_ptr = &dummy_struct;
  186568. png_ptr->mem_ptr=mem_ptr;
  186569. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  186570. }
  186571. else
  186572. #endif /* PNG_USER_MEM_SUPPORTED */
  186573. struct_ptr = (png_voidp)farmalloc(size);
  186574. if (struct_ptr != NULL)
  186575. png_memset(struct_ptr, 0, size);
  186576. return (struct_ptr);
  186577. }
  186578. /* Free memory allocated by a png_create_struct() call */
  186579. void /* PRIVATE */
  186580. png_destroy_struct(png_voidp struct_ptr)
  186581. {
  186582. #ifdef PNG_USER_MEM_SUPPORTED
  186583. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186584. }
  186585. /* Free memory allocated by a png_create_struct() call */
  186586. void /* PRIVATE */
  186587. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186588. png_voidp mem_ptr)
  186589. {
  186590. #endif
  186591. if (struct_ptr != NULL)
  186592. {
  186593. #ifdef PNG_USER_MEM_SUPPORTED
  186594. if(free_fn != NULL)
  186595. {
  186596. png_struct dummy_struct;
  186597. png_structp png_ptr = &dummy_struct;
  186598. png_ptr->mem_ptr=mem_ptr;
  186599. (*(free_fn))(png_ptr, struct_ptr);
  186600. return;
  186601. }
  186602. #endif /* PNG_USER_MEM_SUPPORTED */
  186603. farfree (struct_ptr);
  186604. }
  186605. }
  186606. /* Allocate memory. For reasonable files, size should never exceed
  186607. * 64K. However, zlib may allocate more then 64K if you don't tell
  186608. * it not to. See zconf.h and png.h for more information. zlib does
  186609. * need to allocate exactly 64K, so whatever you call here must
  186610. * have the ability to do that.
  186611. *
  186612. * Borland seems to have a problem in DOS mode for exactly 64K.
  186613. * It gives you a segment with an offset of 8 (perhaps to store its
  186614. * memory stuff). zlib doesn't like this at all, so we have to
  186615. * detect and deal with it. This code should not be needed in
  186616. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  186617. * been updated by Alexander Lehmann for version 0.89 to waste less
  186618. * memory.
  186619. *
  186620. * Note that we can't use png_size_t for the "size" declaration,
  186621. * since on some systems a png_size_t is a 16-bit quantity, and as a
  186622. * result, we would be truncating potentially larger memory requests
  186623. * (which should cause a fatal error) and introducing major problems.
  186624. */
  186625. png_voidp PNGAPI
  186626. png_malloc(png_structp png_ptr, png_uint_32 size)
  186627. {
  186628. png_voidp ret;
  186629. if (png_ptr == NULL || size == 0)
  186630. return (NULL);
  186631. #ifdef PNG_USER_MEM_SUPPORTED
  186632. if(png_ptr->malloc_fn != NULL)
  186633. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186634. else
  186635. ret = (png_malloc_default(png_ptr, size));
  186636. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186637. png_error(png_ptr, "Out of memory!");
  186638. return (ret);
  186639. }
  186640. png_voidp PNGAPI
  186641. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186642. {
  186643. png_voidp ret;
  186644. #endif /* PNG_USER_MEM_SUPPORTED */
  186645. if (png_ptr == NULL || size == 0)
  186646. return (NULL);
  186647. #ifdef PNG_MAX_MALLOC_64K
  186648. if (size > (png_uint_32)65536L)
  186649. {
  186650. png_warning(png_ptr, "Cannot Allocate > 64K");
  186651. ret = NULL;
  186652. }
  186653. else
  186654. #endif
  186655. if (size != (size_t)size)
  186656. ret = NULL;
  186657. else if (size == (png_uint_32)65536L)
  186658. {
  186659. if (png_ptr->offset_table == NULL)
  186660. {
  186661. /* try to see if we need to do any of this fancy stuff */
  186662. ret = farmalloc(size);
  186663. if (ret == NULL || ((png_size_t)ret & 0xffff))
  186664. {
  186665. int num_blocks;
  186666. png_uint_32 total_size;
  186667. png_bytep table;
  186668. int i;
  186669. png_byte huge * hptr;
  186670. if (ret != NULL)
  186671. {
  186672. farfree(ret);
  186673. ret = NULL;
  186674. }
  186675. if(png_ptr->zlib_window_bits > 14)
  186676. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  186677. else
  186678. num_blocks = 1;
  186679. if (png_ptr->zlib_mem_level >= 7)
  186680. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  186681. else
  186682. num_blocks++;
  186683. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  186684. table = farmalloc(total_size);
  186685. if (table == NULL)
  186686. {
  186687. #ifndef PNG_USER_MEM_SUPPORTED
  186688. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186689. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  186690. else
  186691. png_warning(png_ptr, "Out Of Memory.");
  186692. #endif
  186693. return (NULL);
  186694. }
  186695. if ((png_size_t)table & 0xfff0)
  186696. {
  186697. #ifndef PNG_USER_MEM_SUPPORTED
  186698. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186699. png_error(png_ptr,
  186700. "Farmalloc didn't return normalized pointer");
  186701. else
  186702. png_warning(png_ptr,
  186703. "Farmalloc didn't return normalized pointer");
  186704. #endif
  186705. return (NULL);
  186706. }
  186707. png_ptr->offset_table = table;
  186708. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  186709. png_sizeof (png_bytep));
  186710. if (png_ptr->offset_table_ptr == NULL)
  186711. {
  186712. #ifndef PNG_USER_MEM_SUPPORTED
  186713. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186714. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  186715. else
  186716. png_warning(png_ptr, "Out Of memory.");
  186717. #endif
  186718. return (NULL);
  186719. }
  186720. hptr = (png_byte huge *)table;
  186721. if ((png_size_t)hptr & 0xf)
  186722. {
  186723. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  186724. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  186725. }
  186726. for (i = 0; i < num_blocks; i++)
  186727. {
  186728. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  186729. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  186730. }
  186731. png_ptr->offset_table_number = num_blocks;
  186732. png_ptr->offset_table_count = 0;
  186733. png_ptr->offset_table_count_free = 0;
  186734. }
  186735. }
  186736. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  186737. {
  186738. #ifndef PNG_USER_MEM_SUPPORTED
  186739. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186740. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  186741. else
  186742. png_warning(png_ptr, "Out of Memory.");
  186743. #endif
  186744. return (NULL);
  186745. }
  186746. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  186747. }
  186748. else
  186749. ret = farmalloc(size);
  186750. #ifndef PNG_USER_MEM_SUPPORTED
  186751. if (ret == NULL)
  186752. {
  186753. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186754. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186755. else
  186756. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186757. }
  186758. #endif
  186759. return (ret);
  186760. }
  186761. /* free a pointer allocated by png_malloc(). In the default
  186762. configuration, png_ptr is not used, but is passed in case it
  186763. is needed. If ptr is NULL, return without taking any action. */
  186764. void PNGAPI
  186765. png_free(png_structp png_ptr, png_voidp ptr)
  186766. {
  186767. if (png_ptr == NULL || ptr == NULL)
  186768. return;
  186769. #ifdef PNG_USER_MEM_SUPPORTED
  186770. if (png_ptr->free_fn != NULL)
  186771. {
  186772. (*(png_ptr->free_fn))(png_ptr, ptr);
  186773. return;
  186774. }
  186775. else png_free_default(png_ptr, ptr);
  186776. }
  186777. void PNGAPI
  186778. png_free_default(png_structp png_ptr, png_voidp ptr)
  186779. {
  186780. #endif /* PNG_USER_MEM_SUPPORTED */
  186781. if(png_ptr == NULL) return;
  186782. if (png_ptr->offset_table != NULL)
  186783. {
  186784. int i;
  186785. for (i = 0; i < png_ptr->offset_table_count; i++)
  186786. {
  186787. if (ptr == png_ptr->offset_table_ptr[i])
  186788. {
  186789. ptr = NULL;
  186790. png_ptr->offset_table_count_free++;
  186791. break;
  186792. }
  186793. }
  186794. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  186795. {
  186796. farfree(png_ptr->offset_table);
  186797. farfree(png_ptr->offset_table_ptr);
  186798. png_ptr->offset_table = NULL;
  186799. png_ptr->offset_table_ptr = NULL;
  186800. }
  186801. }
  186802. if (ptr != NULL)
  186803. {
  186804. farfree(ptr);
  186805. }
  186806. }
  186807. #else /* Not the Borland DOS special memory handler */
  186808. /* Allocate memory for a png_struct or a png_info. The malloc and
  186809. memset can be replaced by a single call to calloc() if this is thought
  186810. to improve performance noticably. */
  186811. png_voidp /* PRIVATE */
  186812. png_create_struct(int type)
  186813. {
  186814. #ifdef PNG_USER_MEM_SUPPORTED
  186815. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186816. }
  186817. /* Allocate memory for a png_struct or a png_info. The malloc and
  186818. memset can be replaced by a single call to calloc() if this is thought
  186819. to improve performance noticably. */
  186820. png_voidp /* PRIVATE */
  186821. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186822. {
  186823. #endif /* PNG_USER_MEM_SUPPORTED */
  186824. png_size_t size;
  186825. png_voidp struct_ptr;
  186826. if (type == PNG_STRUCT_INFO)
  186827. size = png_sizeof(png_info);
  186828. else if (type == PNG_STRUCT_PNG)
  186829. size = png_sizeof(png_struct);
  186830. else
  186831. return (NULL);
  186832. #ifdef PNG_USER_MEM_SUPPORTED
  186833. if(malloc_fn != NULL)
  186834. {
  186835. png_struct dummy_struct;
  186836. png_structp png_ptr = &dummy_struct;
  186837. png_ptr->mem_ptr=mem_ptr;
  186838. struct_ptr = (*(malloc_fn))(png_ptr, size);
  186839. if (struct_ptr != NULL)
  186840. png_memset(struct_ptr, 0, size);
  186841. return (struct_ptr);
  186842. }
  186843. #endif /* PNG_USER_MEM_SUPPORTED */
  186844. #if defined(__TURBOC__) && !defined(__FLAT__)
  186845. struct_ptr = (png_voidp)farmalloc(size);
  186846. #else
  186847. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186848. struct_ptr = (png_voidp)halloc(size,1);
  186849. # else
  186850. struct_ptr = (png_voidp)malloc(size);
  186851. # endif
  186852. #endif
  186853. if (struct_ptr != NULL)
  186854. png_memset(struct_ptr, 0, size);
  186855. return (struct_ptr);
  186856. }
  186857. /* Free memory allocated by a png_create_struct() call */
  186858. void /* PRIVATE */
  186859. png_destroy_struct(png_voidp struct_ptr)
  186860. {
  186861. #ifdef PNG_USER_MEM_SUPPORTED
  186862. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186863. }
  186864. /* Free memory allocated by a png_create_struct() call */
  186865. void /* PRIVATE */
  186866. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186867. png_voidp mem_ptr)
  186868. {
  186869. #endif /* PNG_USER_MEM_SUPPORTED */
  186870. if (struct_ptr != NULL)
  186871. {
  186872. #ifdef PNG_USER_MEM_SUPPORTED
  186873. if(free_fn != NULL)
  186874. {
  186875. png_struct dummy_struct;
  186876. png_structp png_ptr = &dummy_struct;
  186877. png_ptr->mem_ptr=mem_ptr;
  186878. (*(free_fn))(png_ptr, struct_ptr);
  186879. return;
  186880. }
  186881. #endif /* PNG_USER_MEM_SUPPORTED */
  186882. #if defined(__TURBOC__) && !defined(__FLAT__)
  186883. farfree(struct_ptr);
  186884. #else
  186885. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186886. hfree(struct_ptr);
  186887. # else
  186888. free(struct_ptr);
  186889. # endif
  186890. #endif
  186891. }
  186892. }
  186893. /* Allocate memory. For reasonable files, size should never exceed
  186894. 64K. However, zlib may allocate more then 64K if you don't tell
  186895. it not to. See zconf.h and png.h for more information. zlib does
  186896. need to allocate exactly 64K, so whatever you call here must
  186897. have the ability to do that. */
  186898. png_voidp PNGAPI
  186899. png_malloc(png_structp png_ptr, png_uint_32 size)
  186900. {
  186901. png_voidp ret;
  186902. #ifdef PNG_USER_MEM_SUPPORTED
  186903. if (png_ptr == NULL || size == 0)
  186904. return (NULL);
  186905. if(png_ptr->malloc_fn != NULL)
  186906. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186907. else
  186908. ret = (png_malloc_default(png_ptr, size));
  186909. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186910. png_error(png_ptr, "Out of Memory!");
  186911. return (ret);
  186912. }
  186913. png_voidp PNGAPI
  186914. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186915. {
  186916. png_voidp ret;
  186917. #endif /* PNG_USER_MEM_SUPPORTED */
  186918. if (png_ptr == NULL || size == 0)
  186919. return (NULL);
  186920. #ifdef PNG_MAX_MALLOC_64K
  186921. if (size > (png_uint_32)65536L)
  186922. {
  186923. #ifndef PNG_USER_MEM_SUPPORTED
  186924. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186925. png_error(png_ptr, "Cannot Allocate > 64K");
  186926. else
  186927. #endif
  186928. return NULL;
  186929. }
  186930. #endif
  186931. /* Check for overflow */
  186932. #if defined(__TURBOC__) && !defined(__FLAT__)
  186933. if (size != (unsigned long)size)
  186934. ret = NULL;
  186935. else
  186936. ret = farmalloc(size);
  186937. #else
  186938. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186939. if (size != (unsigned long)size)
  186940. ret = NULL;
  186941. else
  186942. ret = halloc(size, 1);
  186943. # else
  186944. if (size != (size_t)size)
  186945. ret = NULL;
  186946. else
  186947. ret = malloc((size_t)size);
  186948. # endif
  186949. #endif
  186950. #ifndef PNG_USER_MEM_SUPPORTED
  186951. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186952. png_error(png_ptr, "Out of Memory");
  186953. #endif
  186954. return (ret);
  186955. }
  186956. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  186957. without taking any action. */
  186958. void PNGAPI
  186959. png_free(png_structp png_ptr, png_voidp ptr)
  186960. {
  186961. if (png_ptr == NULL || ptr == NULL)
  186962. return;
  186963. #ifdef PNG_USER_MEM_SUPPORTED
  186964. if (png_ptr->free_fn != NULL)
  186965. {
  186966. (*(png_ptr->free_fn))(png_ptr, ptr);
  186967. return;
  186968. }
  186969. else png_free_default(png_ptr, ptr);
  186970. }
  186971. void PNGAPI
  186972. png_free_default(png_structp png_ptr, png_voidp ptr)
  186973. {
  186974. if (png_ptr == NULL || ptr == NULL)
  186975. return;
  186976. #endif /* PNG_USER_MEM_SUPPORTED */
  186977. #if defined(__TURBOC__) && !defined(__FLAT__)
  186978. farfree(ptr);
  186979. #else
  186980. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  186981. hfree(ptr);
  186982. # else
  186983. free(ptr);
  186984. # endif
  186985. #endif
  186986. }
  186987. #endif /* Not Borland DOS special memory handler */
  186988. #if defined(PNG_1_0_X)
  186989. # define png_malloc_warn png_malloc
  186990. #else
  186991. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  186992. * function will set up png_malloc() to issue a png_warning and return NULL
  186993. * instead of issuing a png_error, if it fails to allocate the requested
  186994. * memory.
  186995. */
  186996. png_voidp PNGAPI
  186997. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  186998. {
  186999. png_voidp ptr;
  187000. png_uint_32 save_flags;
  187001. if(png_ptr == NULL) return (NULL);
  187002. save_flags=png_ptr->flags;
  187003. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  187004. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  187005. png_ptr->flags=save_flags;
  187006. return(ptr);
  187007. }
  187008. #endif
  187009. png_voidp PNGAPI
  187010. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  187011. png_uint_32 length)
  187012. {
  187013. png_size_t size;
  187014. size = (png_size_t)length;
  187015. if ((png_uint_32)size != length)
  187016. png_error(png_ptr,"Overflow in png_memcpy_check.");
  187017. return(png_memcpy (s1, s2, size));
  187018. }
  187019. png_voidp PNGAPI
  187020. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  187021. png_uint_32 length)
  187022. {
  187023. png_size_t size;
  187024. size = (png_size_t)length;
  187025. if ((png_uint_32)size != length)
  187026. png_error(png_ptr,"Overflow in png_memset_check.");
  187027. return (png_memset (s1, value, size));
  187028. }
  187029. #ifdef PNG_USER_MEM_SUPPORTED
  187030. /* This function is called when the application wants to use another method
  187031. * of allocating and freeing memory.
  187032. */
  187033. void PNGAPI
  187034. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  187035. malloc_fn, png_free_ptr free_fn)
  187036. {
  187037. if(png_ptr != NULL) {
  187038. png_ptr->mem_ptr = mem_ptr;
  187039. png_ptr->malloc_fn = malloc_fn;
  187040. png_ptr->free_fn = free_fn;
  187041. }
  187042. }
  187043. /* This function returns a pointer to the mem_ptr associated with the user
  187044. * functions. The application should free any memory associated with this
  187045. * pointer before png_write_destroy and png_read_destroy are called.
  187046. */
  187047. png_voidp PNGAPI
  187048. png_get_mem_ptr(png_structp png_ptr)
  187049. {
  187050. if(png_ptr == NULL) return (NULL);
  187051. return ((png_voidp)png_ptr->mem_ptr);
  187052. }
  187053. #endif /* PNG_USER_MEM_SUPPORTED */
  187054. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  187055. /*** End of inlined file: pngmem.c ***/
  187056. /*** Start of inlined file: pngread.c ***/
  187057. /* pngread.c - read a PNG file
  187058. *
  187059. * Last changed in libpng 1.2.20 September 7, 2007
  187060. * For conditions of distribution and use, see copyright notice in png.h
  187061. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  187062. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  187063. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  187064. *
  187065. * This file contains routines that an application calls directly to
  187066. * read a PNG file or stream.
  187067. */
  187068. #define PNG_INTERNAL
  187069. #if defined(PNG_READ_SUPPORTED)
  187070. /* Create a PNG structure for reading, and allocate any memory needed. */
  187071. png_structp PNGAPI
  187072. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  187073. png_error_ptr error_fn, png_error_ptr warn_fn)
  187074. {
  187075. #ifdef PNG_USER_MEM_SUPPORTED
  187076. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  187077. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  187078. }
  187079. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  187080. png_structp PNGAPI
  187081. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  187082. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  187083. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  187084. {
  187085. #endif /* PNG_USER_MEM_SUPPORTED */
  187086. png_structp png_ptr;
  187087. #ifdef PNG_SETJMP_SUPPORTED
  187088. #ifdef USE_FAR_KEYWORD
  187089. jmp_buf jmpbuf;
  187090. #endif
  187091. #endif
  187092. int i;
  187093. png_debug(1, "in png_create_read_struct\n");
  187094. #ifdef PNG_USER_MEM_SUPPORTED
  187095. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  187096. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  187097. #else
  187098. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  187099. #endif
  187100. if (png_ptr == NULL)
  187101. return (NULL);
  187102. /* added at libpng-1.2.6 */
  187103. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  187104. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  187105. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  187106. #endif
  187107. #ifdef PNG_SETJMP_SUPPORTED
  187108. #ifdef USE_FAR_KEYWORD
  187109. if (setjmp(jmpbuf))
  187110. #else
  187111. if (setjmp(png_ptr->jmpbuf))
  187112. #endif
  187113. {
  187114. png_free(png_ptr, png_ptr->zbuf);
  187115. png_ptr->zbuf=NULL;
  187116. #ifdef PNG_USER_MEM_SUPPORTED
  187117. png_destroy_struct_2((png_voidp)png_ptr,
  187118. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  187119. #else
  187120. png_destroy_struct((png_voidp)png_ptr);
  187121. #endif
  187122. return (NULL);
  187123. }
  187124. #ifdef USE_FAR_KEYWORD
  187125. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  187126. #endif
  187127. #endif
  187128. #ifdef PNG_USER_MEM_SUPPORTED
  187129. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  187130. #endif
  187131. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  187132. i=0;
  187133. do
  187134. {
  187135. if(user_png_ver[i] != png_libpng_ver[i])
  187136. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  187137. } while (png_libpng_ver[i++]);
  187138. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  187139. {
  187140. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  187141. * we must recompile any applications that use any older library version.
  187142. * For versions after libpng 1.0, we will be compatible, so we need
  187143. * only check the first digit.
  187144. */
  187145. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  187146. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  187147. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  187148. {
  187149. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187150. char msg[80];
  187151. if (user_png_ver)
  187152. {
  187153. png_snprintf(msg, 80,
  187154. "Application was compiled with png.h from libpng-%.20s",
  187155. user_png_ver);
  187156. png_warning(png_ptr, msg);
  187157. }
  187158. png_snprintf(msg, 80,
  187159. "Application is running with png.c from libpng-%.20s",
  187160. png_libpng_ver);
  187161. png_warning(png_ptr, msg);
  187162. #endif
  187163. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187164. png_ptr->flags=0;
  187165. #endif
  187166. png_error(png_ptr,
  187167. "Incompatible libpng version in application and library");
  187168. }
  187169. }
  187170. /* initialize zbuf - compression buffer */
  187171. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  187172. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  187173. (png_uint_32)png_ptr->zbuf_size);
  187174. png_ptr->zstream.zalloc = png_zalloc;
  187175. png_ptr->zstream.zfree = png_zfree;
  187176. png_ptr->zstream.opaque = (voidpf)png_ptr;
  187177. switch (inflateInit(&png_ptr->zstream))
  187178. {
  187179. case Z_OK: /* Do nothing */ break;
  187180. case Z_MEM_ERROR:
  187181. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  187182. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  187183. default: png_error(png_ptr, "Unknown zlib error");
  187184. }
  187185. png_ptr->zstream.next_out = png_ptr->zbuf;
  187186. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187187. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  187188. #ifdef PNG_SETJMP_SUPPORTED
  187189. /* Applications that neglect to set up their own setjmp() and then encounter
  187190. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  187191. abort instead of returning. */
  187192. #ifdef USE_FAR_KEYWORD
  187193. if (setjmp(jmpbuf))
  187194. PNG_ABORT();
  187195. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  187196. #else
  187197. if (setjmp(png_ptr->jmpbuf))
  187198. PNG_ABORT();
  187199. #endif
  187200. #endif
  187201. return (png_ptr);
  187202. }
  187203. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  187204. /* Initialize PNG structure for reading, and allocate any memory needed.
  187205. This interface is deprecated in favour of the png_create_read_struct(),
  187206. and it will disappear as of libpng-1.3.0. */
  187207. #undef png_read_init
  187208. void PNGAPI
  187209. png_read_init(png_structp png_ptr)
  187210. {
  187211. /* We only come here via pre-1.0.7-compiled applications */
  187212. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  187213. }
  187214. void PNGAPI
  187215. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  187216. png_size_t png_struct_size, png_size_t png_info_size)
  187217. {
  187218. /* We only come here via pre-1.0.12-compiled applications */
  187219. if(png_ptr == NULL) return;
  187220. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187221. if(png_sizeof(png_struct) > png_struct_size ||
  187222. png_sizeof(png_info) > png_info_size)
  187223. {
  187224. char msg[80];
  187225. png_ptr->warning_fn=NULL;
  187226. if (user_png_ver)
  187227. {
  187228. png_snprintf(msg, 80,
  187229. "Application was compiled with png.h from libpng-%.20s",
  187230. user_png_ver);
  187231. png_warning(png_ptr, msg);
  187232. }
  187233. png_snprintf(msg, 80,
  187234. "Application is running with png.c from libpng-%.20s",
  187235. png_libpng_ver);
  187236. png_warning(png_ptr, msg);
  187237. }
  187238. #endif
  187239. if(png_sizeof(png_struct) > png_struct_size)
  187240. {
  187241. png_ptr->error_fn=NULL;
  187242. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187243. png_ptr->flags=0;
  187244. #endif
  187245. png_error(png_ptr,
  187246. "The png struct allocated by the application for reading is too small.");
  187247. }
  187248. if(png_sizeof(png_info) > png_info_size)
  187249. {
  187250. png_ptr->error_fn=NULL;
  187251. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187252. png_ptr->flags=0;
  187253. #endif
  187254. png_error(png_ptr,
  187255. "The info struct allocated by application for reading is too small.");
  187256. }
  187257. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  187258. }
  187259. #endif /* PNG_1_0_X || PNG_1_2_X */
  187260. void PNGAPI
  187261. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  187262. png_size_t png_struct_size)
  187263. {
  187264. #ifdef PNG_SETJMP_SUPPORTED
  187265. jmp_buf tmp_jmp; /* to save current jump buffer */
  187266. #endif
  187267. int i=0;
  187268. png_structp png_ptr=*ptr_ptr;
  187269. if(png_ptr == NULL) return;
  187270. do
  187271. {
  187272. if(user_png_ver[i] != png_libpng_ver[i])
  187273. {
  187274. #ifdef PNG_LEGACY_SUPPORTED
  187275. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  187276. #else
  187277. png_ptr->warning_fn=NULL;
  187278. png_warning(png_ptr,
  187279. "Application uses deprecated png_read_init() and should be recompiled.");
  187280. break;
  187281. #endif
  187282. }
  187283. } while (png_libpng_ver[i++]);
  187284. png_debug(1, "in png_read_init_3\n");
  187285. #ifdef PNG_SETJMP_SUPPORTED
  187286. /* save jump buffer and error functions */
  187287. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  187288. #endif
  187289. if(png_sizeof(png_struct) > png_struct_size)
  187290. {
  187291. png_destroy_struct(png_ptr);
  187292. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  187293. png_ptr = *ptr_ptr;
  187294. }
  187295. /* reset all variables to 0 */
  187296. png_memset(png_ptr, 0, png_sizeof (png_struct));
  187297. #ifdef PNG_SETJMP_SUPPORTED
  187298. /* restore jump buffer */
  187299. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  187300. #endif
  187301. /* added at libpng-1.2.6 */
  187302. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  187303. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  187304. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  187305. #endif
  187306. /* initialize zbuf - compression buffer */
  187307. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  187308. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  187309. (png_uint_32)png_ptr->zbuf_size);
  187310. png_ptr->zstream.zalloc = png_zalloc;
  187311. png_ptr->zstream.zfree = png_zfree;
  187312. png_ptr->zstream.opaque = (voidpf)png_ptr;
  187313. switch (inflateInit(&png_ptr->zstream))
  187314. {
  187315. case Z_OK: /* Do nothing */ break;
  187316. case Z_MEM_ERROR:
  187317. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  187318. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  187319. default: png_error(png_ptr, "Unknown zlib error");
  187320. }
  187321. png_ptr->zstream.next_out = png_ptr->zbuf;
  187322. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187323. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  187324. }
  187325. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187326. /* Read the information before the actual image data. This has been
  187327. * changed in v0.90 to allow reading a file that already has the magic
  187328. * bytes read from the stream. You can tell libpng how many bytes have
  187329. * been read from the beginning of the stream (up to the maximum of 8)
  187330. * via png_set_sig_bytes(), and we will only check the remaining bytes
  187331. * here. The application can then have access to the signature bytes we
  187332. * read if it is determined that this isn't a valid PNG file.
  187333. */
  187334. void PNGAPI
  187335. png_read_info(png_structp png_ptr, png_infop info_ptr)
  187336. {
  187337. if(png_ptr == NULL) return;
  187338. png_debug(1, "in png_read_info\n");
  187339. /* If we haven't checked all of the PNG signature bytes, do so now. */
  187340. if (png_ptr->sig_bytes < 8)
  187341. {
  187342. png_size_t num_checked = png_ptr->sig_bytes,
  187343. num_to_check = 8 - num_checked;
  187344. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  187345. png_ptr->sig_bytes = 8;
  187346. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  187347. {
  187348. if (num_checked < 4 &&
  187349. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  187350. png_error(png_ptr, "Not a PNG file");
  187351. else
  187352. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  187353. }
  187354. if (num_checked < 3)
  187355. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  187356. }
  187357. for(;;)
  187358. {
  187359. #ifdef PNG_USE_LOCAL_ARRAYS
  187360. PNG_CONST PNG_IHDR;
  187361. PNG_CONST PNG_IDAT;
  187362. PNG_CONST PNG_IEND;
  187363. PNG_CONST PNG_PLTE;
  187364. #if defined(PNG_READ_bKGD_SUPPORTED)
  187365. PNG_CONST PNG_bKGD;
  187366. #endif
  187367. #if defined(PNG_READ_cHRM_SUPPORTED)
  187368. PNG_CONST PNG_cHRM;
  187369. #endif
  187370. #if defined(PNG_READ_gAMA_SUPPORTED)
  187371. PNG_CONST PNG_gAMA;
  187372. #endif
  187373. #if defined(PNG_READ_hIST_SUPPORTED)
  187374. PNG_CONST PNG_hIST;
  187375. #endif
  187376. #if defined(PNG_READ_iCCP_SUPPORTED)
  187377. PNG_CONST PNG_iCCP;
  187378. #endif
  187379. #if defined(PNG_READ_iTXt_SUPPORTED)
  187380. PNG_CONST PNG_iTXt;
  187381. #endif
  187382. #if defined(PNG_READ_oFFs_SUPPORTED)
  187383. PNG_CONST PNG_oFFs;
  187384. #endif
  187385. #if defined(PNG_READ_pCAL_SUPPORTED)
  187386. PNG_CONST PNG_pCAL;
  187387. #endif
  187388. #if defined(PNG_READ_pHYs_SUPPORTED)
  187389. PNG_CONST PNG_pHYs;
  187390. #endif
  187391. #if defined(PNG_READ_sBIT_SUPPORTED)
  187392. PNG_CONST PNG_sBIT;
  187393. #endif
  187394. #if defined(PNG_READ_sCAL_SUPPORTED)
  187395. PNG_CONST PNG_sCAL;
  187396. #endif
  187397. #if defined(PNG_READ_sPLT_SUPPORTED)
  187398. PNG_CONST PNG_sPLT;
  187399. #endif
  187400. #if defined(PNG_READ_sRGB_SUPPORTED)
  187401. PNG_CONST PNG_sRGB;
  187402. #endif
  187403. #if defined(PNG_READ_tEXt_SUPPORTED)
  187404. PNG_CONST PNG_tEXt;
  187405. #endif
  187406. #if defined(PNG_READ_tIME_SUPPORTED)
  187407. PNG_CONST PNG_tIME;
  187408. #endif
  187409. #if defined(PNG_READ_tRNS_SUPPORTED)
  187410. PNG_CONST PNG_tRNS;
  187411. #endif
  187412. #if defined(PNG_READ_zTXt_SUPPORTED)
  187413. PNG_CONST PNG_zTXt;
  187414. #endif
  187415. #endif /* PNG_USE_LOCAL_ARRAYS */
  187416. png_byte chunk_length[4];
  187417. png_uint_32 length;
  187418. png_read_data(png_ptr, chunk_length, 4);
  187419. length = png_get_uint_31(png_ptr,chunk_length);
  187420. png_reset_crc(png_ptr);
  187421. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187422. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  187423. length);
  187424. /* This should be a binary subdivision search or a hash for
  187425. * matching the chunk name rather than a linear search.
  187426. */
  187427. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187428. if(png_ptr->mode & PNG_AFTER_IDAT)
  187429. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  187430. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187431. png_handle_IHDR(png_ptr, info_ptr, length);
  187432. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187433. png_handle_IEND(png_ptr, info_ptr, length);
  187434. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187435. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187436. {
  187437. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187438. png_ptr->mode |= PNG_HAVE_IDAT;
  187439. png_handle_unknown(png_ptr, info_ptr, length);
  187440. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187441. png_ptr->mode |= PNG_HAVE_PLTE;
  187442. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187443. {
  187444. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187445. png_error(png_ptr, "Missing IHDR before IDAT");
  187446. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187447. !(png_ptr->mode & PNG_HAVE_PLTE))
  187448. png_error(png_ptr, "Missing PLTE before IDAT");
  187449. break;
  187450. }
  187451. }
  187452. #endif
  187453. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187454. png_handle_PLTE(png_ptr, info_ptr, length);
  187455. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187456. {
  187457. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187458. png_error(png_ptr, "Missing IHDR before IDAT");
  187459. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187460. !(png_ptr->mode & PNG_HAVE_PLTE))
  187461. png_error(png_ptr, "Missing PLTE before IDAT");
  187462. png_ptr->idat_size = length;
  187463. png_ptr->mode |= PNG_HAVE_IDAT;
  187464. break;
  187465. }
  187466. #if defined(PNG_READ_bKGD_SUPPORTED)
  187467. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187468. png_handle_bKGD(png_ptr, info_ptr, length);
  187469. #endif
  187470. #if defined(PNG_READ_cHRM_SUPPORTED)
  187471. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187472. png_handle_cHRM(png_ptr, info_ptr, length);
  187473. #endif
  187474. #if defined(PNG_READ_gAMA_SUPPORTED)
  187475. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187476. png_handle_gAMA(png_ptr, info_ptr, length);
  187477. #endif
  187478. #if defined(PNG_READ_hIST_SUPPORTED)
  187479. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187480. png_handle_hIST(png_ptr, info_ptr, length);
  187481. #endif
  187482. #if defined(PNG_READ_oFFs_SUPPORTED)
  187483. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187484. png_handle_oFFs(png_ptr, info_ptr, length);
  187485. #endif
  187486. #if defined(PNG_READ_pCAL_SUPPORTED)
  187487. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187488. png_handle_pCAL(png_ptr, info_ptr, length);
  187489. #endif
  187490. #if defined(PNG_READ_sCAL_SUPPORTED)
  187491. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187492. png_handle_sCAL(png_ptr, info_ptr, length);
  187493. #endif
  187494. #if defined(PNG_READ_pHYs_SUPPORTED)
  187495. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187496. png_handle_pHYs(png_ptr, info_ptr, length);
  187497. #endif
  187498. #if defined(PNG_READ_sBIT_SUPPORTED)
  187499. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187500. png_handle_sBIT(png_ptr, info_ptr, length);
  187501. #endif
  187502. #if defined(PNG_READ_sRGB_SUPPORTED)
  187503. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187504. png_handle_sRGB(png_ptr, info_ptr, length);
  187505. #endif
  187506. #if defined(PNG_READ_iCCP_SUPPORTED)
  187507. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187508. png_handle_iCCP(png_ptr, info_ptr, length);
  187509. #endif
  187510. #if defined(PNG_READ_sPLT_SUPPORTED)
  187511. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187512. png_handle_sPLT(png_ptr, info_ptr, length);
  187513. #endif
  187514. #if defined(PNG_READ_tEXt_SUPPORTED)
  187515. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187516. png_handle_tEXt(png_ptr, info_ptr, length);
  187517. #endif
  187518. #if defined(PNG_READ_tIME_SUPPORTED)
  187519. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187520. png_handle_tIME(png_ptr, info_ptr, length);
  187521. #endif
  187522. #if defined(PNG_READ_tRNS_SUPPORTED)
  187523. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187524. png_handle_tRNS(png_ptr, info_ptr, length);
  187525. #endif
  187526. #if defined(PNG_READ_zTXt_SUPPORTED)
  187527. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187528. png_handle_zTXt(png_ptr, info_ptr, length);
  187529. #endif
  187530. #if defined(PNG_READ_iTXt_SUPPORTED)
  187531. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187532. png_handle_iTXt(png_ptr, info_ptr, length);
  187533. #endif
  187534. else
  187535. png_handle_unknown(png_ptr, info_ptr, length);
  187536. }
  187537. }
  187538. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187539. /* optional call to update the users info_ptr structure */
  187540. void PNGAPI
  187541. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  187542. {
  187543. png_debug(1, "in png_read_update_info\n");
  187544. if(png_ptr == NULL) return;
  187545. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187546. png_read_start_row(png_ptr);
  187547. else
  187548. png_warning(png_ptr,
  187549. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  187550. png_read_transform_info(png_ptr, info_ptr);
  187551. }
  187552. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187553. /* Initialize palette, background, etc, after transformations
  187554. * are set, but before any reading takes place. This allows
  187555. * the user to obtain a gamma-corrected palette, for example.
  187556. * If the user doesn't call this, we will do it ourselves.
  187557. */
  187558. void PNGAPI
  187559. png_start_read_image(png_structp png_ptr)
  187560. {
  187561. png_debug(1, "in png_start_read_image\n");
  187562. if(png_ptr == NULL) return;
  187563. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187564. png_read_start_row(png_ptr);
  187565. }
  187566. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187567. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187568. void PNGAPI
  187569. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  187570. {
  187571. #ifdef PNG_USE_LOCAL_ARRAYS
  187572. PNG_CONST PNG_IDAT;
  187573. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  187574. 0xff};
  187575. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  187576. #endif
  187577. int ret;
  187578. if(png_ptr == NULL) return;
  187579. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  187580. png_ptr->row_number, png_ptr->pass);
  187581. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187582. png_read_start_row(png_ptr);
  187583. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  187584. {
  187585. /* check for transforms that have been set but were defined out */
  187586. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  187587. if (png_ptr->transformations & PNG_INVERT_MONO)
  187588. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  187589. #endif
  187590. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  187591. if (png_ptr->transformations & PNG_FILLER)
  187592. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  187593. #endif
  187594. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  187595. if (png_ptr->transformations & PNG_PACKSWAP)
  187596. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  187597. #endif
  187598. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  187599. if (png_ptr->transformations & PNG_PACK)
  187600. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  187601. #endif
  187602. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  187603. if (png_ptr->transformations & PNG_SHIFT)
  187604. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  187605. #endif
  187606. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  187607. if (png_ptr->transformations & PNG_BGR)
  187608. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  187609. #endif
  187610. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  187611. if (png_ptr->transformations & PNG_SWAP_BYTES)
  187612. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  187613. #endif
  187614. }
  187615. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187616. /* if interlaced and we do not need a new row, combine row and return */
  187617. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  187618. {
  187619. switch (png_ptr->pass)
  187620. {
  187621. case 0:
  187622. if (png_ptr->row_number & 0x07)
  187623. {
  187624. if (dsp_row != NULL)
  187625. png_combine_row(png_ptr, dsp_row,
  187626. png_pass_dsp_mask[png_ptr->pass]);
  187627. png_read_finish_row(png_ptr);
  187628. return;
  187629. }
  187630. break;
  187631. case 1:
  187632. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  187633. {
  187634. if (dsp_row != NULL)
  187635. png_combine_row(png_ptr, dsp_row,
  187636. png_pass_dsp_mask[png_ptr->pass]);
  187637. png_read_finish_row(png_ptr);
  187638. return;
  187639. }
  187640. break;
  187641. case 2:
  187642. if ((png_ptr->row_number & 0x07) != 4)
  187643. {
  187644. if (dsp_row != NULL && (png_ptr->row_number & 4))
  187645. png_combine_row(png_ptr, dsp_row,
  187646. png_pass_dsp_mask[png_ptr->pass]);
  187647. png_read_finish_row(png_ptr);
  187648. return;
  187649. }
  187650. break;
  187651. case 3:
  187652. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  187653. {
  187654. if (dsp_row != NULL)
  187655. png_combine_row(png_ptr, dsp_row,
  187656. png_pass_dsp_mask[png_ptr->pass]);
  187657. png_read_finish_row(png_ptr);
  187658. return;
  187659. }
  187660. break;
  187661. case 4:
  187662. if ((png_ptr->row_number & 3) != 2)
  187663. {
  187664. if (dsp_row != NULL && (png_ptr->row_number & 2))
  187665. png_combine_row(png_ptr, dsp_row,
  187666. png_pass_dsp_mask[png_ptr->pass]);
  187667. png_read_finish_row(png_ptr);
  187668. return;
  187669. }
  187670. break;
  187671. case 5:
  187672. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  187673. {
  187674. if (dsp_row != NULL)
  187675. png_combine_row(png_ptr, dsp_row,
  187676. png_pass_dsp_mask[png_ptr->pass]);
  187677. png_read_finish_row(png_ptr);
  187678. return;
  187679. }
  187680. break;
  187681. case 6:
  187682. if (!(png_ptr->row_number & 1))
  187683. {
  187684. png_read_finish_row(png_ptr);
  187685. return;
  187686. }
  187687. break;
  187688. }
  187689. }
  187690. #endif
  187691. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  187692. png_error(png_ptr, "Invalid attempt to read row data");
  187693. png_ptr->zstream.next_out = png_ptr->row_buf;
  187694. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  187695. do
  187696. {
  187697. if (!(png_ptr->zstream.avail_in))
  187698. {
  187699. while (!png_ptr->idat_size)
  187700. {
  187701. png_byte chunk_length[4];
  187702. png_crc_finish(png_ptr, 0);
  187703. png_read_data(png_ptr, chunk_length, 4);
  187704. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  187705. png_reset_crc(png_ptr);
  187706. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187707. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187708. png_error(png_ptr, "Not enough image data");
  187709. }
  187710. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  187711. png_ptr->zstream.next_in = png_ptr->zbuf;
  187712. if (png_ptr->zbuf_size > png_ptr->idat_size)
  187713. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  187714. png_crc_read(png_ptr, png_ptr->zbuf,
  187715. (png_size_t)png_ptr->zstream.avail_in);
  187716. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  187717. }
  187718. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  187719. if (ret == Z_STREAM_END)
  187720. {
  187721. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  187722. png_ptr->idat_size)
  187723. png_error(png_ptr, "Extra compressed data");
  187724. png_ptr->mode |= PNG_AFTER_IDAT;
  187725. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  187726. break;
  187727. }
  187728. if (ret != Z_OK)
  187729. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  187730. "Decompression error");
  187731. } while (png_ptr->zstream.avail_out);
  187732. png_ptr->row_info.color_type = png_ptr->color_type;
  187733. png_ptr->row_info.width = png_ptr->iwidth;
  187734. png_ptr->row_info.channels = png_ptr->channels;
  187735. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  187736. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  187737. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  187738. png_ptr->row_info.width);
  187739. if(png_ptr->row_buf[0])
  187740. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  187741. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  187742. (int)(png_ptr->row_buf[0]));
  187743. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  187744. png_ptr->rowbytes + 1);
  187745. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  187746. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  187747. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  187748. {
  187749. /* Intrapixel differencing */
  187750. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187751. }
  187752. #endif
  187753. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  187754. png_do_read_transformations(png_ptr);
  187755. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187756. /* blow up interlaced rows to full size */
  187757. if (png_ptr->interlaced &&
  187758. (png_ptr->transformations & PNG_INTERLACE))
  187759. {
  187760. if (png_ptr->pass < 6)
  187761. /* old interface (pre-1.0.9):
  187762. png_do_read_interlace(&(png_ptr->row_info),
  187763. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  187764. */
  187765. png_do_read_interlace(png_ptr);
  187766. if (dsp_row != NULL)
  187767. png_combine_row(png_ptr, dsp_row,
  187768. png_pass_dsp_mask[png_ptr->pass]);
  187769. if (row != NULL)
  187770. png_combine_row(png_ptr, row,
  187771. png_pass_mask[png_ptr->pass]);
  187772. }
  187773. else
  187774. #endif
  187775. {
  187776. if (row != NULL)
  187777. png_combine_row(png_ptr, row, 0xff);
  187778. if (dsp_row != NULL)
  187779. png_combine_row(png_ptr, dsp_row, 0xff);
  187780. }
  187781. png_read_finish_row(png_ptr);
  187782. if (png_ptr->read_row_fn != NULL)
  187783. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  187784. }
  187785. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187786. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187787. /* Read one or more rows of image data. If the image is interlaced,
  187788. * and png_set_interlace_handling() has been called, the rows need to
  187789. * contain the contents of the rows from the previous pass. If the
  187790. * image has alpha or transparency, and png_handle_alpha()[*] has been
  187791. * called, the rows contents must be initialized to the contents of the
  187792. * screen.
  187793. *
  187794. * "row" holds the actual image, and pixels are placed in it
  187795. * as they arrive. If the image is displayed after each pass, it will
  187796. * appear to "sparkle" in. "display_row" can be used to display a
  187797. * "chunky" progressive image, with finer detail added as it becomes
  187798. * available. If you do not want this "chunky" display, you may pass
  187799. * NULL for display_row. If you do not want the sparkle display, and
  187800. * you have not called png_handle_alpha(), you may pass NULL for rows.
  187801. * If you have called png_handle_alpha(), and the image has either an
  187802. * alpha channel or a transparency chunk, you must provide a buffer for
  187803. * rows. In this case, you do not have to provide a display_row buffer
  187804. * also, but you may. If the image is not interlaced, or if you have
  187805. * not called png_set_interlace_handling(), the display_row buffer will
  187806. * be ignored, so pass NULL to it.
  187807. *
  187808. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  187809. */
  187810. void PNGAPI
  187811. png_read_rows(png_structp png_ptr, png_bytepp row,
  187812. png_bytepp display_row, png_uint_32 num_rows)
  187813. {
  187814. png_uint_32 i;
  187815. png_bytepp rp;
  187816. png_bytepp dp;
  187817. png_debug(1, "in png_read_rows\n");
  187818. if(png_ptr == NULL) return;
  187819. rp = row;
  187820. dp = display_row;
  187821. if (rp != NULL && dp != NULL)
  187822. for (i = 0; i < num_rows; i++)
  187823. {
  187824. png_bytep rptr = *rp++;
  187825. png_bytep dptr = *dp++;
  187826. png_read_row(png_ptr, rptr, dptr);
  187827. }
  187828. else if(rp != NULL)
  187829. for (i = 0; i < num_rows; i++)
  187830. {
  187831. png_bytep rptr = *rp;
  187832. png_read_row(png_ptr, rptr, png_bytep_NULL);
  187833. rp++;
  187834. }
  187835. else if(dp != NULL)
  187836. for (i = 0; i < num_rows; i++)
  187837. {
  187838. png_bytep dptr = *dp;
  187839. png_read_row(png_ptr, png_bytep_NULL, dptr);
  187840. dp++;
  187841. }
  187842. }
  187843. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187844. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187845. /* Read the entire image. If the image has an alpha channel or a tRNS
  187846. * chunk, and you have called png_handle_alpha()[*], you will need to
  187847. * initialize the image to the current image that PNG will be overlaying.
  187848. * We set the num_rows again here, in case it was incorrectly set in
  187849. * png_read_start_row() by a call to png_read_update_info() or
  187850. * png_start_read_image() if png_set_interlace_handling() wasn't called
  187851. * prior to either of these functions like it should have been. You can
  187852. * only call this function once. If you desire to have an image for
  187853. * each pass of a interlaced image, use png_read_rows() instead.
  187854. *
  187855. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  187856. */
  187857. void PNGAPI
  187858. png_read_image(png_structp png_ptr, png_bytepp image)
  187859. {
  187860. png_uint_32 i,image_height;
  187861. int pass, j;
  187862. png_bytepp rp;
  187863. png_debug(1, "in png_read_image\n");
  187864. if(png_ptr == NULL) return;
  187865. #ifdef PNG_READ_INTERLACING_SUPPORTED
  187866. pass = png_set_interlace_handling(png_ptr);
  187867. #else
  187868. if (png_ptr->interlaced)
  187869. png_error(png_ptr,
  187870. "Cannot read interlaced image -- interlace handler disabled.");
  187871. pass = 1;
  187872. #endif
  187873. image_height=png_ptr->height;
  187874. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  187875. for (j = 0; j < pass; j++)
  187876. {
  187877. rp = image;
  187878. for (i = 0; i < image_height; i++)
  187879. {
  187880. png_read_row(png_ptr, *rp, png_bytep_NULL);
  187881. rp++;
  187882. }
  187883. }
  187884. }
  187885. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187886. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187887. /* Read the end of the PNG file. Will not read past the end of the
  187888. * file, will verify the end is accurate, and will read any comments
  187889. * or time information at the end of the file, if info is not NULL.
  187890. */
  187891. void PNGAPI
  187892. png_read_end(png_structp png_ptr, png_infop info_ptr)
  187893. {
  187894. png_byte chunk_length[4];
  187895. png_uint_32 length;
  187896. png_debug(1, "in png_read_end\n");
  187897. if(png_ptr == NULL) return;
  187898. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  187899. do
  187900. {
  187901. #ifdef PNG_USE_LOCAL_ARRAYS
  187902. PNG_CONST PNG_IHDR;
  187903. PNG_CONST PNG_IDAT;
  187904. PNG_CONST PNG_IEND;
  187905. PNG_CONST PNG_PLTE;
  187906. #if defined(PNG_READ_bKGD_SUPPORTED)
  187907. PNG_CONST PNG_bKGD;
  187908. #endif
  187909. #if defined(PNG_READ_cHRM_SUPPORTED)
  187910. PNG_CONST PNG_cHRM;
  187911. #endif
  187912. #if defined(PNG_READ_gAMA_SUPPORTED)
  187913. PNG_CONST PNG_gAMA;
  187914. #endif
  187915. #if defined(PNG_READ_hIST_SUPPORTED)
  187916. PNG_CONST PNG_hIST;
  187917. #endif
  187918. #if defined(PNG_READ_iCCP_SUPPORTED)
  187919. PNG_CONST PNG_iCCP;
  187920. #endif
  187921. #if defined(PNG_READ_iTXt_SUPPORTED)
  187922. PNG_CONST PNG_iTXt;
  187923. #endif
  187924. #if defined(PNG_READ_oFFs_SUPPORTED)
  187925. PNG_CONST PNG_oFFs;
  187926. #endif
  187927. #if defined(PNG_READ_pCAL_SUPPORTED)
  187928. PNG_CONST PNG_pCAL;
  187929. #endif
  187930. #if defined(PNG_READ_pHYs_SUPPORTED)
  187931. PNG_CONST PNG_pHYs;
  187932. #endif
  187933. #if defined(PNG_READ_sBIT_SUPPORTED)
  187934. PNG_CONST PNG_sBIT;
  187935. #endif
  187936. #if defined(PNG_READ_sCAL_SUPPORTED)
  187937. PNG_CONST PNG_sCAL;
  187938. #endif
  187939. #if defined(PNG_READ_sPLT_SUPPORTED)
  187940. PNG_CONST PNG_sPLT;
  187941. #endif
  187942. #if defined(PNG_READ_sRGB_SUPPORTED)
  187943. PNG_CONST PNG_sRGB;
  187944. #endif
  187945. #if defined(PNG_READ_tEXt_SUPPORTED)
  187946. PNG_CONST PNG_tEXt;
  187947. #endif
  187948. #if defined(PNG_READ_tIME_SUPPORTED)
  187949. PNG_CONST PNG_tIME;
  187950. #endif
  187951. #if defined(PNG_READ_tRNS_SUPPORTED)
  187952. PNG_CONST PNG_tRNS;
  187953. #endif
  187954. #if defined(PNG_READ_zTXt_SUPPORTED)
  187955. PNG_CONST PNG_zTXt;
  187956. #endif
  187957. #endif /* PNG_USE_LOCAL_ARRAYS */
  187958. png_read_data(png_ptr, chunk_length, 4);
  187959. length = png_get_uint_31(png_ptr,chunk_length);
  187960. png_reset_crc(png_ptr);
  187961. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187962. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  187963. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187964. png_handle_IHDR(png_ptr, info_ptr, length);
  187965. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187966. png_handle_IEND(png_ptr, info_ptr, length);
  187967. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187968. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187969. {
  187970. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187971. {
  187972. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187973. png_error(png_ptr, "Too many IDAT's found");
  187974. }
  187975. png_handle_unknown(png_ptr, info_ptr, length);
  187976. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187977. png_ptr->mode |= PNG_HAVE_PLTE;
  187978. }
  187979. #endif
  187980. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187981. {
  187982. /* Zero length IDATs are legal after the last IDAT has been
  187983. * read, but not after other chunks have been read.
  187984. */
  187985. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  187986. png_error(png_ptr, "Too many IDAT's found");
  187987. png_crc_finish(png_ptr, length);
  187988. }
  187989. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187990. png_handle_PLTE(png_ptr, info_ptr, length);
  187991. #if defined(PNG_READ_bKGD_SUPPORTED)
  187992. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187993. png_handle_bKGD(png_ptr, info_ptr, length);
  187994. #endif
  187995. #if defined(PNG_READ_cHRM_SUPPORTED)
  187996. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187997. png_handle_cHRM(png_ptr, info_ptr, length);
  187998. #endif
  187999. #if defined(PNG_READ_gAMA_SUPPORTED)
  188000. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  188001. png_handle_gAMA(png_ptr, info_ptr, length);
  188002. #endif
  188003. #if defined(PNG_READ_hIST_SUPPORTED)
  188004. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  188005. png_handle_hIST(png_ptr, info_ptr, length);
  188006. #endif
  188007. #if defined(PNG_READ_oFFs_SUPPORTED)
  188008. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  188009. png_handle_oFFs(png_ptr, info_ptr, length);
  188010. #endif
  188011. #if defined(PNG_READ_pCAL_SUPPORTED)
  188012. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  188013. png_handle_pCAL(png_ptr, info_ptr, length);
  188014. #endif
  188015. #if defined(PNG_READ_sCAL_SUPPORTED)
  188016. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  188017. png_handle_sCAL(png_ptr, info_ptr, length);
  188018. #endif
  188019. #if defined(PNG_READ_pHYs_SUPPORTED)
  188020. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  188021. png_handle_pHYs(png_ptr, info_ptr, length);
  188022. #endif
  188023. #if defined(PNG_READ_sBIT_SUPPORTED)
  188024. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  188025. png_handle_sBIT(png_ptr, info_ptr, length);
  188026. #endif
  188027. #if defined(PNG_READ_sRGB_SUPPORTED)
  188028. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  188029. png_handle_sRGB(png_ptr, info_ptr, length);
  188030. #endif
  188031. #if defined(PNG_READ_iCCP_SUPPORTED)
  188032. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  188033. png_handle_iCCP(png_ptr, info_ptr, length);
  188034. #endif
  188035. #if defined(PNG_READ_sPLT_SUPPORTED)
  188036. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  188037. png_handle_sPLT(png_ptr, info_ptr, length);
  188038. #endif
  188039. #if defined(PNG_READ_tEXt_SUPPORTED)
  188040. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  188041. png_handle_tEXt(png_ptr, info_ptr, length);
  188042. #endif
  188043. #if defined(PNG_READ_tIME_SUPPORTED)
  188044. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  188045. png_handle_tIME(png_ptr, info_ptr, length);
  188046. #endif
  188047. #if defined(PNG_READ_tRNS_SUPPORTED)
  188048. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188049. png_handle_tRNS(png_ptr, info_ptr, length);
  188050. #endif
  188051. #if defined(PNG_READ_zTXt_SUPPORTED)
  188052. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  188053. png_handle_zTXt(png_ptr, info_ptr, length);
  188054. #endif
  188055. #if defined(PNG_READ_iTXt_SUPPORTED)
  188056. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  188057. png_handle_iTXt(png_ptr, info_ptr, length);
  188058. #endif
  188059. else
  188060. png_handle_unknown(png_ptr, info_ptr, length);
  188061. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  188062. }
  188063. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188064. /* free all memory used by the read */
  188065. void PNGAPI
  188066. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  188067. png_infopp end_info_ptr_ptr)
  188068. {
  188069. png_structp png_ptr = NULL;
  188070. png_infop info_ptr = NULL, end_info_ptr = NULL;
  188071. #ifdef PNG_USER_MEM_SUPPORTED
  188072. png_free_ptr free_fn;
  188073. png_voidp mem_ptr;
  188074. #endif
  188075. png_debug(1, "in png_destroy_read_struct\n");
  188076. if (png_ptr_ptr != NULL)
  188077. png_ptr = *png_ptr_ptr;
  188078. if (info_ptr_ptr != NULL)
  188079. info_ptr = *info_ptr_ptr;
  188080. if (end_info_ptr_ptr != NULL)
  188081. end_info_ptr = *end_info_ptr_ptr;
  188082. #ifdef PNG_USER_MEM_SUPPORTED
  188083. free_fn = png_ptr->free_fn;
  188084. mem_ptr = png_ptr->mem_ptr;
  188085. #endif
  188086. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  188087. if (info_ptr != NULL)
  188088. {
  188089. #if defined(PNG_TEXT_SUPPORTED)
  188090. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  188091. #endif
  188092. #ifdef PNG_USER_MEM_SUPPORTED
  188093. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  188094. (png_voidp)mem_ptr);
  188095. #else
  188096. png_destroy_struct((png_voidp)info_ptr);
  188097. #endif
  188098. *info_ptr_ptr = NULL;
  188099. }
  188100. if (end_info_ptr != NULL)
  188101. {
  188102. #if defined(PNG_READ_TEXT_SUPPORTED)
  188103. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  188104. #endif
  188105. #ifdef PNG_USER_MEM_SUPPORTED
  188106. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  188107. (png_voidp)mem_ptr);
  188108. #else
  188109. png_destroy_struct((png_voidp)end_info_ptr);
  188110. #endif
  188111. *end_info_ptr_ptr = NULL;
  188112. }
  188113. if (png_ptr != NULL)
  188114. {
  188115. #ifdef PNG_USER_MEM_SUPPORTED
  188116. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  188117. (png_voidp)mem_ptr);
  188118. #else
  188119. png_destroy_struct((png_voidp)png_ptr);
  188120. #endif
  188121. *png_ptr_ptr = NULL;
  188122. }
  188123. }
  188124. /* free all memory used by the read (old method) */
  188125. void /* PRIVATE */
  188126. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  188127. {
  188128. #ifdef PNG_SETJMP_SUPPORTED
  188129. jmp_buf tmp_jmp;
  188130. #endif
  188131. png_error_ptr error_fn;
  188132. png_error_ptr warning_fn;
  188133. png_voidp error_ptr;
  188134. #ifdef PNG_USER_MEM_SUPPORTED
  188135. png_free_ptr free_fn;
  188136. #endif
  188137. png_debug(1, "in png_read_destroy\n");
  188138. if (info_ptr != NULL)
  188139. png_info_destroy(png_ptr, info_ptr);
  188140. if (end_info_ptr != NULL)
  188141. png_info_destroy(png_ptr, end_info_ptr);
  188142. png_free(png_ptr, png_ptr->zbuf);
  188143. png_free(png_ptr, png_ptr->big_row_buf);
  188144. png_free(png_ptr, png_ptr->prev_row);
  188145. #if defined(PNG_READ_DITHER_SUPPORTED)
  188146. png_free(png_ptr, png_ptr->palette_lookup);
  188147. png_free(png_ptr, png_ptr->dither_index);
  188148. #endif
  188149. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188150. png_free(png_ptr, png_ptr->gamma_table);
  188151. #endif
  188152. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188153. png_free(png_ptr, png_ptr->gamma_from_1);
  188154. png_free(png_ptr, png_ptr->gamma_to_1);
  188155. #endif
  188156. #ifdef PNG_FREE_ME_SUPPORTED
  188157. if (png_ptr->free_me & PNG_FREE_PLTE)
  188158. png_zfree(png_ptr, png_ptr->palette);
  188159. png_ptr->free_me &= ~PNG_FREE_PLTE;
  188160. #else
  188161. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  188162. png_zfree(png_ptr, png_ptr->palette);
  188163. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  188164. #endif
  188165. #if defined(PNG_tRNS_SUPPORTED) || \
  188166. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  188167. #ifdef PNG_FREE_ME_SUPPORTED
  188168. if (png_ptr->free_me & PNG_FREE_TRNS)
  188169. png_free(png_ptr, png_ptr->trans);
  188170. png_ptr->free_me &= ~PNG_FREE_TRNS;
  188171. #else
  188172. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  188173. png_free(png_ptr, png_ptr->trans);
  188174. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  188175. #endif
  188176. #endif
  188177. #if defined(PNG_READ_hIST_SUPPORTED)
  188178. #ifdef PNG_FREE_ME_SUPPORTED
  188179. if (png_ptr->free_me & PNG_FREE_HIST)
  188180. png_free(png_ptr, png_ptr->hist);
  188181. png_ptr->free_me &= ~PNG_FREE_HIST;
  188182. #else
  188183. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  188184. png_free(png_ptr, png_ptr->hist);
  188185. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  188186. #endif
  188187. #endif
  188188. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188189. if (png_ptr->gamma_16_table != NULL)
  188190. {
  188191. int i;
  188192. int istop = (1 << (8 - png_ptr->gamma_shift));
  188193. for (i = 0; i < istop; i++)
  188194. {
  188195. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  188196. }
  188197. png_free(png_ptr, png_ptr->gamma_16_table);
  188198. }
  188199. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188200. if (png_ptr->gamma_16_from_1 != NULL)
  188201. {
  188202. int i;
  188203. int istop = (1 << (8 - png_ptr->gamma_shift));
  188204. for (i = 0; i < istop; i++)
  188205. {
  188206. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  188207. }
  188208. png_free(png_ptr, png_ptr->gamma_16_from_1);
  188209. }
  188210. if (png_ptr->gamma_16_to_1 != NULL)
  188211. {
  188212. int i;
  188213. int istop = (1 << (8 - png_ptr->gamma_shift));
  188214. for (i = 0; i < istop; i++)
  188215. {
  188216. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  188217. }
  188218. png_free(png_ptr, png_ptr->gamma_16_to_1);
  188219. }
  188220. #endif
  188221. #endif
  188222. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  188223. png_free(png_ptr, png_ptr->time_buffer);
  188224. #endif
  188225. inflateEnd(&png_ptr->zstream);
  188226. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188227. png_free(png_ptr, png_ptr->save_buffer);
  188228. #endif
  188229. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188230. #ifdef PNG_TEXT_SUPPORTED
  188231. png_free(png_ptr, png_ptr->current_text);
  188232. #endif /* PNG_TEXT_SUPPORTED */
  188233. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  188234. /* Save the important info out of the png_struct, in case it is
  188235. * being used again.
  188236. */
  188237. #ifdef PNG_SETJMP_SUPPORTED
  188238. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  188239. #endif
  188240. error_fn = png_ptr->error_fn;
  188241. warning_fn = png_ptr->warning_fn;
  188242. error_ptr = png_ptr->error_ptr;
  188243. #ifdef PNG_USER_MEM_SUPPORTED
  188244. free_fn = png_ptr->free_fn;
  188245. #endif
  188246. png_memset(png_ptr, 0, png_sizeof (png_struct));
  188247. png_ptr->error_fn = error_fn;
  188248. png_ptr->warning_fn = warning_fn;
  188249. png_ptr->error_ptr = error_ptr;
  188250. #ifdef PNG_USER_MEM_SUPPORTED
  188251. png_ptr->free_fn = free_fn;
  188252. #endif
  188253. #ifdef PNG_SETJMP_SUPPORTED
  188254. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  188255. #endif
  188256. }
  188257. void PNGAPI
  188258. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  188259. {
  188260. if(png_ptr == NULL) return;
  188261. png_ptr->read_row_fn = read_row_fn;
  188262. }
  188263. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188264. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  188265. void PNGAPI
  188266. png_read_png(png_structp png_ptr, png_infop info_ptr,
  188267. int transforms,
  188268. voidp params)
  188269. {
  188270. int row;
  188271. if(png_ptr == NULL) return;
  188272. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  188273. /* invert the alpha channel from opacity to transparency
  188274. */
  188275. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  188276. png_set_invert_alpha(png_ptr);
  188277. #endif
  188278. /* png_read_info() gives us all of the information from the
  188279. * PNG file before the first IDAT (image data chunk).
  188280. */
  188281. png_read_info(png_ptr, info_ptr);
  188282. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  188283. png_error(png_ptr,"Image is too high to process with png_read_png()");
  188284. /* -------------- image transformations start here ------------------- */
  188285. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  188286. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  188287. */
  188288. if (transforms & PNG_TRANSFORM_STRIP_16)
  188289. png_set_strip_16(png_ptr);
  188290. #endif
  188291. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  188292. /* Strip alpha bytes from the input data without combining with
  188293. * the background (not recommended).
  188294. */
  188295. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  188296. png_set_strip_alpha(png_ptr);
  188297. #endif
  188298. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  188299. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  188300. * byte into separate bytes (useful for paletted and grayscale images).
  188301. */
  188302. if (transforms & PNG_TRANSFORM_PACKING)
  188303. png_set_packing(png_ptr);
  188304. #endif
  188305. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  188306. /* Change the order of packed pixels to least significant bit first
  188307. * (not useful if you are using png_set_packing).
  188308. */
  188309. if (transforms & PNG_TRANSFORM_PACKSWAP)
  188310. png_set_packswap(png_ptr);
  188311. #endif
  188312. #if defined(PNG_READ_EXPAND_SUPPORTED)
  188313. /* Expand paletted colors into true RGB triplets
  188314. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  188315. * Expand paletted or RGB images with transparency to full alpha
  188316. * channels so the data will be available as RGBA quartets.
  188317. */
  188318. if (transforms & PNG_TRANSFORM_EXPAND)
  188319. if ((png_ptr->bit_depth < 8) ||
  188320. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  188321. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  188322. png_set_expand(png_ptr);
  188323. #endif
  188324. /* We don't handle background color or gamma transformation or dithering.
  188325. */
  188326. #if defined(PNG_READ_INVERT_SUPPORTED)
  188327. /* invert monochrome files to have 0 as white and 1 as black
  188328. */
  188329. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  188330. png_set_invert_mono(png_ptr);
  188331. #endif
  188332. #if defined(PNG_READ_SHIFT_SUPPORTED)
  188333. /* If you want to shift the pixel values from the range [0,255] or
  188334. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  188335. * colors were originally in:
  188336. */
  188337. if ((transforms & PNG_TRANSFORM_SHIFT)
  188338. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  188339. {
  188340. png_color_8p sig_bit;
  188341. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  188342. png_set_shift(png_ptr, sig_bit);
  188343. }
  188344. #endif
  188345. #if defined(PNG_READ_BGR_SUPPORTED)
  188346. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  188347. */
  188348. if (transforms & PNG_TRANSFORM_BGR)
  188349. png_set_bgr(png_ptr);
  188350. #endif
  188351. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  188352. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  188353. */
  188354. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  188355. png_set_swap_alpha(png_ptr);
  188356. #endif
  188357. #if defined(PNG_READ_SWAP_SUPPORTED)
  188358. /* swap bytes of 16 bit files to least significant byte first
  188359. */
  188360. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  188361. png_set_swap(png_ptr);
  188362. #endif
  188363. /* We don't handle adding filler bytes */
  188364. /* Optional call to gamma correct and add the background to the palette
  188365. * and update info structure. REQUIRED if you are expecting libpng to
  188366. * update the palette for you (i.e., you selected such a transform above).
  188367. */
  188368. png_read_update_info(png_ptr, info_ptr);
  188369. /* -------------- image transformations end here ------------------- */
  188370. #ifdef PNG_FREE_ME_SUPPORTED
  188371. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  188372. #endif
  188373. if(info_ptr->row_pointers == NULL)
  188374. {
  188375. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  188376. info_ptr->height * png_sizeof(png_bytep));
  188377. #ifdef PNG_FREE_ME_SUPPORTED
  188378. info_ptr->free_me |= PNG_FREE_ROWS;
  188379. #endif
  188380. for (row = 0; row < (int)info_ptr->height; row++)
  188381. {
  188382. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  188383. png_get_rowbytes(png_ptr, info_ptr));
  188384. }
  188385. }
  188386. png_read_image(png_ptr, info_ptr->row_pointers);
  188387. info_ptr->valid |= PNG_INFO_IDAT;
  188388. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  188389. png_read_end(png_ptr, info_ptr);
  188390. transforms = transforms; /* quiet compiler warnings */
  188391. params = params;
  188392. }
  188393. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  188394. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188395. #endif /* PNG_READ_SUPPORTED */
  188396. /*** End of inlined file: pngread.c ***/
  188397. /*** Start of inlined file: pngpread.c ***/
  188398. /* pngpread.c - read a png file in push mode
  188399. *
  188400. * Last changed in libpng 1.2.21 October 4, 2007
  188401. * For conditions of distribution and use, see copyright notice in png.h
  188402. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  188403. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  188404. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  188405. */
  188406. #define PNG_INTERNAL
  188407. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188408. /* push model modes */
  188409. #define PNG_READ_SIG_MODE 0
  188410. #define PNG_READ_CHUNK_MODE 1
  188411. #define PNG_READ_IDAT_MODE 2
  188412. #define PNG_SKIP_MODE 3
  188413. #define PNG_READ_tEXt_MODE 4
  188414. #define PNG_READ_zTXt_MODE 5
  188415. #define PNG_READ_DONE_MODE 6
  188416. #define PNG_READ_iTXt_MODE 7
  188417. #define PNG_ERROR_MODE 8
  188418. void PNGAPI
  188419. png_process_data(png_structp png_ptr, png_infop info_ptr,
  188420. png_bytep buffer, png_size_t buffer_size)
  188421. {
  188422. if(png_ptr == NULL) return;
  188423. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  188424. while (png_ptr->buffer_size)
  188425. {
  188426. png_process_some_data(png_ptr, info_ptr);
  188427. }
  188428. }
  188429. /* What we do with the incoming data depends on what we were previously
  188430. * doing before we ran out of data...
  188431. */
  188432. void /* PRIVATE */
  188433. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  188434. {
  188435. if(png_ptr == NULL) return;
  188436. switch (png_ptr->process_mode)
  188437. {
  188438. case PNG_READ_SIG_MODE:
  188439. {
  188440. png_push_read_sig(png_ptr, info_ptr);
  188441. break;
  188442. }
  188443. case PNG_READ_CHUNK_MODE:
  188444. {
  188445. png_push_read_chunk(png_ptr, info_ptr);
  188446. break;
  188447. }
  188448. case PNG_READ_IDAT_MODE:
  188449. {
  188450. png_push_read_IDAT(png_ptr);
  188451. break;
  188452. }
  188453. #if defined(PNG_READ_tEXt_SUPPORTED)
  188454. case PNG_READ_tEXt_MODE:
  188455. {
  188456. png_push_read_tEXt(png_ptr, info_ptr);
  188457. break;
  188458. }
  188459. #endif
  188460. #if defined(PNG_READ_zTXt_SUPPORTED)
  188461. case PNG_READ_zTXt_MODE:
  188462. {
  188463. png_push_read_zTXt(png_ptr, info_ptr);
  188464. break;
  188465. }
  188466. #endif
  188467. #if defined(PNG_READ_iTXt_SUPPORTED)
  188468. case PNG_READ_iTXt_MODE:
  188469. {
  188470. png_push_read_iTXt(png_ptr, info_ptr);
  188471. break;
  188472. }
  188473. #endif
  188474. case PNG_SKIP_MODE:
  188475. {
  188476. png_push_crc_finish(png_ptr);
  188477. break;
  188478. }
  188479. default:
  188480. {
  188481. png_ptr->buffer_size = 0;
  188482. break;
  188483. }
  188484. }
  188485. }
  188486. /* Read any remaining signature bytes from the stream and compare them with
  188487. * the correct PNG signature. It is possible that this routine is called
  188488. * with bytes already read from the signature, either because they have been
  188489. * checked by the calling application, or because of multiple calls to this
  188490. * routine.
  188491. */
  188492. void /* PRIVATE */
  188493. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  188494. {
  188495. png_size_t num_checked = png_ptr->sig_bytes,
  188496. num_to_check = 8 - num_checked;
  188497. if (png_ptr->buffer_size < num_to_check)
  188498. {
  188499. num_to_check = png_ptr->buffer_size;
  188500. }
  188501. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  188502. num_to_check);
  188503. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  188504. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  188505. {
  188506. if (num_checked < 4 &&
  188507. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  188508. png_error(png_ptr, "Not a PNG file");
  188509. else
  188510. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  188511. }
  188512. else
  188513. {
  188514. if (png_ptr->sig_bytes >= 8)
  188515. {
  188516. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188517. }
  188518. }
  188519. }
  188520. void /* PRIVATE */
  188521. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  188522. {
  188523. #ifdef PNG_USE_LOCAL_ARRAYS
  188524. PNG_CONST PNG_IHDR;
  188525. PNG_CONST PNG_IDAT;
  188526. PNG_CONST PNG_IEND;
  188527. PNG_CONST PNG_PLTE;
  188528. #if defined(PNG_READ_bKGD_SUPPORTED)
  188529. PNG_CONST PNG_bKGD;
  188530. #endif
  188531. #if defined(PNG_READ_cHRM_SUPPORTED)
  188532. PNG_CONST PNG_cHRM;
  188533. #endif
  188534. #if defined(PNG_READ_gAMA_SUPPORTED)
  188535. PNG_CONST PNG_gAMA;
  188536. #endif
  188537. #if defined(PNG_READ_hIST_SUPPORTED)
  188538. PNG_CONST PNG_hIST;
  188539. #endif
  188540. #if defined(PNG_READ_iCCP_SUPPORTED)
  188541. PNG_CONST PNG_iCCP;
  188542. #endif
  188543. #if defined(PNG_READ_iTXt_SUPPORTED)
  188544. PNG_CONST PNG_iTXt;
  188545. #endif
  188546. #if defined(PNG_READ_oFFs_SUPPORTED)
  188547. PNG_CONST PNG_oFFs;
  188548. #endif
  188549. #if defined(PNG_READ_pCAL_SUPPORTED)
  188550. PNG_CONST PNG_pCAL;
  188551. #endif
  188552. #if defined(PNG_READ_pHYs_SUPPORTED)
  188553. PNG_CONST PNG_pHYs;
  188554. #endif
  188555. #if defined(PNG_READ_sBIT_SUPPORTED)
  188556. PNG_CONST PNG_sBIT;
  188557. #endif
  188558. #if defined(PNG_READ_sCAL_SUPPORTED)
  188559. PNG_CONST PNG_sCAL;
  188560. #endif
  188561. #if defined(PNG_READ_sRGB_SUPPORTED)
  188562. PNG_CONST PNG_sRGB;
  188563. #endif
  188564. #if defined(PNG_READ_sPLT_SUPPORTED)
  188565. PNG_CONST PNG_sPLT;
  188566. #endif
  188567. #if defined(PNG_READ_tEXt_SUPPORTED)
  188568. PNG_CONST PNG_tEXt;
  188569. #endif
  188570. #if defined(PNG_READ_tIME_SUPPORTED)
  188571. PNG_CONST PNG_tIME;
  188572. #endif
  188573. #if defined(PNG_READ_tRNS_SUPPORTED)
  188574. PNG_CONST PNG_tRNS;
  188575. #endif
  188576. #if defined(PNG_READ_zTXt_SUPPORTED)
  188577. PNG_CONST PNG_zTXt;
  188578. #endif
  188579. #endif /* PNG_USE_LOCAL_ARRAYS */
  188580. /* First we make sure we have enough data for the 4 byte chunk name
  188581. * and the 4 byte chunk length before proceeding with decoding the
  188582. * chunk data. To fully decode each of these chunks, we also make
  188583. * sure we have enough data in the buffer for the 4 byte CRC at the
  188584. * end of every chunk (except IDAT, which is handled separately).
  188585. */
  188586. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188587. {
  188588. png_byte chunk_length[4];
  188589. if (png_ptr->buffer_size < 8)
  188590. {
  188591. png_push_save_buffer(png_ptr);
  188592. return;
  188593. }
  188594. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188595. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188596. png_reset_crc(png_ptr);
  188597. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188598. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188599. }
  188600. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188601. if(png_ptr->mode & PNG_AFTER_IDAT)
  188602. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  188603. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  188604. {
  188605. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188606. {
  188607. png_push_save_buffer(png_ptr);
  188608. return;
  188609. }
  188610. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  188611. }
  188612. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  188613. {
  188614. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188615. {
  188616. png_push_save_buffer(png_ptr);
  188617. return;
  188618. }
  188619. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  188620. png_ptr->process_mode = PNG_READ_DONE_MODE;
  188621. png_push_have_end(png_ptr, info_ptr);
  188622. }
  188623. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  188624. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  188625. {
  188626. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188627. {
  188628. png_push_save_buffer(png_ptr);
  188629. return;
  188630. }
  188631. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188632. png_ptr->mode |= PNG_HAVE_IDAT;
  188633. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188634. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188635. png_ptr->mode |= PNG_HAVE_PLTE;
  188636. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188637. {
  188638. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188639. png_error(png_ptr, "Missing IHDR before IDAT");
  188640. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188641. !(png_ptr->mode & PNG_HAVE_PLTE))
  188642. png_error(png_ptr, "Missing PLTE before IDAT");
  188643. }
  188644. }
  188645. #endif
  188646. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188647. {
  188648. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188649. {
  188650. png_push_save_buffer(png_ptr);
  188651. return;
  188652. }
  188653. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  188654. }
  188655. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188656. {
  188657. /* If we reach an IDAT chunk, this means we have read all of the
  188658. * header chunks, and we can start reading the image (or if this
  188659. * is called after the image has been read - we have an error).
  188660. */
  188661. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188662. png_error(png_ptr, "Missing IHDR before IDAT");
  188663. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188664. !(png_ptr->mode & PNG_HAVE_PLTE))
  188665. png_error(png_ptr, "Missing PLTE before IDAT");
  188666. if (png_ptr->mode & PNG_HAVE_IDAT)
  188667. {
  188668. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188669. if (png_ptr->push_length == 0)
  188670. return;
  188671. if (png_ptr->mode & PNG_AFTER_IDAT)
  188672. png_error(png_ptr, "Too many IDAT's found");
  188673. }
  188674. png_ptr->idat_size = png_ptr->push_length;
  188675. png_ptr->mode |= PNG_HAVE_IDAT;
  188676. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  188677. png_push_have_info(png_ptr, info_ptr);
  188678. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  188679. png_ptr->zstream.next_out = png_ptr->row_buf;
  188680. return;
  188681. }
  188682. #if defined(PNG_READ_gAMA_SUPPORTED)
  188683. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  188684. {
  188685. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188686. {
  188687. png_push_save_buffer(png_ptr);
  188688. return;
  188689. }
  188690. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  188691. }
  188692. #endif
  188693. #if defined(PNG_READ_sBIT_SUPPORTED)
  188694. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  188695. {
  188696. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188697. {
  188698. png_push_save_buffer(png_ptr);
  188699. return;
  188700. }
  188701. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  188702. }
  188703. #endif
  188704. #if defined(PNG_READ_cHRM_SUPPORTED)
  188705. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  188706. {
  188707. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188708. {
  188709. png_push_save_buffer(png_ptr);
  188710. return;
  188711. }
  188712. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  188713. }
  188714. #endif
  188715. #if defined(PNG_READ_sRGB_SUPPORTED)
  188716. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  188717. {
  188718. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188719. {
  188720. png_push_save_buffer(png_ptr);
  188721. return;
  188722. }
  188723. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  188724. }
  188725. #endif
  188726. #if defined(PNG_READ_iCCP_SUPPORTED)
  188727. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  188728. {
  188729. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188730. {
  188731. png_push_save_buffer(png_ptr);
  188732. return;
  188733. }
  188734. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  188735. }
  188736. #endif
  188737. #if defined(PNG_READ_sPLT_SUPPORTED)
  188738. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  188739. {
  188740. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188741. {
  188742. png_push_save_buffer(png_ptr);
  188743. return;
  188744. }
  188745. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  188746. }
  188747. #endif
  188748. #if defined(PNG_READ_tRNS_SUPPORTED)
  188749. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188750. {
  188751. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188752. {
  188753. png_push_save_buffer(png_ptr);
  188754. return;
  188755. }
  188756. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  188757. }
  188758. #endif
  188759. #if defined(PNG_READ_bKGD_SUPPORTED)
  188760. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  188761. {
  188762. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188763. {
  188764. png_push_save_buffer(png_ptr);
  188765. return;
  188766. }
  188767. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  188768. }
  188769. #endif
  188770. #if defined(PNG_READ_hIST_SUPPORTED)
  188771. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  188772. {
  188773. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188774. {
  188775. png_push_save_buffer(png_ptr);
  188776. return;
  188777. }
  188778. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  188779. }
  188780. #endif
  188781. #if defined(PNG_READ_pHYs_SUPPORTED)
  188782. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  188783. {
  188784. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188785. {
  188786. png_push_save_buffer(png_ptr);
  188787. return;
  188788. }
  188789. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  188790. }
  188791. #endif
  188792. #if defined(PNG_READ_oFFs_SUPPORTED)
  188793. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  188794. {
  188795. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188796. {
  188797. png_push_save_buffer(png_ptr);
  188798. return;
  188799. }
  188800. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  188801. }
  188802. #endif
  188803. #if defined(PNG_READ_pCAL_SUPPORTED)
  188804. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  188805. {
  188806. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188807. {
  188808. png_push_save_buffer(png_ptr);
  188809. return;
  188810. }
  188811. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  188812. }
  188813. #endif
  188814. #if defined(PNG_READ_sCAL_SUPPORTED)
  188815. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  188816. {
  188817. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188818. {
  188819. png_push_save_buffer(png_ptr);
  188820. return;
  188821. }
  188822. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  188823. }
  188824. #endif
  188825. #if defined(PNG_READ_tIME_SUPPORTED)
  188826. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  188827. {
  188828. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188829. {
  188830. png_push_save_buffer(png_ptr);
  188831. return;
  188832. }
  188833. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  188834. }
  188835. #endif
  188836. #if defined(PNG_READ_tEXt_SUPPORTED)
  188837. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  188838. {
  188839. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188840. {
  188841. png_push_save_buffer(png_ptr);
  188842. return;
  188843. }
  188844. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  188845. }
  188846. #endif
  188847. #if defined(PNG_READ_zTXt_SUPPORTED)
  188848. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  188849. {
  188850. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188851. {
  188852. png_push_save_buffer(png_ptr);
  188853. return;
  188854. }
  188855. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  188856. }
  188857. #endif
  188858. #if defined(PNG_READ_iTXt_SUPPORTED)
  188859. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  188860. {
  188861. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188862. {
  188863. png_push_save_buffer(png_ptr);
  188864. return;
  188865. }
  188866. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  188867. }
  188868. #endif
  188869. else
  188870. {
  188871. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188872. {
  188873. png_push_save_buffer(png_ptr);
  188874. return;
  188875. }
  188876. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188877. }
  188878. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  188879. }
  188880. void /* PRIVATE */
  188881. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  188882. {
  188883. png_ptr->process_mode = PNG_SKIP_MODE;
  188884. png_ptr->skip_length = skip;
  188885. }
  188886. void /* PRIVATE */
  188887. png_push_crc_finish(png_structp png_ptr)
  188888. {
  188889. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  188890. {
  188891. png_size_t save_size;
  188892. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  188893. save_size = (png_size_t)png_ptr->skip_length;
  188894. else
  188895. save_size = png_ptr->save_buffer_size;
  188896. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  188897. png_ptr->skip_length -= save_size;
  188898. png_ptr->buffer_size -= save_size;
  188899. png_ptr->save_buffer_size -= save_size;
  188900. png_ptr->save_buffer_ptr += save_size;
  188901. }
  188902. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  188903. {
  188904. png_size_t save_size;
  188905. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  188906. save_size = (png_size_t)png_ptr->skip_length;
  188907. else
  188908. save_size = png_ptr->current_buffer_size;
  188909. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  188910. png_ptr->skip_length -= save_size;
  188911. png_ptr->buffer_size -= save_size;
  188912. png_ptr->current_buffer_size -= save_size;
  188913. png_ptr->current_buffer_ptr += save_size;
  188914. }
  188915. if (!png_ptr->skip_length)
  188916. {
  188917. if (png_ptr->buffer_size < 4)
  188918. {
  188919. png_push_save_buffer(png_ptr);
  188920. return;
  188921. }
  188922. png_crc_finish(png_ptr, 0);
  188923. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188924. }
  188925. }
  188926. void PNGAPI
  188927. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  188928. {
  188929. png_bytep ptr;
  188930. if(png_ptr == NULL) return;
  188931. ptr = buffer;
  188932. if (png_ptr->save_buffer_size)
  188933. {
  188934. png_size_t save_size;
  188935. if (length < png_ptr->save_buffer_size)
  188936. save_size = length;
  188937. else
  188938. save_size = png_ptr->save_buffer_size;
  188939. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  188940. length -= save_size;
  188941. ptr += save_size;
  188942. png_ptr->buffer_size -= save_size;
  188943. png_ptr->save_buffer_size -= save_size;
  188944. png_ptr->save_buffer_ptr += save_size;
  188945. }
  188946. if (length && png_ptr->current_buffer_size)
  188947. {
  188948. png_size_t save_size;
  188949. if (length < png_ptr->current_buffer_size)
  188950. save_size = length;
  188951. else
  188952. save_size = png_ptr->current_buffer_size;
  188953. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  188954. png_ptr->buffer_size -= save_size;
  188955. png_ptr->current_buffer_size -= save_size;
  188956. png_ptr->current_buffer_ptr += save_size;
  188957. }
  188958. }
  188959. void /* PRIVATE */
  188960. png_push_save_buffer(png_structp png_ptr)
  188961. {
  188962. if (png_ptr->save_buffer_size)
  188963. {
  188964. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  188965. {
  188966. png_size_t i,istop;
  188967. png_bytep sp;
  188968. png_bytep dp;
  188969. istop = png_ptr->save_buffer_size;
  188970. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  188971. i < istop; i++, sp++, dp++)
  188972. {
  188973. *dp = *sp;
  188974. }
  188975. }
  188976. }
  188977. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  188978. png_ptr->save_buffer_max)
  188979. {
  188980. png_size_t new_max;
  188981. png_bytep old_buffer;
  188982. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  188983. (png_ptr->current_buffer_size + 256))
  188984. {
  188985. png_error(png_ptr, "Potential overflow of save_buffer");
  188986. }
  188987. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  188988. old_buffer = png_ptr->save_buffer;
  188989. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  188990. (png_uint_32)new_max);
  188991. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  188992. png_free(png_ptr, old_buffer);
  188993. png_ptr->save_buffer_max = new_max;
  188994. }
  188995. if (png_ptr->current_buffer_size)
  188996. {
  188997. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  188998. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  188999. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  189000. png_ptr->current_buffer_size = 0;
  189001. }
  189002. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  189003. png_ptr->buffer_size = 0;
  189004. }
  189005. void /* PRIVATE */
  189006. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  189007. png_size_t buffer_length)
  189008. {
  189009. png_ptr->current_buffer = buffer;
  189010. png_ptr->current_buffer_size = buffer_length;
  189011. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  189012. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  189013. }
  189014. void /* PRIVATE */
  189015. png_push_read_IDAT(png_structp png_ptr)
  189016. {
  189017. #ifdef PNG_USE_LOCAL_ARRAYS
  189018. PNG_CONST PNG_IDAT;
  189019. #endif
  189020. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  189021. {
  189022. png_byte chunk_length[4];
  189023. if (png_ptr->buffer_size < 8)
  189024. {
  189025. png_push_save_buffer(png_ptr);
  189026. return;
  189027. }
  189028. png_push_fill_buffer(png_ptr, chunk_length, 4);
  189029. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  189030. png_reset_crc(png_ptr);
  189031. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  189032. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  189033. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  189034. {
  189035. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  189036. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189037. png_error(png_ptr, "Not enough compressed data");
  189038. return;
  189039. }
  189040. png_ptr->idat_size = png_ptr->push_length;
  189041. }
  189042. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  189043. {
  189044. png_size_t save_size;
  189045. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  189046. {
  189047. save_size = (png_size_t)png_ptr->idat_size;
  189048. /* check for overflow */
  189049. if((png_uint_32)save_size != png_ptr->idat_size)
  189050. png_error(png_ptr, "save_size overflowed in pngpread");
  189051. }
  189052. else
  189053. save_size = png_ptr->save_buffer_size;
  189054. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  189055. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189056. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  189057. png_ptr->idat_size -= save_size;
  189058. png_ptr->buffer_size -= save_size;
  189059. png_ptr->save_buffer_size -= save_size;
  189060. png_ptr->save_buffer_ptr += save_size;
  189061. }
  189062. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  189063. {
  189064. png_size_t save_size;
  189065. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  189066. {
  189067. save_size = (png_size_t)png_ptr->idat_size;
  189068. /* check for overflow */
  189069. if((png_uint_32)save_size != png_ptr->idat_size)
  189070. png_error(png_ptr, "save_size overflowed in pngpread");
  189071. }
  189072. else
  189073. save_size = png_ptr->current_buffer_size;
  189074. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  189075. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189076. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  189077. png_ptr->idat_size -= save_size;
  189078. png_ptr->buffer_size -= save_size;
  189079. png_ptr->current_buffer_size -= save_size;
  189080. png_ptr->current_buffer_ptr += save_size;
  189081. }
  189082. if (!png_ptr->idat_size)
  189083. {
  189084. if (png_ptr->buffer_size < 4)
  189085. {
  189086. png_push_save_buffer(png_ptr);
  189087. return;
  189088. }
  189089. png_crc_finish(png_ptr, 0);
  189090. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  189091. png_ptr->mode |= PNG_AFTER_IDAT;
  189092. }
  189093. }
  189094. void /* PRIVATE */
  189095. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  189096. png_size_t buffer_length)
  189097. {
  189098. int ret;
  189099. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  189100. png_error(png_ptr, "Extra compression data");
  189101. png_ptr->zstream.next_in = buffer;
  189102. png_ptr->zstream.avail_in = (uInt)buffer_length;
  189103. for(;;)
  189104. {
  189105. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189106. if (ret != Z_OK)
  189107. {
  189108. if (ret == Z_STREAM_END)
  189109. {
  189110. if (png_ptr->zstream.avail_in)
  189111. png_error(png_ptr, "Extra compressed data");
  189112. if (!(png_ptr->zstream.avail_out))
  189113. {
  189114. png_push_process_row(png_ptr);
  189115. }
  189116. png_ptr->mode |= PNG_AFTER_IDAT;
  189117. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  189118. break;
  189119. }
  189120. else if (ret == Z_BUF_ERROR)
  189121. break;
  189122. else
  189123. png_error(png_ptr, "Decompression Error");
  189124. }
  189125. if (!(png_ptr->zstream.avail_out))
  189126. {
  189127. if ((
  189128. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  189129. png_ptr->interlaced && png_ptr->pass > 6) ||
  189130. (!png_ptr->interlaced &&
  189131. #endif
  189132. png_ptr->row_number == png_ptr->num_rows))
  189133. {
  189134. if (png_ptr->zstream.avail_in)
  189135. {
  189136. png_warning(png_ptr, "Too much data in IDAT chunks");
  189137. }
  189138. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  189139. break;
  189140. }
  189141. png_push_process_row(png_ptr);
  189142. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  189143. png_ptr->zstream.next_out = png_ptr->row_buf;
  189144. }
  189145. else
  189146. break;
  189147. }
  189148. }
  189149. void /* PRIVATE */
  189150. png_push_process_row(png_structp png_ptr)
  189151. {
  189152. png_ptr->row_info.color_type = png_ptr->color_type;
  189153. png_ptr->row_info.width = png_ptr->iwidth;
  189154. png_ptr->row_info.channels = png_ptr->channels;
  189155. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  189156. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  189157. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  189158. png_ptr->row_info.width);
  189159. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  189160. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  189161. (int)(png_ptr->row_buf[0]));
  189162. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  189163. png_ptr->rowbytes + 1);
  189164. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  189165. png_do_read_transformations(png_ptr);
  189166. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  189167. /* blow up interlaced rows to full size */
  189168. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  189169. {
  189170. if (png_ptr->pass < 6)
  189171. /* old interface (pre-1.0.9):
  189172. png_do_read_interlace(&(png_ptr->row_info),
  189173. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  189174. */
  189175. png_do_read_interlace(png_ptr);
  189176. switch (png_ptr->pass)
  189177. {
  189178. case 0:
  189179. {
  189180. int i;
  189181. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  189182. {
  189183. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189184. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  189185. }
  189186. if (png_ptr->pass == 2) /* pass 1 might be empty */
  189187. {
  189188. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189189. {
  189190. png_push_have_row(png_ptr, png_bytep_NULL);
  189191. png_read_push_finish_row(png_ptr);
  189192. }
  189193. }
  189194. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  189195. {
  189196. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189197. {
  189198. png_push_have_row(png_ptr, png_bytep_NULL);
  189199. png_read_push_finish_row(png_ptr);
  189200. }
  189201. }
  189202. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  189203. {
  189204. png_push_have_row(png_ptr, png_bytep_NULL);
  189205. png_read_push_finish_row(png_ptr);
  189206. }
  189207. break;
  189208. }
  189209. case 1:
  189210. {
  189211. int i;
  189212. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  189213. {
  189214. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189215. png_read_push_finish_row(png_ptr);
  189216. }
  189217. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  189218. {
  189219. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189220. {
  189221. png_push_have_row(png_ptr, png_bytep_NULL);
  189222. png_read_push_finish_row(png_ptr);
  189223. }
  189224. }
  189225. break;
  189226. }
  189227. case 2:
  189228. {
  189229. int i;
  189230. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189231. {
  189232. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189233. png_read_push_finish_row(png_ptr);
  189234. }
  189235. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189236. {
  189237. png_push_have_row(png_ptr, png_bytep_NULL);
  189238. png_read_push_finish_row(png_ptr);
  189239. }
  189240. if (png_ptr->pass == 4) /* pass 3 might be empty */
  189241. {
  189242. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189243. {
  189244. png_push_have_row(png_ptr, png_bytep_NULL);
  189245. png_read_push_finish_row(png_ptr);
  189246. }
  189247. }
  189248. break;
  189249. }
  189250. case 3:
  189251. {
  189252. int i;
  189253. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  189254. {
  189255. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189256. png_read_push_finish_row(png_ptr);
  189257. }
  189258. if (png_ptr->pass == 4) /* skip top two generated rows */
  189259. {
  189260. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189261. {
  189262. png_push_have_row(png_ptr, png_bytep_NULL);
  189263. png_read_push_finish_row(png_ptr);
  189264. }
  189265. }
  189266. break;
  189267. }
  189268. case 4:
  189269. {
  189270. int i;
  189271. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189272. {
  189273. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189274. png_read_push_finish_row(png_ptr);
  189275. }
  189276. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189277. {
  189278. png_push_have_row(png_ptr, png_bytep_NULL);
  189279. png_read_push_finish_row(png_ptr);
  189280. }
  189281. if (png_ptr->pass == 6) /* pass 5 might be empty */
  189282. {
  189283. png_push_have_row(png_ptr, png_bytep_NULL);
  189284. png_read_push_finish_row(png_ptr);
  189285. }
  189286. break;
  189287. }
  189288. case 5:
  189289. {
  189290. int i;
  189291. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  189292. {
  189293. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189294. png_read_push_finish_row(png_ptr);
  189295. }
  189296. if (png_ptr->pass == 6) /* skip top generated row */
  189297. {
  189298. png_push_have_row(png_ptr, png_bytep_NULL);
  189299. png_read_push_finish_row(png_ptr);
  189300. }
  189301. break;
  189302. }
  189303. case 6:
  189304. {
  189305. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189306. png_read_push_finish_row(png_ptr);
  189307. if (png_ptr->pass != 6)
  189308. break;
  189309. png_push_have_row(png_ptr, png_bytep_NULL);
  189310. png_read_push_finish_row(png_ptr);
  189311. }
  189312. }
  189313. }
  189314. else
  189315. #endif
  189316. {
  189317. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189318. png_read_push_finish_row(png_ptr);
  189319. }
  189320. }
  189321. void /* PRIVATE */
  189322. png_read_push_finish_row(png_structp png_ptr)
  189323. {
  189324. #ifdef PNG_USE_LOCAL_ARRAYS
  189325. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  189326. /* start of interlace block */
  189327. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  189328. /* offset to next interlace block */
  189329. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  189330. /* start of interlace block in the y direction */
  189331. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  189332. /* offset to next interlace block in the y direction */
  189333. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  189334. /* Height of interlace block. This is not currently used - if you need
  189335. * it, uncomment it here and in png.h
  189336. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  189337. */
  189338. #endif
  189339. png_ptr->row_number++;
  189340. if (png_ptr->row_number < png_ptr->num_rows)
  189341. return;
  189342. if (png_ptr->interlaced)
  189343. {
  189344. png_ptr->row_number = 0;
  189345. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  189346. png_ptr->rowbytes + 1);
  189347. do
  189348. {
  189349. png_ptr->pass++;
  189350. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  189351. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  189352. (png_ptr->pass == 5 && png_ptr->width < 2))
  189353. png_ptr->pass++;
  189354. if (png_ptr->pass > 7)
  189355. png_ptr->pass--;
  189356. if (png_ptr->pass >= 7)
  189357. break;
  189358. png_ptr->iwidth = (png_ptr->width +
  189359. png_pass_inc[png_ptr->pass] - 1 -
  189360. png_pass_start[png_ptr->pass]) /
  189361. png_pass_inc[png_ptr->pass];
  189362. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  189363. png_ptr->iwidth) + 1;
  189364. if (png_ptr->transformations & PNG_INTERLACE)
  189365. break;
  189366. png_ptr->num_rows = (png_ptr->height +
  189367. png_pass_yinc[png_ptr->pass] - 1 -
  189368. png_pass_ystart[png_ptr->pass]) /
  189369. png_pass_yinc[png_ptr->pass];
  189370. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  189371. }
  189372. }
  189373. #if defined(PNG_READ_tEXt_SUPPORTED)
  189374. void /* PRIVATE */
  189375. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189376. length)
  189377. {
  189378. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189379. {
  189380. png_error(png_ptr, "Out of place tEXt");
  189381. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189382. }
  189383. #ifdef PNG_MAX_MALLOC_64K
  189384. png_ptr->skip_length = 0; /* This may not be necessary */
  189385. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189386. {
  189387. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  189388. png_ptr->skip_length = length - (png_uint_32)65535L;
  189389. length = (png_uint_32)65535L;
  189390. }
  189391. #endif
  189392. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189393. (png_uint_32)(length+1));
  189394. png_ptr->current_text[length] = '\0';
  189395. png_ptr->current_text_ptr = png_ptr->current_text;
  189396. png_ptr->current_text_size = (png_size_t)length;
  189397. png_ptr->current_text_left = (png_size_t)length;
  189398. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  189399. }
  189400. void /* PRIVATE */
  189401. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  189402. {
  189403. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189404. {
  189405. png_size_t text_size;
  189406. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189407. text_size = png_ptr->buffer_size;
  189408. else
  189409. text_size = png_ptr->current_text_left;
  189410. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189411. png_ptr->current_text_left -= text_size;
  189412. png_ptr->current_text_ptr += text_size;
  189413. }
  189414. if (!(png_ptr->current_text_left))
  189415. {
  189416. png_textp text_ptr;
  189417. png_charp text;
  189418. png_charp key;
  189419. int ret;
  189420. if (png_ptr->buffer_size < 4)
  189421. {
  189422. png_push_save_buffer(png_ptr);
  189423. return;
  189424. }
  189425. png_push_crc_finish(png_ptr);
  189426. #if defined(PNG_MAX_MALLOC_64K)
  189427. if (png_ptr->skip_length)
  189428. return;
  189429. #endif
  189430. key = png_ptr->current_text;
  189431. for (text = key; *text; text++)
  189432. /* empty loop */ ;
  189433. if (text < key + png_ptr->current_text_size)
  189434. text++;
  189435. text_ptr = (png_textp)png_malloc(png_ptr,
  189436. (png_uint_32)png_sizeof(png_text));
  189437. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  189438. text_ptr->key = key;
  189439. #ifdef PNG_iTXt_SUPPORTED
  189440. text_ptr->lang = NULL;
  189441. text_ptr->lang_key = NULL;
  189442. #endif
  189443. text_ptr->text = text;
  189444. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189445. png_free(png_ptr, key);
  189446. png_free(png_ptr, text_ptr);
  189447. png_ptr->current_text = NULL;
  189448. if (ret)
  189449. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189450. }
  189451. }
  189452. #endif
  189453. #if defined(PNG_READ_zTXt_SUPPORTED)
  189454. void /* PRIVATE */
  189455. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189456. length)
  189457. {
  189458. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189459. {
  189460. png_error(png_ptr, "Out of place zTXt");
  189461. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189462. }
  189463. #ifdef PNG_MAX_MALLOC_64K
  189464. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  189465. * to be able to store the uncompressed data. Actually, the threshold
  189466. * is probably around 32K, but it isn't as definite as 64K is.
  189467. */
  189468. if (length > (png_uint_32)65535L)
  189469. {
  189470. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  189471. png_push_crc_skip(png_ptr, length);
  189472. return;
  189473. }
  189474. #endif
  189475. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189476. (png_uint_32)(length+1));
  189477. png_ptr->current_text[length] = '\0';
  189478. png_ptr->current_text_ptr = png_ptr->current_text;
  189479. png_ptr->current_text_size = (png_size_t)length;
  189480. png_ptr->current_text_left = (png_size_t)length;
  189481. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  189482. }
  189483. void /* PRIVATE */
  189484. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  189485. {
  189486. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189487. {
  189488. png_size_t text_size;
  189489. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  189490. text_size = png_ptr->buffer_size;
  189491. else
  189492. text_size = png_ptr->current_text_left;
  189493. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189494. png_ptr->current_text_left -= text_size;
  189495. png_ptr->current_text_ptr += text_size;
  189496. }
  189497. if (!(png_ptr->current_text_left))
  189498. {
  189499. png_textp text_ptr;
  189500. png_charp text;
  189501. png_charp key;
  189502. int ret;
  189503. png_size_t text_size, key_size;
  189504. if (png_ptr->buffer_size < 4)
  189505. {
  189506. png_push_save_buffer(png_ptr);
  189507. return;
  189508. }
  189509. png_push_crc_finish(png_ptr);
  189510. key = png_ptr->current_text;
  189511. for (text = key; *text; text++)
  189512. /* empty loop */ ;
  189513. /* zTXt can't have zero text */
  189514. if (text >= key + png_ptr->current_text_size)
  189515. {
  189516. png_ptr->current_text = NULL;
  189517. png_free(png_ptr, key);
  189518. return;
  189519. }
  189520. text++;
  189521. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  189522. {
  189523. png_ptr->current_text = NULL;
  189524. png_free(png_ptr, key);
  189525. return;
  189526. }
  189527. text++;
  189528. png_ptr->zstream.next_in = (png_bytep )text;
  189529. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  189530. (text - key));
  189531. png_ptr->zstream.next_out = png_ptr->zbuf;
  189532. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189533. key_size = text - key;
  189534. text_size = 0;
  189535. text = NULL;
  189536. ret = Z_STREAM_END;
  189537. while (png_ptr->zstream.avail_in)
  189538. {
  189539. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189540. if (ret != Z_OK && ret != Z_STREAM_END)
  189541. {
  189542. inflateReset(&png_ptr->zstream);
  189543. png_ptr->zstream.avail_in = 0;
  189544. png_ptr->current_text = NULL;
  189545. png_free(png_ptr, key);
  189546. png_free(png_ptr, text);
  189547. return;
  189548. }
  189549. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  189550. {
  189551. if (text == NULL)
  189552. {
  189553. text = (png_charp)png_malloc(png_ptr,
  189554. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189555. + key_size + 1));
  189556. png_memcpy(text + key_size, png_ptr->zbuf,
  189557. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189558. png_memcpy(text, key, key_size);
  189559. text_size = key_size + png_ptr->zbuf_size -
  189560. png_ptr->zstream.avail_out;
  189561. *(text + text_size) = '\0';
  189562. }
  189563. else
  189564. {
  189565. png_charp tmp;
  189566. tmp = text;
  189567. text = (png_charp)png_malloc(png_ptr, text_size +
  189568. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189569. + 1));
  189570. png_memcpy(text, tmp, text_size);
  189571. png_free(png_ptr, tmp);
  189572. png_memcpy(text + text_size, png_ptr->zbuf,
  189573. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189574. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  189575. *(text + text_size) = '\0';
  189576. }
  189577. if (ret != Z_STREAM_END)
  189578. {
  189579. png_ptr->zstream.next_out = png_ptr->zbuf;
  189580. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189581. }
  189582. }
  189583. else
  189584. {
  189585. break;
  189586. }
  189587. if (ret == Z_STREAM_END)
  189588. break;
  189589. }
  189590. inflateReset(&png_ptr->zstream);
  189591. png_ptr->zstream.avail_in = 0;
  189592. if (ret != Z_STREAM_END)
  189593. {
  189594. png_ptr->current_text = NULL;
  189595. png_free(png_ptr, key);
  189596. png_free(png_ptr, text);
  189597. return;
  189598. }
  189599. png_ptr->current_text = NULL;
  189600. png_free(png_ptr, key);
  189601. key = text;
  189602. text += key_size;
  189603. text_ptr = (png_textp)png_malloc(png_ptr,
  189604. (png_uint_32)png_sizeof(png_text));
  189605. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  189606. text_ptr->key = key;
  189607. #ifdef PNG_iTXt_SUPPORTED
  189608. text_ptr->lang = NULL;
  189609. text_ptr->lang_key = NULL;
  189610. #endif
  189611. text_ptr->text = text;
  189612. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189613. png_free(png_ptr, key);
  189614. png_free(png_ptr, text_ptr);
  189615. if (ret)
  189616. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189617. }
  189618. }
  189619. #endif
  189620. #if defined(PNG_READ_iTXt_SUPPORTED)
  189621. void /* PRIVATE */
  189622. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189623. length)
  189624. {
  189625. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189626. {
  189627. png_error(png_ptr, "Out of place iTXt");
  189628. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189629. }
  189630. #ifdef PNG_MAX_MALLOC_64K
  189631. png_ptr->skip_length = 0; /* This may not be necessary */
  189632. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189633. {
  189634. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  189635. png_ptr->skip_length = length - (png_uint_32)65535L;
  189636. length = (png_uint_32)65535L;
  189637. }
  189638. #endif
  189639. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189640. (png_uint_32)(length+1));
  189641. png_ptr->current_text[length] = '\0';
  189642. png_ptr->current_text_ptr = png_ptr->current_text;
  189643. png_ptr->current_text_size = (png_size_t)length;
  189644. png_ptr->current_text_left = (png_size_t)length;
  189645. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  189646. }
  189647. void /* PRIVATE */
  189648. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  189649. {
  189650. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189651. {
  189652. png_size_t text_size;
  189653. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189654. text_size = png_ptr->buffer_size;
  189655. else
  189656. text_size = png_ptr->current_text_left;
  189657. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189658. png_ptr->current_text_left -= text_size;
  189659. png_ptr->current_text_ptr += text_size;
  189660. }
  189661. if (!(png_ptr->current_text_left))
  189662. {
  189663. png_textp text_ptr;
  189664. png_charp key;
  189665. int comp_flag;
  189666. png_charp lang;
  189667. png_charp lang_key;
  189668. png_charp text;
  189669. int ret;
  189670. if (png_ptr->buffer_size < 4)
  189671. {
  189672. png_push_save_buffer(png_ptr);
  189673. return;
  189674. }
  189675. png_push_crc_finish(png_ptr);
  189676. #if defined(PNG_MAX_MALLOC_64K)
  189677. if (png_ptr->skip_length)
  189678. return;
  189679. #endif
  189680. key = png_ptr->current_text;
  189681. for (lang = key; *lang; lang++)
  189682. /* empty loop */ ;
  189683. if (lang < key + png_ptr->current_text_size - 3)
  189684. lang++;
  189685. comp_flag = *lang++;
  189686. lang++; /* skip comp_type, always zero */
  189687. for (lang_key = lang; *lang_key; lang_key++)
  189688. /* empty loop */ ;
  189689. lang_key++; /* skip NUL separator */
  189690. text=lang_key;
  189691. if (lang_key < key + png_ptr->current_text_size - 1)
  189692. {
  189693. for (; *text; text++)
  189694. /* empty loop */ ;
  189695. }
  189696. if (text < key + png_ptr->current_text_size)
  189697. text++;
  189698. text_ptr = (png_textp)png_malloc(png_ptr,
  189699. (png_uint_32)png_sizeof(png_text));
  189700. text_ptr->compression = comp_flag + 2;
  189701. text_ptr->key = key;
  189702. text_ptr->lang = lang;
  189703. text_ptr->lang_key = lang_key;
  189704. text_ptr->text = text;
  189705. text_ptr->text_length = 0;
  189706. text_ptr->itxt_length = png_strlen(text);
  189707. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189708. png_ptr->current_text = NULL;
  189709. png_free(png_ptr, text_ptr);
  189710. if (ret)
  189711. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  189712. }
  189713. }
  189714. #endif
  189715. /* This function is called when we haven't found a handler for this
  189716. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  189717. * name or a critical chunk), the chunk is (currently) silently ignored.
  189718. */
  189719. void /* PRIVATE */
  189720. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189721. length)
  189722. {
  189723. png_uint_32 skip=0;
  189724. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  189725. if (!(png_ptr->chunk_name[0] & 0x20))
  189726. {
  189727. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189728. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189729. PNG_HANDLE_CHUNK_ALWAYS
  189730. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189731. && png_ptr->read_user_chunk_fn == NULL
  189732. #endif
  189733. )
  189734. #endif
  189735. png_chunk_error(png_ptr, "unknown critical chunk");
  189736. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189737. }
  189738. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189739. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  189740. {
  189741. #ifdef PNG_MAX_MALLOC_64K
  189742. if (length > (png_uint_32)65535L)
  189743. {
  189744. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  189745. skip = length - (png_uint_32)65535L;
  189746. length = (png_uint_32)65535L;
  189747. }
  189748. #endif
  189749. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  189750. (png_charp)png_ptr->chunk_name, 5);
  189751. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  189752. png_ptr->unknown_chunk.size = (png_size_t)length;
  189753. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  189754. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189755. if(png_ptr->read_user_chunk_fn != NULL)
  189756. {
  189757. /* callback to user unknown chunk handler */
  189758. int ret;
  189759. ret = (*(png_ptr->read_user_chunk_fn))
  189760. (png_ptr, &png_ptr->unknown_chunk);
  189761. if (ret < 0)
  189762. png_chunk_error(png_ptr, "error in user chunk");
  189763. if (ret == 0)
  189764. {
  189765. if (!(png_ptr->chunk_name[0] & 0x20))
  189766. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189767. PNG_HANDLE_CHUNK_ALWAYS)
  189768. png_chunk_error(png_ptr, "unknown critical chunk");
  189769. png_set_unknown_chunks(png_ptr, info_ptr,
  189770. &png_ptr->unknown_chunk, 1);
  189771. }
  189772. }
  189773. #else
  189774. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  189775. #endif
  189776. png_free(png_ptr, png_ptr->unknown_chunk.data);
  189777. png_ptr->unknown_chunk.data = NULL;
  189778. }
  189779. else
  189780. #endif
  189781. skip=length;
  189782. png_push_crc_skip(png_ptr, skip);
  189783. }
  189784. void /* PRIVATE */
  189785. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  189786. {
  189787. if (png_ptr->info_fn != NULL)
  189788. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  189789. }
  189790. void /* PRIVATE */
  189791. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  189792. {
  189793. if (png_ptr->end_fn != NULL)
  189794. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  189795. }
  189796. void /* PRIVATE */
  189797. png_push_have_row(png_structp png_ptr, png_bytep row)
  189798. {
  189799. if (png_ptr->row_fn != NULL)
  189800. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  189801. (int)png_ptr->pass);
  189802. }
  189803. void PNGAPI
  189804. png_progressive_combine_row (png_structp png_ptr,
  189805. png_bytep old_row, png_bytep new_row)
  189806. {
  189807. #ifdef PNG_USE_LOCAL_ARRAYS
  189808. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  189809. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  189810. #endif
  189811. if(png_ptr == NULL) return;
  189812. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  189813. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  189814. }
  189815. void PNGAPI
  189816. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  189817. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  189818. png_progressive_end_ptr end_fn)
  189819. {
  189820. if(png_ptr == NULL) return;
  189821. png_ptr->info_fn = info_fn;
  189822. png_ptr->row_fn = row_fn;
  189823. png_ptr->end_fn = end_fn;
  189824. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  189825. }
  189826. png_voidp PNGAPI
  189827. png_get_progressive_ptr(png_structp png_ptr)
  189828. {
  189829. if(png_ptr == NULL) return (NULL);
  189830. return png_ptr->io_ptr;
  189831. }
  189832. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  189833. /*** End of inlined file: pngpread.c ***/
  189834. /*** Start of inlined file: pngrio.c ***/
  189835. /* pngrio.c - functions for data input
  189836. *
  189837. * Last changed in libpng 1.2.13 November 13, 2006
  189838. * For conditions of distribution and use, see copyright notice in png.h
  189839. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  189840. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189841. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189842. *
  189843. * This file provides a location for all input. Users who need
  189844. * special handling are expected to write a function that has the same
  189845. * arguments as this and performs a similar function, but that possibly
  189846. * has a different input method. Note that you shouldn't change this
  189847. * function, but rather write a replacement function and then make
  189848. * libpng use it at run time with png_set_read_fn(...).
  189849. */
  189850. #define PNG_INTERNAL
  189851. #if defined(PNG_READ_SUPPORTED)
  189852. /* Read the data from whatever input you are using. The default routine
  189853. reads from a file pointer. Note that this routine sometimes gets called
  189854. with very small lengths, so you should implement some kind of simple
  189855. buffering if you are using unbuffered reads. This should never be asked
  189856. to read more then 64K on a 16 bit machine. */
  189857. void /* PRIVATE */
  189858. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189859. {
  189860. png_debug1(4,"reading %d bytes\n", (int)length);
  189861. if (png_ptr->read_data_fn != NULL)
  189862. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  189863. else
  189864. png_error(png_ptr, "Call to NULL read function");
  189865. }
  189866. #if !defined(PNG_NO_STDIO)
  189867. /* This is the function that does the actual reading of data. If you are
  189868. not reading from a standard C stream, you should create a replacement
  189869. read_data function and use it at run time with png_set_read_fn(), rather
  189870. than changing the library. */
  189871. #ifndef USE_FAR_KEYWORD
  189872. void PNGAPI
  189873. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189874. {
  189875. png_size_t check;
  189876. if(png_ptr == NULL) return;
  189877. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  189878. * instead of an int, which is what fread() actually returns.
  189879. */
  189880. #if defined(_WIN32_WCE)
  189881. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  189882. check = 0;
  189883. #else
  189884. check = (png_size_t)fread(data, (png_size_t)1, length,
  189885. (png_FILE_p)png_ptr->io_ptr);
  189886. #endif
  189887. if (check != length)
  189888. png_error(png_ptr, "Read Error");
  189889. }
  189890. #else
  189891. /* this is the model-independent version. Since the standard I/O library
  189892. can't handle far buffers in the medium and small models, we have to copy
  189893. the data.
  189894. */
  189895. #define NEAR_BUF_SIZE 1024
  189896. #define MIN(a,b) (a <= b ? a : b)
  189897. static void PNGAPI
  189898. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  189899. {
  189900. int check;
  189901. png_byte *n_data;
  189902. png_FILE_p io_ptr;
  189903. if(png_ptr == NULL) return;
  189904. /* Check if data really is near. If so, use usual code. */
  189905. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  189906. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  189907. if ((png_bytep)n_data == data)
  189908. {
  189909. #if defined(_WIN32_WCE)
  189910. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  189911. check = 0;
  189912. #else
  189913. check = fread(n_data, 1, length, io_ptr);
  189914. #endif
  189915. }
  189916. else
  189917. {
  189918. png_byte buf[NEAR_BUF_SIZE];
  189919. png_size_t read, remaining, err;
  189920. check = 0;
  189921. remaining = length;
  189922. do
  189923. {
  189924. read = MIN(NEAR_BUF_SIZE, remaining);
  189925. #if defined(_WIN32_WCE)
  189926. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  189927. err = 0;
  189928. #else
  189929. err = fread(buf, (png_size_t)1, read, io_ptr);
  189930. #endif
  189931. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  189932. if(err != read)
  189933. break;
  189934. else
  189935. check += err;
  189936. data += read;
  189937. remaining -= read;
  189938. }
  189939. while (remaining != 0);
  189940. }
  189941. if ((png_uint_32)check != (png_uint_32)length)
  189942. png_error(png_ptr, "read Error");
  189943. }
  189944. #endif
  189945. #endif
  189946. /* This function allows the application to supply a new input function
  189947. for libpng if standard C streams aren't being used.
  189948. This function takes as its arguments:
  189949. png_ptr - pointer to a png input data structure
  189950. io_ptr - pointer to user supplied structure containing info about
  189951. the input functions. May be NULL.
  189952. read_data_fn - pointer to a new input function that takes as its
  189953. arguments a pointer to a png_struct, a pointer to
  189954. a location where input data can be stored, and a 32-bit
  189955. unsigned int that is the number of bytes to be read.
  189956. To exit and output any fatal error messages the new write
  189957. function should call png_error(png_ptr, "Error msg"). */
  189958. void PNGAPI
  189959. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  189960. png_rw_ptr read_data_fn)
  189961. {
  189962. if(png_ptr == NULL) return;
  189963. png_ptr->io_ptr = io_ptr;
  189964. #if !defined(PNG_NO_STDIO)
  189965. if (read_data_fn != NULL)
  189966. png_ptr->read_data_fn = read_data_fn;
  189967. else
  189968. png_ptr->read_data_fn = png_default_read_data;
  189969. #else
  189970. png_ptr->read_data_fn = read_data_fn;
  189971. #endif
  189972. /* It is an error to write to a read device */
  189973. if (png_ptr->write_data_fn != NULL)
  189974. {
  189975. png_ptr->write_data_fn = NULL;
  189976. png_warning(png_ptr,
  189977. "It's an error to set both read_data_fn and write_data_fn in the ");
  189978. png_warning(png_ptr,
  189979. "same structure. Resetting write_data_fn to NULL.");
  189980. }
  189981. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  189982. png_ptr->output_flush_fn = NULL;
  189983. #endif
  189984. }
  189985. #endif /* PNG_READ_SUPPORTED */
  189986. /*** End of inlined file: pngrio.c ***/
  189987. /*** Start of inlined file: pngrtran.c ***/
  189988. /* pngrtran.c - transforms the data in a row for PNG readers
  189989. *
  189990. * Last changed in libpng 1.2.21 [October 4, 2007]
  189991. * For conditions of distribution and use, see copyright notice in png.h
  189992. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  189993. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189994. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189995. *
  189996. * This file contains functions optionally called by an application
  189997. * in order to tell libpng how to handle data when reading a PNG.
  189998. * Transformations that are used in both reading and writing are
  189999. * in pngtrans.c.
  190000. */
  190001. #define PNG_INTERNAL
  190002. #if defined(PNG_READ_SUPPORTED)
  190003. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  190004. void PNGAPI
  190005. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  190006. {
  190007. png_debug(1, "in png_set_crc_action\n");
  190008. /* Tell libpng how we react to CRC errors in critical chunks */
  190009. if(png_ptr == NULL) return;
  190010. switch (crit_action)
  190011. {
  190012. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  190013. break;
  190014. case PNG_CRC_WARN_USE: /* warn/use data */
  190015. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190016. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  190017. break;
  190018. case PNG_CRC_QUIET_USE: /* quiet/use data */
  190019. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190020. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  190021. PNG_FLAG_CRC_CRITICAL_IGNORE;
  190022. break;
  190023. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  190024. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  190025. case PNG_CRC_ERROR_QUIT: /* error/quit */
  190026. case PNG_CRC_DEFAULT:
  190027. default:
  190028. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190029. break;
  190030. }
  190031. switch (ancil_action)
  190032. {
  190033. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  190034. break;
  190035. case PNG_CRC_WARN_USE: /* warn/use data */
  190036. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190037. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  190038. break;
  190039. case PNG_CRC_QUIET_USE: /* quiet/use data */
  190040. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190041. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  190042. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  190043. break;
  190044. case PNG_CRC_ERROR_QUIT: /* error/quit */
  190045. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190046. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  190047. break;
  190048. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  190049. case PNG_CRC_DEFAULT:
  190050. default:
  190051. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190052. break;
  190053. }
  190054. }
  190055. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  190056. defined(PNG_FLOATING_POINT_SUPPORTED)
  190057. /* handle alpha and tRNS via a background color */
  190058. void PNGAPI
  190059. png_set_background(png_structp png_ptr,
  190060. png_color_16p background_color, int background_gamma_code,
  190061. int need_expand, double background_gamma)
  190062. {
  190063. png_debug(1, "in png_set_background\n");
  190064. if(png_ptr == NULL) return;
  190065. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  190066. {
  190067. png_warning(png_ptr, "Application must supply a known background gamma");
  190068. return;
  190069. }
  190070. png_ptr->transformations |= PNG_BACKGROUND;
  190071. png_memcpy(&(png_ptr->background), background_color,
  190072. png_sizeof(png_color_16));
  190073. png_ptr->background_gamma = (float)background_gamma;
  190074. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  190075. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  190076. }
  190077. #endif
  190078. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190079. /* strip 16 bit depth files to 8 bit depth */
  190080. void PNGAPI
  190081. png_set_strip_16(png_structp png_ptr)
  190082. {
  190083. png_debug(1, "in png_set_strip_16\n");
  190084. if(png_ptr == NULL) return;
  190085. png_ptr->transformations |= PNG_16_TO_8;
  190086. }
  190087. #endif
  190088. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190089. void PNGAPI
  190090. png_set_strip_alpha(png_structp png_ptr)
  190091. {
  190092. png_debug(1, "in png_set_strip_alpha\n");
  190093. if(png_ptr == NULL) return;
  190094. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  190095. }
  190096. #endif
  190097. #if defined(PNG_READ_DITHER_SUPPORTED)
  190098. /* Dither file to 8 bit. Supply a palette, the current number
  190099. * of elements in the palette, the maximum number of elements
  190100. * allowed, and a histogram if possible. If the current number
  190101. * of colors is greater then the maximum number, the palette will be
  190102. * modified to fit in the maximum number. "full_dither" indicates
  190103. * whether we need a dithering cube set up for RGB images, or if we
  190104. * simply are reducing the number of colors in a paletted image.
  190105. */
  190106. typedef struct png_dsort_struct
  190107. {
  190108. struct png_dsort_struct FAR * next;
  190109. png_byte left;
  190110. png_byte right;
  190111. } png_dsort;
  190112. typedef png_dsort FAR * png_dsortp;
  190113. typedef png_dsort FAR * FAR * png_dsortpp;
  190114. void PNGAPI
  190115. png_set_dither(png_structp png_ptr, png_colorp palette,
  190116. int num_palette, int maximum_colors, png_uint_16p histogram,
  190117. int full_dither)
  190118. {
  190119. png_debug(1, "in png_set_dither\n");
  190120. if(png_ptr == NULL) return;
  190121. png_ptr->transformations |= PNG_DITHER;
  190122. if (!full_dither)
  190123. {
  190124. int i;
  190125. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  190126. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190127. for (i = 0; i < num_palette; i++)
  190128. png_ptr->dither_index[i] = (png_byte)i;
  190129. }
  190130. if (num_palette > maximum_colors)
  190131. {
  190132. if (histogram != NULL)
  190133. {
  190134. /* This is easy enough, just throw out the least used colors.
  190135. Perhaps not the best solution, but good enough. */
  190136. int i;
  190137. /* initialize an array to sort colors */
  190138. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  190139. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190140. /* initialize the dither_sort array */
  190141. for (i = 0; i < num_palette; i++)
  190142. png_ptr->dither_sort[i] = (png_byte)i;
  190143. /* Find the least used palette entries by starting a
  190144. bubble sort, and running it until we have sorted
  190145. out enough colors. Note that we don't care about
  190146. sorting all the colors, just finding which are
  190147. least used. */
  190148. for (i = num_palette - 1; i >= maximum_colors; i--)
  190149. {
  190150. int done; /* to stop early if the list is pre-sorted */
  190151. int j;
  190152. done = 1;
  190153. for (j = 0; j < i; j++)
  190154. {
  190155. if (histogram[png_ptr->dither_sort[j]]
  190156. < histogram[png_ptr->dither_sort[j + 1]])
  190157. {
  190158. png_byte t;
  190159. t = png_ptr->dither_sort[j];
  190160. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  190161. png_ptr->dither_sort[j + 1] = t;
  190162. done = 0;
  190163. }
  190164. }
  190165. if (done)
  190166. break;
  190167. }
  190168. /* swap the palette around, and set up a table, if necessary */
  190169. if (full_dither)
  190170. {
  190171. int j = num_palette;
  190172. /* put all the useful colors within the max, but don't
  190173. move the others */
  190174. for (i = 0; i < maximum_colors; i++)
  190175. {
  190176. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  190177. {
  190178. do
  190179. j--;
  190180. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  190181. palette[i] = palette[j];
  190182. }
  190183. }
  190184. }
  190185. else
  190186. {
  190187. int j = num_palette;
  190188. /* move all the used colors inside the max limit, and
  190189. develop a translation table */
  190190. for (i = 0; i < maximum_colors; i++)
  190191. {
  190192. /* only move the colors we need to */
  190193. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  190194. {
  190195. png_color tmp_color;
  190196. do
  190197. j--;
  190198. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  190199. tmp_color = palette[j];
  190200. palette[j] = palette[i];
  190201. palette[i] = tmp_color;
  190202. /* indicate where the color went */
  190203. png_ptr->dither_index[j] = (png_byte)i;
  190204. png_ptr->dither_index[i] = (png_byte)j;
  190205. }
  190206. }
  190207. /* find closest color for those colors we are not using */
  190208. for (i = 0; i < num_palette; i++)
  190209. {
  190210. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  190211. {
  190212. int min_d, k, min_k, d_index;
  190213. /* find the closest color to one we threw out */
  190214. d_index = png_ptr->dither_index[i];
  190215. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  190216. for (k = 1, min_k = 0; k < maximum_colors; k++)
  190217. {
  190218. int d;
  190219. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  190220. if (d < min_d)
  190221. {
  190222. min_d = d;
  190223. min_k = k;
  190224. }
  190225. }
  190226. /* point to closest color */
  190227. png_ptr->dither_index[i] = (png_byte)min_k;
  190228. }
  190229. }
  190230. }
  190231. png_free(png_ptr, png_ptr->dither_sort);
  190232. png_ptr->dither_sort=NULL;
  190233. }
  190234. else
  190235. {
  190236. /* This is much harder to do simply (and quickly). Perhaps
  190237. we need to go through a median cut routine, but those
  190238. don't always behave themselves with only a few colors
  190239. as input. So we will just find the closest two colors,
  190240. and throw out one of them (chosen somewhat randomly).
  190241. [We don't understand this at all, so if someone wants to
  190242. work on improving it, be our guest - AED, GRP]
  190243. */
  190244. int i;
  190245. int max_d;
  190246. int num_new_palette;
  190247. png_dsortp t;
  190248. png_dsortpp hash;
  190249. t=NULL;
  190250. /* initialize palette index arrays */
  190251. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  190252. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190253. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  190254. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190255. /* initialize the sort array */
  190256. for (i = 0; i < num_palette; i++)
  190257. {
  190258. png_ptr->index_to_palette[i] = (png_byte)i;
  190259. png_ptr->palette_to_index[i] = (png_byte)i;
  190260. }
  190261. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  190262. png_sizeof (png_dsortp)));
  190263. for (i = 0; i < 769; i++)
  190264. hash[i] = NULL;
  190265. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  190266. num_new_palette = num_palette;
  190267. /* initial wild guess at how far apart the farthest pixel
  190268. pair we will be eliminating will be. Larger
  190269. numbers mean more areas will be allocated, Smaller
  190270. numbers run the risk of not saving enough data, and
  190271. having to do this all over again.
  190272. I have not done extensive checking on this number.
  190273. */
  190274. max_d = 96;
  190275. while (num_new_palette > maximum_colors)
  190276. {
  190277. for (i = 0; i < num_new_palette - 1; i++)
  190278. {
  190279. int j;
  190280. for (j = i + 1; j < num_new_palette; j++)
  190281. {
  190282. int d;
  190283. d = PNG_COLOR_DIST(palette[i], palette[j]);
  190284. if (d <= max_d)
  190285. {
  190286. t = (png_dsortp)png_malloc_warn(png_ptr,
  190287. (png_uint_32)(png_sizeof(png_dsort)));
  190288. if (t == NULL)
  190289. break;
  190290. t->next = hash[d];
  190291. t->left = (png_byte)i;
  190292. t->right = (png_byte)j;
  190293. hash[d] = t;
  190294. }
  190295. }
  190296. if (t == NULL)
  190297. break;
  190298. }
  190299. if (t != NULL)
  190300. for (i = 0; i <= max_d; i++)
  190301. {
  190302. if (hash[i] != NULL)
  190303. {
  190304. png_dsortp p;
  190305. for (p = hash[i]; p; p = p->next)
  190306. {
  190307. if ((int)png_ptr->index_to_palette[p->left]
  190308. < num_new_palette &&
  190309. (int)png_ptr->index_to_palette[p->right]
  190310. < num_new_palette)
  190311. {
  190312. int j, next_j;
  190313. if (num_new_palette & 0x01)
  190314. {
  190315. j = p->left;
  190316. next_j = p->right;
  190317. }
  190318. else
  190319. {
  190320. j = p->right;
  190321. next_j = p->left;
  190322. }
  190323. num_new_palette--;
  190324. palette[png_ptr->index_to_palette[j]]
  190325. = palette[num_new_palette];
  190326. if (!full_dither)
  190327. {
  190328. int k;
  190329. for (k = 0; k < num_palette; k++)
  190330. {
  190331. if (png_ptr->dither_index[k] ==
  190332. png_ptr->index_to_palette[j])
  190333. png_ptr->dither_index[k] =
  190334. png_ptr->index_to_palette[next_j];
  190335. if ((int)png_ptr->dither_index[k] ==
  190336. num_new_palette)
  190337. png_ptr->dither_index[k] =
  190338. png_ptr->index_to_palette[j];
  190339. }
  190340. }
  190341. png_ptr->index_to_palette[png_ptr->palette_to_index
  190342. [num_new_palette]] = png_ptr->index_to_palette[j];
  190343. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  190344. = png_ptr->palette_to_index[num_new_palette];
  190345. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  190346. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  190347. }
  190348. if (num_new_palette <= maximum_colors)
  190349. break;
  190350. }
  190351. if (num_new_palette <= maximum_colors)
  190352. break;
  190353. }
  190354. }
  190355. for (i = 0; i < 769; i++)
  190356. {
  190357. if (hash[i] != NULL)
  190358. {
  190359. png_dsortp p = hash[i];
  190360. while (p)
  190361. {
  190362. t = p->next;
  190363. png_free(png_ptr, p);
  190364. p = t;
  190365. }
  190366. }
  190367. hash[i] = 0;
  190368. }
  190369. max_d += 96;
  190370. }
  190371. png_free(png_ptr, hash);
  190372. png_free(png_ptr, png_ptr->palette_to_index);
  190373. png_free(png_ptr, png_ptr->index_to_palette);
  190374. png_ptr->palette_to_index=NULL;
  190375. png_ptr->index_to_palette=NULL;
  190376. }
  190377. num_palette = maximum_colors;
  190378. }
  190379. if (png_ptr->palette == NULL)
  190380. {
  190381. png_ptr->palette = palette;
  190382. }
  190383. png_ptr->num_palette = (png_uint_16)num_palette;
  190384. if (full_dither)
  190385. {
  190386. int i;
  190387. png_bytep distance;
  190388. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  190389. PNG_DITHER_BLUE_BITS;
  190390. int num_red = (1 << PNG_DITHER_RED_BITS);
  190391. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  190392. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  190393. png_size_t num_entries = ((png_size_t)1 << total_bits);
  190394. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  190395. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  190396. png_memset(png_ptr->palette_lookup, 0, num_entries *
  190397. png_sizeof (png_byte));
  190398. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  190399. png_sizeof(png_byte)));
  190400. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  190401. for (i = 0; i < num_palette; i++)
  190402. {
  190403. int ir, ig, ib;
  190404. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  190405. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  190406. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  190407. for (ir = 0; ir < num_red; ir++)
  190408. {
  190409. /* int dr = abs(ir - r); */
  190410. int dr = ((ir > r) ? ir - r : r - ir);
  190411. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  190412. for (ig = 0; ig < num_green; ig++)
  190413. {
  190414. /* int dg = abs(ig - g); */
  190415. int dg = ((ig > g) ? ig - g : g - ig);
  190416. int dt = dr + dg;
  190417. int dm = ((dr > dg) ? dr : dg);
  190418. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  190419. for (ib = 0; ib < num_blue; ib++)
  190420. {
  190421. int d_index = index_g | ib;
  190422. /* int db = abs(ib - b); */
  190423. int db = ((ib > b) ? ib - b : b - ib);
  190424. int dmax = ((dm > db) ? dm : db);
  190425. int d = dmax + dt + db;
  190426. if (d < (int)distance[d_index])
  190427. {
  190428. distance[d_index] = (png_byte)d;
  190429. png_ptr->palette_lookup[d_index] = (png_byte)i;
  190430. }
  190431. }
  190432. }
  190433. }
  190434. }
  190435. png_free(png_ptr, distance);
  190436. }
  190437. }
  190438. #endif
  190439. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190440. /* Transform the image from the file_gamma to the screen_gamma. We
  190441. * only do transformations on images where the file_gamma and screen_gamma
  190442. * are not close reciprocals, otherwise it slows things down slightly, and
  190443. * also needlessly introduces small errors.
  190444. *
  190445. * We will turn off gamma transformation later if no semitransparent entries
  190446. * are present in the tRNS array for palette images. We can't do it here
  190447. * because we don't necessarily have the tRNS chunk yet.
  190448. */
  190449. void PNGAPI
  190450. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  190451. {
  190452. png_debug(1, "in png_set_gamma\n");
  190453. if(png_ptr == NULL) return;
  190454. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  190455. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  190456. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  190457. png_ptr->transformations |= PNG_GAMMA;
  190458. png_ptr->gamma = (float)file_gamma;
  190459. png_ptr->screen_gamma = (float)scrn_gamma;
  190460. }
  190461. #endif
  190462. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190463. /* Expand paletted images to RGB, expand grayscale images of
  190464. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  190465. * to alpha channels.
  190466. */
  190467. void PNGAPI
  190468. png_set_expand(png_structp png_ptr)
  190469. {
  190470. png_debug(1, "in png_set_expand\n");
  190471. if(png_ptr == NULL) return;
  190472. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190473. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190474. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190475. #endif
  190476. }
  190477. /* GRR 19990627: the following three functions currently are identical
  190478. * to png_set_expand(). However, it is entirely reasonable that someone
  190479. * might wish to expand an indexed image to RGB but *not* expand a single,
  190480. * fully transparent palette entry to a full alpha channel--perhaps instead
  190481. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  190482. * the transparent color with a particular RGB value, or drop tRNS entirely.
  190483. * IOW, a future version of the library may make the transformations flag
  190484. * a bit more fine-grained, with separate bits for each of these three
  190485. * functions.
  190486. *
  190487. * More to the point, these functions make it obvious what libpng will be
  190488. * doing, whereas "expand" can (and does) mean any number of things.
  190489. *
  190490. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  190491. * to expand only the sample depth but not to expand the tRNS to alpha.
  190492. */
  190493. /* Expand paletted images to RGB. */
  190494. void PNGAPI
  190495. png_set_palette_to_rgb(png_structp png_ptr)
  190496. {
  190497. png_debug(1, "in png_set_palette_to_rgb\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. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190503. #endif
  190504. }
  190505. #if !defined(PNG_1_0_X)
  190506. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190507. void PNGAPI
  190508. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  190509. {
  190510. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  190511. if(png_ptr == NULL) return;
  190512. png_ptr->transformations |= PNG_EXPAND;
  190513. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190514. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190515. #endif
  190516. }
  190517. #endif
  190518. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  190519. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190520. /* Deprecated as of libpng-1.2.9 */
  190521. void PNGAPI
  190522. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  190523. {
  190524. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  190525. if(png_ptr == NULL) return;
  190526. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190527. }
  190528. #endif
  190529. /* Expand tRNS chunks to alpha channels. */
  190530. void PNGAPI
  190531. png_set_tRNS_to_alpha(png_structp png_ptr)
  190532. {
  190533. png_debug(1, "in png_set_tRNS_to_alpha\n");
  190534. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190535. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190536. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190537. #endif
  190538. }
  190539. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  190540. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190541. void PNGAPI
  190542. png_set_gray_to_rgb(png_structp png_ptr)
  190543. {
  190544. png_debug(1, "in png_set_gray_to_rgb\n");
  190545. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  190546. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190547. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190548. #endif
  190549. }
  190550. #endif
  190551. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190552. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  190553. /* Convert a RGB image to a grayscale of the same width. This allows us,
  190554. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  190555. */
  190556. void PNGAPI
  190557. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  190558. double green)
  190559. {
  190560. int red_fixed = (int)((float)red*100000.0 + 0.5);
  190561. int green_fixed = (int)((float)green*100000.0 + 0.5);
  190562. if(png_ptr == NULL) return;
  190563. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  190564. }
  190565. #endif
  190566. void PNGAPI
  190567. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  190568. png_fixed_point red, png_fixed_point green)
  190569. {
  190570. png_debug(1, "in png_set_rgb_to_gray\n");
  190571. if(png_ptr == NULL) return;
  190572. switch(error_action)
  190573. {
  190574. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  190575. break;
  190576. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  190577. break;
  190578. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  190579. }
  190580. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190581. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190582. png_ptr->transformations |= PNG_EXPAND;
  190583. #else
  190584. {
  190585. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  190586. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  190587. }
  190588. #endif
  190589. {
  190590. png_uint_16 red_int, green_int;
  190591. if(red < 0 || green < 0)
  190592. {
  190593. red_int = 6968; /* .212671 * 32768 + .5 */
  190594. green_int = 23434; /* .715160 * 32768 + .5 */
  190595. }
  190596. else if(red + green < 100000L)
  190597. {
  190598. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  190599. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  190600. }
  190601. else
  190602. {
  190603. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  190604. red_int = 6968;
  190605. green_int = 23434;
  190606. }
  190607. png_ptr->rgb_to_gray_red_coeff = red_int;
  190608. png_ptr->rgb_to_gray_green_coeff = green_int;
  190609. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  190610. }
  190611. }
  190612. #endif
  190613. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  190614. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  190615. defined(PNG_LEGACY_SUPPORTED)
  190616. void PNGAPI
  190617. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  190618. read_user_transform_fn)
  190619. {
  190620. png_debug(1, "in png_set_read_user_transform_fn\n");
  190621. if(png_ptr == NULL) return;
  190622. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190623. png_ptr->transformations |= PNG_USER_TRANSFORM;
  190624. png_ptr->read_user_transform_fn = read_user_transform_fn;
  190625. #endif
  190626. #ifdef PNG_LEGACY_SUPPORTED
  190627. if(read_user_transform_fn)
  190628. png_warning(png_ptr,
  190629. "This version of libpng does not support user transforms");
  190630. #endif
  190631. }
  190632. #endif
  190633. /* Initialize everything needed for the read. This includes modifying
  190634. * the palette.
  190635. */
  190636. void /* PRIVATE */
  190637. png_init_read_transformations(png_structp png_ptr)
  190638. {
  190639. png_debug(1, "in png_init_read_transformations\n");
  190640. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190641. if(png_ptr != NULL)
  190642. #endif
  190643. {
  190644. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  190645. || defined(PNG_READ_GAMMA_SUPPORTED)
  190646. int color_type = png_ptr->color_type;
  190647. #endif
  190648. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  190649. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190650. /* Detect gray background and attempt to enable optimization
  190651. * for gray --> RGB case */
  190652. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  190653. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  190654. * background color might actually be gray yet not be flagged as such.
  190655. * This is not a problem for the current code, which uses
  190656. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  190657. * png_do_gray_to_rgb() transformation.
  190658. */
  190659. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190660. !(color_type & PNG_COLOR_MASK_COLOR))
  190661. {
  190662. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190663. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190664. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190665. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190666. png_ptr->background.red == png_ptr->background.green &&
  190667. png_ptr->background.red == png_ptr->background.blue)
  190668. {
  190669. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190670. png_ptr->background.gray = png_ptr->background.red;
  190671. }
  190672. #endif
  190673. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190674. (png_ptr->transformations & PNG_EXPAND))
  190675. {
  190676. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  190677. {
  190678. /* expand background and tRNS chunks */
  190679. switch (png_ptr->bit_depth)
  190680. {
  190681. case 1:
  190682. png_ptr->background.gray *= (png_uint_16)0xff;
  190683. png_ptr->background.red = png_ptr->background.green
  190684. = png_ptr->background.blue = png_ptr->background.gray;
  190685. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190686. {
  190687. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  190688. png_ptr->trans_values.red = png_ptr->trans_values.green
  190689. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190690. }
  190691. break;
  190692. case 2:
  190693. png_ptr->background.gray *= (png_uint_16)0x55;
  190694. png_ptr->background.red = png_ptr->background.green
  190695. = png_ptr->background.blue = png_ptr->background.gray;
  190696. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190697. {
  190698. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  190699. png_ptr->trans_values.red = png_ptr->trans_values.green
  190700. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190701. }
  190702. break;
  190703. case 4:
  190704. png_ptr->background.gray *= (png_uint_16)0x11;
  190705. png_ptr->background.red = png_ptr->background.green
  190706. = png_ptr->background.blue = png_ptr->background.gray;
  190707. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190708. {
  190709. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  190710. png_ptr->trans_values.red = png_ptr->trans_values.green
  190711. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190712. }
  190713. break;
  190714. case 8:
  190715. case 16:
  190716. png_ptr->background.red = png_ptr->background.green
  190717. = png_ptr->background.blue = png_ptr->background.gray;
  190718. break;
  190719. }
  190720. }
  190721. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  190722. {
  190723. png_ptr->background.red =
  190724. png_ptr->palette[png_ptr->background.index].red;
  190725. png_ptr->background.green =
  190726. png_ptr->palette[png_ptr->background.index].green;
  190727. png_ptr->background.blue =
  190728. png_ptr->palette[png_ptr->background.index].blue;
  190729. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190730. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  190731. {
  190732. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190733. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190734. #endif
  190735. {
  190736. /* invert the alpha channel (in tRNS) unless the pixels are
  190737. going to be expanded, in which case leave it for later */
  190738. int i,istop;
  190739. istop=(int)png_ptr->num_trans;
  190740. for (i=0; i<istop; i++)
  190741. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  190742. }
  190743. }
  190744. #endif
  190745. }
  190746. }
  190747. #endif
  190748. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  190749. png_ptr->background_1 = png_ptr->background;
  190750. #endif
  190751. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190752. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  190753. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  190754. < PNG_GAMMA_THRESHOLD))
  190755. {
  190756. int i,k;
  190757. k=0;
  190758. for (i=0; i<png_ptr->num_trans; i++)
  190759. {
  190760. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  190761. k=1; /* partial transparency is present */
  190762. }
  190763. if (k == 0)
  190764. png_ptr->transformations &= (~PNG_GAMMA);
  190765. }
  190766. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  190767. png_ptr->gamma != 0.0)
  190768. {
  190769. png_build_gamma_table(png_ptr);
  190770. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190771. if (png_ptr->transformations & PNG_BACKGROUND)
  190772. {
  190773. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190774. {
  190775. /* could skip if no transparency and
  190776. */
  190777. png_color back, back_1;
  190778. png_colorp palette = png_ptr->palette;
  190779. int num_palette = png_ptr->num_palette;
  190780. int i;
  190781. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  190782. {
  190783. back.red = png_ptr->gamma_table[png_ptr->background.red];
  190784. back.green = png_ptr->gamma_table[png_ptr->background.green];
  190785. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  190786. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  190787. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  190788. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  190789. }
  190790. else
  190791. {
  190792. double g, gs;
  190793. switch (png_ptr->background_gamma_type)
  190794. {
  190795. case PNG_BACKGROUND_GAMMA_SCREEN:
  190796. g = (png_ptr->screen_gamma);
  190797. gs = 1.0;
  190798. break;
  190799. case PNG_BACKGROUND_GAMMA_FILE:
  190800. g = 1.0 / (png_ptr->gamma);
  190801. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190802. break;
  190803. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190804. g = 1.0 / (png_ptr->background_gamma);
  190805. gs = 1.0 / (png_ptr->background_gamma *
  190806. png_ptr->screen_gamma);
  190807. break;
  190808. default:
  190809. g = 1.0; /* back_1 */
  190810. gs = 1.0; /* back */
  190811. }
  190812. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  190813. {
  190814. back.red = (png_byte)png_ptr->background.red;
  190815. back.green = (png_byte)png_ptr->background.green;
  190816. back.blue = (png_byte)png_ptr->background.blue;
  190817. }
  190818. else
  190819. {
  190820. back.red = (png_byte)(pow(
  190821. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  190822. back.green = (png_byte)(pow(
  190823. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  190824. back.blue = (png_byte)(pow(
  190825. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  190826. }
  190827. back_1.red = (png_byte)(pow(
  190828. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  190829. back_1.green = (png_byte)(pow(
  190830. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  190831. back_1.blue = (png_byte)(pow(
  190832. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  190833. }
  190834. for (i = 0; i < num_palette; i++)
  190835. {
  190836. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  190837. {
  190838. if (png_ptr->trans[i] == 0)
  190839. {
  190840. palette[i] = back;
  190841. }
  190842. else /* if (png_ptr->trans[i] != 0xff) */
  190843. {
  190844. png_byte v, w;
  190845. v = png_ptr->gamma_to_1[palette[i].red];
  190846. png_composite(w, v, png_ptr->trans[i], back_1.red);
  190847. palette[i].red = png_ptr->gamma_from_1[w];
  190848. v = png_ptr->gamma_to_1[palette[i].green];
  190849. png_composite(w, v, png_ptr->trans[i], back_1.green);
  190850. palette[i].green = png_ptr->gamma_from_1[w];
  190851. v = png_ptr->gamma_to_1[palette[i].blue];
  190852. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  190853. palette[i].blue = png_ptr->gamma_from_1[w];
  190854. }
  190855. }
  190856. else
  190857. {
  190858. palette[i].red = png_ptr->gamma_table[palette[i].red];
  190859. palette[i].green = png_ptr->gamma_table[palette[i].green];
  190860. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  190861. }
  190862. }
  190863. }
  190864. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  190865. else
  190866. /* color_type != PNG_COLOR_TYPE_PALETTE */
  190867. {
  190868. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  190869. double g = 1.0;
  190870. double gs = 1.0;
  190871. switch (png_ptr->background_gamma_type)
  190872. {
  190873. case PNG_BACKGROUND_GAMMA_SCREEN:
  190874. g = (png_ptr->screen_gamma);
  190875. gs = 1.0;
  190876. break;
  190877. case PNG_BACKGROUND_GAMMA_FILE:
  190878. g = 1.0 / (png_ptr->gamma);
  190879. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  190880. break;
  190881. case PNG_BACKGROUND_GAMMA_UNIQUE:
  190882. g = 1.0 / (png_ptr->background_gamma);
  190883. gs = 1.0 / (png_ptr->background_gamma *
  190884. png_ptr->screen_gamma);
  190885. break;
  190886. }
  190887. png_ptr->background_1.gray = (png_uint_16)(pow(
  190888. (double)png_ptr->background.gray / m, g) * m + .5);
  190889. png_ptr->background.gray = (png_uint_16)(pow(
  190890. (double)png_ptr->background.gray / m, gs) * m + .5);
  190891. if ((png_ptr->background.red != png_ptr->background.green) ||
  190892. (png_ptr->background.red != png_ptr->background.blue) ||
  190893. (png_ptr->background.red != png_ptr->background.gray))
  190894. {
  190895. /* RGB or RGBA with color background */
  190896. png_ptr->background_1.red = (png_uint_16)(pow(
  190897. (double)png_ptr->background.red / m, g) * m + .5);
  190898. png_ptr->background_1.green = (png_uint_16)(pow(
  190899. (double)png_ptr->background.green / m, g) * m + .5);
  190900. png_ptr->background_1.blue = (png_uint_16)(pow(
  190901. (double)png_ptr->background.blue / m, g) * m + .5);
  190902. png_ptr->background.red = (png_uint_16)(pow(
  190903. (double)png_ptr->background.red / m, gs) * m + .5);
  190904. png_ptr->background.green = (png_uint_16)(pow(
  190905. (double)png_ptr->background.green / m, gs) * m + .5);
  190906. png_ptr->background.blue = (png_uint_16)(pow(
  190907. (double)png_ptr->background.blue / m, gs) * m + .5);
  190908. }
  190909. else
  190910. {
  190911. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  190912. png_ptr->background_1.red = png_ptr->background_1.green
  190913. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  190914. png_ptr->background.red = png_ptr->background.green
  190915. = png_ptr->background.blue = png_ptr->background.gray;
  190916. }
  190917. }
  190918. }
  190919. else
  190920. /* transformation does not include PNG_BACKGROUND */
  190921. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  190922. if (color_type == PNG_COLOR_TYPE_PALETTE)
  190923. {
  190924. png_colorp palette = png_ptr->palette;
  190925. int num_palette = png_ptr->num_palette;
  190926. int i;
  190927. for (i = 0; i < num_palette; i++)
  190928. {
  190929. palette[i].red = png_ptr->gamma_table[palette[i].red];
  190930. palette[i].green = png_ptr->gamma_table[palette[i].green];
  190931. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  190932. }
  190933. }
  190934. }
  190935. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190936. else
  190937. #endif
  190938. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  190939. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190940. /* No GAMMA transformation */
  190941. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190942. (color_type == PNG_COLOR_TYPE_PALETTE))
  190943. {
  190944. int i;
  190945. int istop = (int)png_ptr->num_trans;
  190946. png_color back;
  190947. png_colorp palette = png_ptr->palette;
  190948. back.red = (png_byte)png_ptr->background.red;
  190949. back.green = (png_byte)png_ptr->background.green;
  190950. back.blue = (png_byte)png_ptr->background.blue;
  190951. for (i = 0; i < istop; i++)
  190952. {
  190953. if (png_ptr->trans[i] == 0)
  190954. {
  190955. palette[i] = back;
  190956. }
  190957. else if (png_ptr->trans[i] != 0xff)
  190958. {
  190959. /* The png_composite() macro is defined in png.h */
  190960. png_composite(palette[i].red, palette[i].red,
  190961. png_ptr->trans[i], back.red);
  190962. png_composite(palette[i].green, palette[i].green,
  190963. png_ptr->trans[i], back.green);
  190964. png_composite(palette[i].blue, palette[i].blue,
  190965. png_ptr->trans[i], back.blue);
  190966. }
  190967. }
  190968. }
  190969. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  190970. #if defined(PNG_READ_SHIFT_SUPPORTED)
  190971. if ((png_ptr->transformations & PNG_SHIFT) &&
  190972. (color_type == PNG_COLOR_TYPE_PALETTE))
  190973. {
  190974. png_uint_16 i;
  190975. png_uint_16 istop = png_ptr->num_palette;
  190976. int sr = 8 - png_ptr->sig_bit.red;
  190977. int sg = 8 - png_ptr->sig_bit.green;
  190978. int sb = 8 - png_ptr->sig_bit.blue;
  190979. if (sr < 0 || sr > 8)
  190980. sr = 0;
  190981. if (sg < 0 || sg > 8)
  190982. sg = 0;
  190983. if (sb < 0 || sb > 8)
  190984. sb = 0;
  190985. for (i = 0; i < istop; i++)
  190986. {
  190987. png_ptr->palette[i].red >>= sr;
  190988. png_ptr->palette[i].green >>= sg;
  190989. png_ptr->palette[i].blue >>= sb;
  190990. }
  190991. }
  190992. #endif /* PNG_READ_SHIFT_SUPPORTED */
  190993. }
  190994. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  190995. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  190996. if(png_ptr)
  190997. return;
  190998. #endif
  190999. }
  191000. /* Modify the info structure to reflect the transformations. The
  191001. * info should be updated so a PNG file could be written with it,
  191002. * assuming the transformations result in valid PNG data.
  191003. */
  191004. void /* PRIVATE */
  191005. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  191006. {
  191007. png_debug(1, "in png_read_transform_info\n");
  191008. #if defined(PNG_READ_EXPAND_SUPPORTED)
  191009. if (png_ptr->transformations & PNG_EXPAND)
  191010. {
  191011. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191012. {
  191013. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  191014. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  191015. else
  191016. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  191017. info_ptr->bit_depth = 8;
  191018. info_ptr->num_trans = 0;
  191019. }
  191020. else
  191021. {
  191022. if (png_ptr->num_trans)
  191023. {
  191024. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  191025. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  191026. else
  191027. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  191028. }
  191029. if (info_ptr->bit_depth < 8)
  191030. info_ptr->bit_depth = 8;
  191031. info_ptr->num_trans = 0;
  191032. }
  191033. }
  191034. #endif
  191035. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191036. if (png_ptr->transformations & PNG_BACKGROUND)
  191037. {
  191038. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  191039. info_ptr->num_trans = 0;
  191040. info_ptr->background = png_ptr->background;
  191041. }
  191042. #endif
  191043. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191044. if (png_ptr->transformations & PNG_GAMMA)
  191045. {
  191046. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191047. info_ptr->gamma = png_ptr->gamma;
  191048. #endif
  191049. #ifdef PNG_FIXED_POINT_SUPPORTED
  191050. info_ptr->int_gamma = png_ptr->int_gamma;
  191051. #endif
  191052. }
  191053. #endif
  191054. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191055. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  191056. info_ptr->bit_depth = 8;
  191057. #endif
  191058. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191059. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  191060. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  191061. #endif
  191062. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191063. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  191064. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  191065. #endif
  191066. #if defined(PNG_READ_DITHER_SUPPORTED)
  191067. if (png_ptr->transformations & PNG_DITHER)
  191068. {
  191069. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  191070. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  191071. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  191072. {
  191073. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  191074. }
  191075. }
  191076. #endif
  191077. #if defined(PNG_READ_PACK_SUPPORTED)
  191078. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  191079. info_ptr->bit_depth = 8;
  191080. #endif
  191081. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191082. info_ptr->channels = 1;
  191083. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  191084. info_ptr->channels = 3;
  191085. else
  191086. info_ptr->channels = 1;
  191087. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  191088. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  191089. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  191090. #endif
  191091. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  191092. info_ptr->channels++;
  191093. #if defined(PNG_READ_FILLER_SUPPORTED)
  191094. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  191095. if ((png_ptr->transformations & PNG_FILLER) &&
  191096. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  191097. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  191098. {
  191099. info_ptr->channels++;
  191100. /* if adding a true alpha channel not just filler */
  191101. #if !defined(PNG_1_0_X)
  191102. if (png_ptr->transformations & PNG_ADD_ALPHA)
  191103. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  191104. #endif
  191105. }
  191106. #endif
  191107. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  191108. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  191109. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  191110. {
  191111. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  191112. info_ptr->bit_depth = png_ptr->user_transform_depth;
  191113. if(info_ptr->channels < png_ptr->user_transform_channels)
  191114. info_ptr->channels = png_ptr->user_transform_channels;
  191115. }
  191116. #endif
  191117. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  191118. info_ptr->bit_depth);
  191119. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  191120. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  191121. if(png_ptr)
  191122. return;
  191123. #endif
  191124. }
  191125. /* Transform the row. The order of transformations is significant,
  191126. * and is very touchy. If you add a transformation, take care to
  191127. * decide how it fits in with the other transformations here.
  191128. */
  191129. void /* PRIVATE */
  191130. png_do_read_transformations(png_structp png_ptr)
  191131. {
  191132. png_debug(1, "in png_do_read_transformations\n");
  191133. if (png_ptr->row_buf == NULL)
  191134. {
  191135. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  191136. char msg[50];
  191137. png_snprintf2(msg, 50,
  191138. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  191139. png_ptr->pass);
  191140. png_error(png_ptr, msg);
  191141. #else
  191142. png_error(png_ptr, "NULL row buffer");
  191143. #endif
  191144. }
  191145. #ifdef PNG_WARN_UNINITIALIZED_ROW
  191146. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  191147. /* Application has failed to call either png_read_start_image()
  191148. * or png_read_update_info() after setting transforms that expand
  191149. * pixels. This check added to libpng-1.2.19 */
  191150. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  191151. png_error(png_ptr, "Uninitialized row");
  191152. #else
  191153. png_warning(png_ptr, "Uninitialized row");
  191154. #endif
  191155. #endif
  191156. #if defined(PNG_READ_EXPAND_SUPPORTED)
  191157. if (png_ptr->transformations & PNG_EXPAND)
  191158. {
  191159. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  191160. {
  191161. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191162. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  191163. }
  191164. else
  191165. {
  191166. if (png_ptr->num_trans &&
  191167. (png_ptr->transformations & PNG_EXPAND_tRNS))
  191168. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191169. &(png_ptr->trans_values));
  191170. else
  191171. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191172. NULL);
  191173. }
  191174. }
  191175. #endif
  191176. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  191177. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  191178. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191179. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  191180. #endif
  191181. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191182. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  191183. {
  191184. int rgb_error =
  191185. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  191186. if(rgb_error)
  191187. {
  191188. png_ptr->rgb_to_gray_status=1;
  191189. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  191190. PNG_RGB_TO_GRAY_WARN)
  191191. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  191192. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  191193. PNG_RGB_TO_GRAY_ERR)
  191194. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  191195. }
  191196. }
  191197. #endif
  191198. /*
  191199. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  191200. In most cases, the "simple transparency" should be done prior to doing
  191201. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  191202. pixel is transparent. You would also need to make sure that the
  191203. transparency information is upgraded to RGB.
  191204. To summarize, the current flow is:
  191205. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  191206. with background "in place" if transparent,
  191207. convert to RGB if necessary
  191208. - Gray + alpha -> composite with gray background and remove alpha bytes,
  191209. convert to RGB if necessary
  191210. To support RGB backgrounds for gray images we need:
  191211. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  191212. 3 or 6 bytes and composite with background
  191213. "in place" if transparent (3x compare/pixel
  191214. compared to doing composite with gray bkgrnd)
  191215. - Gray + alpha -> convert to RGB + alpha, composite with background and
  191216. remove alpha bytes (3x float operations/pixel
  191217. compared with composite on gray background)
  191218. Greg's change will do this. The reason it wasn't done before is for
  191219. performance, as this increases the per-pixel operations. If we would check
  191220. in advance if the background was gray or RGB, and position the gray-to-RGB
  191221. transform appropriately, then it would save a lot of work/time.
  191222. */
  191223. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191224. /* if gray -> RGB, do so now only if background is non-gray; else do later
  191225. * for performance reasons */
  191226. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  191227. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  191228. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191229. #endif
  191230. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191231. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  191232. ((png_ptr->num_trans != 0 ) ||
  191233. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  191234. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191235. &(png_ptr->trans_values), &(png_ptr->background)
  191236. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191237. , &(png_ptr->background_1),
  191238. png_ptr->gamma_table, png_ptr->gamma_from_1,
  191239. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  191240. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  191241. png_ptr->gamma_shift
  191242. #endif
  191243. );
  191244. #endif
  191245. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191246. if ((png_ptr->transformations & PNG_GAMMA) &&
  191247. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191248. !((png_ptr->transformations & PNG_BACKGROUND) &&
  191249. ((png_ptr->num_trans != 0) ||
  191250. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  191251. #endif
  191252. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  191253. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191254. png_ptr->gamma_table, png_ptr->gamma_16_table,
  191255. png_ptr->gamma_shift);
  191256. #endif
  191257. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191258. if (png_ptr->transformations & PNG_16_TO_8)
  191259. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191260. #endif
  191261. #if defined(PNG_READ_DITHER_SUPPORTED)
  191262. if (png_ptr->transformations & PNG_DITHER)
  191263. {
  191264. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  191265. png_ptr->palette_lookup, png_ptr->dither_index);
  191266. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  191267. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  191268. }
  191269. #endif
  191270. #if defined(PNG_READ_INVERT_SUPPORTED)
  191271. if (png_ptr->transformations & PNG_INVERT_MONO)
  191272. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191273. #endif
  191274. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191275. if (png_ptr->transformations & PNG_SHIFT)
  191276. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191277. &(png_ptr->shift));
  191278. #endif
  191279. #if defined(PNG_READ_PACK_SUPPORTED)
  191280. if (png_ptr->transformations & PNG_PACK)
  191281. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191282. #endif
  191283. #if defined(PNG_READ_BGR_SUPPORTED)
  191284. if (png_ptr->transformations & PNG_BGR)
  191285. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191286. #endif
  191287. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191288. if (png_ptr->transformations & PNG_PACKSWAP)
  191289. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191290. #endif
  191291. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191292. /* if gray -> RGB, do so now only if we did not do so above */
  191293. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  191294. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  191295. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191296. #endif
  191297. #if defined(PNG_READ_FILLER_SUPPORTED)
  191298. if (png_ptr->transformations & PNG_FILLER)
  191299. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191300. (png_uint_32)png_ptr->filler, png_ptr->flags);
  191301. #endif
  191302. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191303. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  191304. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191305. #endif
  191306. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191307. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  191308. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191309. #endif
  191310. #if defined(PNG_READ_SWAP_SUPPORTED)
  191311. if (png_ptr->transformations & PNG_SWAP_BYTES)
  191312. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191313. #endif
  191314. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  191315. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  191316. {
  191317. if(png_ptr->read_user_transform_fn != NULL)
  191318. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  191319. (png_ptr, /* png_ptr */
  191320. &(png_ptr->row_info), /* row_info: */
  191321. /* png_uint_32 width; width of row */
  191322. /* png_uint_32 rowbytes; number of bytes in row */
  191323. /* png_byte color_type; color type of pixels */
  191324. /* png_byte bit_depth; bit depth of samples */
  191325. /* png_byte channels; number of channels (1-4) */
  191326. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  191327. png_ptr->row_buf + 1); /* start of pixel data for row */
  191328. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  191329. if(png_ptr->user_transform_depth)
  191330. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  191331. if(png_ptr->user_transform_channels)
  191332. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  191333. #endif
  191334. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  191335. png_ptr->row_info.channels);
  191336. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  191337. png_ptr->row_info.width);
  191338. }
  191339. #endif
  191340. }
  191341. #if defined(PNG_READ_PACK_SUPPORTED)
  191342. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  191343. * without changing the actual values. Thus, if you had a row with
  191344. * a bit depth of 1, you would end up with bytes that only contained
  191345. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  191346. * png_do_shift() after this.
  191347. */
  191348. void /* PRIVATE */
  191349. png_do_unpack(png_row_infop row_info, png_bytep row)
  191350. {
  191351. png_debug(1, "in png_do_unpack\n");
  191352. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191353. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  191354. #else
  191355. if (row_info->bit_depth < 8)
  191356. #endif
  191357. {
  191358. png_uint_32 i;
  191359. png_uint_32 row_width=row_info->width;
  191360. switch (row_info->bit_depth)
  191361. {
  191362. case 1:
  191363. {
  191364. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  191365. png_bytep dp = row + (png_size_t)row_width - 1;
  191366. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  191367. for (i = 0; i < row_width; i++)
  191368. {
  191369. *dp = (png_byte)((*sp >> shift) & 0x01);
  191370. if (shift == 7)
  191371. {
  191372. shift = 0;
  191373. sp--;
  191374. }
  191375. else
  191376. shift++;
  191377. dp--;
  191378. }
  191379. break;
  191380. }
  191381. case 2:
  191382. {
  191383. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  191384. png_bytep dp = row + (png_size_t)row_width - 1;
  191385. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  191386. for (i = 0; i < row_width; i++)
  191387. {
  191388. *dp = (png_byte)((*sp >> shift) & 0x03);
  191389. if (shift == 6)
  191390. {
  191391. shift = 0;
  191392. sp--;
  191393. }
  191394. else
  191395. shift += 2;
  191396. dp--;
  191397. }
  191398. break;
  191399. }
  191400. case 4:
  191401. {
  191402. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  191403. png_bytep dp = row + (png_size_t)row_width - 1;
  191404. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  191405. for (i = 0; i < row_width; i++)
  191406. {
  191407. *dp = (png_byte)((*sp >> shift) & 0x0f);
  191408. if (shift == 4)
  191409. {
  191410. shift = 0;
  191411. sp--;
  191412. }
  191413. else
  191414. shift = 4;
  191415. dp--;
  191416. }
  191417. break;
  191418. }
  191419. }
  191420. row_info->bit_depth = 8;
  191421. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191422. row_info->rowbytes = row_width * row_info->channels;
  191423. }
  191424. }
  191425. #endif
  191426. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191427. /* Reverse the effects of png_do_shift. This routine merely shifts the
  191428. * pixels back to their significant bits values. Thus, if you have
  191429. * a row of bit depth 8, but only 5 are significant, this will shift
  191430. * the values back to 0 through 31.
  191431. */
  191432. void /* PRIVATE */
  191433. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  191434. {
  191435. png_debug(1, "in png_do_unshift\n");
  191436. if (
  191437. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191438. row != NULL && row_info != NULL && sig_bits != NULL &&
  191439. #endif
  191440. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  191441. {
  191442. int shift[4];
  191443. int channels = 0;
  191444. int c;
  191445. png_uint_16 value = 0;
  191446. png_uint_32 row_width = row_info->width;
  191447. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  191448. {
  191449. shift[channels++] = row_info->bit_depth - sig_bits->red;
  191450. shift[channels++] = row_info->bit_depth - sig_bits->green;
  191451. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  191452. }
  191453. else
  191454. {
  191455. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  191456. }
  191457. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  191458. {
  191459. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  191460. }
  191461. for (c = 0; c < channels; c++)
  191462. {
  191463. if (shift[c] <= 0)
  191464. shift[c] = 0;
  191465. else
  191466. value = 1;
  191467. }
  191468. if (!value)
  191469. return;
  191470. switch (row_info->bit_depth)
  191471. {
  191472. case 2:
  191473. {
  191474. png_bytep bp;
  191475. png_uint_32 i;
  191476. png_uint_32 istop = row_info->rowbytes;
  191477. for (bp = row, i = 0; i < istop; i++)
  191478. {
  191479. *bp >>= 1;
  191480. *bp++ &= 0x55;
  191481. }
  191482. break;
  191483. }
  191484. case 4:
  191485. {
  191486. png_bytep bp = row;
  191487. png_uint_32 i;
  191488. png_uint_32 istop = row_info->rowbytes;
  191489. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  191490. (png_byte)((int)0xf >> shift[0]));
  191491. for (i = 0; i < istop; i++)
  191492. {
  191493. *bp >>= shift[0];
  191494. *bp++ &= mask;
  191495. }
  191496. break;
  191497. }
  191498. case 8:
  191499. {
  191500. png_bytep bp = row;
  191501. png_uint_32 i;
  191502. png_uint_32 istop = row_width * channels;
  191503. for (i = 0; i < istop; i++)
  191504. {
  191505. *bp++ >>= shift[i%channels];
  191506. }
  191507. break;
  191508. }
  191509. case 16:
  191510. {
  191511. png_bytep bp = row;
  191512. png_uint_32 i;
  191513. png_uint_32 istop = channels * row_width;
  191514. for (i = 0; i < istop; i++)
  191515. {
  191516. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  191517. value >>= shift[i%channels];
  191518. *bp++ = (png_byte)(value >> 8);
  191519. *bp++ = (png_byte)(value & 0xff);
  191520. }
  191521. break;
  191522. }
  191523. }
  191524. }
  191525. }
  191526. #endif
  191527. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191528. /* chop rows of bit depth 16 down to 8 */
  191529. void /* PRIVATE */
  191530. png_do_chop(png_row_infop row_info, png_bytep row)
  191531. {
  191532. png_debug(1, "in png_do_chop\n");
  191533. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191534. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  191535. #else
  191536. if (row_info->bit_depth == 16)
  191537. #endif
  191538. {
  191539. png_bytep sp = row;
  191540. png_bytep dp = row;
  191541. png_uint_32 i;
  191542. png_uint_32 istop = row_info->width * row_info->channels;
  191543. for (i = 0; i<istop; i++, sp += 2, dp++)
  191544. {
  191545. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  191546. /* This does a more accurate scaling of the 16-bit color
  191547. * value, rather than a simple low-byte truncation.
  191548. *
  191549. * What the ideal calculation should be:
  191550. * *dp = (((((png_uint_32)(*sp) << 8) |
  191551. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  191552. *
  191553. * GRR: no, I think this is what it really should be:
  191554. * *dp = (((((png_uint_32)(*sp) << 8) |
  191555. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  191556. *
  191557. * GRR: here's the exact calculation with shifts:
  191558. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  191559. * *dp = (temp - (temp >> 8)) >> 8;
  191560. *
  191561. * Approximate calculation with shift/add instead of multiply/divide:
  191562. * *dp = ((((png_uint_32)(*sp) << 8) |
  191563. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  191564. *
  191565. * What we actually do to avoid extra shifting and conversion:
  191566. */
  191567. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  191568. #else
  191569. /* Simply discard the low order byte */
  191570. *dp = *sp;
  191571. #endif
  191572. }
  191573. row_info->bit_depth = 8;
  191574. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191575. row_info->rowbytes = row_info->width * row_info->channels;
  191576. }
  191577. }
  191578. #endif
  191579. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191580. void /* PRIVATE */
  191581. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  191582. {
  191583. png_debug(1, "in png_do_read_swap_alpha\n");
  191584. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191585. if (row != NULL && row_info != NULL)
  191586. #endif
  191587. {
  191588. png_uint_32 row_width = row_info->width;
  191589. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191590. {
  191591. /* This converts from RGBA to ARGB */
  191592. if (row_info->bit_depth == 8)
  191593. {
  191594. png_bytep sp = row + row_info->rowbytes;
  191595. png_bytep dp = sp;
  191596. png_byte save;
  191597. png_uint_32 i;
  191598. for (i = 0; i < row_width; i++)
  191599. {
  191600. save = *(--sp);
  191601. *(--dp) = *(--sp);
  191602. *(--dp) = *(--sp);
  191603. *(--dp) = *(--sp);
  191604. *(--dp) = save;
  191605. }
  191606. }
  191607. /* This converts from RRGGBBAA to AARRGGBB */
  191608. else
  191609. {
  191610. png_bytep sp = row + row_info->rowbytes;
  191611. png_bytep dp = sp;
  191612. png_byte save[2];
  191613. png_uint_32 i;
  191614. for (i = 0; i < row_width; i++)
  191615. {
  191616. save[0] = *(--sp);
  191617. save[1] = *(--sp);
  191618. *(--dp) = *(--sp);
  191619. *(--dp) = *(--sp);
  191620. *(--dp) = *(--sp);
  191621. *(--dp) = *(--sp);
  191622. *(--dp) = *(--sp);
  191623. *(--dp) = *(--sp);
  191624. *(--dp) = save[0];
  191625. *(--dp) = save[1];
  191626. }
  191627. }
  191628. }
  191629. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191630. {
  191631. /* This converts from GA to AG */
  191632. if (row_info->bit_depth == 8)
  191633. {
  191634. png_bytep sp = row + row_info->rowbytes;
  191635. png_bytep dp = sp;
  191636. png_byte save;
  191637. png_uint_32 i;
  191638. for (i = 0; i < row_width; i++)
  191639. {
  191640. save = *(--sp);
  191641. *(--dp) = *(--sp);
  191642. *(--dp) = save;
  191643. }
  191644. }
  191645. /* This converts from GGAA to AAGG */
  191646. else
  191647. {
  191648. png_bytep sp = row + row_info->rowbytes;
  191649. png_bytep dp = sp;
  191650. png_byte save[2];
  191651. png_uint_32 i;
  191652. for (i = 0; i < row_width; i++)
  191653. {
  191654. save[0] = *(--sp);
  191655. save[1] = *(--sp);
  191656. *(--dp) = *(--sp);
  191657. *(--dp) = *(--sp);
  191658. *(--dp) = save[0];
  191659. *(--dp) = save[1];
  191660. }
  191661. }
  191662. }
  191663. }
  191664. }
  191665. #endif
  191666. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191667. void /* PRIVATE */
  191668. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  191669. {
  191670. png_debug(1, "in png_do_read_invert_alpha\n");
  191671. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191672. if (row != NULL && row_info != NULL)
  191673. #endif
  191674. {
  191675. png_uint_32 row_width = row_info->width;
  191676. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191677. {
  191678. /* This inverts the alpha channel in RGBA */
  191679. if (row_info->bit_depth == 8)
  191680. {
  191681. png_bytep sp = row + row_info->rowbytes;
  191682. png_bytep dp = sp;
  191683. png_uint_32 i;
  191684. for (i = 0; i < row_width; i++)
  191685. {
  191686. *(--dp) = (png_byte)(255 - *(--sp));
  191687. /* This does nothing:
  191688. *(--dp) = *(--sp);
  191689. *(--dp) = *(--sp);
  191690. *(--dp) = *(--sp);
  191691. We can replace it with:
  191692. */
  191693. sp-=3;
  191694. dp=sp;
  191695. }
  191696. }
  191697. /* This inverts the alpha channel in RRGGBBAA */
  191698. else
  191699. {
  191700. png_bytep sp = row + row_info->rowbytes;
  191701. png_bytep dp = sp;
  191702. png_uint_32 i;
  191703. for (i = 0; i < row_width; i++)
  191704. {
  191705. *(--dp) = (png_byte)(255 - *(--sp));
  191706. *(--dp) = (png_byte)(255 - *(--sp));
  191707. /* This does nothing:
  191708. *(--dp) = *(--sp);
  191709. *(--dp) = *(--sp);
  191710. *(--dp) = *(--sp);
  191711. *(--dp) = *(--sp);
  191712. *(--dp) = *(--sp);
  191713. *(--dp) = *(--sp);
  191714. We can replace it with:
  191715. */
  191716. sp-=6;
  191717. dp=sp;
  191718. }
  191719. }
  191720. }
  191721. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191722. {
  191723. /* This inverts the alpha channel in GA */
  191724. if (row_info->bit_depth == 8)
  191725. {
  191726. png_bytep sp = row + row_info->rowbytes;
  191727. png_bytep dp = sp;
  191728. png_uint_32 i;
  191729. for (i = 0; i < row_width; i++)
  191730. {
  191731. *(--dp) = (png_byte)(255 - *(--sp));
  191732. *(--dp) = *(--sp);
  191733. }
  191734. }
  191735. /* This inverts the alpha channel in GGAA */
  191736. else
  191737. {
  191738. png_bytep sp = row + row_info->rowbytes;
  191739. png_bytep dp = sp;
  191740. png_uint_32 i;
  191741. for (i = 0; i < row_width; i++)
  191742. {
  191743. *(--dp) = (png_byte)(255 - *(--sp));
  191744. *(--dp) = (png_byte)(255 - *(--sp));
  191745. /*
  191746. *(--dp) = *(--sp);
  191747. *(--dp) = *(--sp);
  191748. */
  191749. sp-=2;
  191750. dp=sp;
  191751. }
  191752. }
  191753. }
  191754. }
  191755. }
  191756. #endif
  191757. #if defined(PNG_READ_FILLER_SUPPORTED)
  191758. /* Add filler channel if we have RGB color */
  191759. void /* PRIVATE */
  191760. png_do_read_filler(png_row_infop row_info, png_bytep row,
  191761. png_uint_32 filler, png_uint_32 flags)
  191762. {
  191763. png_uint_32 i;
  191764. png_uint_32 row_width = row_info->width;
  191765. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  191766. png_byte lo_filler = (png_byte)(filler & 0xff);
  191767. png_debug(1, "in png_do_read_filler\n");
  191768. if (
  191769. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191770. row != NULL && row_info != NULL &&
  191771. #endif
  191772. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191773. {
  191774. if(row_info->bit_depth == 8)
  191775. {
  191776. /* This changes the data from G to GX */
  191777. if (flags & PNG_FLAG_FILLER_AFTER)
  191778. {
  191779. png_bytep sp = row + (png_size_t)row_width;
  191780. png_bytep dp = sp + (png_size_t)row_width;
  191781. for (i = 1; i < row_width; i++)
  191782. {
  191783. *(--dp) = lo_filler;
  191784. *(--dp) = *(--sp);
  191785. }
  191786. *(--dp) = lo_filler;
  191787. row_info->channels = 2;
  191788. row_info->pixel_depth = 16;
  191789. row_info->rowbytes = row_width * 2;
  191790. }
  191791. /* This changes the data from G to XG */
  191792. else
  191793. {
  191794. png_bytep sp = row + (png_size_t)row_width;
  191795. png_bytep dp = sp + (png_size_t)row_width;
  191796. for (i = 0; i < row_width; i++)
  191797. {
  191798. *(--dp) = *(--sp);
  191799. *(--dp) = lo_filler;
  191800. }
  191801. row_info->channels = 2;
  191802. row_info->pixel_depth = 16;
  191803. row_info->rowbytes = row_width * 2;
  191804. }
  191805. }
  191806. else if(row_info->bit_depth == 16)
  191807. {
  191808. /* This changes the data from GG to GGXX */
  191809. if (flags & PNG_FLAG_FILLER_AFTER)
  191810. {
  191811. png_bytep sp = row + (png_size_t)row_width * 2;
  191812. png_bytep dp = sp + (png_size_t)row_width * 2;
  191813. for (i = 1; i < row_width; i++)
  191814. {
  191815. *(--dp) = hi_filler;
  191816. *(--dp) = lo_filler;
  191817. *(--dp) = *(--sp);
  191818. *(--dp) = *(--sp);
  191819. }
  191820. *(--dp) = hi_filler;
  191821. *(--dp) = lo_filler;
  191822. row_info->channels = 2;
  191823. row_info->pixel_depth = 32;
  191824. row_info->rowbytes = row_width * 4;
  191825. }
  191826. /* This changes the data from GG to XXGG */
  191827. else
  191828. {
  191829. png_bytep sp = row + (png_size_t)row_width * 2;
  191830. png_bytep dp = sp + (png_size_t)row_width * 2;
  191831. for (i = 0; i < row_width; i++)
  191832. {
  191833. *(--dp) = *(--sp);
  191834. *(--dp) = *(--sp);
  191835. *(--dp) = hi_filler;
  191836. *(--dp) = lo_filler;
  191837. }
  191838. row_info->channels = 2;
  191839. row_info->pixel_depth = 32;
  191840. row_info->rowbytes = row_width * 4;
  191841. }
  191842. }
  191843. } /* COLOR_TYPE == GRAY */
  191844. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  191845. {
  191846. if(row_info->bit_depth == 8)
  191847. {
  191848. /* This changes the data from RGB to RGBX */
  191849. if (flags & PNG_FLAG_FILLER_AFTER)
  191850. {
  191851. png_bytep sp = row + (png_size_t)row_width * 3;
  191852. png_bytep dp = sp + (png_size_t)row_width;
  191853. for (i = 1; i < row_width; i++)
  191854. {
  191855. *(--dp) = lo_filler;
  191856. *(--dp) = *(--sp);
  191857. *(--dp) = *(--sp);
  191858. *(--dp) = *(--sp);
  191859. }
  191860. *(--dp) = lo_filler;
  191861. row_info->channels = 4;
  191862. row_info->pixel_depth = 32;
  191863. row_info->rowbytes = row_width * 4;
  191864. }
  191865. /* This changes the data from RGB to XRGB */
  191866. else
  191867. {
  191868. png_bytep sp = row + (png_size_t)row_width * 3;
  191869. png_bytep dp = sp + (png_size_t)row_width;
  191870. for (i = 0; i < row_width; i++)
  191871. {
  191872. *(--dp) = *(--sp);
  191873. *(--dp) = *(--sp);
  191874. *(--dp) = *(--sp);
  191875. *(--dp) = lo_filler;
  191876. }
  191877. row_info->channels = 4;
  191878. row_info->pixel_depth = 32;
  191879. row_info->rowbytes = row_width * 4;
  191880. }
  191881. }
  191882. else if(row_info->bit_depth == 16)
  191883. {
  191884. /* This changes the data from RRGGBB to RRGGBBXX */
  191885. if (flags & PNG_FLAG_FILLER_AFTER)
  191886. {
  191887. png_bytep sp = row + (png_size_t)row_width * 6;
  191888. png_bytep dp = sp + (png_size_t)row_width * 2;
  191889. for (i = 1; i < row_width; i++)
  191890. {
  191891. *(--dp) = hi_filler;
  191892. *(--dp) = lo_filler;
  191893. *(--dp) = *(--sp);
  191894. *(--dp) = *(--sp);
  191895. *(--dp) = *(--sp);
  191896. *(--dp) = *(--sp);
  191897. *(--dp) = *(--sp);
  191898. *(--dp) = *(--sp);
  191899. }
  191900. *(--dp) = hi_filler;
  191901. *(--dp) = lo_filler;
  191902. row_info->channels = 4;
  191903. row_info->pixel_depth = 64;
  191904. row_info->rowbytes = row_width * 8;
  191905. }
  191906. /* This changes the data from RRGGBB to XXRRGGBB */
  191907. else
  191908. {
  191909. png_bytep sp = row + (png_size_t)row_width * 6;
  191910. png_bytep dp = sp + (png_size_t)row_width * 2;
  191911. for (i = 0; i < row_width; i++)
  191912. {
  191913. *(--dp) = *(--sp);
  191914. *(--dp) = *(--sp);
  191915. *(--dp) = *(--sp);
  191916. *(--dp) = *(--sp);
  191917. *(--dp) = *(--sp);
  191918. *(--dp) = *(--sp);
  191919. *(--dp) = hi_filler;
  191920. *(--dp) = lo_filler;
  191921. }
  191922. row_info->channels = 4;
  191923. row_info->pixel_depth = 64;
  191924. row_info->rowbytes = row_width * 8;
  191925. }
  191926. }
  191927. } /* COLOR_TYPE == RGB */
  191928. }
  191929. #endif
  191930. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191931. /* expand grayscale files to RGB, with or without alpha */
  191932. void /* PRIVATE */
  191933. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  191934. {
  191935. png_uint_32 i;
  191936. png_uint_32 row_width = row_info->width;
  191937. png_debug(1, "in png_do_gray_to_rgb\n");
  191938. if (row_info->bit_depth >= 8 &&
  191939. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191940. row != NULL && row_info != NULL &&
  191941. #endif
  191942. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  191943. {
  191944. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191945. {
  191946. if (row_info->bit_depth == 8)
  191947. {
  191948. png_bytep sp = row + (png_size_t)row_width - 1;
  191949. png_bytep dp = sp + (png_size_t)row_width * 2;
  191950. for (i = 0; i < row_width; i++)
  191951. {
  191952. *(dp--) = *sp;
  191953. *(dp--) = *sp;
  191954. *(dp--) = *(sp--);
  191955. }
  191956. }
  191957. else
  191958. {
  191959. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  191960. png_bytep dp = sp + (png_size_t)row_width * 4;
  191961. for (i = 0; i < row_width; i++)
  191962. {
  191963. *(dp--) = *sp;
  191964. *(dp--) = *(sp - 1);
  191965. *(dp--) = *sp;
  191966. *(dp--) = *(sp - 1);
  191967. *(dp--) = *(sp--);
  191968. *(dp--) = *(sp--);
  191969. }
  191970. }
  191971. }
  191972. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191973. {
  191974. if (row_info->bit_depth == 8)
  191975. {
  191976. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  191977. png_bytep dp = sp + (png_size_t)row_width * 2;
  191978. for (i = 0; i < row_width; i++)
  191979. {
  191980. *(dp--) = *(sp--);
  191981. *(dp--) = *sp;
  191982. *(dp--) = *sp;
  191983. *(dp--) = *(sp--);
  191984. }
  191985. }
  191986. else
  191987. {
  191988. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  191989. png_bytep dp = sp + (png_size_t)row_width * 4;
  191990. for (i = 0; i < row_width; i++)
  191991. {
  191992. *(dp--) = *(sp--);
  191993. *(dp--) = *(sp--);
  191994. *(dp--) = *sp;
  191995. *(dp--) = *(sp - 1);
  191996. *(dp--) = *sp;
  191997. *(dp--) = *(sp - 1);
  191998. *(dp--) = *(sp--);
  191999. *(dp--) = *(sp--);
  192000. }
  192001. }
  192002. }
  192003. row_info->channels += (png_byte)2;
  192004. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  192005. row_info->pixel_depth = (png_byte)(row_info->channels *
  192006. row_info->bit_depth);
  192007. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192008. }
  192009. }
  192010. #endif
  192011. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  192012. /* reduce RGB files to grayscale, with or without alpha
  192013. * using the equation given in Poynton's ColorFAQ at
  192014. * <http://www.inforamp.net/~poynton/>
  192015. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  192016. *
  192017. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  192018. *
  192019. * We approximate this with
  192020. *
  192021. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  192022. *
  192023. * which can be expressed with integers as
  192024. *
  192025. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  192026. *
  192027. * The calculation is to be done in a linear colorspace.
  192028. *
  192029. * Other integer coefficents can be used via png_set_rgb_to_gray().
  192030. */
  192031. int /* PRIVATE */
  192032. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  192033. {
  192034. png_uint_32 i;
  192035. png_uint_32 row_width = row_info->width;
  192036. int rgb_error = 0;
  192037. png_debug(1, "in png_do_rgb_to_gray\n");
  192038. if (
  192039. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192040. row != NULL && row_info != NULL &&
  192041. #endif
  192042. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  192043. {
  192044. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  192045. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  192046. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  192047. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  192048. {
  192049. if (row_info->bit_depth == 8)
  192050. {
  192051. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192052. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  192053. {
  192054. png_bytep sp = row;
  192055. png_bytep dp = row;
  192056. for (i = 0; i < row_width; i++)
  192057. {
  192058. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  192059. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  192060. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  192061. if(red != green || red != blue)
  192062. {
  192063. rgb_error |= 1;
  192064. *(dp++) = png_ptr->gamma_from_1[
  192065. (rc*red+gc*green+bc*blue)>>15];
  192066. }
  192067. else
  192068. *(dp++) = *(sp-1);
  192069. }
  192070. }
  192071. else
  192072. #endif
  192073. {
  192074. png_bytep sp = row;
  192075. png_bytep dp = row;
  192076. for (i = 0; i < row_width; i++)
  192077. {
  192078. png_byte red = *(sp++);
  192079. png_byte green = *(sp++);
  192080. png_byte blue = *(sp++);
  192081. if(red != green || red != blue)
  192082. {
  192083. rgb_error |= 1;
  192084. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  192085. }
  192086. else
  192087. *(dp++) = *(sp-1);
  192088. }
  192089. }
  192090. }
  192091. else /* RGB bit_depth == 16 */
  192092. {
  192093. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192094. if (png_ptr->gamma_16_to_1 != NULL &&
  192095. png_ptr->gamma_16_from_1 != NULL)
  192096. {
  192097. png_bytep sp = row;
  192098. png_bytep dp = row;
  192099. for (i = 0; i < row_width; i++)
  192100. {
  192101. png_uint_16 red, green, blue, w;
  192102. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192103. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192104. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192105. if(red == green && red == blue)
  192106. w = red;
  192107. else
  192108. {
  192109. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  192110. png_ptr->gamma_shift][red>>8];
  192111. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  192112. png_ptr->gamma_shift][green>>8];
  192113. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  192114. png_ptr->gamma_shift][blue>>8];
  192115. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  192116. + bc*blue_1)>>15);
  192117. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  192118. png_ptr->gamma_shift][gray16 >> 8];
  192119. rgb_error |= 1;
  192120. }
  192121. *(dp++) = (png_byte)((w>>8) & 0xff);
  192122. *(dp++) = (png_byte)(w & 0xff);
  192123. }
  192124. }
  192125. else
  192126. #endif
  192127. {
  192128. png_bytep sp = row;
  192129. png_bytep dp = row;
  192130. for (i = 0; i < row_width; i++)
  192131. {
  192132. png_uint_16 red, green, blue, gray16;
  192133. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192134. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192135. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192136. if(red != green || red != blue)
  192137. rgb_error |= 1;
  192138. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  192139. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  192140. *(dp++) = (png_byte)(gray16 & 0xff);
  192141. }
  192142. }
  192143. }
  192144. }
  192145. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  192146. {
  192147. if (row_info->bit_depth == 8)
  192148. {
  192149. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192150. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  192151. {
  192152. png_bytep sp = row;
  192153. png_bytep dp = row;
  192154. for (i = 0; i < row_width; i++)
  192155. {
  192156. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  192157. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  192158. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  192159. if(red != green || red != blue)
  192160. rgb_error |= 1;
  192161. *(dp++) = png_ptr->gamma_from_1
  192162. [(rc*red + gc*green + bc*blue)>>15];
  192163. *(dp++) = *(sp++); /* alpha */
  192164. }
  192165. }
  192166. else
  192167. #endif
  192168. {
  192169. png_bytep sp = row;
  192170. png_bytep dp = row;
  192171. for (i = 0; i < row_width; i++)
  192172. {
  192173. png_byte red = *(sp++);
  192174. png_byte green = *(sp++);
  192175. png_byte blue = *(sp++);
  192176. if(red != green || red != blue)
  192177. rgb_error |= 1;
  192178. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  192179. *(dp++) = *(sp++); /* alpha */
  192180. }
  192181. }
  192182. }
  192183. else /* RGBA bit_depth == 16 */
  192184. {
  192185. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192186. if (png_ptr->gamma_16_to_1 != NULL &&
  192187. png_ptr->gamma_16_from_1 != NULL)
  192188. {
  192189. png_bytep sp = row;
  192190. png_bytep dp = row;
  192191. for (i = 0; i < row_width; i++)
  192192. {
  192193. png_uint_16 red, green, blue, w;
  192194. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192195. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192196. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192197. if(red == green && red == blue)
  192198. w = red;
  192199. else
  192200. {
  192201. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  192202. png_ptr->gamma_shift][red>>8];
  192203. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  192204. png_ptr->gamma_shift][green>>8];
  192205. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  192206. png_ptr->gamma_shift][blue>>8];
  192207. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  192208. + gc * green_1 + bc * blue_1)>>15);
  192209. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  192210. png_ptr->gamma_shift][gray16 >> 8];
  192211. rgb_error |= 1;
  192212. }
  192213. *(dp++) = (png_byte)((w>>8) & 0xff);
  192214. *(dp++) = (png_byte)(w & 0xff);
  192215. *(dp++) = *(sp++); /* alpha */
  192216. *(dp++) = *(sp++);
  192217. }
  192218. }
  192219. else
  192220. #endif
  192221. {
  192222. png_bytep sp = row;
  192223. png_bytep dp = row;
  192224. for (i = 0; i < row_width; i++)
  192225. {
  192226. png_uint_16 red, green, blue, gray16;
  192227. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192228. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192229. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192230. if(red != green || red != blue)
  192231. rgb_error |= 1;
  192232. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  192233. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  192234. *(dp++) = (png_byte)(gray16 & 0xff);
  192235. *(dp++) = *(sp++); /* alpha */
  192236. *(dp++) = *(sp++);
  192237. }
  192238. }
  192239. }
  192240. }
  192241. row_info->channels -= (png_byte)2;
  192242. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  192243. row_info->pixel_depth = (png_byte)(row_info->channels *
  192244. row_info->bit_depth);
  192245. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192246. }
  192247. return rgb_error;
  192248. }
  192249. #endif
  192250. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  192251. * large of png_color. This lets grayscale images be treated as
  192252. * paletted. Most useful for gamma correction and simplification
  192253. * of code.
  192254. */
  192255. void PNGAPI
  192256. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  192257. {
  192258. int num_palette;
  192259. int color_inc;
  192260. int i;
  192261. int v;
  192262. png_debug(1, "in png_do_build_grayscale_palette\n");
  192263. if (palette == NULL)
  192264. return;
  192265. switch (bit_depth)
  192266. {
  192267. case 1:
  192268. num_palette = 2;
  192269. color_inc = 0xff;
  192270. break;
  192271. case 2:
  192272. num_palette = 4;
  192273. color_inc = 0x55;
  192274. break;
  192275. case 4:
  192276. num_palette = 16;
  192277. color_inc = 0x11;
  192278. break;
  192279. case 8:
  192280. num_palette = 256;
  192281. color_inc = 1;
  192282. break;
  192283. default:
  192284. num_palette = 0;
  192285. color_inc = 0;
  192286. break;
  192287. }
  192288. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  192289. {
  192290. palette[i].red = (png_byte)v;
  192291. palette[i].green = (png_byte)v;
  192292. palette[i].blue = (png_byte)v;
  192293. }
  192294. }
  192295. /* This function is currently unused. Do we really need it? */
  192296. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  192297. void /* PRIVATE */
  192298. png_correct_palette(png_structp png_ptr, png_colorp palette,
  192299. int num_palette)
  192300. {
  192301. png_debug(1, "in png_correct_palette\n");
  192302. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  192303. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  192304. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  192305. {
  192306. png_color back, back_1;
  192307. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  192308. {
  192309. back.red = png_ptr->gamma_table[png_ptr->background.red];
  192310. back.green = png_ptr->gamma_table[png_ptr->background.green];
  192311. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  192312. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  192313. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  192314. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  192315. }
  192316. else
  192317. {
  192318. double g;
  192319. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  192320. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  192321. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  192322. {
  192323. back.red = png_ptr->background.red;
  192324. back.green = png_ptr->background.green;
  192325. back.blue = png_ptr->background.blue;
  192326. }
  192327. else
  192328. {
  192329. back.red =
  192330. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192331. 255.0 + 0.5);
  192332. back.green =
  192333. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192334. 255.0 + 0.5);
  192335. back.blue =
  192336. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192337. 255.0 + 0.5);
  192338. }
  192339. g = 1.0 / png_ptr->background_gamma;
  192340. back_1.red =
  192341. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192342. 255.0 + 0.5);
  192343. back_1.green =
  192344. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192345. 255.0 + 0.5);
  192346. back_1.blue =
  192347. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192348. 255.0 + 0.5);
  192349. }
  192350. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192351. {
  192352. png_uint_32 i;
  192353. for (i = 0; i < (png_uint_32)num_palette; i++)
  192354. {
  192355. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  192356. {
  192357. palette[i] = back;
  192358. }
  192359. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  192360. {
  192361. png_byte v, w;
  192362. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  192363. png_composite(w, v, png_ptr->trans[i], back_1.red);
  192364. palette[i].red = png_ptr->gamma_from_1[w];
  192365. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  192366. png_composite(w, v, png_ptr->trans[i], back_1.green);
  192367. palette[i].green = png_ptr->gamma_from_1[w];
  192368. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  192369. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  192370. palette[i].blue = png_ptr->gamma_from_1[w];
  192371. }
  192372. else
  192373. {
  192374. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192375. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192376. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192377. }
  192378. }
  192379. }
  192380. else
  192381. {
  192382. int i;
  192383. for (i = 0; i < num_palette; i++)
  192384. {
  192385. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  192386. {
  192387. palette[i] = back;
  192388. }
  192389. else
  192390. {
  192391. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192392. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192393. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192394. }
  192395. }
  192396. }
  192397. }
  192398. else
  192399. #endif
  192400. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192401. if (png_ptr->transformations & PNG_GAMMA)
  192402. {
  192403. int i;
  192404. for (i = 0; i < num_palette; i++)
  192405. {
  192406. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192407. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192408. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192409. }
  192410. }
  192411. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192412. else
  192413. #endif
  192414. #endif
  192415. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192416. if (png_ptr->transformations & PNG_BACKGROUND)
  192417. {
  192418. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192419. {
  192420. png_color back;
  192421. back.red = (png_byte)png_ptr->background.red;
  192422. back.green = (png_byte)png_ptr->background.green;
  192423. back.blue = (png_byte)png_ptr->background.blue;
  192424. for (i = 0; i < (int)png_ptr->num_trans; i++)
  192425. {
  192426. if (png_ptr->trans[i] == 0)
  192427. {
  192428. palette[i].red = back.red;
  192429. palette[i].green = back.green;
  192430. palette[i].blue = back.blue;
  192431. }
  192432. else if (png_ptr->trans[i] != 0xff)
  192433. {
  192434. png_composite(palette[i].red, png_ptr->palette[i].red,
  192435. png_ptr->trans[i], back.red);
  192436. png_composite(palette[i].green, png_ptr->palette[i].green,
  192437. png_ptr->trans[i], back.green);
  192438. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  192439. png_ptr->trans[i], back.blue);
  192440. }
  192441. }
  192442. }
  192443. else /* assume grayscale palette (what else could it be?) */
  192444. {
  192445. int i;
  192446. for (i = 0; i < num_palette; i++)
  192447. {
  192448. if (i == (png_byte)png_ptr->trans_values.gray)
  192449. {
  192450. palette[i].red = (png_byte)png_ptr->background.red;
  192451. palette[i].green = (png_byte)png_ptr->background.green;
  192452. palette[i].blue = (png_byte)png_ptr->background.blue;
  192453. }
  192454. }
  192455. }
  192456. }
  192457. #endif
  192458. }
  192459. #endif
  192460. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192461. /* Replace any alpha or transparency with the supplied background color.
  192462. * "background" is already in the screen gamma, while "background_1" is
  192463. * at a gamma of 1.0. Paletted files have already been taken care of.
  192464. */
  192465. void /* PRIVATE */
  192466. png_do_background(png_row_infop row_info, png_bytep row,
  192467. png_color_16p trans_values, png_color_16p background
  192468. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192469. , png_color_16p background_1,
  192470. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  192471. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  192472. png_uint_16pp gamma_16_to_1, int gamma_shift
  192473. #endif
  192474. )
  192475. {
  192476. png_bytep sp, dp;
  192477. png_uint_32 i;
  192478. png_uint_32 row_width=row_info->width;
  192479. int shift;
  192480. png_debug(1, "in png_do_background\n");
  192481. if (background != NULL &&
  192482. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192483. row != NULL && row_info != NULL &&
  192484. #endif
  192485. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  192486. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  192487. {
  192488. switch (row_info->color_type)
  192489. {
  192490. case PNG_COLOR_TYPE_GRAY:
  192491. {
  192492. switch (row_info->bit_depth)
  192493. {
  192494. case 1:
  192495. {
  192496. sp = row;
  192497. shift = 7;
  192498. for (i = 0; i < row_width; i++)
  192499. {
  192500. if ((png_uint_16)((*sp >> shift) & 0x01)
  192501. == trans_values->gray)
  192502. {
  192503. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  192504. *sp |= (png_byte)(background->gray << shift);
  192505. }
  192506. if (!shift)
  192507. {
  192508. shift = 7;
  192509. sp++;
  192510. }
  192511. else
  192512. shift--;
  192513. }
  192514. break;
  192515. }
  192516. case 2:
  192517. {
  192518. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192519. if (gamma_table != NULL)
  192520. {
  192521. sp = row;
  192522. shift = 6;
  192523. for (i = 0; i < row_width; i++)
  192524. {
  192525. if ((png_uint_16)((*sp >> shift) & 0x03)
  192526. == trans_values->gray)
  192527. {
  192528. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192529. *sp |= (png_byte)(background->gray << shift);
  192530. }
  192531. else
  192532. {
  192533. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  192534. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  192535. (p << 4) | (p << 6)] >> 6) & 0x03);
  192536. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192537. *sp |= (png_byte)(g << shift);
  192538. }
  192539. if (!shift)
  192540. {
  192541. shift = 6;
  192542. sp++;
  192543. }
  192544. else
  192545. shift -= 2;
  192546. }
  192547. }
  192548. else
  192549. #endif
  192550. {
  192551. sp = row;
  192552. shift = 6;
  192553. for (i = 0; i < row_width; i++)
  192554. {
  192555. if ((png_uint_16)((*sp >> shift) & 0x03)
  192556. == trans_values->gray)
  192557. {
  192558. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192559. *sp |= (png_byte)(background->gray << shift);
  192560. }
  192561. if (!shift)
  192562. {
  192563. shift = 6;
  192564. sp++;
  192565. }
  192566. else
  192567. shift -= 2;
  192568. }
  192569. }
  192570. break;
  192571. }
  192572. case 4:
  192573. {
  192574. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192575. if (gamma_table != NULL)
  192576. {
  192577. sp = row;
  192578. shift = 4;
  192579. for (i = 0; i < row_width; i++)
  192580. {
  192581. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192582. == trans_values->gray)
  192583. {
  192584. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192585. *sp |= (png_byte)(background->gray << shift);
  192586. }
  192587. else
  192588. {
  192589. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  192590. png_byte g = (png_byte)((gamma_table[p |
  192591. (p << 4)] >> 4) & 0x0f);
  192592. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192593. *sp |= (png_byte)(g << shift);
  192594. }
  192595. if (!shift)
  192596. {
  192597. shift = 4;
  192598. sp++;
  192599. }
  192600. else
  192601. shift -= 4;
  192602. }
  192603. }
  192604. else
  192605. #endif
  192606. {
  192607. sp = row;
  192608. shift = 4;
  192609. for (i = 0; i < row_width; i++)
  192610. {
  192611. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192612. == trans_values->gray)
  192613. {
  192614. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192615. *sp |= (png_byte)(background->gray << shift);
  192616. }
  192617. if (!shift)
  192618. {
  192619. shift = 4;
  192620. sp++;
  192621. }
  192622. else
  192623. shift -= 4;
  192624. }
  192625. }
  192626. break;
  192627. }
  192628. case 8:
  192629. {
  192630. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192631. if (gamma_table != NULL)
  192632. {
  192633. sp = row;
  192634. for (i = 0; i < row_width; i++, sp++)
  192635. {
  192636. if (*sp == trans_values->gray)
  192637. {
  192638. *sp = (png_byte)background->gray;
  192639. }
  192640. else
  192641. {
  192642. *sp = gamma_table[*sp];
  192643. }
  192644. }
  192645. }
  192646. else
  192647. #endif
  192648. {
  192649. sp = row;
  192650. for (i = 0; i < row_width; i++, sp++)
  192651. {
  192652. if (*sp == trans_values->gray)
  192653. {
  192654. *sp = (png_byte)background->gray;
  192655. }
  192656. }
  192657. }
  192658. break;
  192659. }
  192660. case 16:
  192661. {
  192662. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192663. if (gamma_16 != NULL)
  192664. {
  192665. sp = row;
  192666. for (i = 0; i < row_width; i++, sp += 2)
  192667. {
  192668. png_uint_16 v;
  192669. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192670. if (v == trans_values->gray)
  192671. {
  192672. /* background is already in screen gamma */
  192673. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192674. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192675. }
  192676. else
  192677. {
  192678. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192679. *sp = (png_byte)((v >> 8) & 0xff);
  192680. *(sp + 1) = (png_byte)(v & 0xff);
  192681. }
  192682. }
  192683. }
  192684. else
  192685. #endif
  192686. {
  192687. sp = row;
  192688. for (i = 0; i < row_width; i++, sp += 2)
  192689. {
  192690. png_uint_16 v;
  192691. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192692. if (v == trans_values->gray)
  192693. {
  192694. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192695. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192696. }
  192697. }
  192698. }
  192699. break;
  192700. }
  192701. }
  192702. break;
  192703. }
  192704. case PNG_COLOR_TYPE_RGB:
  192705. {
  192706. if (row_info->bit_depth == 8)
  192707. {
  192708. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192709. if (gamma_table != NULL)
  192710. {
  192711. sp = row;
  192712. for (i = 0; i < row_width; i++, sp += 3)
  192713. {
  192714. if (*sp == trans_values->red &&
  192715. *(sp + 1) == trans_values->green &&
  192716. *(sp + 2) == trans_values->blue)
  192717. {
  192718. *sp = (png_byte)background->red;
  192719. *(sp + 1) = (png_byte)background->green;
  192720. *(sp + 2) = (png_byte)background->blue;
  192721. }
  192722. else
  192723. {
  192724. *sp = gamma_table[*sp];
  192725. *(sp + 1) = gamma_table[*(sp + 1)];
  192726. *(sp + 2) = gamma_table[*(sp + 2)];
  192727. }
  192728. }
  192729. }
  192730. else
  192731. #endif
  192732. {
  192733. sp = row;
  192734. for (i = 0; i < row_width; i++, sp += 3)
  192735. {
  192736. if (*sp == trans_values->red &&
  192737. *(sp + 1) == trans_values->green &&
  192738. *(sp + 2) == trans_values->blue)
  192739. {
  192740. *sp = (png_byte)background->red;
  192741. *(sp + 1) = (png_byte)background->green;
  192742. *(sp + 2) = (png_byte)background->blue;
  192743. }
  192744. }
  192745. }
  192746. }
  192747. else /* if (row_info->bit_depth == 16) */
  192748. {
  192749. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192750. if (gamma_16 != NULL)
  192751. {
  192752. sp = row;
  192753. for (i = 0; i < row_width; i++, sp += 6)
  192754. {
  192755. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192756. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192757. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192758. if (r == trans_values->red && g == trans_values->green &&
  192759. b == trans_values->blue)
  192760. {
  192761. /* background is already in screen gamma */
  192762. *sp = (png_byte)((background->red >> 8) & 0xff);
  192763. *(sp + 1) = (png_byte)(background->red & 0xff);
  192764. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192765. *(sp + 3) = (png_byte)(background->green & 0xff);
  192766. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192767. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192768. }
  192769. else
  192770. {
  192771. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192772. *sp = (png_byte)((v >> 8) & 0xff);
  192773. *(sp + 1) = (png_byte)(v & 0xff);
  192774. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  192775. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  192776. *(sp + 3) = (png_byte)(v & 0xff);
  192777. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  192778. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  192779. *(sp + 5) = (png_byte)(v & 0xff);
  192780. }
  192781. }
  192782. }
  192783. else
  192784. #endif
  192785. {
  192786. sp = row;
  192787. for (i = 0; i < row_width; i++, sp += 6)
  192788. {
  192789. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  192790. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192791. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192792. if (r == trans_values->red && g == trans_values->green &&
  192793. b == trans_values->blue)
  192794. {
  192795. *sp = (png_byte)((background->red >> 8) & 0xff);
  192796. *(sp + 1) = (png_byte)(background->red & 0xff);
  192797. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192798. *(sp + 3) = (png_byte)(background->green & 0xff);
  192799. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192800. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192801. }
  192802. }
  192803. }
  192804. }
  192805. break;
  192806. }
  192807. case PNG_COLOR_TYPE_GRAY_ALPHA:
  192808. {
  192809. if (row_info->bit_depth == 8)
  192810. {
  192811. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192812. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  192813. gamma_table != NULL)
  192814. {
  192815. sp = row;
  192816. dp = row;
  192817. for (i = 0; i < row_width; i++, sp += 2, dp++)
  192818. {
  192819. png_uint_16 a = *(sp + 1);
  192820. if (a == 0xff)
  192821. {
  192822. *dp = gamma_table[*sp];
  192823. }
  192824. else if (a == 0)
  192825. {
  192826. /* background is already in screen gamma */
  192827. *dp = (png_byte)background->gray;
  192828. }
  192829. else
  192830. {
  192831. png_byte v, w;
  192832. v = gamma_to_1[*sp];
  192833. png_composite(w, v, a, background_1->gray);
  192834. *dp = gamma_from_1[w];
  192835. }
  192836. }
  192837. }
  192838. else
  192839. #endif
  192840. {
  192841. sp = row;
  192842. dp = row;
  192843. for (i = 0; i < row_width; i++, sp += 2, dp++)
  192844. {
  192845. png_byte a = *(sp + 1);
  192846. if (a == 0xff)
  192847. {
  192848. *dp = *sp;
  192849. }
  192850. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192851. else if (a == 0)
  192852. {
  192853. *dp = (png_byte)background->gray;
  192854. }
  192855. else
  192856. {
  192857. png_composite(*dp, *sp, a, background_1->gray);
  192858. }
  192859. #else
  192860. *dp = (png_byte)background->gray;
  192861. #endif
  192862. }
  192863. }
  192864. }
  192865. else /* if (png_ptr->bit_depth == 16) */
  192866. {
  192867. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192868. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  192869. gamma_16_to_1 != NULL)
  192870. {
  192871. sp = row;
  192872. dp = row;
  192873. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  192874. {
  192875. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192876. if (a == (png_uint_16)0xffff)
  192877. {
  192878. png_uint_16 v;
  192879. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192880. *dp = (png_byte)((v >> 8) & 0xff);
  192881. *(dp + 1) = (png_byte)(v & 0xff);
  192882. }
  192883. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192884. else if (a == 0)
  192885. #else
  192886. else
  192887. #endif
  192888. {
  192889. /* background is already in screen gamma */
  192890. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192891. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192892. }
  192893. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192894. else
  192895. {
  192896. png_uint_16 g, v, w;
  192897. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  192898. png_composite_16(v, g, a, background_1->gray);
  192899. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  192900. *dp = (png_byte)((w >> 8) & 0xff);
  192901. *(dp + 1) = (png_byte)(w & 0xff);
  192902. }
  192903. #endif
  192904. }
  192905. }
  192906. else
  192907. #endif
  192908. {
  192909. sp = row;
  192910. dp = row;
  192911. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  192912. {
  192913. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192914. if (a == (png_uint_16)0xffff)
  192915. {
  192916. png_memcpy(dp, sp, 2);
  192917. }
  192918. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192919. else if (a == 0)
  192920. #else
  192921. else
  192922. #endif
  192923. {
  192924. *dp = (png_byte)((background->gray >> 8) & 0xff);
  192925. *(dp + 1) = (png_byte)(background->gray & 0xff);
  192926. }
  192927. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192928. else
  192929. {
  192930. png_uint_16 g, v;
  192931. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192932. png_composite_16(v, g, a, background_1->gray);
  192933. *dp = (png_byte)((v >> 8) & 0xff);
  192934. *(dp + 1) = (png_byte)(v & 0xff);
  192935. }
  192936. #endif
  192937. }
  192938. }
  192939. }
  192940. break;
  192941. }
  192942. case PNG_COLOR_TYPE_RGB_ALPHA:
  192943. {
  192944. if (row_info->bit_depth == 8)
  192945. {
  192946. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192947. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  192948. gamma_table != NULL)
  192949. {
  192950. sp = row;
  192951. dp = row;
  192952. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  192953. {
  192954. png_byte a = *(sp + 3);
  192955. if (a == 0xff)
  192956. {
  192957. *dp = gamma_table[*sp];
  192958. *(dp + 1) = gamma_table[*(sp + 1)];
  192959. *(dp + 2) = gamma_table[*(sp + 2)];
  192960. }
  192961. else if (a == 0)
  192962. {
  192963. /* background is already in screen gamma */
  192964. *dp = (png_byte)background->red;
  192965. *(dp + 1) = (png_byte)background->green;
  192966. *(dp + 2) = (png_byte)background->blue;
  192967. }
  192968. else
  192969. {
  192970. png_byte v, w;
  192971. v = gamma_to_1[*sp];
  192972. png_composite(w, v, a, background_1->red);
  192973. *dp = gamma_from_1[w];
  192974. v = gamma_to_1[*(sp + 1)];
  192975. png_composite(w, v, a, background_1->green);
  192976. *(dp + 1) = gamma_from_1[w];
  192977. v = gamma_to_1[*(sp + 2)];
  192978. png_composite(w, v, a, background_1->blue);
  192979. *(dp + 2) = gamma_from_1[w];
  192980. }
  192981. }
  192982. }
  192983. else
  192984. #endif
  192985. {
  192986. sp = row;
  192987. dp = row;
  192988. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  192989. {
  192990. png_byte a = *(sp + 3);
  192991. if (a == 0xff)
  192992. {
  192993. *dp = *sp;
  192994. *(dp + 1) = *(sp + 1);
  192995. *(dp + 2) = *(sp + 2);
  192996. }
  192997. else if (a == 0)
  192998. {
  192999. *dp = (png_byte)background->red;
  193000. *(dp + 1) = (png_byte)background->green;
  193001. *(dp + 2) = (png_byte)background->blue;
  193002. }
  193003. else
  193004. {
  193005. png_composite(*dp, *sp, a, background->red);
  193006. png_composite(*(dp + 1), *(sp + 1), a,
  193007. background->green);
  193008. png_composite(*(dp + 2), *(sp + 2), a,
  193009. background->blue);
  193010. }
  193011. }
  193012. }
  193013. }
  193014. else /* if (row_info->bit_depth == 16) */
  193015. {
  193016. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193017. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  193018. gamma_16_to_1 != NULL)
  193019. {
  193020. sp = row;
  193021. dp = row;
  193022. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  193023. {
  193024. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  193025. << 8) + (png_uint_16)(*(sp + 7)));
  193026. if (a == (png_uint_16)0xffff)
  193027. {
  193028. png_uint_16 v;
  193029. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  193030. *dp = (png_byte)((v >> 8) & 0xff);
  193031. *(dp + 1) = (png_byte)(v & 0xff);
  193032. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  193033. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  193034. *(dp + 3) = (png_byte)(v & 0xff);
  193035. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  193036. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  193037. *(dp + 5) = (png_byte)(v & 0xff);
  193038. }
  193039. else if (a == 0)
  193040. {
  193041. /* background is already in screen gamma */
  193042. *dp = (png_byte)((background->red >> 8) & 0xff);
  193043. *(dp + 1) = (png_byte)(background->red & 0xff);
  193044. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  193045. *(dp + 3) = (png_byte)(background->green & 0xff);
  193046. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  193047. *(dp + 5) = (png_byte)(background->blue & 0xff);
  193048. }
  193049. else
  193050. {
  193051. png_uint_16 v, w, x;
  193052. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  193053. png_composite_16(w, v, a, background_1->red);
  193054. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  193055. *dp = (png_byte)((x >> 8) & 0xff);
  193056. *(dp + 1) = (png_byte)(x & 0xff);
  193057. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  193058. png_composite_16(w, v, a, background_1->green);
  193059. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  193060. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  193061. *(dp + 3) = (png_byte)(x & 0xff);
  193062. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  193063. png_composite_16(w, v, a, background_1->blue);
  193064. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  193065. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  193066. *(dp + 5) = (png_byte)(x & 0xff);
  193067. }
  193068. }
  193069. }
  193070. else
  193071. #endif
  193072. {
  193073. sp = row;
  193074. dp = row;
  193075. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  193076. {
  193077. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  193078. << 8) + (png_uint_16)(*(sp + 7)));
  193079. if (a == (png_uint_16)0xffff)
  193080. {
  193081. png_memcpy(dp, sp, 6);
  193082. }
  193083. else if (a == 0)
  193084. {
  193085. *dp = (png_byte)((background->red >> 8) & 0xff);
  193086. *(dp + 1) = (png_byte)(background->red & 0xff);
  193087. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  193088. *(dp + 3) = (png_byte)(background->green & 0xff);
  193089. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  193090. *(dp + 5) = (png_byte)(background->blue & 0xff);
  193091. }
  193092. else
  193093. {
  193094. png_uint_16 v;
  193095. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  193096. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  193097. + *(sp + 3));
  193098. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  193099. + *(sp + 5));
  193100. png_composite_16(v, r, a, background->red);
  193101. *dp = (png_byte)((v >> 8) & 0xff);
  193102. *(dp + 1) = (png_byte)(v & 0xff);
  193103. png_composite_16(v, g, a, background->green);
  193104. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  193105. *(dp + 3) = (png_byte)(v & 0xff);
  193106. png_composite_16(v, b, a, background->blue);
  193107. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  193108. *(dp + 5) = (png_byte)(v & 0xff);
  193109. }
  193110. }
  193111. }
  193112. }
  193113. break;
  193114. }
  193115. }
  193116. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  193117. {
  193118. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  193119. row_info->channels--;
  193120. row_info->pixel_depth = (png_byte)(row_info->channels *
  193121. row_info->bit_depth);
  193122. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193123. }
  193124. }
  193125. }
  193126. #endif
  193127. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193128. /* Gamma correct the image, avoiding the alpha channel. Make sure
  193129. * you do this after you deal with the transparency issue on grayscale
  193130. * or RGB images. If your bit depth is 8, use gamma_table, if it
  193131. * is 16, use gamma_16_table and gamma_shift. Build these with
  193132. * build_gamma_table().
  193133. */
  193134. void /* PRIVATE */
  193135. png_do_gamma(png_row_infop row_info, png_bytep row,
  193136. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  193137. int gamma_shift)
  193138. {
  193139. png_bytep sp;
  193140. png_uint_32 i;
  193141. png_uint_32 row_width=row_info->width;
  193142. png_debug(1, "in png_do_gamma\n");
  193143. if (
  193144. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193145. row != NULL && row_info != NULL &&
  193146. #endif
  193147. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  193148. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  193149. {
  193150. switch (row_info->color_type)
  193151. {
  193152. case PNG_COLOR_TYPE_RGB:
  193153. {
  193154. if (row_info->bit_depth == 8)
  193155. {
  193156. sp = row;
  193157. for (i = 0; i < row_width; i++)
  193158. {
  193159. *sp = gamma_table[*sp];
  193160. sp++;
  193161. *sp = gamma_table[*sp];
  193162. sp++;
  193163. *sp = gamma_table[*sp];
  193164. sp++;
  193165. }
  193166. }
  193167. else /* if (row_info->bit_depth == 16) */
  193168. {
  193169. sp = row;
  193170. for (i = 0; i < row_width; i++)
  193171. {
  193172. png_uint_16 v;
  193173. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193174. *sp = (png_byte)((v >> 8) & 0xff);
  193175. *(sp + 1) = (png_byte)(v & 0xff);
  193176. sp += 2;
  193177. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193178. *sp = (png_byte)((v >> 8) & 0xff);
  193179. *(sp + 1) = (png_byte)(v & 0xff);
  193180. sp += 2;
  193181. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193182. *sp = (png_byte)((v >> 8) & 0xff);
  193183. *(sp + 1) = (png_byte)(v & 0xff);
  193184. sp += 2;
  193185. }
  193186. }
  193187. break;
  193188. }
  193189. case PNG_COLOR_TYPE_RGB_ALPHA:
  193190. {
  193191. if (row_info->bit_depth == 8)
  193192. {
  193193. sp = row;
  193194. for (i = 0; i < row_width; i++)
  193195. {
  193196. *sp = gamma_table[*sp];
  193197. sp++;
  193198. *sp = gamma_table[*sp];
  193199. sp++;
  193200. *sp = gamma_table[*sp];
  193201. sp++;
  193202. sp++;
  193203. }
  193204. }
  193205. else /* if (row_info->bit_depth == 16) */
  193206. {
  193207. sp = row;
  193208. for (i = 0; i < row_width; i++)
  193209. {
  193210. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193211. *sp = (png_byte)((v >> 8) & 0xff);
  193212. *(sp + 1) = (png_byte)(v & 0xff);
  193213. sp += 2;
  193214. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193215. *sp = (png_byte)((v >> 8) & 0xff);
  193216. *(sp + 1) = (png_byte)(v & 0xff);
  193217. sp += 2;
  193218. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193219. *sp = (png_byte)((v >> 8) & 0xff);
  193220. *(sp + 1) = (png_byte)(v & 0xff);
  193221. sp += 4;
  193222. }
  193223. }
  193224. break;
  193225. }
  193226. case PNG_COLOR_TYPE_GRAY_ALPHA:
  193227. {
  193228. if (row_info->bit_depth == 8)
  193229. {
  193230. sp = row;
  193231. for (i = 0; i < row_width; i++)
  193232. {
  193233. *sp = gamma_table[*sp];
  193234. sp += 2;
  193235. }
  193236. }
  193237. else /* if (row_info->bit_depth == 16) */
  193238. {
  193239. sp = row;
  193240. for (i = 0; i < row_width; i++)
  193241. {
  193242. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193243. *sp = (png_byte)((v >> 8) & 0xff);
  193244. *(sp + 1) = (png_byte)(v & 0xff);
  193245. sp += 4;
  193246. }
  193247. }
  193248. break;
  193249. }
  193250. case PNG_COLOR_TYPE_GRAY:
  193251. {
  193252. if (row_info->bit_depth == 2)
  193253. {
  193254. sp = row;
  193255. for (i = 0; i < row_width; i += 4)
  193256. {
  193257. int a = *sp & 0xc0;
  193258. int b = *sp & 0x30;
  193259. int c = *sp & 0x0c;
  193260. int d = *sp & 0x03;
  193261. *sp = (png_byte)(
  193262. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  193263. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  193264. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  193265. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  193266. sp++;
  193267. }
  193268. }
  193269. if (row_info->bit_depth == 4)
  193270. {
  193271. sp = row;
  193272. for (i = 0; i < row_width; i += 2)
  193273. {
  193274. int msb = *sp & 0xf0;
  193275. int lsb = *sp & 0x0f;
  193276. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  193277. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  193278. sp++;
  193279. }
  193280. }
  193281. else if (row_info->bit_depth == 8)
  193282. {
  193283. sp = row;
  193284. for (i = 0; i < row_width; i++)
  193285. {
  193286. *sp = gamma_table[*sp];
  193287. sp++;
  193288. }
  193289. }
  193290. else if (row_info->bit_depth == 16)
  193291. {
  193292. sp = row;
  193293. for (i = 0; i < row_width; i++)
  193294. {
  193295. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193296. *sp = (png_byte)((v >> 8) & 0xff);
  193297. *(sp + 1) = (png_byte)(v & 0xff);
  193298. sp += 2;
  193299. }
  193300. }
  193301. break;
  193302. }
  193303. }
  193304. }
  193305. }
  193306. #endif
  193307. #if defined(PNG_READ_EXPAND_SUPPORTED)
  193308. /* Expands a palette row to an RGB or RGBA row depending
  193309. * upon whether you supply trans and num_trans.
  193310. */
  193311. void /* PRIVATE */
  193312. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  193313. png_colorp palette, png_bytep trans, int num_trans)
  193314. {
  193315. int shift, value;
  193316. png_bytep sp, dp;
  193317. png_uint_32 i;
  193318. png_uint_32 row_width=row_info->width;
  193319. png_debug(1, "in png_do_expand_palette\n");
  193320. if (
  193321. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193322. row != NULL && row_info != NULL &&
  193323. #endif
  193324. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  193325. {
  193326. if (row_info->bit_depth < 8)
  193327. {
  193328. switch (row_info->bit_depth)
  193329. {
  193330. case 1:
  193331. {
  193332. sp = row + (png_size_t)((row_width - 1) >> 3);
  193333. dp = row + (png_size_t)row_width - 1;
  193334. shift = 7 - (int)((row_width + 7) & 0x07);
  193335. for (i = 0; i < row_width; i++)
  193336. {
  193337. if ((*sp >> shift) & 0x01)
  193338. *dp = 1;
  193339. else
  193340. *dp = 0;
  193341. if (shift == 7)
  193342. {
  193343. shift = 0;
  193344. sp--;
  193345. }
  193346. else
  193347. shift++;
  193348. dp--;
  193349. }
  193350. break;
  193351. }
  193352. case 2:
  193353. {
  193354. sp = row + (png_size_t)((row_width - 1) >> 2);
  193355. dp = row + (png_size_t)row_width - 1;
  193356. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193357. for (i = 0; i < row_width; i++)
  193358. {
  193359. value = (*sp >> shift) & 0x03;
  193360. *dp = (png_byte)value;
  193361. if (shift == 6)
  193362. {
  193363. shift = 0;
  193364. sp--;
  193365. }
  193366. else
  193367. shift += 2;
  193368. dp--;
  193369. }
  193370. break;
  193371. }
  193372. case 4:
  193373. {
  193374. sp = row + (png_size_t)((row_width - 1) >> 1);
  193375. dp = row + (png_size_t)row_width - 1;
  193376. shift = (int)((row_width & 0x01) << 2);
  193377. for (i = 0; i < row_width; i++)
  193378. {
  193379. value = (*sp >> shift) & 0x0f;
  193380. *dp = (png_byte)value;
  193381. if (shift == 4)
  193382. {
  193383. shift = 0;
  193384. sp--;
  193385. }
  193386. else
  193387. shift += 4;
  193388. dp--;
  193389. }
  193390. break;
  193391. }
  193392. }
  193393. row_info->bit_depth = 8;
  193394. row_info->pixel_depth = 8;
  193395. row_info->rowbytes = row_width;
  193396. }
  193397. switch (row_info->bit_depth)
  193398. {
  193399. case 8:
  193400. {
  193401. if (trans != NULL)
  193402. {
  193403. sp = row + (png_size_t)row_width - 1;
  193404. dp = row + (png_size_t)(row_width << 2) - 1;
  193405. for (i = 0; i < row_width; i++)
  193406. {
  193407. if ((int)(*sp) >= num_trans)
  193408. *dp-- = 0xff;
  193409. else
  193410. *dp-- = trans[*sp];
  193411. *dp-- = palette[*sp].blue;
  193412. *dp-- = palette[*sp].green;
  193413. *dp-- = palette[*sp].red;
  193414. sp--;
  193415. }
  193416. row_info->bit_depth = 8;
  193417. row_info->pixel_depth = 32;
  193418. row_info->rowbytes = row_width * 4;
  193419. row_info->color_type = 6;
  193420. row_info->channels = 4;
  193421. }
  193422. else
  193423. {
  193424. sp = row + (png_size_t)row_width - 1;
  193425. dp = row + (png_size_t)(row_width * 3) - 1;
  193426. for (i = 0; i < row_width; i++)
  193427. {
  193428. *dp-- = palette[*sp].blue;
  193429. *dp-- = palette[*sp].green;
  193430. *dp-- = palette[*sp].red;
  193431. sp--;
  193432. }
  193433. row_info->bit_depth = 8;
  193434. row_info->pixel_depth = 24;
  193435. row_info->rowbytes = row_width * 3;
  193436. row_info->color_type = 2;
  193437. row_info->channels = 3;
  193438. }
  193439. break;
  193440. }
  193441. }
  193442. }
  193443. }
  193444. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  193445. * expanded transparency value is supplied, an alpha channel is built.
  193446. */
  193447. void /* PRIVATE */
  193448. png_do_expand(png_row_infop row_info, png_bytep row,
  193449. png_color_16p trans_value)
  193450. {
  193451. int shift, value;
  193452. png_bytep sp, dp;
  193453. png_uint_32 i;
  193454. png_uint_32 row_width=row_info->width;
  193455. png_debug(1, "in png_do_expand\n");
  193456. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193457. if (row != NULL && row_info != NULL)
  193458. #endif
  193459. {
  193460. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  193461. {
  193462. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  193463. if (row_info->bit_depth < 8)
  193464. {
  193465. switch (row_info->bit_depth)
  193466. {
  193467. case 1:
  193468. {
  193469. gray = (png_uint_16)((gray&0x01)*0xff);
  193470. sp = row + (png_size_t)((row_width - 1) >> 3);
  193471. dp = row + (png_size_t)row_width - 1;
  193472. shift = 7 - (int)((row_width + 7) & 0x07);
  193473. for (i = 0; i < row_width; i++)
  193474. {
  193475. if ((*sp >> shift) & 0x01)
  193476. *dp = 0xff;
  193477. else
  193478. *dp = 0;
  193479. if (shift == 7)
  193480. {
  193481. shift = 0;
  193482. sp--;
  193483. }
  193484. else
  193485. shift++;
  193486. dp--;
  193487. }
  193488. break;
  193489. }
  193490. case 2:
  193491. {
  193492. gray = (png_uint_16)((gray&0x03)*0x55);
  193493. sp = row + (png_size_t)((row_width - 1) >> 2);
  193494. dp = row + (png_size_t)row_width - 1;
  193495. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193496. for (i = 0; i < row_width; i++)
  193497. {
  193498. value = (*sp >> shift) & 0x03;
  193499. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  193500. (value << 6));
  193501. if (shift == 6)
  193502. {
  193503. shift = 0;
  193504. sp--;
  193505. }
  193506. else
  193507. shift += 2;
  193508. dp--;
  193509. }
  193510. break;
  193511. }
  193512. case 4:
  193513. {
  193514. gray = (png_uint_16)((gray&0x0f)*0x11);
  193515. sp = row + (png_size_t)((row_width - 1) >> 1);
  193516. dp = row + (png_size_t)row_width - 1;
  193517. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  193518. for (i = 0; i < row_width; i++)
  193519. {
  193520. value = (*sp >> shift) & 0x0f;
  193521. *dp = (png_byte)(value | (value << 4));
  193522. if (shift == 4)
  193523. {
  193524. shift = 0;
  193525. sp--;
  193526. }
  193527. else
  193528. shift = 4;
  193529. dp--;
  193530. }
  193531. break;
  193532. }
  193533. }
  193534. row_info->bit_depth = 8;
  193535. row_info->pixel_depth = 8;
  193536. row_info->rowbytes = row_width;
  193537. }
  193538. if (trans_value != NULL)
  193539. {
  193540. if (row_info->bit_depth == 8)
  193541. {
  193542. gray = gray & 0xff;
  193543. sp = row + (png_size_t)row_width - 1;
  193544. dp = row + (png_size_t)(row_width << 1) - 1;
  193545. for (i = 0; i < row_width; i++)
  193546. {
  193547. if (*sp == gray)
  193548. *dp-- = 0;
  193549. else
  193550. *dp-- = 0xff;
  193551. *dp-- = *sp--;
  193552. }
  193553. }
  193554. else if (row_info->bit_depth == 16)
  193555. {
  193556. png_byte gray_high = (gray >> 8) & 0xff;
  193557. png_byte gray_low = gray & 0xff;
  193558. sp = row + row_info->rowbytes - 1;
  193559. dp = row + (row_info->rowbytes << 1) - 1;
  193560. for (i = 0; i < row_width; i++)
  193561. {
  193562. if (*(sp-1) == gray_high && *(sp) == gray_low)
  193563. {
  193564. *dp-- = 0;
  193565. *dp-- = 0;
  193566. }
  193567. else
  193568. {
  193569. *dp-- = 0xff;
  193570. *dp-- = 0xff;
  193571. }
  193572. *dp-- = *sp--;
  193573. *dp-- = *sp--;
  193574. }
  193575. }
  193576. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  193577. row_info->channels = 2;
  193578. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  193579. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  193580. row_width);
  193581. }
  193582. }
  193583. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  193584. {
  193585. if (row_info->bit_depth == 8)
  193586. {
  193587. png_byte red = trans_value->red & 0xff;
  193588. png_byte green = trans_value->green & 0xff;
  193589. png_byte blue = trans_value->blue & 0xff;
  193590. sp = row + (png_size_t)row_info->rowbytes - 1;
  193591. dp = row + (png_size_t)(row_width << 2) - 1;
  193592. for (i = 0; i < row_width; i++)
  193593. {
  193594. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  193595. *dp-- = 0;
  193596. else
  193597. *dp-- = 0xff;
  193598. *dp-- = *sp--;
  193599. *dp-- = *sp--;
  193600. *dp-- = *sp--;
  193601. }
  193602. }
  193603. else if (row_info->bit_depth == 16)
  193604. {
  193605. png_byte red_high = (trans_value->red >> 8) & 0xff;
  193606. png_byte green_high = (trans_value->green >> 8) & 0xff;
  193607. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  193608. png_byte red_low = trans_value->red & 0xff;
  193609. png_byte green_low = trans_value->green & 0xff;
  193610. png_byte blue_low = trans_value->blue & 0xff;
  193611. sp = row + row_info->rowbytes - 1;
  193612. dp = row + (png_size_t)(row_width << 3) - 1;
  193613. for (i = 0; i < row_width; i++)
  193614. {
  193615. if (*(sp - 5) == red_high &&
  193616. *(sp - 4) == red_low &&
  193617. *(sp - 3) == green_high &&
  193618. *(sp - 2) == green_low &&
  193619. *(sp - 1) == blue_high &&
  193620. *(sp ) == blue_low)
  193621. {
  193622. *dp-- = 0;
  193623. *dp-- = 0;
  193624. }
  193625. else
  193626. {
  193627. *dp-- = 0xff;
  193628. *dp-- = 0xff;
  193629. }
  193630. *dp-- = *sp--;
  193631. *dp-- = *sp--;
  193632. *dp-- = *sp--;
  193633. *dp-- = *sp--;
  193634. *dp-- = *sp--;
  193635. *dp-- = *sp--;
  193636. }
  193637. }
  193638. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  193639. row_info->channels = 4;
  193640. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  193641. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193642. }
  193643. }
  193644. }
  193645. #endif
  193646. #if defined(PNG_READ_DITHER_SUPPORTED)
  193647. void /* PRIVATE */
  193648. png_do_dither(png_row_infop row_info, png_bytep row,
  193649. png_bytep palette_lookup, png_bytep dither_lookup)
  193650. {
  193651. png_bytep sp, dp;
  193652. png_uint_32 i;
  193653. png_uint_32 row_width=row_info->width;
  193654. png_debug(1, "in png_do_dither\n");
  193655. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193656. if (row != NULL && row_info != NULL)
  193657. #endif
  193658. {
  193659. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  193660. palette_lookup && row_info->bit_depth == 8)
  193661. {
  193662. int r, g, b, p;
  193663. sp = row;
  193664. dp = row;
  193665. for (i = 0; i < row_width; i++)
  193666. {
  193667. r = *sp++;
  193668. g = *sp++;
  193669. b = *sp++;
  193670. /* this looks real messy, but the compiler will reduce
  193671. it down to a reasonable formula. For example, with
  193672. 5 bits per color, we get:
  193673. p = (((r >> 3) & 0x1f) << 10) |
  193674. (((g >> 3) & 0x1f) << 5) |
  193675. ((b >> 3) & 0x1f);
  193676. */
  193677. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193678. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193679. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193680. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193681. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193682. (PNG_DITHER_BLUE_BITS)) |
  193683. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193684. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193685. *dp++ = palette_lookup[p];
  193686. }
  193687. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193688. row_info->channels = 1;
  193689. row_info->pixel_depth = row_info->bit_depth;
  193690. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193691. }
  193692. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  193693. palette_lookup != NULL && row_info->bit_depth == 8)
  193694. {
  193695. int r, g, b, p;
  193696. sp = row;
  193697. dp = row;
  193698. for (i = 0; i < row_width; i++)
  193699. {
  193700. r = *sp++;
  193701. g = *sp++;
  193702. b = *sp++;
  193703. sp++;
  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_PALETTE &&
  193720. dither_lookup && row_info->bit_depth == 8)
  193721. {
  193722. sp = row;
  193723. for (i = 0; i < row_width; i++, sp++)
  193724. {
  193725. *sp = dither_lookup[*sp];
  193726. }
  193727. }
  193728. }
  193729. }
  193730. #endif
  193731. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193732. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193733. static PNG_CONST int png_gamma_shift[] =
  193734. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  193735. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  193736. * tables, we don't make a full table if we are reducing to 8-bit in
  193737. * the future. Note also how the gamma_16 tables are segmented so that
  193738. * we don't need to allocate > 64K chunks for a full 16-bit table.
  193739. */
  193740. void /* PRIVATE */
  193741. png_build_gamma_table(png_structp png_ptr)
  193742. {
  193743. png_debug(1, "in png_build_gamma_table\n");
  193744. if (png_ptr->bit_depth <= 8)
  193745. {
  193746. int i;
  193747. double g;
  193748. if (png_ptr->screen_gamma > .000001)
  193749. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193750. else
  193751. g = 1.0;
  193752. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  193753. (png_uint_32)256);
  193754. for (i = 0; i < 256; i++)
  193755. {
  193756. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  193757. g) * 255.0 + .5);
  193758. }
  193759. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193760. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193761. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  193762. {
  193763. g = 1.0 / (png_ptr->gamma);
  193764. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  193765. (png_uint_32)256);
  193766. for (i = 0; i < 256; i++)
  193767. {
  193768. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  193769. g) * 255.0 + .5);
  193770. }
  193771. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  193772. (png_uint_32)256);
  193773. if(png_ptr->screen_gamma > 0.000001)
  193774. g = 1.0 / png_ptr->screen_gamma;
  193775. else
  193776. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193777. for (i = 0; i < 256; i++)
  193778. {
  193779. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  193780. g) * 255.0 + .5);
  193781. }
  193782. }
  193783. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193784. }
  193785. else
  193786. {
  193787. double g;
  193788. int i, j, shift, num;
  193789. int sig_bit;
  193790. png_uint_32 ig;
  193791. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  193792. {
  193793. sig_bit = (int)png_ptr->sig_bit.red;
  193794. if ((int)png_ptr->sig_bit.green > sig_bit)
  193795. sig_bit = png_ptr->sig_bit.green;
  193796. if ((int)png_ptr->sig_bit.blue > sig_bit)
  193797. sig_bit = png_ptr->sig_bit.blue;
  193798. }
  193799. else
  193800. {
  193801. sig_bit = (int)png_ptr->sig_bit.gray;
  193802. }
  193803. if (sig_bit > 0)
  193804. shift = 16 - sig_bit;
  193805. else
  193806. shift = 0;
  193807. if (png_ptr->transformations & PNG_16_TO_8)
  193808. {
  193809. if (shift < (16 - PNG_MAX_GAMMA_8))
  193810. shift = (16 - PNG_MAX_GAMMA_8);
  193811. }
  193812. if (shift > 8)
  193813. shift = 8;
  193814. if (shift < 0)
  193815. shift = 0;
  193816. png_ptr->gamma_shift = (png_byte)shift;
  193817. num = (1 << (8 - shift));
  193818. if (png_ptr->screen_gamma > .000001)
  193819. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193820. else
  193821. g = 1.0;
  193822. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  193823. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193824. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  193825. {
  193826. double fin, fout;
  193827. png_uint_32 last, max;
  193828. for (i = 0; i < num; i++)
  193829. {
  193830. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  193831. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193832. }
  193833. g = 1.0 / g;
  193834. last = 0;
  193835. for (i = 0; i < 256; i++)
  193836. {
  193837. fout = ((double)i + 0.5) / 256.0;
  193838. fin = pow(fout, g);
  193839. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  193840. while (last <= max)
  193841. {
  193842. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  193843. [(int)(last >> (8 - shift))] = (png_uint_16)(
  193844. (png_uint_16)i | ((png_uint_16)i << 8));
  193845. last++;
  193846. }
  193847. }
  193848. while (last < ((png_uint_32)num << 8))
  193849. {
  193850. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  193851. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  193852. last++;
  193853. }
  193854. }
  193855. else
  193856. {
  193857. for (i = 0; i < num; i++)
  193858. {
  193859. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  193860. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193861. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  193862. for (j = 0; j < 256; j++)
  193863. {
  193864. png_ptr->gamma_16_table[i][j] =
  193865. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193866. 65535.0, g) * 65535.0 + .5);
  193867. }
  193868. }
  193869. }
  193870. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193871. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193872. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  193873. {
  193874. g = 1.0 / (png_ptr->gamma);
  193875. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  193876. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  193877. for (i = 0; i < num; i++)
  193878. {
  193879. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  193880. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193881. ig = (((png_uint_32)i *
  193882. (png_uint_32)png_gamma_shift[shift]) >> 4);
  193883. for (j = 0; j < 256; j++)
  193884. {
  193885. png_ptr->gamma_16_to_1[i][j] =
  193886. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193887. 65535.0, g) * 65535.0 + .5);
  193888. }
  193889. }
  193890. if(png_ptr->screen_gamma > 0.000001)
  193891. g = 1.0 / png_ptr->screen_gamma;
  193892. else
  193893. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  193894. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  193895. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  193896. for (i = 0; i < num; i++)
  193897. {
  193898. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  193899. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  193900. ig = (((png_uint_32)i *
  193901. (png_uint_32)png_gamma_shift[shift]) >> 4);
  193902. for (j = 0; j < 256; j++)
  193903. {
  193904. png_ptr->gamma_16_from_1[i][j] =
  193905. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  193906. 65535.0, g) * 65535.0 + .5);
  193907. }
  193908. }
  193909. }
  193910. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  193911. }
  193912. }
  193913. #endif
  193914. /* To do: install integer version of png_build_gamma_table here */
  193915. #endif
  193916. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193917. /* undoes intrapixel differencing */
  193918. void /* PRIVATE */
  193919. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  193920. {
  193921. png_debug(1, "in png_do_read_intrapixel\n");
  193922. if (
  193923. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193924. row != NULL && row_info != NULL &&
  193925. #endif
  193926. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  193927. {
  193928. int bytes_per_pixel;
  193929. png_uint_32 row_width = row_info->width;
  193930. if (row_info->bit_depth == 8)
  193931. {
  193932. png_bytep rp;
  193933. png_uint_32 i;
  193934. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193935. bytes_per_pixel = 3;
  193936. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193937. bytes_per_pixel = 4;
  193938. else
  193939. return;
  193940. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193941. {
  193942. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  193943. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  193944. }
  193945. }
  193946. else if (row_info->bit_depth == 16)
  193947. {
  193948. png_bytep rp;
  193949. png_uint_32 i;
  193950. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193951. bytes_per_pixel = 6;
  193952. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193953. bytes_per_pixel = 8;
  193954. else
  193955. return;
  193956. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193957. {
  193958. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  193959. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  193960. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  193961. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  193962. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  193963. *(rp ) = (png_byte)((red >> 8) & 0xff);
  193964. *(rp+1) = (png_byte)(red & 0xff);
  193965. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  193966. *(rp+5) = (png_byte)(blue & 0xff);
  193967. }
  193968. }
  193969. }
  193970. }
  193971. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  193972. #endif /* PNG_READ_SUPPORTED */
  193973. /*** End of inlined file: pngrtran.c ***/
  193974. /*** Start of inlined file: pngrutil.c ***/
  193975. /* pngrutil.c - utilities to read a PNG file
  193976. *
  193977. * Last changed in libpng 1.2.21 [October 4, 2007]
  193978. * For conditions of distribution and use, see copyright notice in png.h
  193979. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  193980. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  193981. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  193982. *
  193983. * This file contains routines that are only called from within
  193984. * libpng itself during the course of reading an image.
  193985. */
  193986. #define PNG_INTERNAL
  193987. #if defined(PNG_READ_SUPPORTED)
  193988. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  193989. # define WIN32_WCE_OLD
  193990. #endif
  193991. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193992. # if defined(WIN32_WCE_OLD)
  193993. /* strtod() function is not supported on WindowsCE */
  193994. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  193995. {
  193996. double result = 0;
  193997. int len;
  193998. wchar_t *str, *end;
  193999. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  194000. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  194001. if ( NULL != str )
  194002. {
  194003. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  194004. result = wcstod(str, &end);
  194005. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  194006. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  194007. png_free(png_ptr, str);
  194008. }
  194009. return result;
  194010. }
  194011. # else
  194012. # define png_strtod(p,a,b) strtod(a,b)
  194013. # endif
  194014. #endif
  194015. png_uint_32 PNGAPI
  194016. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  194017. {
  194018. png_uint_32 i = png_get_uint_32(buf);
  194019. if (i > PNG_UINT_31_MAX)
  194020. png_error(png_ptr, "PNG unsigned integer out of range.");
  194021. return (i);
  194022. }
  194023. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  194024. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  194025. png_uint_32 PNGAPI
  194026. png_get_uint_32(png_bytep buf)
  194027. {
  194028. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  194029. ((png_uint_32)(*(buf + 1)) << 16) +
  194030. ((png_uint_32)(*(buf + 2)) << 8) +
  194031. (png_uint_32)(*(buf + 3));
  194032. return (i);
  194033. }
  194034. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  194035. * data is stored in the PNG file in two's complement format, and it is
  194036. * assumed that the machine format for signed integers is the same. */
  194037. png_int_32 PNGAPI
  194038. png_get_int_32(png_bytep buf)
  194039. {
  194040. png_int_32 i = ((png_int_32)(*buf) << 24) +
  194041. ((png_int_32)(*(buf + 1)) << 16) +
  194042. ((png_int_32)(*(buf + 2)) << 8) +
  194043. (png_int_32)(*(buf + 3));
  194044. return (i);
  194045. }
  194046. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  194047. png_uint_16 PNGAPI
  194048. png_get_uint_16(png_bytep buf)
  194049. {
  194050. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  194051. (png_uint_16)(*(buf + 1)));
  194052. return (i);
  194053. }
  194054. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  194055. /* Read data, and (optionally) run it through the CRC. */
  194056. void /* PRIVATE */
  194057. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  194058. {
  194059. if(png_ptr == NULL) return;
  194060. png_read_data(png_ptr, buf, length);
  194061. png_calculate_crc(png_ptr, buf, length);
  194062. }
  194063. /* Optionally skip data and then check the CRC. Depending on whether we
  194064. are reading a ancillary or critical chunk, and how the program has set
  194065. things up, we may calculate the CRC on the data and print a message.
  194066. Returns '1' if there was a CRC error, '0' otherwise. */
  194067. int /* PRIVATE */
  194068. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  194069. {
  194070. png_size_t i;
  194071. png_size_t istop = png_ptr->zbuf_size;
  194072. for (i = (png_size_t)skip; i > istop; i -= istop)
  194073. {
  194074. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  194075. }
  194076. if (i)
  194077. {
  194078. png_crc_read(png_ptr, png_ptr->zbuf, i);
  194079. }
  194080. if (png_crc_error(png_ptr))
  194081. {
  194082. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  194083. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  194084. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  194085. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  194086. {
  194087. png_chunk_warning(png_ptr, "CRC error");
  194088. }
  194089. else
  194090. {
  194091. png_chunk_error(png_ptr, "CRC error");
  194092. }
  194093. return (1);
  194094. }
  194095. return (0);
  194096. }
  194097. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  194098. the data it has read thus far. */
  194099. int /* PRIVATE */
  194100. png_crc_error(png_structp png_ptr)
  194101. {
  194102. png_byte crc_bytes[4];
  194103. png_uint_32 crc;
  194104. int need_crc = 1;
  194105. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  194106. {
  194107. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  194108. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  194109. need_crc = 0;
  194110. }
  194111. else /* critical */
  194112. {
  194113. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  194114. need_crc = 0;
  194115. }
  194116. png_read_data(png_ptr, crc_bytes, 4);
  194117. if (need_crc)
  194118. {
  194119. crc = png_get_uint_32(crc_bytes);
  194120. return ((int)(crc != png_ptr->crc));
  194121. }
  194122. else
  194123. return (0);
  194124. }
  194125. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  194126. defined(PNG_READ_iCCP_SUPPORTED)
  194127. /*
  194128. * Decompress trailing data in a chunk. The assumption is that chunkdata
  194129. * points at an allocated area holding the contents of a chunk with a
  194130. * trailing compressed part. What we get back is an allocated area
  194131. * holding the original prefix part and an uncompressed version of the
  194132. * trailing part (the malloc area passed in is freed).
  194133. */
  194134. png_charp /* PRIVATE */
  194135. png_decompress_chunk(png_structp png_ptr, int comp_type,
  194136. png_charp chunkdata, png_size_t chunklength,
  194137. png_size_t prefix_size, png_size_t *newlength)
  194138. {
  194139. static PNG_CONST char msg[] = "Error decoding compressed text";
  194140. png_charp text;
  194141. png_size_t text_size;
  194142. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  194143. {
  194144. int ret = Z_OK;
  194145. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  194146. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  194147. png_ptr->zstream.next_out = png_ptr->zbuf;
  194148. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194149. text_size = 0;
  194150. text = NULL;
  194151. while (png_ptr->zstream.avail_in)
  194152. {
  194153. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  194154. if (ret != Z_OK && ret != Z_STREAM_END)
  194155. {
  194156. if (png_ptr->zstream.msg != NULL)
  194157. png_warning(png_ptr, png_ptr->zstream.msg);
  194158. else
  194159. png_warning(png_ptr, msg);
  194160. inflateReset(&png_ptr->zstream);
  194161. png_ptr->zstream.avail_in = 0;
  194162. if (text == NULL)
  194163. {
  194164. text_size = prefix_size + png_sizeof(msg) + 1;
  194165. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  194166. if (text == NULL)
  194167. {
  194168. png_free(png_ptr,chunkdata);
  194169. png_error(png_ptr,"Not enough memory to decompress chunk");
  194170. }
  194171. png_memcpy(text, chunkdata, prefix_size);
  194172. }
  194173. text[text_size - 1] = 0x00;
  194174. /* Copy what we can of the error message into the text chunk */
  194175. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  194176. text_size = png_sizeof(msg) > text_size ? text_size :
  194177. png_sizeof(msg);
  194178. png_memcpy(text + prefix_size, msg, text_size + 1);
  194179. break;
  194180. }
  194181. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  194182. {
  194183. if (text == NULL)
  194184. {
  194185. text_size = prefix_size +
  194186. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  194187. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  194188. if (text == NULL)
  194189. {
  194190. png_free(png_ptr,chunkdata);
  194191. png_error(png_ptr,"Not enough memory to decompress chunk.");
  194192. }
  194193. png_memcpy(text + prefix_size, png_ptr->zbuf,
  194194. text_size - prefix_size);
  194195. png_memcpy(text, chunkdata, prefix_size);
  194196. *(text + text_size) = 0x00;
  194197. }
  194198. else
  194199. {
  194200. png_charp tmp;
  194201. tmp = text;
  194202. text = (png_charp)png_malloc_warn(png_ptr,
  194203. (png_uint_32)(text_size +
  194204. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  194205. if (text == NULL)
  194206. {
  194207. png_free(png_ptr, tmp);
  194208. png_free(png_ptr, chunkdata);
  194209. png_error(png_ptr,"Not enough memory to decompress chunk..");
  194210. }
  194211. png_memcpy(text, tmp, text_size);
  194212. png_free(png_ptr, tmp);
  194213. png_memcpy(text + text_size, png_ptr->zbuf,
  194214. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  194215. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  194216. *(text + text_size) = 0x00;
  194217. }
  194218. if (ret == Z_STREAM_END)
  194219. break;
  194220. else
  194221. {
  194222. png_ptr->zstream.next_out = png_ptr->zbuf;
  194223. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194224. }
  194225. }
  194226. }
  194227. if (ret != Z_STREAM_END)
  194228. {
  194229. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194230. char umsg[52];
  194231. if (ret == Z_BUF_ERROR)
  194232. png_snprintf(umsg, 52,
  194233. "Buffer error in compressed datastream in %s chunk",
  194234. png_ptr->chunk_name);
  194235. else if (ret == Z_DATA_ERROR)
  194236. png_snprintf(umsg, 52,
  194237. "Data error in compressed datastream in %s chunk",
  194238. png_ptr->chunk_name);
  194239. else
  194240. png_snprintf(umsg, 52,
  194241. "Incomplete compressed datastream in %s chunk",
  194242. png_ptr->chunk_name);
  194243. png_warning(png_ptr, umsg);
  194244. #else
  194245. png_warning(png_ptr,
  194246. "Incomplete compressed datastream in chunk other than IDAT");
  194247. #endif
  194248. text_size=prefix_size;
  194249. if (text == NULL)
  194250. {
  194251. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  194252. if (text == NULL)
  194253. {
  194254. png_free(png_ptr, chunkdata);
  194255. png_error(png_ptr,"Not enough memory for text.");
  194256. }
  194257. png_memcpy(text, chunkdata, prefix_size);
  194258. }
  194259. *(text + text_size) = 0x00;
  194260. }
  194261. inflateReset(&png_ptr->zstream);
  194262. png_ptr->zstream.avail_in = 0;
  194263. png_free(png_ptr, chunkdata);
  194264. chunkdata = text;
  194265. *newlength=text_size;
  194266. }
  194267. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  194268. {
  194269. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194270. char umsg[50];
  194271. png_snprintf(umsg, 50,
  194272. "Unknown zTXt compression type %d", comp_type);
  194273. png_warning(png_ptr, umsg);
  194274. #else
  194275. png_warning(png_ptr, "Unknown zTXt compression type");
  194276. #endif
  194277. *(chunkdata + prefix_size) = 0x00;
  194278. *newlength=prefix_size;
  194279. }
  194280. return chunkdata;
  194281. }
  194282. #endif
  194283. /* read and check the IDHR chunk */
  194284. void /* PRIVATE */
  194285. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194286. {
  194287. png_byte buf[13];
  194288. png_uint_32 width, height;
  194289. int bit_depth, color_type, compression_type, filter_type;
  194290. int interlace_type;
  194291. png_debug(1, "in png_handle_IHDR\n");
  194292. if (png_ptr->mode & PNG_HAVE_IHDR)
  194293. png_error(png_ptr, "Out of place IHDR");
  194294. /* check the length */
  194295. if (length != 13)
  194296. png_error(png_ptr, "Invalid IHDR chunk");
  194297. png_ptr->mode |= PNG_HAVE_IHDR;
  194298. png_crc_read(png_ptr, buf, 13);
  194299. png_crc_finish(png_ptr, 0);
  194300. width = png_get_uint_31(png_ptr, buf);
  194301. height = png_get_uint_31(png_ptr, buf + 4);
  194302. bit_depth = buf[8];
  194303. color_type = buf[9];
  194304. compression_type = buf[10];
  194305. filter_type = buf[11];
  194306. interlace_type = buf[12];
  194307. /* set internal variables */
  194308. png_ptr->width = width;
  194309. png_ptr->height = height;
  194310. png_ptr->bit_depth = (png_byte)bit_depth;
  194311. png_ptr->interlaced = (png_byte)interlace_type;
  194312. png_ptr->color_type = (png_byte)color_type;
  194313. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194314. png_ptr->filter_type = (png_byte)filter_type;
  194315. #endif
  194316. png_ptr->compression_type = (png_byte)compression_type;
  194317. /* find number of channels */
  194318. switch (png_ptr->color_type)
  194319. {
  194320. case PNG_COLOR_TYPE_GRAY:
  194321. case PNG_COLOR_TYPE_PALETTE:
  194322. png_ptr->channels = 1;
  194323. break;
  194324. case PNG_COLOR_TYPE_RGB:
  194325. png_ptr->channels = 3;
  194326. break;
  194327. case PNG_COLOR_TYPE_GRAY_ALPHA:
  194328. png_ptr->channels = 2;
  194329. break;
  194330. case PNG_COLOR_TYPE_RGB_ALPHA:
  194331. png_ptr->channels = 4;
  194332. break;
  194333. }
  194334. /* set up other useful info */
  194335. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  194336. png_ptr->channels);
  194337. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  194338. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  194339. png_debug1(3,"channels = %d\n", png_ptr->channels);
  194340. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  194341. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  194342. color_type, interlace_type, compression_type, filter_type);
  194343. }
  194344. /* read and check the palette */
  194345. void /* PRIVATE */
  194346. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194347. {
  194348. png_color palette[PNG_MAX_PALETTE_LENGTH];
  194349. int num, i;
  194350. #ifndef PNG_NO_POINTER_INDEXING
  194351. png_colorp pal_ptr;
  194352. #endif
  194353. png_debug(1, "in png_handle_PLTE\n");
  194354. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194355. png_error(png_ptr, "Missing IHDR before PLTE");
  194356. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194357. {
  194358. png_warning(png_ptr, "Invalid PLTE after IDAT");
  194359. png_crc_finish(png_ptr, length);
  194360. return;
  194361. }
  194362. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194363. png_error(png_ptr, "Duplicate PLTE chunk");
  194364. png_ptr->mode |= PNG_HAVE_PLTE;
  194365. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  194366. {
  194367. png_warning(png_ptr,
  194368. "Ignoring PLTE chunk in grayscale PNG");
  194369. png_crc_finish(png_ptr, length);
  194370. return;
  194371. }
  194372. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194373. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194374. {
  194375. png_crc_finish(png_ptr, length);
  194376. return;
  194377. }
  194378. #endif
  194379. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  194380. {
  194381. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194382. {
  194383. png_warning(png_ptr, "Invalid palette chunk");
  194384. png_crc_finish(png_ptr, length);
  194385. return;
  194386. }
  194387. else
  194388. {
  194389. png_error(png_ptr, "Invalid palette chunk");
  194390. }
  194391. }
  194392. num = (int)length / 3;
  194393. #ifndef PNG_NO_POINTER_INDEXING
  194394. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  194395. {
  194396. png_byte buf[3];
  194397. png_crc_read(png_ptr, buf, 3);
  194398. pal_ptr->red = buf[0];
  194399. pal_ptr->green = buf[1];
  194400. pal_ptr->blue = buf[2];
  194401. }
  194402. #else
  194403. for (i = 0; i < num; i++)
  194404. {
  194405. png_byte buf[3];
  194406. png_crc_read(png_ptr, buf, 3);
  194407. /* don't depend upon png_color being any order */
  194408. palette[i].red = buf[0];
  194409. palette[i].green = buf[1];
  194410. palette[i].blue = buf[2];
  194411. }
  194412. #endif
  194413. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  194414. whatever the normal CRC configuration tells us. However, if we
  194415. have an RGB image, the PLTE can be considered ancillary, so
  194416. we will act as though it is. */
  194417. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194418. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194419. #endif
  194420. {
  194421. png_crc_finish(png_ptr, 0);
  194422. }
  194423. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194424. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  194425. {
  194426. /* If we don't want to use the data from an ancillary chunk,
  194427. we have two options: an error abort, or a warning and we
  194428. ignore the data in this chunk (which should be OK, since
  194429. it's considered ancillary for a RGB or RGBA image). */
  194430. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  194431. {
  194432. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  194433. {
  194434. png_chunk_error(png_ptr, "CRC error");
  194435. }
  194436. else
  194437. {
  194438. png_chunk_warning(png_ptr, "CRC error");
  194439. return;
  194440. }
  194441. }
  194442. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  194443. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  194444. {
  194445. png_chunk_warning(png_ptr, "CRC error");
  194446. }
  194447. }
  194448. #endif
  194449. png_set_PLTE(png_ptr, info_ptr, palette, num);
  194450. #if defined(PNG_READ_tRNS_SUPPORTED)
  194451. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194452. {
  194453. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  194454. {
  194455. if (png_ptr->num_trans > (png_uint_16)num)
  194456. {
  194457. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  194458. png_ptr->num_trans = (png_uint_16)num;
  194459. }
  194460. if (info_ptr->num_trans > (png_uint_16)num)
  194461. {
  194462. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  194463. info_ptr->num_trans = (png_uint_16)num;
  194464. }
  194465. }
  194466. }
  194467. #endif
  194468. }
  194469. void /* PRIVATE */
  194470. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194471. {
  194472. png_debug(1, "in png_handle_IEND\n");
  194473. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  194474. {
  194475. png_error(png_ptr, "No image in file");
  194476. }
  194477. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  194478. if (length != 0)
  194479. {
  194480. png_warning(png_ptr, "Incorrect IEND chunk length");
  194481. }
  194482. png_crc_finish(png_ptr, length);
  194483. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  194484. }
  194485. #if defined(PNG_READ_gAMA_SUPPORTED)
  194486. void /* PRIVATE */
  194487. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194488. {
  194489. png_fixed_point igamma;
  194490. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194491. float file_gamma;
  194492. #endif
  194493. png_byte buf[4];
  194494. png_debug(1, "in png_handle_gAMA\n");
  194495. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194496. png_error(png_ptr, "Missing IHDR before gAMA");
  194497. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194498. {
  194499. png_warning(png_ptr, "Invalid gAMA after IDAT");
  194500. png_crc_finish(png_ptr, length);
  194501. return;
  194502. }
  194503. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194504. /* Should be an error, but we can cope with it */
  194505. png_warning(png_ptr, "Out of place gAMA chunk");
  194506. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  194507. #if defined(PNG_READ_sRGB_SUPPORTED)
  194508. && !(info_ptr->valid & PNG_INFO_sRGB)
  194509. #endif
  194510. )
  194511. {
  194512. png_warning(png_ptr, "Duplicate gAMA chunk");
  194513. png_crc_finish(png_ptr, length);
  194514. return;
  194515. }
  194516. if (length != 4)
  194517. {
  194518. png_warning(png_ptr, "Incorrect gAMA chunk length");
  194519. png_crc_finish(png_ptr, length);
  194520. return;
  194521. }
  194522. png_crc_read(png_ptr, buf, 4);
  194523. if (png_crc_finish(png_ptr, 0))
  194524. return;
  194525. igamma = (png_fixed_point)png_get_uint_32(buf);
  194526. /* check for zero gamma */
  194527. if (igamma == 0)
  194528. {
  194529. png_warning(png_ptr,
  194530. "Ignoring gAMA chunk with gamma=0");
  194531. return;
  194532. }
  194533. #if defined(PNG_READ_sRGB_SUPPORTED)
  194534. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194535. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194536. {
  194537. png_warning(png_ptr,
  194538. "Ignoring incorrect gAMA value when sRGB is also present");
  194539. #ifndef PNG_NO_CONSOLE_IO
  194540. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  194541. #endif
  194542. return;
  194543. }
  194544. #endif /* PNG_READ_sRGB_SUPPORTED */
  194545. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194546. file_gamma = (float)igamma / (float)100000.0;
  194547. # ifdef PNG_READ_GAMMA_SUPPORTED
  194548. png_ptr->gamma = file_gamma;
  194549. # endif
  194550. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  194551. #endif
  194552. #ifdef PNG_FIXED_POINT_SUPPORTED
  194553. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  194554. #endif
  194555. }
  194556. #endif
  194557. #if defined(PNG_READ_sBIT_SUPPORTED)
  194558. void /* PRIVATE */
  194559. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194560. {
  194561. png_size_t truelen;
  194562. png_byte buf[4];
  194563. png_debug(1, "in png_handle_sBIT\n");
  194564. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  194565. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194566. png_error(png_ptr, "Missing IHDR before sBIT");
  194567. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194568. {
  194569. png_warning(png_ptr, "Invalid sBIT after IDAT");
  194570. png_crc_finish(png_ptr, length);
  194571. return;
  194572. }
  194573. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194574. {
  194575. /* Should be an error, but we can cope with it */
  194576. png_warning(png_ptr, "Out of place sBIT chunk");
  194577. }
  194578. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  194579. {
  194580. png_warning(png_ptr, "Duplicate sBIT chunk");
  194581. png_crc_finish(png_ptr, length);
  194582. return;
  194583. }
  194584. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194585. truelen = 3;
  194586. else
  194587. truelen = (png_size_t)png_ptr->channels;
  194588. if (length != truelen || length > 4)
  194589. {
  194590. png_warning(png_ptr, "Incorrect sBIT chunk length");
  194591. png_crc_finish(png_ptr, length);
  194592. return;
  194593. }
  194594. png_crc_read(png_ptr, buf, truelen);
  194595. if (png_crc_finish(png_ptr, 0))
  194596. return;
  194597. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194598. {
  194599. png_ptr->sig_bit.red = buf[0];
  194600. png_ptr->sig_bit.green = buf[1];
  194601. png_ptr->sig_bit.blue = buf[2];
  194602. png_ptr->sig_bit.alpha = buf[3];
  194603. }
  194604. else
  194605. {
  194606. png_ptr->sig_bit.gray = buf[0];
  194607. png_ptr->sig_bit.red = buf[0];
  194608. png_ptr->sig_bit.green = buf[0];
  194609. png_ptr->sig_bit.blue = buf[0];
  194610. png_ptr->sig_bit.alpha = buf[1];
  194611. }
  194612. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  194613. }
  194614. #endif
  194615. #if defined(PNG_READ_cHRM_SUPPORTED)
  194616. void /* PRIVATE */
  194617. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194618. {
  194619. png_byte buf[4];
  194620. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194621. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  194622. #endif
  194623. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194624. int_y_green, int_x_blue, int_y_blue;
  194625. png_uint_32 uint_x, uint_y;
  194626. png_debug(1, "in png_handle_cHRM\n");
  194627. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194628. png_error(png_ptr, "Missing IHDR before cHRM");
  194629. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194630. {
  194631. png_warning(png_ptr, "Invalid cHRM after IDAT");
  194632. png_crc_finish(png_ptr, length);
  194633. return;
  194634. }
  194635. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194636. /* Should be an error, but we can cope with it */
  194637. png_warning(png_ptr, "Missing PLTE before cHRM");
  194638. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  194639. #if defined(PNG_READ_sRGB_SUPPORTED)
  194640. && !(info_ptr->valid & PNG_INFO_sRGB)
  194641. #endif
  194642. )
  194643. {
  194644. png_warning(png_ptr, "Duplicate cHRM chunk");
  194645. png_crc_finish(png_ptr, length);
  194646. return;
  194647. }
  194648. if (length != 32)
  194649. {
  194650. png_warning(png_ptr, "Incorrect cHRM chunk length");
  194651. png_crc_finish(png_ptr, length);
  194652. return;
  194653. }
  194654. png_crc_read(png_ptr, buf, 4);
  194655. uint_x = png_get_uint_32(buf);
  194656. png_crc_read(png_ptr, buf, 4);
  194657. uint_y = png_get_uint_32(buf);
  194658. if (uint_x > 80000L || uint_y > 80000L ||
  194659. uint_x + uint_y > 100000L)
  194660. {
  194661. png_warning(png_ptr, "Invalid cHRM white point");
  194662. png_crc_finish(png_ptr, 24);
  194663. return;
  194664. }
  194665. int_x_white = (png_fixed_point)uint_x;
  194666. int_y_white = (png_fixed_point)uint_y;
  194667. png_crc_read(png_ptr, buf, 4);
  194668. uint_x = png_get_uint_32(buf);
  194669. png_crc_read(png_ptr, buf, 4);
  194670. uint_y = png_get_uint_32(buf);
  194671. if (uint_x + uint_y > 100000L)
  194672. {
  194673. png_warning(png_ptr, "Invalid cHRM red point");
  194674. png_crc_finish(png_ptr, 16);
  194675. return;
  194676. }
  194677. int_x_red = (png_fixed_point)uint_x;
  194678. int_y_red = (png_fixed_point)uint_y;
  194679. png_crc_read(png_ptr, buf, 4);
  194680. uint_x = png_get_uint_32(buf);
  194681. png_crc_read(png_ptr, buf, 4);
  194682. uint_y = png_get_uint_32(buf);
  194683. if (uint_x + uint_y > 100000L)
  194684. {
  194685. png_warning(png_ptr, "Invalid cHRM green point");
  194686. png_crc_finish(png_ptr, 8);
  194687. return;
  194688. }
  194689. int_x_green = (png_fixed_point)uint_x;
  194690. int_y_green = (png_fixed_point)uint_y;
  194691. png_crc_read(png_ptr, buf, 4);
  194692. uint_x = png_get_uint_32(buf);
  194693. png_crc_read(png_ptr, buf, 4);
  194694. uint_y = png_get_uint_32(buf);
  194695. if (uint_x + uint_y > 100000L)
  194696. {
  194697. png_warning(png_ptr, "Invalid cHRM blue point");
  194698. png_crc_finish(png_ptr, 0);
  194699. return;
  194700. }
  194701. int_x_blue = (png_fixed_point)uint_x;
  194702. int_y_blue = (png_fixed_point)uint_y;
  194703. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194704. white_x = (float)int_x_white / (float)100000.0;
  194705. white_y = (float)int_y_white / (float)100000.0;
  194706. red_x = (float)int_x_red / (float)100000.0;
  194707. red_y = (float)int_y_red / (float)100000.0;
  194708. green_x = (float)int_x_green / (float)100000.0;
  194709. green_y = (float)int_y_green / (float)100000.0;
  194710. blue_x = (float)int_x_blue / (float)100000.0;
  194711. blue_y = (float)int_y_blue / (float)100000.0;
  194712. #endif
  194713. #if defined(PNG_READ_sRGB_SUPPORTED)
  194714. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  194715. {
  194716. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  194717. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  194718. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  194719. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  194720. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  194721. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  194722. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  194723. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  194724. {
  194725. png_warning(png_ptr,
  194726. "Ignoring incorrect cHRM value when sRGB is also present");
  194727. #ifndef PNG_NO_CONSOLE_IO
  194728. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194729. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  194730. white_x, white_y, red_x, red_y);
  194731. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  194732. green_x, green_y, blue_x, blue_y);
  194733. #else
  194734. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  194735. int_x_white, int_y_white, int_x_red, int_y_red);
  194736. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  194737. int_x_green, int_y_green, int_x_blue, int_y_blue);
  194738. #endif
  194739. #endif /* PNG_NO_CONSOLE_IO */
  194740. }
  194741. png_crc_finish(png_ptr, 0);
  194742. return;
  194743. }
  194744. #endif /* PNG_READ_sRGB_SUPPORTED */
  194745. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194746. png_set_cHRM(png_ptr, info_ptr,
  194747. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  194748. #endif
  194749. #ifdef PNG_FIXED_POINT_SUPPORTED
  194750. png_set_cHRM_fixed(png_ptr, info_ptr,
  194751. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194752. int_y_green, int_x_blue, int_y_blue);
  194753. #endif
  194754. if (png_crc_finish(png_ptr, 0))
  194755. return;
  194756. }
  194757. #endif
  194758. #if defined(PNG_READ_sRGB_SUPPORTED)
  194759. void /* PRIVATE */
  194760. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194761. {
  194762. int intent;
  194763. png_byte buf[1];
  194764. png_debug(1, "in png_handle_sRGB\n");
  194765. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194766. png_error(png_ptr, "Missing IHDR before sRGB");
  194767. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194768. {
  194769. png_warning(png_ptr, "Invalid sRGB after IDAT");
  194770. png_crc_finish(png_ptr, length);
  194771. return;
  194772. }
  194773. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194774. /* Should be an error, but we can cope with it */
  194775. png_warning(png_ptr, "Out of place sRGB chunk");
  194776. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194777. {
  194778. png_warning(png_ptr, "Duplicate sRGB chunk");
  194779. png_crc_finish(png_ptr, length);
  194780. return;
  194781. }
  194782. if (length != 1)
  194783. {
  194784. png_warning(png_ptr, "Incorrect sRGB chunk length");
  194785. png_crc_finish(png_ptr, length);
  194786. return;
  194787. }
  194788. png_crc_read(png_ptr, buf, 1);
  194789. if (png_crc_finish(png_ptr, 0))
  194790. return;
  194791. intent = buf[0];
  194792. /* check for bad intent */
  194793. if (intent >= PNG_sRGB_INTENT_LAST)
  194794. {
  194795. png_warning(png_ptr, "Unknown sRGB intent");
  194796. return;
  194797. }
  194798. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  194799. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  194800. {
  194801. png_fixed_point igamma;
  194802. #ifdef PNG_FIXED_POINT_SUPPORTED
  194803. igamma=info_ptr->int_gamma;
  194804. #else
  194805. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194806. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  194807. # endif
  194808. #endif
  194809. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194810. {
  194811. png_warning(png_ptr,
  194812. "Ignoring incorrect gAMA value when sRGB is also present");
  194813. #ifndef PNG_NO_CONSOLE_IO
  194814. # ifdef PNG_FIXED_POINT_SUPPORTED
  194815. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  194816. # else
  194817. # ifdef PNG_FLOATING_POINT_SUPPORTED
  194818. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  194819. # endif
  194820. # endif
  194821. #endif
  194822. }
  194823. }
  194824. #endif /* PNG_READ_gAMA_SUPPORTED */
  194825. #ifdef PNG_READ_cHRM_SUPPORTED
  194826. #ifdef PNG_FIXED_POINT_SUPPORTED
  194827. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  194828. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  194829. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  194830. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  194831. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  194832. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  194833. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  194834. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  194835. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  194836. {
  194837. png_warning(png_ptr,
  194838. "Ignoring incorrect cHRM value when sRGB is also present");
  194839. }
  194840. #endif /* PNG_FIXED_POINT_SUPPORTED */
  194841. #endif /* PNG_READ_cHRM_SUPPORTED */
  194842. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  194843. }
  194844. #endif /* PNG_READ_sRGB_SUPPORTED */
  194845. #if defined(PNG_READ_iCCP_SUPPORTED)
  194846. void /* PRIVATE */
  194847. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194848. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194849. {
  194850. png_charp chunkdata;
  194851. png_byte compression_type;
  194852. png_bytep pC;
  194853. png_charp profile;
  194854. png_uint_32 skip = 0;
  194855. png_uint_32 profile_size, profile_length;
  194856. png_size_t slength, prefix_length, data_length;
  194857. png_debug(1, "in png_handle_iCCP\n");
  194858. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194859. png_error(png_ptr, "Missing IHDR before iCCP");
  194860. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194861. {
  194862. png_warning(png_ptr, "Invalid iCCP after IDAT");
  194863. png_crc_finish(png_ptr, length);
  194864. return;
  194865. }
  194866. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194867. /* Should be an error, but we can cope with it */
  194868. png_warning(png_ptr, "Out of place iCCP chunk");
  194869. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  194870. {
  194871. png_warning(png_ptr, "Duplicate iCCP chunk");
  194872. png_crc_finish(png_ptr, length);
  194873. return;
  194874. }
  194875. #ifdef PNG_MAX_MALLOC_64K
  194876. if (length > (png_uint_32)65535L)
  194877. {
  194878. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  194879. skip = length - (png_uint_32)65535L;
  194880. length = (png_uint_32)65535L;
  194881. }
  194882. #endif
  194883. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  194884. slength = (png_size_t)length;
  194885. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194886. if (png_crc_finish(png_ptr, skip))
  194887. {
  194888. png_free(png_ptr, chunkdata);
  194889. return;
  194890. }
  194891. chunkdata[slength] = 0x00;
  194892. for (profile = chunkdata; *profile; profile++)
  194893. /* empty loop to find end of name */ ;
  194894. ++profile;
  194895. /* there should be at least one zero (the compression type byte)
  194896. following the separator, and we should be on it */
  194897. if ( profile >= chunkdata + slength - 1)
  194898. {
  194899. png_free(png_ptr, chunkdata);
  194900. png_warning(png_ptr, "Malformed iCCP chunk");
  194901. return;
  194902. }
  194903. /* compression_type should always be zero */
  194904. compression_type = *profile++;
  194905. if (compression_type)
  194906. {
  194907. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  194908. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  194909. wrote nonzero) */
  194910. }
  194911. prefix_length = profile - chunkdata;
  194912. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  194913. slength, prefix_length, &data_length);
  194914. profile_length = data_length - prefix_length;
  194915. if ( prefix_length > data_length || profile_length < 4)
  194916. {
  194917. png_free(png_ptr, chunkdata);
  194918. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  194919. return;
  194920. }
  194921. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  194922. pC = (png_bytep)(chunkdata+prefix_length);
  194923. profile_size = ((*(pC ))<<24) |
  194924. ((*(pC+1))<<16) |
  194925. ((*(pC+2))<< 8) |
  194926. ((*(pC+3)) );
  194927. if(profile_size < profile_length)
  194928. profile_length = profile_size;
  194929. if(profile_size > profile_length)
  194930. {
  194931. png_free(png_ptr, chunkdata);
  194932. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  194933. return;
  194934. }
  194935. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  194936. chunkdata + prefix_length, profile_length);
  194937. png_free(png_ptr, chunkdata);
  194938. }
  194939. #endif /* PNG_READ_iCCP_SUPPORTED */
  194940. #if defined(PNG_READ_sPLT_SUPPORTED)
  194941. void /* PRIVATE */
  194942. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194943. /* Note: this does not properly handle chunks that are > 64K under DOS */
  194944. {
  194945. png_bytep chunkdata;
  194946. png_bytep entry_start;
  194947. png_sPLT_t new_palette;
  194948. #ifdef PNG_NO_POINTER_INDEXING
  194949. png_sPLT_entryp pp;
  194950. #endif
  194951. int data_length, entry_size, i;
  194952. png_uint_32 skip = 0;
  194953. png_size_t slength;
  194954. png_debug(1, "in png_handle_sPLT\n");
  194955. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194956. png_error(png_ptr, "Missing IHDR before sPLT");
  194957. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194958. {
  194959. png_warning(png_ptr, "Invalid sPLT after IDAT");
  194960. png_crc_finish(png_ptr, length);
  194961. return;
  194962. }
  194963. #ifdef PNG_MAX_MALLOC_64K
  194964. if (length > (png_uint_32)65535L)
  194965. {
  194966. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  194967. skip = length - (png_uint_32)65535L;
  194968. length = (png_uint_32)65535L;
  194969. }
  194970. #endif
  194971. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  194972. slength = (png_size_t)length;
  194973. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  194974. if (png_crc_finish(png_ptr, skip))
  194975. {
  194976. png_free(png_ptr, chunkdata);
  194977. return;
  194978. }
  194979. chunkdata[slength] = 0x00;
  194980. for (entry_start = chunkdata; *entry_start; entry_start++)
  194981. /* empty loop to find end of name */ ;
  194982. ++entry_start;
  194983. /* a sample depth should follow the separator, and we should be on it */
  194984. if (entry_start > chunkdata + slength - 2)
  194985. {
  194986. png_free(png_ptr, chunkdata);
  194987. png_warning(png_ptr, "malformed sPLT chunk");
  194988. return;
  194989. }
  194990. new_palette.depth = *entry_start++;
  194991. entry_size = (new_palette.depth == 8 ? 6 : 10);
  194992. data_length = (slength - (entry_start - chunkdata));
  194993. /* integrity-check the data length */
  194994. if (data_length % entry_size)
  194995. {
  194996. png_free(png_ptr, chunkdata);
  194997. png_warning(png_ptr, "sPLT chunk has bad length");
  194998. return;
  194999. }
  195000. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  195001. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  195002. png_sizeof(png_sPLT_entry)))
  195003. {
  195004. png_warning(png_ptr, "sPLT chunk too long");
  195005. return;
  195006. }
  195007. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  195008. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  195009. if (new_palette.entries == NULL)
  195010. {
  195011. png_warning(png_ptr, "sPLT chunk requires too much memory");
  195012. return;
  195013. }
  195014. #ifndef PNG_NO_POINTER_INDEXING
  195015. for (i = 0; i < new_palette.nentries; i++)
  195016. {
  195017. png_sPLT_entryp pp = new_palette.entries + i;
  195018. if (new_palette.depth == 8)
  195019. {
  195020. pp->red = *entry_start++;
  195021. pp->green = *entry_start++;
  195022. pp->blue = *entry_start++;
  195023. pp->alpha = *entry_start++;
  195024. }
  195025. else
  195026. {
  195027. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  195028. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  195029. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  195030. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  195031. }
  195032. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  195033. }
  195034. #else
  195035. pp = new_palette.entries;
  195036. for (i = 0; i < new_palette.nentries; i++)
  195037. {
  195038. if (new_palette.depth == 8)
  195039. {
  195040. pp[i].red = *entry_start++;
  195041. pp[i].green = *entry_start++;
  195042. pp[i].blue = *entry_start++;
  195043. pp[i].alpha = *entry_start++;
  195044. }
  195045. else
  195046. {
  195047. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  195048. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  195049. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  195050. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  195051. }
  195052. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  195053. }
  195054. #endif
  195055. /* discard all chunk data except the name and stash that */
  195056. new_palette.name = (png_charp)chunkdata;
  195057. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  195058. png_free(png_ptr, chunkdata);
  195059. png_free(png_ptr, new_palette.entries);
  195060. }
  195061. #endif /* PNG_READ_sPLT_SUPPORTED */
  195062. #if defined(PNG_READ_tRNS_SUPPORTED)
  195063. void /* PRIVATE */
  195064. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195065. {
  195066. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  195067. int bit_mask;
  195068. png_debug(1, "in png_handle_tRNS\n");
  195069. /* For non-indexed color, mask off any bits in the tRNS value that
  195070. * exceed the bit depth. Some creators were writing extra bits there.
  195071. * This is not needed for indexed color. */
  195072. bit_mask = (1 << png_ptr->bit_depth) - 1;
  195073. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195074. png_error(png_ptr, "Missing IHDR before tRNS");
  195075. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195076. {
  195077. png_warning(png_ptr, "Invalid tRNS after IDAT");
  195078. png_crc_finish(png_ptr, length);
  195079. return;
  195080. }
  195081. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  195082. {
  195083. png_warning(png_ptr, "Duplicate tRNS chunk");
  195084. png_crc_finish(png_ptr, length);
  195085. return;
  195086. }
  195087. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  195088. {
  195089. png_byte buf[2];
  195090. if (length != 2)
  195091. {
  195092. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195093. png_crc_finish(png_ptr, length);
  195094. return;
  195095. }
  195096. png_crc_read(png_ptr, buf, 2);
  195097. png_ptr->num_trans = 1;
  195098. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  195099. }
  195100. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  195101. {
  195102. png_byte buf[6];
  195103. if (length != 6)
  195104. {
  195105. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195106. png_crc_finish(png_ptr, length);
  195107. return;
  195108. }
  195109. png_crc_read(png_ptr, buf, (png_size_t)length);
  195110. png_ptr->num_trans = 1;
  195111. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  195112. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  195113. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  195114. }
  195115. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195116. {
  195117. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  195118. {
  195119. /* Should be an error, but we can cope with it. */
  195120. png_warning(png_ptr, "Missing PLTE before tRNS");
  195121. }
  195122. if (length > (png_uint_32)png_ptr->num_palette ||
  195123. length > PNG_MAX_PALETTE_LENGTH)
  195124. {
  195125. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195126. png_crc_finish(png_ptr, length);
  195127. return;
  195128. }
  195129. if (length == 0)
  195130. {
  195131. png_warning(png_ptr, "Zero length tRNS chunk");
  195132. png_crc_finish(png_ptr, length);
  195133. return;
  195134. }
  195135. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  195136. png_ptr->num_trans = (png_uint_16)length;
  195137. }
  195138. else
  195139. {
  195140. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  195141. png_crc_finish(png_ptr, length);
  195142. return;
  195143. }
  195144. if (png_crc_finish(png_ptr, 0))
  195145. {
  195146. png_ptr->num_trans = 0;
  195147. return;
  195148. }
  195149. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  195150. &(png_ptr->trans_values));
  195151. }
  195152. #endif
  195153. #if defined(PNG_READ_bKGD_SUPPORTED)
  195154. void /* PRIVATE */
  195155. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195156. {
  195157. png_size_t truelen;
  195158. png_byte buf[6];
  195159. png_debug(1, "in png_handle_bKGD\n");
  195160. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195161. png_error(png_ptr, "Missing IHDR before bKGD");
  195162. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195163. {
  195164. png_warning(png_ptr, "Invalid bKGD after IDAT");
  195165. png_crc_finish(png_ptr, length);
  195166. return;
  195167. }
  195168. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  195169. !(png_ptr->mode & PNG_HAVE_PLTE))
  195170. {
  195171. png_warning(png_ptr, "Missing PLTE before bKGD");
  195172. png_crc_finish(png_ptr, length);
  195173. return;
  195174. }
  195175. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  195176. {
  195177. png_warning(png_ptr, "Duplicate bKGD chunk");
  195178. png_crc_finish(png_ptr, length);
  195179. return;
  195180. }
  195181. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195182. truelen = 1;
  195183. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  195184. truelen = 6;
  195185. else
  195186. truelen = 2;
  195187. if (length != truelen)
  195188. {
  195189. png_warning(png_ptr, "Incorrect bKGD chunk length");
  195190. png_crc_finish(png_ptr, length);
  195191. return;
  195192. }
  195193. png_crc_read(png_ptr, buf, truelen);
  195194. if (png_crc_finish(png_ptr, 0))
  195195. return;
  195196. /* We convert the index value into RGB components so that we can allow
  195197. * arbitrary RGB values for background when we have transparency, and
  195198. * so it is easy to determine the RGB values of the background color
  195199. * from the info_ptr struct. */
  195200. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195201. {
  195202. png_ptr->background.index = buf[0];
  195203. if(info_ptr->num_palette)
  195204. {
  195205. if(buf[0] > info_ptr->num_palette)
  195206. {
  195207. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  195208. return;
  195209. }
  195210. png_ptr->background.red =
  195211. (png_uint_16)png_ptr->palette[buf[0]].red;
  195212. png_ptr->background.green =
  195213. (png_uint_16)png_ptr->palette[buf[0]].green;
  195214. png_ptr->background.blue =
  195215. (png_uint_16)png_ptr->palette[buf[0]].blue;
  195216. }
  195217. }
  195218. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  195219. {
  195220. png_ptr->background.red =
  195221. png_ptr->background.green =
  195222. png_ptr->background.blue =
  195223. png_ptr->background.gray = png_get_uint_16(buf);
  195224. }
  195225. else
  195226. {
  195227. png_ptr->background.red = png_get_uint_16(buf);
  195228. png_ptr->background.green = png_get_uint_16(buf + 2);
  195229. png_ptr->background.blue = png_get_uint_16(buf + 4);
  195230. }
  195231. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  195232. }
  195233. #endif
  195234. #if defined(PNG_READ_hIST_SUPPORTED)
  195235. void /* PRIVATE */
  195236. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195237. {
  195238. unsigned int num, i;
  195239. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  195240. png_debug(1, "in png_handle_hIST\n");
  195241. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195242. png_error(png_ptr, "Missing IHDR before hIST");
  195243. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195244. {
  195245. png_warning(png_ptr, "Invalid hIST after IDAT");
  195246. png_crc_finish(png_ptr, length);
  195247. return;
  195248. }
  195249. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  195250. {
  195251. png_warning(png_ptr, "Missing PLTE before hIST");
  195252. png_crc_finish(png_ptr, length);
  195253. return;
  195254. }
  195255. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  195256. {
  195257. png_warning(png_ptr, "Duplicate hIST chunk");
  195258. png_crc_finish(png_ptr, length);
  195259. return;
  195260. }
  195261. num = length / 2 ;
  195262. if (num != (unsigned int) png_ptr->num_palette || num >
  195263. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  195264. {
  195265. png_warning(png_ptr, "Incorrect hIST chunk length");
  195266. png_crc_finish(png_ptr, length);
  195267. return;
  195268. }
  195269. for (i = 0; i < num; i++)
  195270. {
  195271. png_byte buf[2];
  195272. png_crc_read(png_ptr, buf, 2);
  195273. readbuf[i] = png_get_uint_16(buf);
  195274. }
  195275. if (png_crc_finish(png_ptr, 0))
  195276. return;
  195277. png_set_hIST(png_ptr, info_ptr, readbuf);
  195278. }
  195279. #endif
  195280. #if defined(PNG_READ_pHYs_SUPPORTED)
  195281. void /* PRIVATE */
  195282. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195283. {
  195284. png_byte buf[9];
  195285. png_uint_32 res_x, res_y;
  195286. int unit_type;
  195287. png_debug(1, "in png_handle_pHYs\n");
  195288. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195289. png_error(png_ptr, "Missing IHDR before pHYs");
  195290. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195291. {
  195292. png_warning(png_ptr, "Invalid pHYs after IDAT");
  195293. png_crc_finish(png_ptr, length);
  195294. return;
  195295. }
  195296. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  195297. {
  195298. png_warning(png_ptr, "Duplicate pHYs chunk");
  195299. png_crc_finish(png_ptr, length);
  195300. return;
  195301. }
  195302. if (length != 9)
  195303. {
  195304. png_warning(png_ptr, "Incorrect pHYs chunk length");
  195305. png_crc_finish(png_ptr, length);
  195306. return;
  195307. }
  195308. png_crc_read(png_ptr, buf, 9);
  195309. if (png_crc_finish(png_ptr, 0))
  195310. return;
  195311. res_x = png_get_uint_32(buf);
  195312. res_y = png_get_uint_32(buf + 4);
  195313. unit_type = buf[8];
  195314. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  195315. }
  195316. #endif
  195317. #if defined(PNG_READ_oFFs_SUPPORTED)
  195318. void /* PRIVATE */
  195319. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195320. {
  195321. png_byte buf[9];
  195322. png_int_32 offset_x, offset_y;
  195323. int unit_type;
  195324. png_debug(1, "in png_handle_oFFs\n");
  195325. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195326. png_error(png_ptr, "Missing IHDR before oFFs");
  195327. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195328. {
  195329. png_warning(png_ptr, "Invalid oFFs after IDAT");
  195330. png_crc_finish(png_ptr, length);
  195331. return;
  195332. }
  195333. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  195334. {
  195335. png_warning(png_ptr, "Duplicate oFFs chunk");
  195336. png_crc_finish(png_ptr, length);
  195337. return;
  195338. }
  195339. if (length != 9)
  195340. {
  195341. png_warning(png_ptr, "Incorrect oFFs chunk length");
  195342. png_crc_finish(png_ptr, length);
  195343. return;
  195344. }
  195345. png_crc_read(png_ptr, buf, 9);
  195346. if (png_crc_finish(png_ptr, 0))
  195347. return;
  195348. offset_x = png_get_int_32(buf);
  195349. offset_y = png_get_int_32(buf + 4);
  195350. unit_type = buf[8];
  195351. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  195352. }
  195353. #endif
  195354. #if defined(PNG_READ_pCAL_SUPPORTED)
  195355. /* read the pCAL chunk (described in the PNG Extensions document) */
  195356. void /* PRIVATE */
  195357. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195358. {
  195359. png_charp purpose;
  195360. png_int_32 X0, X1;
  195361. png_byte type, nparams;
  195362. png_charp buf, units, endptr;
  195363. png_charpp params;
  195364. png_size_t slength;
  195365. int i;
  195366. png_debug(1, "in png_handle_pCAL\n");
  195367. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195368. png_error(png_ptr, "Missing IHDR before pCAL");
  195369. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195370. {
  195371. png_warning(png_ptr, "Invalid pCAL after IDAT");
  195372. png_crc_finish(png_ptr, length);
  195373. return;
  195374. }
  195375. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  195376. {
  195377. png_warning(png_ptr, "Duplicate pCAL chunk");
  195378. png_crc_finish(png_ptr, length);
  195379. return;
  195380. }
  195381. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  195382. length + 1);
  195383. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195384. if (purpose == NULL)
  195385. {
  195386. png_warning(png_ptr, "No memory for pCAL purpose.");
  195387. return;
  195388. }
  195389. slength = (png_size_t)length;
  195390. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  195391. if (png_crc_finish(png_ptr, 0))
  195392. {
  195393. png_free(png_ptr, purpose);
  195394. return;
  195395. }
  195396. purpose[slength] = 0x00; /* null terminate the last string */
  195397. png_debug(3, "Finding end of pCAL purpose string\n");
  195398. for (buf = purpose; *buf; buf++)
  195399. /* empty loop */ ;
  195400. endptr = purpose + slength;
  195401. /* We need to have at least 12 bytes after the purpose string
  195402. in order to get the parameter information. */
  195403. if (endptr <= buf + 12)
  195404. {
  195405. png_warning(png_ptr, "Invalid pCAL data");
  195406. png_free(png_ptr, purpose);
  195407. return;
  195408. }
  195409. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  195410. X0 = png_get_int_32((png_bytep)buf+1);
  195411. X1 = png_get_int_32((png_bytep)buf+5);
  195412. type = buf[9];
  195413. nparams = buf[10];
  195414. units = buf + 11;
  195415. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  195416. /* Check that we have the right number of parameters for known
  195417. equation types. */
  195418. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  195419. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  195420. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  195421. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  195422. {
  195423. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  195424. png_free(png_ptr, purpose);
  195425. return;
  195426. }
  195427. else if (type >= PNG_EQUATION_LAST)
  195428. {
  195429. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  195430. }
  195431. for (buf = units; *buf; buf++)
  195432. /* Empty loop to move past the units string. */ ;
  195433. png_debug(3, "Allocating pCAL parameters array\n");
  195434. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  195435. *png_sizeof(png_charp))) ;
  195436. if (params == NULL)
  195437. {
  195438. png_free(png_ptr, purpose);
  195439. png_warning(png_ptr, "No memory for pCAL params.");
  195440. return;
  195441. }
  195442. /* Get pointers to the start of each parameter string. */
  195443. for (i = 0; i < (int)nparams; i++)
  195444. {
  195445. buf++; /* Skip the null string terminator from previous parameter. */
  195446. png_debug1(3, "Reading pCAL parameter %d\n", i);
  195447. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  195448. /* Empty loop to move past each parameter string */ ;
  195449. /* Make sure we haven't run out of data yet */
  195450. if (buf > endptr)
  195451. {
  195452. png_warning(png_ptr, "Invalid pCAL data");
  195453. png_free(png_ptr, purpose);
  195454. png_free(png_ptr, params);
  195455. return;
  195456. }
  195457. }
  195458. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  195459. units, params);
  195460. png_free(png_ptr, purpose);
  195461. png_free(png_ptr, params);
  195462. }
  195463. #endif
  195464. #if defined(PNG_READ_sCAL_SUPPORTED)
  195465. /* read the sCAL chunk */
  195466. void /* PRIVATE */
  195467. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195468. {
  195469. png_charp buffer, ep;
  195470. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195471. double width, height;
  195472. png_charp vp;
  195473. #else
  195474. #ifdef PNG_FIXED_POINT_SUPPORTED
  195475. png_charp swidth, sheight;
  195476. #endif
  195477. #endif
  195478. png_size_t slength;
  195479. png_debug(1, "in png_handle_sCAL\n");
  195480. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195481. png_error(png_ptr, "Missing IHDR before sCAL");
  195482. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195483. {
  195484. png_warning(png_ptr, "Invalid sCAL after IDAT");
  195485. png_crc_finish(png_ptr, length);
  195486. return;
  195487. }
  195488. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  195489. {
  195490. png_warning(png_ptr, "Duplicate sCAL chunk");
  195491. png_crc_finish(png_ptr, length);
  195492. return;
  195493. }
  195494. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  195495. length + 1);
  195496. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195497. if (buffer == NULL)
  195498. {
  195499. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  195500. return;
  195501. }
  195502. slength = (png_size_t)length;
  195503. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  195504. if (png_crc_finish(png_ptr, 0))
  195505. {
  195506. png_free(png_ptr, buffer);
  195507. return;
  195508. }
  195509. buffer[slength] = 0x00; /* null terminate the last string */
  195510. ep = buffer + 1; /* skip unit byte */
  195511. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195512. width = png_strtod(png_ptr, ep, &vp);
  195513. if (*vp)
  195514. {
  195515. png_warning(png_ptr, "malformed width string in sCAL chunk");
  195516. return;
  195517. }
  195518. #else
  195519. #ifdef PNG_FIXED_POINT_SUPPORTED
  195520. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195521. if (swidth == NULL)
  195522. {
  195523. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  195524. return;
  195525. }
  195526. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  195527. #endif
  195528. #endif
  195529. for (ep = buffer; *ep; ep++)
  195530. /* empty loop */ ;
  195531. ep++;
  195532. if (buffer + slength < ep)
  195533. {
  195534. png_warning(png_ptr, "Truncated sCAL chunk");
  195535. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  195536. !defined(PNG_FLOATING_POINT_SUPPORTED)
  195537. png_free(png_ptr, swidth);
  195538. #endif
  195539. png_free(png_ptr, buffer);
  195540. return;
  195541. }
  195542. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195543. height = png_strtod(png_ptr, ep, &vp);
  195544. if (*vp)
  195545. {
  195546. png_warning(png_ptr, "malformed height string in sCAL chunk");
  195547. return;
  195548. }
  195549. #else
  195550. #ifdef PNG_FIXED_POINT_SUPPORTED
  195551. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195552. if (swidth == NULL)
  195553. {
  195554. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  195555. return;
  195556. }
  195557. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  195558. #endif
  195559. #endif
  195560. if (buffer + slength < ep
  195561. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195562. || width <= 0. || height <= 0.
  195563. #endif
  195564. )
  195565. {
  195566. png_warning(png_ptr, "Invalid sCAL data");
  195567. png_free(png_ptr, buffer);
  195568. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195569. png_free(png_ptr, swidth);
  195570. png_free(png_ptr, sheight);
  195571. #endif
  195572. return;
  195573. }
  195574. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195575. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  195576. #else
  195577. #ifdef PNG_FIXED_POINT_SUPPORTED
  195578. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  195579. #endif
  195580. #endif
  195581. png_free(png_ptr, buffer);
  195582. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195583. png_free(png_ptr, swidth);
  195584. png_free(png_ptr, sheight);
  195585. #endif
  195586. }
  195587. #endif
  195588. #if defined(PNG_READ_tIME_SUPPORTED)
  195589. void /* PRIVATE */
  195590. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195591. {
  195592. png_byte buf[7];
  195593. png_time mod_time;
  195594. png_debug(1, "in png_handle_tIME\n");
  195595. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195596. png_error(png_ptr, "Out of place tIME chunk");
  195597. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  195598. {
  195599. png_warning(png_ptr, "Duplicate tIME chunk");
  195600. png_crc_finish(png_ptr, length);
  195601. return;
  195602. }
  195603. if (png_ptr->mode & PNG_HAVE_IDAT)
  195604. png_ptr->mode |= PNG_AFTER_IDAT;
  195605. if (length != 7)
  195606. {
  195607. png_warning(png_ptr, "Incorrect tIME chunk length");
  195608. png_crc_finish(png_ptr, length);
  195609. return;
  195610. }
  195611. png_crc_read(png_ptr, buf, 7);
  195612. if (png_crc_finish(png_ptr, 0))
  195613. return;
  195614. mod_time.second = buf[6];
  195615. mod_time.minute = buf[5];
  195616. mod_time.hour = buf[4];
  195617. mod_time.day = buf[3];
  195618. mod_time.month = buf[2];
  195619. mod_time.year = png_get_uint_16(buf);
  195620. png_set_tIME(png_ptr, info_ptr, &mod_time);
  195621. }
  195622. #endif
  195623. #if defined(PNG_READ_tEXt_SUPPORTED)
  195624. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195625. void /* PRIVATE */
  195626. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195627. {
  195628. png_textp text_ptr;
  195629. png_charp key;
  195630. png_charp text;
  195631. png_uint_32 skip = 0;
  195632. png_size_t slength;
  195633. int ret;
  195634. png_debug(1, "in png_handle_tEXt\n");
  195635. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195636. png_error(png_ptr, "Missing IHDR before tEXt");
  195637. if (png_ptr->mode & PNG_HAVE_IDAT)
  195638. png_ptr->mode |= PNG_AFTER_IDAT;
  195639. #ifdef PNG_MAX_MALLOC_64K
  195640. if (length > (png_uint_32)65535L)
  195641. {
  195642. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  195643. skip = length - (png_uint_32)65535L;
  195644. length = (png_uint_32)65535L;
  195645. }
  195646. #endif
  195647. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195648. if (key == NULL)
  195649. {
  195650. png_warning(png_ptr, "No memory to process text chunk.");
  195651. return;
  195652. }
  195653. slength = (png_size_t)length;
  195654. png_crc_read(png_ptr, (png_bytep)key, slength);
  195655. if (png_crc_finish(png_ptr, skip))
  195656. {
  195657. png_free(png_ptr, key);
  195658. return;
  195659. }
  195660. key[slength] = 0x00;
  195661. for (text = key; *text; text++)
  195662. /* empty loop to find end of key */ ;
  195663. if (text != key + slength)
  195664. text++;
  195665. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195666. (png_uint_32)png_sizeof(png_text));
  195667. if (text_ptr == NULL)
  195668. {
  195669. png_warning(png_ptr, "Not enough memory to process text chunk.");
  195670. png_free(png_ptr, key);
  195671. return;
  195672. }
  195673. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  195674. text_ptr->key = key;
  195675. #ifdef PNG_iTXt_SUPPORTED
  195676. text_ptr->lang = NULL;
  195677. text_ptr->lang_key = NULL;
  195678. text_ptr->itxt_length = 0;
  195679. #endif
  195680. text_ptr->text = text;
  195681. text_ptr->text_length = png_strlen(text);
  195682. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195683. png_free(png_ptr, key);
  195684. png_free(png_ptr, text_ptr);
  195685. if (ret)
  195686. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  195687. }
  195688. #endif
  195689. #if defined(PNG_READ_zTXt_SUPPORTED)
  195690. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195691. void /* PRIVATE */
  195692. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195693. {
  195694. png_textp text_ptr;
  195695. png_charp chunkdata;
  195696. png_charp text;
  195697. int comp_type;
  195698. int ret;
  195699. png_size_t slength, prefix_len, data_len;
  195700. png_debug(1, "in png_handle_zTXt\n");
  195701. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195702. png_error(png_ptr, "Missing IHDR before zTXt");
  195703. if (png_ptr->mode & PNG_HAVE_IDAT)
  195704. png_ptr->mode |= PNG_AFTER_IDAT;
  195705. #ifdef PNG_MAX_MALLOC_64K
  195706. /* We will no doubt have problems with chunks even half this size, but
  195707. there is no hard and fast rule to tell us where to stop. */
  195708. if (length > (png_uint_32)65535L)
  195709. {
  195710. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  195711. png_crc_finish(png_ptr, length);
  195712. return;
  195713. }
  195714. #endif
  195715. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195716. if (chunkdata == NULL)
  195717. {
  195718. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  195719. return;
  195720. }
  195721. slength = (png_size_t)length;
  195722. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195723. if (png_crc_finish(png_ptr, 0))
  195724. {
  195725. png_free(png_ptr, chunkdata);
  195726. return;
  195727. }
  195728. chunkdata[slength] = 0x00;
  195729. for (text = chunkdata; *text; text++)
  195730. /* empty loop */ ;
  195731. /* zTXt must have some text after the chunkdataword */
  195732. if (text >= chunkdata + slength - 2)
  195733. {
  195734. png_warning(png_ptr, "Truncated zTXt chunk");
  195735. png_free(png_ptr, chunkdata);
  195736. return;
  195737. }
  195738. else
  195739. {
  195740. comp_type = *(++text);
  195741. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  195742. {
  195743. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  195744. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  195745. }
  195746. text++; /* skip the compression_method byte */
  195747. }
  195748. prefix_len = text - chunkdata;
  195749. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195750. (png_size_t)length, prefix_len, &data_len);
  195751. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195752. (png_uint_32)png_sizeof(png_text));
  195753. if (text_ptr == NULL)
  195754. {
  195755. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  195756. png_free(png_ptr, chunkdata);
  195757. return;
  195758. }
  195759. text_ptr->compression = comp_type;
  195760. text_ptr->key = chunkdata;
  195761. #ifdef PNG_iTXt_SUPPORTED
  195762. text_ptr->lang = NULL;
  195763. text_ptr->lang_key = NULL;
  195764. text_ptr->itxt_length = 0;
  195765. #endif
  195766. text_ptr->text = chunkdata + prefix_len;
  195767. text_ptr->text_length = data_len;
  195768. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195769. png_free(png_ptr, text_ptr);
  195770. png_free(png_ptr, chunkdata);
  195771. if (ret)
  195772. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  195773. }
  195774. #endif
  195775. #if defined(PNG_READ_iTXt_SUPPORTED)
  195776. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195777. void /* PRIVATE */
  195778. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195779. {
  195780. png_textp text_ptr;
  195781. png_charp chunkdata;
  195782. png_charp key, lang, text, lang_key;
  195783. int comp_flag;
  195784. int comp_type = 0;
  195785. int ret;
  195786. png_size_t slength, prefix_len, data_len;
  195787. png_debug(1, "in png_handle_iTXt\n");
  195788. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195789. png_error(png_ptr, "Missing IHDR before iTXt");
  195790. if (png_ptr->mode & PNG_HAVE_IDAT)
  195791. png_ptr->mode |= PNG_AFTER_IDAT;
  195792. #ifdef PNG_MAX_MALLOC_64K
  195793. /* We will no doubt have problems with chunks even half this size, but
  195794. there is no hard and fast rule to tell us where to stop. */
  195795. if (length > (png_uint_32)65535L)
  195796. {
  195797. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  195798. png_crc_finish(png_ptr, length);
  195799. return;
  195800. }
  195801. #endif
  195802. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195803. if (chunkdata == NULL)
  195804. {
  195805. png_warning(png_ptr, "No memory to process iTXt chunk.");
  195806. return;
  195807. }
  195808. slength = (png_size_t)length;
  195809. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195810. if (png_crc_finish(png_ptr, 0))
  195811. {
  195812. png_free(png_ptr, chunkdata);
  195813. return;
  195814. }
  195815. chunkdata[slength] = 0x00;
  195816. for (lang = chunkdata; *lang; lang++)
  195817. /* empty loop */ ;
  195818. lang++; /* skip NUL separator */
  195819. /* iTXt must have a language tag (possibly empty), two compression bytes,
  195820. translated keyword (possibly empty), and possibly some text after the
  195821. keyword */
  195822. if (lang >= chunkdata + slength - 3)
  195823. {
  195824. png_warning(png_ptr, "Truncated iTXt chunk");
  195825. png_free(png_ptr, chunkdata);
  195826. return;
  195827. }
  195828. else
  195829. {
  195830. comp_flag = *lang++;
  195831. comp_type = *lang++;
  195832. }
  195833. for (lang_key = lang; *lang_key; lang_key++)
  195834. /* empty loop */ ;
  195835. lang_key++; /* skip NUL separator */
  195836. if (lang_key >= chunkdata + slength)
  195837. {
  195838. png_warning(png_ptr, "Truncated iTXt chunk");
  195839. png_free(png_ptr, chunkdata);
  195840. return;
  195841. }
  195842. for (text = lang_key; *text; text++)
  195843. /* empty loop */ ;
  195844. text++; /* skip NUL separator */
  195845. if (text >= chunkdata + slength)
  195846. {
  195847. png_warning(png_ptr, "Malformed iTXt chunk");
  195848. png_free(png_ptr, chunkdata);
  195849. return;
  195850. }
  195851. prefix_len = text - chunkdata;
  195852. key=chunkdata;
  195853. if (comp_flag)
  195854. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195855. (size_t)length, prefix_len, &data_len);
  195856. else
  195857. data_len=png_strlen(chunkdata + prefix_len);
  195858. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195859. (png_uint_32)png_sizeof(png_text));
  195860. if (text_ptr == NULL)
  195861. {
  195862. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  195863. png_free(png_ptr, chunkdata);
  195864. return;
  195865. }
  195866. text_ptr->compression = (int)comp_flag + 1;
  195867. text_ptr->lang_key = chunkdata+(lang_key-key);
  195868. text_ptr->lang = chunkdata+(lang-key);
  195869. text_ptr->itxt_length = data_len;
  195870. text_ptr->text_length = 0;
  195871. text_ptr->key = chunkdata;
  195872. text_ptr->text = chunkdata + prefix_len;
  195873. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195874. png_free(png_ptr, text_ptr);
  195875. png_free(png_ptr, chunkdata);
  195876. if (ret)
  195877. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  195878. }
  195879. #endif
  195880. /* This function is called when we haven't found a handler for a
  195881. chunk. If there isn't a problem with the chunk itself (ie bad
  195882. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  195883. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  195884. case it will be saved away to be written out later. */
  195885. void /* PRIVATE */
  195886. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195887. {
  195888. png_uint_32 skip = 0;
  195889. png_debug(1, "in png_handle_unknown\n");
  195890. if (png_ptr->mode & PNG_HAVE_IDAT)
  195891. {
  195892. #ifdef PNG_USE_LOCAL_ARRAYS
  195893. PNG_CONST PNG_IDAT;
  195894. #endif
  195895. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  195896. png_ptr->mode |= PNG_AFTER_IDAT;
  195897. }
  195898. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  195899. if (!(png_ptr->chunk_name[0] & 0x20))
  195900. {
  195901. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195902. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195903. PNG_HANDLE_CHUNK_ALWAYS
  195904. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195905. && png_ptr->read_user_chunk_fn == NULL
  195906. #endif
  195907. )
  195908. #endif
  195909. png_chunk_error(png_ptr, "unknown critical chunk");
  195910. }
  195911. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  195912. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  195913. (png_ptr->read_user_chunk_fn != NULL))
  195914. {
  195915. #ifdef PNG_MAX_MALLOC_64K
  195916. if (length > (png_uint_32)65535L)
  195917. {
  195918. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  195919. skip = length - (png_uint_32)65535L;
  195920. length = (png_uint_32)65535L;
  195921. }
  195922. #endif
  195923. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  195924. (png_charp)png_ptr->chunk_name, 5);
  195925. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  195926. png_ptr->unknown_chunk.size = (png_size_t)length;
  195927. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  195928. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195929. if(png_ptr->read_user_chunk_fn != NULL)
  195930. {
  195931. /* callback to user unknown chunk handler */
  195932. int ret;
  195933. ret = (*(png_ptr->read_user_chunk_fn))
  195934. (png_ptr, &png_ptr->unknown_chunk);
  195935. if (ret < 0)
  195936. png_chunk_error(png_ptr, "error in user chunk");
  195937. if (ret == 0)
  195938. {
  195939. if (!(png_ptr->chunk_name[0] & 0x20))
  195940. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  195941. PNG_HANDLE_CHUNK_ALWAYS)
  195942. png_chunk_error(png_ptr, "unknown critical chunk");
  195943. png_set_unknown_chunks(png_ptr, info_ptr,
  195944. &png_ptr->unknown_chunk, 1);
  195945. }
  195946. }
  195947. #else
  195948. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  195949. #endif
  195950. png_free(png_ptr, png_ptr->unknown_chunk.data);
  195951. png_ptr->unknown_chunk.data = NULL;
  195952. }
  195953. else
  195954. #endif
  195955. skip = length;
  195956. png_crc_finish(png_ptr, skip);
  195957. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  195958. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  195959. #endif
  195960. }
  195961. /* This function is called to verify that a chunk name is valid.
  195962. This function can't have the "critical chunk check" incorporated
  195963. into it, since in the future we will need to be able to call user
  195964. functions to handle unknown critical chunks after we check that
  195965. the chunk name itself is valid. */
  195966. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  195967. void /* PRIVATE */
  195968. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  195969. {
  195970. png_debug(1, "in png_check_chunk_name\n");
  195971. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  195972. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  195973. {
  195974. png_chunk_error(png_ptr, "invalid chunk type");
  195975. }
  195976. }
  195977. /* Combines the row recently read in with the existing pixels in the
  195978. row. This routine takes care of alpha and transparency if requested.
  195979. This routine also handles the two methods of progressive display
  195980. of interlaced images, depending on the mask value.
  195981. The mask value describes which pixels are to be combined with
  195982. the row. The pattern always repeats every 8 pixels, so just 8
  195983. bits are needed. A one indicates the pixel is to be combined,
  195984. a zero indicates the pixel is to be skipped. This is in addition
  195985. to any alpha or transparency value associated with the pixel. If
  195986. you want all pixels to be combined, pass 0xff (255) in mask. */
  195987. void /* PRIVATE */
  195988. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  195989. {
  195990. png_debug(1,"in png_combine_row\n");
  195991. if (mask == 0xff)
  195992. {
  195993. png_memcpy(row, png_ptr->row_buf + 1,
  195994. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  195995. }
  195996. else
  195997. {
  195998. switch (png_ptr->row_info.pixel_depth)
  195999. {
  196000. case 1:
  196001. {
  196002. png_bytep sp = png_ptr->row_buf + 1;
  196003. png_bytep dp = row;
  196004. int s_inc, s_start, s_end;
  196005. int m = 0x80;
  196006. int shift;
  196007. png_uint_32 i;
  196008. png_uint_32 row_width = png_ptr->width;
  196009. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196010. if (png_ptr->transformations & PNG_PACKSWAP)
  196011. {
  196012. s_start = 0;
  196013. s_end = 7;
  196014. s_inc = 1;
  196015. }
  196016. else
  196017. #endif
  196018. {
  196019. s_start = 7;
  196020. s_end = 0;
  196021. s_inc = -1;
  196022. }
  196023. shift = s_start;
  196024. for (i = 0; i < row_width; i++)
  196025. {
  196026. if (m & mask)
  196027. {
  196028. int value;
  196029. value = (*sp >> shift) & 0x01;
  196030. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  196031. *dp |= (png_byte)(value << shift);
  196032. }
  196033. if (shift == s_end)
  196034. {
  196035. shift = s_start;
  196036. sp++;
  196037. dp++;
  196038. }
  196039. else
  196040. shift += s_inc;
  196041. if (m == 1)
  196042. m = 0x80;
  196043. else
  196044. m >>= 1;
  196045. }
  196046. break;
  196047. }
  196048. case 2:
  196049. {
  196050. png_bytep sp = png_ptr->row_buf + 1;
  196051. png_bytep dp = row;
  196052. int s_start, s_end, s_inc;
  196053. int m = 0x80;
  196054. int shift;
  196055. png_uint_32 i;
  196056. png_uint_32 row_width = png_ptr->width;
  196057. int value;
  196058. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196059. if (png_ptr->transformations & PNG_PACKSWAP)
  196060. {
  196061. s_start = 0;
  196062. s_end = 6;
  196063. s_inc = 2;
  196064. }
  196065. else
  196066. #endif
  196067. {
  196068. s_start = 6;
  196069. s_end = 0;
  196070. s_inc = -2;
  196071. }
  196072. shift = s_start;
  196073. for (i = 0; i < row_width; i++)
  196074. {
  196075. if (m & mask)
  196076. {
  196077. value = (*sp >> shift) & 0x03;
  196078. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  196079. *dp |= (png_byte)(value << shift);
  196080. }
  196081. if (shift == s_end)
  196082. {
  196083. shift = s_start;
  196084. sp++;
  196085. dp++;
  196086. }
  196087. else
  196088. shift += s_inc;
  196089. if (m == 1)
  196090. m = 0x80;
  196091. else
  196092. m >>= 1;
  196093. }
  196094. break;
  196095. }
  196096. case 4:
  196097. {
  196098. png_bytep sp = png_ptr->row_buf + 1;
  196099. png_bytep dp = row;
  196100. int s_start, s_end, s_inc;
  196101. int m = 0x80;
  196102. int shift;
  196103. png_uint_32 i;
  196104. png_uint_32 row_width = png_ptr->width;
  196105. int value;
  196106. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196107. if (png_ptr->transformations & PNG_PACKSWAP)
  196108. {
  196109. s_start = 0;
  196110. s_end = 4;
  196111. s_inc = 4;
  196112. }
  196113. else
  196114. #endif
  196115. {
  196116. s_start = 4;
  196117. s_end = 0;
  196118. s_inc = -4;
  196119. }
  196120. shift = s_start;
  196121. for (i = 0; i < row_width; i++)
  196122. {
  196123. if (m & mask)
  196124. {
  196125. value = (*sp >> shift) & 0xf;
  196126. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  196127. *dp |= (png_byte)(value << shift);
  196128. }
  196129. if (shift == s_end)
  196130. {
  196131. shift = s_start;
  196132. sp++;
  196133. dp++;
  196134. }
  196135. else
  196136. shift += s_inc;
  196137. if (m == 1)
  196138. m = 0x80;
  196139. else
  196140. m >>= 1;
  196141. }
  196142. break;
  196143. }
  196144. default:
  196145. {
  196146. png_bytep sp = png_ptr->row_buf + 1;
  196147. png_bytep dp = row;
  196148. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  196149. png_uint_32 i;
  196150. png_uint_32 row_width = png_ptr->width;
  196151. png_byte m = 0x80;
  196152. for (i = 0; i < row_width; i++)
  196153. {
  196154. if (m & mask)
  196155. {
  196156. png_memcpy(dp, sp, pixel_bytes);
  196157. }
  196158. sp += pixel_bytes;
  196159. dp += pixel_bytes;
  196160. if (m == 1)
  196161. m = 0x80;
  196162. else
  196163. m >>= 1;
  196164. }
  196165. break;
  196166. }
  196167. }
  196168. }
  196169. }
  196170. #ifdef PNG_READ_INTERLACING_SUPPORTED
  196171. /* OLD pre-1.0.9 interface:
  196172. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  196173. png_uint_32 transformations)
  196174. */
  196175. void /* PRIVATE */
  196176. png_do_read_interlace(png_structp png_ptr)
  196177. {
  196178. png_row_infop row_info = &(png_ptr->row_info);
  196179. png_bytep row = png_ptr->row_buf + 1;
  196180. int pass = png_ptr->pass;
  196181. png_uint_32 transformations = png_ptr->transformations;
  196182. #ifdef PNG_USE_LOCAL_ARRAYS
  196183. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196184. /* offset to next interlace block */
  196185. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196186. #endif
  196187. png_debug(1,"in png_do_read_interlace\n");
  196188. if (row != NULL && row_info != NULL)
  196189. {
  196190. png_uint_32 final_width;
  196191. final_width = row_info->width * png_pass_inc[pass];
  196192. switch (row_info->pixel_depth)
  196193. {
  196194. case 1:
  196195. {
  196196. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  196197. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  196198. int sshift, dshift;
  196199. int s_start, s_end, s_inc;
  196200. int jstop = png_pass_inc[pass];
  196201. png_byte v;
  196202. png_uint_32 i;
  196203. int j;
  196204. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196205. if (transformations & PNG_PACKSWAP)
  196206. {
  196207. sshift = (int)((row_info->width + 7) & 0x07);
  196208. dshift = (int)((final_width + 7) & 0x07);
  196209. s_start = 7;
  196210. s_end = 0;
  196211. s_inc = -1;
  196212. }
  196213. else
  196214. #endif
  196215. {
  196216. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  196217. dshift = 7 - (int)((final_width + 7) & 0x07);
  196218. s_start = 0;
  196219. s_end = 7;
  196220. s_inc = 1;
  196221. }
  196222. for (i = 0; i < row_info->width; i++)
  196223. {
  196224. v = (png_byte)((*sp >> sshift) & 0x01);
  196225. for (j = 0; j < jstop; j++)
  196226. {
  196227. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  196228. *dp |= (png_byte)(v << dshift);
  196229. if (dshift == s_end)
  196230. {
  196231. dshift = s_start;
  196232. dp--;
  196233. }
  196234. else
  196235. dshift += s_inc;
  196236. }
  196237. if (sshift == s_end)
  196238. {
  196239. sshift = s_start;
  196240. sp--;
  196241. }
  196242. else
  196243. sshift += s_inc;
  196244. }
  196245. break;
  196246. }
  196247. case 2:
  196248. {
  196249. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  196250. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  196251. int sshift, dshift;
  196252. int s_start, s_end, s_inc;
  196253. int jstop = png_pass_inc[pass];
  196254. png_uint_32 i;
  196255. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196256. if (transformations & PNG_PACKSWAP)
  196257. {
  196258. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  196259. dshift = (int)(((final_width + 3) & 0x03) << 1);
  196260. s_start = 6;
  196261. s_end = 0;
  196262. s_inc = -2;
  196263. }
  196264. else
  196265. #endif
  196266. {
  196267. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  196268. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  196269. s_start = 0;
  196270. s_end = 6;
  196271. s_inc = 2;
  196272. }
  196273. for (i = 0; i < row_info->width; i++)
  196274. {
  196275. png_byte v;
  196276. int j;
  196277. v = (png_byte)((*sp >> sshift) & 0x03);
  196278. for (j = 0; j < jstop; j++)
  196279. {
  196280. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  196281. *dp |= (png_byte)(v << dshift);
  196282. if (dshift == s_end)
  196283. {
  196284. dshift = s_start;
  196285. dp--;
  196286. }
  196287. else
  196288. dshift += s_inc;
  196289. }
  196290. if (sshift == s_end)
  196291. {
  196292. sshift = s_start;
  196293. sp--;
  196294. }
  196295. else
  196296. sshift += s_inc;
  196297. }
  196298. break;
  196299. }
  196300. case 4:
  196301. {
  196302. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  196303. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  196304. int sshift, dshift;
  196305. int s_start, s_end, s_inc;
  196306. png_uint_32 i;
  196307. int jstop = png_pass_inc[pass];
  196308. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196309. if (transformations & PNG_PACKSWAP)
  196310. {
  196311. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  196312. dshift = (int)(((final_width + 1) & 0x01) << 2);
  196313. s_start = 4;
  196314. s_end = 0;
  196315. s_inc = -4;
  196316. }
  196317. else
  196318. #endif
  196319. {
  196320. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  196321. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  196322. s_start = 0;
  196323. s_end = 4;
  196324. s_inc = 4;
  196325. }
  196326. for (i = 0; i < row_info->width; i++)
  196327. {
  196328. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  196329. int j;
  196330. for (j = 0; j < jstop; j++)
  196331. {
  196332. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  196333. *dp |= (png_byte)(v << dshift);
  196334. if (dshift == s_end)
  196335. {
  196336. dshift = s_start;
  196337. dp--;
  196338. }
  196339. else
  196340. dshift += s_inc;
  196341. }
  196342. if (sshift == s_end)
  196343. {
  196344. sshift = s_start;
  196345. sp--;
  196346. }
  196347. else
  196348. sshift += s_inc;
  196349. }
  196350. break;
  196351. }
  196352. default:
  196353. {
  196354. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  196355. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  196356. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  196357. int jstop = png_pass_inc[pass];
  196358. png_uint_32 i;
  196359. for (i = 0; i < row_info->width; i++)
  196360. {
  196361. png_byte v[8];
  196362. int j;
  196363. png_memcpy(v, sp, pixel_bytes);
  196364. for (j = 0; j < jstop; j++)
  196365. {
  196366. png_memcpy(dp, v, pixel_bytes);
  196367. dp -= pixel_bytes;
  196368. }
  196369. sp -= pixel_bytes;
  196370. }
  196371. break;
  196372. }
  196373. }
  196374. row_info->width = final_width;
  196375. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  196376. }
  196377. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  196378. transformations = transformations; /* silence compiler warning */
  196379. #endif
  196380. }
  196381. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  196382. void /* PRIVATE */
  196383. png_read_filter_row(png_structp, png_row_infop row_info, png_bytep row,
  196384. png_bytep prev_row, int filter)
  196385. {
  196386. png_debug(1, "in png_read_filter_row\n");
  196387. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  196388. switch (filter)
  196389. {
  196390. case PNG_FILTER_VALUE_NONE:
  196391. break;
  196392. case PNG_FILTER_VALUE_SUB:
  196393. {
  196394. png_uint_32 i;
  196395. png_uint_32 istop = row_info->rowbytes;
  196396. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196397. png_bytep rp = row + bpp;
  196398. png_bytep lp = row;
  196399. for (i = bpp; i < istop; i++)
  196400. {
  196401. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  196402. rp++;
  196403. }
  196404. break;
  196405. }
  196406. case PNG_FILTER_VALUE_UP:
  196407. {
  196408. png_uint_32 i;
  196409. png_uint_32 istop = row_info->rowbytes;
  196410. png_bytep rp = row;
  196411. png_bytep pp = prev_row;
  196412. for (i = 0; i < istop; i++)
  196413. {
  196414. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196415. rp++;
  196416. }
  196417. break;
  196418. }
  196419. case PNG_FILTER_VALUE_AVG:
  196420. {
  196421. png_uint_32 i;
  196422. png_bytep rp = row;
  196423. png_bytep pp = prev_row;
  196424. png_bytep lp = row;
  196425. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196426. png_uint_32 istop = row_info->rowbytes - bpp;
  196427. for (i = 0; i < bpp; i++)
  196428. {
  196429. *rp = (png_byte)(((int)(*rp) +
  196430. ((int)(*pp++) / 2 )) & 0xff);
  196431. rp++;
  196432. }
  196433. for (i = 0; i < istop; i++)
  196434. {
  196435. *rp = (png_byte)(((int)(*rp) +
  196436. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  196437. rp++;
  196438. }
  196439. break;
  196440. }
  196441. case PNG_FILTER_VALUE_PAETH:
  196442. {
  196443. png_uint_32 i;
  196444. png_bytep rp = row;
  196445. png_bytep pp = prev_row;
  196446. png_bytep lp = row;
  196447. png_bytep cp = prev_row;
  196448. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196449. png_uint_32 istop=row_info->rowbytes - bpp;
  196450. for (i = 0; i < bpp; i++)
  196451. {
  196452. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196453. rp++;
  196454. }
  196455. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  196456. {
  196457. int a, b, c, pa, pb, pc, p;
  196458. a = *lp++;
  196459. b = *pp++;
  196460. c = *cp++;
  196461. p = b - c;
  196462. pc = a - c;
  196463. #ifdef PNG_USE_ABS
  196464. pa = abs(p);
  196465. pb = abs(pc);
  196466. pc = abs(p + pc);
  196467. #else
  196468. pa = p < 0 ? -p : p;
  196469. pb = pc < 0 ? -pc : pc;
  196470. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  196471. #endif
  196472. /*
  196473. if (pa <= pb && pa <= pc)
  196474. p = a;
  196475. else if (pb <= pc)
  196476. p = b;
  196477. else
  196478. p = c;
  196479. */
  196480. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  196481. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  196482. rp++;
  196483. }
  196484. break;
  196485. }
  196486. default:
  196487. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  196488. *row=0;
  196489. break;
  196490. }
  196491. }
  196492. void /* PRIVATE */
  196493. png_read_finish_row(png_structp png_ptr)
  196494. {
  196495. #ifdef PNG_USE_LOCAL_ARRAYS
  196496. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196497. /* start of interlace block */
  196498. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196499. /* offset to next interlace block */
  196500. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196501. /* start of interlace block in the y direction */
  196502. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196503. /* offset to next interlace block in the y direction */
  196504. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196505. #endif
  196506. png_debug(1, "in png_read_finish_row\n");
  196507. png_ptr->row_number++;
  196508. if (png_ptr->row_number < png_ptr->num_rows)
  196509. return;
  196510. if (png_ptr->interlaced)
  196511. {
  196512. png_ptr->row_number = 0;
  196513. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  196514. png_ptr->rowbytes + 1);
  196515. do
  196516. {
  196517. png_ptr->pass++;
  196518. if (png_ptr->pass >= 7)
  196519. break;
  196520. png_ptr->iwidth = (png_ptr->width +
  196521. png_pass_inc[png_ptr->pass] - 1 -
  196522. png_pass_start[png_ptr->pass]) /
  196523. png_pass_inc[png_ptr->pass];
  196524. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  196525. png_ptr->iwidth) + 1;
  196526. if (!(png_ptr->transformations & PNG_INTERLACE))
  196527. {
  196528. png_ptr->num_rows = (png_ptr->height +
  196529. png_pass_yinc[png_ptr->pass] - 1 -
  196530. png_pass_ystart[png_ptr->pass]) /
  196531. png_pass_yinc[png_ptr->pass];
  196532. if (!(png_ptr->num_rows))
  196533. continue;
  196534. }
  196535. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  196536. break;
  196537. } while (png_ptr->iwidth == 0);
  196538. if (png_ptr->pass < 7)
  196539. return;
  196540. }
  196541. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  196542. {
  196543. #ifdef PNG_USE_LOCAL_ARRAYS
  196544. PNG_CONST PNG_IDAT;
  196545. #endif
  196546. char extra;
  196547. int ret;
  196548. png_ptr->zstream.next_out = (Bytef *)&extra;
  196549. png_ptr->zstream.avail_out = (uInt)1;
  196550. for(;;)
  196551. {
  196552. if (!(png_ptr->zstream.avail_in))
  196553. {
  196554. while (!png_ptr->idat_size)
  196555. {
  196556. png_byte chunk_length[4];
  196557. png_crc_finish(png_ptr, 0);
  196558. png_read_data(png_ptr, chunk_length, 4);
  196559. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  196560. png_reset_crc(png_ptr);
  196561. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  196562. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  196563. png_error(png_ptr, "Not enough image data");
  196564. }
  196565. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  196566. png_ptr->zstream.next_in = png_ptr->zbuf;
  196567. if (png_ptr->zbuf_size > png_ptr->idat_size)
  196568. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  196569. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  196570. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  196571. }
  196572. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  196573. if (ret == Z_STREAM_END)
  196574. {
  196575. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  196576. png_ptr->idat_size)
  196577. png_warning(png_ptr, "Extra compressed data");
  196578. png_ptr->mode |= PNG_AFTER_IDAT;
  196579. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196580. break;
  196581. }
  196582. if (ret != Z_OK)
  196583. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  196584. "Decompression Error");
  196585. if (!(png_ptr->zstream.avail_out))
  196586. {
  196587. png_warning(png_ptr, "Extra compressed data.");
  196588. png_ptr->mode |= PNG_AFTER_IDAT;
  196589. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196590. break;
  196591. }
  196592. }
  196593. png_ptr->zstream.avail_out = 0;
  196594. }
  196595. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  196596. png_warning(png_ptr, "Extra compression data");
  196597. inflateReset(&png_ptr->zstream);
  196598. png_ptr->mode |= PNG_AFTER_IDAT;
  196599. }
  196600. void /* PRIVATE */
  196601. png_read_start_row(png_structp png_ptr)
  196602. {
  196603. #ifdef PNG_USE_LOCAL_ARRAYS
  196604. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196605. /* start of interlace block */
  196606. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196607. /* offset to next interlace block */
  196608. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196609. /* start of interlace block in the y direction */
  196610. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196611. /* offset to next interlace block in the y direction */
  196612. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196613. #endif
  196614. int max_pixel_depth;
  196615. png_uint_32 row_bytes;
  196616. png_debug(1, "in png_read_start_row\n");
  196617. png_ptr->zstream.avail_in = 0;
  196618. png_init_read_transformations(png_ptr);
  196619. if (png_ptr->interlaced)
  196620. {
  196621. if (!(png_ptr->transformations & PNG_INTERLACE))
  196622. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  196623. png_pass_ystart[0]) / png_pass_yinc[0];
  196624. else
  196625. png_ptr->num_rows = png_ptr->height;
  196626. png_ptr->iwidth = (png_ptr->width +
  196627. png_pass_inc[png_ptr->pass] - 1 -
  196628. png_pass_start[png_ptr->pass]) /
  196629. png_pass_inc[png_ptr->pass];
  196630. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  196631. png_ptr->irowbytes = (png_size_t)row_bytes;
  196632. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  196633. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  196634. }
  196635. else
  196636. {
  196637. png_ptr->num_rows = png_ptr->height;
  196638. png_ptr->iwidth = png_ptr->width;
  196639. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  196640. }
  196641. max_pixel_depth = png_ptr->pixel_depth;
  196642. #if defined(PNG_READ_PACK_SUPPORTED)
  196643. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  196644. max_pixel_depth = 8;
  196645. #endif
  196646. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196647. if (png_ptr->transformations & PNG_EXPAND)
  196648. {
  196649. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196650. {
  196651. if (png_ptr->num_trans)
  196652. max_pixel_depth = 32;
  196653. else
  196654. max_pixel_depth = 24;
  196655. }
  196656. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196657. {
  196658. if (max_pixel_depth < 8)
  196659. max_pixel_depth = 8;
  196660. if (png_ptr->num_trans)
  196661. max_pixel_depth *= 2;
  196662. }
  196663. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196664. {
  196665. if (png_ptr->num_trans)
  196666. {
  196667. max_pixel_depth *= 4;
  196668. max_pixel_depth /= 3;
  196669. }
  196670. }
  196671. }
  196672. #endif
  196673. #if defined(PNG_READ_FILLER_SUPPORTED)
  196674. if (png_ptr->transformations & (PNG_FILLER))
  196675. {
  196676. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196677. max_pixel_depth = 32;
  196678. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196679. {
  196680. if (max_pixel_depth <= 8)
  196681. max_pixel_depth = 16;
  196682. else
  196683. max_pixel_depth = 32;
  196684. }
  196685. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196686. {
  196687. if (max_pixel_depth <= 32)
  196688. max_pixel_depth = 32;
  196689. else
  196690. max_pixel_depth = 64;
  196691. }
  196692. }
  196693. #endif
  196694. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  196695. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  196696. {
  196697. if (
  196698. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196699. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  196700. #endif
  196701. #if defined(PNG_READ_FILLER_SUPPORTED)
  196702. (png_ptr->transformations & (PNG_FILLER)) ||
  196703. #endif
  196704. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  196705. {
  196706. if (max_pixel_depth <= 16)
  196707. max_pixel_depth = 32;
  196708. else
  196709. max_pixel_depth = 64;
  196710. }
  196711. else
  196712. {
  196713. if (max_pixel_depth <= 8)
  196714. {
  196715. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196716. max_pixel_depth = 32;
  196717. else
  196718. max_pixel_depth = 24;
  196719. }
  196720. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196721. max_pixel_depth = 64;
  196722. else
  196723. max_pixel_depth = 48;
  196724. }
  196725. }
  196726. #endif
  196727. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  196728. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  196729. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  196730. {
  196731. int user_pixel_depth=png_ptr->user_transform_depth*
  196732. png_ptr->user_transform_channels;
  196733. if(user_pixel_depth > max_pixel_depth)
  196734. max_pixel_depth=user_pixel_depth;
  196735. }
  196736. #endif
  196737. /* align the width on the next larger 8 pixels. Mainly used
  196738. for interlacing */
  196739. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  196740. /* calculate the maximum bytes needed, adding a byte and a pixel
  196741. for safety's sake */
  196742. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  196743. 1 + ((max_pixel_depth + 7) >> 3);
  196744. #ifdef PNG_MAX_MALLOC_64K
  196745. if (row_bytes > (png_uint_32)65536L)
  196746. png_error(png_ptr, "This image requires a row greater than 64KB");
  196747. #endif
  196748. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  196749. png_ptr->row_buf = png_ptr->big_row_buf+32;
  196750. #ifdef PNG_MAX_MALLOC_64K
  196751. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  196752. png_error(png_ptr, "This image requires a row greater than 64KB");
  196753. #endif
  196754. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  196755. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  196756. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  196757. png_ptr->rowbytes + 1));
  196758. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  196759. png_debug1(3, "width = %lu,\n", png_ptr->width);
  196760. png_debug1(3, "height = %lu,\n", png_ptr->height);
  196761. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  196762. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  196763. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  196764. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  196765. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  196766. }
  196767. #endif /* PNG_READ_SUPPORTED */
  196768. /*** End of inlined file: pngrutil.c ***/
  196769. /*** Start of inlined file: pngset.c ***/
  196770. /* pngset.c - storage of image information into info struct
  196771. *
  196772. * Last changed in libpng 1.2.21 [October 4, 2007]
  196773. * For conditions of distribution and use, see copyright notice in png.h
  196774. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  196775. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  196776. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  196777. *
  196778. * The functions here are used during reads to store data from the file
  196779. * into the info struct, and during writes to store application data
  196780. * into the info struct for writing into the file. This abstracts the
  196781. * info struct and allows us to change the structure in the future.
  196782. */
  196783. #define PNG_INTERNAL
  196784. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  196785. #if defined(PNG_bKGD_SUPPORTED)
  196786. void PNGAPI
  196787. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  196788. {
  196789. png_debug1(1, "in %s storage function\n", "bKGD");
  196790. if (png_ptr == NULL || info_ptr == NULL)
  196791. return;
  196792. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  196793. info_ptr->valid |= PNG_INFO_bKGD;
  196794. }
  196795. #endif
  196796. #if defined(PNG_cHRM_SUPPORTED)
  196797. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196798. void PNGAPI
  196799. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  196800. double white_x, double white_y, double red_x, double red_y,
  196801. double green_x, double green_y, double blue_x, double blue_y)
  196802. {
  196803. png_debug1(1, "in %s storage function\n", "cHRM");
  196804. if (png_ptr == NULL || info_ptr == NULL)
  196805. return;
  196806. if (white_x < 0.0 || white_y < 0.0 ||
  196807. red_x < 0.0 || red_y < 0.0 ||
  196808. green_x < 0.0 || green_y < 0.0 ||
  196809. blue_x < 0.0 || blue_y < 0.0)
  196810. {
  196811. png_warning(png_ptr,
  196812. "Ignoring attempt to set negative chromaticity value");
  196813. return;
  196814. }
  196815. if (white_x > 21474.83 || white_y > 21474.83 ||
  196816. red_x > 21474.83 || red_y > 21474.83 ||
  196817. green_x > 21474.83 || green_y > 21474.83 ||
  196818. blue_x > 21474.83 || blue_y > 21474.83)
  196819. {
  196820. png_warning(png_ptr,
  196821. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  196822. return;
  196823. }
  196824. info_ptr->x_white = (float)white_x;
  196825. info_ptr->y_white = (float)white_y;
  196826. info_ptr->x_red = (float)red_x;
  196827. info_ptr->y_red = (float)red_y;
  196828. info_ptr->x_green = (float)green_x;
  196829. info_ptr->y_green = (float)green_y;
  196830. info_ptr->x_blue = (float)blue_x;
  196831. info_ptr->y_blue = (float)blue_y;
  196832. #ifdef PNG_FIXED_POINT_SUPPORTED
  196833. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  196834. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  196835. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  196836. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  196837. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  196838. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  196839. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  196840. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  196841. #endif
  196842. info_ptr->valid |= PNG_INFO_cHRM;
  196843. }
  196844. #endif
  196845. #ifdef PNG_FIXED_POINT_SUPPORTED
  196846. void PNGAPI
  196847. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  196848. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  196849. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  196850. png_fixed_point blue_x, png_fixed_point blue_y)
  196851. {
  196852. png_debug1(1, "in %s storage function\n", "cHRM");
  196853. if (png_ptr == NULL || info_ptr == NULL)
  196854. return;
  196855. if (white_x < 0 || white_y < 0 ||
  196856. red_x < 0 || red_y < 0 ||
  196857. green_x < 0 || green_y < 0 ||
  196858. blue_x < 0 || blue_y < 0)
  196859. {
  196860. png_warning(png_ptr,
  196861. "Ignoring attempt to set negative chromaticity value");
  196862. return;
  196863. }
  196864. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196865. if (white_x > (double) PNG_UINT_31_MAX ||
  196866. white_y > (double) PNG_UINT_31_MAX ||
  196867. red_x > (double) PNG_UINT_31_MAX ||
  196868. red_y > (double) PNG_UINT_31_MAX ||
  196869. green_x > (double) PNG_UINT_31_MAX ||
  196870. green_y > (double) PNG_UINT_31_MAX ||
  196871. blue_x > (double) PNG_UINT_31_MAX ||
  196872. blue_y > (double) PNG_UINT_31_MAX)
  196873. #else
  196874. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196875. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196876. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196877. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196878. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196879. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196880. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  196881. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  196882. #endif
  196883. {
  196884. png_warning(png_ptr,
  196885. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  196886. return;
  196887. }
  196888. info_ptr->int_x_white = white_x;
  196889. info_ptr->int_y_white = white_y;
  196890. info_ptr->int_x_red = red_x;
  196891. info_ptr->int_y_red = red_y;
  196892. info_ptr->int_x_green = green_x;
  196893. info_ptr->int_y_green = green_y;
  196894. info_ptr->int_x_blue = blue_x;
  196895. info_ptr->int_y_blue = blue_y;
  196896. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196897. info_ptr->x_white = (float)(white_x/100000.);
  196898. info_ptr->y_white = (float)(white_y/100000.);
  196899. info_ptr->x_red = (float)( red_x/100000.);
  196900. info_ptr->y_red = (float)( red_y/100000.);
  196901. info_ptr->x_green = (float)(green_x/100000.);
  196902. info_ptr->y_green = (float)(green_y/100000.);
  196903. info_ptr->x_blue = (float)( blue_x/100000.);
  196904. info_ptr->y_blue = (float)( blue_y/100000.);
  196905. #endif
  196906. info_ptr->valid |= PNG_INFO_cHRM;
  196907. }
  196908. #endif
  196909. #endif
  196910. #if defined(PNG_gAMA_SUPPORTED)
  196911. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196912. void PNGAPI
  196913. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  196914. {
  196915. double gamma;
  196916. png_debug1(1, "in %s storage function\n", "gAMA");
  196917. if (png_ptr == NULL || info_ptr == NULL)
  196918. return;
  196919. /* Check for overflow */
  196920. if (file_gamma > 21474.83)
  196921. {
  196922. png_warning(png_ptr, "Limiting gamma to 21474.83");
  196923. gamma=21474.83;
  196924. }
  196925. else
  196926. gamma=file_gamma;
  196927. info_ptr->gamma = (float)gamma;
  196928. #ifdef PNG_FIXED_POINT_SUPPORTED
  196929. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  196930. #endif
  196931. info_ptr->valid |= PNG_INFO_gAMA;
  196932. if(gamma == 0.0)
  196933. png_warning(png_ptr, "Setting gamma=0");
  196934. }
  196935. #endif
  196936. void PNGAPI
  196937. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  196938. int_gamma)
  196939. {
  196940. png_fixed_point gamma;
  196941. png_debug1(1, "in %s storage function\n", "gAMA");
  196942. if (png_ptr == NULL || info_ptr == NULL)
  196943. return;
  196944. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  196945. {
  196946. png_warning(png_ptr, "Limiting gamma to 21474.83");
  196947. gamma=PNG_UINT_31_MAX;
  196948. }
  196949. else
  196950. {
  196951. if (int_gamma < 0)
  196952. {
  196953. png_warning(png_ptr, "Setting negative gamma to zero");
  196954. gamma=0;
  196955. }
  196956. else
  196957. gamma=int_gamma;
  196958. }
  196959. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196960. info_ptr->gamma = (float)(gamma/100000.);
  196961. #endif
  196962. #ifdef PNG_FIXED_POINT_SUPPORTED
  196963. info_ptr->int_gamma = gamma;
  196964. #endif
  196965. info_ptr->valid |= PNG_INFO_gAMA;
  196966. if(gamma == 0)
  196967. png_warning(png_ptr, "Setting gamma=0");
  196968. }
  196969. #endif
  196970. #if defined(PNG_hIST_SUPPORTED)
  196971. void PNGAPI
  196972. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  196973. {
  196974. int i;
  196975. png_debug1(1, "in %s storage function\n", "hIST");
  196976. if (png_ptr == NULL || info_ptr == NULL)
  196977. return;
  196978. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  196979. > PNG_MAX_PALETTE_LENGTH)
  196980. {
  196981. png_warning(png_ptr,
  196982. "Invalid palette size, hIST allocation skipped.");
  196983. return;
  196984. }
  196985. #ifdef PNG_FREE_ME_SUPPORTED
  196986. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  196987. #endif
  196988. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  196989. 1.2.1 */
  196990. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  196991. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  196992. if (png_ptr->hist == NULL)
  196993. {
  196994. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  196995. return;
  196996. }
  196997. for (i = 0; i < info_ptr->num_palette; i++)
  196998. png_ptr->hist[i] = hist[i];
  196999. info_ptr->hist = png_ptr->hist;
  197000. info_ptr->valid |= PNG_INFO_hIST;
  197001. #ifdef PNG_FREE_ME_SUPPORTED
  197002. info_ptr->free_me |= PNG_FREE_HIST;
  197003. #else
  197004. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  197005. #endif
  197006. }
  197007. #endif
  197008. void PNGAPI
  197009. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  197010. png_uint_32 width, png_uint_32 height, int bit_depth,
  197011. int color_type, int interlace_type, int compression_type,
  197012. int filter_type)
  197013. {
  197014. png_debug1(1, "in %s storage function\n", "IHDR");
  197015. if (png_ptr == NULL || info_ptr == NULL)
  197016. return;
  197017. /* check for width and height valid values */
  197018. if (width == 0 || height == 0)
  197019. png_error(png_ptr, "Image width or height is zero in IHDR");
  197020. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  197021. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  197022. png_error(png_ptr, "image size exceeds user limits in IHDR");
  197023. #else
  197024. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  197025. png_error(png_ptr, "image size exceeds user limits in IHDR");
  197026. #endif
  197027. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  197028. png_error(png_ptr, "Invalid image size in IHDR");
  197029. if ( width > (PNG_UINT_32_MAX
  197030. >> 3) /* 8-byte RGBA pixels */
  197031. - 64 /* bigrowbuf hack */
  197032. - 1 /* filter byte */
  197033. - 7*8 /* rounding of width to multiple of 8 pixels */
  197034. - 8) /* extra max_pixel_depth pad */
  197035. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  197036. /* check other values */
  197037. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  197038. bit_depth != 8 && bit_depth != 16)
  197039. png_error(png_ptr, "Invalid bit depth in IHDR");
  197040. if (color_type < 0 || color_type == 1 ||
  197041. color_type == 5 || color_type > 6)
  197042. png_error(png_ptr, "Invalid color type in IHDR");
  197043. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  197044. ((color_type == PNG_COLOR_TYPE_RGB ||
  197045. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  197046. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  197047. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  197048. if (interlace_type >= PNG_INTERLACE_LAST)
  197049. png_error(png_ptr, "Unknown interlace method in IHDR");
  197050. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  197051. png_error(png_ptr, "Unknown compression method in IHDR");
  197052. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197053. /* Accept filter_method 64 (intrapixel differencing) only if
  197054. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  197055. * 2. Libpng did not read a PNG signature (this filter_method is only
  197056. * used in PNG datastreams that are embedded in MNG datastreams) and
  197057. * 3. The application called png_permit_mng_features with a mask that
  197058. * included PNG_FLAG_MNG_FILTER_64 and
  197059. * 4. The filter_method is 64 and
  197060. * 5. The color_type is RGB or RGBA
  197061. */
  197062. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  197063. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  197064. if(filter_type != PNG_FILTER_TYPE_BASE)
  197065. {
  197066. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  197067. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  197068. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  197069. (color_type == PNG_COLOR_TYPE_RGB ||
  197070. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  197071. png_error(png_ptr, "Unknown filter method in IHDR");
  197072. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  197073. png_warning(png_ptr, "Invalid filter method in IHDR");
  197074. }
  197075. #else
  197076. if(filter_type != PNG_FILTER_TYPE_BASE)
  197077. png_error(png_ptr, "Unknown filter method in IHDR");
  197078. #endif
  197079. info_ptr->width = width;
  197080. info_ptr->height = height;
  197081. info_ptr->bit_depth = (png_byte)bit_depth;
  197082. info_ptr->color_type =(png_byte) color_type;
  197083. info_ptr->compression_type = (png_byte)compression_type;
  197084. info_ptr->filter_type = (png_byte)filter_type;
  197085. info_ptr->interlace_type = (png_byte)interlace_type;
  197086. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197087. info_ptr->channels = 1;
  197088. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  197089. info_ptr->channels = 3;
  197090. else
  197091. info_ptr->channels = 1;
  197092. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  197093. info_ptr->channels++;
  197094. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  197095. /* check for potential overflow */
  197096. if (width > (PNG_UINT_32_MAX
  197097. >> 3) /* 8-byte RGBA pixels */
  197098. - 64 /* bigrowbuf hack */
  197099. - 1 /* filter byte */
  197100. - 7*8 /* rounding of width to multiple of 8 pixels */
  197101. - 8) /* extra max_pixel_depth pad */
  197102. info_ptr->rowbytes = (png_size_t)0;
  197103. else
  197104. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  197105. }
  197106. #if defined(PNG_oFFs_SUPPORTED)
  197107. void PNGAPI
  197108. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  197109. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  197110. {
  197111. png_debug1(1, "in %s storage function\n", "oFFs");
  197112. if (png_ptr == NULL || info_ptr == NULL)
  197113. return;
  197114. info_ptr->x_offset = offset_x;
  197115. info_ptr->y_offset = offset_y;
  197116. info_ptr->offset_unit_type = (png_byte)unit_type;
  197117. info_ptr->valid |= PNG_INFO_oFFs;
  197118. }
  197119. #endif
  197120. #if defined(PNG_pCAL_SUPPORTED)
  197121. void PNGAPI
  197122. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  197123. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  197124. png_charp units, png_charpp params)
  197125. {
  197126. png_uint_32 length;
  197127. int i;
  197128. png_debug1(1, "in %s storage function\n", "pCAL");
  197129. if (png_ptr == NULL || info_ptr == NULL)
  197130. return;
  197131. length = png_strlen(purpose) + 1;
  197132. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  197133. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  197134. if (info_ptr->pcal_purpose == NULL)
  197135. {
  197136. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  197137. return;
  197138. }
  197139. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  197140. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  197141. info_ptr->pcal_X0 = X0;
  197142. info_ptr->pcal_X1 = X1;
  197143. info_ptr->pcal_type = (png_byte)type;
  197144. info_ptr->pcal_nparams = (png_byte)nparams;
  197145. length = png_strlen(units) + 1;
  197146. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  197147. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  197148. if (info_ptr->pcal_units == NULL)
  197149. {
  197150. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  197151. return;
  197152. }
  197153. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  197154. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  197155. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  197156. if (info_ptr->pcal_params == NULL)
  197157. {
  197158. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  197159. return;
  197160. }
  197161. info_ptr->pcal_params[nparams] = NULL;
  197162. for (i = 0; i < nparams; i++)
  197163. {
  197164. length = png_strlen(params[i]) + 1;
  197165. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  197166. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  197167. if (info_ptr->pcal_params[i] == NULL)
  197168. {
  197169. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  197170. return;
  197171. }
  197172. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  197173. }
  197174. info_ptr->valid |= PNG_INFO_pCAL;
  197175. #ifdef PNG_FREE_ME_SUPPORTED
  197176. info_ptr->free_me |= PNG_FREE_PCAL;
  197177. #endif
  197178. }
  197179. #endif
  197180. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  197181. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197182. void PNGAPI
  197183. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  197184. int unit, double width, double height)
  197185. {
  197186. png_debug1(1, "in %s storage function\n", "sCAL");
  197187. if (png_ptr == NULL || info_ptr == NULL)
  197188. return;
  197189. info_ptr->scal_unit = (png_byte)unit;
  197190. info_ptr->scal_pixel_width = width;
  197191. info_ptr->scal_pixel_height = height;
  197192. info_ptr->valid |= PNG_INFO_sCAL;
  197193. }
  197194. #else
  197195. #ifdef PNG_FIXED_POINT_SUPPORTED
  197196. void PNGAPI
  197197. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  197198. int unit, png_charp swidth, png_charp sheight)
  197199. {
  197200. png_uint_32 length;
  197201. png_debug1(1, "in %s storage function\n", "sCAL");
  197202. if (png_ptr == NULL || info_ptr == NULL)
  197203. return;
  197204. info_ptr->scal_unit = (png_byte)unit;
  197205. length = png_strlen(swidth) + 1;
  197206. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  197207. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  197208. if (info_ptr->scal_s_width == NULL)
  197209. {
  197210. png_warning(png_ptr,
  197211. "Memory allocation failed while processing sCAL.");
  197212. }
  197213. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  197214. length = png_strlen(sheight) + 1;
  197215. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  197216. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  197217. if (info_ptr->scal_s_height == NULL)
  197218. {
  197219. png_free (png_ptr, info_ptr->scal_s_width);
  197220. png_warning(png_ptr,
  197221. "Memory allocation failed while processing sCAL.");
  197222. }
  197223. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  197224. info_ptr->valid |= PNG_INFO_sCAL;
  197225. #ifdef PNG_FREE_ME_SUPPORTED
  197226. info_ptr->free_me |= PNG_FREE_SCAL;
  197227. #endif
  197228. }
  197229. #endif
  197230. #endif
  197231. #endif
  197232. #if defined(PNG_pHYs_SUPPORTED)
  197233. void PNGAPI
  197234. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  197235. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  197236. {
  197237. png_debug1(1, "in %s storage function\n", "pHYs");
  197238. if (png_ptr == NULL || info_ptr == NULL)
  197239. return;
  197240. info_ptr->x_pixels_per_unit = res_x;
  197241. info_ptr->y_pixels_per_unit = res_y;
  197242. info_ptr->phys_unit_type = (png_byte)unit_type;
  197243. info_ptr->valid |= PNG_INFO_pHYs;
  197244. }
  197245. #endif
  197246. void PNGAPI
  197247. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  197248. png_colorp palette, int num_palette)
  197249. {
  197250. png_debug1(1, "in %s storage function\n", "PLTE");
  197251. if (png_ptr == NULL || info_ptr == NULL)
  197252. return;
  197253. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  197254. {
  197255. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197256. png_error(png_ptr, "Invalid palette length");
  197257. else
  197258. {
  197259. png_warning(png_ptr, "Invalid palette length");
  197260. return;
  197261. }
  197262. }
  197263. /*
  197264. * It may not actually be necessary to set png_ptr->palette here;
  197265. * we do it for backward compatibility with the way the png_handle_tRNS
  197266. * function used to do the allocation.
  197267. */
  197268. #ifdef PNG_FREE_ME_SUPPORTED
  197269. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  197270. #endif
  197271. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  197272. of num_palette entries,
  197273. in case of an invalid PNG file that has too-large sample values. */
  197274. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  197275. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  197276. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  197277. png_sizeof(png_color));
  197278. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  197279. info_ptr->palette = png_ptr->palette;
  197280. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  197281. #ifdef PNG_FREE_ME_SUPPORTED
  197282. info_ptr->free_me |= PNG_FREE_PLTE;
  197283. #else
  197284. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  197285. #endif
  197286. info_ptr->valid |= PNG_INFO_PLTE;
  197287. }
  197288. #if defined(PNG_sBIT_SUPPORTED)
  197289. void PNGAPI
  197290. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  197291. png_color_8p sig_bit)
  197292. {
  197293. png_debug1(1, "in %s storage function\n", "sBIT");
  197294. if (png_ptr == NULL || info_ptr == NULL)
  197295. return;
  197296. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  197297. info_ptr->valid |= PNG_INFO_sBIT;
  197298. }
  197299. #endif
  197300. #if defined(PNG_sRGB_SUPPORTED)
  197301. void PNGAPI
  197302. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  197303. {
  197304. png_debug1(1, "in %s storage function\n", "sRGB");
  197305. if (png_ptr == NULL || info_ptr == NULL)
  197306. return;
  197307. info_ptr->srgb_intent = (png_byte)intent;
  197308. info_ptr->valid |= PNG_INFO_sRGB;
  197309. }
  197310. void PNGAPI
  197311. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  197312. int intent)
  197313. {
  197314. #if defined(PNG_gAMA_SUPPORTED)
  197315. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197316. float file_gamma;
  197317. #endif
  197318. #ifdef PNG_FIXED_POINT_SUPPORTED
  197319. png_fixed_point int_file_gamma;
  197320. #endif
  197321. #endif
  197322. #if defined(PNG_cHRM_SUPPORTED)
  197323. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197324. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  197325. #endif
  197326. #ifdef PNG_FIXED_POINT_SUPPORTED
  197327. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  197328. int_green_y, int_blue_x, int_blue_y;
  197329. #endif
  197330. #endif
  197331. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  197332. if (png_ptr == NULL || info_ptr == NULL)
  197333. return;
  197334. png_set_sRGB(png_ptr, info_ptr, intent);
  197335. #if defined(PNG_gAMA_SUPPORTED)
  197336. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197337. file_gamma = (float).45455;
  197338. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  197339. #endif
  197340. #ifdef PNG_FIXED_POINT_SUPPORTED
  197341. int_file_gamma = 45455L;
  197342. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  197343. #endif
  197344. #endif
  197345. #if defined(PNG_cHRM_SUPPORTED)
  197346. #ifdef PNG_FIXED_POINT_SUPPORTED
  197347. int_white_x = 31270L;
  197348. int_white_y = 32900L;
  197349. int_red_x = 64000L;
  197350. int_red_y = 33000L;
  197351. int_green_x = 30000L;
  197352. int_green_y = 60000L;
  197353. int_blue_x = 15000L;
  197354. int_blue_y = 6000L;
  197355. png_set_cHRM_fixed(png_ptr, info_ptr,
  197356. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  197357. int_blue_x, int_blue_y);
  197358. #endif
  197359. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197360. white_x = (float).3127;
  197361. white_y = (float).3290;
  197362. red_x = (float).64;
  197363. red_y = (float).33;
  197364. green_x = (float).30;
  197365. green_y = (float).60;
  197366. blue_x = (float).15;
  197367. blue_y = (float).06;
  197368. png_set_cHRM(png_ptr, info_ptr,
  197369. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  197370. #endif
  197371. #endif
  197372. }
  197373. #endif
  197374. #if defined(PNG_iCCP_SUPPORTED)
  197375. void PNGAPI
  197376. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  197377. png_charp name, int compression_type,
  197378. png_charp profile, png_uint_32 proflen)
  197379. {
  197380. png_charp new_iccp_name;
  197381. png_charp new_iccp_profile;
  197382. png_debug1(1, "in %s storage function\n", "iCCP");
  197383. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  197384. return;
  197385. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  197386. if (new_iccp_name == NULL)
  197387. {
  197388. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  197389. return;
  197390. }
  197391. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  197392. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  197393. if (new_iccp_profile == NULL)
  197394. {
  197395. png_free (png_ptr, new_iccp_name);
  197396. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  197397. return;
  197398. }
  197399. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  197400. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  197401. info_ptr->iccp_proflen = proflen;
  197402. info_ptr->iccp_name = new_iccp_name;
  197403. info_ptr->iccp_profile = new_iccp_profile;
  197404. /* Compression is always zero but is here so the API and info structure
  197405. * does not have to change if we introduce multiple compression types */
  197406. info_ptr->iccp_compression = (png_byte)compression_type;
  197407. #ifdef PNG_FREE_ME_SUPPORTED
  197408. info_ptr->free_me |= PNG_FREE_ICCP;
  197409. #endif
  197410. info_ptr->valid |= PNG_INFO_iCCP;
  197411. }
  197412. #endif
  197413. #if defined(PNG_TEXT_SUPPORTED)
  197414. void PNGAPI
  197415. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197416. int num_text)
  197417. {
  197418. int ret;
  197419. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  197420. if (ret)
  197421. png_error(png_ptr, "Insufficient memory to store text");
  197422. }
  197423. int /* PRIVATE */
  197424. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197425. int num_text)
  197426. {
  197427. int i;
  197428. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  197429. "text" : (png_const_charp)png_ptr->chunk_name));
  197430. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  197431. return(0);
  197432. /* Make sure we have enough space in the "text" array in info_struct
  197433. * to hold all of the incoming text_ptr objects.
  197434. */
  197435. if (info_ptr->num_text + num_text > info_ptr->max_text)
  197436. {
  197437. if (info_ptr->text != NULL)
  197438. {
  197439. png_textp old_text;
  197440. int old_max;
  197441. old_max = info_ptr->max_text;
  197442. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  197443. old_text = info_ptr->text;
  197444. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197445. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197446. if (info_ptr->text == NULL)
  197447. {
  197448. png_free(png_ptr, old_text);
  197449. return(1);
  197450. }
  197451. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  197452. png_sizeof(png_text)));
  197453. png_free(png_ptr, old_text);
  197454. }
  197455. else
  197456. {
  197457. info_ptr->max_text = num_text + 8;
  197458. info_ptr->num_text = 0;
  197459. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197460. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197461. if (info_ptr->text == NULL)
  197462. return(1);
  197463. #ifdef PNG_FREE_ME_SUPPORTED
  197464. info_ptr->free_me |= PNG_FREE_TEXT;
  197465. #endif
  197466. }
  197467. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  197468. info_ptr->max_text);
  197469. }
  197470. for (i = 0; i < num_text; i++)
  197471. {
  197472. png_size_t text_length,key_len;
  197473. png_size_t lang_len,lang_key_len;
  197474. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  197475. if (text_ptr[i].key == NULL)
  197476. continue;
  197477. key_len = png_strlen(text_ptr[i].key);
  197478. if(text_ptr[i].compression <= 0)
  197479. {
  197480. lang_len = 0;
  197481. lang_key_len = 0;
  197482. }
  197483. else
  197484. #ifdef PNG_iTXt_SUPPORTED
  197485. {
  197486. /* set iTXt data */
  197487. if (text_ptr[i].lang != NULL)
  197488. lang_len = png_strlen(text_ptr[i].lang);
  197489. else
  197490. lang_len = 0;
  197491. if (text_ptr[i].lang_key != NULL)
  197492. lang_key_len = png_strlen(text_ptr[i].lang_key);
  197493. else
  197494. lang_key_len = 0;
  197495. }
  197496. #else
  197497. {
  197498. png_warning(png_ptr, "iTXt chunk not supported.");
  197499. continue;
  197500. }
  197501. #endif
  197502. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  197503. {
  197504. text_length = 0;
  197505. #ifdef PNG_iTXt_SUPPORTED
  197506. if(text_ptr[i].compression > 0)
  197507. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  197508. else
  197509. #endif
  197510. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  197511. }
  197512. else
  197513. {
  197514. text_length = png_strlen(text_ptr[i].text);
  197515. textp->compression = text_ptr[i].compression;
  197516. }
  197517. textp->key = (png_charp)png_malloc_warn(png_ptr,
  197518. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  197519. if (textp->key == NULL)
  197520. return(1);
  197521. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  197522. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  197523. (int)textp->key);
  197524. png_memcpy(textp->key, text_ptr[i].key,
  197525. (png_size_t)(key_len));
  197526. *(textp->key+key_len) = '\0';
  197527. #ifdef PNG_iTXt_SUPPORTED
  197528. if (text_ptr[i].compression > 0)
  197529. {
  197530. textp->lang=textp->key + key_len + 1;
  197531. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  197532. *(textp->lang+lang_len) = '\0';
  197533. textp->lang_key=textp->lang + lang_len + 1;
  197534. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  197535. *(textp->lang_key+lang_key_len) = '\0';
  197536. textp->text=textp->lang_key + lang_key_len + 1;
  197537. }
  197538. else
  197539. #endif
  197540. {
  197541. #ifdef PNG_iTXt_SUPPORTED
  197542. textp->lang=NULL;
  197543. textp->lang_key=NULL;
  197544. #endif
  197545. textp->text=textp->key + key_len + 1;
  197546. }
  197547. if(text_length)
  197548. png_memcpy(textp->text, text_ptr[i].text,
  197549. (png_size_t)(text_length));
  197550. *(textp->text+text_length) = '\0';
  197551. #ifdef PNG_iTXt_SUPPORTED
  197552. if(textp->compression > 0)
  197553. {
  197554. textp->text_length = 0;
  197555. textp->itxt_length = text_length;
  197556. }
  197557. else
  197558. #endif
  197559. {
  197560. textp->text_length = text_length;
  197561. #ifdef PNG_iTXt_SUPPORTED
  197562. textp->itxt_length = 0;
  197563. #endif
  197564. }
  197565. info_ptr->num_text++;
  197566. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  197567. }
  197568. return(0);
  197569. }
  197570. #endif
  197571. #if defined(PNG_tIME_SUPPORTED)
  197572. void PNGAPI
  197573. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  197574. {
  197575. png_debug1(1, "in %s storage function\n", "tIME");
  197576. if (png_ptr == NULL || info_ptr == NULL ||
  197577. (png_ptr->mode & PNG_WROTE_tIME))
  197578. return;
  197579. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  197580. info_ptr->valid |= PNG_INFO_tIME;
  197581. }
  197582. #endif
  197583. #if defined(PNG_tRNS_SUPPORTED)
  197584. void PNGAPI
  197585. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  197586. png_bytep trans, int num_trans, png_color_16p trans_values)
  197587. {
  197588. png_debug1(1, "in %s storage function\n", "tRNS");
  197589. if (png_ptr == NULL || info_ptr == NULL)
  197590. return;
  197591. if (trans != NULL)
  197592. {
  197593. /*
  197594. * It may not actually be necessary to set png_ptr->trans here;
  197595. * we do it for backward compatibility with the way the png_handle_tRNS
  197596. * function used to do the allocation.
  197597. */
  197598. #ifdef PNG_FREE_ME_SUPPORTED
  197599. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  197600. #endif
  197601. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  197602. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  197603. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  197604. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  197605. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  197606. #ifdef PNG_FREE_ME_SUPPORTED
  197607. info_ptr->free_me |= PNG_FREE_TRNS;
  197608. #else
  197609. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  197610. #endif
  197611. }
  197612. if (trans_values != NULL)
  197613. {
  197614. png_memcpy(&(info_ptr->trans_values), trans_values,
  197615. png_sizeof(png_color_16));
  197616. if (num_trans == 0)
  197617. num_trans = 1;
  197618. }
  197619. info_ptr->num_trans = (png_uint_16)num_trans;
  197620. info_ptr->valid |= PNG_INFO_tRNS;
  197621. }
  197622. #endif
  197623. #if defined(PNG_sPLT_SUPPORTED)
  197624. void PNGAPI
  197625. png_set_sPLT(png_structp png_ptr,
  197626. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  197627. {
  197628. png_sPLT_tp np;
  197629. int i;
  197630. if (png_ptr == NULL || info_ptr == NULL)
  197631. return;
  197632. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  197633. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  197634. if (np == NULL)
  197635. {
  197636. png_warning(png_ptr, "No memory for sPLT palettes.");
  197637. return;
  197638. }
  197639. png_memcpy(np, info_ptr->splt_palettes,
  197640. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  197641. png_free(png_ptr, info_ptr->splt_palettes);
  197642. info_ptr->splt_palettes=NULL;
  197643. for (i = 0; i < nentries; i++)
  197644. {
  197645. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  197646. png_sPLT_tp from = entries + i;
  197647. to->name = (png_charp)png_malloc_warn(png_ptr,
  197648. png_strlen(from->name) + 1);
  197649. if (to->name == NULL)
  197650. {
  197651. png_warning(png_ptr,
  197652. "Out of memory while processing sPLT chunk");
  197653. }
  197654. /* TODO: use png_malloc_warn */
  197655. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  197656. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  197657. from->nentries * png_sizeof(png_sPLT_entry));
  197658. /* TODO: use png_malloc_warn */
  197659. png_memcpy(to->entries, from->entries,
  197660. from->nentries * png_sizeof(png_sPLT_entry));
  197661. if (to->entries == NULL)
  197662. {
  197663. png_warning(png_ptr,
  197664. "Out of memory while processing sPLT chunk");
  197665. png_free(png_ptr,to->name);
  197666. to->name = NULL;
  197667. }
  197668. to->nentries = from->nentries;
  197669. to->depth = from->depth;
  197670. }
  197671. info_ptr->splt_palettes = np;
  197672. info_ptr->splt_palettes_num += nentries;
  197673. info_ptr->valid |= PNG_INFO_sPLT;
  197674. #ifdef PNG_FREE_ME_SUPPORTED
  197675. info_ptr->free_me |= PNG_FREE_SPLT;
  197676. #endif
  197677. }
  197678. #endif /* PNG_sPLT_SUPPORTED */
  197679. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197680. void PNGAPI
  197681. png_set_unknown_chunks(png_structp png_ptr,
  197682. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  197683. {
  197684. png_unknown_chunkp np;
  197685. int i;
  197686. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  197687. return;
  197688. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  197689. (info_ptr->unknown_chunks_num + num_unknowns) *
  197690. png_sizeof(png_unknown_chunk));
  197691. if (np == NULL)
  197692. {
  197693. png_warning(png_ptr,
  197694. "Out of memory while processing unknown chunk.");
  197695. return;
  197696. }
  197697. png_memcpy(np, info_ptr->unknown_chunks,
  197698. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  197699. png_free(png_ptr, info_ptr->unknown_chunks);
  197700. info_ptr->unknown_chunks=NULL;
  197701. for (i = 0; i < num_unknowns; i++)
  197702. {
  197703. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  197704. png_unknown_chunkp from = unknowns + i;
  197705. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  197706. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  197707. if (to->data == NULL)
  197708. {
  197709. png_warning(png_ptr,
  197710. "Out of memory while processing unknown chunk.");
  197711. }
  197712. else
  197713. {
  197714. png_memcpy(to->data, from->data, from->size);
  197715. to->size = from->size;
  197716. /* note our location in the read or write sequence */
  197717. to->location = (png_byte)(png_ptr->mode & 0xff);
  197718. }
  197719. }
  197720. info_ptr->unknown_chunks = np;
  197721. info_ptr->unknown_chunks_num += num_unknowns;
  197722. #ifdef PNG_FREE_ME_SUPPORTED
  197723. info_ptr->free_me |= PNG_FREE_UNKN;
  197724. #endif
  197725. }
  197726. void PNGAPI
  197727. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  197728. int chunk, int location)
  197729. {
  197730. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  197731. (int)info_ptr->unknown_chunks_num)
  197732. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  197733. }
  197734. #endif
  197735. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  197736. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  197737. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  197738. void PNGAPI
  197739. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  197740. {
  197741. /* This function is deprecated in favor of png_permit_mng_features()
  197742. and will be removed from libpng-1.3.0 */
  197743. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  197744. if (png_ptr == NULL)
  197745. return;
  197746. png_ptr->mng_features_permitted = (png_byte)
  197747. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  197748. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  197749. }
  197750. #endif
  197751. #endif
  197752. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197753. png_uint_32 PNGAPI
  197754. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  197755. {
  197756. png_debug(1, "in png_permit_mng_features\n");
  197757. if (png_ptr == NULL)
  197758. return (png_uint_32)0;
  197759. png_ptr->mng_features_permitted =
  197760. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  197761. return (png_uint_32)png_ptr->mng_features_permitted;
  197762. }
  197763. #endif
  197764. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197765. void PNGAPI
  197766. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  197767. chunk_list, int num_chunks)
  197768. {
  197769. png_bytep new_list, p;
  197770. int i, old_num_chunks;
  197771. if (png_ptr == NULL)
  197772. return;
  197773. if (num_chunks == 0)
  197774. {
  197775. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  197776. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197777. else
  197778. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  197779. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  197780. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197781. else
  197782. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  197783. return;
  197784. }
  197785. if (chunk_list == NULL)
  197786. return;
  197787. old_num_chunks=png_ptr->num_chunk_list;
  197788. new_list=(png_bytep)png_malloc(png_ptr,
  197789. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  197790. if(png_ptr->chunk_list != NULL)
  197791. {
  197792. png_memcpy(new_list, png_ptr->chunk_list,
  197793. (png_size_t)(5*old_num_chunks));
  197794. png_free(png_ptr, png_ptr->chunk_list);
  197795. png_ptr->chunk_list=NULL;
  197796. }
  197797. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  197798. (png_size_t)(5*num_chunks));
  197799. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  197800. *p=(png_byte)keep;
  197801. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  197802. png_ptr->chunk_list=new_list;
  197803. #ifdef PNG_FREE_ME_SUPPORTED
  197804. png_ptr->free_me |= PNG_FREE_LIST;
  197805. #endif
  197806. }
  197807. #endif
  197808. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  197809. void PNGAPI
  197810. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  197811. png_user_chunk_ptr read_user_chunk_fn)
  197812. {
  197813. png_debug(1, "in png_set_read_user_chunk_fn\n");
  197814. if (png_ptr == NULL)
  197815. return;
  197816. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  197817. png_ptr->user_chunk_ptr = user_chunk_ptr;
  197818. }
  197819. #endif
  197820. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  197821. void PNGAPI
  197822. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  197823. {
  197824. png_debug1(1, "in %s storage function\n", "rows");
  197825. if (png_ptr == NULL || info_ptr == NULL)
  197826. return;
  197827. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  197828. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  197829. info_ptr->row_pointers = row_pointers;
  197830. if(row_pointers)
  197831. info_ptr->valid |= PNG_INFO_IDAT;
  197832. }
  197833. #endif
  197834. #ifdef PNG_WRITE_SUPPORTED
  197835. void PNGAPI
  197836. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  197837. {
  197838. if (png_ptr == NULL)
  197839. return;
  197840. if(png_ptr->zbuf)
  197841. png_free(png_ptr, png_ptr->zbuf);
  197842. png_ptr->zbuf_size = (png_size_t)size;
  197843. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  197844. png_ptr->zstream.next_out = png_ptr->zbuf;
  197845. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  197846. }
  197847. #endif
  197848. void PNGAPI
  197849. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  197850. {
  197851. if (png_ptr && info_ptr)
  197852. info_ptr->valid &= ~(mask);
  197853. }
  197854. #ifndef PNG_1_0_X
  197855. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  197856. /* function was added to libpng 1.2.0 and should always exist by default */
  197857. void PNGAPI
  197858. png_set_asm_flags (png_structp png_ptr, png_uint_32)
  197859. {
  197860. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  197861. if (png_ptr != NULL)
  197862. png_ptr->asm_flags = 0;
  197863. }
  197864. /* this function was added to libpng 1.2.0 */
  197865. void PNGAPI
  197866. png_set_mmx_thresholds (png_structp png_ptr,
  197867. png_byte,
  197868. png_uint_32)
  197869. {
  197870. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  197871. if (png_ptr == NULL)
  197872. return;
  197873. }
  197874. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  197875. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  197876. /* this function was added to libpng 1.2.6 */
  197877. void PNGAPI
  197878. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  197879. png_uint_32 user_height_max)
  197880. {
  197881. /* Images with dimensions larger than these limits will be
  197882. * rejected by png_set_IHDR(). To accept any PNG datastream
  197883. * regardless of dimensions, set both limits to 0x7ffffffL.
  197884. */
  197885. if(png_ptr == NULL) return;
  197886. png_ptr->user_width_max = user_width_max;
  197887. png_ptr->user_height_max = user_height_max;
  197888. }
  197889. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  197890. #endif /* ?PNG_1_0_X */
  197891. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  197892. /*** End of inlined file: pngset.c ***/
  197893. /*** Start of inlined file: pngtrans.c ***/
  197894. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  197895. *
  197896. * Last changed in libpng 1.2.17 May 15, 2007
  197897. * For conditions of distribution and use, see copyright notice in png.h
  197898. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  197899. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197900. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197901. */
  197902. #define PNG_INTERNAL
  197903. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  197904. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  197905. /* turn on BGR-to-RGB mapping */
  197906. void PNGAPI
  197907. png_set_bgr(png_structp png_ptr)
  197908. {
  197909. png_debug(1, "in png_set_bgr\n");
  197910. if(png_ptr == NULL) return;
  197911. png_ptr->transformations |= PNG_BGR;
  197912. }
  197913. #endif
  197914. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  197915. /* turn on 16 bit byte swapping */
  197916. void PNGAPI
  197917. png_set_swap(png_structp png_ptr)
  197918. {
  197919. png_debug(1, "in png_set_swap\n");
  197920. if(png_ptr == NULL) return;
  197921. if (png_ptr->bit_depth == 16)
  197922. png_ptr->transformations |= PNG_SWAP_BYTES;
  197923. }
  197924. #endif
  197925. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  197926. /* turn on pixel packing */
  197927. void PNGAPI
  197928. png_set_packing(png_structp png_ptr)
  197929. {
  197930. png_debug(1, "in png_set_packing\n");
  197931. if(png_ptr == NULL) return;
  197932. if (png_ptr->bit_depth < 8)
  197933. {
  197934. png_ptr->transformations |= PNG_PACK;
  197935. png_ptr->usr_bit_depth = 8;
  197936. }
  197937. }
  197938. #endif
  197939. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  197940. /* turn on packed pixel swapping */
  197941. void PNGAPI
  197942. png_set_packswap(png_structp png_ptr)
  197943. {
  197944. png_debug(1, "in png_set_packswap\n");
  197945. if(png_ptr == NULL) return;
  197946. if (png_ptr->bit_depth < 8)
  197947. png_ptr->transformations |= PNG_PACKSWAP;
  197948. }
  197949. #endif
  197950. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  197951. void PNGAPI
  197952. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  197953. {
  197954. png_debug(1, "in png_set_shift\n");
  197955. if(png_ptr == NULL) return;
  197956. png_ptr->transformations |= PNG_SHIFT;
  197957. png_ptr->shift = *true_bits;
  197958. }
  197959. #endif
  197960. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  197961. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  197962. int PNGAPI
  197963. png_set_interlace_handling(png_structp png_ptr)
  197964. {
  197965. png_debug(1, "in png_set_interlace handling\n");
  197966. if (png_ptr && png_ptr->interlaced)
  197967. {
  197968. png_ptr->transformations |= PNG_INTERLACE;
  197969. return (7);
  197970. }
  197971. return (1);
  197972. }
  197973. #endif
  197974. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  197975. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  197976. * The filler type has changed in v0.95 to allow future 2-byte fillers
  197977. * for 48-bit input data, as well as to avoid problems with some compilers
  197978. * that don't like bytes as parameters.
  197979. */
  197980. void PNGAPI
  197981. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  197982. {
  197983. png_debug(1, "in png_set_filler\n");
  197984. if(png_ptr == NULL) return;
  197985. png_ptr->transformations |= PNG_FILLER;
  197986. png_ptr->filler = (png_byte)filler;
  197987. if (filler_loc == PNG_FILLER_AFTER)
  197988. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  197989. else
  197990. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  197991. /* This should probably go in the "do_read_filler" routine.
  197992. * I attempted to do that in libpng-1.0.1a but that caused problems
  197993. * so I restored it in libpng-1.0.2a
  197994. */
  197995. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  197996. {
  197997. png_ptr->usr_channels = 4;
  197998. }
  197999. /* Also I added this in libpng-1.0.2a (what happens when we expand
  198000. * a less-than-8-bit grayscale to GA? */
  198001. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  198002. {
  198003. png_ptr->usr_channels = 2;
  198004. }
  198005. }
  198006. #if !defined(PNG_1_0_X)
  198007. /* Added to libpng-1.2.7 */
  198008. void PNGAPI
  198009. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  198010. {
  198011. png_debug(1, "in png_set_add_alpha\n");
  198012. if(png_ptr == NULL) return;
  198013. png_set_filler(png_ptr, filler, filler_loc);
  198014. png_ptr->transformations |= PNG_ADD_ALPHA;
  198015. }
  198016. #endif
  198017. #endif
  198018. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  198019. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  198020. void PNGAPI
  198021. png_set_swap_alpha(png_structp png_ptr)
  198022. {
  198023. png_debug(1, "in png_set_swap_alpha\n");
  198024. if(png_ptr == NULL) return;
  198025. png_ptr->transformations |= PNG_SWAP_ALPHA;
  198026. }
  198027. #endif
  198028. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  198029. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  198030. void PNGAPI
  198031. png_set_invert_alpha(png_structp png_ptr)
  198032. {
  198033. png_debug(1, "in png_set_invert_alpha\n");
  198034. if(png_ptr == NULL) return;
  198035. png_ptr->transformations |= PNG_INVERT_ALPHA;
  198036. }
  198037. #endif
  198038. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  198039. void PNGAPI
  198040. png_set_invert_mono(png_structp png_ptr)
  198041. {
  198042. png_debug(1, "in png_set_invert_mono\n");
  198043. if(png_ptr == NULL) return;
  198044. png_ptr->transformations |= PNG_INVERT_MONO;
  198045. }
  198046. /* invert monochrome grayscale data */
  198047. void /* PRIVATE */
  198048. png_do_invert(png_row_infop row_info, png_bytep row)
  198049. {
  198050. png_debug(1, "in png_do_invert\n");
  198051. /* This test removed from libpng version 1.0.13 and 1.2.0:
  198052. * if (row_info->bit_depth == 1 &&
  198053. */
  198054. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198055. if (row == NULL || row_info == NULL)
  198056. return;
  198057. #endif
  198058. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  198059. {
  198060. png_bytep rp = row;
  198061. png_uint_32 i;
  198062. png_uint_32 istop = row_info->rowbytes;
  198063. for (i = 0; i < istop; i++)
  198064. {
  198065. *rp = (png_byte)(~(*rp));
  198066. rp++;
  198067. }
  198068. }
  198069. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198070. row_info->bit_depth == 8)
  198071. {
  198072. png_bytep rp = row;
  198073. png_uint_32 i;
  198074. png_uint_32 istop = row_info->rowbytes;
  198075. for (i = 0; i < istop; i+=2)
  198076. {
  198077. *rp = (png_byte)(~(*rp));
  198078. rp+=2;
  198079. }
  198080. }
  198081. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198082. row_info->bit_depth == 16)
  198083. {
  198084. png_bytep rp = row;
  198085. png_uint_32 i;
  198086. png_uint_32 istop = row_info->rowbytes;
  198087. for (i = 0; i < istop; i+=4)
  198088. {
  198089. *rp = (png_byte)(~(*rp));
  198090. *(rp+1) = (png_byte)(~(*(rp+1)));
  198091. rp+=4;
  198092. }
  198093. }
  198094. }
  198095. #endif
  198096. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  198097. /* swaps byte order on 16 bit depth images */
  198098. void /* PRIVATE */
  198099. png_do_swap(png_row_infop row_info, png_bytep row)
  198100. {
  198101. png_debug(1, "in png_do_swap\n");
  198102. if (
  198103. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198104. row != NULL && row_info != NULL &&
  198105. #endif
  198106. row_info->bit_depth == 16)
  198107. {
  198108. png_bytep rp = row;
  198109. png_uint_32 i;
  198110. png_uint_32 istop= row_info->width * row_info->channels;
  198111. for (i = 0; i < istop; i++, rp += 2)
  198112. {
  198113. png_byte t = *rp;
  198114. *rp = *(rp + 1);
  198115. *(rp + 1) = t;
  198116. }
  198117. }
  198118. }
  198119. #endif
  198120. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  198121. static PNG_CONST png_byte onebppswaptable[256] = {
  198122. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  198123. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  198124. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  198125. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  198126. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  198127. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  198128. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  198129. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  198130. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  198131. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  198132. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  198133. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  198134. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  198135. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  198136. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  198137. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  198138. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  198139. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  198140. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  198141. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  198142. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  198143. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  198144. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  198145. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  198146. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  198147. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  198148. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  198149. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  198150. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  198151. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  198152. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  198153. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  198154. };
  198155. static PNG_CONST png_byte twobppswaptable[256] = {
  198156. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  198157. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  198158. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  198159. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  198160. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  198161. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  198162. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  198163. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  198164. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  198165. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  198166. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  198167. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  198168. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  198169. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  198170. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  198171. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  198172. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  198173. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  198174. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  198175. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  198176. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  198177. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  198178. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  198179. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  198180. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  198181. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  198182. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  198183. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  198184. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  198185. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  198186. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  198187. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  198188. };
  198189. static PNG_CONST png_byte fourbppswaptable[256] = {
  198190. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  198191. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  198192. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  198193. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  198194. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  198195. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  198196. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  198197. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  198198. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  198199. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  198200. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  198201. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  198202. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  198203. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  198204. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  198205. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  198206. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  198207. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  198208. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  198209. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  198210. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  198211. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  198212. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  198213. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  198214. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  198215. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  198216. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  198217. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  198218. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  198219. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  198220. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  198221. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  198222. };
  198223. /* swaps pixel packing order within bytes */
  198224. void /* PRIVATE */
  198225. png_do_packswap(png_row_infop row_info, png_bytep row)
  198226. {
  198227. png_debug(1, "in png_do_packswap\n");
  198228. if (
  198229. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198230. row != NULL && row_info != NULL &&
  198231. #endif
  198232. row_info->bit_depth < 8)
  198233. {
  198234. png_bytep rp, end, table;
  198235. end = row + row_info->rowbytes;
  198236. if (row_info->bit_depth == 1)
  198237. table = (png_bytep)onebppswaptable;
  198238. else if (row_info->bit_depth == 2)
  198239. table = (png_bytep)twobppswaptable;
  198240. else if (row_info->bit_depth == 4)
  198241. table = (png_bytep)fourbppswaptable;
  198242. else
  198243. return;
  198244. for (rp = row; rp < end; rp++)
  198245. *rp = table[*rp];
  198246. }
  198247. }
  198248. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  198249. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  198250. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  198251. /* remove filler or alpha byte(s) */
  198252. void /* PRIVATE */
  198253. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  198254. {
  198255. png_debug(1, "in png_do_strip_filler\n");
  198256. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198257. if (row != NULL && row_info != NULL)
  198258. #endif
  198259. {
  198260. png_bytep sp=row;
  198261. png_bytep dp=row;
  198262. png_uint_32 row_width=row_info->width;
  198263. png_uint_32 i;
  198264. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  198265. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  198266. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198267. row_info->channels == 4)
  198268. {
  198269. if (row_info->bit_depth == 8)
  198270. {
  198271. /* This converts from RGBX or RGBA to RGB */
  198272. if (flags & PNG_FLAG_FILLER_AFTER)
  198273. {
  198274. dp+=3; sp+=4;
  198275. for (i = 1; i < row_width; i++)
  198276. {
  198277. *dp++ = *sp++;
  198278. *dp++ = *sp++;
  198279. *dp++ = *sp++;
  198280. sp++;
  198281. }
  198282. }
  198283. /* This converts from XRGB or ARGB to RGB */
  198284. else
  198285. {
  198286. for (i = 0; i < row_width; i++)
  198287. {
  198288. sp++;
  198289. *dp++ = *sp++;
  198290. *dp++ = *sp++;
  198291. *dp++ = *sp++;
  198292. }
  198293. }
  198294. row_info->pixel_depth = 24;
  198295. row_info->rowbytes = row_width * 3;
  198296. }
  198297. else /* if (row_info->bit_depth == 16) */
  198298. {
  198299. if (flags & PNG_FLAG_FILLER_AFTER)
  198300. {
  198301. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  198302. sp += 8; dp += 6;
  198303. for (i = 1; i < row_width; i++)
  198304. {
  198305. /* This could be (although png_memcpy is probably slower):
  198306. png_memcpy(dp, sp, 6);
  198307. sp += 8;
  198308. dp += 6;
  198309. */
  198310. *dp++ = *sp++;
  198311. *dp++ = *sp++;
  198312. *dp++ = *sp++;
  198313. *dp++ = *sp++;
  198314. *dp++ = *sp++;
  198315. *dp++ = *sp++;
  198316. sp += 2;
  198317. }
  198318. }
  198319. else
  198320. {
  198321. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  198322. for (i = 0; i < row_width; i++)
  198323. {
  198324. /* This could be (although png_memcpy is probably slower):
  198325. png_memcpy(dp, sp, 6);
  198326. sp += 8;
  198327. dp += 6;
  198328. */
  198329. sp+=2;
  198330. *dp++ = *sp++;
  198331. *dp++ = *sp++;
  198332. *dp++ = *sp++;
  198333. *dp++ = *sp++;
  198334. *dp++ = *sp++;
  198335. *dp++ = *sp++;
  198336. }
  198337. }
  198338. row_info->pixel_depth = 48;
  198339. row_info->rowbytes = row_width * 6;
  198340. }
  198341. row_info->channels = 3;
  198342. }
  198343. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  198344. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198345. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198346. row_info->channels == 2)
  198347. {
  198348. if (row_info->bit_depth == 8)
  198349. {
  198350. /* This converts from GX or GA to G */
  198351. if (flags & PNG_FLAG_FILLER_AFTER)
  198352. {
  198353. for (i = 0; i < row_width; i++)
  198354. {
  198355. *dp++ = *sp++;
  198356. sp++;
  198357. }
  198358. }
  198359. /* This converts from XG or AG to G */
  198360. else
  198361. {
  198362. for (i = 0; i < row_width; i++)
  198363. {
  198364. sp++;
  198365. *dp++ = *sp++;
  198366. }
  198367. }
  198368. row_info->pixel_depth = 8;
  198369. row_info->rowbytes = row_width;
  198370. }
  198371. else /* if (row_info->bit_depth == 16) */
  198372. {
  198373. if (flags & PNG_FLAG_FILLER_AFTER)
  198374. {
  198375. /* This converts from GGXX or GGAA to GG */
  198376. sp += 4; dp += 2;
  198377. for (i = 1; i < row_width; i++)
  198378. {
  198379. *dp++ = *sp++;
  198380. *dp++ = *sp++;
  198381. sp += 2;
  198382. }
  198383. }
  198384. else
  198385. {
  198386. /* This converts from XXGG or AAGG to GG */
  198387. for (i = 0; i < row_width; i++)
  198388. {
  198389. sp += 2;
  198390. *dp++ = *sp++;
  198391. *dp++ = *sp++;
  198392. }
  198393. }
  198394. row_info->pixel_depth = 16;
  198395. row_info->rowbytes = row_width * 2;
  198396. }
  198397. row_info->channels = 1;
  198398. }
  198399. if (flags & PNG_FLAG_STRIP_ALPHA)
  198400. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  198401. }
  198402. }
  198403. #endif
  198404. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  198405. /* swaps red and blue bytes within a pixel */
  198406. void /* PRIVATE */
  198407. png_do_bgr(png_row_infop row_info, png_bytep row)
  198408. {
  198409. png_debug(1, "in png_do_bgr\n");
  198410. if (
  198411. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198412. row != NULL && row_info != NULL &&
  198413. #endif
  198414. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  198415. {
  198416. png_uint_32 row_width = row_info->width;
  198417. if (row_info->bit_depth == 8)
  198418. {
  198419. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198420. {
  198421. png_bytep rp;
  198422. png_uint_32 i;
  198423. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  198424. {
  198425. png_byte save = *rp;
  198426. *rp = *(rp + 2);
  198427. *(rp + 2) = save;
  198428. }
  198429. }
  198430. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198431. {
  198432. png_bytep rp;
  198433. png_uint_32 i;
  198434. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  198435. {
  198436. png_byte save = *rp;
  198437. *rp = *(rp + 2);
  198438. *(rp + 2) = save;
  198439. }
  198440. }
  198441. }
  198442. else if (row_info->bit_depth == 16)
  198443. {
  198444. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198445. {
  198446. png_bytep rp;
  198447. png_uint_32 i;
  198448. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  198449. {
  198450. png_byte save = *rp;
  198451. *rp = *(rp + 4);
  198452. *(rp + 4) = save;
  198453. save = *(rp + 1);
  198454. *(rp + 1) = *(rp + 5);
  198455. *(rp + 5) = save;
  198456. }
  198457. }
  198458. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198459. {
  198460. png_bytep rp;
  198461. png_uint_32 i;
  198462. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  198463. {
  198464. png_byte save = *rp;
  198465. *rp = *(rp + 4);
  198466. *(rp + 4) = save;
  198467. save = *(rp + 1);
  198468. *(rp + 1) = *(rp + 5);
  198469. *(rp + 5) = save;
  198470. }
  198471. }
  198472. }
  198473. }
  198474. }
  198475. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  198476. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  198477. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  198478. defined(PNG_LEGACY_SUPPORTED)
  198479. void PNGAPI
  198480. png_set_user_transform_info(png_structp png_ptr, png_voidp
  198481. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  198482. {
  198483. png_debug(1, "in png_set_user_transform_info\n");
  198484. if(png_ptr == NULL) return;
  198485. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198486. png_ptr->user_transform_ptr = user_transform_ptr;
  198487. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  198488. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  198489. #else
  198490. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  198491. png_warning(png_ptr,
  198492. "This version of libpng does not support user transform info");
  198493. #endif
  198494. }
  198495. #endif
  198496. /* This function returns a pointer to the user_transform_ptr associated with
  198497. * the user transform functions. The application should free any memory
  198498. * associated with this pointer before png_write_destroy and png_read_destroy
  198499. * are called.
  198500. */
  198501. png_voidp PNGAPI
  198502. png_get_user_transform_ptr(png_structp png_ptr)
  198503. {
  198504. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198505. if (png_ptr == NULL) return (NULL);
  198506. return ((png_voidp)png_ptr->user_transform_ptr);
  198507. #else
  198508. return (NULL);
  198509. #endif
  198510. }
  198511. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  198512. /*** End of inlined file: pngtrans.c ***/
  198513. /*** Start of inlined file: pngwio.c ***/
  198514. /* pngwio.c - functions for data output
  198515. *
  198516. * Last changed in libpng 1.2.13 November 13, 2006
  198517. * For conditions of distribution and use, see copyright notice in png.h
  198518. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  198519. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198520. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198521. *
  198522. * This file provides a location for all output. Users who need
  198523. * special handling are expected to write functions that have the same
  198524. * arguments as these and perform similar functions, but that possibly
  198525. * use different output methods. Note that you shouldn't change these
  198526. * functions, but rather write replacement functions and then change
  198527. * them at run time with png_set_write_fn(...).
  198528. */
  198529. #define PNG_INTERNAL
  198530. #ifdef PNG_WRITE_SUPPORTED
  198531. /* Write the data to whatever output you are using. The default routine
  198532. writes to a file pointer. Note that this routine sometimes gets called
  198533. with very small lengths, so you should implement some kind of simple
  198534. buffering if you are using unbuffered writes. This should never be asked
  198535. to write more than 64K on a 16 bit machine. */
  198536. void /* PRIVATE */
  198537. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198538. {
  198539. if (png_ptr->write_data_fn != NULL )
  198540. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  198541. else
  198542. png_error(png_ptr, "Call to NULL write function");
  198543. }
  198544. #if !defined(PNG_NO_STDIO)
  198545. /* This is the function that does the actual writing of data. If you are
  198546. not writing to a standard C stream, you should create a replacement
  198547. write_data function and use it at run time with png_set_write_fn(), rather
  198548. than changing the library. */
  198549. #ifndef USE_FAR_KEYWORD
  198550. void PNGAPI
  198551. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198552. {
  198553. png_uint_32 check;
  198554. if(png_ptr == NULL) return;
  198555. #if defined(_WIN32_WCE)
  198556. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  198557. check = 0;
  198558. #else
  198559. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  198560. #endif
  198561. if (check != length)
  198562. png_error(png_ptr, "Write Error");
  198563. }
  198564. #else
  198565. /* this is the model-independent version. Since the standard I/O library
  198566. can't handle far buffers in the medium and small models, we have to copy
  198567. the data.
  198568. */
  198569. #define NEAR_BUF_SIZE 1024
  198570. #define MIN(a,b) (a <= b ? a : b)
  198571. void PNGAPI
  198572. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198573. {
  198574. png_uint_32 check;
  198575. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  198576. png_FILE_p io_ptr;
  198577. if(png_ptr == NULL) return;
  198578. /* Check if data really is near. If so, use usual code. */
  198579. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  198580. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  198581. if ((png_bytep)near_data == data)
  198582. {
  198583. #if defined(_WIN32_WCE)
  198584. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  198585. check = 0;
  198586. #else
  198587. check = fwrite(near_data, 1, length, io_ptr);
  198588. #endif
  198589. }
  198590. else
  198591. {
  198592. png_byte buf[NEAR_BUF_SIZE];
  198593. png_size_t written, remaining, err;
  198594. check = 0;
  198595. remaining = length;
  198596. do
  198597. {
  198598. written = MIN(NEAR_BUF_SIZE, remaining);
  198599. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  198600. #if defined(_WIN32_WCE)
  198601. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  198602. err = 0;
  198603. #else
  198604. err = fwrite(buf, 1, written, io_ptr);
  198605. #endif
  198606. if (err != written)
  198607. break;
  198608. else
  198609. check += err;
  198610. data += written;
  198611. remaining -= written;
  198612. }
  198613. while (remaining != 0);
  198614. }
  198615. if (check != length)
  198616. png_error(png_ptr, "Write Error");
  198617. }
  198618. #endif
  198619. #endif
  198620. /* This function is called to output any data pending writing (normally
  198621. to disk). After png_flush is called, there should be no data pending
  198622. writing in any buffers. */
  198623. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198624. void /* PRIVATE */
  198625. png_flush(png_structp png_ptr)
  198626. {
  198627. if (png_ptr->output_flush_fn != NULL)
  198628. (*(png_ptr->output_flush_fn))(png_ptr);
  198629. }
  198630. #if !defined(PNG_NO_STDIO)
  198631. void PNGAPI
  198632. png_default_flush(png_structp png_ptr)
  198633. {
  198634. #if !defined(_WIN32_WCE)
  198635. png_FILE_p io_ptr;
  198636. #endif
  198637. if(png_ptr == NULL) return;
  198638. #if !defined(_WIN32_WCE)
  198639. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  198640. if (io_ptr != NULL)
  198641. fflush(io_ptr);
  198642. #endif
  198643. }
  198644. #endif
  198645. #endif
  198646. /* This function allows the application to supply new output functions for
  198647. libpng if standard C streams aren't being used.
  198648. This function takes as its arguments:
  198649. png_ptr - pointer to a png output data structure
  198650. io_ptr - pointer to user supplied structure containing info about
  198651. the output functions. May be NULL.
  198652. write_data_fn - pointer to a new output function that takes as its
  198653. arguments a pointer to a png_struct, a pointer to
  198654. data to be written, and a 32-bit unsigned int that is
  198655. the number of bytes to be written. The new write
  198656. function should call png_error(png_ptr, "Error msg")
  198657. to exit and output any fatal error messages.
  198658. flush_data_fn - pointer to a new flush function that takes as its
  198659. arguments a pointer to a png_struct. After a call to
  198660. the flush function, there should be no data in any buffers
  198661. or pending transmission. If the output method doesn't do
  198662. any buffering of ouput, a function prototype must still be
  198663. supplied although it doesn't have to do anything. If
  198664. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  198665. time, output_flush_fn will be ignored, although it must be
  198666. supplied for compatibility. */
  198667. void PNGAPI
  198668. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  198669. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  198670. {
  198671. if(png_ptr == NULL) return;
  198672. png_ptr->io_ptr = io_ptr;
  198673. #if !defined(PNG_NO_STDIO)
  198674. if (write_data_fn != NULL)
  198675. png_ptr->write_data_fn = write_data_fn;
  198676. else
  198677. png_ptr->write_data_fn = png_default_write_data;
  198678. #else
  198679. png_ptr->write_data_fn = write_data_fn;
  198680. #endif
  198681. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198682. #if !defined(PNG_NO_STDIO)
  198683. if (output_flush_fn != NULL)
  198684. png_ptr->output_flush_fn = output_flush_fn;
  198685. else
  198686. png_ptr->output_flush_fn = png_default_flush;
  198687. #else
  198688. png_ptr->output_flush_fn = output_flush_fn;
  198689. #endif
  198690. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  198691. /* It is an error to read while writing a png file */
  198692. if (png_ptr->read_data_fn != NULL)
  198693. {
  198694. png_ptr->read_data_fn = NULL;
  198695. png_warning(png_ptr,
  198696. "Attempted to set both read_data_fn and write_data_fn in");
  198697. png_warning(png_ptr,
  198698. "the same structure. Resetting read_data_fn to NULL.");
  198699. }
  198700. }
  198701. #if defined(USE_FAR_KEYWORD)
  198702. #if defined(_MSC_VER)
  198703. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198704. {
  198705. void *near_ptr;
  198706. void FAR *far_ptr;
  198707. FP_OFF(near_ptr) = FP_OFF(ptr);
  198708. far_ptr = (void FAR *)near_ptr;
  198709. if(check != 0)
  198710. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  198711. png_error(png_ptr,"segment lost in conversion");
  198712. return(near_ptr);
  198713. }
  198714. # else
  198715. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198716. {
  198717. void *near_ptr;
  198718. void FAR *far_ptr;
  198719. near_ptr = (void FAR *)ptr;
  198720. far_ptr = (void FAR *)near_ptr;
  198721. if(check != 0)
  198722. if(far_ptr != ptr)
  198723. png_error(png_ptr,"segment lost in conversion");
  198724. return(near_ptr);
  198725. }
  198726. # endif
  198727. # endif
  198728. #endif /* PNG_WRITE_SUPPORTED */
  198729. /*** End of inlined file: pngwio.c ***/
  198730. /*** Start of inlined file: pngwrite.c ***/
  198731. /* pngwrite.c - general routines to write a PNG file
  198732. *
  198733. * Last changed in libpng 1.2.15 January 5, 2007
  198734. * For conditions of distribution and use, see copyright notice in png.h
  198735. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  198736. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198737. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198738. */
  198739. /* get internal access to png.h */
  198740. #define PNG_INTERNAL
  198741. #ifdef PNG_WRITE_SUPPORTED
  198742. /* Writes all the PNG information. This is the suggested way to use the
  198743. * library. If you have a new chunk to add, make a function to write it,
  198744. * and put it in the correct location here. If you want the chunk written
  198745. * after the image data, put it in png_write_end(). I strongly encourage
  198746. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  198747. * the chunk, as that will keep the code from breaking if you want to just
  198748. * write a plain PNG file. If you have long comments, I suggest writing
  198749. * them in png_write_end(), and compressing them.
  198750. */
  198751. void PNGAPI
  198752. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  198753. {
  198754. png_debug(1, "in png_write_info_before_PLTE\n");
  198755. if (png_ptr == NULL || info_ptr == NULL)
  198756. return;
  198757. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  198758. {
  198759. png_write_sig(png_ptr); /* write PNG signature */
  198760. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198761. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  198762. {
  198763. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  198764. png_ptr->mng_features_permitted=0;
  198765. }
  198766. #endif
  198767. /* write IHDR information. */
  198768. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  198769. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  198770. info_ptr->filter_type,
  198771. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198772. info_ptr->interlace_type);
  198773. #else
  198774. 0);
  198775. #endif
  198776. /* the rest of these check to see if the valid field has the appropriate
  198777. flag set, and if it does, writes the chunk. */
  198778. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  198779. if (info_ptr->valid & PNG_INFO_gAMA)
  198780. {
  198781. # ifdef PNG_FLOATING_POINT_SUPPORTED
  198782. png_write_gAMA(png_ptr, info_ptr->gamma);
  198783. #else
  198784. #ifdef PNG_FIXED_POINT_SUPPORTED
  198785. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  198786. # endif
  198787. #endif
  198788. }
  198789. #endif
  198790. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  198791. if (info_ptr->valid & PNG_INFO_sRGB)
  198792. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  198793. #endif
  198794. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  198795. if (info_ptr->valid & PNG_INFO_iCCP)
  198796. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  198797. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  198798. #endif
  198799. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  198800. if (info_ptr->valid & PNG_INFO_sBIT)
  198801. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  198802. #endif
  198803. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  198804. if (info_ptr->valid & PNG_INFO_cHRM)
  198805. {
  198806. #ifdef PNG_FLOATING_POINT_SUPPORTED
  198807. png_write_cHRM(png_ptr,
  198808. info_ptr->x_white, info_ptr->y_white,
  198809. info_ptr->x_red, info_ptr->y_red,
  198810. info_ptr->x_green, info_ptr->y_green,
  198811. info_ptr->x_blue, info_ptr->y_blue);
  198812. #else
  198813. # ifdef PNG_FIXED_POINT_SUPPORTED
  198814. png_write_cHRM_fixed(png_ptr,
  198815. info_ptr->int_x_white, info_ptr->int_y_white,
  198816. info_ptr->int_x_red, info_ptr->int_y_red,
  198817. info_ptr->int_x_green, info_ptr->int_y_green,
  198818. info_ptr->int_x_blue, info_ptr->int_y_blue);
  198819. # endif
  198820. #endif
  198821. }
  198822. #endif
  198823. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198824. if (info_ptr->unknown_chunks_num)
  198825. {
  198826. png_unknown_chunk *up;
  198827. png_debug(5, "writing extra chunks\n");
  198828. for (up = info_ptr->unknown_chunks;
  198829. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198830. up++)
  198831. {
  198832. int keep=png_handle_as_unknown(png_ptr, up->name);
  198833. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198834. up->location && !(up->location & PNG_HAVE_PLTE) &&
  198835. !(up->location & PNG_HAVE_IDAT) &&
  198836. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198837. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198838. {
  198839. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198840. }
  198841. }
  198842. }
  198843. #endif
  198844. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  198845. }
  198846. }
  198847. void PNGAPI
  198848. png_write_info(png_structp png_ptr, png_infop info_ptr)
  198849. {
  198850. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  198851. int i;
  198852. #endif
  198853. png_debug(1, "in png_write_info\n");
  198854. if (png_ptr == NULL || info_ptr == NULL)
  198855. return;
  198856. png_write_info_before_PLTE(png_ptr, info_ptr);
  198857. if (info_ptr->valid & PNG_INFO_PLTE)
  198858. png_write_PLTE(png_ptr, info_ptr->palette,
  198859. (png_uint_32)info_ptr->num_palette);
  198860. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198861. png_error(png_ptr, "Valid palette required for paletted images");
  198862. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  198863. if (info_ptr->valid & PNG_INFO_tRNS)
  198864. {
  198865. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  198866. /* invert the alpha channel (in tRNS) */
  198867. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  198868. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198869. {
  198870. int j;
  198871. for (j=0; j<(int)info_ptr->num_trans; j++)
  198872. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  198873. }
  198874. #endif
  198875. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  198876. info_ptr->num_trans, info_ptr->color_type);
  198877. }
  198878. #endif
  198879. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  198880. if (info_ptr->valid & PNG_INFO_bKGD)
  198881. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  198882. #endif
  198883. #if defined(PNG_WRITE_hIST_SUPPORTED)
  198884. if (info_ptr->valid & PNG_INFO_hIST)
  198885. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  198886. #endif
  198887. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  198888. if (info_ptr->valid & PNG_INFO_oFFs)
  198889. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  198890. info_ptr->offset_unit_type);
  198891. #endif
  198892. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  198893. if (info_ptr->valid & PNG_INFO_pCAL)
  198894. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  198895. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  198896. info_ptr->pcal_units, info_ptr->pcal_params);
  198897. #endif
  198898. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  198899. if (info_ptr->valid & PNG_INFO_sCAL)
  198900. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  198901. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  198902. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  198903. #else
  198904. #ifdef PNG_FIXED_POINT_SUPPORTED
  198905. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  198906. info_ptr->scal_s_width, info_ptr->scal_s_height);
  198907. #else
  198908. png_warning(png_ptr,
  198909. "png_write_sCAL not supported; sCAL chunk not written.");
  198910. #endif
  198911. #endif
  198912. #endif
  198913. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  198914. if (info_ptr->valid & PNG_INFO_pHYs)
  198915. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  198916. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  198917. #endif
  198918. #if defined(PNG_WRITE_tIME_SUPPORTED)
  198919. if (info_ptr->valid & PNG_INFO_tIME)
  198920. {
  198921. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  198922. png_ptr->mode |= PNG_WROTE_tIME;
  198923. }
  198924. #endif
  198925. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  198926. if (info_ptr->valid & PNG_INFO_sPLT)
  198927. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  198928. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  198929. #endif
  198930. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  198931. /* Check to see if we need to write text chunks */
  198932. for (i = 0; i < info_ptr->num_text; i++)
  198933. {
  198934. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  198935. info_ptr->text[i].compression);
  198936. /* an internationalized chunk? */
  198937. if (info_ptr->text[i].compression > 0)
  198938. {
  198939. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  198940. /* write international chunk */
  198941. png_write_iTXt(png_ptr,
  198942. info_ptr->text[i].compression,
  198943. info_ptr->text[i].key,
  198944. info_ptr->text[i].lang,
  198945. info_ptr->text[i].lang_key,
  198946. info_ptr->text[i].text);
  198947. #else
  198948. png_warning(png_ptr, "Unable to write international text");
  198949. #endif
  198950. /* Mark this chunk as written */
  198951. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198952. }
  198953. /* If we want a compressed text chunk */
  198954. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  198955. {
  198956. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  198957. /* write compressed chunk */
  198958. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  198959. info_ptr->text[i].text, 0,
  198960. info_ptr->text[i].compression);
  198961. #else
  198962. png_warning(png_ptr, "Unable to write compressed text");
  198963. #endif
  198964. /* Mark this chunk as written */
  198965. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  198966. }
  198967. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  198968. {
  198969. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  198970. /* write uncompressed chunk */
  198971. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  198972. info_ptr->text[i].text,
  198973. 0);
  198974. #else
  198975. png_warning(png_ptr, "Unable to write uncompressed text");
  198976. #endif
  198977. /* Mark this chunk as written */
  198978. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  198979. }
  198980. }
  198981. #endif
  198982. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  198983. if (info_ptr->unknown_chunks_num)
  198984. {
  198985. png_unknown_chunk *up;
  198986. png_debug(5, "writing extra chunks\n");
  198987. for (up = info_ptr->unknown_chunks;
  198988. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  198989. up++)
  198990. {
  198991. int keep=png_handle_as_unknown(png_ptr, up->name);
  198992. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  198993. up->location && (up->location & PNG_HAVE_PLTE) &&
  198994. !(up->location & PNG_HAVE_IDAT) &&
  198995. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  198996. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  198997. {
  198998. png_write_chunk(png_ptr, up->name, up->data, up->size);
  198999. }
  199000. }
  199001. }
  199002. #endif
  199003. }
  199004. /* Writes the end of the PNG file. If you don't want to write comments or
  199005. * time information, you can pass NULL for info. If you already wrote these
  199006. * in png_write_info(), do not write them again here. If you have long
  199007. * comments, I suggest writing them here, and compressing them.
  199008. */
  199009. void PNGAPI
  199010. png_write_end(png_structp png_ptr, png_infop info_ptr)
  199011. {
  199012. png_debug(1, "in png_write_end\n");
  199013. if (png_ptr == NULL)
  199014. return;
  199015. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  199016. png_error(png_ptr, "No IDATs written into file");
  199017. /* see if user wants us to write information chunks */
  199018. if (info_ptr != NULL)
  199019. {
  199020. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  199021. int i; /* local index variable */
  199022. #endif
  199023. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199024. /* check to see if user has supplied a time chunk */
  199025. if ((info_ptr->valid & PNG_INFO_tIME) &&
  199026. !(png_ptr->mode & PNG_WROTE_tIME))
  199027. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  199028. #endif
  199029. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  199030. /* loop through comment chunks */
  199031. for (i = 0; i < info_ptr->num_text; i++)
  199032. {
  199033. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  199034. info_ptr->text[i].compression);
  199035. /* an internationalized chunk? */
  199036. if (info_ptr->text[i].compression > 0)
  199037. {
  199038. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  199039. /* write international chunk */
  199040. png_write_iTXt(png_ptr,
  199041. info_ptr->text[i].compression,
  199042. info_ptr->text[i].key,
  199043. info_ptr->text[i].lang,
  199044. info_ptr->text[i].lang_key,
  199045. info_ptr->text[i].text);
  199046. #else
  199047. png_warning(png_ptr, "Unable to write international text");
  199048. #endif
  199049. /* Mark this chunk as written */
  199050. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199051. }
  199052. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  199053. {
  199054. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  199055. /* write compressed chunk */
  199056. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  199057. info_ptr->text[i].text, 0,
  199058. info_ptr->text[i].compression);
  199059. #else
  199060. png_warning(png_ptr, "Unable to write compressed text");
  199061. #endif
  199062. /* Mark this chunk as written */
  199063. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  199064. }
  199065. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  199066. {
  199067. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  199068. /* write uncompressed chunk */
  199069. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  199070. info_ptr->text[i].text, 0);
  199071. #else
  199072. png_warning(png_ptr, "Unable to write uncompressed text");
  199073. #endif
  199074. /* Mark this chunk as written */
  199075. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199076. }
  199077. }
  199078. #endif
  199079. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  199080. if (info_ptr->unknown_chunks_num)
  199081. {
  199082. png_unknown_chunk *up;
  199083. png_debug(5, "writing extra chunks\n");
  199084. for (up = info_ptr->unknown_chunks;
  199085. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  199086. up++)
  199087. {
  199088. int keep=png_handle_as_unknown(png_ptr, up->name);
  199089. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  199090. up->location && (up->location & PNG_AFTER_IDAT) &&
  199091. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  199092. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  199093. {
  199094. png_write_chunk(png_ptr, up->name, up->data, up->size);
  199095. }
  199096. }
  199097. }
  199098. #endif
  199099. }
  199100. png_ptr->mode |= PNG_AFTER_IDAT;
  199101. /* write end of PNG file */
  199102. png_write_IEND(png_ptr);
  199103. }
  199104. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199105. #if !defined(_WIN32_WCE)
  199106. /* "time.h" functions are not supported on WindowsCE */
  199107. void PNGAPI
  199108. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  199109. {
  199110. png_debug(1, "in png_convert_from_struct_tm\n");
  199111. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  199112. ptime->month = (png_byte)(ttime->tm_mon + 1);
  199113. ptime->day = (png_byte)ttime->tm_mday;
  199114. ptime->hour = (png_byte)ttime->tm_hour;
  199115. ptime->minute = (png_byte)ttime->tm_min;
  199116. ptime->second = (png_byte)ttime->tm_sec;
  199117. }
  199118. void PNGAPI
  199119. png_convert_from_time_t(png_timep ptime, time_t ttime)
  199120. {
  199121. struct tm *tbuf;
  199122. png_debug(1, "in png_convert_from_time_t\n");
  199123. tbuf = gmtime(&ttime);
  199124. png_convert_from_struct_tm(ptime, tbuf);
  199125. }
  199126. #endif
  199127. #endif
  199128. /* Initialize png_ptr structure, and allocate any memory needed */
  199129. png_structp PNGAPI
  199130. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  199131. png_error_ptr error_fn, png_error_ptr warn_fn)
  199132. {
  199133. #ifdef PNG_USER_MEM_SUPPORTED
  199134. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  199135. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  199136. }
  199137. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  199138. png_structp PNGAPI
  199139. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  199140. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  199141. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  199142. {
  199143. #endif /* PNG_USER_MEM_SUPPORTED */
  199144. png_structp png_ptr;
  199145. #ifdef PNG_SETJMP_SUPPORTED
  199146. #ifdef USE_FAR_KEYWORD
  199147. jmp_buf jmpbuf;
  199148. #endif
  199149. #endif
  199150. int i;
  199151. png_debug(1, "in png_create_write_struct\n");
  199152. #ifdef PNG_USER_MEM_SUPPORTED
  199153. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  199154. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  199155. #else
  199156. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  199157. #endif /* PNG_USER_MEM_SUPPORTED */
  199158. if (png_ptr == NULL)
  199159. return (NULL);
  199160. /* added at libpng-1.2.6 */
  199161. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  199162. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  199163. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  199164. #endif
  199165. #ifdef PNG_SETJMP_SUPPORTED
  199166. #ifdef USE_FAR_KEYWORD
  199167. if (setjmp(jmpbuf))
  199168. #else
  199169. if (setjmp(png_ptr->jmpbuf))
  199170. #endif
  199171. {
  199172. png_free(png_ptr, png_ptr->zbuf);
  199173. png_ptr->zbuf=NULL;
  199174. png_destroy_struct(png_ptr);
  199175. return (NULL);
  199176. }
  199177. #ifdef USE_FAR_KEYWORD
  199178. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  199179. #endif
  199180. #endif
  199181. #ifdef PNG_USER_MEM_SUPPORTED
  199182. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  199183. #endif /* PNG_USER_MEM_SUPPORTED */
  199184. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  199185. i=0;
  199186. do
  199187. {
  199188. if(user_png_ver[i] != png_libpng_ver[i])
  199189. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  199190. } while (png_libpng_ver[i++]);
  199191. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  199192. {
  199193. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  199194. * we must recompile any applications that use any older library version.
  199195. * For versions after libpng 1.0, we will be compatible, so we need
  199196. * only check the first digit.
  199197. */
  199198. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  199199. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  199200. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  199201. {
  199202. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199203. char msg[80];
  199204. if (user_png_ver)
  199205. {
  199206. png_snprintf(msg, 80,
  199207. "Application was compiled with png.h from libpng-%.20s",
  199208. user_png_ver);
  199209. png_warning(png_ptr, msg);
  199210. }
  199211. png_snprintf(msg, 80,
  199212. "Application is running with png.c from libpng-%.20s",
  199213. png_libpng_ver);
  199214. png_warning(png_ptr, msg);
  199215. #endif
  199216. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199217. png_ptr->flags=0;
  199218. #endif
  199219. png_error(png_ptr,
  199220. "Incompatible libpng version in application and library");
  199221. }
  199222. }
  199223. /* initialize zbuf - compression buffer */
  199224. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199225. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199226. (png_uint_32)png_ptr->zbuf_size);
  199227. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199228. png_flush_ptr_NULL);
  199229. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199230. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199231. 1, png_doublep_NULL, png_doublep_NULL);
  199232. #endif
  199233. #ifdef PNG_SETJMP_SUPPORTED
  199234. /* Applications that neglect to set up their own setjmp() and then encounter
  199235. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  199236. abort instead of returning. */
  199237. #ifdef USE_FAR_KEYWORD
  199238. if (setjmp(jmpbuf))
  199239. PNG_ABORT();
  199240. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  199241. #else
  199242. if (setjmp(png_ptr->jmpbuf))
  199243. PNG_ABORT();
  199244. #endif
  199245. #endif
  199246. return (png_ptr);
  199247. }
  199248. /* Initialize png_ptr structure, and allocate any memory needed */
  199249. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  199250. /* Deprecated. */
  199251. #undef png_write_init
  199252. void PNGAPI
  199253. png_write_init(png_structp png_ptr)
  199254. {
  199255. /* We only come here via pre-1.0.7-compiled applications */
  199256. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  199257. }
  199258. void PNGAPI
  199259. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  199260. png_size_t png_struct_size, png_size_t png_info_size)
  199261. {
  199262. /* We only come here via pre-1.0.12-compiled applications */
  199263. if(png_ptr == NULL) return;
  199264. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199265. if(png_sizeof(png_struct) > png_struct_size ||
  199266. png_sizeof(png_info) > png_info_size)
  199267. {
  199268. char msg[80];
  199269. png_ptr->warning_fn=NULL;
  199270. if (user_png_ver)
  199271. {
  199272. png_snprintf(msg, 80,
  199273. "Application was compiled with png.h from libpng-%.20s",
  199274. user_png_ver);
  199275. png_warning(png_ptr, msg);
  199276. }
  199277. png_snprintf(msg, 80,
  199278. "Application is running with png.c from libpng-%.20s",
  199279. png_libpng_ver);
  199280. png_warning(png_ptr, msg);
  199281. }
  199282. #endif
  199283. if(png_sizeof(png_struct) > png_struct_size)
  199284. {
  199285. png_ptr->error_fn=NULL;
  199286. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199287. png_ptr->flags=0;
  199288. #endif
  199289. png_error(png_ptr,
  199290. "The png struct allocated by the application for writing is too small.");
  199291. }
  199292. if(png_sizeof(png_info) > png_info_size)
  199293. {
  199294. png_ptr->error_fn=NULL;
  199295. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199296. png_ptr->flags=0;
  199297. #endif
  199298. png_error(png_ptr,
  199299. "The info struct allocated by the application for writing is too small.");
  199300. }
  199301. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  199302. }
  199303. #endif /* PNG_1_0_X || PNG_1_2_X */
  199304. void PNGAPI
  199305. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  199306. png_size_t png_struct_size)
  199307. {
  199308. png_structp png_ptr=*ptr_ptr;
  199309. #ifdef PNG_SETJMP_SUPPORTED
  199310. jmp_buf tmp_jmp; /* to save current jump buffer */
  199311. #endif
  199312. int i = 0;
  199313. if (png_ptr == NULL)
  199314. return;
  199315. do
  199316. {
  199317. if (user_png_ver[i] != png_libpng_ver[i])
  199318. {
  199319. #ifdef PNG_LEGACY_SUPPORTED
  199320. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  199321. #else
  199322. png_ptr->warning_fn=NULL;
  199323. png_warning(png_ptr,
  199324. "Application uses deprecated png_write_init() and should be recompiled.");
  199325. break;
  199326. #endif
  199327. }
  199328. } while (png_libpng_ver[i++]);
  199329. png_debug(1, "in png_write_init_3\n");
  199330. #ifdef PNG_SETJMP_SUPPORTED
  199331. /* save jump buffer and error functions */
  199332. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199333. #endif
  199334. if (png_sizeof(png_struct) > png_struct_size)
  199335. {
  199336. png_destroy_struct(png_ptr);
  199337. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  199338. *ptr_ptr = png_ptr;
  199339. }
  199340. /* reset all variables to 0 */
  199341. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199342. /* added at libpng-1.2.6 */
  199343. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  199344. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  199345. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  199346. #endif
  199347. #ifdef PNG_SETJMP_SUPPORTED
  199348. /* restore jump buffer */
  199349. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199350. #endif
  199351. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199352. png_flush_ptr_NULL);
  199353. /* initialize zbuf - compression buffer */
  199354. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199355. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199356. (png_uint_32)png_ptr->zbuf_size);
  199357. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199358. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199359. 1, png_doublep_NULL, png_doublep_NULL);
  199360. #endif
  199361. }
  199362. /* Write a few rows of image data. If the image is interlaced,
  199363. * either you will have to write the 7 sub images, or, if you
  199364. * have called png_set_interlace_handling(), you will have to
  199365. * "write" the image seven times.
  199366. */
  199367. void PNGAPI
  199368. png_write_rows(png_structp png_ptr, png_bytepp row,
  199369. png_uint_32 num_rows)
  199370. {
  199371. png_uint_32 i; /* row counter */
  199372. png_bytepp rp; /* row pointer */
  199373. png_debug(1, "in png_write_rows\n");
  199374. if (png_ptr == NULL)
  199375. return;
  199376. /* loop through the rows */
  199377. for (i = 0, rp = row; i < num_rows; i++, rp++)
  199378. {
  199379. png_write_row(png_ptr, *rp);
  199380. }
  199381. }
  199382. /* Write the image. You only need to call this function once, even
  199383. * if you are writing an interlaced image.
  199384. */
  199385. void PNGAPI
  199386. png_write_image(png_structp png_ptr, png_bytepp image)
  199387. {
  199388. png_uint_32 i; /* row index */
  199389. int pass, num_pass; /* pass variables */
  199390. png_bytepp rp; /* points to current row */
  199391. if (png_ptr == NULL)
  199392. return;
  199393. png_debug(1, "in png_write_image\n");
  199394. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199395. /* intialize interlace handling. If image is not interlaced,
  199396. this will set pass to 1 */
  199397. num_pass = png_set_interlace_handling(png_ptr);
  199398. #else
  199399. num_pass = 1;
  199400. #endif
  199401. /* loop through passes */
  199402. for (pass = 0; pass < num_pass; pass++)
  199403. {
  199404. /* loop through image */
  199405. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  199406. {
  199407. png_write_row(png_ptr, *rp);
  199408. }
  199409. }
  199410. }
  199411. /* called by user to write a row of image data */
  199412. void PNGAPI
  199413. png_write_row(png_structp png_ptr, png_bytep row)
  199414. {
  199415. if (png_ptr == NULL)
  199416. return;
  199417. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  199418. png_ptr->row_number, png_ptr->pass);
  199419. /* initialize transformations and other stuff if first time */
  199420. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  199421. {
  199422. /* make sure we wrote the header info */
  199423. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  199424. png_error(png_ptr,
  199425. "png_write_info was never called before png_write_row.");
  199426. /* check for transforms that have been set but were defined out */
  199427. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  199428. if (png_ptr->transformations & PNG_INVERT_MONO)
  199429. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  199430. #endif
  199431. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  199432. if (png_ptr->transformations & PNG_FILLER)
  199433. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  199434. #endif
  199435. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  199436. if (png_ptr->transformations & PNG_PACKSWAP)
  199437. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  199438. #endif
  199439. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  199440. if (png_ptr->transformations & PNG_PACK)
  199441. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  199442. #endif
  199443. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  199444. if (png_ptr->transformations & PNG_SHIFT)
  199445. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  199446. #endif
  199447. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  199448. if (png_ptr->transformations & PNG_BGR)
  199449. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  199450. #endif
  199451. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  199452. if (png_ptr->transformations & PNG_SWAP_BYTES)
  199453. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  199454. #endif
  199455. png_write_start_row(png_ptr);
  199456. }
  199457. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199458. /* if interlaced and not interested in row, return */
  199459. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  199460. {
  199461. switch (png_ptr->pass)
  199462. {
  199463. case 0:
  199464. if (png_ptr->row_number & 0x07)
  199465. {
  199466. png_write_finish_row(png_ptr);
  199467. return;
  199468. }
  199469. break;
  199470. case 1:
  199471. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  199472. {
  199473. png_write_finish_row(png_ptr);
  199474. return;
  199475. }
  199476. break;
  199477. case 2:
  199478. if ((png_ptr->row_number & 0x07) != 4)
  199479. {
  199480. png_write_finish_row(png_ptr);
  199481. return;
  199482. }
  199483. break;
  199484. case 3:
  199485. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  199486. {
  199487. png_write_finish_row(png_ptr);
  199488. return;
  199489. }
  199490. break;
  199491. case 4:
  199492. if ((png_ptr->row_number & 0x03) != 2)
  199493. {
  199494. png_write_finish_row(png_ptr);
  199495. return;
  199496. }
  199497. break;
  199498. case 5:
  199499. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  199500. {
  199501. png_write_finish_row(png_ptr);
  199502. return;
  199503. }
  199504. break;
  199505. case 6:
  199506. if (!(png_ptr->row_number & 0x01))
  199507. {
  199508. png_write_finish_row(png_ptr);
  199509. return;
  199510. }
  199511. break;
  199512. }
  199513. }
  199514. #endif
  199515. /* set up row info for transformations */
  199516. png_ptr->row_info.color_type = png_ptr->color_type;
  199517. png_ptr->row_info.width = png_ptr->usr_width;
  199518. png_ptr->row_info.channels = png_ptr->usr_channels;
  199519. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  199520. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  199521. png_ptr->row_info.channels);
  199522. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  199523. png_ptr->row_info.width);
  199524. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  199525. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  199526. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  199527. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  199528. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  199529. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  199530. /* Copy user's row into buffer, leaving room for filter byte. */
  199531. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  199532. png_ptr->row_info.rowbytes);
  199533. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199534. /* handle interlacing */
  199535. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  199536. (png_ptr->transformations & PNG_INTERLACE))
  199537. {
  199538. png_do_write_interlace(&(png_ptr->row_info),
  199539. png_ptr->row_buf + 1, png_ptr->pass);
  199540. /* this should always get caught above, but still ... */
  199541. if (!(png_ptr->row_info.width))
  199542. {
  199543. png_write_finish_row(png_ptr);
  199544. return;
  199545. }
  199546. }
  199547. #endif
  199548. /* handle other transformations */
  199549. if (png_ptr->transformations)
  199550. png_do_write_transformations(png_ptr);
  199551. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199552. /* Write filter_method 64 (intrapixel differencing) only if
  199553. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  199554. * 2. Libpng did not write a PNG signature (this filter_method is only
  199555. * used in PNG datastreams that are embedded in MNG datastreams) and
  199556. * 3. The application called png_permit_mng_features with a mask that
  199557. * included PNG_FLAG_MNG_FILTER_64 and
  199558. * 4. The filter_method is 64 and
  199559. * 5. The color_type is RGB or RGBA
  199560. */
  199561. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199562. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  199563. {
  199564. /* Intrapixel differencing */
  199565. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199566. }
  199567. #endif
  199568. /* Find a filter if necessary, filter the row and write it out. */
  199569. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  199570. if (png_ptr->write_row_fn != NULL)
  199571. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  199572. }
  199573. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  199574. /* Set the automatic flush interval or 0 to turn flushing off */
  199575. void PNGAPI
  199576. png_set_flush(png_structp png_ptr, int nrows)
  199577. {
  199578. png_debug(1, "in png_set_flush\n");
  199579. if (png_ptr == NULL)
  199580. return;
  199581. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  199582. }
  199583. /* flush the current output buffers now */
  199584. void PNGAPI
  199585. png_write_flush(png_structp png_ptr)
  199586. {
  199587. int wrote_IDAT;
  199588. png_debug(1, "in png_write_flush\n");
  199589. if (png_ptr == NULL)
  199590. return;
  199591. /* We have already written out all of the data */
  199592. if (png_ptr->row_number >= png_ptr->num_rows)
  199593. return;
  199594. do
  199595. {
  199596. int ret;
  199597. /* compress the data */
  199598. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  199599. wrote_IDAT = 0;
  199600. /* check for compression errors */
  199601. if (ret != Z_OK)
  199602. {
  199603. if (png_ptr->zstream.msg != NULL)
  199604. png_error(png_ptr, png_ptr->zstream.msg);
  199605. else
  199606. png_error(png_ptr, "zlib error");
  199607. }
  199608. if (!(png_ptr->zstream.avail_out))
  199609. {
  199610. /* write the IDAT and reset the zlib output buffer */
  199611. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199612. png_ptr->zbuf_size);
  199613. png_ptr->zstream.next_out = png_ptr->zbuf;
  199614. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199615. wrote_IDAT = 1;
  199616. }
  199617. } while(wrote_IDAT == 1);
  199618. /* If there is any data left to be output, write it into a new IDAT */
  199619. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  199620. {
  199621. /* write the IDAT and reset the zlib output buffer */
  199622. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199623. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  199624. png_ptr->zstream.next_out = png_ptr->zbuf;
  199625. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199626. }
  199627. png_ptr->flush_rows = 0;
  199628. png_flush(png_ptr);
  199629. }
  199630. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  199631. /* free all memory used by the write */
  199632. void PNGAPI
  199633. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  199634. {
  199635. png_structp png_ptr = NULL;
  199636. png_infop info_ptr = NULL;
  199637. #ifdef PNG_USER_MEM_SUPPORTED
  199638. png_free_ptr free_fn = NULL;
  199639. png_voidp mem_ptr = NULL;
  199640. #endif
  199641. png_debug(1, "in png_destroy_write_struct\n");
  199642. if (png_ptr_ptr != NULL)
  199643. {
  199644. png_ptr = *png_ptr_ptr;
  199645. #ifdef PNG_USER_MEM_SUPPORTED
  199646. free_fn = png_ptr->free_fn;
  199647. mem_ptr = png_ptr->mem_ptr;
  199648. #endif
  199649. }
  199650. if (info_ptr_ptr != NULL)
  199651. info_ptr = *info_ptr_ptr;
  199652. if (info_ptr != NULL)
  199653. {
  199654. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  199655. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  199656. if (png_ptr->num_chunk_list)
  199657. {
  199658. png_free(png_ptr, png_ptr->chunk_list);
  199659. png_ptr->chunk_list=NULL;
  199660. png_ptr->num_chunk_list=0;
  199661. }
  199662. #endif
  199663. #ifdef PNG_USER_MEM_SUPPORTED
  199664. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  199665. (png_voidp)mem_ptr);
  199666. #else
  199667. png_destroy_struct((png_voidp)info_ptr);
  199668. #endif
  199669. *info_ptr_ptr = NULL;
  199670. }
  199671. if (png_ptr != NULL)
  199672. {
  199673. png_write_destroy(png_ptr);
  199674. #ifdef PNG_USER_MEM_SUPPORTED
  199675. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  199676. (png_voidp)mem_ptr);
  199677. #else
  199678. png_destroy_struct((png_voidp)png_ptr);
  199679. #endif
  199680. *png_ptr_ptr = NULL;
  199681. }
  199682. }
  199683. /* Free any memory used in png_ptr struct (old method) */
  199684. void /* PRIVATE */
  199685. png_write_destroy(png_structp png_ptr)
  199686. {
  199687. #ifdef PNG_SETJMP_SUPPORTED
  199688. jmp_buf tmp_jmp; /* save jump buffer */
  199689. #endif
  199690. png_error_ptr error_fn;
  199691. png_error_ptr warning_fn;
  199692. png_voidp error_ptr;
  199693. #ifdef PNG_USER_MEM_SUPPORTED
  199694. png_free_ptr free_fn;
  199695. #endif
  199696. png_debug(1, "in png_write_destroy\n");
  199697. /* free any memory zlib uses */
  199698. deflateEnd(&png_ptr->zstream);
  199699. /* free our memory. png_free checks NULL for us. */
  199700. png_free(png_ptr, png_ptr->zbuf);
  199701. png_free(png_ptr, png_ptr->row_buf);
  199702. png_free(png_ptr, png_ptr->prev_row);
  199703. png_free(png_ptr, png_ptr->sub_row);
  199704. png_free(png_ptr, png_ptr->up_row);
  199705. png_free(png_ptr, png_ptr->avg_row);
  199706. png_free(png_ptr, png_ptr->paeth_row);
  199707. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  199708. png_free(png_ptr, png_ptr->time_buffer);
  199709. #endif
  199710. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199711. png_free(png_ptr, png_ptr->prev_filters);
  199712. png_free(png_ptr, png_ptr->filter_weights);
  199713. png_free(png_ptr, png_ptr->inv_filter_weights);
  199714. png_free(png_ptr, png_ptr->filter_costs);
  199715. png_free(png_ptr, png_ptr->inv_filter_costs);
  199716. #endif
  199717. #ifdef PNG_SETJMP_SUPPORTED
  199718. /* reset structure */
  199719. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199720. #endif
  199721. error_fn = png_ptr->error_fn;
  199722. warning_fn = png_ptr->warning_fn;
  199723. error_ptr = png_ptr->error_ptr;
  199724. #ifdef PNG_USER_MEM_SUPPORTED
  199725. free_fn = png_ptr->free_fn;
  199726. #endif
  199727. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199728. png_ptr->error_fn = error_fn;
  199729. png_ptr->warning_fn = warning_fn;
  199730. png_ptr->error_ptr = error_ptr;
  199731. #ifdef PNG_USER_MEM_SUPPORTED
  199732. png_ptr->free_fn = free_fn;
  199733. #endif
  199734. #ifdef PNG_SETJMP_SUPPORTED
  199735. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199736. #endif
  199737. }
  199738. /* Allow the application to select one or more row filters to use. */
  199739. void PNGAPI
  199740. png_set_filter(png_structp png_ptr, int method, int filters)
  199741. {
  199742. png_debug(1, "in png_set_filter\n");
  199743. if (png_ptr == NULL)
  199744. return;
  199745. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199746. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199747. (method == PNG_INTRAPIXEL_DIFFERENCING))
  199748. method = PNG_FILTER_TYPE_BASE;
  199749. #endif
  199750. if (method == PNG_FILTER_TYPE_BASE)
  199751. {
  199752. switch (filters & (PNG_ALL_FILTERS | 0x07))
  199753. {
  199754. #ifndef PNG_NO_WRITE_FILTER
  199755. case 5:
  199756. case 6:
  199757. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  199758. #endif /* PNG_NO_WRITE_FILTER */
  199759. case PNG_FILTER_VALUE_NONE:
  199760. png_ptr->do_filter=PNG_FILTER_NONE; break;
  199761. #ifndef PNG_NO_WRITE_FILTER
  199762. case PNG_FILTER_VALUE_SUB:
  199763. png_ptr->do_filter=PNG_FILTER_SUB; break;
  199764. case PNG_FILTER_VALUE_UP:
  199765. png_ptr->do_filter=PNG_FILTER_UP; break;
  199766. case PNG_FILTER_VALUE_AVG:
  199767. png_ptr->do_filter=PNG_FILTER_AVG; break;
  199768. case PNG_FILTER_VALUE_PAETH:
  199769. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  199770. default: png_ptr->do_filter = (png_byte)filters; break;
  199771. #else
  199772. default: png_warning(png_ptr, "Unknown row filter for method 0");
  199773. #endif /* PNG_NO_WRITE_FILTER */
  199774. }
  199775. /* If we have allocated the row_buf, this means we have already started
  199776. * with the image and we should have allocated all of the filter buffers
  199777. * that have been selected. If prev_row isn't already allocated, then
  199778. * it is too late to start using the filters that need it, since we
  199779. * will be missing the data in the previous row. If an application
  199780. * wants to start and stop using particular filters during compression,
  199781. * it should start out with all of the filters, and then add and
  199782. * remove them after the start of compression.
  199783. */
  199784. if (png_ptr->row_buf != NULL)
  199785. {
  199786. #ifndef PNG_NO_WRITE_FILTER
  199787. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  199788. {
  199789. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  199790. (png_ptr->rowbytes + 1));
  199791. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  199792. }
  199793. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  199794. {
  199795. if (png_ptr->prev_row == NULL)
  199796. {
  199797. png_warning(png_ptr, "Can't add Up filter after starting");
  199798. png_ptr->do_filter &= ~PNG_FILTER_UP;
  199799. }
  199800. else
  199801. {
  199802. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  199803. (png_ptr->rowbytes + 1));
  199804. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  199805. }
  199806. }
  199807. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  199808. {
  199809. if (png_ptr->prev_row == NULL)
  199810. {
  199811. png_warning(png_ptr, "Can't add Average filter after starting");
  199812. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  199813. }
  199814. else
  199815. {
  199816. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  199817. (png_ptr->rowbytes + 1));
  199818. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  199819. }
  199820. }
  199821. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  199822. png_ptr->paeth_row == NULL)
  199823. {
  199824. if (png_ptr->prev_row == NULL)
  199825. {
  199826. png_warning(png_ptr, "Can't add Paeth filter after starting");
  199827. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  199828. }
  199829. else
  199830. {
  199831. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  199832. (png_ptr->rowbytes + 1));
  199833. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  199834. }
  199835. }
  199836. if (png_ptr->do_filter == PNG_NO_FILTERS)
  199837. #endif /* PNG_NO_WRITE_FILTER */
  199838. png_ptr->do_filter = PNG_FILTER_NONE;
  199839. }
  199840. }
  199841. else
  199842. png_error(png_ptr, "Unknown custom filter method");
  199843. }
  199844. /* This allows us to influence the way in which libpng chooses the "best"
  199845. * filter for the current scanline. While the "minimum-sum-of-absolute-
  199846. * differences metric is relatively fast and effective, there is some
  199847. * question as to whether it can be improved upon by trying to keep the
  199848. * filtered data going to zlib more consistent, hopefully resulting in
  199849. * better compression.
  199850. */
  199851. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  199852. void PNGAPI
  199853. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  199854. int num_weights, png_doublep filter_weights,
  199855. png_doublep filter_costs)
  199856. {
  199857. int i;
  199858. png_debug(1, "in png_set_filter_heuristics\n");
  199859. if (png_ptr == NULL)
  199860. return;
  199861. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  199862. {
  199863. png_warning(png_ptr, "Unknown filter heuristic method");
  199864. return;
  199865. }
  199866. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  199867. {
  199868. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  199869. }
  199870. if (num_weights < 0 || filter_weights == NULL ||
  199871. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  199872. {
  199873. num_weights = 0;
  199874. }
  199875. png_ptr->num_prev_filters = (png_byte)num_weights;
  199876. png_ptr->heuristic_method = (png_byte)heuristic_method;
  199877. if (num_weights > 0)
  199878. {
  199879. if (png_ptr->prev_filters == NULL)
  199880. {
  199881. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  199882. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  199883. /* To make sure that the weighting starts out fairly */
  199884. for (i = 0; i < num_weights; i++)
  199885. {
  199886. png_ptr->prev_filters[i] = 255;
  199887. }
  199888. }
  199889. if (png_ptr->filter_weights == NULL)
  199890. {
  199891. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199892. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199893. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  199894. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  199895. for (i = 0; i < num_weights; i++)
  199896. {
  199897. png_ptr->inv_filter_weights[i] =
  199898. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199899. }
  199900. }
  199901. for (i = 0; i < num_weights; i++)
  199902. {
  199903. if (filter_weights[i] < 0.0)
  199904. {
  199905. png_ptr->inv_filter_weights[i] =
  199906. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  199907. }
  199908. else
  199909. {
  199910. png_ptr->inv_filter_weights[i] =
  199911. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  199912. png_ptr->filter_weights[i] =
  199913. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  199914. }
  199915. }
  199916. }
  199917. /* If, in the future, there are other filter methods, this would
  199918. * need to be based on png_ptr->filter.
  199919. */
  199920. if (png_ptr->filter_costs == NULL)
  199921. {
  199922. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  199923. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  199924. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  199925. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  199926. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  199927. {
  199928. png_ptr->inv_filter_costs[i] =
  199929. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  199930. }
  199931. }
  199932. /* Here is where we set the relative costs of the different filters. We
  199933. * should take the desired compression level into account when setting
  199934. * the costs, so that Paeth, for instance, has a high relative cost at low
  199935. * compression levels, while it has a lower relative cost at higher
  199936. * compression settings. The filter types are in order of increasing
  199937. * relative cost, so it would be possible to do this with an algorithm.
  199938. */
  199939. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  199940. {
  199941. if (filter_costs == NULL || filter_costs[i] < 0.0)
  199942. {
  199943. png_ptr->inv_filter_costs[i] =
  199944. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  199945. }
  199946. else if (filter_costs[i] >= 1.0)
  199947. {
  199948. png_ptr->inv_filter_costs[i] =
  199949. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  199950. png_ptr->filter_costs[i] =
  199951. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  199952. }
  199953. }
  199954. }
  199955. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  199956. void PNGAPI
  199957. png_set_compression_level(png_structp png_ptr, int level)
  199958. {
  199959. png_debug(1, "in png_set_compression_level\n");
  199960. if (png_ptr == NULL)
  199961. return;
  199962. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  199963. png_ptr->zlib_level = level;
  199964. }
  199965. void PNGAPI
  199966. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  199967. {
  199968. png_debug(1, "in png_set_compression_mem_level\n");
  199969. if (png_ptr == NULL)
  199970. return;
  199971. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  199972. png_ptr->zlib_mem_level = mem_level;
  199973. }
  199974. void PNGAPI
  199975. png_set_compression_strategy(png_structp png_ptr, int strategy)
  199976. {
  199977. png_debug(1, "in png_set_compression_strategy\n");
  199978. if (png_ptr == NULL)
  199979. return;
  199980. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  199981. png_ptr->zlib_strategy = strategy;
  199982. }
  199983. void PNGAPI
  199984. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  199985. {
  199986. if (png_ptr == NULL)
  199987. return;
  199988. if (window_bits > 15)
  199989. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  199990. else if (window_bits < 8)
  199991. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  199992. #ifndef WBITS_8_OK
  199993. /* avoid libpng bug with 256-byte windows */
  199994. if (window_bits == 8)
  199995. {
  199996. png_warning(png_ptr, "Compression window is being reset to 512");
  199997. window_bits=9;
  199998. }
  199999. #endif
  200000. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  200001. png_ptr->zlib_window_bits = window_bits;
  200002. }
  200003. void PNGAPI
  200004. png_set_compression_method(png_structp png_ptr, int method)
  200005. {
  200006. png_debug(1, "in png_set_compression_method\n");
  200007. if (png_ptr == NULL)
  200008. return;
  200009. if (method != 8)
  200010. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  200011. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  200012. png_ptr->zlib_method = method;
  200013. }
  200014. void PNGAPI
  200015. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  200016. {
  200017. if (png_ptr == NULL)
  200018. return;
  200019. png_ptr->write_row_fn = write_row_fn;
  200020. }
  200021. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  200022. void PNGAPI
  200023. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  200024. write_user_transform_fn)
  200025. {
  200026. png_debug(1, "in png_set_write_user_transform_fn\n");
  200027. if (png_ptr == NULL)
  200028. return;
  200029. png_ptr->transformations |= PNG_USER_TRANSFORM;
  200030. png_ptr->write_user_transform_fn = write_user_transform_fn;
  200031. }
  200032. #endif
  200033. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  200034. void PNGAPI
  200035. png_write_png(png_structp png_ptr, png_infop info_ptr,
  200036. int transforms, voidp params)
  200037. {
  200038. if (png_ptr == NULL || info_ptr == NULL)
  200039. return;
  200040. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200041. /* invert the alpha channel from opacity to transparency */
  200042. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  200043. png_set_invert_alpha(png_ptr);
  200044. #endif
  200045. /* Write the file header information. */
  200046. png_write_info(png_ptr, info_ptr);
  200047. /* ------ these transformations don't touch the info structure ------- */
  200048. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  200049. /* invert monochrome pixels */
  200050. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  200051. png_set_invert_mono(png_ptr);
  200052. #endif
  200053. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200054. /* Shift the pixels up to a legal bit depth and fill in
  200055. * as appropriate to correctly scale the image.
  200056. */
  200057. if ((transforms & PNG_TRANSFORM_SHIFT)
  200058. && (info_ptr->valid & PNG_INFO_sBIT))
  200059. png_set_shift(png_ptr, &info_ptr->sig_bit);
  200060. #endif
  200061. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200062. /* pack pixels into bytes */
  200063. if (transforms & PNG_TRANSFORM_PACKING)
  200064. png_set_packing(png_ptr);
  200065. #endif
  200066. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200067. /* swap location of alpha bytes from ARGB to RGBA */
  200068. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  200069. png_set_swap_alpha(png_ptr);
  200070. #endif
  200071. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  200072. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  200073. * RGB (4 channels -> 3 channels). The second parameter is not used.
  200074. */
  200075. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  200076. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  200077. #endif
  200078. #if defined(PNG_WRITE_BGR_SUPPORTED)
  200079. /* flip BGR pixels to RGB */
  200080. if (transforms & PNG_TRANSFORM_BGR)
  200081. png_set_bgr(png_ptr);
  200082. #endif
  200083. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  200084. /* swap bytes of 16-bit files to most significant byte first */
  200085. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  200086. png_set_swap(png_ptr);
  200087. #endif
  200088. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  200089. /* swap bits of 1, 2, 4 bit packed pixel formats */
  200090. if (transforms & PNG_TRANSFORM_PACKSWAP)
  200091. png_set_packswap(png_ptr);
  200092. #endif
  200093. /* ----------------------- end of transformations ------------------- */
  200094. /* write the bits */
  200095. if (info_ptr->valid & PNG_INFO_IDAT)
  200096. png_write_image(png_ptr, info_ptr->row_pointers);
  200097. /* It is REQUIRED to call this to finish writing the rest of the file */
  200098. png_write_end(png_ptr, info_ptr);
  200099. transforms = transforms; /* quiet compiler warnings */
  200100. params = params;
  200101. }
  200102. #endif
  200103. #endif /* PNG_WRITE_SUPPORTED */
  200104. /*** End of inlined file: pngwrite.c ***/
  200105. /*** Start of inlined file: pngwtran.c ***/
  200106. /* pngwtran.c - transforms the data in a row for PNG writers
  200107. *
  200108. * Last changed in libpng 1.2.9 April 14, 2006
  200109. * For conditions of distribution and use, see copyright notice in png.h
  200110. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  200111. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200112. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200113. */
  200114. #define PNG_INTERNAL
  200115. #ifdef PNG_WRITE_SUPPORTED
  200116. /* Transform the data according to the user's wishes. The order of
  200117. * transformations is significant.
  200118. */
  200119. void /* PRIVATE */
  200120. png_do_write_transformations(png_structp png_ptr)
  200121. {
  200122. png_debug(1, "in png_do_write_transformations\n");
  200123. if (png_ptr == NULL)
  200124. return;
  200125. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  200126. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  200127. if(png_ptr->write_user_transform_fn != NULL)
  200128. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  200129. (png_ptr, /* png_ptr */
  200130. &(png_ptr->row_info), /* row_info: */
  200131. /* png_uint_32 width; width of row */
  200132. /* png_uint_32 rowbytes; number of bytes in row */
  200133. /* png_byte color_type; color type of pixels */
  200134. /* png_byte bit_depth; bit depth of samples */
  200135. /* png_byte channels; number of channels (1-4) */
  200136. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  200137. png_ptr->row_buf + 1); /* start of pixel data for row */
  200138. #endif
  200139. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  200140. if (png_ptr->transformations & PNG_FILLER)
  200141. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200142. png_ptr->flags);
  200143. #endif
  200144. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  200145. if (png_ptr->transformations & PNG_PACKSWAP)
  200146. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200147. #endif
  200148. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200149. if (png_ptr->transformations & PNG_PACK)
  200150. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200151. (png_uint_32)png_ptr->bit_depth);
  200152. #endif
  200153. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  200154. if (png_ptr->transformations & PNG_SWAP_BYTES)
  200155. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200156. #endif
  200157. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200158. if (png_ptr->transformations & PNG_SHIFT)
  200159. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200160. &(png_ptr->shift));
  200161. #endif
  200162. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200163. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  200164. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200165. #endif
  200166. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200167. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  200168. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200169. #endif
  200170. #if defined(PNG_WRITE_BGR_SUPPORTED)
  200171. if (png_ptr->transformations & PNG_BGR)
  200172. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200173. #endif
  200174. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  200175. if (png_ptr->transformations & PNG_INVERT_MONO)
  200176. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200177. #endif
  200178. }
  200179. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200180. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  200181. * row_info bit depth should be 8 (one pixel per byte). The channels
  200182. * should be 1 (this only happens on grayscale and paletted images).
  200183. */
  200184. void /* PRIVATE */
  200185. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  200186. {
  200187. png_debug(1, "in png_do_pack\n");
  200188. if (row_info->bit_depth == 8 &&
  200189. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200190. row != NULL && row_info != NULL &&
  200191. #endif
  200192. row_info->channels == 1)
  200193. {
  200194. switch ((int)bit_depth)
  200195. {
  200196. case 1:
  200197. {
  200198. png_bytep sp, dp;
  200199. int mask, v;
  200200. png_uint_32 i;
  200201. png_uint_32 row_width = row_info->width;
  200202. sp = row;
  200203. dp = row;
  200204. mask = 0x80;
  200205. v = 0;
  200206. for (i = 0; i < row_width; i++)
  200207. {
  200208. if (*sp != 0)
  200209. v |= mask;
  200210. sp++;
  200211. if (mask > 1)
  200212. mask >>= 1;
  200213. else
  200214. {
  200215. mask = 0x80;
  200216. *dp = (png_byte)v;
  200217. dp++;
  200218. v = 0;
  200219. }
  200220. }
  200221. if (mask != 0x80)
  200222. *dp = (png_byte)v;
  200223. break;
  200224. }
  200225. case 2:
  200226. {
  200227. png_bytep sp, dp;
  200228. int shift, v;
  200229. png_uint_32 i;
  200230. png_uint_32 row_width = row_info->width;
  200231. sp = row;
  200232. dp = row;
  200233. shift = 6;
  200234. v = 0;
  200235. for (i = 0; i < row_width; i++)
  200236. {
  200237. png_byte value;
  200238. value = (png_byte)(*sp & 0x03);
  200239. v |= (value << shift);
  200240. if (shift == 0)
  200241. {
  200242. shift = 6;
  200243. *dp = (png_byte)v;
  200244. dp++;
  200245. v = 0;
  200246. }
  200247. else
  200248. shift -= 2;
  200249. sp++;
  200250. }
  200251. if (shift != 6)
  200252. *dp = (png_byte)v;
  200253. break;
  200254. }
  200255. case 4:
  200256. {
  200257. png_bytep sp, dp;
  200258. int shift, v;
  200259. png_uint_32 i;
  200260. png_uint_32 row_width = row_info->width;
  200261. sp = row;
  200262. dp = row;
  200263. shift = 4;
  200264. v = 0;
  200265. for (i = 0; i < row_width; i++)
  200266. {
  200267. png_byte value;
  200268. value = (png_byte)(*sp & 0x0f);
  200269. v |= (value << shift);
  200270. if (shift == 0)
  200271. {
  200272. shift = 4;
  200273. *dp = (png_byte)v;
  200274. dp++;
  200275. v = 0;
  200276. }
  200277. else
  200278. shift -= 4;
  200279. sp++;
  200280. }
  200281. if (shift != 4)
  200282. *dp = (png_byte)v;
  200283. break;
  200284. }
  200285. }
  200286. row_info->bit_depth = (png_byte)bit_depth;
  200287. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  200288. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  200289. row_info->width);
  200290. }
  200291. }
  200292. #endif
  200293. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200294. /* Shift pixel values to take advantage of whole range. Pass the
  200295. * true number of bits in bit_depth. The row should be packed
  200296. * according to row_info->bit_depth. Thus, if you had a row of
  200297. * bit depth 4, but the pixels only had values from 0 to 7, you
  200298. * would pass 3 as bit_depth, and this routine would translate the
  200299. * data to 0 to 15.
  200300. */
  200301. void /* PRIVATE */
  200302. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  200303. {
  200304. png_debug(1, "in png_do_shift\n");
  200305. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200306. if (row != NULL && row_info != NULL &&
  200307. #else
  200308. if (
  200309. #endif
  200310. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  200311. {
  200312. int shift_start[4], shift_dec[4];
  200313. int channels = 0;
  200314. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  200315. {
  200316. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  200317. shift_dec[channels] = bit_depth->red;
  200318. channels++;
  200319. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  200320. shift_dec[channels] = bit_depth->green;
  200321. channels++;
  200322. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  200323. shift_dec[channels] = bit_depth->blue;
  200324. channels++;
  200325. }
  200326. else
  200327. {
  200328. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  200329. shift_dec[channels] = bit_depth->gray;
  200330. channels++;
  200331. }
  200332. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  200333. {
  200334. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  200335. shift_dec[channels] = bit_depth->alpha;
  200336. channels++;
  200337. }
  200338. /* with low row depths, could only be grayscale, so one channel */
  200339. if (row_info->bit_depth < 8)
  200340. {
  200341. png_bytep bp = row;
  200342. png_uint_32 i;
  200343. png_byte mask;
  200344. png_uint_32 row_bytes = row_info->rowbytes;
  200345. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  200346. mask = 0x55;
  200347. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  200348. mask = 0x11;
  200349. else
  200350. mask = 0xff;
  200351. for (i = 0; i < row_bytes; i++, bp++)
  200352. {
  200353. png_uint_16 v;
  200354. int j;
  200355. v = *bp;
  200356. *bp = 0;
  200357. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  200358. {
  200359. if (j > 0)
  200360. *bp |= (png_byte)((v << j) & 0xff);
  200361. else
  200362. *bp |= (png_byte)((v >> (-j)) & mask);
  200363. }
  200364. }
  200365. }
  200366. else if (row_info->bit_depth == 8)
  200367. {
  200368. png_bytep bp = row;
  200369. png_uint_32 i;
  200370. png_uint_32 istop = channels * row_info->width;
  200371. for (i = 0; i < istop; i++, bp++)
  200372. {
  200373. png_uint_16 v;
  200374. int j;
  200375. int c = (int)(i%channels);
  200376. v = *bp;
  200377. *bp = 0;
  200378. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200379. {
  200380. if (j > 0)
  200381. *bp |= (png_byte)((v << j) & 0xff);
  200382. else
  200383. *bp |= (png_byte)((v >> (-j)) & 0xff);
  200384. }
  200385. }
  200386. }
  200387. else
  200388. {
  200389. png_bytep bp;
  200390. png_uint_32 i;
  200391. png_uint_32 istop = channels * row_info->width;
  200392. for (bp = row, i = 0; i < istop; i++)
  200393. {
  200394. int c = (int)(i%channels);
  200395. png_uint_16 value, v;
  200396. int j;
  200397. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  200398. value = 0;
  200399. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200400. {
  200401. if (j > 0)
  200402. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  200403. else
  200404. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  200405. }
  200406. *bp++ = (png_byte)(value >> 8);
  200407. *bp++ = (png_byte)(value & 0xff);
  200408. }
  200409. }
  200410. }
  200411. }
  200412. #endif
  200413. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200414. void /* PRIVATE */
  200415. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  200416. {
  200417. png_debug(1, "in png_do_write_swap_alpha\n");
  200418. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200419. if (row != NULL && row_info != NULL)
  200420. #endif
  200421. {
  200422. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200423. {
  200424. /* This converts from ARGB to RGBA */
  200425. if (row_info->bit_depth == 8)
  200426. {
  200427. png_bytep sp, dp;
  200428. png_uint_32 i;
  200429. png_uint_32 row_width = row_info->width;
  200430. for (i = 0, sp = dp = row; i < row_width; i++)
  200431. {
  200432. png_byte save = *(sp++);
  200433. *(dp++) = *(sp++);
  200434. *(dp++) = *(sp++);
  200435. *(dp++) = *(sp++);
  200436. *(dp++) = save;
  200437. }
  200438. }
  200439. /* This converts from AARRGGBB to RRGGBBAA */
  200440. else
  200441. {
  200442. png_bytep sp, dp;
  200443. png_uint_32 i;
  200444. png_uint_32 row_width = row_info->width;
  200445. for (i = 0, sp = dp = row; i < row_width; i++)
  200446. {
  200447. png_byte save[2];
  200448. save[0] = *(sp++);
  200449. save[1] = *(sp++);
  200450. *(dp++) = *(sp++);
  200451. *(dp++) = *(sp++);
  200452. *(dp++) = *(sp++);
  200453. *(dp++) = *(sp++);
  200454. *(dp++) = *(sp++);
  200455. *(dp++) = *(sp++);
  200456. *(dp++) = save[0];
  200457. *(dp++) = save[1];
  200458. }
  200459. }
  200460. }
  200461. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200462. {
  200463. /* This converts from AG to GA */
  200464. if (row_info->bit_depth == 8)
  200465. {
  200466. png_bytep sp, dp;
  200467. png_uint_32 i;
  200468. png_uint_32 row_width = row_info->width;
  200469. for (i = 0, sp = dp = row; i < row_width; i++)
  200470. {
  200471. png_byte save = *(sp++);
  200472. *(dp++) = *(sp++);
  200473. *(dp++) = save;
  200474. }
  200475. }
  200476. /* This converts from AAGG to GGAA */
  200477. else
  200478. {
  200479. png_bytep sp, dp;
  200480. png_uint_32 i;
  200481. png_uint_32 row_width = row_info->width;
  200482. for (i = 0, sp = dp = row; i < row_width; i++)
  200483. {
  200484. png_byte save[2];
  200485. save[0] = *(sp++);
  200486. save[1] = *(sp++);
  200487. *(dp++) = *(sp++);
  200488. *(dp++) = *(sp++);
  200489. *(dp++) = save[0];
  200490. *(dp++) = save[1];
  200491. }
  200492. }
  200493. }
  200494. }
  200495. }
  200496. #endif
  200497. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200498. void /* PRIVATE */
  200499. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  200500. {
  200501. png_debug(1, "in png_do_write_invert_alpha\n");
  200502. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200503. if (row != NULL && row_info != NULL)
  200504. #endif
  200505. {
  200506. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200507. {
  200508. /* This inverts the alpha channel in RGBA */
  200509. if (row_info->bit_depth == 8)
  200510. {
  200511. png_bytep sp, dp;
  200512. png_uint_32 i;
  200513. png_uint_32 row_width = row_info->width;
  200514. for (i = 0, sp = dp = row; i < row_width; i++)
  200515. {
  200516. /* does nothing
  200517. *(dp++) = *(sp++);
  200518. *(dp++) = *(sp++);
  200519. *(dp++) = *(sp++);
  200520. */
  200521. sp+=3; dp = sp;
  200522. *(dp++) = (png_byte)(255 - *(sp++));
  200523. }
  200524. }
  200525. /* This inverts the alpha channel in RRGGBBAA */
  200526. else
  200527. {
  200528. png_bytep sp, dp;
  200529. png_uint_32 i;
  200530. png_uint_32 row_width = row_info->width;
  200531. for (i = 0, sp = dp = row; i < row_width; i++)
  200532. {
  200533. /* does nothing
  200534. *(dp++) = *(sp++);
  200535. *(dp++) = *(sp++);
  200536. *(dp++) = *(sp++);
  200537. *(dp++) = *(sp++);
  200538. *(dp++) = *(sp++);
  200539. *(dp++) = *(sp++);
  200540. */
  200541. sp+=6; dp = sp;
  200542. *(dp++) = (png_byte)(255 - *(sp++));
  200543. *(dp++) = (png_byte)(255 - *(sp++));
  200544. }
  200545. }
  200546. }
  200547. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200548. {
  200549. /* This inverts the alpha channel in GA */
  200550. if (row_info->bit_depth == 8)
  200551. {
  200552. png_bytep sp, dp;
  200553. png_uint_32 i;
  200554. png_uint_32 row_width = row_info->width;
  200555. for (i = 0, sp = dp = row; i < row_width; i++)
  200556. {
  200557. *(dp++) = *(sp++);
  200558. *(dp++) = (png_byte)(255 - *(sp++));
  200559. }
  200560. }
  200561. /* This inverts the alpha channel in GGAA */
  200562. else
  200563. {
  200564. png_bytep sp, dp;
  200565. png_uint_32 i;
  200566. png_uint_32 row_width = row_info->width;
  200567. for (i = 0, sp = dp = row; i < row_width; i++)
  200568. {
  200569. /* does nothing
  200570. *(dp++) = *(sp++);
  200571. *(dp++) = *(sp++);
  200572. */
  200573. sp+=2; dp = sp;
  200574. *(dp++) = (png_byte)(255 - *(sp++));
  200575. *(dp++) = (png_byte)(255 - *(sp++));
  200576. }
  200577. }
  200578. }
  200579. }
  200580. }
  200581. #endif
  200582. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200583. /* undoes intrapixel differencing */
  200584. void /* PRIVATE */
  200585. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  200586. {
  200587. png_debug(1, "in png_do_write_intrapixel\n");
  200588. if (
  200589. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200590. row != NULL && row_info != NULL &&
  200591. #endif
  200592. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  200593. {
  200594. int bytes_per_pixel;
  200595. png_uint_32 row_width = row_info->width;
  200596. if (row_info->bit_depth == 8)
  200597. {
  200598. png_bytep rp;
  200599. png_uint_32 i;
  200600. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200601. bytes_per_pixel = 3;
  200602. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200603. bytes_per_pixel = 4;
  200604. else
  200605. return;
  200606. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200607. {
  200608. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  200609. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  200610. }
  200611. }
  200612. else if (row_info->bit_depth == 16)
  200613. {
  200614. png_bytep rp;
  200615. png_uint_32 i;
  200616. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200617. bytes_per_pixel = 6;
  200618. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200619. bytes_per_pixel = 8;
  200620. else
  200621. return;
  200622. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200623. {
  200624. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  200625. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  200626. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  200627. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  200628. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  200629. *(rp ) = (png_byte)((red >> 8) & 0xff);
  200630. *(rp+1) = (png_byte)(red & 0xff);
  200631. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  200632. *(rp+5) = (png_byte)(blue & 0xff);
  200633. }
  200634. }
  200635. }
  200636. }
  200637. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  200638. #endif /* PNG_WRITE_SUPPORTED */
  200639. /*** End of inlined file: pngwtran.c ***/
  200640. /*** Start of inlined file: pngwutil.c ***/
  200641. /* pngwutil.c - utilities to write a PNG file
  200642. *
  200643. * Last changed in libpng 1.2.20 Septhember 3, 2007
  200644. * For conditions of distribution and use, see copyright notice in png.h
  200645. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  200646. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200647. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200648. */
  200649. #define PNG_INTERNAL
  200650. #ifdef PNG_WRITE_SUPPORTED
  200651. /* Place a 32-bit number into a buffer in PNG byte order. We work
  200652. * with unsigned numbers for convenience, although one supported
  200653. * ancillary chunk uses signed (two's complement) numbers.
  200654. */
  200655. void PNGAPI
  200656. png_save_uint_32(png_bytep buf, png_uint_32 i)
  200657. {
  200658. buf[0] = (png_byte)((i >> 24) & 0xff);
  200659. buf[1] = (png_byte)((i >> 16) & 0xff);
  200660. buf[2] = (png_byte)((i >> 8) & 0xff);
  200661. buf[3] = (png_byte)(i & 0xff);
  200662. }
  200663. /* The png_save_int_32 function assumes integers are stored in two's
  200664. * complement format. If this isn't the case, then this routine needs to
  200665. * be modified to write data in two's complement format.
  200666. */
  200667. void PNGAPI
  200668. png_save_int_32(png_bytep buf, png_int_32 i)
  200669. {
  200670. buf[0] = (png_byte)((i >> 24) & 0xff);
  200671. buf[1] = (png_byte)((i >> 16) & 0xff);
  200672. buf[2] = (png_byte)((i >> 8) & 0xff);
  200673. buf[3] = (png_byte)(i & 0xff);
  200674. }
  200675. /* Place a 16-bit number into a buffer in PNG byte order.
  200676. * The parameter is declared unsigned int, not png_uint_16,
  200677. * just to avoid potential problems on pre-ANSI C compilers.
  200678. */
  200679. void PNGAPI
  200680. png_save_uint_16(png_bytep buf, unsigned int i)
  200681. {
  200682. buf[0] = (png_byte)((i >> 8) & 0xff);
  200683. buf[1] = (png_byte)(i & 0xff);
  200684. }
  200685. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  200686. * representing the chunk name. The array must be at least 4 bytes in
  200687. * length, and does not need to be null terminated. To be safe, pass the
  200688. * pre-defined chunk names here, and if you need a new one, define it
  200689. * where the others are defined. The length is the length of the data.
  200690. * All the data must be present. If that is not possible, use the
  200691. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  200692. * functions instead.
  200693. */
  200694. void PNGAPI
  200695. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  200696. png_bytep data, png_size_t length)
  200697. {
  200698. if(png_ptr == NULL) return;
  200699. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  200700. png_write_chunk_data(png_ptr, data, length);
  200701. png_write_chunk_end(png_ptr);
  200702. }
  200703. /* Write the start of a PNG chunk. The type is the chunk type.
  200704. * The total_length is the sum of the lengths of all the data you will be
  200705. * passing in png_write_chunk_data().
  200706. */
  200707. void PNGAPI
  200708. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  200709. png_uint_32 length)
  200710. {
  200711. png_byte buf[4];
  200712. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  200713. if(png_ptr == NULL) return;
  200714. /* write the length */
  200715. png_save_uint_32(buf, length);
  200716. png_write_data(png_ptr, buf, (png_size_t)4);
  200717. /* write the chunk name */
  200718. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  200719. /* reset the crc and run it over the chunk name */
  200720. png_reset_crc(png_ptr);
  200721. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  200722. }
  200723. /* Write the data of a PNG chunk started with png_write_chunk_start().
  200724. * Note that multiple calls to this function are allowed, and that the
  200725. * sum of the lengths from these calls *must* add up to the total_length
  200726. * given to png_write_chunk_start().
  200727. */
  200728. void PNGAPI
  200729. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  200730. {
  200731. /* write the data, and run the CRC over it */
  200732. if(png_ptr == NULL) return;
  200733. if (data != NULL && length > 0)
  200734. {
  200735. png_calculate_crc(png_ptr, data, length);
  200736. png_write_data(png_ptr, data, length);
  200737. }
  200738. }
  200739. /* Finish a chunk started with png_write_chunk_start(). */
  200740. void PNGAPI
  200741. png_write_chunk_end(png_structp png_ptr)
  200742. {
  200743. png_byte buf[4];
  200744. if(png_ptr == NULL) return;
  200745. /* write the crc */
  200746. png_save_uint_32(buf, png_ptr->crc);
  200747. png_write_data(png_ptr, buf, (png_size_t)4);
  200748. }
  200749. /* Simple function to write the signature. If we have already written
  200750. * the magic bytes of the signature, or more likely, the PNG stream is
  200751. * being embedded into another stream and doesn't need its own signature,
  200752. * we should call png_set_sig_bytes() to tell libpng how many of the
  200753. * bytes have already been written.
  200754. */
  200755. void /* PRIVATE */
  200756. png_write_sig(png_structp png_ptr)
  200757. {
  200758. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  200759. /* write the rest of the 8 byte signature */
  200760. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  200761. (png_size_t)8 - png_ptr->sig_bytes);
  200762. if(png_ptr->sig_bytes < 3)
  200763. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  200764. }
  200765. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  200766. /*
  200767. * This pair of functions encapsulates the operation of (a) compressing a
  200768. * text string, and (b) issuing it later as a series of chunk data writes.
  200769. * The compression_state structure is shared context for these functions
  200770. * set up by the caller in order to make the whole mess thread-safe.
  200771. */
  200772. typedef struct
  200773. {
  200774. char *input; /* the uncompressed input data */
  200775. int input_len; /* its length */
  200776. int num_output_ptr; /* number of output pointers used */
  200777. int max_output_ptr; /* size of output_ptr */
  200778. png_charpp output_ptr; /* array of pointers to output */
  200779. } compression_state;
  200780. /* compress given text into storage in the png_ptr structure */
  200781. static int /* PRIVATE */
  200782. png_text_compress(png_structp png_ptr,
  200783. png_charp text, png_size_t text_len, int compression,
  200784. compression_state *comp)
  200785. {
  200786. int ret;
  200787. comp->num_output_ptr = 0;
  200788. comp->max_output_ptr = 0;
  200789. comp->output_ptr = NULL;
  200790. comp->input = NULL;
  200791. comp->input_len = 0;
  200792. /* we may just want to pass the text right through */
  200793. if (compression == PNG_TEXT_COMPRESSION_NONE)
  200794. {
  200795. comp->input = text;
  200796. comp->input_len = text_len;
  200797. return((int)text_len);
  200798. }
  200799. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  200800. {
  200801. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  200802. char msg[50];
  200803. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  200804. png_warning(png_ptr, msg);
  200805. #else
  200806. png_warning(png_ptr, "Unknown compression type");
  200807. #endif
  200808. }
  200809. /* We can't write the chunk until we find out how much data we have,
  200810. * which means we need to run the compressor first and save the
  200811. * output. This shouldn't be a problem, as the vast majority of
  200812. * comments should be reasonable, but we will set up an array of
  200813. * malloc'd pointers to be sure.
  200814. *
  200815. * If we knew the application was well behaved, we could simplify this
  200816. * greatly by assuming we can always malloc an output buffer large
  200817. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  200818. * and malloc this directly. The only time this would be a bad idea is
  200819. * if we can't malloc more than 64K and we have 64K of random input
  200820. * data, or if the input string is incredibly large (although this
  200821. * wouldn't cause a failure, just a slowdown due to swapping).
  200822. */
  200823. /* set up the compression buffers */
  200824. png_ptr->zstream.avail_in = (uInt)text_len;
  200825. png_ptr->zstream.next_in = (Bytef *)text;
  200826. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200827. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  200828. /* this is the same compression loop as in png_write_row() */
  200829. do
  200830. {
  200831. /* compress the data */
  200832. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  200833. if (ret != Z_OK)
  200834. {
  200835. /* error */
  200836. if (png_ptr->zstream.msg != NULL)
  200837. png_error(png_ptr, png_ptr->zstream.msg);
  200838. else
  200839. png_error(png_ptr, "zlib error");
  200840. }
  200841. /* check to see if we need more room */
  200842. if (!(png_ptr->zstream.avail_out))
  200843. {
  200844. /* make sure the output array has room */
  200845. if (comp->num_output_ptr >= comp->max_output_ptr)
  200846. {
  200847. int old_max;
  200848. old_max = comp->max_output_ptr;
  200849. comp->max_output_ptr = comp->num_output_ptr + 4;
  200850. if (comp->output_ptr != NULL)
  200851. {
  200852. png_charpp old_ptr;
  200853. old_ptr = comp->output_ptr;
  200854. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200855. (png_uint_32)(comp->max_output_ptr *
  200856. png_sizeof (png_charpp)));
  200857. png_memcpy(comp->output_ptr, old_ptr, old_max
  200858. * png_sizeof (png_charp));
  200859. png_free(png_ptr, old_ptr);
  200860. }
  200861. else
  200862. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200863. (png_uint_32)(comp->max_output_ptr *
  200864. png_sizeof (png_charp)));
  200865. }
  200866. /* save the data */
  200867. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  200868. (png_uint_32)png_ptr->zbuf_size);
  200869. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  200870. png_ptr->zbuf_size);
  200871. comp->num_output_ptr++;
  200872. /* and reset the buffer */
  200873. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200874. png_ptr->zstream.next_out = png_ptr->zbuf;
  200875. }
  200876. /* continue until we don't have any more to compress */
  200877. } while (png_ptr->zstream.avail_in);
  200878. /* finish the compression */
  200879. do
  200880. {
  200881. /* tell zlib we are finished */
  200882. ret = deflate(&png_ptr->zstream, Z_FINISH);
  200883. if (ret == Z_OK)
  200884. {
  200885. /* check to see if we need more room */
  200886. if (!(png_ptr->zstream.avail_out))
  200887. {
  200888. /* check to make sure our output array has room */
  200889. if (comp->num_output_ptr >= comp->max_output_ptr)
  200890. {
  200891. int old_max;
  200892. old_max = comp->max_output_ptr;
  200893. comp->max_output_ptr = comp->num_output_ptr + 4;
  200894. if (comp->output_ptr != NULL)
  200895. {
  200896. png_charpp old_ptr;
  200897. old_ptr = comp->output_ptr;
  200898. /* This could be optimized to realloc() */
  200899. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200900. (png_uint_32)(comp->max_output_ptr *
  200901. png_sizeof (png_charpp)));
  200902. png_memcpy(comp->output_ptr, old_ptr,
  200903. old_max * png_sizeof (png_charp));
  200904. png_free(png_ptr, old_ptr);
  200905. }
  200906. else
  200907. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  200908. (png_uint_32)(comp->max_output_ptr *
  200909. png_sizeof (png_charp)));
  200910. }
  200911. /* save off the data */
  200912. comp->output_ptr[comp->num_output_ptr] =
  200913. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  200914. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  200915. png_ptr->zbuf_size);
  200916. comp->num_output_ptr++;
  200917. /* and reset the buffer pointers */
  200918. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200919. png_ptr->zstream.next_out = png_ptr->zbuf;
  200920. }
  200921. }
  200922. else if (ret != Z_STREAM_END)
  200923. {
  200924. /* we got an error */
  200925. if (png_ptr->zstream.msg != NULL)
  200926. png_error(png_ptr, png_ptr->zstream.msg);
  200927. else
  200928. png_error(png_ptr, "zlib error");
  200929. }
  200930. } while (ret != Z_STREAM_END);
  200931. /* text length is number of buffers plus last buffer */
  200932. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  200933. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  200934. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  200935. return((int)text_len);
  200936. }
  200937. /* ship the compressed text out via chunk writes */
  200938. static void /* PRIVATE */
  200939. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  200940. {
  200941. int i;
  200942. /* handle the no-compression case */
  200943. if (comp->input)
  200944. {
  200945. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  200946. (png_size_t)comp->input_len);
  200947. return;
  200948. }
  200949. /* write saved output buffers, if any */
  200950. for (i = 0; i < comp->num_output_ptr; i++)
  200951. {
  200952. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  200953. png_ptr->zbuf_size);
  200954. png_free(png_ptr, comp->output_ptr[i]);
  200955. comp->output_ptr[i]=NULL;
  200956. }
  200957. if (comp->max_output_ptr != 0)
  200958. png_free(png_ptr, comp->output_ptr);
  200959. comp->output_ptr=NULL;
  200960. /* write anything left in zbuf */
  200961. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  200962. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  200963. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  200964. /* reset zlib for another zTXt/iTXt or image data */
  200965. deflateReset(&png_ptr->zstream);
  200966. png_ptr->zstream.data_type = Z_BINARY;
  200967. }
  200968. #endif
  200969. /* Write the IHDR chunk, and update the png_struct with the necessary
  200970. * information. Note that the rest of this code depends upon this
  200971. * information being correct.
  200972. */
  200973. void /* PRIVATE */
  200974. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  200975. int bit_depth, int color_type, int compression_type, int filter_type,
  200976. int interlace_type)
  200977. {
  200978. #ifdef PNG_USE_LOCAL_ARRAYS
  200979. PNG_IHDR;
  200980. #endif
  200981. png_byte buf[13]; /* buffer to store the IHDR info */
  200982. png_debug(1, "in png_write_IHDR\n");
  200983. /* Check that we have valid input data from the application info */
  200984. switch (color_type)
  200985. {
  200986. case PNG_COLOR_TYPE_GRAY:
  200987. switch (bit_depth)
  200988. {
  200989. case 1:
  200990. case 2:
  200991. case 4:
  200992. case 8:
  200993. case 16: png_ptr->channels = 1; break;
  200994. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  200995. }
  200996. break;
  200997. case PNG_COLOR_TYPE_RGB:
  200998. if (bit_depth != 8 && bit_depth != 16)
  200999. png_error(png_ptr, "Invalid bit depth for RGB image");
  201000. png_ptr->channels = 3;
  201001. break;
  201002. case PNG_COLOR_TYPE_PALETTE:
  201003. switch (bit_depth)
  201004. {
  201005. case 1:
  201006. case 2:
  201007. case 4:
  201008. case 8: png_ptr->channels = 1; break;
  201009. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  201010. }
  201011. break;
  201012. case PNG_COLOR_TYPE_GRAY_ALPHA:
  201013. if (bit_depth != 8 && bit_depth != 16)
  201014. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  201015. png_ptr->channels = 2;
  201016. break;
  201017. case PNG_COLOR_TYPE_RGB_ALPHA:
  201018. if (bit_depth != 8 && bit_depth != 16)
  201019. png_error(png_ptr, "Invalid bit depth for RGBA image");
  201020. png_ptr->channels = 4;
  201021. break;
  201022. default:
  201023. png_error(png_ptr, "Invalid image color type specified");
  201024. }
  201025. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  201026. {
  201027. png_warning(png_ptr, "Invalid compression type specified");
  201028. compression_type = PNG_COMPRESSION_TYPE_BASE;
  201029. }
  201030. /* Write filter_method 64 (intrapixel differencing) only if
  201031. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  201032. * 2. Libpng did not write a PNG signature (this filter_method is only
  201033. * used in PNG datastreams that are embedded in MNG datastreams) and
  201034. * 3. The application called png_permit_mng_features with a mask that
  201035. * included PNG_FLAG_MNG_FILTER_64 and
  201036. * 4. The filter_method is 64 and
  201037. * 5. The color_type is RGB or RGBA
  201038. */
  201039. if (
  201040. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201041. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  201042. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  201043. (color_type == PNG_COLOR_TYPE_RGB ||
  201044. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  201045. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  201046. #endif
  201047. filter_type != PNG_FILTER_TYPE_BASE)
  201048. {
  201049. png_warning(png_ptr, "Invalid filter type specified");
  201050. filter_type = PNG_FILTER_TYPE_BASE;
  201051. }
  201052. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201053. if (interlace_type != PNG_INTERLACE_NONE &&
  201054. interlace_type != PNG_INTERLACE_ADAM7)
  201055. {
  201056. png_warning(png_ptr, "Invalid interlace type specified");
  201057. interlace_type = PNG_INTERLACE_ADAM7;
  201058. }
  201059. #else
  201060. interlace_type=PNG_INTERLACE_NONE;
  201061. #endif
  201062. /* save off the relevent information */
  201063. png_ptr->bit_depth = (png_byte)bit_depth;
  201064. png_ptr->color_type = (png_byte)color_type;
  201065. png_ptr->interlaced = (png_byte)interlace_type;
  201066. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201067. png_ptr->filter_type = (png_byte)filter_type;
  201068. #endif
  201069. png_ptr->compression_type = (png_byte)compression_type;
  201070. png_ptr->width = width;
  201071. png_ptr->height = height;
  201072. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  201073. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  201074. /* set the usr info, so any transformations can modify it */
  201075. png_ptr->usr_width = png_ptr->width;
  201076. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  201077. png_ptr->usr_channels = png_ptr->channels;
  201078. /* pack the header information into the buffer */
  201079. png_save_uint_32(buf, width);
  201080. png_save_uint_32(buf + 4, height);
  201081. buf[8] = (png_byte)bit_depth;
  201082. buf[9] = (png_byte)color_type;
  201083. buf[10] = (png_byte)compression_type;
  201084. buf[11] = (png_byte)filter_type;
  201085. buf[12] = (png_byte)interlace_type;
  201086. /* write the chunk */
  201087. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  201088. /* initialize zlib with PNG info */
  201089. png_ptr->zstream.zalloc = png_zalloc;
  201090. png_ptr->zstream.zfree = png_zfree;
  201091. png_ptr->zstream.opaque = (voidpf)png_ptr;
  201092. if (!(png_ptr->do_filter))
  201093. {
  201094. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  201095. png_ptr->bit_depth < 8)
  201096. png_ptr->do_filter = PNG_FILTER_NONE;
  201097. else
  201098. png_ptr->do_filter = PNG_ALL_FILTERS;
  201099. }
  201100. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  201101. {
  201102. if (png_ptr->do_filter != PNG_FILTER_NONE)
  201103. png_ptr->zlib_strategy = Z_FILTERED;
  201104. else
  201105. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  201106. }
  201107. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  201108. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  201109. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  201110. png_ptr->zlib_mem_level = 8;
  201111. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  201112. png_ptr->zlib_window_bits = 15;
  201113. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  201114. png_ptr->zlib_method = 8;
  201115. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  201116. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  201117. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  201118. png_error(png_ptr, "zlib failed to initialize compressor");
  201119. png_ptr->zstream.next_out = png_ptr->zbuf;
  201120. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201121. /* libpng is not interested in zstream.data_type */
  201122. /* set it to a predefined value, to avoid its evaluation inside zlib */
  201123. png_ptr->zstream.data_type = Z_BINARY;
  201124. png_ptr->mode = PNG_HAVE_IHDR;
  201125. }
  201126. /* write the palette. We are careful not to trust png_color to be in the
  201127. * correct order for PNG, so people can redefine it to any convenient
  201128. * structure.
  201129. */
  201130. void /* PRIVATE */
  201131. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  201132. {
  201133. #ifdef PNG_USE_LOCAL_ARRAYS
  201134. PNG_PLTE;
  201135. #endif
  201136. png_uint_32 i;
  201137. png_colorp pal_ptr;
  201138. png_byte buf[3];
  201139. png_debug(1, "in png_write_PLTE\n");
  201140. if ((
  201141. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201142. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  201143. #endif
  201144. num_pal == 0) || num_pal > 256)
  201145. {
  201146. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  201147. {
  201148. png_error(png_ptr, "Invalid number of colors in palette");
  201149. }
  201150. else
  201151. {
  201152. png_warning(png_ptr, "Invalid number of colors in palette");
  201153. return;
  201154. }
  201155. }
  201156. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  201157. {
  201158. png_warning(png_ptr,
  201159. "Ignoring request to write a PLTE chunk in grayscale PNG");
  201160. return;
  201161. }
  201162. png_ptr->num_palette = (png_uint_16)num_pal;
  201163. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  201164. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  201165. #ifndef PNG_NO_POINTER_INDEXING
  201166. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  201167. {
  201168. buf[0] = pal_ptr->red;
  201169. buf[1] = pal_ptr->green;
  201170. buf[2] = pal_ptr->blue;
  201171. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  201172. }
  201173. #else
  201174. /* This is a little slower but some buggy compilers need to do this instead */
  201175. pal_ptr=palette;
  201176. for (i = 0; i < num_pal; i++)
  201177. {
  201178. buf[0] = pal_ptr[i].red;
  201179. buf[1] = pal_ptr[i].green;
  201180. buf[2] = pal_ptr[i].blue;
  201181. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  201182. }
  201183. #endif
  201184. png_write_chunk_end(png_ptr);
  201185. png_ptr->mode |= PNG_HAVE_PLTE;
  201186. }
  201187. /* write an IDAT chunk */
  201188. void /* PRIVATE */
  201189. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  201190. {
  201191. #ifdef PNG_USE_LOCAL_ARRAYS
  201192. PNG_IDAT;
  201193. #endif
  201194. png_debug(1, "in png_write_IDAT\n");
  201195. /* Optimize the CMF field in the zlib stream. */
  201196. /* This hack of the zlib stream is compliant to the stream specification. */
  201197. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  201198. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  201199. {
  201200. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  201201. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  201202. {
  201203. /* Avoid memory underflows and multiplication overflows. */
  201204. /* The conditions below are practically always satisfied;
  201205. however, they still must be checked. */
  201206. if (length >= 2 &&
  201207. png_ptr->height < 16384 && png_ptr->width < 16384)
  201208. {
  201209. png_uint_32 uncompressed_idat_size = png_ptr->height *
  201210. ((png_ptr->width *
  201211. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  201212. unsigned int z_cinfo = z_cmf >> 4;
  201213. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  201214. while (uncompressed_idat_size <= half_z_window_size &&
  201215. half_z_window_size >= 256)
  201216. {
  201217. z_cinfo--;
  201218. half_z_window_size >>= 1;
  201219. }
  201220. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  201221. if (data[0] != (png_byte)z_cmf)
  201222. {
  201223. data[0] = (png_byte)z_cmf;
  201224. data[1] &= 0xe0;
  201225. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  201226. }
  201227. }
  201228. }
  201229. else
  201230. png_error(png_ptr,
  201231. "Invalid zlib compression method or flags in IDAT");
  201232. }
  201233. png_write_chunk(png_ptr, png_IDAT, data, length);
  201234. png_ptr->mode |= PNG_HAVE_IDAT;
  201235. }
  201236. /* write an IEND chunk */
  201237. void /* PRIVATE */
  201238. png_write_IEND(png_structp png_ptr)
  201239. {
  201240. #ifdef PNG_USE_LOCAL_ARRAYS
  201241. PNG_IEND;
  201242. #endif
  201243. png_debug(1, "in png_write_IEND\n");
  201244. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  201245. (png_size_t)0);
  201246. png_ptr->mode |= PNG_HAVE_IEND;
  201247. }
  201248. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  201249. /* write a gAMA chunk */
  201250. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201251. void /* PRIVATE */
  201252. png_write_gAMA(png_structp png_ptr, double file_gamma)
  201253. {
  201254. #ifdef PNG_USE_LOCAL_ARRAYS
  201255. PNG_gAMA;
  201256. #endif
  201257. png_uint_32 igamma;
  201258. png_byte buf[4];
  201259. png_debug(1, "in png_write_gAMA\n");
  201260. /* file_gamma is saved in 1/100,000ths */
  201261. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  201262. png_save_uint_32(buf, igamma);
  201263. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  201264. }
  201265. #endif
  201266. #ifdef PNG_FIXED_POINT_SUPPORTED
  201267. void /* PRIVATE */
  201268. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  201269. {
  201270. #ifdef PNG_USE_LOCAL_ARRAYS
  201271. PNG_gAMA;
  201272. #endif
  201273. png_byte buf[4];
  201274. png_debug(1, "in png_write_gAMA\n");
  201275. /* file_gamma is saved in 1/100,000ths */
  201276. png_save_uint_32(buf, (png_uint_32)file_gamma);
  201277. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  201278. }
  201279. #endif
  201280. #endif
  201281. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  201282. /* write a sRGB chunk */
  201283. void /* PRIVATE */
  201284. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  201285. {
  201286. #ifdef PNG_USE_LOCAL_ARRAYS
  201287. PNG_sRGB;
  201288. #endif
  201289. png_byte buf[1];
  201290. png_debug(1, "in png_write_sRGB\n");
  201291. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  201292. png_warning(png_ptr,
  201293. "Invalid sRGB rendering intent specified");
  201294. buf[0]=(png_byte)srgb_intent;
  201295. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  201296. }
  201297. #endif
  201298. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  201299. /* write an iCCP chunk */
  201300. void /* PRIVATE */
  201301. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  201302. png_charp profile, int profile_len)
  201303. {
  201304. #ifdef PNG_USE_LOCAL_ARRAYS
  201305. PNG_iCCP;
  201306. #endif
  201307. png_size_t name_len;
  201308. png_charp new_name;
  201309. compression_state comp;
  201310. int embedded_profile_len = 0;
  201311. png_debug(1, "in png_write_iCCP\n");
  201312. comp.num_output_ptr = 0;
  201313. comp.max_output_ptr = 0;
  201314. comp.output_ptr = NULL;
  201315. comp.input = NULL;
  201316. comp.input_len = 0;
  201317. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  201318. &new_name)) == 0)
  201319. {
  201320. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  201321. return;
  201322. }
  201323. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  201324. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  201325. if (profile == NULL)
  201326. profile_len = 0;
  201327. if (profile_len > 3)
  201328. embedded_profile_len =
  201329. ((*( (png_bytep)profile ))<<24) |
  201330. ((*( (png_bytep)profile+1))<<16) |
  201331. ((*( (png_bytep)profile+2))<< 8) |
  201332. ((*( (png_bytep)profile+3)) );
  201333. if (profile_len < embedded_profile_len)
  201334. {
  201335. png_warning(png_ptr,
  201336. "Embedded profile length too large in iCCP chunk");
  201337. return;
  201338. }
  201339. if (profile_len > embedded_profile_len)
  201340. {
  201341. png_warning(png_ptr,
  201342. "Truncating profile to actual length in iCCP chunk");
  201343. profile_len = embedded_profile_len;
  201344. }
  201345. if (profile_len)
  201346. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  201347. PNG_COMPRESSION_TYPE_BASE, &comp);
  201348. /* make sure we include the NULL after the name and the compression type */
  201349. png_write_chunk_start(png_ptr, png_iCCP,
  201350. (png_uint_32)name_len+profile_len+2);
  201351. new_name[name_len+1]=0x00;
  201352. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  201353. if (profile_len)
  201354. png_write_compressed_data_out(png_ptr, &comp);
  201355. png_write_chunk_end(png_ptr);
  201356. png_free(png_ptr, new_name);
  201357. }
  201358. #endif
  201359. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  201360. /* write a sPLT chunk */
  201361. void /* PRIVATE */
  201362. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  201363. {
  201364. #ifdef PNG_USE_LOCAL_ARRAYS
  201365. PNG_sPLT;
  201366. #endif
  201367. png_size_t name_len;
  201368. png_charp new_name;
  201369. png_byte entrybuf[10];
  201370. int entry_size = (spalette->depth == 8 ? 6 : 10);
  201371. int palette_size = entry_size * spalette->nentries;
  201372. png_sPLT_entryp ep;
  201373. #ifdef PNG_NO_POINTER_INDEXING
  201374. int i;
  201375. #endif
  201376. png_debug(1, "in png_write_sPLT\n");
  201377. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  201378. spalette->name, &new_name))==0)
  201379. {
  201380. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  201381. return;
  201382. }
  201383. /* make sure we include the NULL after the name */
  201384. png_write_chunk_start(png_ptr, png_sPLT,
  201385. (png_uint_32)(name_len + 2 + palette_size));
  201386. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  201387. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  201388. /* loop through each palette entry, writing appropriately */
  201389. #ifndef PNG_NO_POINTER_INDEXING
  201390. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  201391. {
  201392. if (spalette->depth == 8)
  201393. {
  201394. entrybuf[0] = (png_byte)ep->red;
  201395. entrybuf[1] = (png_byte)ep->green;
  201396. entrybuf[2] = (png_byte)ep->blue;
  201397. entrybuf[3] = (png_byte)ep->alpha;
  201398. png_save_uint_16(entrybuf + 4, ep->frequency);
  201399. }
  201400. else
  201401. {
  201402. png_save_uint_16(entrybuf + 0, ep->red);
  201403. png_save_uint_16(entrybuf + 2, ep->green);
  201404. png_save_uint_16(entrybuf + 4, ep->blue);
  201405. png_save_uint_16(entrybuf + 6, ep->alpha);
  201406. png_save_uint_16(entrybuf + 8, ep->frequency);
  201407. }
  201408. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  201409. }
  201410. #else
  201411. ep=spalette->entries;
  201412. for (i=0; i>spalette->nentries; i++)
  201413. {
  201414. if (spalette->depth == 8)
  201415. {
  201416. entrybuf[0] = (png_byte)ep[i].red;
  201417. entrybuf[1] = (png_byte)ep[i].green;
  201418. entrybuf[2] = (png_byte)ep[i].blue;
  201419. entrybuf[3] = (png_byte)ep[i].alpha;
  201420. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  201421. }
  201422. else
  201423. {
  201424. png_save_uint_16(entrybuf + 0, ep[i].red);
  201425. png_save_uint_16(entrybuf + 2, ep[i].green);
  201426. png_save_uint_16(entrybuf + 4, ep[i].blue);
  201427. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  201428. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  201429. }
  201430. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  201431. }
  201432. #endif
  201433. png_write_chunk_end(png_ptr);
  201434. png_free(png_ptr, new_name);
  201435. }
  201436. #endif
  201437. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  201438. /* write the sBIT chunk */
  201439. void /* PRIVATE */
  201440. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  201441. {
  201442. #ifdef PNG_USE_LOCAL_ARRAYS
  201443. PNG_sBIT;
  201444. #endif
  201445. png_byte buf[4];
  201446. png_size_t size;
  201447. png_debug(1, "in png_write_sBIT\n");
  201448. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  201449. if (color_type & PNG_COLOR_MASK_COLOR)
  201450. {
  201451. png_byte maxbits;
  201452. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  201453. png_ptr->usr_bit_depth);
  201454. if (sbit->red == 0 || sbit->red > maxbits ||
  201455. sbit->green == 0 || sbit->green > maxbits ||
  201456. sbit->blue == 0 || sbit->blue > maxbits)
  201457. {
  201458. png_warning(png_ptr, "Invalid sBIT depth specified");
  201459. return;
  201460. }
  201461. buf[0] = sbit->red;
  201462. buf[1] = sbit->green;
  201463. buf[2] = sbit->blue;
  201464. size = 3;
  201465. }
  201466. else
  201467. {
  201468. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  201469. {
  201470. png_warning(png_ptr, "Invalid sBIT depth specified");
  201471. return;
  201472. }
  201473. buf[0] = sbit->gray;
  201474. size = 1;
  201475. }
  201476. if (color_type & PNG_COLOR_MASK_ALPHA)
  201477. {
  201478. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  201479. {
  201480. png_warning(png_ptr, "Invalid sBIT depth specified");
  201481. return;
  201482. }
  201483. buf[size++] = sbit->alpha;
  201484. }
  201485. png_write_chunk(png_ptr, png_sBIT, buf, size);
  201486. }
  201487. #endif
  201488. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  201489. /* write the cHRM chunk */
  201490. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201491. void /* PRIVATE */
  201492. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  201493. double red_x, double red_y, double green_x, double green_y,
  201494. double blue_x, double blue_y)
  201495. {
  201496. #ifdef PNG_USE_LOCAL_ARRAYS
  201497. PNG_cHRM;
  201498. #endif
  201499. png_byte buf[32];
  201500. png_uint_32 itemp;
  201501. png_debug(1, "in png_write_cHRM\n");
  201502. /* each value is saved in 1/100,000ths */
  201503. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  201504. white_x + white_y > 1.0)
  201505. {
  201506. png_warning(png_ptr, "Invalid cHRM white point specified");
  201507. #if !defined(PNG_NO_CONSOLE_IO)
  201508. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  201509. #endif
  201510. return;
  201511. }
  201512. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  201513. png_save_uint_32(buf, itemp);
  201514. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  201515. png_save_uint_32(buf + 4, itemp);
  201516. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  201517. {
  201518. png_warning(png_ptr, "Invalid cHRM red point specified");
  201519. return;
  201520. }
  201521. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  201522. png_save_uint_32(buf + 8, itemp);
  201523. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  201524. png_save_uint_32(buf + 12, itemp);
  201525. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  201526. {
  201527. png_warning(png_ptr, "Invalid cHRM green point specified");
  201528. return;
  201529. }
  201530. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  201531. png_save_uint_32(buf + 16, itemp);
  201532. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  201533. png_save_uint_32(buf + 20, itemp);
  201534. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  201535. {
  201536. png_warning(png_ptr, "Invalid cHRM blue point specified");
  201537. return;
  201538. }
  201539. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  201540. png_save_uint_32(buf + 24, itemp);
  201541. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  201542. png_save_uint_32(buf + 28, itemp);
  201543. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201544. }
  201545. #endif
  201546. #ifdef PNG_FIXED_POINT_SUPPORTED
  201547. void /* PRIVATE */
  201548. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  201549. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  201550. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  201551. png_fixed_point blue_y)
  201552. {
  201553. #ifdef PNG_USE_LOCAL_ARRAYS
  201554. PNG_cHRM;
  201555. #endif
  201556. png_byte buf[32];
  201557. png_debug(1, "in png_write_cHRM\n");
  201558. /* each value is saved in 1/100,000ths */
  201559. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  201560. {
  201561. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  201562. #if !defined(PNG_NO_CONSOLE_IO)
  201563. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  201564. #endif
  201565. return;
  201566. }
  201567. png_save_uint_32(buf, (png_uint_32)white_x);
  201568. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  201569. if (red_x + red_y > 100000L)
  201570. {
  201571. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  201572. return;
  201573. }
  201574. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  201575. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  201576. if (green_x + green_y > 100000L)
  201577. {
  201578. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  201579. return;
  201580. }
  201581. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  201582. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  201583. if (blue_x + blue_y > 100000L)
  201584. {
  201585. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  201586. return;
  201587. }
  201588. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  201589. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  201590. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201591. }
  201592. #endif
  201593. #endif
  201594. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  201595. /* write the tRNS chunk */
  201596. void /* PRIVATE */
  201597. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  201598. int num_trans, int color_type)
  201599. {
  201600. #ifdef PNG_USE_LOCAL_ARRAYS
  201601. PNG_tRNS;
  201602. #endif
  201603. png_byte buf[6];
  201604. png_debug(1, "in png_write_tRNS\n");
  201605. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201606. {
  201607. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  201608. {
  201609. png_warning(png_ptr,"Invalid number of transparent colors specified");
  201610. return;
  201611. }
  201612. /* write the chunk out as it is */
  201613. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  201614. }
  201615. else if (color_type == PNG_COLOR_TYPE_GRAY)
  201616. {
  201617. /* one 16 bit value */
  201618. if(tran->gray >= (1 << png_ptr->bit_depth))
  201619. {
  201620. png_warning(png_ptr,
  201621. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  201622. return;
  201623. }
  201624. png_save_uint_16(buf, tran->gray);
  201625. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  201626. }
  201627. else if (color_type == PNG_COLOR_TYPE_RGB)
  201628. {
  201629. /* three 16 bit values */
  201630. png_save_uint_16(buf, tran->red);
  201631. png_save_uint_16(buf + 2, tran->green);
  201632. png_save_uint_16(buf + 4, tran->blue);
  201633. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201634. {
  201635. png_warning(png_ptr,
  201636. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  201637. return;
  201638. }
  201639. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  201640. }
  201641. else
  201642. {
  201643. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  201644. }
  201645. }
  201646. #endif
  201647. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  201648. /* write the background chunk */
  201649. void /* PRIVATE */
  201650. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  201651. {
  201652. #ifdef PNG_USE_LOCAL_ARRAYS
  201653. PNG_bKGD;
  201654. #endif
  201655. png_byte buf[6];
  201656. png_debug(1, "in png_write_bKGD\n");
  201657. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201658. {
  201659. if (
  201660. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201661. (png_ptr->num_palette ||
  201662. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  201663. #endif
  201664. back->index > png_ptr->num_palette)
  201665. {
  201666. png_warning(png_ptr, "Invalid background palette index");
  201667. return;
  201668. }
  201669. buf[0] = back->index;
  201670. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  201671. }
  201672. else if (color_type & PNG_COLOR_MASK_COLOR)
  201673. {
  201674. png_save_uint_16(buf, back->red);
  201675. png_save_uint_16(buf + 2, back->green);
  201676. png_save_uint_16(buf + 4, back->blue);
  201677. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201678. {
  201679. png_warning(png_ptr,
  201680. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  201681. return;
  201682. }
  201683. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  201684. }
  201685. else
  201686. {
  201687. if(back->gray >= (1 << png_ptr->bit_depth))
  201688. {
  201689. png_warning(png_ptr,
  201690. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  201691. return;
  201692. }
  201693. png_save_uint_16(buf, back->gray);
  201694. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  201695. }
  201696. }
  201697. #endif
  201698. #if defined(PNG_WRITE_hIST_SUPPORTED)
  201699. /* write the histogram */
  201700. void /* PRIVATE */
  201701. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  201702. {
  201703. #ifdef PNG_USE_LOCAL_ARRAYS
  201704. PNG_hIST;
  201705. #endif
  201706. int i;
  201707. png_byte buf[3];
  201708. png_debug(1, "in png_write_hIST\n");
  201709. if (num_hist > (int)png_ptr->num_palette)
  201710. {
  201711. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  201712. png_ptr->num_palette);
  201713. png_warning(png_ptr, "Invalid number of histogram entries specified");
  201714. return;
  201715. }
  201716. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  201717. for (i = 0; i < num_hist; i++)
  201718. {
  201719. png_save_uint_16(buf, hist[i]);
  201720. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  201721. }
  201722. png_write_chunk_end(png_ptr);
  201723. }
  201724. #endif
  201725. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  201726. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  201727. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  201728. * and if invalid, correct the keyword rather than discarding the entire
  201729. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  201730. * length, forbids leading or trailing whitespace, multiple internal spaces,
  201731. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  201732. *
  201733. * The new_key is allocated to hold the corrected keyword and must be freed
  201734. * by the calling routine. This avoids problems with trying to write to
  201735. * static keywords without having to have duplicate copies of the strings.
  201736. */
  201737. png_size_t /* PRIVATE */
  201738. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  201739. {
  201740. png_size_t key_len;
  201741. png_charp kp, dp;
  201742. int kflag;
  201743. int kwarn=0;
  201744. png_debug(1, "in png_check_keyword\n");
  201745. *new_key = NULL;
  201746. if (key == NULL || (key_len = png_strlen(key)) == 0)
  201747. {
  201748. png_warning(png_ptr, "zero length keyword");
  201749. return ((png_size_t)0);
  201750. }
  201751. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  201752. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  201753. if (*new_key == NULL)
  201754. {
  201755. png_warning(png_ptr, "Out of memory while procesing keyword");
  201756. return ((png_size_t)0);
  201757. }
  201758. /* Replace non-printing characters with a blank and print a warning */
  201759. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  201760. {
  201761. if ((png_byte)*kp < 0x20 ||
  201762. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  201763. {
  201764. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  201765. char msg[40];
  201766. png_snprintf(msg, 40,
  201767. "invalid keyword character 0x%02X", (png_byte)*kp);
  201768. png_warning(png_ptr, msg);
  201769. #else
  201770. png_warning(png_ptr, "invalid character in keyword");
  201771. #endif
  201772. *dp = ' ';
  201773. }
  201774. else
  201775. {
  201776. *dp = *kp;
  201777. }
  201778. }
  201779. *dp = '\0';
  201780. /* Remove any trailing white space. */
  201781. kp = *new_key + key_len - 1;
  201782. if (*kp == ' ')
  201783. {
  201784. png_warning(png_ptr, "trailing spaces removed from keyword");
  201785. while (*kp == ' ')
  201786. {
  201787. *(kp--) = '\0';
  201788. key_len--;
  201789. }
  201790. }
  201791. /* Remove any leading white space. */
  201792. kp = *new_key;
  201793. if (*kp == ' ')
  201794. {
  201795. png_warning(png_ptr, "leading spaces removed from keyword");
  201796. while (*kp == ' ')
  201797. {
  201798. kp++;
  201799. key_len--;
  201800. }
  201801. }
  201802. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  201803. /* Remove multiple internal spaces. */
  201804. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  201805. {
  201806. if (*kp == ' ' && kflag == 0)
  201807. {
  201808. *(dp++) = *kp;
  201809. kflag = 1;
  201810. }
  201811. else if (*kp == ' ')
  201812. {
  201813. key_len--;
  201814. kwarn=1;
  201815. }
  201816. else
  201817. {
  201818. *(dp++) = *kp;
  201819. kflag = 0;
  201820. }
  201821. }
  201822. *dp = '\0';
  201823. if(kwarn)
  201824. png_warning(png_ptr, "extra interior spaces removed from keyword");
  201825. if (key_len == 0)
  201826. {
  201827. png_free(png_ptr, *new_key);
  201828. *new_key=NULL;
  201829. png_warning(png_ptr, "Zero length keyword");
  201830. }
  201831. if (key_len > 79)
  201832. {
  201833. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  201834. new_key[79] = '\0';
  201835. key_len = 79;
  201836. }
  201837. return (key_len);
  201838. }
  201839. #endif
  201840. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  201841. /* write a tEXt chunk */
  201842. void /* PRIVATE */
  201843. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  201844. png_size_t text_len)
  201845. {
  201846. #ifdef PNG_USE_LOCAL_ARRAYS
  201847. PNG_tEXt;
  201848. #endif
  201849. png_size_t key_len;
  201850. png_charp new_key;
  201851. png_debug(1, "in png_write_tEXt\n");
  201852. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201853. {
  201854. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  201855. return;
  201856. }
  201857. if (text == NULL || *text == '\0')
  201858. text_len = 0;
  201859. else
  201860. text_len = png_strlen(text);
  201861. /* make sure we include the 0 after the key */
  201862. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  201863. /*
  201864. * We leave it to the application to meet PNG-1.0 requirements on the
  201865. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  201866. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  201867. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  201868. */
  201869. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201870. if (text_len)
  201871. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  201872. png_write_chunk_end(png_ptr);
  201873. png_free(png_ptr, new_key);
  201874. }
  201875. #endif
  201876. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  201877. /* write a compressed text chunk */
  201878. void /* PRIVATE */
  201879. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  201880. png_size_t text_len, int compression)
  201881. {
  201882. #ifdef PNG_USE_LOCAL_ARRAYS
  201883. PNG_zTXt;
  201884. #endif
  201885. png_size_t key_len;
  201886. char buf[1];
  201887. png_charp new_key;
  201888. compression_state comp;
  201889. png_debug(1, "in png_write_zTXt\n");
  201890. comp.num_output_ptr = 0;
  201891. comp.max_output_ptr = 0;
  201892. comp.output_ptr = NULL;
  201893. comp.input = NULL;
  201894. comp.input_len = 0;
  201895. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201896. {
  201897. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  201898. return;
  201899. }
  201900. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  201901. {
  201902. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  201903. png_free(png_ptr, new_key);
  201904. return;
  201905. }
  201906. text_len = png_strlen(text);
  201907. /* compute the compressed data; do it now for the length */
  201908. text_len = png_text_compress(png_ptr, text, text_len, compression,
  201909. &comp);
  201910. /* write start of chunk */
  201911. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  201912. (key_len+text_len+2));
  201913. /* write key */
  201914. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201915. png_free(png_ptr, new_key);
  201916. buf[0] = (png_byte)compression;
  201917. /* write compression */
  201918. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  201919. /* write the compressed data */
  201920. png_write_compressed_data_out(png_ptr, &comp);
  201921. /* close the chunk */
  201922. png_write_chunk_end(png_ptr);
  201923. }
  201924. #endif
  201925. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  201926. /* write an iTXt chunk */
  201927. void /* PRIVATE */
  201928. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  201929. png_charp lang, png_charp lang_key, png_charp text)
  201930. {
  201931. #ifdef PNG_USE_LOCAL_ARRAYS
  201932. PNG_iTXt;
  201933. #endif
  201934. png_size_t lang_len, key_len, lang_key_len, text_len;
  201935. png_charp new_lang, new_key;
  201936. png_byte cbuf[2];
  201937. compression_state comp;
  201938. png_debug(1, "in png_write_iTXt\n");
  201939. comp.num_output_ptr = 0;
  201940. comp.max_output_ptr = 0;
  201941. comp.output_ptr = NULL;
  201942. comp.input = NULL;
  201943. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  201944. {
  201945. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  201946. return;
  201947. }
  201948. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  201949. {
  201950. png_warning(png_ptr, "Empty language field in iTXt chunk");
  201951. new_lang = NULL;
  201952. lang_len = 0;
  201953. }
  201954. if (lang_key == NULL)
  201955. lang_key_len = 0;
  201956. else
  201957. lang_key_len = png_strlen(lang_key);
  201958. if (text == NULL)
  201959. text_len = 0;
  201960. else
  201961. text_len = png_strlen(text);
  201962. /* compute the compressed data; do it now for the length */
  201963. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  201964. &comp);
  201965. /* make sure we include the compression flag, the compression byte,
  201966. * and the NULs after the key, lang, and lang_key parts */
  201967. png_write_chunk_start(png_ptr, png_iTXt,
  201968. (png_uint_32)(
  201969. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  201970. + key_len
  201971. + lang_len
  201972. + lang_key_len
  201973. + text_len));
  201974. /*
  201975. * We leave it to the application to meet PNG-1.0 requirements on the
  201976. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  201977. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  201978. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  201979. */
  201980. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  201981. /* set the compression flag */
  201982. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  201983. compression == PNG_TEXT_COMPRESSION_NONE)
  201984. cbuf[0] = 0;
  201985. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  201986. cbuf[0] = 1;
  201987. /* set the compression method */
  201988. cbuf[1] = 0;
  201989. png_write_chunk_data(png_ptr, cbuf, 2);
  201990. cbuf[0] = 0;
  201991. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  201992. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  201993. png_write_compressed_data_out(png_ptr, &comp);
  201994. png_write_chunk_end(png_ptr);
  201995. png_free(png_ptr, new_key);
  201996. if (new_lang)
  201997. png_free(png_ptr, new_lang);
  201998. }
  201999. #endif
  202000. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  202001. /* write the oFFs chunk */
  202002. void /* PRIVATE */
  202003. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  202004. int unit_type)
  202005. {
  202006. #ifdef PNG_USE_LOCAL_ARRAYS
  202007. PNG_oFFs;
  202008. #endif
  202009. png_byte buf[9];
  202010. png_debug(1, "in png_write_oFFs\n");
  202011. if (unit_type >= PNG_OFFSET_LAST)
  202012. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  202013. png_save_int_32(buf, x_offset);
  202014. png_save_int_32(buf + 4, y_offset);
  202015. buf[8] = (png_byte)unit_type;
  202016. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  202017. }
  202018. #endif
  202019. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  202020. /* write the pCAL chunk (described in the PNG extensions document) */
  202021. void /* PRIVATE */
  202022. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  202023. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  202024. {
  202025. #ifdef PNG_USE_LOCAL_ARRAYS
  202026. PNG_pCAL;
  202027. #endif
  202028. png_size_t purpose_len, units_len, total_len;
  202029. png_uint_32p params_len;
  202030. png_byte buf[10];
  202031. png_charp new_purpose;
  202032. int i;
  202033. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  202034. if (type >= PNG_EQUATION_LAST)
  202035. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  202036. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  202037. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  202038. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  202039. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  202040. total_len = purpose_len + units_len + 10;
  202041. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  202042. *png_sizeof(png_uint_32)));
  202043. /* Find the length of each parameter, making sure we don't count the
  202044. null terminator for the last parameter. */
  202045. for (i = 0; i < nparams; i++)
  202046. {
  202047. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  202048. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  202049. total_len += (png_size_t)params_len[i];
  202050. }
  202051. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  202052. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  202053. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  202054. png_save_int_32(buf, X0);
  202055. png_save_int_32(buf + 4, X1);
  202056. buf[8] = (png_byte)type;
  202057. buf[9] = (png_byte)nparams;
  202058. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  202059. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  202060. png_free(png_ptr, new_purpose);
  202061. for (i = 0; i < nparams; i++)
  202062. {
  202063. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  202064. (png_size_t)params_len[i]);
  202065. }
  202066. png_free(png_ptr, params_len);
  202067. png_write_chunk_end(png_ptr);
  202068. }
  202069. #endif
  202070. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  202071. /* write the sCAL chunk */
  202072. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  202073. void /* PRIVATE */
  202074. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  202075. {
  202076. #ifdef PNG_USE_LOCAL_ARRAYS
  202077. PNG_sCAL;
  202078. #endif
  202079. char buf[64];
  202080. png_size_t total_len;
  202081. png_debug(1, "in png_write_sCAL\n");
  202082. buf[0] = (char)unit;
  202083. #if defined(_WIN32_WCE)
  202084. /* sprintf() function is not supported on WindowsCE */
  202085. {
  202086. wchar_t wc_buf[32];
  202087. size_t wc_len;
  202088. swprintf(wc_buf, TEXT("%12.12e"), width);
  202089. wc_len = wcslen(wc_buf);
  202090. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  202091. total_len = wc_len + 2;
  202092. swprintf(wc_buf, TEXT("%12.12e"), height);
  202093. wc_len = wcslen(wc_buf);
  202094. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  202095. NULL, NULL);
  202096. total_len += wc_len;
  202097. }
  202098. #else
  202099. png_snprintf(buf + 1, 63, "%12.12e", width);
  202100. total_len = 1 + png_strlen(buf + 1) + 1;
  202101. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  202102. total_len += png_strlen(buf + total_len);
  202103. #endif
  202104. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  202105. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  202106. }
  202107. #else
  202108. #ifdef PNG_FIXED_POINT_SUPPORTED
  202109. void /* PRIVATE */
  202110. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  202111. png_charp height)
  202112. {
  202113. #ifdef PNG_USE_LOCAL_ARRAYS
  202114. PNG_sCAL;
  202115. #endif
  202116. png_byte buf[64];
  202117. png_size_t wlen, hlen, total_len;
  202118. png_debug(1, "in png_write_sCAL_s\n");
  202119. wlen = png_strlen(width);
  202120. hlen = png_strlen(height);
  202121. total_len = wlen + hlen + 2;
  202122. if (total_len > 64)
  202123. {
  202124. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  202125. return;
  202126. }
  202127. buf[0] = (png_byte)unit;
  202128. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  202129. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  202130. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  202131. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  202132. }
  202133. #endif
  202134. #endif
  202135. #endif
  202136. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  202137. /* write the pHYs chunk */
  202138. void /* PRIVATE */
  202139. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  202140. png_uint_32 y_pixels_per_unit,
  202141. int unit_type)
  202142. {
  202143. #ifdef PNG_USE_LOCAL_ARRAYS
  202144. PNG_pHYs;
  202145. #endif
  202146. png_byte buf[9];
  202147. png_debug(1, "in png_write_pHYs\n");
  202148. if (unit_type >= PNG_RESOLUTION_LAST)
  202149. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  202150. png_save_uint_32(buf, x_pixels_per_unit);
  202151. png_save_uint_32(buf + 4, y_pixels_per_unit);
  202152. buf[8] = (png_byte)unit_type;
  202153. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  202154. }
  202155. #endif
  202156. #if defined(PNG_WRITE_tIME_SUPPORTED)
  202157. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  202158. * or png_convert_from_time_t(), or fill in the structure yourself.
  202159. */
  202160. void /* PRIVATE */
  202161. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  202162. {
  202163. #ifdef PNG_USE_LOCAL_ARRAYS
  202164. PNG_tIME;
  202165. #endif
  202166. png_byte buf[7];
  202167. png_debug(1, "in png_write_tIME\n");
  202168. if (mod_time->month > 12 || mod_time->month < 1 ||
  202169. mod_time->day > 31 || mod_time->day < 1 ||
  202170. mod_time->hour > 23 || mod_time->second > 60)
  202171. {
  202172. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  202173. return;
  202174. }
  202175. png_save_uint_16(buf, mod_time->year);
  202176. buf[2] = mod_time->month;
  202177. buf[3] = mod_time->day;
  202178. buf[4] = mod_time->hour;
  202179. buf[5] = mod_time->minute;
  202180. buf[6] = mod_time->second;
  202181. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  202182. }
  202183. #endif
  202184. /* initializes the row writing capability of libpng */
  202185. void /* PRIVATE */
  202186. png_write_start_row(png_structp png_ptr)
  202187. {
  202188. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202189. #ifdef PNG_USE_LOCAL_ARRAYS
  202190. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202191. /* start of interlace block */
  202192. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202193. /* offset to next interlace block */
  202194. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202195. /* start of interlace block in the y direction */
  202196. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  202197. /* offset to next interlace block in the y direction */
  202198. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  202199. #endif
  202200. #endif
  202201. png_size_t buf_size;
  202202. png_debug(1, "in png_write_start_row\n");
  202203. buf_size = (png_size_t)(PNG_ROWBYTES(
  202204. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  202205. /* set up row buffer */
  202206. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  202207. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  202208. #ifndef PNG_NO_WRITE_FILTERING
  202209. /* set up filtering buffer, if using this filter */
  202210. if (png_ptr->do_filter & PNG_FILTER_SUB)
  202211. {
  202212. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  202213. (png_ptr->rowbytes + 1));
  202214. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  202215. }
  202216. /* We only need to keep the previous row if we are using one of these. */
  202217. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  202218. {
  202219. /* set up previous row buffer */
  202220. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  202221. png_memset(png_ptr->prev_row, 0, buf_size);
  202222. if (png_ptr->do_filter & PNG_FILTER_UP)
  202223. {
  202224. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  202225. (png_ptr->rowbytes + 1));
  202226. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  202227. }
  202228. if (png_ptr->do_filter & PNG_FILTER_AVG)
  202229. {
  202230. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  202231. (png_ptr->rowbytes + 1));
  202232. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  202233. }
  202234. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  202235. {
  202236. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  202237. (png_ptr->rowbytes + 1));
  202238. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  202239. }
  202240. #endif /* PNG_NO_WRITE_FILTERING */
  202241. }
  202242. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202243. /* if interlaced, we need to set up width and height of pass */
  202244. if (png_ptr->interlaced)
  202245. {
  202246. if (!(png_ptr->transformations & PNG_INTERLACE))
  202247. {
  202248. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  202249. png_pass_ystart[0]) / png_pass_yinc[0];
  202250. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  202251. png_pass_start[0]) / png_pass_inc[0];
  202252. }
  202253. else
  202254. {
  202255. png_ptr->num_rows = png_ptr->height;
  202256. png_ptr->usr_width = png_ptr->width;
  202257. }
  202258. }
  202259. else
  202260. #endif
  202261. {
  202262. png_ptr->num_rows = png_ptr->height;
  202263. png_ptr->usr_width = png_ptr->width;
  202264. }
  202265. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202266. png_ptr->zstream.next_out = png_ptr->zbuf;
  202267. }
  202268. /* Internal use only. Called when finished processing a row of data. */
  202269. void /* PRIVATE */
  202270. png_write_finish_row(png_structp png_ptr)
  202271. {
  202272. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202273. #ifdef PNG_USE_LOCAL_ARRAYS
  202274. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202275. /* start of interlace block */
  202276. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202277. /* offset to next interlace block */
  202278. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202279. /* start of interlace block in the y direction */
  202280. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  202281. /* offset to next interlace block in the y direction */
  202282. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  202283. #endif
  202284. #endif
  202285. int ret;
  202286. png_debug(1, "in png_write_finish_row\n");
  202287. /* next row */
  202288. png_ptr->row_number++;
  202289. /* see if we are done */
  202290. if (png_ptr->row_number < png_ptr->num_rows)
  202291. return;
  202292. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202293. /* if interlaced, go to next pass */
  202294. if (png_ptr->interlaced)
  202295. {
  202296. png_ptr->row_number = 0;
  202297. if (png_ptr->transformations & PNG_INTERLACE)
  202298. {
  202299. png_ptr->pass++;
  202300. }
  202301. else
  202302. {
  202303. /* loop until we find a non-zero width or height pass */
  202304. do
  202305. {
  202306. png_ptr->pass++;
  202307. if (png_ptr->pass >= 7)
  202308. break;
  202309. png_ptr->usr_width = (png_ptr->width +
  202310. png_pass_inc[png_ptr->pass] - 1 -
  202311. png_pass_start[png_ptr->pass]) /
  202312. png_pass_inc[png_ptr->pass];
  202313. png_ptr->num_rows = (png_ptr->height +
  202314. png_pass_yinc[png_ptr->pass] - 1 -
  202315. png_pass_ystart[png_ptr->pass]) /
  202316. png_pass_yinc[png_ptr->pass];
  202317. if (png_ptr->transformations & PNG_INTERLACE)
  202318. break;
  202319. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  202320. }
  202321. /* reset the row above the image for the next pass */
  202322. if (png_ptr->pass < 7)
  202323. {
  202324. if (png_ptr->prev_row != NULL)
  202325. png_memset(png_ptr->prev_row, 0,
  202326. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  202327. png_ptr->usr_bit_depth,png_ptr->width))+1);
  202328. return;
  202329. }
  202330. }
  202331. #endif
  202332. /* if we get here, we've just written the last row, so we need
  202333. to flush the compressor */
  202334. do
  202335. {
  202336. /* tell the compressor we are done */
  202337. ret = deflate(&png_ptr->zstream, Z_FINISH);
  202338. /* check for an error */
  202339. if (ret == Z_OK)
  202340. {
  202341. /* check to see if we need more room */
  202342. if (!(png_ptr->zstream.avail_out))
  202343. {
  202344. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  202345. png_ptr->zstream.next_out = png_ptr->zbuf;
  202346. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202347. }
  202348. }
  202349. else if (ret != Z_STREAM_END)
  202350. {
  202351. if (png_ptr->zstream.msg != NULL)
  202352. png_error(png_ptr, png_ptr->zstream.msg);
  202353. else
  202354. png_error(png_ptr, "zlib error");
  202355. }
  202356. } while (ret != Z_STREAM_END);
  202357. /* write any extra space */
  202358. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  202359. {
  202360. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  202361. png_ptr->zstream.avail_out);
  202362. }
  202363. deflateReset(&png_ptr->zstream);
  202364. png_ptr->zstream.data_type = Z_BINARY;
  202365. }
  202366. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  202367. /* Pick out the correct pixels for the interlace pass.
  202368. * The basic idea here is to go through the row with a source
  202369. * pointer and a destination pointer (sp and dp), and copy the
  202370. * correct pixels for the pass. As the row gets compacted,
  202371. * sp will always be >= dp, so we should never overwrite anything.
  202372. * See the default: case for the easiest code to understand.
  202373. */
  202374. void /* PRIVATE */
  202375. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  202376. {
  202377. #ifdef PNG_USE_LOCAL_ARRAYS
  202378. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202379. /* start of interlace block */
  202380. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202381. /* offset to next interlace block */
  202382. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202383. #endif
  202384. png_debug(1, "in png_do_write_interlace\n");
  202385. /* we don't have to do anything on the last pass (6) */
  202386. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  202387. if (row != NULL && row_info != NULL && pass < 6)
  202388. #else
  202389. if (pass < 6)
  202390. #endif
  202391. {
  202392. /* each pixel depth is handled separately */
  202393. switch (row_info->pixel_depth)
  202394. {
  202395. case 1:
  202396. {
  202397. png_bytep sp;
  202398. png_bytep dp;
  202399. int shift;
  202400. int d;
  202401. int value;
  202402. png_uint_32 i;
  202403. png_uint_32 row_width = row_info->width;
  202404. dp = row;
  202405. d = 0;
  202406. shift = 7;
  202407. for (i = png_pass_start[pass]; i < row_width;
  202408. i += png_pass_inc[pass])
  202409. {
  202410. sp = row + (png_size_t)(i >> 3);
  202411. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  202412. d |= (value << shift);
  202413. if (shift == 0)
  202414. {
  202415. shift = 7;
  202416. *dp++ = (png_byte)d;
  202417. d = 0;
  202418. }
  202419. else
  202420. shift--;
  202421. }
  202422. if (shift != 7)
  202423. *dp = (png_byte)d;
  202424. break;
  202425. }
  202426. case 2:
  202427. {
  202428. png_bytep sp;
  202429. png_bytep dp;
  202430. int shift;
  202431. int d;
  202432. int value;
  202433. png_uint_32 i;
  202434. png_uint_32 row_width = row_info->width;
  202435. dp = row;
  202436. shift = 6;
  202437. d = 0;
  202438. for (i = png_pass_start[pass]; i < row_width;
  202439. i += png_pass_inc[pass])
  202440. {
  202441. sp = row + (png_size_t)(i >> 2);
  202442. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  202443. d |= (value << shift);
  202444. if (shift == 0)
  202445. {
  202446. shift = 6;
  202447. *dp++ = (png_byte)d;
  202448. d = 0;
  202449. }
  202450. else
  202451. shift -= 2;
  202452. }
  202453. if (shift != 6)
  202454. *dp = (png_byte)d;
  202455. break;
  202456. }
  202457. case 4:
  202458. {
  202459. png_bytep sp;
  202460. png_bytep dp;
  202461. int shift;
  202462. int d;
  202463. int value;
  202464. png_uint_32 i;
  202465. png_uint_32 row_width = row_info->width;
  202466. dp = row;
  202467. shift = 4;
  202468. d = 0;
  202469. for (i = png_pass_start[pass]; i < row_width;
  202470. i += png_pass_inc[pass])
  202471. {
  202472. sp = row + (png_size_t)(i >> 1);
  202473. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  202474. d |= (value << shift);
  202475. if (shift == 0)
  202476. {
  202477. shift = 4;
  202478. *dp++ = (png_byte)d;
  202479. d = 0;
  202480. }
  202481. else
  202482. shift -= 4;
  202483. }
  202484. if (shift != 4)
  202485. *dp = (png_byte)d;
  202486. break;
  202487. }
  202488. default:
  202489. {
  202490. png_bytep sp;
  202491. png_bytep dp;
  202492. png_uint_32 i;
  202493. png_uint_32 row_width = row_info->width;
  202494. png_size_t pixel_bytes;
  202495. /* start at the beginning */
  202496. dp = row;
  202497. /* find out how many bytes each pixel takes up */
  202498. pixel_bytes = (row_info->pixel_depth >> 3);
  202499. /* loop through the row, only looking at the pixels that
  202500. matter */
  202501. for (i = png_pass_start[pass]; i < row_width;
  202502. i += png_pass_inc[pass])
  202503. {
  202504. /* find out where the original pixel is */
  202505. sp = row + (png_size_t)i * pixel_bytes;
  202506. /* move the pixel */
  202507. if (dp != sp)
  202508. png_memcpy(dp, sp, pixel_bytes);
  202509. /* next pixel */
  202510. dp += pixel_bytes;
  202511. }
  202512. break;
  202513. }
  202514. }
  202515. /* set new row width */
  202516. row_info->width = (row_info->width +
  202517. png_pass_inc[pass] - 1 -
  202518. png_pass_start[pass]) /
  202519. png_pass_inc[pass];
  202520. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  202521. row_info->width);
  202522. }
  202523. }
  202524. #endif
  202525. /* This filters the row, chooses which filter to use, if it has not already
  202526. * been specified by the application, and then writes the row out with the
  202527. * chosen filter.
  202528. */
  202529. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  202530. #define PNG_HISHIFT 10
  202531. #define PNG_LOMASK ((png_uint_32)0xffffL)
  202532. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  202533. void /* PRIVATE */
  202534. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  202535. {
  202536. png_bytep best_row;
  202537. #ifndef PNG_NO_WRITE_FILTER
  202538. png_bytep prev_row, row_buf;
  202539. png_uint_32 mins, bpp;
  202540. png_byte filter_to_do = png_ptr->do_filter;
  202541. png_uint_32 row_bytes = row_info->rowbytes;
  202542. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202543. int num_p_filters = (int)png_ptr->num_prev_filters;
  202544. #endif
  202545. png_debug(1, "in png_write_find_filter\n");
  202546. /* find out how many bytes offset each pixel is */
  202547. bpp = (row_info->pixel_depth + 7) >> 3;
  202548. prev_row = png_ptr->prev_row;
  202549. #endif
  202550. best_row = png_ptr->row_buf;
  202551. #ifndef PNG_NO_WRITE_FILTER
  202552. row_buf = best_row;
  202553. mins = PNG_MAXSUM;
  202554. /* The prediction method we use is to find which method provides the
  202555. * smallest value when summing the absolute values of the distances
  202556. * from zero, using anything >= 128 as negative numbers. This is known
  202557. * as the "minimum sum of absolute differences" heuristic. Other
  202558. * heuristics are the "weighted minimum sum of absolute differences"
  202559. * (experimental and can in theory improve compression), and the "zlib
  202560. * predictive" method (not implemented yet), which does test compressions
  202561. * of lines using different filter methods, and then chooses the
  202562. * (series of) filter(s) that give minimum compressed data size (VERY
  202563. * computationally expensive).
  202564. *
  202565. * GRR 980525: consider also
  202566. * (1) minimum sum of absolute differences from running average (i.e.,
  202567. * keep running sum of non-absolute differences & count of bytes)
  202568. * [track dispersion, too? restart average if dispersion too large?]
  202569. * (1b) minimum sum of absolute differences from sliding average, probably
  202570. * with window size <= deflate window (usually 32K)
  202571. * (2) minimum sum of squared differences from zero or running average
  202572. * (i.e., ~ root-mean-square approach)
  202573. */
  202574. /* We don't need to test the 'no filter' case if this is the only filter
  202575. * that has been chosen, as it doesn't actually do anything to the data.
  202576. */
  202577. if ((filter_to_do & PNG_FILTER_NONE) &&
  202578. filter_to_do != PNG_FILTER_NONE)
  202579. {
  202580. png_bytep rp;
  202581. png_uint_32 sum = 0;
  202582. png_uint_32 i;
  202583. int v;
  202584. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  202585. {
  202586. v = *rp;
  202587. sum += (v < 128) ? v : 256 - v;
  202588. }
  202589. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202590. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202591. {
  202592. png_uint_32 sumhi, sumlo;
  202593. int j;
  202594. sumlo = sum & PNG_LOMASK;
  202595. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  202596. /* Reduce the sum if we match any of the previous rows */
  202597. for (j = 0; j < num_p_filters; j++)
  202598. {
  202599. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202600. {
  202601. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202602. PNG_WEIGHT_SHIFT;
  202603. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202604. PNG_WEIGHT_SHIFT;
  202605. }
  202606. }
  202607. /* Factor in the cost of this filter (this is here for completeness,
  202608. * but it makes no sense to have a "cost" for the NONE filter, as
  202609. * it has the minimum possible computational cost - none).
  202610. */
  202611. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202612. PNG_COST_SHIFT;
  202613. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202614. PNG_COST_SHIFT;
  202615. if (sumhi > PNG_HIMASK)
  202616. sum = PNG_MAXSUM;
  202617. else
  202618. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202619. }
  202620. #endif
  202621. mins = sum;
  202622. }
  202623. /* sub filter */
  202624. if (filter_to_do == PNG_FILTER_SUB)
  202625. /* it's the only filter so no testing is needed */
  202626. {
  202627. png_bytep rp, lp, dp;
  202628. png_uint_32 i;
  202629. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202630. i++, rp++, dp++)
  202631. {
  202632. *dp = *rp;
  202633. }
  202634. for (lp = row_buf + 1; i < row_bytes;
  202635. i++, rp++, lp++, dp++)
  202636. {
  202637. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202638. }
  202639. best_row = png_ptr->sub_row;
  202640. }
  202641. else if (filter_to_do & PNG_FILTER_SUB)
  202642. {
  202643. png_bytep rp, dp, lp;
  202644. png_uint_32 sum = 0, lmins = mins;
  202645. png_uint_32 i;
  202646. int v;
  202647. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202648. /* We temporarily increase the "minimum sum" by the factor we
  202649. * would reduce the sum of this filter, so that we can do the
  202650. * early exit comparison without scaling the sum each time.
  202651. */
  202652. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202653. {
  202654. int j;
  202655. png_uint_32 lmhi, lmlo;
  202656. lmlo = lmins & PNG_LOMASK;
  202657. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202658. for (j = 0; j < num_p_filters; j++)
  202659. {
  202660. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202661. {
  202662. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202663. PNG_WEIGHT_SHIFT;
  202664. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202665. PNG_WEIGHT_SHIFT;
  202666. }
  202667. }
  202668. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202669. PNG_COST_SHIFT;
  202670. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202671. PNG_COST_SHIFT;
  202672. if (lmhi > PNG_HIMASK)
  202673. lmins = PNG_MAXSUM;
  202674. else
  202675. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202676. }
  202677. #endif
  202678. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202679. i++, rp++, dp++)
  202680. {
  202681. v = *dp = *rp;
  202682. sum += (v < 128) ? v : 256 - v;
  202683. }
  202684. for (lp = row_buf + 1; i < row_bytes;
  202685. i++, rp++, lp++, dp++)
  202686. {
  202687. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202688. sum += (v < 128) ? v : 256 - v;
  202689. if (sum > lmins) /* We are already worse, don't continue. */
  202690. break;
  202691. }
  202692. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202693. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202694. {
  202695. int j;
  202696. png_uint_32 sumhi, sumlo;
  202697. sumlo = sum & PNG_LOMASK;
  202698. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202699. for (j = 0; j < num_p_filters; j++)
  202700. {
  202701. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202702. {
  202703. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  202704. PNG_WEIGHT_SHIFT;
  202705. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  202706. PNG_WEIGHT_SHIFT;
  202707. }
  202708. }
  202709. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202710. PNG_COST_SHIFT;
  202711. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202712. PNG_COST_SHIFT;
  202713. if (sumhi > PNG_HIMASK)
  202714. sum = PNG_MAXSUM;
  202715. else
  202716. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202717. }
  202718. #endif
  202719. if (sum < mins)
  202720. {
  202721. mins = sum;
  202722. best_row = png_ptr->sub_row;
  202723. }
  202724. }
  202725. /* up filter */
  202726. if (filter_to_do == PNG_FILTER_UP)
  202727. {
  202728. png_bytep rp, dp, pp;
  202729. png_uint_32 i;
  202730. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202731. pp = prev_row + 1; i < row_bytes;
  202732. i++, rp++, pp++, dp++)
  202733. {
  202734. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  202735. }
  202736. best_row = png_ptr->up_row;
  202737. }
  202738. else if (filter_to_do & PNG_FILTER_UP)
  202739. {
  202740. png_bytep rp, dp, pp;
  202741. png_uint_32 sum = 0, lmins = mins;
  202742. png_uint_32 i;
  202743. int v;
  202744. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202745. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202746. {
  202747. int j;
  202748. png_uint_32 lmhi, lmlo;
  202749. lmlo = lmins & PNG_LOMASK;
  202750. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202751. for (j = 0; j < num_p_filters; j++)
  202752. {
  202753. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202754. {
  202755. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202756. PNG_WEIGHT_SHIFT;
  202757. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202758. PNG_WEIGHT_SHIFT;
  202759. }
  202760. }
  202761. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202762. PNG_COST_SHIFT;
  202763. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202764. PNG_COST_SHIFT;
  202765. if (lmhi > PNG_HIMASK)
  202766. lmins = PNG_MAXSUM;
  202767. else
  202768. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202769. }
  202770. #endif
  202771. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202772. pp = prev_row + 1; i < row_bytes; i++)
  202773. {
  202774. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202775. sum += (v < 128) ? v : 256 - v;
  202776. if (sum > lmins) /* We are already worse, don't continue. */
  202777. break;
  202778. }
  202779. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202780. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202781. {
  202782. int j;
  202783. png_uint_32 sumhi, sumlo;
  202784. sumlo = sum & PNG_LOMASK;
  202785. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202786. for (j = 0; j < num_p_filters; j++)
  202787. {
  202788. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202789. {
  202790. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202791. PNG_WEIGHT_SHIFT;
  202792. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202793. PNG_WEIGHT_SHIFT;
  202794. }
  202795. }
  202796. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202797. PNG_COST_SHIFT;
  202798. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  202799. PNG_COST_SHIFT;
  202800. if (sumhi > PNG_HIMASK)
  202801. sum = PNG_MAXSUM;
  202802. else
  202803. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202804. }
  202805. #endif
  202806. if (sum < mins)
  202807. {
  202808. mins = sum;
  202809. best_row = png_ptr->up_row;
  202810. }
  202811. }
  202812. /* avg filter */
  202813. if (filter_to_do == PNG_FILTER_AVG)
  202814. {
  202815. png_bytep rp, dp, pp, lp;
  202816. png_uint_32 i;
  202817. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  202818. pp = prev_row + 1; i < bpp; i++)
  202819. {
  202820. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  202821. }
  202822. for (lp = row_buf + 1; i < row_bytes; i++)
  202823. {
  202824. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  202825. & 0xff);
  202826. }
  202827. best_row = png_ptr->avg_row;
  202828. }
  202829. else if (filter_to_do & PNG_FILTER_AVG)
  202830. {
  202831. png_bytep rp, dp, pp, lp;
  202832. png_uint_32 sum = 0, lmins = mins;
  202833. png_uint_32 i;
  202834. int v;
  202835. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202836. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202837. {
  202838. int j;
  202839. png_uint_32 lmhi, lmlo;
  202840. lmlo = lmins & PNG_LOMASK;
  202841. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202842. for (j = 0; j < num_p_filters; j++)
  202843. {
  202844. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  202845. {
  202846. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202847. PNG_WEIGHT_SHIFT;
  202848. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202849. PNG_WEIGHT_SHIFT;
  202850. }
  202851. }
  202852. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202853. PNG_COST_SHIFT;
  202854. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202855. PNG_COST_SHIFT;
  202856. if (lmhi > PNG_HIMASK)
  202857. lmins = PNG_MAXSUM;
  202858. else
  202859. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202860. }
  202861. #endif
  202862. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  202863. pp = prev_row + 1; i < bpp; i++)
  202864. {
  202865. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  202866. sum += (v < 128) ? v : 256 - v;
  202867. }
  202868. for (lp = row_buf + 1; i < row_bytes; i++)
  202869. {
  202870. v = *dp++ =
  202871. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  202872. sum += (v < 128) ? v : 256 - v;
  202873. if (sum > lmins) /* We are already worse, don't continue. */
  202874. break;
  202875. }
  202876. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202877. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202878. {
  202879. int j;
  202880. png_uint_32 sumhi, sumlo;
  202881. sumlo = sum & PNG_LOMASK;
  202882. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202883. for (j = 0; j < num_p_filters; j++)
  202884. {
  202885. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202886. {
  202887. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202888. PNG_WEIGHT_SHIFT;
  202889. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202890. PNG_WEIGHT_SHIFT;
  202891. }
  202892. }
  202893. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202894. PNG_COST_SHIFT;
  202895. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  202896. PNG_COST_SHIFT;
  202897. if (sumhi > PNG_HIMASK)
  202898. sum = PNG_MAXSUM;
  202899. else
  202900. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202901. }
  202902. #endif
  202903. if (sum < mins)
  202904. {
  202905. mins = sum;
  202906. best_row = png_ptr->avg_row;
  202907. }
  202908. }
  202909. /* Paeth filter */
  202910. if (filter_to_do == PNG_FILTER_PAETH)
  202911. {
  202912. png_bytep rp, dp, pp, cp, lp;
  202913. png_uint_32 i;
  202914. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  202915. pp = prev_row + 1; i < bpp; i++)
  202916. {
  202917. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202918. }
  202919. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  202920. {
  202921. int a, b, c, pa, pb, pc, p;
  202922. b = *pp++;
  202923. c = *cp++;
  202924. a = *lp++;
  202925. p = b - c;
  202926. pc = a - c;
  202927. #ifdef PNG_USE_ABS
  202928. pa = abs(p);
  202929. pb = abs(pc);
  202930. pc = abs(p + pc);
  202931. #else
  202932. pa = p < 0 ? -p : p;
  202933. pb = pc < 0 ? -pc : pc;
  202934. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  202935. #endif
  202936. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  202937. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  202938. }
  202939. best_row = png_ptr->paeth_row;
  202940. }
  202941. else if (filter_to_do & PNG_FILTER_PAETH)
  202942. {
  202943. png_bytep rp, dp, pp, cp, lp;
  202944. png_uint_32 sum = 0, lmins = mins;
  202945. png_uint_32 i;
  202946. int v;
  202947. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202948. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202949. {
  202950. int j;
  202951. png_uint_32 lmhi, lmlo;
  202952. lmlo = lmins & PNG_LOMASK;
  202953. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202954. for (j = 0; j < num_p_filters; j++)
  202955. {
  202956. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  202957. {
  202958. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202959. PNG_WEIGHT_SHIFT;
  202960. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202961. PNG_WEIGHT_SHIFT;
  202962. }
  202963. }
  202964. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202965. PNG_COST_SHIFT;
  202966. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  202967. PNG_COST_SHIFT;
  202968. if (lmhi > PNG_HIMASK)
  202969. lmins = PNG_MAXSUM;
  202970. else
  202971. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202972. }
  202973. #endif
  202974. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  202975. pp = prev_row + 1; i < bpp; i++)
  202976. {
  202977. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  202978. sum += (v < 128) ? v : 256 - v;
  202979. }
  202980. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  202981. {
  202982. int a, b, c, pa, pb, pc, p;
  202983. b = *pp++;
  202984. c = *cp++;
  202985. a = *lp++;
  202986. #ifndef PNG_SLOW_PAETH
  202987. p = b - c;
  202988. pc = a - c;
  202989. #ifdef PNG_USE_ABS
  202990. pa = abs(p);
  202991. pb = abs(pc);
  202992. pc = abs(p + pc);
  202993. #else
  202994. pa = p < 0 ? -p : p;
  202995. pb = pc < 0 ? -pc : pc;
  202996. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  202997. #endif
  202998. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  202999. #else /* PNG_SLOW_PAETH */
  203000. p = a + b - c;
  203001. pa = abs(p - a);
  203002. pb = abs(p - b);
  203003. pc = abs(p - c);
  203004. if (pa <= pb && pa <= pc)
  203005. p = a;
  203006. else if (pb <= pc)
  203007. p = b;
  203008. else
  203009. p = c;
  203010. #endif /* PNG_SLOW_PAETH */
  203011. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  203012. sum += (v < 128) ? v : 256 - v;
  203013. if (sum > lmins) /* We are already worse, don't continue. */
  203014. break;
  203015. }
  203016. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203017. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203018. {
  203019. int j;
  203020. png_uint_32 sumhi, sumlo;
  203021. sumlo = sum & PNG_LOMASK;
  203022. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  203023. for (j = 0; j < num_p_filters; j++)
  203024. {
  203025. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  203026. {
  203027. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  203028. PNG_WEIGHT_SHIFT;
  203029. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  203030. PNG_WEIGHT_SHIFT;
  203031. }
  203032. }
  203033. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203034. PNG_COST_SHIFT;
  203035. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203036. PNG_COST_SHIFT;
  203037. if (sumhi > PNG_HIMASK)
  203038. sum = PNG_MAXSUM;
  203039. else
  203040. sum = (sumhi << PNG_HISHIFT) + sumlo;
  203041. }
  203042. #endif
  203043. if (sum < mins)
  203044. {
  203045. best_row = png_ptr->paeth_row;
  203046. }
  203047. }
  203048. #endif /* PNG_NO_WRITE_FILTER */
  203049. /* Do the actual writing of the filtered row data from the chosen filter. */
  203050. png_write_filtered_row(png_ptr, best_row);
  203051. #ifndef PNG_NO_WRITE_FILTER
  203052. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203053. /* Save the type of filter we picked this time for future calculations */
  203054. if (png_ptr->num_prev_filters > 0)
  203055. {
  203056. int j;
  203057. for (j = 1; j < num_p_filters; j++)
  203058. {
  203059. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  203060. }
  203061. png_ptr->prev_filters[j] = best_row[0];
  203062. }
  203063. #endif
  203064. #endif /* PNG_NO_WRITE_FILTER */
  203065. }
  203066. /* Do the actual writing of a previously filtered row. */
  203067. void /* PRIVATE */
  203068. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  203069. {
  203070. png_debug(1, "in png_write_filtered_row\n");
  203071. png_debug1(2, "filter = %d\n", filtered_row[0]);
  203072. /* set up the zlib input buffer */
  203073. png_ptr->zstream.next_in = filtered_row;
  203074. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  203075. /* repeat until we have compressed all the data */
  203076. do
  203077. {
  203078. int ret; /* return of zlib */
  203079. /* compress the data */
  203080. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  203081. /* check for compression errors */
  203082. if (ret != Z_OK)
  203083. {
  203084. if (png_ptr->zstream.msg != NULL)
  203085. png_error(png_ptr, png_ptr->zstream.msg);
  203086. else
  203087. png_error(png_ptr, "zlib error");
  203088. }
  203089. /* see if it is time to write another IDAT */
  203090. if (!(png_ptr->zstream.avail_out))
  203091. {
  203092. /* write the IDAT and reset the zlib output buffer */
  203093. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  203094. png_ptr->zstream.next_out = png_ptr->zbuf;
  203095. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  203096. }
  203097. /* repeat until all data has been compressed */
  203098. } while (png_ptr->zstream.avail_in);
  203099. /* swap the current and previous rows */
  203100. if (png_ptr->prev_row != NULL)
  203101. {
  203102. png_bytep tptr;
  203103. tptr = png_ptr->prev_row;
  203104. png_ptr->prev_row = png_ptr->row_buf;
  203105. png_ptr->row_buf = tptr;
  203106. }
  203107. /* finish row - updates counters and flushes zlib if last row */
  203108. png_write_finish_row(png_ptr);
  203109. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  203110. png_ptr->flush_rows++;
  203111. if (png_ptr->flush_dist > 0 &&
  203112. png_ptr->flush_rows >= png_ptr->flush_dist)
  203113. {
  203114. png_write_flush(png_ptr);
  203115. }
  203116. #endif
  203117. }
  203118. #endif /* PNG_WRITE_SUPPORTED */
  203119. /*** End of inlined file: pngwutil.c ***/
  203120. #else
  203121. extern "C"
  203122. {
  203123. #include <png.h>
  203124. #include <pngconf.h>
  203125. }
  203126. #endif
  203127. }
  203128. #undef max
  203129. #undef min
  203130. #if JUCE_MSVC
  203131. #pragma warning (pop)
  203132. #endif
  203133. BEGIN_JUCE_NAMESPACE
  203134. using ::calloc;
  203135. using ::malloc;
  203136. using ::free;
  203137. namespace PNGHelpers
  203138. {
  203139. using namespace pnglibNamespace;
  203140. static void readCallback (png_structp png, png_bytep data, png_size_t length)
  203141. {
  203142. static_cast<InputStream*> (png_get_io_ptr (png))->read (data, (int) length);
  203143. }
  203144. static void writeDataCallback (png_structp png, png_bytep data, png_size_t length)
  203145. {
  203146. static_cast<OutputStream*> (png_get_io_ptr (png))->write (data, (int) length);
  203147. }
  203148. struct PNGErrorStruct {};
  203149. static void errorCallback (png_structp, png_const_charp)
  203150. {
  203151. throw PNGErrorStruct();
  203152. }
  203153. }
  203154. PNGImageFormat::PNGImageFormat() {}
  203155. PNGImageFormat::~PNGImageFormat() {}
  203156. const String PNGImageFormat::getFormatName()
  203157. {
  203158. return "PNG";
  203159. }
  203160. bool PNGImageFormat::canUnderstand (InputStream& in)
  203161. {
  203162. const int bytesNeeded = 4;
  203163. char header [bytesNeeded];
  203164. return in.read (header, bytesNeeded) == bytesNeeded
  203165. && header[1] == 'P'
  203166. && header[2] == 'N'
  203167. && header[3] == 'G';
  203168. }
  203169. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  203170. const Image juce_loadWithCoreImage (InputStream& input);
  203171. #endif
  203172. const Image PNGImageFormat::decodeImage (InputStream& in)
  203173. {
  203174. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  203175. return juce_loadWithCoreImage (in);
  203176. #else
  203177. using namespace pnglibNamespace;
  203178. Image image;
  203179. png_structp pngReadStruct;
  203180. png_infop pngInfoStruct;
  203181. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  203182. if (pngReadStruct != 0)
  203183. {
  203184. pngInfoStruct = png_create_info_struct (pngReadStruct);
  203185. if (pngInfoStruct == 0)
  203186. {
  203187. png_destroy_read_struct (&pngReadStruct, 0, 0);
  203188. return Image::null;
  203189. }
  203190. png_set_error_fn (pngReadStruct, 0, PNGHelpers::errorCallback, PNGHelpers::errorCallback );
  203191. // read the header..
  203192. png_set_read_fn (pngReadStruct, &in, PNGHelpers::readCallback);
  203193. png_uint_32 width, height;
  203194. int bitDepth, colorType, interlaceType;
  203195. png_read_info (pngReadStruct, pngInfoStruct);
  203196. png_get_IHDR (pngReadStruct, pngInfoStruct,
  203197. &width, &height,
  203198. &bitDepth, &colorType,
  203199. &interlaceType, 0, 0);
  203200. if (bitDepth == 16)
  203201. png_set_strip_16 (pngReadStruct);
  203202. if (colorType == PNG_COLOR_TYPE_PALETTE)
  203203. png_set_expand (pngReadStruct);
  203204. if (bitDepth < 8)
  203205. png_set_expand (pngReadStruct);
  203206. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  203207. png_set_expand (pngReadStruct);
  203208. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  203209. png_set_gray_to_rgb (pngReadStruct);
  203210. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  203211. bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  203212. || pngInfoStruct->num_trans > 0;
  203213. // Load the image into a temp buffer in the pnglib format..
  203214. HeapBlock <uint8> tempBuffer (height * (width << 2));
  203215. {
  203216. HeapBlock <png_bytep> rows (height);
  203217. for (int y = (int) height; --y >= 0;)
  203218. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  203219. png_read_image (pngReadStruct, rows);
  203220. png_read_end (pngReadStruct, pngInfoStruct);
  203221. }
  203222. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  203223. // now convert the data to a juce image format..
  203224. image = Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  203225. (int) width, (int) height, hasAlphaChan);
  203226. hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  203227. const Image::BitmapData destData (image, true);
  203228. uint8* srcRow = tempBuffer;
  203229. uint8* destRow = destData.data;
  203230. for (int y = 0; y < (int) height; ++y)
  203231. {
  203232. const uint8* src = srcRow;
  203233. srcRow += (width << 2);
  203234. uint8* dest = destRow;
  203235. destRow += destData.lineStride;
  203236. if (hasAlphaChan)
  203237. {
  203238. for (int i = (int) width; --i >= 0;)
  203239. {
  203240. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  203241. ((PixelARGB*) dest)->premultiply();
  203242. dest += destData.pixelStride;
  203243. src += 4;
  203244. }
  203245. }
  203246. else
  203247. {
  203248. for (int i = (int) width; --i >= 0;)
  203249. {
  203250. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  203251. dest += destData.pixelStride;
  203252. src += 4;
  203253. }
  203254. }
  203255. }
  203256. }
  203257. return image;
  203258. #endif
  203259. }
  203260. bool PNGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  203261. {
  203262. using namespace pnglibNamespace;
  203263. const int width = image.getWidth();
  203264. const int height = image.getHeight();
  203265. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  203266. if (pngWriteStruct == 0)
  203267. return false;
  203268. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  203269. if (pngInfoStruct == 0)
  203270. {
  203271. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  203272. return false;
  203273. }
  203274. png_set_write_fn (pngWriteStruct, &out, PNGHelpers::writeDataCallback, 0);
  203275. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  203276. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  203277. : PNG_COLOR_TYPE_RGB,
  203278. PNG_INTERLACE_NONE,
  203279. PNG_COMPRESSION_TYPE_BASE,
  203280. PNG_FILTER_TYPE_BASE);
  203281. HeapBlock <uint8> rowData (width * 4);
  203282. png_color_8 sig_bit;
  203283. sig_bit.red = 8;
  203284. sig_bit.green = 8;
  203285. sig_bit.blue = 8;
  203286. sig_bit.alpha = 8;
  203287. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  203288. png_write_info (pngWriteStruct, pngInfoStruct);
  203289. png_set_shift (pngWriteStruct, &sig_bit);
  203290. png_set_packing (pngWriteStruct);
  203291. const Image::BitmapData srcData (image, false);
  203292. for (int y = 0; y < height; ++y)
  203293. {
  203294. uint8* dst = rowData;
  203295. const uint8* src = srcData.getLinePointer (y);
  203296. if (image.hasAlphaChannel())
  203297. {
  203298. for (int i = width; --i >= 0;)
  203299. {
  203300. PixelARGB p (*(const PixelARGB*) src);
  203301. p.unpremultiply();
  203302. *dst++ = p.getRed();
  203303. *dst++ = p.getGreen();
  203304. *dst++ = p.getBlue();
  203305. *dst++ = p.getAlpha();
  203306. src += srcData.pixelStride;
  203307. }
  203308. }
  203309. else
  203310. {
  203311. for (int i = width; --i >= 0;)
  203312. {
  203313. *dst++ = ((const PixelRGB*) src)->getRed();
  203314. *dst++ = ((const PixelRGB*) src)->getGreen();
  203315. *dst++ = ((const PixelRGB*) src)->getBlue();
  203316. src += srcData.pixelStride;
  203317. }
  203318. }
  203319. png_bytep rowPtr = rowData;
  203320. png_write_rows (pngWriteStruct, &rowPtr, 1);
  203321. }
  203322. png_write_end (pngWriteStruct, pngInfoStruct);
  203323. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  203324. out.flush();
  203325. return true;
  203326. }
  203327. END_JUCE_NAMESPACE
  203328. /*** End of inlined file: juce_PNGLoader.cpp ***/
  203329. #endif
  203330. //==============================================================================
  203331. #if JUCE_BUILD_NATIVE
  203332. #if JUCE_WINDOWS
  203333. /*** Start of inlined file: juce_win32_NativeCode.cpp ***/
  203334. /*
  203335. This file wraps together all the win32-specific code, so that
  203336. we can include all the native headers just once, and compile all our
  203337. platform-specific stuff in one big lump, keeping it out of the way of
  203338. the rest of the codebase.
  203339. */
  203340. #if JUCE_WINDOWS
  203341. BEGIN_JUCE_NAMESPACE
  203342. /*** Start of inlined file: juce_MidiDataConcatenator.h ***/
  203343. #ifndef __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203344. #define __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203345. /**
  203346. Helper class that takes chunks of incoming midi bytes, packages them into
  203347. messages, and dispatches them to a midi callback.
  203348. */
  203349. class MidiDataConcatenator
  203350. {
  203351. public:
  203352. MidiDataConcatenator (const int initialBufferSize)
  203353. : pendingData (initialBufferSize),
  203354. pendingBytes (0), pendingDataTime (0)
  203355. {
  203356. }
  203357. void reset()
  203358. {
  203359. pendingBytes = 0;
  203360. pendingDataTime = 0;
  203361. }
  203362. void pushMidiData (const void* data, int numBytes, double time,
  203363. MidiInput* input, MidiInputCallback& callback)
  203364. {
  203365. const uint8* d = static_cast <const uint8*> (data);
  203366. while (numBytes > 0)
  203367. {
  203368. if (pendingBytes > 0 || d[0] == 0xf0)
  203369. {
  203370. processSysex (d, numBytes, time, input, callback);
  203371. }
  203372. else
  203373. {
  203374. int used = 0;
  203375. const MidiMessage m (d, numBytes, used, 0, time);
  203376. if (used <= 0)
  203377. break; // malformed message..
  203378. callback.handleIncomingMidiMessage (input, m);
  203379. numBytes -= used;
  203380. d += used;
  203381. }
  203382. }
  203383. }
  203384. private:
  203385. void processSysex (const uint8*& d, int& numBytes, double time,
  203386. MidiInput* input, MidiInputCallback& callback)
  203387. {
  203388. if (*d == 0xf0)
  203389. {
  203390. pendingBytes = 0;
  203391. pendingDataTime = time;
  203392. }
  203393. pendingData.ensureSize (pendingBytes + numBytes, false);
  203394. uint8* totalMessage = static_cast<uint8*> (pendingData.getData());
  203395. uint8* dest = totalMessage + pendingBytes;
  203396. do
  203397. {
  203398. if (pendingBytes > 0 && *d >= 0x80)
  203399. {
  203400. if (*d >= 0xfa || *d == 0xf8)
  203401. {
  203402. callback.handleIncomingMidiMessage (input, MidiMessage (*d, time));
  203403. ++d;
  203404. --numBytes;
  203405. }
  203406. else
  203407. {
  203408. if (*d == 0xf7)
  203409. {
  203410. *dest++ = *d++;
  203411. pendingBytes++;
  203412. --numBytes;
  203413. }
  203414. break;
  203415. }
  203416. }
  203417. else
  203418. {
  203419. *dest++ = *d++;
  203420. pendingBytes++;
  203421. --numBytes;
  203422. }
  203423. }
  203424. while (numBytes > 0);
  203425. if (pendingBytes > 0)
  203426. {
  203427. if (totalMessage [pendingBytes - 1] == 0xf7)
  203428. {
  203429. callback.handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  203430. pendingBytes = 0;
  203431. }
  203432. else
  203433. {
  203434. callback.handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  203435. }
  203436. }
  203437. }
  203438. MemoryBlock pendingData;
  203439. int pendingBytes;
  203440. double pendingDataTime;
  203441. MidiDataConcatenator (const MidiDataConcatenator&);
  203442. MidiDataConcatenator& operator= (const MidiDataConcatenator&);
  203443. };
  203444. #endif // __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203445. /*** End of inlined file: juce_MidiDataConcatenator.h ***/
  203446. #define JUCE_INCLUDED_FILE 1
  203447. // Now include the actual code files..
  203448. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203449. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203450. // compiled on its own).
  203451. #if JUCE_INCLUDED_FILE
  203452. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203453. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203454. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203455. #ifndef DOXYGEN
  203456. // use with DynamicLibraryLoader to simplify importing functions
  203457. //
  203458. // functionName: function to import
  203459. // localFunctionName: name you want to use to actually call it (must be different)
  203460. // returnType: the return type
  203461. // object: the DynamicLibraryLoader to use
  203462. // params: list of params (bracketed)
  203463. //
  203464. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  203465. typedef returnType (WINAPI *type##localFunctionName) params; \
  203466. type##localFunctionName localFunctionName \
  203467. = (type##localFunctionName)object.findProcAddress (#functionName);
  203468. // loads and unloads a DLL automatically
  203469. class JUCE_API DynamicLibraryLoader
  203470. {
  203471. public:
  203472. DynamicLibraryLoader (const String& name);
  203473. ~DynamicLibraryLoader();
  203474. void* findProcAddress (const String& functionName);
  203475. private:
  203476. void* libHandle;
  203477. };
  203478. #endif
  203479. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203480. /*** End of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203481. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  203482. {
  203483. libHandle = LoadLibrary (name);
  203484. }
  203485. DynamicLibraryLoader::~DynamicLibraryLoader()
  203486. {
  203487. FreeLibrary ((HMODULE) libHandle);
  203488. }
  203489. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  203490. {
  203491. return (void*) GetProcAddress ((HMODULE) libHandle, functionName.toCString()); // (void* cast is required for mingw)
  203492. }
  203493. #endif
  203494. /*** End of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203495. /*** Start of inlined file: juce_win32_SystemStats.cpp ***/
  203496. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203497. // compiled on its own).
  203498. #if JUCE_INCLUDED_FILE
  203499. extern void juce_initialiseThreadEvents();
  203500. void Logger::outputDebugString (const String& text)
  203501. {
  203502. OutputDebugString (text + "\n");
  203503. }
  203504. static int64 hiResTicksPerSecond;
  203505. static double hiResTicksScaleFactor;
  203506. #if JUCE_USE_INTRINSICS
  203507. // CPU info functions using intrinsics...
  203508. #pragma intrinsic (__cpuid)
  203509. #pragma intrinsic (__rdtsc)
  203510. const String SystemStats::getCpuVendor()
  203511. {
  203512. int info [4];
  203513. __cpuid (info, 0);
  203514. char v [12];
  203515. memcpy (v, info + 1, 4);
  203516. memcpy (v + 4, info + 3, 4);
  203517. memcpy (v + 8, info + 2, 4);
  203518. return String (v, 12);
  203519. }
  203520. #else
  203521. // CPU info functions using old fashioned inline asm...
  203522. static void juce_getCpuVendor (char* const v)
  203523. {
  203524. int vendor[4];
  203525. zeromem (vendor, 16);
  203526. #ifdef JUCE_64BIT
  203527. #else
  203528. #ifndef __MINGW32__
  203529. __try
  203530. #endif
  203531. {
  203532. #if JUCE_GCC
  203533. unsigned int dummy = 0;
  203534. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  203535. #else
  203536. __asm
  203537. {
  203538. mov eax, 0
  203539. cpuid
  203540. mov [vendor], ebx
  203541. mov [vendor + 4], edx
  203542. mov [vendor + 8], ecx
  203543. }
  203544. #endif
  203545. }
  203546. #ifndef __MINGW32__
  203547. __except (EXCEPTION_EXECUTE_HANDLER)
  203548. {
  203549. *v = 0;
  203550. }
  203551. #endif
  203552. #endif
  203553. memcpy (v, vendor, 16);
  203554. }
  203555. const String SystemStats::getCpuVendor()
  203556. {
  203557. char v [16];
  203558. juce_getCpuVendor (v);
  203559. return String (v, 16);
  203560. }
  203561. #endif
  203562. void SystemStats::initialiseStats()
  203563. {
  203564. juce_initialiseThreadEvents();
  203565. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  203566. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  203567. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  203568. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  203569. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  203570. #else
  203571. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  203572. #endif
  203573. {
  203574. SYSTEM_INFO systemInfo;
  203575. GetSystemInfo (&systemInfo);
  203576. cpuFlags.numCpus = systemInfo.dwNumberOfProcessors;
  203577. }
  203578. LARGE_INTEGER f;
  203579. QueryPerformanceFrequency (&f);
  203580. hiResTicksPerSecond = f.QuadPart;
  203581. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  203582. String s (SystemStats::getJUCEVersion());
  203583. const MMRESULT res = timeBeginPeriod (1);
  203584. (void) res;
  203585. jassert (res == TIMERR_NOERROR);
  203586. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  203587. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  203588. #endif
  203589. }
  203590. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  203591. {
  203592. OSVERSIONINFO info;
  203593. info.dwOSVersionInfoSize = sizeof (info);
  203594. GetVersionEx (&info);
  203595. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  203596. {
  203597. switch (info.dwMajorVersion)
  203598. {
  203599. case 5: return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  203600. case 6: return (info.dwMinorVersion == 0) ? WinVista : Windows7;
  203601. default: jassertfalse; break; // !! not a supported OS!
  203602. }
  203603. }
  203604. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  203605. {
  203606. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  203607. return Win98;
  203608. }
  203609. return UnknownOS;
  203610. }
  203611. const String SystemStats::getOperatingSystemName()
  203612. {
  203613. const char* name = "Unknown OS";
  203614. switch (getOperatingSystemType())
  203615. {
  203616. case Windows7: name = "Windows 7"; break;
  203617. case WinVista: name = "Windows Vista"; break;
  203618. case WinXP: name = "Windows XP"; break;
  203619. case Win2000: name = "Windows 2000"; break;
  203620. case Win98: name = "Windows 98"; break;
  203621. default: jassertfalse; break; // !! new type of OS?
  203622. }
  203623. return name;
  203624. }
  203625. bool SystemStats::isOperatingSystem64Bit()
  203626. {
  203627. #ifdef _WIN64
  203628. return true;
  203629. #else
  203630. typedef BOOL (WINAPI* LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  203631. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  203632. BOOL isWow64 = FALSE;
  203633. return (fnIsWow64Process != 0)
  203634. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  203635. && (isWow64 != FALSE);
  203636. #endif
  203637. }
  203638. int SystemStats::getMemorySizeInMegabytes()
  203639. {
  203640. MEMORYSTATUSEX mem;
  203641. mem.dwLength = sizeof (mem);
  203642. GlobalMemoryStatusEx (&mem);
  203643. return (int) (mem.ullTotalPhys / (1024 * 1024)) + 1;
  203644. }
  203645. uint32 juce_millisecondsSinceStartup() throw()
  203646. {
  203647. return (uint32) timeGetTime();
  203648. }
  203649. int64 Time::getHighResolutionTicks() throw()
  203650. {
  203651. LARGE_INTEGER ticks;
  203652. QueryPerformanceCounter (&ticks);
  203653. const int64 mainCounterAsHiResTicks = (GetTickCount() * hiResTicksPerSecond) / 1000;
  203654. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  203655. // fix for a very obscure PCI hardware bug that can make the counter
  203656. // sometimes jump forwards by a few seconds..
  203657. static int64 hiResTicksOffset = 0;
  203658. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  203659. if (offsetDrift > (hiResTicksPerSecond >> 1))
  203660. hiResTicksOffset = newOffset;
  203661. return ticks.QuadPart + hiResTicksOffset;
  203662. }
  203663. double Time::getMillisecondCounterHiRes() throw()
  203664. {
  203665. return getHighResolutionTicks() * hiResTicksScaleFactor;
  203666. }
  203667. int64 Time::getHighResolutionTicksPerSecond() throw()
  203668. {
  203669. return hiResTicksPerSecond;
  203670. }
  203671. static int64 juce_getClockCycleCounter() throw()
  203672. {
  203673. #if JUCE_USE_INTRINSICS
  203674. // MS intrinsics version...
  203675. return __rdtsc();
  203676. #elif JUCE_GCC
  203677. // GNU inline asm version...
  203678. unsigned int hi = 0, lo = 0;
  203679. __asm__ __volatile__ (
  203680. "xor %%eax, %%eax \n\
  203681. xor %%edx, %%edx \n\
  203682. rdtsc \n\
  203683. movl %%eax, %[lo] \n\
  203684. movl %%edx, %[hi]"
  203685. :
  203686. : [hi] "m" (hi),
  203687. [lo] "m" (lo)
  203688. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  203689. return (int64) ((((uint64) hi) << 32) | lo);
  203690. #else
  203691. // MSVC inline asm version...
  203692. unsigned int hi = 0, lo = 0;
  203693. __asm
  203694. {
  203695. xor eax, eax
  203696. xor edx, edx
  203697. rdtsc
  203698. mov lo, eax
  203699. mov hi, edx
  203700. }
  203701. return (int64) ((((uint64) hi) << 32) | lo);
  203702. #endif
  203703. }
  203704. int SystemStats::getCpuSpeedInMegaherz()
  203705. {
  203706. const int64 cycles = juce_getClockCycleCounter();
  203707. const uint32 millis = Time::getMillisecondCounter();
  203708. int lastResult = 0;
  203709. for (;;)
  203710. {
  203711. int n = 1000000;
  203712. while (--n > 0) {}
  203713. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  203714. const int64 cyclesNow = juce_getClockCycleCounter();
  203715. if (millisElapsed > 80)
  203716. {
  203717. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  203718. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  203719. return newResult;
  203720. lastResult = newResult;
  203721. }
  203722. }
  203723. }
  203724. bool Time::setSystemTimeToThisTime() const
  203725. {
  203726. SYSTEMTIME st;
  203727. st.wDayOfWeek = 0;
  203728. st.wYear = (WORD) getYear();
  203729. st.wMonth = (WORD) (getMonth() + 1);
  203730. st.wDay = (WORD) getDayOfMonth();
  203731. st.wHour = (WORD) getHours();
  203732. st.wMinute = (WORD) getMinutes();
  203733. st.wSecond = (WORD) getSeconds();
  203734. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  203735. // do this twice because of daylight saving conversion problems - the
  203736. // first one sets it up, the second one kicks it in.
  203737. return SetLocalTime (&st) != 0
  203738. && SetLocalTime (&st) != 0;
  203739. }
  203740. int SystemStats::getPageSize()
  203741. {
  203742. SYSTEM_INFO systemInfo;
  203743. GetSystemInfo (&systemInfo);
  203744. return systemInfo.dwPageSize;
  203745. }
  203746. const String SystemStats::getLogonName()
  203747. {
  203748. TCHAR text [256];
  203749. DWORD len = numElementsInArray (text) - 2;
  203750. zerostruct (text);
  203751. GetUserName (text, &len);
  203752. return String (text, len);
  203753. }
  203754. const String SystemStats::getFullUserName()
  203755. {
  203756. return getLogonName();
  203757. }
  203758. #endif
  203759. /*** End of inlined file: juce_win32_SystemStats.cpp ***/
  203760. /*** Start of inlined file: juce_win32_Threads.cpp ***/
  203761. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203762. // compiled on its own).
  203763. #if JUCE_INCLUDED_FILE
  203764. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203765. extern HWND juce_messageWindowHandle;
  203766. #endif
  203767. #if ! JUCE_USE_INTRINSICS
  203768. // In newer compilers, the inline versions of these are used (in juce_Atomic.h), but in
  203769. // older ones we have to actually call the ops as win32 functions..
  203770. long juce_InterlockedExchange (volatile long* a, long b) throw() { return InterlockedExchange (a, b); }
  203771. long juce_InterlockedIncrement (volatile long* a) throw() { return InterlockedIncrement (a); }
  203772. long juce_InterlockedDecrement (volatile long* a) throw() { return InterlockedDecrement (a); }
  203773. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw() { return InterlockedExchangeAdd (a, b); }
  203774. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw() { return InterlockedCompareExchange (a, b, c); }
  203775. __int64 juce_InterlockedCompareExchange64 (volatile __int64* value, __int64 newValue, __int64 valueToCompare) throw()
  203776. {
  203777. jassertfalse; // This operation isn't available in old MS compiler versions!
  203778. __int64 oldValue = *value;
  203779. if (oldValue == valueToCompare)
  203780. *value = newValue;
  203781. return oldValue;
  203782. }
  203783. #endif
  203784. CriticalSection::CriticalSection() throw()
  203785. {
  203786. // (just to check the MS haven't changed this structure and broken things...)
  203787. #if _MSC_VER >= 1400
  203788. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  203789. #else
  203790. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  203791. #endif
  203792. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  203793. }
  203794. CriticalSection::~CriticalSection() throw()
  203795. {
  203796. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  203797. }
  203798. void CriticalSection::enter() const throw()
  203799. {
  203800. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  203801. }
  203802. bool CriticalSection::tryEnter() const throw()
  203803. {
  203804. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  203805. }
  203806. void CriticalSection::exit() const throw()
  203807. {
  203808. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  203809. }
  203810. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  203811. : internal (CreateEvent (0, manualReset ? TRUE : FALSE, FALSE, 0))
  203812. {
  203813. }
  203814. WaitableEvent::~WaitableEvent() throw()
  203815. {
  203816. CloseHandle (internal);
  203817. }
  203818. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  203819. {
  203820. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  203821. }
  203822. void WaitableEvent::signal() const throw()
  203823. {
  203824. SetEvent (internal);
  203825. }
  203826. void WaitableEvent::reset() const throw()
  203827. {
  203828. ResetEvent (internal);
  203829. }
  203830. void JUCE_API juce_threadEntryPoint (void*);
  203831. static unsigned int __stdcall threadEntryProc (void* userData)
  203832. {
  203833. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203834. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  203835. GetCurrentThreadId(), TRUE);
  203836. #endif
  203837. juce_threadEntryPoint (userData);
  203838. _endthreadex (0);
  203839. return 0;
  203840. }
  203841. void juce_CloseThreadHandle (void* handle)
  203842. {
  203843. CloseHandle ((HANDLE) handle);
  203844. }
  203845. void* juce_createThread (void* userData)
  203846. {
  203847. unsigned int threadId;
  203848. return (void*) _beginthreadex (0, 0, &threadEntryProc, userData, 0, &threadId);
  203849. }
  203850. void juce_killThread (void* handle)
  203851. {
  203852. if (handle != 0)
  203853. {
  203854. #if JUCE_DEBUG
  203855. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  203856. #endif
  203857. TerminateThread (handle, 0);
  203858. }
  203859. }
  203860. void juce_setCurrentThreadName (const String& name)
  203861. {
  203862. #if JUCE_DEBUG && JUCE_MSVC
  203863. struct
  203864. {
  203865. DWORD dwType;
  203866. LPCSTR szName;
  203867. DWORD dwThreadID;
  203868. DWORD dwFlags;
  203869. } info;
  203870. info.dwType = 0x1000;
  203871. info.szName = name.toCString();
  203872. info.dwThreadID = GetCurrentThreadId();
  203873. info.dwFlags = 0;
  203874. __try
  203875. {
  203876. RaiseException (0x406d1388 /*MS_VC_EXCEPTION*/, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  203877. }
  203878. __except (EXCEPTION_CONTINUE_EXECUTION)
  203879. {}
  203880. #else
  203881. (void) name;
  203882. #endif
  203883. }
  203884. Thread::ThreadID Thread::getCurrentThreadId()
  203885. {
  203886. return (ThreadID) (pointer_sized_int) GetCurrentThreadId();
  203887. }
  203888. // priority 1 to 10 where 5=normal, 1=low
  203889. bool juce_setThreadPriority (void* threadHandle, int priority)
  203890. {
  203891. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  203892. if (priority < 1) pri = THREAD_PRIORITY_IDLE;
  203893. else if (priority < 2) pri = THREAD_PRIORITY_LOWEST;
  203894. else if (priority < 5) pri = THREAD_PRIORITY_BELOW_NORMAL;
  203895. else if (priority < 7) pri = THREAD_PRIORITY_NORMAL;
  203896. else if (priority < 9) pri = THREAD_PRIORITY_ABOVE_NORMAL;
  203897. else if (priority < 10) pri = THREAD_PRIORITY_HIGHEST;
  203898. if (threadHandle == 0)
  203899. threadHandle = GetCurrentThread();
  203900. return SetThreadPriority (threadHandle, pri) != FALSE;
  203901. }
  203902. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  203903. {
  203904. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  203905. }
  203906. static HANDLE sleepEvent = 0;
  203907. void juce_initialiseThreadEvents()
  203908. {
  203909. if (sleepEvent == 0)
  203910. #if JUCE_DEBUG
  203911. sleepEvent = CreateEvent (0, 0, 0, _T("Juce Sleep Event"));
  203912. #else
  203913. sleepEvent = CreateEvent (0, 0, 0, 0);
  203914. #endif
  203915. }
  203916. void Thread::yield()
  203917. {
  203918. Sleep (0);
  203919. }
  203920. void JUCE_CALLTYPE Thread::sleep (const int millisecs)
  203921. {
  203922. if (millisecs >= 10)
  203923. {
  203924. Sleep (millisecs);
  203925. }
  203926. else
  203927. {
  203928. jassert (sleepEvent != 0);
  203929. // unlike Sleep() this is guaranteed to return to the current thread after
  203930. // the time expires, so we'll use this for short waits, which are more likely
  203931. // to need to be accurate
  203932. WaitForSingleObject (sleepEvent, millisecs);
  203933. }
  203934. }
  203935. static int lastProcessPriority = -1;
  203936. // called by WindowDriver because Windows does wierd things to process priority
  203937. // when you swap apps, and this forces an update when the app is brought to the front.
  203938. void juce_repeatLastProcessPriority()
  203939. {
  203940. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  203941. {
  203942. DWORD p;
  203943. switch (lastProcessPriority)
  203944. {
  203945. case Process::LowPriority: p = IDLE_PRIORITY_CLASS; break;
  203946. case Process::NormalPriority: p = NORMAL_PRIORITY_CLASS; break;
  203947. case Process::HighPriority: p = HIGH_PRIORITY_CLASS; break;
  203948. case Process::RealtimePriority: p = REALTIME_PRIORITY_CLASS; break;
  203949. default: jassertfalse; return; // bad priority value
  203950. }
  203951. SetPriorityClass (GetCurrentProcess(), p);
  203952. }
  203953. }
  203954. void Process::setPriority (ProcessPriority prior)
  203955. {
  203956. if (lastProcessPriority != (int) prior)
  203957. {
  203958. lastProcessPriority = (int) prior;
  203959. juce_repeatLastProcessPriority();
  203960. }
  203961. }
  203962. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  203963. {
  203964. return IsDebuggerPresent() != FALSE;
  203965. }
  203966. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  203967. {
  203968. return juce_isRunningUnderDebugger();
  203969. }
  203970. void Process::raisePrivilege()
  203971. {
  203972. jassertfalse; // xxx not implemented
  203973. }
  203974. void Process::lowerPrivilege()
  203975. {
  203976. jassertfalse; // xxx not implemented
  203977. }
  203978. void Process::terminate()
  203979. {
  203980. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  203981. _CrtDumpMemoryLeaks();
  203982. #endif
  203983. // bullet in the head in case there's a problem shutting down..
  203984. ExitProcess (0);
  203985. }
  203986. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  203987. {
  203988. void* result = 0;
  203989. JUCE_TRY
  203990. {
  203991. result = LoadLibrary (name);
  203992. }
  203993. JUCE_CATCH_ALL
  203994. return result;
  203995. }
  203996. void PlatformUtilities::freeDynamicLibrary (void* h)
  203997. {
  203998. JUCE_TRY
  203999. {
  204000. if (h != 0)
  204001. FreeLibrary ((HMODULE) h);
  204002. }
  204003. JUCE_CATCH_ALL
  204004. }
  204005. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  204006. {
  204007. return (h != 0) ? (void*) GetProcAddress ((HMODULE) h, name.toCString()) : 0; // (void* cast is required for mingw)
  204008. }
  204009. class InterProcessLock::Pimpl
  204010. {
  204011. public:
  204012. Pimpl (const String& name, const int timeOutMillisecs)
  204013. : handle (0), refCount (1)
  204014. {
  204015. handle = CreateMutex (0, TRUE, "Global\\" + name.replaceCharacter ('\\','/'));
  204016. if (handle != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  204017. {
  204018. if (timeOutMillisecs == 0)
  204019. {
  204020. close();
  204021. return;
  204022. }
  204023. switch (WaitForSingleObject (handle, timeOutMillisecs < 0 ? INFINITE : timeOutMillisecs))
  204024. {
  204025. case WAIT_OBJECT_0:
  204026. case WAIT_ABANDONED:
  204027. break;
  204028. case WAIT_TIMEOUT:
  204029. default:
  204030. close();
  204031. break;
  204032. }
  204033. }
  204034. }
  204035. ~Pimpl()
  204036. {
  204037. close();
  204038. }
  204039. void close()
  204040. {
  204041. if (handle != 0)
  204042. {
  204043. ReleaseMutex (handle);
  204044. CloseHandle (handle);
  204045. handle = 0;
  204046. }
  204047. }
  204048. HANDLE handle;
  204049. int refCount;
  204050. };
  204051. InterProcessLock::InterProcessLock (const String& name_)
  204052. : name (name_)
  204053. {
  204054. }
  204055. InterProcessLock::~InterProcessLock()
  204056. {
  204057. }
  204058. bool InterProcessLock::enter (const int timeOutMillisecs)
  204059. {
  204060. const ScopedLock sl (lock);
  204061. if (pimpl == 0)
  204062. {
  204063. pimpl = new Pimpl (name, timeOutMillisecs);
  204064. if (pimpl->handle == 0)
  204065. pimpl = 0;
  204066. }
  204067. else
  204068. {
  204069. pimpl->refCount++;
  204070. }
  204071. return pimpl != 0;
  204072. }
  204073. void InterProcessLock::exit()
  204074. {
  204075. const ScopedLock sl (lock);
  204076. // Trying to release the lock too many times!
  204077. jassert (pimpl != 0);
  204078. if (pimpl != 0 && --(pimpl->refCount) == 0)
  204079. pimpl = 0;
  204080. }
  204081. #endif
  204082. /*** End of inlined file: juce_win32_Threads.cpp ***/
  204083. /*** Start of inlined file: juce_win32_Files.cpp ***/
  204084. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204085. // compiled on its own).
  204086. #if JUCE_INCLUDED_FILE
  204087. #ifndef CSIDL_MYMUSIC
  204088. #define CSIDL_MYMUSIC 0x000d
  204089. #endif
  204090. #ifndef CSIDL_MYVIDEO
  204091. #define CSIDL_MYVIDEO 0x000e
  204092. #endif
  204093. #ifndef INVALID_FILE_ATTRIBUTES
  204094. #define INVALID_FILE_ATTRIBUTES ((DWORD) -1)
  204095. #endif
  204096. const juce_wchar File::separator = '\\';
  204097. const String File::separatorString ("\\");
  204098. bool File::exists() const
  204099. {
  204100. return fullPath.isNotEmpty()
  204101. && GetFileAttributes (fullPath) != INVALID_FILE_ATTRIBUTES;
  204102. }
  204103. bool File::existsAsFile() const
  204104. {
  204105. return fullPath.isNotEmpty()
  204106. && (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_DIRECTORY) == 0;
  204107. }
  204108. bool File::isDirectory() const
  204109. {
  204110. const DWORD attr = GetFileAttributes (fullPath);
  204111. return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) && (attr != INVALID_FILE_ATTRIBUTES);
  204112. }
  204113. bool File::hasWriteAccess() const
  204114. {
  204115. if (exists())
  204116. return (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_READONLY) == 0;
  204117. // on windows, it seems that even read-only directories can still be written into,
  204118. // so checking the parent directory's permissions would return the wrong result..
  204119. return true;
  204120. }
  204121. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  204122. {
  204123. DWORD attr = GetFileAttributes (fullPath);
  204124. if (attr == INVALID_FILE_ATTRIBUTES)
  204125. return false;
  204126. if (shouldBeReadOnly == ((attr & FILE_ATTRIBUTE_READONLY) != 0))
  204127. return true;
  204128. if (shouldBeReadOnly)
  204129. attr |= FILE_ATTRIBUTE_READONLY;
  204130. else
  204131. attr &= ~FILE_ATTRIBUTE_READONLY;
  204132. return SetFileAttributes (fullPath, attr) != FALSE;
  204133. }
  204134. bool File::isHidden() const
  204135. {
  204136. return (GetFileAttributes (getFullPathName()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  204137. }
  204138. bool File::deleteFile() const
  204139. {
  204140. if (! exists())
  204141. return true;
  204142. else if (isDirectory())
  204143. return RemoveDirectory (fullPath) != 0;
  204144. else
  204145. return DeleteFile (fullPath) != 0;
  204146. }
  204147. bool File::moveToTrash() const
  204148. {
  204149. if (! exists())
  204150. return true;
  204151. SHFILEOPSTRUCT fos;
  204152. zerostruct (fos);
  204153. // The string we pass in must be double null terminated..
  204154. String doubleNullTermPath (getFullPathName() + " ");
  204155. TCHAR* const p = const_cast <TCHAR*> (static_cast <const TCHAR*> (doubleNullTermPath));
  204156. p [getFullPathName().length()] = 0;
  204157. fos.wFunc = FO_DELETE;
  204158. fos.pFrom = p;
  204159. fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION
  204160. | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION;
  204161. return SHFileOperation (&fos) == 0;
  204162. }
  204163. bool File::copyInternal (const File& dest) const
  204164. {
  204165. return CopyFile (fullPath, dest.getFullPathName(), false) != 0;
  204166. }
  204167. bool File::moveInternal (const File& dest) const
  204168. {
  204169. return MoveFile (fullPath, dest.getFullPathName()) != 0;
  204170. }
  204171. void File::createDirectoryInternal (const String& fileName) const
  204172. {
  204173. CreateDirectory (fileName, 0);
  204174. }
  204175. int64 juce_fileSetPosition (void* handle, int64 pos)
  204176. {
  204177. LARGE_INTEGER li;
  204178. li.QuadPart = pos;
  204179. li.LowPart = SetFilePointer ((HANDLE) handle, li.LowPart, &li.HighPart, FILE_BEGIN); // (returns -1 if it fails)
  204180. return li.QuadPart;
  204181. }
  204182. void FileInputStream::openHandle()
  204183. {
  204184. totalSize = file.getSize();
  204185. HANDLE h = CreateFile (file.getFullPathName(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  204186. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  204187. if (h != INVALID_HANDLE_VALUE)
  204188. fileHandle = (void*) h;
  204189. }
  204190. void FileInputStream::closeHandle()
  204191. {
  204192. CloseHandle ((HANDLE) fileHandle);
  204193. }
  204194. size_t FileInputStream::readInternal (void* buffer, size_t numBytes)
  204195. {
  204196. if (fileHandle != 0)
  204197. {
  204198. DWORD actualNum = 0;
  204199. ReadFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  204200. return (size_t) actualNum;
  204201. }
  204202. return 0;
  204203. }
  204204. void FileOutputStream::openHandle()
  204205. {
  204206. HANDLE h = CreateFile (file.getFullPathName(), GENERIC_WRITE, FILE_SHARE_READ, 0,
  204207. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  204208. if (h != INVALID_HANDLE_VALUE)
  204209. {
  204210. LARGE_INTEGER li;
  204211. li.QuadPart = 0;
  204212. li.LowPart = SetFilePointer (h, 0, &li.HighPart, FILE_END);
  204213. if (li.LowPart != INVALID_SET_FILE_POINTER)
  204214. {
  204215. fileHandle = (void*) h;
  204216. currentPosition = li.QuadPart;
  204217. }
  204218. }
  204219. }
  204220. void FileOutputStream::closeHandle()
  204221. {
  204222. CloseHandle ((HANDLE) fileHandle);
  204223. }
  204224. int FileOutputStream::writeInternal (const void* buffer, int numBytes)
  204225. {
  204226. if (fileHandle != 0)
  204227. {
  204228. DWORD actualNum = 0;
  204229. WriteFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  204230. return (int) actualNum;
  204231. }
  204232. return 0;
  204233. }
  204234. void FileOutputStream::flushInternal()
  204235. {
  204236. if (fileHandle != 0)
  204237. FlushFileBuffers ((HANDLE) fileHandle);
  204238. }
  204239. int64 File::getSize() const
  204240. {
  204241. WIN32_FILE_ATTRIBUTE_DATA attributes;
  204242. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  204243. return (((int64) attributes.nFileSizeHigh) << 32) | attributes.nFileSizeLow;
  204244. return 0;
  204245. }
  204246. static int64 fileTimeToTime (const FILETIME* const ft)
  204247. {
  204248. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME)); // tell me if this fails!
  204249. return (reinterpret_cast<const ULARGE_INTEGER*> (ft)->QuadPart - literal64bit (116444736000000000)) / 10000;
  204250. }
  204251. static void timeToFileTime (const int64 time, FILETIME* const ft)
  204252. {
  204253. reinterpret_cast<ULARGE_INTEGER*> (ft)->QuadPart = time * 10000 + literal64bit (116444736000000000);
  204254. }
  204255. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  204256. {
  204257. WIN32_FILE_ATTRIBUTE_DATA attributes;
  204258. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  204259. {
  204260. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  204261. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  204262. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  204263. }
  204264. else
  204265. {
  204266. creationTime = accessTime = modificationTime = 0;
  204267. }
  204268. }
  204269. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const
  204270. {
  204271. bool ok = false;
  204272. HANDLE h = CreateFile (fullPath, GENERIC_WRITE, FILE_SHARE_READ, 0,
  204273. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  204274. if (h != INVALID_HANDLE_VALUE)
  204275. {
  204276. FILETIME m, a, c;
  204277. timeToFileTime (modificationTime, &m);
  204278. timeToFileTime (accessTime, &a);
  204279. timeToFileTime (creationTime, &c);
  204280. ok = SetFileTime (h,
  204281. creationTime > 0 ? &c : 0,
  204282. accessTime > 0 ? &a : 0,
  204283. modificationTime > 0 ? &m : 0) != 0;
  204284. CloseHandle (h);
  204285. }
  204286. return ok;
  204287. }
  204288. void File::findFileSystemRoots (Array<File>& destArray)
  204289. {
  204290. TCHAR buffer [2048];
  204291. buffer[0] = 0;
  204292. buffer[1] = 0;
  204293. GetLogicalDriveStrings (2048, buffer);
  204294. const TCHAR* n = buffer;
  204295. StringArray roots;
  204296. while (*n != 0)
  204297. {
  204298. roots.add (String (n));
  204299. while (*n++ != 0)
  204300. {}
  204301. }
  204302. roots.sort (true);
  204303. for (int i = 0; i < roots.size(); ++i)
  204304. destArray.add (roots [i]);
  204305. }
  204306. static const String getDriveFromPath (const String& path)
  204307. {
  204308. if (path.isNotEmpty() && path[1] == ':')
  204309. return path.substring (0, 2) + '\\';
  204310. return path;
  204311. }
  204312. const String File::getVolumeLabel() const
  204313. {
  204314. TCHAR dest[64];
  204315. if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest,
  204316. numElementsInArray (dest), 0, 0, 0, 0, 0))
  204317. dest[0] = 0;
  204318. return dest;
  204319. }
  204320. int File::getVolumeSerialNumber() const
  204321. {
  204322. TCHAR dest[64];
  204323. DWORD serialNum;
  204324. if (! GetVolumeInformation (getDriveFromPath (getFullPathName()), dest,
  204325. numElementsInArray (dest), &serialNum, 0, 0, 0, 0))
  204326. return 0;
  204327. return (int) serialNum;
  204328. }
  204329. static int64 getDiskSpaceInfo (const String& path, const bool total)
  204330. {
  204331. ULARGE_INTEGER spc, tot, totFree;
  204332. if (GetDiskFreeSpaceEx (getDriveFromPath (path), &spc, &tot, &totFree))
  204333. return total ? (int64) tot.QuadPart
  204334. : (int64) spc.QuadPart;
  204335. return 0;
  204336. }
  204337. int64 File::getBytesFreeOnVolume() const
  204338. {
  204339. return getDiskSpaceInfo (getFullPathName(), false);
  204340. }
  204341. int64 File::getVolumeTotalSize() const
  204342. {
  204343. return getDiskSpaceInfo (getFullPathName(), true);
  204344. }
  204345. static unsigned int getWindowsDriveType (const String& path)
  204346. {
  204347. return GetDriveType (getDriveFromPath (path));
  204348. }
  204349. bool File::isOnCDRomDrive() const
  204350. {
  204351. return getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  204352. }
  204353. bool File::isOnHardDisk() const
  204354. {
  204355. if (fullPath.isEmpty())
  204356. return false;
  204357. const unsigned int n = getWindowsDriveType (getFullPathName());
  204358. if (fullPath.toLowerCase()[0] <= 'b' && fullPath[1] == ':')
  204359. return n != DRIVE_REMOVABLE;
  204360. else
  204361. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  204362. }
  204363. bool File::isOnRemovableDrive() const
  204364. {
  204365. if (fullPath.isEmpty())
  204366. return false;
  204367. const unsigned int n = getWindowsDriveType (getFullPathName());
  204368. return n == DRIVE_CDROM
  204369. || n == DRIVE_REMOTE
  204370. || n == DRIVE_REMOVABLE
  204371. || n == DRIVE_RAMDISK;
  204372. }
  204373. static const File juce_getSpecialFolderPath (int type)
  204374. {
  204375. WCHAR path [MAX_PATH + 256];
  204376. if (SHGetSpecialFolderPath (0, path, type, FALSE))
  204377. return File (String (path));
  204378. return File::nonexistent;
  204379. }
  204380. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  204381. {
  204382. int csidlType = 0;
  204383. switch (type)
  204384. {
  204385. case userHomeDirectory: csidlType = CSIDL_PROFILE; break;
  204386. case userDocumentsDirectory: csidlType = CSIDL_PERSONAL; break;
  204387. case userDesktopDirectory: csidlType = CSIDL_DESKTOP; break;
  204388. case userApplicationDataDirectory: csidlType = CSIDL_APPDATA; break;
  204389. case commonApplicationDataDirectory: csidlType = CSIDL_COMMON_APPDATA; break;
  204390. case globalApplicationsDirectory: csidlType = CSIDL_PROGRAM_FILES; break;
  204391. case userMusicDirectory: csidlType = CSIDL_MYMUSIC; break;
  204392. case userMoviesDirectory: csidlType = CSIDL_MYVIDEO; break;
  204393. case tempDirectory:
  204394. {
  204395. WCHAR dest [2048];
  204396. dest[0] = 0;
  204397. GetTempPath (numElementsInArray (dest), dest);
  204398. return File (String (dest));
  204399. }
  204400. case invokedExecutableFile:
  204401. case currentExecutableFile:
  204402. case currentApplicationFile:
  204403. {
  204404. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  204405. WCHAR dest [MAX_PATH + 256];
  204406. dest[0] = 0;
  204407. GetModuleFileName (moduleHandle, dest, numElementsInArray (dest));
  204408. return File (String (dest));
  204409. }
  204410. case hostApplicationPath:
  204411. {
  204412. WCHAR dest [MAX_PATH + 256];
  204413. dest[0] = 0;
  204414. GetModuleFileName (0, dest, numElementsInArray (dest));
  204415. return File (String (dest));
  204416. }
  204417. default:
  204418. jassertfalse; // unknown type?
  204419. return File::nonexistent;
  204420. }
  204421. return juce_getSpecialFolderPath (csidlType);
  204422. }
  204423. const File File::getCurrentWorkingDirectory()
  204424. {
  204425. WCHAR dest [MAX_PATH + 256];
  204426. dest[0] = 0;
  204427. GetCurrentDirectory (numElementsInArray (dest), dest);
  204428. return File (String (dest));
  204429. }
  204430. bool File::setAsCurrentWorkingDirectory() const
  204431. {
  204432. return SetCurrentDirectory (getFullPathName()) != FALSE;
  204433. }
  204434. const String File::getVersion() const
  204435. {
  204436. String result;
  204437. DWORD handle = 0;
  204438. DWORD bufferSize = GetFileVersionInfoSize (getFullPathName(), &handle);
  204439. HeapBlock<char> buffer;
  204440. buffer.calloc (bufferSize);
  204441. if (GetFileVersionInfo (getFullPathName(), 0, bufferSize, buffer))
  204442. {
  204443. VS_FIXEDFILEINFO* vffi;
  204444. UINT len = 0;
  204445. if (VerQueryValue (buffer, (LPTSTR) _T("\\"), (LPVOID*) &vffi, &len))
  204446. {
  204447. result << (int) HIWORD (vffi->dwFileVersionMS) << '.'
  204448. << (int) LOWORD (vffi->dwFileVersionMS) << '.'
  204449. << (int) HIWORD (vffi->dwFileVersionLS) << '.'
  204450. << (int) LOWORD (vffi->dwFileVersionLS);
  204451. }
  204452. }
  204453. return result;
  204454. }
  204455. const File File::getLinkedTarget() const
  204456. {
  204457. File result (*this);
  204458. String p (getFullPathName());
  204459. if (! exists())
  204460. p += ".lnk";
  204461. else if (getFileExtension() != ".lnk")
  204462. return result;
  204463. ComSmartPtr <IShellLink> shellLink;
  204464. if (SUCCEEDED (shellLink.CoCreateInstance (CLSID_ShellLink)))
  204465. {
  204466. ComSmartPtr <IPersistFile> persistFile;
  204467. if (SUCCEEDED (shellLink.QueryInterface (IID_IPersistFile, persistFile)))
  204468. {
  204469. if (SUCCEEDED (persistFile->Load ((const WCHAR*) p, STGM_READ))
  204470. && SUCCEEDED (shellLink->Resolve (0, SLR_ANY_MATCH | SLR_NO_UI)))
  204471. {
  204472. WIN32_FIND_DATA winFindData;
  204473. WCHAR resolvedPath [MAX_PATH];
  204474. if (SUCCEEDED (shellLink->GetPath (resolvedPath, MAX_PATH, &winFindData, SLGP_UNCPRIORITY)))
  204475. result = File (resolvedPath);
  204476. }
  204477. }
  204478. }
  204479. return result;
  204480. }
  204481. class DirectoryIterator::NativeIterator::Pimpl
  204482. {
  204483. public:
  204484. Pimpl (const File& directory, const String& wildCard)
  204485. : directoryWithWildCard (File::addTrailingSeparator (directory.getFullPathName()) + wildCard),
  204486. handle (INVALID_HANDLE_VALUE)
  204487. {
  204488. }
  204489. ~Pimpl()
  204490. {
  204491. if (handle != INVALID_HANDLE_VALUE)
  204492. FindClose (handle);
  204493. }
  204494. bool next (String& filenameFound,
  204495. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204496. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204497. {
  204498. WIN32_FIND_DATA findData;
  204499. if (handle == INVALID_HANDLE_VALUE)
  204500. {
  204501. handle = FindFirstFile (directoryWithWildCard, &findData);
  204502. if (handle == INVALID_HANDLE_VALUE)
  204503. return false;
  204504. }
  204505. else
  204506. {
  204507. if (FindNextFile (handle, &findData) == 0)
  204508. return false;
  204509. }
  204510. filenameFound = findData.cFileName;
  204511. if (isDir != 0) *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  204512. if (isHidden != 0) *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  204513. if (fileSize != 0) *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  204514. if (modTime != 0) *modTime = fileTimeToTime (&findData.ftLastWriteTime);
  204515. if (creationTime != 0) *creationTime = fileTimeToTime (&findData.ftCreationTime);
  204516. if (isReadOnly != 0) *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  204517. return true;
  204518. }
  204519. juce_UseDebuggingNewOperator
  204520. private:
  204521. const String directoryWithWildCard;
  204522. HANDLE handle;
  204523. Pimpl (const Pimpl&);
  204524. Pimpl& operator= (const Pimpl&);
  204525. };
  204526. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  204527. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  204528. {
  204529. }
  204530. DirectoryIterator::NativeIterator::~NativeIterator()
  204531. {
  204532. }
  204533. bool DirectoryIterator::NativeIterator::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. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  204538. }
  204539. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  204540. {
  204541. HINSTANCE hInstance = 0;
  204542. JUCE_TRY
  204543. {
  204544. hInstance = ShellExecute (0, 0, fileName, parameters, 0, SW_SHOWDEFAULT);
  204545. }
  204546. JUCE_CATCH_ALL
  204547. return hInstance > (HINSTANCE) 32;
  204548. }
  204549. void File::revealToUser() const
  204550. {
  204551. if (isDirectory())
  204552. startAsProcess();
  204553. else if (getParentDirectory().exists())
  204554. getParentDirectory().startAsProcess();
  204555. }
  204556. class NamedPipeInternal
  204557. {
  204558. public:
  204559. NamedPipeInternal (const String& file, const bool isPipe_)
  204560. : pipeH (0),
  204561. cancelEvent (0),
  204562. connected (false),
  204563. isPipe (isPipe_)
  204564. {
  204565. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  204566. pipeH = isPipe ? CreateNamedPipe (file, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  204567. PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, 0)
  204568. : CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0,
  204569. OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
  204570. }
  204571. ~NamedPipeInternal()
  204572. {
  204573. disconnectPipe();
  204574. if (pipeH != 0)
  204575. CloseHandle (pipeH);
  204576. CloseHandle (cancelEvent);
  204577. }
  204578. bool connect (const int timeOutMs)
  204579. {
  204580. if (! isPipe)
  204581. return true;
  204582. if (! connected)
  204583. {
  204584. OVERLAPPED over;
  204585. zerostruct (over);
  204586. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204587. if (ConnectNamedPipe (pipeH, &over))
  204588. {
  204589. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  204590. }
  204591. else
  204592. {
  204593. const int err = GetLastError();
  204594. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  204595. {
  204596. HANDLE handles[] = { over.hEvent, cancelEvent };
  204597. if (WaitForMultipleObjects (2, handles, FALSE,
  204598. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  204599. connected = true;
  204600. }
  204601. else if (err == ERROR_PIPE_CONNECTED)
  204602. {
  204603. connected = true;
  204604. }
  204605. }
  204606. CloseHandle (over.hEvent);
  204607. }
  204608. return connected;
  204609. }
  204610. void disconnectPipe()
  204611. {
  204612. if (connected)
  204613. {
  204614. DisconnectNamedPipe (pipeH);
  204615. connected = false;
  204616. }
  204617. }
  204618. HANDLE pipeH;
  204619. HANDLE cancelEvent;
  204620. bool connected, isPipe;
  204621. };
  204622. void NamedPipe::close()
  204623. {
  204624. cancelPendingReads();
  204625. const ScopedLock sl (lock);
  204626. delete static_cast<NamedPipeInternal*> (internal);
  204627. internal = 0;
  204628. }
  204629. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  204630. {
  204631. close();
  204632. ScopedPointer<NamedPipeInternal> intern (new NamedPipeInternal ("\\\\.\\pipe\\" + pipeName, createPipe));
  204633. if (intern->pipeH != INVALID_HANDLE_VALUE)
  204634. {
  204635. internal = intern.release();
  204636. return true;
  204637. }
  204638. return false;
  204639. }
  204640. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  204641. {
  204642. const ScopedLock sl (lock);
  204643. int bytesRead = -1;
  204644. bool waitAgain = true;
  204645. while (waitAgain && internal != 0)
  204646. {
  204647. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204648. waitAgain = false;
  204649. if (! intern->connect (timeOutMilliseconds))
  204650. break;
  204651. if (maxBytesToRead <= 0)
  204652. return 0;
  204653. OVERLAPPED over;
  204654. zerostruct (over);
  204655. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204656. unsigned long numRead;
  204657. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  204658. {
  204659. bytesRead = (int) numRead;
  204660. }
  204661. else if (GetLastError() == ERROR_IO_PENDING)
  204662. {
  204663. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204664. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204665. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204666. : INFINITE);
  204667. if (waitResult != WAIT_OBJECT_0)
  204668. {
  204669. // if the operation timed out, let's cancel it...
  204670. CancelIo (intern->pipeH);
  204671. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  204672. }
  204673. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  204674. {
  204675. bytesRead = (int) numRead;
  204676. }
  204677. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204678. {
  204679. intern->disconnectPipe();
  204680. waitAgain = true;
  204681. }
  204682. }
  204683. else
  204684. {
  204685. waitAgain = internal != 0;
  204686. Sleep (5);
  204687. }
  204688. CloseHandle (over.hEvent);
  204689. }
  204690. return bytesRead;
  204691. }
  204692. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  204693. {
  204694. int bytesWritten = -1;
  204695. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204696. if (intern != 0 && intern->connect (timeOutMilliseconds))
  204697. {
  204698. if (numBytesToWrite <= 0)
  204699. return 0;
  204700. OVERLAPPED over;
  204701. zerostruct (over);
  204702. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204703. unsigned long numWritten;
  204704. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  204705. {
  204706. bytesWritten = (int) numWritten;
  204707. }
  204708. else if (GetLastError() == ERROR_IO_PENDING)
  204709. {
  204710. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204711. DWORD waitResult;
  204712. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204713. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204714. : INFINITE);
  204715. if (waitResult != WAIT_OBJECT_0)
  204716. {
  204717. CancelIo (intern->pipeH);
  204718. WaitForSingleObject (over.hEvent, INFINITE);
  204719. }
  204720. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  204721. {
  204722. bytesWritten = (int) numWritten;
  204723. }
  204724. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204725. {
  204726. intern->disconnectPipe();
  204727. }
  204728. }
  204729. CloseHandle (over.hEvent);
  204730. }
  204731. return bytesWritten;
  204732. }
  204733. void NamedPipe::cancelPendingReads()
  204734. {
  204735. if (internal != 0)
  204736. SetEvent (static_cast<NamedPipeInternal*> (internal)->cancelEvent);
  204737. }
  204738. #endif
  204739. /*** End of inlined file: juce_win32_Files.cpp ***/
  204740. /*** Start of inlined file: juce_win32_Network.cpp ***/
  204741. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204742. // compiled on its own).
  204743. #if JUCE_INCLUDED_FILE
  204744. #ifndef INTERNET_FLAG_NEED_FILE
  204745. #define INTERNET_FLAG_NEED_FILE 0x00000010
  204746. #endif
  204747. #ifndef INTERNET_OPTION_DISABLE_AUTODIAL
  204748. #define INTERNET_OPTION_DISABLE_AUTODIAL 70
  204749. #endif
  204750. struct ConnectionAndRequestStruct
  204751. {
  204752. HINTERNET connection, request;
  204753. };
  204754. static HINTERNET sessionHandle = 0;
  204755. #ifndef WORKAROUND_TIMEOUT_BUG
  204756. //#define WORKAROUND_TIMEOUT_BUG 1
  204757. #endif
  204758. #if WORKAROUND_TIMEOUT_BUG
  204759. // Required because of a Microsoft bug in setting a timeout
  204760. class InternetConnectThread : public Thread
  204761. {
  204762. public:
  204763. InternetConnectThread (URL_COMPONENTS& uc_, HINTERNET& connection_, const bool isFtp_)
  204764. : Thread ("Internet"), uc (uc_), connection (connection_), isFtp (isFtp_)
  204765. {
  204766. startThread();
  204767. }
  204768. ~InternetConnectThread()
  204769. {
  204770. stopThread (60000);
  204771. }
  204772. void run()
  204773. {
  204774. connection = InternetConnect (sessionHandle, uc.lpszHostName,
  204775. uc.nPort, _T(""), _T(""),
  204776. isFtp ? INTERNET_SERVICE_FTP
  204777. : INTERNET_SERVICE_HTTP,
  204778. 0, 0);
  204779. notify();
  204780. }
  204781. juce_UseDebuggingNewOperator
  204782. private:
  204783. URL_COMPONENTS& uc;
  204784. HINTERNET& connection;
  204785. const bool isFtp;
  204786. InternetConnectThread (const InternetConnectThread&);
  204787. InternetConnectThread& operator= (const InternetConnectThread&);
  204788. };
  204789. #endif
  204790. void* juce_openInternetFile (const String& url,
  204791. const String& headers,
  204792. const MemoryBlock& postData,
  204793. const bool isPost,
  204794. URL::OpenStreamProgressCallback* callback,
  204795. void* callbackContext,
  204796. int timeOutMs)
  204797. {
  204798. if (sessionHandle == 0)
  204799. sessionHandle = InternetOpen (_T("juce"),
  204800. INTERNET_OPEN_TYPE_PRECONFIG,
  204801. 0, 0, 0);
  204802. if (sessionHandle != 0)
  204803. {
  204804. // break up the url..
  204805. TCHAR file[1024], server[1024];
  204806. URL_COMPONENTS uc;
  204807. zerostruct (uc);
  204808. uc.dwStructSize = sizeof (uc);
  204809. uc.dwUrlPathLength = sizeof (file);
  204810. uc.dwHostNameLength = sizeof (server);
  204811. uc.lpszUrlPath = file;
  204812. uc.lpszHostName = server;
  204813. if (InternetCrackUrl (url, 0, 0, &uc))
  204814. {
  204815. int disable = 1;
  204816. InternetSetOption (sessionHandle, INTERNET_OPTION_DISABLE_AUTODIAL, &disable, sizeof (disable));
  204817. if (timeOutMs == 0)
  204818. timeOutMs = 30000;
  204819. else if (timeOutMs < 0)
  204820. timeOutMs = -1;
  204821. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  204822. const bool isFtp = url.startsWithIgnoreCase ("ftp:");
  204823. #if WORKAROUND_TIMEOUT_BUG
  204824. HINTERNET connection = 0;
  204825. {
  204826. InternetConnectThread connectThread (uc, connection, isFtp);
  204827. connectThread.wait (timeOutMs);
  204828. if (connection == 0)
  204829. {
  204830. InternetCloseHandle (sessionHandle);
  204831. sessionHandle = 0;
  204832. }
  204833. }
  204834. #else
  204835. HINTERNET connection = InternetConnect (sessionHandle,
  204836. uc.lpszHostName,
  204837. uc.nPort,
  204838. _T(""), _T(""),
  204839. isFtp ? INTERNET_SERVICE_FTP
  204840. : INTERNET_SERVICE_HTTP,
  204841. 0, 0);
  204842. #endif
  204843. if (connection != 0)
  204844. {
  204845. if (isFtp)
  204846. {
  204847. HINTERNET request = FtpOpenFile (connection,
  204848. uc.lpszUrlPath,
  204849. GENERIC_READ,
  204850. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE,
  204851. 0);
  204852. ConnectionAndRequestStruct* const result = new ConnectionAndRequestStruct();
  204853. result->connection = connection;
  204854. result->request = request;
  204855. return result;
  204856. }
  204857. else
  204858. {
  204859. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  204860. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES;
  204861. if (url.startsWithIgnoreCase ("https:"))
  204862. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  204863. // IE7 seems to automatically work out when it's https)
  204864. HINTERNET request = HttpOpenRequest (connection,
  204865. isPost ? _T("POST")
  204866. : _T("GET"),
  204867. uc.lpszUrlPath,
  204868. 0, 0, mimeTypes, flags, 0);
  204869. if (request != 0)
  204870. {
  204871. INTERNET_BUFFERS buffers;
  204872. zerostruct (buffers);
  204873. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  204874. buffers.lpcszHeader = (LPCTSTR) headers;
  204875. buffers.dwHeadersLength = headers.length();
  204876. buffers.dwBufferTotal = (DWORD) postData.getSize();
  204877. ConnectionAndRequestStruct* result = 0;
  204878. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  204879. {
  204880. int bytesSent = 0;
  204881. for (;;)
  204882. {
  204883. const int bytesToDo = jmin (1024, (int) postData.getSize() - bytesSent);
  204884. DWORD bytesDone = 0;
  204885. if (bytesToDo > 0
  204886. && ! InternetWriteFile (request,
  204887. static_cast <const char*> (postData.getData()) + bytesSent,
  204888. bytesToDo, &bytesDone))
  204889. {
  204890. break;
  204891. }
  204892. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  204893. {
  204894. result = new ConnectionAndRequestStruct();
  204895. result->connection = connection;
  204896. result->request = request;
  204897. if (! HttpEndRequest (request, 0, 0, 0))
  204898. break;
  204899. return result;
  204900. }
  204901. bytesSent += bytesDone;
  204902. if (callback != 0 && ! callback (callbackContext, bytesSent, postData.getSize()))
  204903. break;
  204904. }
  204905. }
  204906. InternetCloseHandle (request);
  204907. }
  204908. InternetCloseHandle (connection);
  204909. }
  204910. }
  204911. }
  204912. }
  204913. return 0;
  204914. }
  204915. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  204916. {
  204917. DWORD bytesRead = 0;
  204918. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204919. if (crs != 0)
  204920. InternetReadFile (crs->request,
  204921. buffer, bytesToRead,
  204922. &bytesRead);
  204923. return bytesRead;
  204924. }
  204925. int juce_seekInInternetFile (void* handle, int newPosition)
  204926. {
  204927. if (handle != 0)
  204928. {
  204929. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204930. return InternetSetFilePointer (crs->request, newPosition, 0, FILE_BEGIN, 0);
  204931. }
  204932. return -1;
  204933. }
  204934. int64 juce_getInternetFileContentLength (void* handle)
  204935. {
  204936. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204937. if (crs != 0)
  204938. {
  204939. DWORD index = 0, result = 0, size = sizeof (result);
  204940. if (HttpQueryInfo (crs->request, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &result, &size, &index))
  204941. return (int64) result;
  204942. }
  204943. return -1;
  204944. }
  204945. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  204946. {
  204947. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  204948. if (crs != 0)
  204949. {
  204950. DWORD bufferSizeBytes = 4096;
  204951. for (;;)
  204952. {
  204953. HeapBlock<char> buffer ((size_t) bufferSizeBytes);
  204954. if (HttpQueryInfo (crs->request, HTTP_QUERY_RAW_HEADERS_CRLF, buffer.getData(), &bufferSizeBytes, 0))
  204955. {
  204956. StringArray headersArray;
  204957. headersArray.addLines (reinterpret_cast <const WCHAR*> (buffer.getData()));
  204958. for (int i = 0; i < headersArray.size(); ++i)
  204959. {
  204960. const String& header = headersArray[i];
  204961. const String key (header.upToFirstOccurrenceOf (": ", false, false));
  204962. const String value (header.fromFirstOccurrenceOf (": ", false, false));
  204963. const String previousValue (headers [key]);
  204964. headers.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  204965. }
  204966. break;
  204967. }
  204968. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
  204969. break;
  204970. }
  204971. }
  204972. }
  204973. void juce_closeInternetFile (void* handle)
  204974. {
  204975. if (handle != 0)
  204976. {
  204977. ScopedPointer <ConnectionAndRequestStruct> crs (static_cast <ConnectionAndRequestStruct*> (handle));
  204978. InternetCloseHandle (crs->request);
  204979. InternetCloseHandle (crs->connection);
  204980. }
  204981. }
  204982. static int getMACAddressViaGetAdaptersInfo (int64* addresses, int maxNum, const bool littleEndian) throw()
  204983. {
  204984. int numFound = 0;
  204985. DynamicLibraryLoader dll ("iphlpapi.dll");
  204986. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  204987. if (getAdaptersInfo != 0)
  204988. {
  204989. ULONG len = sizeof (IP_ADAPTER_INFO);
  204990. MemoryBlock mb;
  204991. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  204992. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  204993. {
  204994. mb.setSize (len);
  204995. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  204996. }
  204997. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  204998. {
  204999. PIP_ADAPTER_INFO adapter = adapterInfo;
  205000. while (adapter != 0)
  205001. {
  205002. int64 mac = 0;
  205003. for (unsigned int i = 0; i < adapter->AddressLength; ++i)
  205004. mac = (mac << 8) | adapter->Address[i];
  205005. if (littleEndian)
  205006. mac = (int64) ByteOrder::swap ((uint64) mac);
  205007. if (numFound < maxNum && mac != 0)
  205008. addresses [numFound++] = mac;
  205009. adapter = adapter->Next;
  205010. }
  205011. }
  205012. }
  205013. return numFound;
  205014. }
  205015. static int getMACAddressesViaNetBios (int64* addresses, int maxNum, const bool littleEndian) throw()
  205016. {
  205017. int numFound = 0;
  205018. DynamicLibraryLoader dll ("netapi32.dll");
  205019. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  205020. if (NetbiosCall != 0)
  205021. {
  205022. NCB ncb;
  205023. zerostruct (ncb);
  205024. struct ASTAT
  205025. {
  205026. ADAPTER_STATUS adapt;
  205027. NAME_BUFFER NameBuff [30];
  205028. };
  205029. ASTAT astat;
  205030. zeromem (&astat, sizeof (astat)); // (can't use zerostruct here in VC6)
  205031. LANA_ENUM enums;
  205032. zerostruct (enums);
  205033. ncb.ncb_command = NCBENUM;
  205034. ncb.ncb_buffer = (unsigned char*) &enums;
  205035. ncb.ncb_length = sizeof (LANA_ENUM);
  205036. NetbiosCall (&ncb);
  205037. for (int i = 0; i < enums.length; ++i)
  205038. {
  205039. zerostruct (ncb);
  205040. ncb.ncb_command = NCBRESET;
  205041. ncb.ncb_lana_num = enums.lana[i];
  205042. if (NetbiosCall (&ncb) == 0)
  205043. {
  205044. zerostruct (ncb);
  205045. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  205046. ncb.ncb_command = NCBASTAT;
  205047. ncb.ncb_lana_num = enums.lana[i];
  205048. ncb.ncb_buffer = (unsigned char*) &astat;
  205049. ncb.ncb_length = sizeof (ASTAT);
  205050. if (NetbiosCall (&ncb) == 0)
  205051. {
  205052. if (astat.adapt.adapter_type == 0xfe)
  205053. {
  205054. uint64 mac = 0;
  205055. for (int i = 6; --i >= 0;)
  205056. mac = (mac << 8) | astat.adapt.adapter_address [littleEndian ? i : (5 - i)];
  205057. if (numFound < maxNum && mac != 0)
  205058. addresses [numFound++] = mac;
  205059. }
  205060. }
  205061. }
  205062. }
  205063. }
  205064. return numFound;
  205065. }
  205066. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  205067. {
  205068. int numFound = getMACAddressViaGetAdaptersInfo (addresses, maxNum, littleEndian);
  205069. if (numFound == 0)
  205070. numFound = getMACAddressesViaNetBios (addresses, maxNum, littleEndian);
  205071. return numFound;
  205072. }
  205073. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  205074. const String& emailSubject,
  205075. const String& bodyText,
  205076. const StringArray& filesToAttach)
  205077. {
  205078. HMODULE h = LoadLibraryA ("MAPI32.dll");
  205079. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  205080. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  205081. bool ok = false;
  205082. if (mapiSendMail != 0)
  205083. {
  205084. MapiMessage message;
  205085. zerostruct (message);
  205086. message.lpszSubject = (LPSTR) emailSubject.toCString();
  205087. message.lpszNoteText = (LPSTR) bodyText.toCString();
  205088. MapiRecipDesc recip;
  205089. zerostruct (recip);
  205090. recip.ulRecipClass = MAPI_TO;
  205091. String targetEmailAddress_ (targetEmailAddress);
  205092. if (targetEmailAddress_.isEmpty())
  205093. targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address)
  205094. recip.lpszName = (LPSTR) targetEmailAddress_.toCString();
  205095. message.nRecipCount = 1;
  205096. message.lpRecips = &recip;
  205097. HeapBlock <MapiFileDesc> files;
  205098. files.calloc (filesToAttach.size());
  205099. message.nFileCount = filesToAttach.size();
  205100. message.lpFiles = files;
  205101. for (int i = 0; i < filesToAttach.size(); ++i)
  205102. {
  205103. files[i].nPosition = (ULONG) -1;
  205104. files[i].lpszPathName = (LPSTR) filesToAttach[i].toCString();
  205105. }
  205106. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  205107. }
  205108. FreeLibrary (h);
  205109. return ok;
  205110. }
  205111. #endif
  205112. /*** End of inlined file: juce_win32_Network.cpp ***/
  205113. /*** Start of inlined file: juce_win32_PlatformUtils.cpp ***/
  205114. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205115. // compiled on its own).
  205116. #if JUCE_INCLUDED_FILE
  205117. static HKEY findKeyForPath (String name,
  205118. const bool createForWriting,
  205119. String& valueName)
  205120. {
  205121. HKEY rootKey = 0;
  205122. if (name.startsWithIgnoreCase ("HKEY_CURRENT_USER\\"))
  205123. rootKey = HKEY_CURRENT_USER;
  205124. else if (name.startsWithIgnoreCase ("HKEY_LOCAL_MACHINE\\"))
  205125. rootKey = HKEY_LOCAL_MACHINE;
  205126. else if (name.startsWithIgnoreCase ("HKEY_CLASSES_ROOT\\"))
  205127. rootKey = HKEY_CLASSES_ROOT;
  205128. if (rootKey != 0)
  205129. {
  205130. name = name.substring (name.indexOfChar ('\\') + 1);
  205131. const int lastSlash = name.lastIndexOfChar ('\\');
  205132. valueName = name.substring (lastSlash + 1);
  205133. name = name.substring (0, lastSlash);
  205134. HKEY key;
  205135. DWORD result;
  205136. if (createForWriting)
  205137. {
  205138. if (RegCreateKeyEx (rootKey, name, 0, 0, REG_OPTION_NON_VOLATILE,
  205139. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  205140. return key;
  205141. }
  205142. else
  205143. {
  205144. if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS)
  205145. return key;
  205146. }
  205147. }
  205148. return 0;
  205149. }
  205150. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  205151. const String& defaultValue)
  205152. {
  205153. String valueName, result (defaultValue);
  205154. HKEY k = findKeyForPath (regValuePath, false, valueName);
  205155. if (k != 0)
  205156. {
  205157. WCHAR buffer [2048];
  205158. unsigned long bufferSize = sizeof (buffer);
  205159. DWORD type = REG_SZ;
  205160. if (RegQueryValueEx (k, valueName, 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  205161. {
  205162. if (type == REG_SZ)
  205163. result = buffer;
  205164. else if (type == REG_DWORD)
  205165. result = String ((int) *(DWORD*) buffer);
  205166. }
  205167. RegCloseKey (k);
  205168. }
  205169. return result;
  205170. }
  205171. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  205172. const String& value)
  205173. {
  205174. String valueName;
  205175. HKEY k = findKeyForPath (regValuePath, true, valueName);
  205176. if (k != 0)
  205177. {
  205178. RegSetValueEx (k, valueName, 0, REG_SZ,
  205179. (const BYTE*) (const WCHAR*) value,
  205180. sizeof (WCHAR) * (value.length() + 1));
  205181. RegCloseKey (k);
  205182. }
  205183. }
  205184. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  205185. {
  205186. bool exists = false;
  205187. String valueName;
  205188. HKEY k = findKeyForPath (regValuePath, false, valueName);
  205189. if (k != 0)
  205190. {
  205191. unsigned char buffer [2048];
  205192. unsigned long bufferSize = sizeof (buffer);
  205193. DWORD type = 0;
  205194. if (RegQueryValueEx (k, valueName, 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  205195. exists = true;
  205196. RegCloseKey (k);
  205197. }
  205198. return exists;
  205199. }
  205200. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  205201. {
  205202. String valueName;
  205203. HKEY k = findKeyForPath (regValuePath, true, valueName);
  205204. if (k != 0)
  205205. {
  205206. RegDeleteValue (k, valueName);
  205207. RegCloseKey (k);
  205208. }
  205209. }
  205210. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  205211. {
  205212. String valueName;
  205213. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  205214. if (k != 0)
  205215. {
  205216. RegDeleteKey (k, valueName);
  205217. RegCloseKey (k);
  205218. }
  205219. }
  205220. void PlatformUtilities::registerFileAssociation (const String& fileExtension,
  205221. const String& symbolicDescription,
  205222. const String& fullDescription,
  205223. const File& targetExecutable,
  205224. int iconResourceNumber)
  205225. {
  205226. setRegistryValue ("HKEY_CLASSES_ROOT\\" + fileExtension + "\\", symbolicDescription);
  205227. const String key ("HKEY_CLASSES_ROOT\\" + symbolicDescription);
  205228. if (iconResourceNumber != 0)
  205229. setRegistryValue (key + "\\DefaultIcon\\",
  205230. targetExecutable.getFullPathName() + "," + String (-iconResourceNumber));
  205231. setRegistryValue (key + "\\", fullDescription);
  205232. setRegistryValue (key + "\\shell\\open\\command\\",
  205233. targetExecutable.getFullPathName() + " %1");
  205234. }
  205235. bool juce_IsRunningInWine()
  205236. {
  205237. HKEY key;
  205238. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  205239. {
  205240. RegCloseKey (key);
  205241. return true;
  205242. }
  205243. return false;
  205244. }
  205245. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams()
  205246. {
  205247. String s (::GetCommandLineW());
  205248. StringArray tokens;
  205249. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  205250. return tokens.joinIntoString (" ", 1);
  205251. }
  205252. static void* currentModuleHandle = 0;
  205253. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  205254. {
  205255. if (currentModuleHandle == 0)
  205256. currentModuleHandle = GetModuleHandle (0);
  205257. return currentModuleHandle;
  205258. }
  205259. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  205260. {
  205261. currentModuleHandle = newHandle;
  205262. }
  205263. void PlatformUtilities::fpuReset()
  205264. {
  205265. #if JUCE_MSVC
  205266. _clearfp();
  205267. #endif
  205268. }
  205269. void PlatformUtilities::beep()
  205270. {
  205271. MessageBeep (MB_OK);
  205272. }
  205273. #endif
  205274. /*** End of inlined file: juce_win32_PlatformUtils.cpp ***/
  205275. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  205276. /*** Start of inlined file: juce_win32_Messaging.cpp ***/
  205277. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205278. // compiled on its own).
  205279. #if JUCE_INCLUDED_FILE
  205280. static const unsigned int specialId = WM_APP + 0x4400;
  205281. static const unsigned int broadcastId = WM_APP + 0x4403;
  205282. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  205283. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  205284. HWND juce_messageWindowHandle = 0;
  205285. extern long improbableWindowNumber; // defined in windowing.cpp
  205286. #ifndef WM_APPCOMMAND
  205287. #define WM_APPCOMMAND 0x0319
  205288. #endif
  205289. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  205290. const UINT message,
  205291. const WPARAM wParam,
  205292. const LPARAM lParam) throw()
  205293. {
  205294. JUCE_TRY
  205295. {
  205296. if (h == juce_messageWindowHandle)
  205297. {
  205298. if (message == specialCallbackId)
  205299. {
  205300. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  205301. return (LRESULT) (*func) ((void*) lParam);
  205302. }
  205303. else if (message == specialId)
  205304. {
  205305. // these are trapped early in the dispatch call, but must also be checked
  205306. // here in case there are windows modal dialog boxes doing their own
  205307. // dispatch loop and not calling our version
  205308. MessageManager::getInstance()->deliverMessage ((Message*) lParam);
  205309. return 0;
  205310. }
  205311. else if (message == broadcastId)
  205312. {
  205313. const ScopedPointer <String> messageString ((String*) lParam);
  205314. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  205315. return 0;
  205316. }
  205317. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  205318. {
  205319. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  205320. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  205321. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  205322. return 0;
  205323. }
  205324. }
  205325. }
  205326. JUCE_CATCH_EXCEPTION
  205327. return DefWindowProc (h, message, wParam, lParam);
  205328. }
  205329. static bool isEventBlockedByModalComps (MSG& m)
  205330. {
  205331. if (Component::getNumCurrentlyModalComponents() == 0
  205332. || GetWindowLong (m.hwnd, GWLP_USERDATA) == improbableWindowNumber)
  205333. return false;
  205334. switch (m.message)
  205335. {
  205336. case WM_MOUSEMOVE:
  205337. case WM_NCMOUSEMOVE:
  205338. case 0x020A: /* WM_MOUSEWHEEL */
  205339. case 0x020E: /* WM_MOUSEHWHEEL */
  205340. case WM_KEYUP:
  205341. case WM_SYSKEYUP:
  205342. case WM_CHAR:
  205343. case WM_APPCOMMAND:
  205344. case WM_LBUTTONUP:
  205345. case WM_MBUTTONUP:
  205346. case WM_RBUTTONUP:
  205347. case WM_MOUSEACTIVATE:
  205348. case WM_NCMOUSEHOVER:
  205349. case WM_MOUSEHOVER:
  205350. return true;
  205351. case WM_NCLBUTTONDOWN:
  205352. case WM_NCLBUTTONDBLCLK:
  205353. case WM_NCRBUTTONDOWN:
  205354. case WM_NCRBUTTONDBLCLK:
  205355. case WM_NCMBUTTONDOWN:
  205356. case WM_NCMBUTTONDBLCLK:
  205357. case WM_LBUTTONDOWN:
  205358. case WM_LBUTTONDBLCLK:
  205359. case WM_MBUTTONDOWN:
  205360. case WM_MBUTTONDBLCLK:
  205361. case WM_RBUTTONDOWN:
  205362. case WM_RBUTTONDBLCLK:
  205363. case WM_KEYDOWN:
  205364. case WM_SYSKEYDOWN:
  205365. {
  205366. Component* const modal = Component::getCurrentlyModalComponent (0);
  205367. if (modal != 0)
  205368. modal->inputAttemptWhenModal();
  205369. return true;
  205370. }
  205371. default:
  205372. break;
  205373. }
  205374. return false;
  205375. }
  205376. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  205377. {
  205378. MSG m;
  205379. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  205380. return false;
  205381. if (GetMessage (&m, (HWND) 0, 0, 0) >= 0)
  205382. {
  205383. if (m.message == specialId && m.hwnd == juce_messageWindowHandle)
  205384. {
  205385. MessageManager::getInstance()->deliverMessage ((Message*) (void*) m.lParam);
  205386. }
  205387. else if (m.message == WM_QUIT)
  205388. {
  205389. if (JUCEApplication::getInstance() != 0)
  205390. JUCEApplication::getInstance()->systemRequestedQuit();
  205391. }
  205392. else if (! isEventBlockedByModalComps (m))
  205393. {
  205394. if ((m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN)
  205395. && GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber)
  205396. {
  205397. // if it's someone else's window being clicked on, and the focus is
  205398. // currently on a juce window, pass the kb focus over..
  205399. HWND currentFocus = GetFocus();
  205400. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  205401. SetFocus (m.hwnd);
  205402. }
  205403. TranslateMessage (&m);
  205404. DispatchMessage (&m);
  205405. }
  205406. }
  205407. return true;
  205408. }
  205409. bool juce_postMessageToSystemQueue (Message* message)
  205410. {
  205411. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  205412. }
  205413. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  205414. void* userData)
  205415. {
  205416. if (MessageManager::getInstance()->isThisTheMessageThread())
  205417. {
  205418. return (*callback) (userData);
  205419. }
  205420. else
  205421. {
  205422. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  205423. // deadlock because the message manager is blocked from running, and can't
  205424. // call your function..
  205425. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  205426. return (void*) SendMessage (juce_messageWindowHandle,
  205427. specialCallbackId,
  205428. (WPARAM) callback,
  205429. (LPARAM) userData);
  205430. }
  205431. }
  205432. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  205433. {
  205434. if (hwnd != juce_messageWindowHandle)
  205435. reinterpret_cast <Array<void*>*> (lParam)->add ((void*) hwnd);
  205436. return TRUE;
  205437. }
  205438. void MessageManager::broadcastMessage (const String& value)
  205439. {
  205440. Array<void*> windows;
  205441. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  205442. const String localCopy (value);
  205443. COPYDATASTRUCT data;
  205444. data.dwData = broadcastId;
  205445. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  205446. data.lpData = (void*) static_cast <const juce_wchar*> (localCopy);
  205447. for (int i = windows.size(); --i >= 0;)
  205448. {
  205449. HWND hwnd = (HWND) windows.getUnchecked(i);
  205450. TCHAR windowName [64]; // no need to read longer strings than this
  205451. GetWindowText (hwnd, windowName, 64);
  205452. windowName [63] = 0;
  205453. if (String (windowName) == messageWindowName)
  205454. {
  205455. DWORD_PTR result;
  205456. SendMessageTimeout (hwnd, WM_COPYDATA,
  205457. (WPARAM) juce_messageWindowHandle,
  205458. (LPARAM) &data,
  205459. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  205460. 8000,
  205461. &result);
  205462. }
  205463. }
  205464. }
  205465. static const String getMessageWindowClassName()
  205466. {
  205467. // this name has to be different for each app/dll instance because otherwise
  205468. // poor old Win32 can get a bit confused (even despite it not being a process-global
  205469. // window class).
  205470. static int number = 0;
  205471. if (number == 0)
  205472. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  205473. return "JUCEcs_" + String (number);
  205474. }
  205475. void MessageManager::doPlatformSpecificInitialisation()
  205476. {
  205477. OleInitialize (0);
  205478. const String className (getMessageWindowClassName());
  205479. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  205480. WNDCLASSEX wc;
  205481. zerostruct (wc);
  205482. wc.cbSize = sizeof (wc);
  205483. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  205484. wc.cbWndExtra = 4;
  205485. wc.hInstance = hmod;
  205486. wc.lpszClassName = className;
  205487. RegisterClassEx (&wc);
  205488. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  205489. messageWindowName,
  205490. 0, 0, 0, 0, 0, 0, 0,
  205491. hmod, 0);
  205492. }
  205493. void MessageManager::doPlatformSpecificShutdown()
  205494. {
  205495. DestroyWindow (juce_messageWindowHandle);
  205496. UnregisterClass (getMessageWindowClassName(), 0);
  205497. OleUninitialize();
  205498. }
  205499. #endif
  205500. /*** End of inlined file: juce_win32_Messaging.cpp ***/
  205501. /*** Start of inlined file: juce_win32_Fonts.cpp ***/
  205502. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205503. // compiled on its own).
  205504. #if JUCE_INCLUDED_FILE
  205505. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  205506. NEWTEXTMETRICEXW*,
  205507. int type,
  205508. LPARAM lParam)
  205509. {
  205510. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205511. {
  205512. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205513. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters ("@"));
  205514. }
  205515. return 1;
  205516. }
  205517. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  205518. NEWTEXTMETRICEXW*,
  205519. int type,
  205520. LPARAM lParam)
  205521. {
  205522. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205523. {
  205524. LOGFONTW lf;
  205525. zerostruct (lf);
  205526. lf.lfWeight = FW_DONTCARE;
  205527. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205528. lf.lfQuality = DEFAULT_QUALITY;
  205529. lf.lfCharSet = DEFAULT_CHARSET;
  205530. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205531. lf.lfPitchAndFamily = FF_DONTCARE;
  205532. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205533. fontName.copyToUnicode (lf.lfFaceName, LF_FACESIZE - 1);
  205534. HDC dc = CreateCompatibleDC (0);
  205535. EnumFontFamiliesEx (dc, &lf,
  205536. (FONTENUMPROCW) &wfontEnum2,
  205537. lParam, 0);
  205538. DeleteDC (dc);
  205539. }
  205540. return 1;
  205541. }
  205542. const StringArray Font::findAllTypefaceNames()
  205543. {
  205544. StringArray results;
  205545. HDC dc = CreateCompatibleDC (0);
  205546. {
  205547. LOGFONTW lf;
  205548. zerostruct (lf);
  205549. lf.lfWeight = FW_DONTCARE;
  205550. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205551. lf.lfQuality = DEFAULT_QUALITY;
  205552. lf.lfCharSet = DEFAULT_CHARSET;
  205553. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205554. lf.lfPitchAndFamily = FF_DONTCARE;
  205555. lf.lfFaceName[0] = 0;
  205556. EnumFontFamiliesEx (dc, &lf,
  205557. (FONTENUMPROCW) &wfontEnum1,
  205558. (LPARAM) &results, 0);
  205559. }
  205560. DeleteDC (dc);
  205561. results.sort (true);
  205562. return results;
  205563. }
  205564. extern bool juce_IsRunningInWine();
  205565. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  205566. {
  205567. if (juce_IsRunningInWine())
  205568. {
  205569. // If we're running in Wine, then use fonts that might be available on Linux..
  205570. defaultSans = "Bitstream Vera Sans";
  205571. defaultSerif = "Bitstream Vera Serif";
  205572. defaultFixed = "Bitstream Vera Sans Mono";
  205573. }
  205574. else
  205575. {
  205576. defaultSans = "Verdana";
  205577. defaultSerif = "Times";
  205578. defaultFixed = "Lucida Console";
  205579. }
  205580. }
  205581. class FontDCHolder : private DeletedAtShutdown
  205582. {
  205583. public:
  205584. FontDCHolder()
  205585. : dc (0), numKPs (0), size (0),
  205586. bold (false), italic (false)
  205587. {
  205588. }
  205589. ~FontDCHolder()
  205590. {
  205591. if (dc != 0)
  205592. {
  205593. DeleteDC (dc);
  205594. DeleteObject (fontH);
  205595. }
  205596. clearSingletonInstance();
  205597. }
  205598. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  205599. HDC loadFont (const String& fontName_, const bool bold_, const bool italic_, const int size_)
  205600. {
  205601. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  205602. {
  205603. fontName = fontName_;
  205604. bold = bold_;
  205605. italic = italic_;
  205606. size = size_;
  205607. if (dc != 0)
  205608. {
  205609. DeleteDC (dc);
  205610. DeleteObject (fontH);
  205611. kps.free();
  205612. }
  205613. fontH = 0;
  205614. dc = CreateCompatibleDC (0);
  205615. SetMapperFlags (dc, 0);
  205616. SetMapMode (dc, MM_TEXT);
  205617. LOGFONTW lfw;
  205618. zerostruct (lfw);
  205619. lfw.lfCharSet = DEFAULT_CHARSET;
  205620. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205621. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205622. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  205623. lfw.lfQuality = PROOF_QUALITY;
  205624. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  205625. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  205626. fontName.copyToUnicode (lfw.lfFaceName, LF_FACESIZE - 1);
  205627. lfw.lfHeight = size > 0 ? size : -256;
  205628. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  205629. if (standardSizedFont != 0)
  205630. {
  205631. if (SelectObject (dc, standardSizedFont) != 0)
  205632. {
  205633. fontH = standardSizedFont;
  205634. if (size == 0)
  205635. {
  205636. OUTLINETEXTMETRIC otm;
  205637. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  205638. {
  205639. lfw.lfHeight = -(int) otm.otmEMSquare;
  205640. fontH = CreateFontIndirect (&lfw);
  205641. SelectObject (dc, fontH);
  205642. DeleteObject (standardSizedFont);
  205643. }
  205644. }
  205645. }
  205646. else
  205647. {
  205648. jassertfalse;
  205649. }
  205650. }
  205651. else
  205652. {
  205653. jassertfalse;
  205654. }
  205655. }
  205656. return dc;
  205657. }
  205658. KERNINGPAIR* getKerningPairs (int& numKPs_)
  205659. {
  205660. if (kps == 0)
  205661. {
  205662. numKPs = GetKerningPairs (dc, 0, 0);
  205663. kps.calloc (numKPs);
  205664. GetKerningPairs (dc, numKPs, kps);
  205665. }
  205666. numKPs_ = numKPs;
  205667. return kps;
  205668. }
  205669. private:
  205670. HFONT fontH;
  205671. HDC dc;
  205672. String fontName;
  205673. HeapBlock <KERNINGPAIR> kps;
  205674. int numKPs, size;
  205675. bool bold, italic;
  205676. FontDCHolder (const FontDCHolder&);
  205677. FontDCHolder& operator= (const FontDCHolder&);
  205678. };
  205679. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  205680. class WindowsTypeface : public CustomTypeface
  205681. {
  205682. public:
  205683. WindowsTypeface (const Font& font)
  205684. {
  205685. HDC dc = FontDCHolder::getInstance()->loadFont (font.getTypefaceName(),
  205686. font.isBold(), font.isItalic(), 0);
  205687. TEXTMETRIC tm;
  205688. tm.tmAscent = tm.tmHeight = 1;
  205689. tm.tmDefaultChar = 0;
  205690. GetTextMetrics (dc, &tm);
  205691. setCharacteristics (font.getTypefaceName(),
  205692. tm.tmAscent / (float) tm.tmHeight,
  205693. font.isBold(), font.isItalic(),
  205694. tm.tmDefaultChar);
  205695. }
  205696. bool loadGlyphIfPossible (juce_wchar character)
  205697. {
  205698. HDC dc = FontDCHolder::getInstance()->loadFont (name, isBold, isItalic, 0);
  205699. GLYPHMETRICS gm;
  205700. {
  205701. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  205702. WORD index = 0;
  205703. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  205704. && index == 0xffff)
  205705. {
  205706. return false;
  205707. }
  205708. }
  205709. Path glyphPath;
  205710. TEXTMETRIC tm;
  205711. if (! GetTextMetrics (dc, &tm))
  205712. {
  205713. addGlyph (character, glyphPath, 0);
  205714. return true;
  205715. }
  205716. const float height = (float) tm.tmHeight;
  205717. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  205718. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  205719. &gm, 0, 0, &identityMatrix);
  205720. if (bufSize > 0)
  205721. {
  205722. HeapBlock<char> data (bufSize);
  205723. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  205724. bufSize, data, &identityMatrix);
  205725. const TTPOLYGONHEADER* pheader = reinterpret_cast<TTPOLYGONHEADER*> (data.getData());
  205726. const float scaleX = 1.0f / height;
  205727. const float scaleY = -1.0f / height;
  205728. while ((char*) pheader < data + bufSize)
  205729. {
  205730. float x = scaleX * pheader->pfxStart.x.value;
  205731. float y = scaleY * pheader->pfxStart.y.value;
  205732. glyphPath.startNewSubPath (x, y);
  205733. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  205734. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  205735. while ((const char*) curve < curveEnd)
  205736. {
  205737. if (curve->wType == TT_PRIM_LINE)
  205738. {
  205739. for (int i = 0; i < curve->cpfx; ++i)
  205740. {
  205741. x = scaleX * curve->apfx[i].x.value;
  205742. y = scaleY * curve->apfx[i].y.value;
  205743. glyphPath.lineTo (x, y);
  205744. }
  205745. }
  205746. else if (curve->wType == TT_PRIM_QSPLINE)
  205747. {
  205748. for (int i = 0; i < curve->cpfx - 1; ++i)
  205749. {
  205750. const float x2 = scaleX * curve->apfx[i].x.value;
  205751. const float y2 = scaleY * curve->apfx[i].y.value;
  205752. float x3, y3;
  205753. if (i < curve->cpfx - 2)
  205754. {
  205755. x3 = 0.5f * (x2 + scaleX * curve->apfx[i + 1].x.value);
  205756. y3 = 0.5f * (y2 + scaleY * curve->apfx[i + 1].y.value);
  205757. }
  205758. else
  205759. {
  205760. x3 = scaleX * curve->apfx[i + 1].x.value;
  205761. y3 = scaleY * curve->apfx[i + 1].y.value;
  205762. }
  205763. glyphPath.quadraticTo (x2, y2, x3, y3);
  205764. x = x3;
  205765. y = y3;
  205766. }
  205767. }
  205768. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  205769. }
  205770. pheader = (const TTPOLYGONHEADER*) curve;
  205771. glyphPath.closeSubPath();
  205772. }
  205773. }
  205774. addGlyph (character, glyphPath, gm.gmCellIncX / height);
  205775. int numKPs;
  205776. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  205777. for (int i = 0; i < numKPs; ++i)
  205778. {
  205779. if (kps[i].wFirst == character)
  205780. addKerningPair (kps[i].wFirst, kps[i].wSecond,
  205781. kps[i].iKernAmount / height);
  205782. }
  205783. return true;
  205784. }
  205785. juce_UseDebuggingNewOperator
  205786. };
  205787. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  205788. {
  205789. return new WindowsTypeface (font);
  205790. }
  205791. #endif
  205792. /*** End of inlined file: juce_win32_Fonts.cpp ***/
  205793. /*** Start of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  205794. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205795. // compiled on its own).
  205796. #if JUCE_INCLUDED_FILE && JUCE_DIRECT2D
  205797. class SharedD2DFactory : public DeletedAtShutdown
  205798. {
  205799. public:
  205800. SharedD2DFactory()
  205801. {
  205802. D2D1CreateFactory (D2D1_FACTORY_TYPE_SINGLE_THREADED, &d2dFactory);
  205803. DWriteCreateFactory (DWRITE_FACTORY_TYPE_SHARED, __uuidof (IDWriteFactory), (IUnknown**) &directWriteFactory);
  205804. if (directWriteFactory != 0)
  205805. directWriteFactory->GetSystemFontCollection (&systemFonts);
  205806. }
  205807. ~SharedD2DFactory()
  205808. {
  205809. clearSingletonInstance();
  205810. }
  205811. juce_DeclareSingleton (SharedD2DFactory, false);
  205812. ComSmartPtr <ID2D1Factory> d2dFactory;
  205813. ComSmartPtr <IDWriteFactory> directWriteFactory;
  205814. ComSmartPtr <IDWriteFontCollection> systemFonts;
  205815. };
  205816. juce_ImplementSingleton (SharedD2DFactory)
  205817. class Direct2DLowLevelGraphicsContext : public LowLevelGraphicsContext
  205818. {
  205819. public:
  205820. Direct2DLowLevelGraphicsContext (HWND hwnd_)
  205821. : hwnd (hwnd_),
  205822. currentState (0)
  205823. {
  205824. RECT windowRect;
  205825. GetClientRect (hwnd, &windowRect);
  205826. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  205827. bounds.setSize (size.width, size.height);
  205828. D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties();
  205829. D2D1_HWND_RENDER_TARGET_PROPERTIES propsHwnd = D2D1::HwndRenderTargetProperties (hwnd, size);
  205830. HRESULT hr = SharedD2DFactory::getInstance()->d2dFactory->CreateHwndRenderTarget (props, propsHwnd, &renderingTarget);
  205831. // xxx check for error
  205832. hr = renderingTarget->CreateSolidColorBrush (D2D1::ColorF::ColorF (0.0f, 0.0f, 0.0f, 1.0f), &colourBrush);
  205833. }
  205834. ~Direct2DLowLevelGraphicsContext()
  205835. {
  205836. states.clear();
  205837. }
  205838. void resized()
  205839. {
  205840. RECT windowRect;
  205841. GetClientRect (hwnd, &windowRect);
  205842. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  205843. renderingTarget->Resize (size);
  205844. bounds.setSize (size.width, size.height);
  205845. }
  205846. void clear()
  205847. {
  205848. renderingTarget->Clear (D2D1::ColorF (D2D1::ColorF::White, 0.0f)); // xxx why white and not black?
  205849. }
  205850. void start()
  205851. {
  205852. renderingTarget->BeginDraw();
  205853. saveState();
  205854. }
  205855. void end()
  205856. {
  205857. states.clear();
  205858. currentState = 0;
  205859. renderingTarget->EndDraw();
  205860. renderingTarget->CheckWindowState();
  205861. }
  205862. bool isVectorDevice() const { return false; }
  205863. void setOrigin (int x, int y)
  205864. {
  205865. currentState->origin.addXY (x, y);
  205866. }
  205867. bool clipToRectangle (const Rectangle<int>& r)
  205868. {
  205869. currentState->clipToRectangle (r);
  205870. return ! isClipEmpty();
  205871. }
  205872. bool clipToRectangleList (const RectangleList& clipRegion)
  205873. {
  205874. currentState->clipToRectList (rectListToPathGeometry (clipRegion));
  205875. return ! isClipEmpty();
  205876. }
  205877. void excludeClipRectangle (const Rectangle<int>&)
  205878. {
  205879. //xxx
  205880. }
  205881. void clipToPath (const Path& path, const AffineTransform& transform)
  205882. {
  205883. currentState->clipToPath (pathToPathGeometry (path, transform, currentState->origin));
  205884. }
  205885. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  205886. {
  205887. currentState->clipToImage (sourceImage,transform);
  205888. }
  205889. bool clipRegionIntersects (const Rectangle<int>& r)
  205890. {
  205891. const Rectangle<int> r2 (r + currentState->origin);
  205892. return currentState->clipRect.intersects (r2);
  205893. }
  205894. const Rectangle<int> getClipBounds() const
  205895. {
  205896. // xxx could this take into account complex clip regions?
  205897. return currentState->clipRect - currentState->origin;
  205898. }
  205899. bool isClipEmpty() const
  205900. {
  205901. return currentState->clipRect.isEmpty();
  205902. }
  205903. void saveState()
  205904. {
  205905. states.add (new SavedState (*this));
  205906. currentState = states.getLast();
  205907. }
  205908. void restoreState()
  205909. {
  205910. jassert (states.size() > 1) //you should never pop the last state!
  205911. states.removeLast (1);
  205912. currentState = states.getLast();
  205913. }
  205914. void setFill (const FillType& fillType)
  205915. {
  205916. currentState->setFill (fillType);
  205917. }
  205918. void setOpacity (float newOpacity)
  205919. {
  205920. currentState->setOpacity (newOpacity);
  205921. }
  205922. void setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  205923. {
  205924. }
  205925. void fillRect (const Rectangle<int>& r, bool replaceExistingContents)
  205926. {
  205927. currentState->createBrush();
  205928. renderingTarget->FillRectangle (rectangleToRectF (r + currentState->origin), currentState->currentBrush);
  205929. }
  205930. void fillPath (const Path& p, const AffineTransform& transform)
  205931. {
  205932. currentState->createBrush();
  205933. ComSmartPtr <ID2D1Geometry> geometry (pathToPathGeometry (p, transform, currentState->origin));
  205934. if (renderingTarget != 0)
  205935. renderingTarget->FillGeometry (geometry, currentState->currentBrush);
  205936. }
  205937. void drawImage (const Image& image, const AffineTransform& transform, bool fillEntireClipAsTiles)
  205938. {
  205939. const int x = currentState->origin.getX();
  205940. const int y = currentState->origin.getY();
  205941. renderingTarget->SetTransform (transfromToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  205942. D2D1_SIZE_U size;
  205943. size.width = image.getWidth();
  205944. size.height = image.getHeight();
  205945. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  205946. Image img (image.convertedToFormat (Image::ARGB));
  205947. Image::BitmapData bd (img, false);
  205948. bp.pixelFormat = renderingTarget->GetPixelFormat();
  205949. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  205950. {
  205951. ComSmartPtr <ID2D1Bitmap> tempBitmap;
  205952. renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &tempBitmap);
  205953. if (tempBitmap != 0)
  205954. renderingTarget->DrawBitmap (tempBitmap);
  205955. }
  205956. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  205957. }
  205958. void drawLine (const Line <float>& line)
  205959. {
  205960. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  205961. const Line<float> l (line.getStart() + currentState->origin.toFloat(),
  205962. line.getEnd() + currentState->origin.toFloat());
  205963. currentState->createBrush();
  205964. renderingTarget->DrawLine (D2D1::Point2F (l.getStartX(), l.getStartY()),
  205965. D2D1::Point2F (l.getEndX(), l.getEndY()),
  205966. currentState->currentBrush);
  205967. }
  205968. void drawVerticalLine (int x, float top, float bottom)
  205969. {
  205970. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  205971. currentState->createBrush();
  205972. x += currentState->origin.getX();
  205973. const int y = currentState->origin.getY();
  205974. renderingTarget->DrawLine (D2D1::Point2F (x, y + top),
  205975. D2D1::Point2F (x, y + bottom),
  205976. currentState->currentBrush);
  205977. }
  205978. void drawHorizontalLine (int y, float left, float right)
  205979. {
  205980. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  205981. currentState->createBrush();
  205982. y += currentState->origin.getY();
  205983. const int x = currentState->origin.getX();
  205984. renderingTarget->DrawLine (D2D1::Point2F (x + left, y),
  205985. D2D1::Point2F (x + right, y),
  205986. currentState->currentBrush);
  205987. }
  205988. void setFont (const Font& newFont)
  205989. {
  205990. currentState->setFont (newFont);
  205991. }
  205992. const Font getFont()
  205993. {
  205994. return currentState->font;
  205995. }
  205996. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  205997. {
  205998. const float x = currentState->origin.getX();
  205999. const float y = currentState->origin.getY();
  206000. currentState->createBrush();
  206001. currentState->createFont();
  206002. float kerning = currentState->font.getExtraKerningFactor(); // xxx why does removing this line mess up the kerning??
  206003. float hScale = currentState->font.getHorizontalScale();
  206004. renderingTarget->SetTransform (D2D1::Matrix3x2F::Scale (hScale, 1) * transfromToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  206005. float dpiX = 0, dpiY = 0;
  206006. SharedD2DFactory::getInstance()->d2dFactory->GetDesktopDpi (&dpiX, &dpiY);
  206007. UINT32 glyphNum = glyphNumber;
  206008. UINT16 glyphNum1 = 0; // xxx needs a better name - what is this for?
  206009. currentState->currentFontFace->GetGlyphIndices (&glyphNum, 1, &glyphNum1);
  206010. DWRITE_GLYPH_OFFSET offset;
  206011. offset.advanceOffset = 0;
  206012. offset.ascenderOffset = 0;
  206013. float glyphAdvances = 0;
  206014. DWRITE_GLYPH_RUN glyph;
  206015. glyph.fontFace = currentState->currentFontFace;
  206016. glyph.glyphCount = 1;
  206017. glyph.glyphIndices = &glyphNum1;
  206018. glyph.isSideways = FALSE;
  206019. glyph.glyphAdvances = &glyphAdvances;
  206020. glyph.glyphOffsets = &offset;
  206021. glyph.fontEmSize = (float) currentState->font.getHeight() * dpiX / 96.0f * (1 + currentState->fontScaling) / 2;
  206022. renderingTarget->DrawGlyphRun (D2D1::Point2F (0, 0), &glyph, currentState->currentBrush);
  206023. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  206024. }
  206025. class SavedState
  206026. {
  206027. public:
  206028. SavedState (Direct2DLowLevelGraphicsContext& owner_)
  206029. : owner (owner_), currentBrush (0),
  206030. fontScaling (1.0f), currentFontFace (0),
  206031. clipsRect (false), shouldClipRect (false),
  206032. clipsRectList (false), shouldClipRectList (false),
  206033. clipsComplex (false), shouldClipComplex (false),
  206034. clipsBitmap (false), shouldClipBitmap (false)
  206035. {
  206036. if (owner.currentState != 0)
  206037. {
  206038. // xxx seems like a very slow way to create one of these, and this is a performance
  206039. // bottleneck.. Can the same internal objects be shared by multiple state objects, maybe using copy-on-write?
  206040. setFill (owner.currentState->fillType);
  206041. currentBrush = owner.currentState->currentBrush;
  206042. origin = owner.currentState->origin;
  206043. clipRect = owner.currentState->clipRect;
  206044. font = owner.currentState->font;
  206045. currentFontFace = owner.currentState->currentFontFace;
  206046. }
  206047. else
  206048. {
  206049. const D2D1_SIZE_U size (owner.renderingTarget->GetPixelSize());
  206050. clipRect.setSize (size.width, size.height);
  206051. setFill (FillType (Colours::black));
  206052. }
  206053. }
  206054. ~SavedState()
  206055. {
  206056. clearClip();
  206057. clearFont();
  206058. clearFill();
  206059. clearPathClip();
  206060. clearImageClip();
  206061. complexClipLayer = 0;
  206062. bitmapMaskLayer = 0;
  206063. }
  206064. void clearClip()
  206065. {
  206066. popClips();
  206067. shouldClipRect = false;
  206068. }
  206069. void clipToRectangle (const Rectangle<int>& r)
  206070. {
  206071. clearClip();
  206072. clipRect = r + origin;
  206073. shouldClipRect = true;
  206074. pushClips();
  206075. }
  206076. void clearPathClip()
  206077. {
  206078. popClips();
  206079. if (shouldClipComplex)
  206080. {
  206081. complexClipGeometry = 0;
  206082. shouldClipComplex = false;
  206083. }
  206084. }
  206085. void clipToPath (ID2D1Geometry* geometry)
  206086. {
  206087. clearPathClip();
  206088. if (complexClipLayer == 0)
  206089. owner.renderingTarget->CreateLayer (&complexClipLayer);
  206090. complexClipGeometry = geometry;
  206091. shouldClipComplex = true;
  206092. pushClips();
  206093. }
  206094. void clearRectListClip()
  206095. {
  206096. popClips();
  206097. if (shouldClipRectList)
  206098. {
  206099. rectListGeometry = 0;
  206100. shouldClipRectList = false;
  206101. }
  206102. }
  206103. void clipToRectList (ID2D1Geometry* geometry)
  206104. {
  206105. clearRectListClip();
  206106. if (rectListLayer == 0)
  206107. owner.renderingTarget->CreateLayer (&rectListLayer);
  206108. rectListGeometry = geometry;
  206109. shouldClipRectList = true;
  206110. pushClips();
  206111. }
  206112. void clearImageClip()
  206113. {
  206114. popClips();
  206115. if (shouldClipBitmap)
  206116. {
  206117. maskBitmap = 0;
  206118. bitmapMaskBrush = 0;
  206119. shouldClipBitmap = false;
  206120. }
  206121. }
  206122. void clipToImage (const Image& image, const AffineTransform& transform)
  206123. {
  206124. clearImageClip();
  206125. if (bitmapMaskLayer == 0)
  206126. owner.renderingTarget->CreateLayer (&bitmapMaskLayer);
  206127. D2D1_BRUSH_PROPERTIES brushProps;
  206128. brushProps.opacity = 1;
  206129. brushProps.transform = transfromToMatrix (transform);
  206130. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP, D2D1_EXTEND_MODE_WRAP);
  206131. D2D1_SIZE_U size;
  206132. size.width = image.getWidth();
  206133. size.height = image.getHeight();
  206134. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206135. maskImage = image.convertedToFormat (Image::ARGB);
  206136. Image::BitmapData bd (this->image, false); // xxx should be maskImage?
  206137. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  206138. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206139. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &maskBitmap);
  206140. hr = owner.renderingTarget->CreateBitmapBrush (maskBitmap, bmProps, brushProps, &bitmapMaskBrush);
  206141. imageMaskLayerParams = D2D1::LayerParameters();
  206142. imageMaskLayerParams.opacityBrush = bitmapMaskBrush;
  206143. shouldClipBitmap = true;
  206144. pushClips();
  206145. }
  206146. void popClips()
  206147. {
  206148. if (clipsBitmap)
  206149. {
  206150. owner.renderingTarget->PopLayer();
  206151. clipsBitmap = false;
  206152. }
  206153. if (clipsComplex)
  206154. {
  206155. owner.renderingTarget->PopLayer();
  206156. clipsComplex = false;
  206157. }
  206158. if (clipsRectList)
  206159. {
  206160. owner.renderingTarget->PopLayer();
  206161. clipsRectList = false;
  206162. }
  206163. if (clipsRect)
  206164. {
  206165. owner.renderingTarget->PopAxisAlignedClip();
  206166. clipsRect = false;
  206167. }
  206168. }
  206169. void pushClips()
  206170. {
  206171. if (shouldClipRect && ! clipsRect)
  206172. {
  206173. owner.renderingTarget->PushAxisAlignedClip (rectangleToRectF (clipRect), D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
  206174. clipsRect = true;
  206175. }
  206176. if (shouldClipRectList && ! clipsRectList)
  206177. {
  206178. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  206179. rectListGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  206180. layerParams.geometricMask = rectListGeometry;
  206181. owner.renderingTarget->PushLayer (layerParams, rectListLayer);
  206182. clipsRectList = true;
  206183. }
  206184. if (shouldClipComplex && ! clipsComplex)
  206185. {
  206186. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  206187. complexClipGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  206188. layerParams.geometricMask = complexClipGeometry;
  206189. owner.renderingTarget->PushLayer (layerParams, complexClipLayer);
  206190. clipsComplex = true;
  206191. }
  206192. if (shouldClipBitmap && ! clipsBitmap)
  206193. {
  206194. owner.renderingTarget->PushLayer (imageMaskLayerParams, bitmapMaskLayer);
  206195. clipsBitmap = true;
  206196. }
  206197. }
  206198. void setFill (const FillType& newFillType)
  206199. {
  206200. if (fillType != newFillType)
  206201. {
  206202. fillType = newFillType;
  206203. clearFill();
  206204. }
  206205. }
  206206. void clearFont()
  206207. {
  206208. currentFontFace = localFontFace = 0;
  206209. }
  206210. void setFont (const Font& newFont)
  206211. {
  206212. if (font != newFont)
  206213. {
  206214. font = newFont;
  206215. clearFont();
  206216. }
  206217. }
  206218. void createFont()
  206219. {
  206220. // xxx The font shouldn't be managed by the graphics context.
  206221. // The correct way to handle font lifetimes is to use a subclass of Typeface - see
  206222. // MacTypeface and WindowsTypeface classes. D2D support could probably just be added to the
  206223. // WindowsTypeface class.
  206224. if (currentFontFace == 0)
  206225. {
  206226. WindowsTypeface* systemType = dynamic_cast<WindowsTypeface*> (font.getTypeface());
  206227. fontScaling = systemType->getAscent();
  206228. BOOL fontFound;
  206229. uint32 fontIndex;
  206230. IDWriteFontCollection* fonts = SharedD2DFactory::getInstance()->systemFonts;
  206231. fonts->FindFamilyName (systemType->getName(), &fontIndex, &fontFound);
  206232. if (! fontFound)
  206233. fontIndex = 0;
  206234. ComSmartPtr <IDWriteFontFamily> fontFam;
  206235. fonts->GetFontFamily (fontIndex, &fontFam);
  206236. ComSmartPtr <IDWriteFont> font;
  206237. DWRITE_FONT_WEIGHT weight = this->font.isBold() ? DWRITE_FONT_WEIGHT_BOLD : DWRITE_FONT_WEIGHT_NORMAL;
  206238. DWRITE_FONT_STYLE style = this->font.isItalic() ? DWRITE_FONT_STYLE_ITALIC : DWRITE_FONT_STYLE_NORMAL;
  206239. fontFam->GetFirstMatchingFont (weight, DWRITE_FONT_STRETCH_NORMAL, style, &font);
  206240. font->CreateFontFace (&localFontFace);
  206241. currentFontFace = localFontFace;
  206242. }
  206243. }
  206244. void setOpacity (float newOpacity)
  206245. {
  206246. fillType.setOpacity (newOpacity);
  206247. if (currentBrush != 0)
  206248. currentBrush->SetOpacity (newOpacity);
  206249. }
  206250. void clearFill()
  206251. {
  206252. gradientStops = 0;
  206253. linearGradient = 0;
  206254. radialGradient = 0;
  206255. bitmap = 0;
  206256. bitmapBrush = 0;
  206257. currentBrush = 0;
  206258. }
  206259. void createBrush()
  206260. {
  206261. if (currentBrush == 0)
  206262. {
  206263. const int x = origin.getX();
  206264. const int y = origin.getY();
  206265. if (fillType.isColour())
  206266. {
  206267. D2D1_COLOR_F colour = colourToD2D (fillType.colour);
  206268. owner.colourBrush->SetColor (colour);
  206269. currentBrush = owner.colourBrush;
  206270. }
  206271. else if (fillType.isTiledImage())
  206272. {
  206273. D2D1_BRUSH_PROPERTIES brushProps;
  206274. brushProps.opacity = fillType.getOpacity();
  206275. brushProps.transform = transfromToMatrix (fillType.transform);
  206276. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP,D2D1_EXTEND_MODE_WRAP);
  206277. image = fillType.image;
  206278. D2D1_SIZE_U size;
  206279. size.width = image.getWidth();
  206280. size.height = image.getHeight();
  206281. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206282. this->image = image.convertedToFormat (Image::ARGB);
  206283. Image::BitmapData bd (this->image, false);
  206284. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  206285. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206286. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &bitmap);
  206287. hr = owner.renderingTarget->CreateBitmapBrush (bitmap, bmProps, brushProps, &bitmapBrush);
  206288. currentBrush = bitmapBrush;
  206289. }
  206290. else if (fillType.isGradient())
  206291. {
  206292. gradientStops = 0;
  206293. D2D1_BRUSH_PROPERTIES brushProps;
  206294. brushProps.opacity = fillType.getOpacity();
  206295. brushProps.transform = transfromToMatrix (fillType.transform);
  206296. const int numColors = fillType.gradient->getNumColours();
  206297. HeapBlock<D2D1_GRADIENT_STOP> stops (numColors);
  206298. for (int i = fillType.gradient->getNumColours(); --i >= 0;)
  206299. {
  206300. stops[i].color = colourToD2D (fillType.gradient->getColour(i));
  206301. stops[i].position = fillType.gradient->getColourPosition(i);
  206302. }
  206303. owner.renderingTarget->CreateGradientStopCollection (stops.getData(), numColors, &gradientStops);
  206304. if (fillType.gradient->isRadial)
  206305. {
  206306. radialGradient = 0;
  206307. const Point<float>& p1 = fillType.gradient->point1;
  206308. const Point<float>& p2 = fillType.gradient->point2;
  206309. float r = p1.getDistanceFrom (p2);
  206310. D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES props =
  206311. D2D1::RadialGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206312. D2D1::Point2F (0, 0),
  206313. r, r);
  206314. owner.renderingTarget->CreateRadialGradientBrush (props, brushProps, gradientStops, &radialGradient);
  206315. currentBrush = radialGradient;
  206316. }
  206317. else
  206318. {
  206319. linearGradient = 0;
  206320. const Point<float>& p1 = fillType.gradient->point1;
  206321. const Point<float>& p2 = fillType.gradient->point2;
  206322. D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES props =
  206323. D2D1::LinearGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206324. D2D1::Point2F (p2.getX() + x, p2.getY() + y));
  206325. owner.renderingTarget->CreateLinearGradientBrush (props, brushProps, gradientStops, &linearGradient);
  206326. currentBrush = linearGradient;
  206327. }
  206328. }
  206329. }
  206330. }
  206331. juce_UseDebuggingNewOperator
  206332. //xxx most of these members should probably be private...
  206333. Direct2DLowLevelGraphicsContext& owner;
  206334. Point<int> origin;
  206335. Font font;
  206336. float fontScaling;
  206337. IDWriteFontFace* currentFontFace;
  206338. ComSmartPtr <IDWriteFontFace> localFontFace;
  206339. FillType fillType;
  206340. Image image;
  206341. ComSmartPtr <ID2D1Bitmap> bitmap; // xxx needs a better name - what is this for??
  206342. Rectangle<int> clipRect;
  206343. bool clipsRect, shouldClipRect;
  206344. ComSmartPtr <ID2D1Geometry> complexClipGeometry;
  206345. D2D1_LAYER_PARAMETERS complexClipLayerParams;
  206346. ComSmartPtr <ID2D1Layer> complexClipLayer;
  206347. bool clipsComplex, shouldClipComplex;
  206348. ComSmartPtr <ID2D1Geometry> rectListGeometry;
  206349. D2D1_LAYER_PARAMETERS rectListLayerParams;
  206350. ComSmartPtr <ID2D1Layer> rectListLayer;
  206351. bool clipsRectList, shouldClipRectList;
  206352. Image maskImage;
  206353. D2D1_LAYER_PARAMETERS imageMaskLayerParams;
  206354. ComSmartPtr <ID2D1Layer> bitmapMaskLayer;
  206355. ComSmartPtr <ID2D1Bitmap> maskBitmap;
  206356. ComSmartPtr <ID2D1BitmapBrush> bitmapMaskBrush;
  206357. bool clipsBitmap, shouldClipBitmap;
  206358. ID2D1Brush* currentBrush;
  206359. ComSmartPtr <ID2D1BitmapBrush> bitmapBrush;
  206360. ComSmartPtr <ID2D1LinearGradientBrush> linearGradient;
  206361. ComSmartPtr <ID2D1RadialGradientBrush> radialGradient;
  206362. ComSmartPtr <ID2D1GradientStopCollection> gradientStops;
  206363. private:
  206364. SavedState (const SavedState&);
  206365. SavedState& operator= (const SavedState& other);
  206366. };
  206367. juce_UseDebuggingNewOperator
  206368. private:
  206369. HWND hwnd;
  206370. ComSmartPtr <ID2D1HwndRenderTarget> renderingTarget;
  206371. ComSmartPtr <ID2D1SolidColorBrush> colourBrush;
  206372. Rectangle<int> bounds;
  206373. SavedState* currentState;
  206374. OwnedArray<SavedState> states;
  206375. static D2D1_RECT_F rectangleToRectF (const Rectangle<int>& r)
  206376. {
  206377. return D2D1::RectF ((float) r.getX(), (float) r.getY(), (float) r.getRight(), (float) r.getBottom());
  206378. }
  206379. static const D2D1_COLOR_F colourToD2D (const Colour& c)
  206380. {
  206381. return D2D1::ColorF::ColorF (c.getFloatRed(), c.getFloatGreen(), c.getFloatBlue(), c.getFloatAlpha());
  206382. }
  206383. static const D2D1_POINT_2F pointTransformed (int x, int y, const AffineTransform& transform = AffineTransform::identity)
  206384. {
  206385. transform.transformPoint (x, y);
  206386. return D2D1::Point2F (x, y);
  206387. }
  206388. static void rectToGeometrySink (const Rectangle<int>& rect, ID2D1GeometrySink* sink)
  206389. {
  206390. sink->BeginFigure (pointTransformed (rect.getX(), rect.getY()), D2D1_FIGURE_BEGIN_FILLED);
  206391. sink->AddLine (pointTransformed (rect.getRight(), rect.getY()));
  206392. sink->AddLine (pointTransformed (rect.getRight(), rect.getBottom()));
  206393. sink->AddLine (pointTransformed (rect.getX(), rect.getBottom()));
  206394. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206395. }
  206396. static ID2D1PathGeometry* rectListToPathGeometry (const RectangleList& clipRegion)
  206397. {
  206398. ID2D1PathGeometry* p = 0;
  206399. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206400. ComSmartPtr <ID2D1GeometrySink> sink;
  206401. HRESULT hr = p->Open (&sink); // xxx handle error
  206402. sink->SetFillMode (D2D1_FILL_MODE_WINDING);
  206403. for (int i = clipRegion.getNumRectangles(); --i >= 0;)
  206404. rectToGeometrySink (clipRegion.getRectangle(i), sink);
  206405. hr = sink->Close();
  206406. return p;
  206407. }
  206408. static void pathToGeometrySink (const Path& path, ID2D1GeometrySink* sink, const AffineTransform& transform, int x, int y)
  206409. {
  206410. Path::Iterator it (path);
  206411. while (it.next())
  206412. {
  206413. switch (it.elementType)
  206414. {
  206415. case Path::Iterator::cubicTo:
  206416. {
  206417. D2D1_BEZIER_SEGMENT seg;
  206418. transform.transformPoint (it.x1, it.y1);
  206419. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206420. transform.transformPoint (it.x2, it.y2);
  206421. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206422. transform.transformPoint(it.x3, it.y3);
  206423. seg.point3 = D2D1::Point2F (it.x3 + x, it.y3 + y);
  206424. sink->AddBezier (seg);
  206425. break;
  206426. }
  206427. case Path::Iterator::lineTo:
  206428. {
  206429. transform.transformPoint (it.x1, it.y1);
  206430. sink->AddLine (D2D1::Point2F (it.x1 + x, it.y1 + y));
  206431. break;
  206432. }
  206433. case Path::Iterator::quadraticTo:
  206434. {
  206435. D2D1_QUADRATIC_BEZIER_SEGMENT seg;
  206436. transform.transformPoint (it.x1, it.y1);
  206437. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206438. transform.transformPoint (it.x2, it.y2);
  206439. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206440. sink->AddQuadraticBezier (seg);
  206441. break;
  206442. }
  206443. case Path::Iterator::closePath:
  206444. {
  206445. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206446. break;
  206447. }
  206448. case Path::Iterator::startNewSubPath:
  206449. {
  206450. transform.transformPoint (it.x1, it.y1);
  206451. sink->BeginFigure (D2D1::Point2F (it.x1 + x, it.y1 + y), D2D1_FIGURE_BEGIN_FILLED);
  206452. break;
  206453. }
  206454. }
  206455. }
  206456. }
  206457. static ID2D1PathGeometry* pathToPathGeometry (const Path& path, const AffineTransform& transform, const Point<int>& point)
  206458. {
  206459. ID2D1PathGeometry* p = 0;
  206460. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206461. ComSmartPtr <ID2D1GeometrySink> sink;
  206462. HRESULT hr = p->Open (&sink);
  206463. sink->SetFillMode (D2D1_FILL_MODE_WINDING); // xxx need to check Path::isUsingNonZeroWinding()
  206464. pathToGeometrySink (path, sink, transform, point.getX(), point.getY());
  206465. hr = sink->Close();
  206466. return p;
  206467. }
  206468. static const D2D1::Matrix3x2F transfromToMatrix (const AffineTransform& transform)
  206469. {
  206470. D2D1::Matrix3x2F matrix;
  206471. matrix._11 = transform.mat00;
  206472. matrix._12 = transform.mat10;
  206473. matrix._21 = transform.mat01;
  206474. matrix._22 = transform.mat11;
  206475. matrix._31 = transform.mat02;
  206476. matrix._32 = transform.mat12;
  206477. return matrix;
  206478. }
  206479. };
  206480. #endif
  206481. /*** End of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  206482. /*** Start of inlined file: juce_win32_Windowing.cpp ***/
  206483. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206484. // compiled on its own).
  206485. #if JUCE_INCLUDED_FILE
  206486. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  206487. // these are in the windows SDK, but need to be repeated here for GCC..
  206488. #ifndef GET_APPCOMMAND_LPARAM
  206489. #define FAPPCOMMAND_MASK 0xF000
  206490. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  206491. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  206492. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  206493. #define APPCOMMAND_MEDIA_STOP 13
  206494. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  206495. #define WM_APPCOMMAND 0x0319
  206496. #endif
  206497. extern void juce_repeatLastProcessPriority(); // in juce_win32_Threads.cpp
  206498. extern void juce_CheckCurrentlyFocusedTopLevelWindow(); // in juce_TopLevelWindow.cpp
  206499. extern bool juce_IsRunningInWine();
  206500. #ifndef ULW_ALPHA
  206501. #define ULW_ALPHA 0x00000002
  206502. #endif
  206503. #ifndef AC_SRC_ALPHA
  206504. #define AC_SRC_ALPHA 0x01
  206505. #endif
  206506. static HPALETTE palette = 0;
  206507. static bool createPaletteIfNeeded = true;
  206508. static bool shouldDeactivateTitleBar = true;
  206509. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY);
  206510. #define WM_TRAYNOTIFY WM_USER + 100
  206511. using ::abs;
  206512. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  206513. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  206514. bool Desktop::canUseSemiTransparentWindows() throw()
  206515. {
  206516. if (updateLayeredWindow == 0)
  206517. {
  206518. if (! juce_IsRunningInWine())
  206519. {
  206520. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  206521. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  206522. }
  206523. }
  206524. return updateLayeredWindow != 0;
  206525. }
  206526. const int extendedKeyModifier = 0x10000;
  206527. const int KeyPress::spaceKey = VK_SPACE;
  206528. const int KeyPress::returnKey = VK_RETURN;
  206529. const int KeyPress::escapeKey = VK_ESCAPE;
  206530. const int KeyPress::backspaceKey = VK_BACK;
  206531. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  206532. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  206533. const int KeyPress::tabKey = VK_TAB;
  206534. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  206535. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  206536. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  206537. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  206538. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  206539. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  206540. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  206541. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  206542. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  206543. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  206544. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  206545. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  206546. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  206547. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  206548. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  206549. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  206550. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  206551. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  206552. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  206553. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  206554. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  206555. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  206556. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  206557. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  206558. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  206559. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  206560. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  206561. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  206562. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  206563. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  206564. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  206565. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  206566. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  206567. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  206568. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  206569. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  206570. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  206571. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  206572. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  206573. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  206574. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  206575. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  206576. const int KeyPress::playKey = 0x30000;
  206577. const int KeyPress::stopKey = 0x30001;
  206578. const int KeyPress::fastForwardKey = 0x30002;
  206579. const int KeyPress::rewindKey = 0x30003;
  206580. class WindowsBitmapImage : public Image::SharedImage
  206581. {
  206582. public:
  206583. HBITMAP hBitmap;
  206584. BITMAPV4HEADER bitmapInfo;
  206585. HDC hdc;
  206586. unsigned char* bitmapData;
  206587. WindowsBitmapImage (const Image::PixelFormat format_,
  206588. const int w, const int h, const bool clearImage)
  206589. : Image::SharedImage (format_, w, h)
  206590. {
  206591. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  206592. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  206593. zerostruct (bitmapInfo);
  206594. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  206595. bitmapInfo.bV4Width = w;
  206596. bitmapInfo.bV4Height = h;
  206597. bitmapInfo.bV4Planes = 1;
  206598. bitmapInfo.bV4CSType = 1;
  206599. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  206600. if (format_ == Image::ARGB)
  206601. {
  206602. bitmapInfo.bV4AlphaMask = 0xff000000;
  206603. bitmapInfo.bV4RedMask = 0xff0000;
  206604. bitmapInfo.bV4GreenMask = 0xff00;
  206605. bitmapInfo.bV4BlueMask = 0xff;
  206606. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  206607. }
  206608. else
  206609. {
  206610. bitmapInfo.bV4V4Compression = BI_RGB;
  206611. }
  206612. lineStride = -((w * pixelStride + 3) & ~3);
  206613. HDC dc = GetDC (0);
  206614. hdc = CreateCompatibleDC (dc);
  206615. ReleaseDC (0, dc);
  206616. SetMapMode (hdc, MM_TEXT);
  206617. hBitmap = CreateDIBSection (hdc,
  206618. (BITMAPINFO*) &(bitmapInfo),
  206619. DIB_RGB_COLORS,
  206620. (void**) &bitmapData,
  206621. 0, 0);
  206622. SelectObject (hdc, hBitmap);
  206623. if (format_ == Image::ARGB && clearImage)
  206624. zeromem (bitmapData, abs (h * lineStride));
  206625. imageData = bitmapData - (lineStride * (h - 1));
  206626. }
  206627. ~WindowsBitmapImage()
  206628. {
  206629. DeleteDC (hdc);
  206630. DeleteObject (hBitmap);
  206631. }
  206632. Image::ImageType getType() const { return Image::NativeImage; }
  206633. LowLevelGraphicsContext* createLowLevelContext()
  206634. {
  206635. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  206636. }
  206637. SharedImage* clone()
  206638. {
  206639. WindowsBitmapImage* im = new WindowsBitmapImage (format, width, height, false);
  206640. for (int i = 0; i < height; ++i)
  206641. memcpy (im->imageData + i * lineStride, imageData + i * lineStride, lineStride);
  206642. return im;
  206643. }
  206644. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  206645. const int x, const int y,
  206646. const RectangleList& maskedRegion) throw()
  206647. {
  206648. static HDRAWDIB hdd = 0;
  206649. static bool needToCreateDrawDib = true;
  206650. if (needToCreateDrawDib)
  206651. {
  206652. needToCreateDrawDib = false;
  206653. HDC dc = GetDC (0);
  206654. const int n = GetDeviceCaps (dc, BITSPIXEL);
  206655. ReleaseDC (0, dc);
  206656. // only open if we're not palettised
  206657. if (n > 8)
  206658. hdd = DrawDibOpen();
  206659. }
  206660. if (createPaletteIfNeeded)
  206661. {
  206662. HDC dc = GetDC (0);
  206663. const int n = GetDeviceCaps (dc, BITSPIXEL);
  206664. ReleaseDC (0, dc);
  206665. if (n <= 8)
  206666. palette = CreateHalftonePalette (dc);
  206667. createPaletteIfNeeded = false;
  206668. }
  206669. if (palette != 0)
  206670. {
  206671. SelectPalette (dc, palette, FALSE);
  206672. RealizePalette (dc);
  206673. SetStretchBltMode (dc, HALFTONE);
  206674. }
  206675. SetMapMode (dc, MM_TEXT);
  206676. if (transparent)
  206677. {
  206678. POINT p, pos;
  206679. SIZE size;
  206680. RECT windowBounds;
  206681. GetWindowRect (hwnd, &windowBounds);
  206682. p.x = -x;
  206683. p.y = -y;
  206684. pos.x = windowBounds.left;
  206685. pos.y = windowBounds.top;
  206686. size.cx = windowBounds.right - windowBounds.left;
  206687. size.cy = windowBounds.bottom - windowBounds.top;
  206688. BLENDFUNCTION bf;
  206689. bf.AlphaFormat = AC_SRC_ALPHA;
  206690. bf.BlendFlags = 0;
  206691. bf.BlendOp = AC_SRC_OVER;
  206692. bf.SourceConstantAlpha = 0xff;
  206693. if (! maskedRegion.isEmpty())
  206694. {
  206695. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206696. {
  206697. const Rectangle<int>& r = *i.getRectangle();
  206698. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206699. }
  206700. }
  206701. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  206702. }
  206703. else
  206704. {
  206705. int savedDC = 0;
  206706. if (! maskedRegion.isEmpty())
  206707. {
  206708. savedDC = SaveDC (dc);
  206709. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206710. {
  206711. const Rectangle<int>& r = *i.getRectangle();
  206712. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206713. }
  206714. }
  206715. if (hdd == 0)
  206716. {
  206717. StretchDIBits (dc,
  206718. x, y, width, height,
  206719. 0, 0, width, height,
  206720. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  206721. DIB_RGB_COLORS, SRCCOPY);
  206722. }
  206723. else
  206724. {
  206725. DrawDibDraw (hdd, dc, x, y, -1, -1,
  206726. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  206727. 0, 0, width, height, 0);
  206728. }
  206729. if (! maskedRegion.isEmpty())
  206730. RestoreDC (dc, savedDC);
  206731. }
  206732. }
  206733. juce_UseDebuggingNewOperator
  206734. private:
  206735. WindowsBitmapImage (const WindowsBitmapImage&);
  206736. WindowsBitmapImage& operator= (const WindowsBitmapImage&);
  206737. };
  206738. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  206739. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  206740. {
  206741. SHORT k = (SHORT) keyCode;
  206742. if ((keyCode & extendedKeyModifier) == 0
  206743. && (k >= (SHORT) 'a' && k <= (SHORT) 'z'))
  206744. k += (SHORT) 'A' - (SHORT) 'a';
  206745. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  206746. (SHORT) '+', VK_OEM_PLUS,
  206747. (SHORT) '-', VK_OEM_MINUS,
  206748. (SHORT) '.', VK_OEM_PERIOD,
  206749. (SHORT) ';', VK_OEM_1,
  206750. (SHORT) ':', VK_OEM_1,
  206751. (SHORT) '/', VK_OEM_2,
  206752. (SHORT) '?', VK_OEM_2,
  206753. (SHORT) '[', VK_OEM_4,
  206754. (SHORT) ']', VK_OEM_6 };
  206755. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  206756. if (k == translatedValues [i])
  206757. k = translatedValues [i + 1];
  206758. return (GetKeyState (k) & 0x8000) != 0;
  206759. }
  206760. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  206761. {
  206762. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  206763. return callback (userData);
  206764. else
  206765. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  206766. }
  206767. class Win32ComponentPeer : public ComponentPeer
  206768. {
  206769. public:
  206770. enum RenderingEngineType
  206771. {
  206772. softwareRenderingEngine = 0,
  206773. direct2DRenderingEngine
  206774. };
  206775. Win32ComponentPeer (Component* const component,
  206776. const int windowStyleFlags,
  206777. HWND parentToAddTo_)
  206778. : ComponentPeer (component, windowStyleFlags),
  206779. dontRepaint (false),
  206780. #if JUCE_DIRECT2D
  206781. currentRenderingEngine (direct2DRenderingEngine),
  206782. #else
  206783. currentRenderingEngine (softwareRenderingEngine),
  206784. #endif
  206785. fullScreen (false),
  206786. isDragging (false),
  206787. isMouseOver (false),
  206788. hasCreatedCaret (false),
  206789. currentWindowIcon (0),
  206790. dropTarget (0),
  206791. parentToAddTo (parentToAddTo_)
  206792. {
  206793. callFunctionIfNotLocked (&createWindowCallback, this);
  206794. setTitle (component->getName());
  206795. if ((windowStyleFlags & windowHasDropShadow) != 0
  206796. && Desktop::canUseSemiTransparentWindows())
  206797. {
  206798. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  206799. if (shadower != 0)
  206800. shadower->setOwner (component);
  206801. }
  206802. }
  206803. ~Win32ComponentPeer()
  206804. {
  206805. setTaskBarIcon (Image());
  206806. shadower = 0;
  206807. // do this before the next bit to avoid messages arriving for this window
  206808. // before it's destroyed
  206809. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  206810. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  206811. if (currentWindowIcon != 0)
  206812. DestroyIcon (currentWindowIcon);
  206813. if (dropTarget != 0)
  206814. {
  206815. dropTarget->Release();
  206816. dropTarget = 0;
  206817. }
  206818. #if JUCE_DIRECT2D
  206819. direct2DContext = 0;
  206820. #endif
  206821. }
  206822. void* getNativeHandle() const
  206823. {
  206824. return hwnd;
  206825. }
  206826. void setVisible (bool shouldBeVisible)
  206827. {
  206828. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  206829. if (shouldBeVisible)
  206830. InvalidateRect (hwnd, 0, 0);
  206831. else
  206832. lastPaintTime = 0;
  206833. }
  206834. void setTitle (const String& title)
  206835. {
  206836. SetWindowText (hwnd, title);
  206837. }
  206838. void setPosition (int x, int y)
  206839. {
  206840. offsetWithinParent (x, y);
  206841. SetWindowPos (hwnd, 0,
  206842. x - windowBorder.getLeft(),
  206843. y - windowBorder.getTop(),
  206844. 0, 0,
  206845. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206846. }
  206847. void repaintNowIfTransparent()
  206848. {
  206849. if (isTransparent() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  206850. handlePaintMessage();
  206851. }
  206852. void updateBorderSize()
  206853. {
  206854. WINDOWINFO info;
  206855. info.cbSize = sizeof (info);
  206856. if (GetWindowInfo (hwnd, &info))
  206857. {
  206858. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  206859. info.rcClient.left - info.rcWindow.left,
  206860. info.rcWindow.bottom - info.rcClient.bottom,
  206861. info.rcWindow.right - info.rcClient.right);
  206862. }
  206863. #if JUCE_DIRECT2D
  206864. if (direct2DContext != 0)
  206865. direct2DContext->resized();
  206866. #endif
  206867. }
  206868. void setSize (int w, int h)
  206869. {
  206870. SetWindowPos (hwnd, 0, 0, 0,
  206871. w + windowBorder.getLeftAndRight(),
  206872. h + windowBorder.getTopAndBottom(),
  206873. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206874. updateBorderSize();
  206875. repaintNowIfTransparent();
  206876. }
  206877. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  206878. {
  206879. fullScreen = isNowFullScreen;
  206880. offsetWithinParent (x, y);
  206881. SetWindowPos (hwnd, 0,
  206882. x - windowBorder.getLeft(),
  206883. y - windowBorder.getTop(),
  206884. w + windowBorder.getLeftAndRight(),
  206885. h + windowBorder.getTopAndBottom(),
  206886. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206887. updateBorderSize();
  206888. repaintNowIfTransparent();
  206889. }
  206890. const Rectangle<int> getBounds() const
  206891. {
  206892. RECT r;
  206893. GetWindowRect (hwnd, &r);
  206894. Rectangle<int> bounds (r.left, r.top, r.right - r.left, r.bottom - r.top);
  206895. HWND parentH = GetParent (hwnd);
  206896. if (parentH != 0)
  206897. {
  206898. GetWindowRect (parentH, &r);
  206899. bounds.translate (-r.left, -r.top);
  206900. }
  206901. return windowBorder.subtractedFrom (bounds);
  206902. }
  206903. const Point<int> getScreenPosition() const
  206904. {
  206905. RECT r;
  206906. GetWindowRect (hwnd, &r);
  206907. return Point<int> (r.left + windowBorder.getLeft(),
  206908. r.top + windowBorder.getTop());
  206909. }
  206910. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  206911. {
  206912. return relativePosition + getScreenPosition();
  206913. }
  206914. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  206915. {
  206916. return screenPosition - getScreenPosition();
  206917. }
  206918. void setMinimised (bool shouldBeMinimised)
  206919. {
  206920. if (shouldBeMinimised != isMinimised())
  206921. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  206922. }
  206923. bool isMinimised() const
  206924. {
  206925. WINDOWPLACEMENT wp;
  206926. wp.length = sizeof (WINDOWPLACEMENT);
  206927. GetWindowPlacement (hwnd, &wp);
  206928. return wp.showCmd == SW_SHOWMINIMIZED;
  206929. }
  206930. void setFullScreen (bool shouldBeFullScreen)
  206931. {
  206932. setMinimised (false);
  206933. if (fullScreen != shouldBeFullScreen)
  206934. {
  206935. fullScreen = shouldBeFullScreen;
  206936. const Component::SafePointer<Component> deletionChecker (component);
  206937. if (! fullScreen)
  206938. {
  206939. const Rectangle<int> boundsCopy (lastNonFullscreenBounds);
  206940. if (hasTitleBar())
  206941. ShowWindow (hwnd, SW_SHOWNORMAL);
  206942. if (! boundsCopy.isEmpty())
  206943. {
  206944. setBounds (boundsCopy.getX(),
  206945. boundsCopy.getY(),
  206946. boundsCopy.getWidth(),
  206947. boundsCopy.getHeight(),
  206948. false);
  206949. }
  206950. }
  206951. else
  206952. {
  206953. if (hasTitleBar())
  206954. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  206955. else
  206956. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  206957. }
  206958. if (deletionChecker != 0)
  206959. handleMovedOrResized();
  206960. }
  206961. }
  206962. bool isFullScreen() const
  206963. {
  206964. if (! hasTitleBar())
  206965. return fullScreen;
  206966. WINDOWPLACEMENT wp;
  206967. wp.length = sizeof (wp);
  206968. GetWindowPlacement (hwnd, &wp);
  206969. return wp.showCmd == SW_SHOWMAXIMIZED;
  206970. }
  206971. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  206972. {
  206973. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  206974. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  206975. return false;
  206976. RECT r;
  206977. GetWindowRect (hwnd, &r);
  206978. POINT p;
  206979. p.x = position.getX() + r.left + windowBorder.getLeft();
  206980. p.y = position.getY() + r.top + windowBorder.getTop();
  206981. HWND w = WindowFromPoint (p);
  206982. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  206983. }
  206984. const BorderSize getFrameSize() const
  206985. {
  206986. return windowBorder;
  206987. }
  206988. bool setAlwaysOnTop (bool alwaysOnTop)
  206989. {
  206990. const bool oldDeactivate = shouldDeactivateTitleBar;
  206991. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  206992. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  206993. 0, 0, 0, 0,
  206994. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  206995. shouldDeactivateTitleBar = oldDeactivate;
  206996. if (shadower != 0)
  206997. shadower->componentBroughtToFront (*component);
  206998. return true;
  206999. }
  207000. void toFront (bool makeActive)
  207001. {
  207002. setMinimised (false);
  207003. const bool oldDeactivate = shouldDeactivateTitleBar;
  207004. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207005. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  207006. shouldDeactivateTitleBar = oldDeactivate;
  207007. if (! makeActive)
  207008. {
  207009. // in this case a broughttofront call won't have occured, so do it now..
  207010. handleBroughtToFront();
  207011. }
  207012. }
  207013. void toBehind (ComponentPeer* other)
  207014. {
  207015. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  207016. jassert (otherPeer != 0); // wrong type of window?
  207017. if (otherPeer != 0)
  207018. {
  207019. setMinimised (false);
  207020. // must be careful not to try to put a topmost window behind a normal one, or win32
  207021. // promotes the normal one to be topmost!
  207022. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  207023. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  207024. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207025. else if (otherPeer->getComponent()->isAlwaysOnTop())
  207026. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  207027. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207028. }
  207029. }
  207030. bool isFocused() const
  207031. {
  207032. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  207033. }
  207034. void grabFocus()
  207035. {
  207036. const bool oldDeactivate = shouldDeactivateTitleBar;
  207037. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207038. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  207039. shouldDeactivateTitleBar = oldDeactivate;
  207040. }
  207041. void textInputRequired (const Point<int>&)
  207042. {
  207043. if (! hasCreatedCaret)
  207044. {
  207045. hasCreatedCaret = true;
  207046. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  207047. }
  207048. ShowCaret (hwnd);
  207049. SetCaretPos (0, 0);
  207050. }
  207051. void repaint (const Rectangle<int>& area)
  207052. {
  207053. const RECT r = { area.getX(), area.getY(), area.getRight(), area.getBottom() };
  207054. InvalidateRect (hwnd, &r, FALSE);
  207055. }
  207056. void performAnyPendingRepaintsNow()
  207057. {
  207058. MSG m;
  207059. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  207060. DispatchMessage (&m);
  207061. }
  207062. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  207063. {
  207064. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  207065. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  207066. return 0;
  207067. }
  207068. void setTaskBarIcon (const Image& image)
  207069. {
  207070. if (image.isValid())
  207071. {
  207072. HICON hicon = createHICONFromImage (image, TRUE, 0, 0);
  207073. if (taskBarIcon == 0)
  207074. {
  207075. taskBarIcon = new NOTIFYICONDATA();
  207076. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  207077. taskBarIcon->hWnd = (HWND) hwnd;
  207078. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  207079. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  207080. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  207081. taskBarIcon->hIcon = hicon;
  207082. taskBarIcon->szTip[0] = 0;
  207083. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  207084. }
  207085. else
  207086. {
  207087. HICON oldIcon = taskBarIcon->hIcon;
  207088. taskBarIcon->hIcon = hicon;
  207089. taskBarIcon->uFlags = NIF_ICON;
  207090. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  207091. DestroyIcon (oldIcon);
  207092. }
  207093. DestroyIcon (hicon);
  207094. }
  207095. else if (taskBarIcon != 0)
  207096. {
  207097. taskBarIcon->uFlags = 0;
  207098. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  207099. DestroyIcon (taskBarIcon->hIcon);
  207100. taskBarIcon = 0;
  207101. }
  207102. }
  207103. void setTaskBarIconToolTip (const String& toolTip) const
  207104. {
  207105. if (taskBarIcon != 0)
  207106. {
  207107. taskBarIcon->uFlags = NIF_TIP;
  207108. toolTip.copyToUnicode (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  207109. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  207110. }
  207111. }
  207112. bool isInside (HWND h) const
  207113. {
  207114. return GetAncestor (hwnd, GA_ROOT) == h;
  207115. }
  207116. static void updateKeyModifiers() throw()
  207117. {
  207118. int keyMods = 0;
  207119. if (GetKeyState (VK_SHIFT) & 0x8000) keyMods |= ModifierKeys::shiftModifier;
  207120. if (GetKeyState (VK_CONTROL) & 0x8000) keyMods |= ModifierKeys::ctrlModifier;
  207121. if (GetKeyState (VK_MENU) & 0x8000) keyMods |= ModifierKeys::altModifier;
  207122. if (GetKeyState (VK_RMENU) & 0x8000) keyMods &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  207123. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  207124. }
  207125. static void updateModifiersFromWParam (const WPARAM wParam)
  207126. {
  207127. int mouseMods = 0;
  207128. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  207129. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  207130. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  207131. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  207132. updateKeyModifiers();
  207133. }
  207134. static int64 getMouseEventTime()
  207135. {
  207136. static int64 eventTimeOffset = 0;
  207137. static DWORD lastMessageTime = 0;
  207138. const DWORD thisMessageTime = GetMessageTime();
  207139. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  207140. {
  207141. lastMessageTime = thisMessageTime;
  207142. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  207143. }
  207144. return eventTimeOffset + thisMessageTime;
  207145. }
  207146. juce_UseDebuggingNewOperator
  207147. bool dontRepaint;
  207148. static ModifierKeys currentModifiers;
  207149. static ModifierKeys modifiersAtLastCallback;
  207150. private:
  207151. HWND hwnd, parentToAddTo;
  207152. ScopedPointer<DropShadower> shadower;
  207153. RenderingEngineType currentRenderingEngine;
  207154. #if JUCE_DIRECT2D
  207155. ScopedPointer<Direct2DLowLevelGraphicsContext> direct2DContext;
  207156. #endif
  207157. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret;
  207158. BorderSize windowBorder;
  207159. HICON currentWindowIcon;
  207160. ScopedPointer<NOTIFYICONDATA> taskBarIcon;
  207161. IDropTarget* dropTarget;
  207162. class TemporaryImage : public Timer
  207163. {
  207164. public:
  207165. TemporaryImage() {}
  207166. ~TemporaryImage() {}
  207167. const Image& getImage (const bool transparent, const int w, const int h)
  207168. {
  207169. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  207170. if ((! image.isValid()) || image.getWidth() < w || image.getHeight() < h || image.getFormat() != format)
  207171. image = Image (new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false));
  207172. startTimer (3000);
  207173. return image;
  207174. }
  207175. void timerCallback()
  207176. {
  207177. stopTimer();
  207178. image = Image::null;
  207179. }
  207180. private:
  207181. Image image;
  207182. TemporaryImage (const TemporaryImage&);
  207183. TemporaryImage& operator= (const TemporaryImage&);
  207184. };
  207185. TemporaryImage offscreenImageGenerator;
  207186. class WindowClassHolder : public DeletedAtShutdown
  207187. {
  207188. public:
  207189. WindowClassHolder()
  207190. : windowClassName ("JUCE_")
  207191. {
  207192. // this name has to be different for each app/dll instance because otherwise
  207193. // poor old Win32 can get a bit confused (even despite it not being a process-global
  207194. // window class).
  207195. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  207196. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  207197. TCHAR moduleFile [1024];
  207198. moduleFile[0] = 0;
  207199. GetModuleFileName (moduleHandle, moduleFile, 1024);
  207200. WORD iconNum = 0;
  207201. WNDCLASSEX wcex;
  207202. wcex.cbSize = sizeof (wcex);
  207203. wcex.style = CS_OWNDC;
  207204. wcex.lpfnWndProc = (WNDPROC) windowProc;
  207205. wcex.lpszClassName = windowClassName;
  207206. wcex.cbClsExtra = 0;
  207207. wcex.cbWndExtra = 32;
  207208. wcex.hInstance = moduleHandle;
  207209. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207210. iconNum = 1;
  207211. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207212. wcex.hCursor = 0;
  207213. wcex.hbrBackground = 0;
  207214. wcex.lpszMenuName = 0;
  207215. RegisterClassEx (&wcex);
  207216. }
  207217. ~WindowClassHolder()
  207218. {
  207219. if (ComponentPeer::getNumPeers() == 0)
  207220. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  207221. clearSingletonInstance();
  207222. }
  207223. String windowClassName;
  207224. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  207225. };
  207226. static void* createWindowCallback (void* userData)
  207227. {
  207228. static_cast <Win32ComponentPeer*> (userData)->createWindow();
  207229. return 0;
  207230. }
  207231. void createWindow()
  207232. {
  207233. DWORD exstyle = WS_EX_ACCEPTFILES;
  207234. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  207235. if (hasTitleBar())
  207236. {
  207237. type |= WS_OVERLAPPED;
  207238. if ((styleFlags & windowHasCloseButton) != 0)
  207239. {
  207240. type |= WS_SYSMENU;
  207241. }
  207242. else
  207243. {
  207244. // annoyingly, windows won't let you have a min/max button without a close button
  207245. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  207246. }
  207247. if ((styleFlags & windowIsResizable) != 0)
  207248. type |= WS_THICKFRAME;
  207249. }
  207250. else if (parentToAddTo != 0)
  207251. {
  207252. type |= WS_CHILD;
  207253. }
  207254. else
  207255. {
  207256. type |= WS_POPUP | WS_SYSMENU;
  207257. }
  207258. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  207259. exstyle |= WS_EX_TOOLWINDOW;
  207260. else
  207261. exstyle |= WS_EX_APPWINDOW;
  207262. if ((styleFlags & windowHasMinimiseButton) != 0)
  207263. type |= WS_MINIMIZEBOX;
  207264. if ((styleFlags & windowHasMaximiseButton) != 0)
  207265. type |= WS_MAXIMIZEBOX;
  207266. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  207267. exstyle |= WS_EX_TRANSPARENT;
  207268. if ((styleFlags & windowIsSemiTransparent) != 0
  207269. && Desktop::canUseSemiTransparentWindows())
  207270. exstyle |= WS_EX_LAYERED;
  207271. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0,
  207272. parentToAddTo, 0, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(), 0);
  207273. #if JUCE_DIRECT2D
  207274. updateDirect2DContext();
  207275. #endif
  207276. if (hwnd != 0)
  207277. {
  207278. SetWindowLongPtr (hwnd, 0, 0);
  207279. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  207280. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  207281. if (dropTarget == 0)
  207282. dropTarget = new JuceDropTarget (this);
  207283. RegisterDragDrop (hwnd, dropTarget);
  207284. updateBorderSize();
  207285. // Calling this function here is (for some reason) necessary to make Windows
  207286. // correctly enable the menu items that we specify in the wm_initmenu message.
  207287. GetSystemMenu (hwnd, false);
  207288. }
  207289. else
  207290. {
  207291. jassertfalse;
  207292. }
  207293. }
  207294. static void* destroyWindowCallback (void* handle)
  207295. {
  207296. RevokeDragDrop ((HWND) handle);
  207297. DestroyWindow ((HWND) handle);
  207298. return 0;
  207299. }
  207300. static void* toFrontCallback1 (void* h)
  207301. {
  207302. SetForegroundWindow ((HWND) h);
  207303. return 0;
  207304. }
  207305. static void* toFrontCallback2 (void* h)
  207306. {
  207307. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207308. return 0;
  207309. }
  207310. static void* setFocusCallback (void* h)
  207311. {
  207312. SetFocus ((HWND) h);
  207313. return 0;
  207314. }
  207315. static void* getFocusCallback (void*)
  207316. {
  207317. return GetFocus();
  207318. }
  207319. void offsetWithinParent (int& x, int& y) const
  207320. {
  207321. if (isTransparent())
  207322. {
  207323. HWND parentHwnd = GetParent (hwnd);
  207324. if (parentHwnd != 0)
  207325. {
  207326. RECT parentRect;
  207327. GetWindowRect (parentHwnd, &parentRect);
  207328. x += parentRect.left;
  207329. y += parentRect.top;
  207330. }
  207331. }
  207332. }
  207333. bool isTransparent() const
  207334. {
  207335. return (GetWindowLong (hwnd, GWL_EXSTYLE) & WS_EX_LAYERED) != 0;
  207336. }
  207337. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  207338. void setIcon (const Image& newIcon)
  207339. {
  207340. HICON hicon = createHICONFromImage (newIcon, TRUE, 0, 0);
  207341. if (hicon != 0)
  207342. {
  207343. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  207344. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  207345. if (currentWindowIcon != 0)
  207346. DestroyIcon (currentWindowIcon);
  207347. currentWindowIcon = hicon;
  207348. }
  207349. }
  207350. void handlePaintMessage()
  207351. {
  207352. #if JUCE_DIRECT2D
  207353. if (direct2DContext != 0)
  207354. {
  207355. RECT r;
  207356. if (GetUpdateRect (hwnd, &r, false))
  207357. {
  207358. direct2DContext->start();
  207359. direct2DContext->clipToRectangle (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  207360. handlePaint (*direct2DContext);
  207361. direct2DContext->end();
  207362. }
  207363. }
  207364. else
  207365. #endif
  207366. {
  207367. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  207368. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  207369. PAINTSTRUCT paintStruct;
  207370. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  207371. // message and become re-entrant, but that's OK
  207372. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  207373. // corrupt the image it's using to paint into, so do a check here.
  207374. static bool reentrant = false;
  207375. if (reentrant)
  207376. {
  207377. DeleteObject (rgn);
  207378. EndPaint (hwnd, &paintStruct);
  207379. return;
  207380. }
  207381. reentrant = true;
  207382. // this is the rectangle to update..
  207383. int x = paintStruct.rcPaint.left;
  207384. int y = paintStruct.rcPaint.top;
  207385. int w = paintStruct.rcPaint.right - x;
  207386. int h = paintStruct.rcPaint.bottom - y;
  207387. const bool transparent = isTransparent();
  207388. if (transparent)
  207389. {
  207390. // it's not possible to have a transparent window with a title bar at the moment!
  207391. jassert (! hasTitleBar());
  207392. RECT r;
  207393. GetWindowRect (hwnd, &r);
  207394. x = y = 0;
  207395. w = r.right - r.left;
  207396. h = r.bottom - r.top;
  207397. }
  207398. if (w > 0 && h > 0)
  207399. {
  207400. clearMaskedRegion();
  207401. Image offscreenImage (offscreenImageGenerator.getImage (transparent, w, h));
  207402. RectangleList contextClip;
  207403. const Rectangle<int> clipBounds (0, 0, w, h);
  207404. bool needToPaintAll = true;
  207405. if (regionType == COMPLEXREGION && ! transparent)
  207406. {
  207407. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  207408. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  207409. DeleteObject (clipRgn);
  207410. char rgnData [8192];
  207411. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  207412. if (res > 0 && res <= sizeof (rgnData))
  207413. {
  207414. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  207415. if (hdr->iType == RDH_RECTANGLES
  207416. && hdr->rcBound.right - hdr->rcBound.left >= w
  207417. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  207418. {
  207419. needToPaintAll = false;
  207420. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  207421. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  207422. while (--num >= 0)
  207423. {
  207424. if (rects->right <= x + w && rects->bottom <= y + h)
  207425. {
  207426. const int cx = jmax (x, (int) rects->left);
  207427. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y, rects->right - cx, rects->bottom - rects->top)
  207428. .getIntersection (clipBounds));
  207429. }
  207430. else
  207431. {
  207432. needToPaintAll = true;
  207433. break;
  207434. }
  207435. ++rects;
  207436. }
  207437. }
  207438. }
  207439. }
  207440. if (needToPaintAll)
  207441. {
  207442. contextClip.clear();
  207443. contextClip.addWithoutMerging (Rectangle<int> (w, h));
  207444. }
  207445. if (transparent)
  207446. {
  207447. RectangleList::Iterator i (contextClip);
  207448. while (i.next())
  207449. offscreenImage.clear (*i.getRectangle());
  207450. }
  207451. // if the component's not opaque, this won't draw properly unless the platform can support this
  207452. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  207453. updateCurrentModifiers();
  207454. LowLevelGraphicsSoftwareRenderer context (offscreenImage, -x, -y, contextClip);
  207455. handlePaint (context);
  207456. if (! dontRepaint)
  207457. static_cast <WindowsBitmapImage*> (offscreenImage.getSharedImage())
  207458. ->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion);
  207459. }
  207460. DeleteObject (rgn);
  207461. EndPaint (hwnd, &paintStruct);
  207462. reentrant = false;
  207463. }
  207464. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  207465. _fpreset(); // because some graphics cards can unmask FP exceptions
  207466. #endif
  207467. lastPaintTime = Time::getMillisecondCounter();
  207468. }
  207469. void doMouseEvent (const Point<int>& position)
  207470. {
  207471. handleMouseEvent (0, position, currentModifiers, getMouseEventTime());
  207472. }
  207473. const StringArray getAvailableRenderingEngines()
  207474. {
  207475. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  207476. #if JUCE_DIRECT2D
  207477. // xxx is this correct? Seems to enable it on Vista too??
  207478. OSVERSIONINFO info;
  207479. zerostruct (info);
  207480. info.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
  207481. GetVersionEx (&info);
  207482. if (info.dwMajorVersion >= 6)
  207483. s.add ("Direct2D");
  207484. #endif
  207485. return s;
  207486. }
  207487. int getCurrentRenderingEngine() throw()
  207488. {
  207489. return currentRenderingEngine;
  207490. }
  207491. #if JUCE_DIRECT2D
  207492. void updateDirect2DContext()
  207493. {
  207494. if (currentRenderingEngine != direct2DRenderingEngine)
  207495. direct2DContext = 0;
  207496. else if (direct2DContext == 0)
  207497. direct2DContext = new Direct2DLowLevelGraphicsContext (hwnd);
  207498. }
  207499. #endif
  207500. void setCurrentRenderingEngine (int index)
  207501. {
  207502. (void) index;
  207503. #if JUCE_DIRECT2D
  207504. currentRenderingEngine = index == 1 ? direct2DRenderingEngine : softwareRenderingEngine;
  207505. updateDirect2DContext();
  207506. repaint (component->getLocalBounds());
  207507. #endif
  207508. }
  207509. void doMouseMove (const Point<int>& position)
  207510. {
  207511. if (! isMouseOver)
  207512. {
  207513. isMouseOver = true;
  207514. updateKeyModifiers();
  207515. TRACKMOUSEEVENT tme;
  207516. tme.cbSize = sizeof (tme);
  207517. tme.dwFlags = TME_LEAVE;
  207518. tme.hwndTrack = hwnd;
  207519. tme.dwHoverTime = 0;
  207520. if (! TrackMouseEvent (&tme))
  207521. jassertfalse;
  207522. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  207523. }
  207524. else if (! isDragging)
  207525. {
  207526. if (! contains (position, false))
  207527. return;
  207528. }
  207529. // (Throttling the incoming queue of mouse-events seems to still be required in XP..)
  207530. static uint32 lastMouseTime = 0;
  207531. const uint32 now = Time::getMillisecondCounter();
  207532. const int maxMouseMovesPerSecond = 60;
  207533. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  207534. {
  207535. lastMouseTime = now;
  207536. doMouseEvent (position);
  207537. }
  207538. }
  207539. void doMouseDown (const Point<int>& position, const WPARAM wParam)
  207540. {
  207541. if (GetCapture() != hwnd)
  207542. SetCapture (hwnd);
  207543. doMouseMove (position);
  207544. updateModifiersFromWParam (wParam);
  207545. isDragging = true;
  207546. doMouseEvent (position);
  207547. }
  207548. void doMouseUp (const Point<int>& position, const WPARAM wParam)
  207549. {
  207550. updateModifiersFromWParam (wParam);
  207551. isDragging = false;
  207552. // release the mouse capture if the user has released all buttons
  207553. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  207554. ReleaseCapture();
  207555. doMouseEvent (position);
  207556. }
  207557. void doCaptureChanged()
  207558. {
  207559. if (isDragging)
  207560. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  207561. }
  207562. void doMouseExit()
  207563. {
  207564. isMouseOver = false;
  207565. doMouseEvent (getCurrentMousePos());
  207566. }
  207567. void doMouseWheel (const Point<int>& position, const WPARAM wParam, const bool isVertical)
  207568. {
  207569. updateKeyModifiers();
  207570. const float amount = jlimit (-1000.0f, 1000.0f, 0.75f * (short) HIWORD (wParam));
  207571. handleMouseWheel (0, position, getMouseEventTime(),
  207572. isVertical ? 0.0f : amount,
  207573. isVertical ? amount : 0.0f);
  207574. }
  207575. void sendModifierKeyChangeIfNeeded()
  207576. {
  207577. if (modifiersAtLastCallback != currentModifiers)
  207578. {
  207579. modifiersAtLastCallback = currentModifiers;
  207580. handleModifierKeysChange();
  207581. }
  207582. }
  207583. bool doKeyUp (const WPARAM key)
  207584. {
  207585. updateKeyModifiers();
  207586. switch (key)
  207587. {
  207588. case VK_SHIFT:
  207589. case VK_CONTROL:
  207590. case VK_MENU:
  207591. case VK_CAPITAL:
  207592. case VK_LWIN:
  207593. case VK_RWIN:
  207594. case VK_APPS:
  207595. case VK_NUMLOCK:
  207596. case VK_SCROLL:
  207597. case VK_LSHIFT:
  207598. case VK_RSHIFT:
  207599. case VK_LCONTROL:
  207600. case VK_LMENU:
  207601. case VK_RCONTROL:
  207602. case VK_RMENU:
  207603. sendModifierKeyChangeIfNeeded();
  207604. }
  207605. return handleKeyUpOrDown (false)
  207606. || Component::getCurrentlyModalComponent() != 0;
  207607. }
  207608. bool doKeyDown (const WPARAM key)
  207609. {
  207610. updateKeyModifiers();
  207611. bool used = false;
  207612. switch (key)
  207613. {
  207614. case VK_SHIFT:
  207615. case VK_LSHIFT:
  207616. case VK_RSHIFT:
  207617. case VK_CONTROL:
  207618. case VK_LCONTROL:
  207619. case VK_RCONTROL:
  207620. case VK_MENU:
  207621. case VK_LMENU:
  207622. case VK_RMENU:
  207623. case VK_LWIN:
  207624. case VK_RWIN:
  207625. case VK_CAPITAL:
  207626. case VK_NUMLOCK:
  207627. case VK_SCROLL:
  207628. case VK_APPS:
  207629. sendModifierKeyChangeIfNeeded();
  207630. break;
  207631. case VK_LEFT:
  207632. case VK_RIGHT:
  207633. case VK_UP:
  207634. case VK_DOWN:
  207635. case VK_PRIOR:
  207636. case VK_NEXT:
  207637. case VK_HOME:
  207638. case VK_END:
  207639. case VK_DELETE:
  207640. case VK_INSERT:
  207641. case VK_F1:
  207642. case VK_F2:
  207643. case VK_F3:
  207644. case VK_F4:
  207645. case VK_F5:
  207646. case VK_F6:
  207647. case VK_F7:
  207648. case VK_F8:
  207649. case VK_F9:
  207650. case VK_F10:
  207651. case VK_F11:
  207652. case VK_F12:
  207653. case VK_F13:
  207654. case VK_F14:
  207655. case VK_F15:
  207656. case VK_F16:
  207657. used = handleKeyUpOrDown (true);
  207658. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  207659. break;
  207660. case VK_ADD:
  207661. case VK_SUBTRACT:
  207662. case VK_MULTIPLY:
  207663. case VK_DIVIDE:
  207664. case VK_SEPARATOR:
  207665. case VK_DECIMAL:
  207666. used = handleKeyUpOrDown (true);
  207667. break;
  207668. default:
  207669. used = handleKeyUpOrDown (true);
  207670. {
  207671. MSG msg;
  207672. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  207673. {
  207674. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  207675. // manually generate the key-press event that matches this key-down.
  207676. const UINT keyChar = MapVirtualKey (key, 2);
  207677. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  207678. }
  207679. }
  207680. break;
  207681. }
  207682. if (Component::getCurrentlyModalComponent() != 0)
  207683. used = true;
  207684. return used;
  207685. }
  207686. bool doKeyChar (int key, const LPARAM flags)
  207687. {
  207688. updateKeyModifiers();
  207689. juce_wchar textChar = (juce_wchar) key;
  207690. const int virtualScanCode = (flags >> 16) & 0xff;
  207691. if (key >= '0' && key <= '9')
  207692. {
  207693. switch (virtualScanCode) // check for a numeric keypad scan-code
  207694. {
  207695. case 0x52:
  207696. case 0x4f:
  207697. case 0x50:
  207698. case 0x51:
  207699. case 0x4b:
  207700. case 0x4c:
  207701. case 0x4d:
  207702. case 0x47:
  207703. case 0x48:
  207704. case 0x49:
  207705. key = (key - '0') + KeyPress::numberPad0;
  207706. break;
  207707. default:
  207708. break;
  207709. }
  207710. }
  207711. else
  207712. {
  207713. // convert the scan code to an unmodified character code..
  207714. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  207715. UINT keyChar = MapVirtualKey (virtualKey, 2);
  207716. keyChar = LOWORD (keyChar);
  207717. if (keyChar != 0)
  207718. key = (int) keyChar;
  207719. // avoid sending junk text characters for some control-key combinations
  207720. if (textChar < ' ' && currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  207721. textChar = 0;
  207722. }
  207723. return handleKeyPress (key, textChar);
  207724. }
  207725. bool doAppCommand (const LPARAM lParam)
  207726. {
  207727. int key = 0;
  207728. switch (GET_APPCOMMAND_LPARAM (lParam))
  207729. {
  207730. case APPCOMMAND_MEDIA_PLAY_PAUSE:
  207731. key = KeyPress::playKey;
  207732. break;
  207733. case APPCOMMAND_MEDIA_STOP:
  207734. key = KeyPress::stopKey;
  207735. break;
  207736. case APPCOMMAND_MEDIA_NEXTTRACK:
  207737. key = KeyPress::fastForwardKey;
  207738. break;
  207739. case APPCOMMAND_MEDIA_PREVIOUSTRACK:
  207740. key = KeyPress::rewindKey;
  207741. break;
  207742. }
  207743. if (key != 0)
  207744. {
  207745. updateKeyModifiers();
  207746. if (hwnd == GetActiveWindow())
  207747. {
  207748. handleKeyPress (key, 0);
  207749. return true;
  207750. }
  207751. }
  207752. return false;
  207753. }
  207754. class JuceDropTarget : public ComBaseClassHelper <IDropTarget>
  207755. {
  207756. public:
  207757. JuceDropTarget (Win32ComponentPeer* const owner_)
  207758. : owner (owner_)
  207759. {
  207760. }
  207761. ~JuceDropTarget() {}
  207762. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207763. {
  207764. updateFileList (pDataObject);
  207765. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  207766. *pdwEffect = DROPEFFECT_COPY;
  207767. return S_OK;
  207768. }
  207769. HRESULT __stdcall DragLeave()
  207770. {
  207771. owner->handleFileDragExit (files);
  207772. return S_OK;
  207773. }
  207774. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207775. {
  207776. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  207777. *pdwEffect = DROPEFFECT_COPY;
  207778. return S_OK;
  207779. }
  207780. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207781. {
  207782. updateFileList (pDataObject);
  207783. owner->handleFileDragDrop (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  207784. *pdwEffect = DROPEFFECT_COPY;
  207785. return S_OK;
  207786. }
  207787. private:
  207788. Win32ComponentPeer* const owner;
  207789. StringArray files;
  207790. void updateFileList (IDataObject* const pDataObject)
  207791. {
  207792. files.clear();
  207793. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  207794. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  207795. if (pDataObject->GetData (&format, &medium) == S_OK)
  207796. {
  207797. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  207798. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  207799. unsigned int i = 0;
  207800. if (pDropFiles->fWide)
  207801. {
  207802. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  207803. for (;;)
  207804. {
  207805. unsigned int len = 0;
  207806. while (i + len < totalLen && fname [i + len] != 0)
  207807. ++len;
  207808. if (len == 0)
  207809. break;
  207810. files.add (String (fname + i, len));
  207811. i += len + 1;
  207812. }
  207813. }
  207814. else
  207815. {
  207816. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  207817. for (;;)
  207818. {
  207819. unsigned int len = 0;
  207820. while (i + len < totalLen && fname [i + len] != 0)
  207821. ++len;
  207822. if (len == 0)
  207823. break;
  207824. files.add (String (fname + i, len));
  207825. i += len + 1;
  207826. }
  207827. }
  207828. GlobalUnlock (medium.hGlobal);
  207829. }
  207830. }
  207831. JuceDropTarget (const JuceDropTarget&);
  207832. JuceDropTarget& operator= (const JuceDropTarget&);
  207833. };
  207834. void doSettingChange()
  207835. {
  207836. Desktop::getInstance().refreshMonitorSizes();
  207837. if (fullScreen && ! isMinimised())
  207838. {
  207839. const Rectangle<int> r (component->getParentMonitorArea());
  207840. SetWindowPos (hwnd, 0,
  207841. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  207842. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  207843. }
  207844. }
  207845. public:
  207846. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  207847. {
  207848. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  207849. if (peer != 0)
  207850. return peer->peerWindowProc (h, message, wParam, lParam);
  207851. return DefWindowProcW (h, message, wParam, lParam);
  207852. }
  207853. private:
  207854. static const Point<int> getPointFromLParam (LPARAM lParam) throw()
  207855. {
  207856. return Point<int> (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  207857. }
  207858. const Point<int> getCurrentMousePos() throw()
  207859. {
  207860. RECT wr;
  207861. GetWindowRect (hwnd, &wr);
  207862. const DWORD mp = GetMessagePos();
  207863. return Point<int> (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  207864. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop());
  207865. }
  207866. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  207867. {
  207868. if (isValidPeer (this))
  207869. {
  207870. switch (message)
  207871. {
  207872. case WM_NCHITTEST:
  207873. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  207874. return HTTRANSPARENT;
  207875. if (hasTitleBar())
  207876. break;
  207877. return HTCLIENT;
  207878. case WM_PAINT:
  207879. handlePaintMessage();
  207880. return 0;
  207881. case WM_NCPAINT:
  207882. if (wParam != 1)
  207883. handlePaintMessage();
  207884. if (hasTitleBar())
  207885. break;
  207886. return 0;
  207887. case WM_ERASEBKGND:
  207888. case WM_NCCALCSIZE:
  207889. if (hasTitleBar())
  207890. break;
  207891. return 1;
  207892. case WM_MOUSEMOVE:
  207893. doMouseMove (getPointFromLParam (lParam));
  207894. return 0;
  207895. case WM_MOUSELEAVE:
  207896. doMouseExit();
  207897. return 0;
  207898. case WM_LBUTTONDOWN:
  207899. case WM_MBUTTONDOWN:
  207900. case WM_RBUTTONDOWN:
  207901. doMouseDown (getPointFromLParam (lParam), wParam);
  207902. return 0;
  207903. case WM_LBUTTONUP:
  207904. case WM_MBUTTONUP:
  207905. case WM_RBUTTONUP:
  207906. doMouseUp (getPointFromLParam (lParam), wParam);
  207907. return 0;
  207908. case WM_CAPTURECHANGED:
  207909. doCaptureChanged();
  207910. return 0;
  207911. case WM_NCMOUSEMOVE:
  207912. if (hasTitleBar())
  207913. break;
  207914. return 0;
  207915. case 0x020A: /* WM_MOUSEWHEEL */
  207916. doMouseWheel (getCurrentMousePos(), wParam, true);
  207917. return 0;
  207918. case 0x020E: /* WM_MOUSEHWHEEL */
  207919. doMouseWheel (getCurrentMousePos(), wParam, false);
  207920. return 0;
  207921. case WM_WINDOWPOSCHANGING:
  207922. if ((styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  207923. {
  207924. WINDOWPOS* const wp = (WINDOWPOS*) lParam;
  207925. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE))
  207926. {
  207927. if (constrainer != 0)
  207928. {
  207929. const Rectangle<int> current (component->getX() - windowBorder.getLeft(),
  207930. component->getY() - windowBorder.getTop(),
  207931. component->getWidth() + windowBorder.getLeftAndRight(),
  207932. component->getHeight() + windowBorder.getTopAndBottom());
  207933. Rectangle<int> pos (wp->x, wp->y, wp->cx, wp->cy);
  207934. constrainer->checkBounds (pos, current,
  207935. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  207936. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  207937. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  207938. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  207939. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  207940. wp->x = pos.getX();
  207941. wp->y = pos.getY();
  207942. wp->cx = pos.getWidth();
  207943. wp->cy = pos.getHeight();
  207944. }
  207945. }
  207946. }
  207947. return 0;
  207948. case WM_WINDOWPOSCHANGED:
  207949. doMouseEvent (getCurrentMousePos());
  207950. handleMovedOrResized();
  207951. if (dontRepaint)
  207952. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  207953. return 0;
  207954. case WM_KEYDOWN:
  207955. case WM_SYSKEYDOWN:
  207956. if (doKeyDown (wParam))
  207957. return 0;
  207958. break;
  207959. case WM_KEYUP:
  207960. case WM_SYSKEYUP:
  207961. if (doKeyUp (wParam))
  207962. return 0;
  207963. break;
  207964. case WM_CHAR:
  207965. if (doKeyChar ((int) wParam, lParam))
  207966. return 0;
  207967. break;
  207968. case WM_APPCOMMAND:
  207969. if (doAppCommand (lParam))
  207970. return TRUE;
  207971. break;
  207972. case WM_SETFOCUS:
  207973. updateKeyModifiers();
  207974. handleFocusGain();
  207975. break;
  207976. case WM_KILLFOCUS:
  207977. if (hasCreatedCaret)
  207978. {
  207979. hasCreatedCaret = false;
  207980. DestroyCaret();
  207981. }
  207982. handleFocusLoss();
  207983. break;
  207984. case WM_ACTIVATEAPP:
  207985. // Windows does weird things to process priority when you swap apps,
  207986. // so this forces an update when the app is brought to the front
  207987. if (wParam != FALSE)
  207988. juce_repeatLastProcessPriority();
  207989. else
  207990. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  207991. juce_CheckCurrentlyFocusedTopLevelWindow();
  207992. modifiersAtLastCallback = -1;
  207993. return 0;
  207994. case WM_ACTIVATE:
  207995. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  207996. {
  207997. modifiersAtLastCallback = -1;
  207998. updateKeyModifiers();
  207999. if (isMinimised())
  208000. {
  208001. component->repaint();
  208002. handleMovedOrResized();
  208003. if (! ComponentPeer::isValidPeer (this))
  208004. return 0;
  208005. }
  208006. if (LOWORD (wParam) == WA_CLICKACTIVE
  208007. && component->isCurrentlyBlockedByAnotherModalComponent())
  208008. {
  208009. const Point<int> mousePos (component->getMouseXYRelative());
  208010. Component* const underMouse = component->getComponentAt (mousePos.getX(), mousePos.getY());
  208011. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  208012. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  208013. return 0;
  208014. }
  208015. handleBroughtToFront();
  208016. if (component->isCurrentlyBlockedByAnotherModalComponent())
  208017. Component::getCurrentlyModalComponent()->toFront (true);
  208018. return 0;
  208019. }
  208020. break;
  208021. case WM_NCACTIVATE:
  208022. // while a temporary window is being shown, prevent Windows from deactivating the
  208023. // title bars of our main windows.
  208024. if (wParam == 0 && ! shouldDeactivateTitleBar)
  208025. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  208026. break;
  208027. case WM_MOUSEACTIVATE:
  208028. if (! component->getMouseClickGrabsKeyboardFocus())
  208029. return MA_NOACTIVATE;
  208030. break;
  208031. case WM_SHOWWINDOW:
  208032. if (wParam != 0)
  208033. handleBroughtToFront();
  208034. break;
  208035. case WM_CLOSE:
  208036. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  208037. handleUserClosingWindow();
  208038. return 0;
  208039. case WM_QUERYENDSESSION:
  208040. if (JUCEApplication::getInstance() != 0)
  208041. {
  208042. JUCEApplication::getInstance()->systemRequestedQuit();
  208043. return MessageManager::getInstance()->hasStopMessageBeenSent();
  208044. }
  208045. return TRUE;
  208046. case WM_TRAYNOTIFY:
  208047. if (component->isCurrentlyBlockedByAnotherModalComponent())
  208048. {
  208049. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  208050. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  208051. {
  208052. Component* const current = Component::getCurrentlyModalComponent();
  208053. if (current != 0)
  208054. current->inputAttemptWhenModal();
  208055. }
  208056. }
  208057. else
  208058. {
  208059. ModifierKeys eventMods (ModifierKeys::getCurrentModifiersRealtime());
  208060. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  208061. eventMods = eventMods.withFlags (ModifierKeys::leftButtonModifier);
  208062. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  208063. eventMods = eventMods.withFlags (ModifierKeys::rightButtonModifier);
  208064. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  208065. eventMods = eventMods.withoutMouseButtons();
  208066. const MouseEvent e (Desktop::getInstance().getMainMouseSource(),
  208067. Point<int>(), eventMods, component, component, getMouseEventTime(),
  208068. Point<int>(), getMouseEventTime(), 1, false);
  208069. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  208070. {
  208071. SetFocus (hwnd);
  208072. SetForegroundWindow (hwnd);
  208073. component->mouseDown (e);
  208074. }
  208075. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  208076. {
  208077. component->mouseUp (e);
  208078. }
  208079. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  208080. {
  208081. component->mouseDoubleClick (e);
  208082. }
  208083. else if (lParam == WM_MOUSEMOVE)
  208084. {
  208085. component->mouseMove (e);
  208086. }
  208087. }
  208088. break;
  208089. case WM_SYNCPAINT:
  208090. return 0;
  208091. case WM_PALETTECHANGED:
  208092. InvalidateRect (h, 0, 0);
  208093. break;
  208094. case WM_DISPLAYCHANGE:
  208095. InvalidateRect (h, 0, 0);
  208096. createPaletteIfNeeded = true;
  208097. // intentional fall-through...
  208098. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  208099. doSettingChange();
  208100. break;
  208101. case WM_INITMENU:
  208102. if (! hasTitleBar())
  208103. {
  208104. if (isFullScreen())
  208105. {
  208106. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  208107. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  208108. }
  208109. else if (! isMinimised())
  208110. {
  208111. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  208112. }
  208113. }
  208114. break;
  208115. case WM_SYSCOMMAND:
  208116. switch (wParam & 0xfff0)
  208117. {
  208118. case SC_CLOSE:
  208119. if (sendInputAttemptWhenModalMessage())
  208120. return 0;
  208121. if (hasTitleBar())
  208122. {
  208123. PostMessage (h, WM_CLOSE, 0, 0);
  208124. return 0;
  208125. }
  208126. break;
  208127. case SC_KEYMENU:
  208128. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very
  208129. // obscure situations that can arise if a modal loop is started from an alt-key
  208130. // keypress).
  208131. if (hasTitleBar() && h == GetCapture())
  208132. ReleaseCapture();
  208133. break;
  208134. case SC_MAXIMIZE:
  208135. if (sendInputAttemptWhenModalMessage())
  208136. return 0;
  208137. setFullScreen (true);
  208138. return 0;
  208139. case SC_MINIMIZE:
  208140. if (sendInputAttemptWhenModalMessage())
  208141. return 0;
  208142. if (! hasTitleBar())
  208143. {
  208144. setMinimised (true);
  208145. return 0;
  208146. }
  208147. break;
  208148. case SC_RESTORE:
  208149. if (sendInputAttemptWhenModalMessage())
  208150. return 0;
  208151. if (hasTitleBar())
  208152. {
  208153. if (isFullScreen())
  208154. {
  208155. setFullScreen (false);
  208156. return 0;
  208157. }
  208158. }
  208159. else
  208160. {
  208161. if (isMinimised())
  208162. setMinimised (false);
  208163. else if (isFullScreen())
  208164. setFullScreen (false);
  208165. return 0;
  208166. }
  208167. break;
  208168. }
  208169. break;
  208170. case WM_NCLBUTTONDOWN:
  208171. case WM_NCRBUTTONDOWN:
  208172. case WM_NCMBUTTONDOWN:
  208173. sendInputAttemptWhenModalMessage();
  208174. break;
  208175. //case WM_IME_STARTCOMPOSITION;
  208176. // return 0;
  208177. case WM_GETDLGCODE:
  208178. return DLGC_WANTALLKEYS;
  208179. default:
  208180. break;
  208181. }
  208182. }
  208183. return DefWindowProcW (h, message, wParam, lParam);
  208184. }
  208185. bool sendInputAttemptWhenModalMessage()
  208186. {
  208187. if (component->isCurrentlyBlockedByAnotherModalComponent())
  208188. {
  208189. Component* const current = Component::getCurrentlyModalComponent();
  208190. if (current != 0)
  208191. current->inputAttemptWhenModal();
  208192. return true;
  208193. }
  208194. return false;
  208195. }
  208196. Win32ComponentPeer (const Win32ComponentPeer&);
  208197. Win32ComponentPeer& operator= (const Win32ComponentPeer&);
  208198. };
  208199. ModifierKeys Win32ComponentPeer::currentModifiers;
  208200. ModifierKeys Win32ComponentPeer::modifiersAtLastCallback;
  208201. ComponentPeer* Component::createNewPeer (int styleFlags, void* nativeWindowToAttachTo)
  208202. {
  208203. return new Win32ComponentPeer (this, styleFlags, (HWND) nativeWindowToAttachTo);
  208204. }
  208205. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  208206. void ModifierKeys::updateCurrentModifiers() throw()
  208207. {
  208208. currentModifiers = Win32ComponentPeer::currentModifiers;
  208209. }
  208210. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  208211. {
  208212. Win32ComponentPeer::updateKeyModifiers();
  208213. int keyMods = 0;
  208214. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::leftButtonModifier;
  208215. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::rightButtonModifier;
  208216. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0) keyMods |= ModifierKeys::middleButtonModifier;
  208217. Win32ComponentPeer::currentModifiers
  208218. = Win32ComponentPeer::currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  208219. return Win32ComponentPeer::currentModifiers;
  208220. }
  208221. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  208222. {
  208223. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208224. if (wp != 0)
  208225. wp->setTaskBarIcon (newImage);
  208226. }
  208227. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  208228. {
  208229. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208230. if (wp != 0)
  208231. wp->setTaskBarIconToolTip (tooltip);
  208232. }
  208233. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  208234. {
  208235. DWORD val = GetWindowLong (h, styleType);
  208236. if (bitIsSet)
  208237. val |= feature;
  208238. else
  208239. val &= ~feature;
  208240. SetWindowLongPtr (h, styleType, val);
  208241. SetWindowPos (h, 0, 0, 0, 0, 0,
  208242. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  208243. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  208244. }
  208245. bool Process::isForegroundProcess()
  208246. {
  208247. HWND fg = GetForegroundWindow();
  208248. if (fg == 0)
  208249. return true;
  208250. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  208251. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  208252. // have to see if any of our windows are children of the foreground window
  208253. fg = GetAncestor (fg, GA_ROOT);
  208254. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  208255. {
  208256. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  208257. if (wp != 0 && wp->isInside (fg))
  208258. return true;
  208259. }
  208260. return false;
  208261. }
  208262. bool AlertWindow::showNativeDialogBox (const String& title,
  208263. const String& bodyText,
  208264. bool isOkCancel)
  208265. {
  208266. return MessageBox (0, bodyText, title,
  208267. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  208268. : MB_OK)) == IDOK;
  208269. }
  208270. void Desktop::createMouseInputSources()
  208271. {
  208272. mouseSources.add (new MouseInputSource (0, true));
  208273. }
  208274. const Point<int> Desktop::getMousePosition()
  208275. {
  208276. POINT mousePos;
  208277. GetCursorPos (&mousePos);
  208278. return Point<int> (mousePos.x, mousePos.y);
  208279. }
  208280. void Desktop::setMousePosition (const Point<int>& newPosition)
  208281. {
  208282. SetCursorPos (newPosition.getX(), newPosition.getY());
  208283. }
  208284. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  208285. {
  208286. return createSoftwareImage (format, width, height, clearImage);
  208287. }
  208288. class ScreenSaverDefeater : public Timer,
  208289. public DeletedAtShutdown
  208290. {
  208291. public:
  208292. ScreenSaverDefeater()
  208293. {
  208294. startTimer (10000);
  208295. timerCallback();
  208296. }
  208297. ~ScreenSaverDefeater() {}
  208298. void timerCallback()
  208299. {
  208300. if (Process::isForegroundProcess())
  208301. {
  208302. // simulate a shift key getting pressed..
  208303. INPUT input[2];
  208304. input[0].type = INPUT_KEYBOARD;
  208305. input[0].ki.wVk = VK_SHIFT;
  208306. input[0].ki.dwFlags = 0;
  208307. input[0].ki.dwExtraInfo = 0;
  208308. input[1].type = INPUT_KEYBOARD;
  208309. input[1].ki.wVk = VK_SHIFT;
  208310. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  208311. input[1].ki.dwExtraInfo = 0;
  208312. SendInput (2, input, sizeof (INPUT));
  208313. }
  208314. }
  208315. };
  208316. static ScreenSaverDefeater* screenSaverDefeater = 0;
  208317. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  208318. {
  208319. if (isEnabled)
  208320. deleteAndZero (screenSaverDefeater);
  208321. else if (screenSaverDefeater == 0)
  208322. screenSaverDefeater = new ScreenSaverDefeater();
  208323. }
  208324. bool Desktop::isScreenSaverEnabled()
  208325. {
  208326. return screenSaverDefeater == 0;
  208327. }
  208328. /* (The code below is the "correct" way to disable the screen saver, but it
  208329. completely fails on winXP when the saver is password-protected...)
  208330. static bool juce_screenSaverEnabled = true;
  208331. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  208332. {
  208333. juce_screenSaverEnabled = isEnabled;
  208334. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  208335. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  208336. }
  208337. bool Desktop::isScreenSaverEnabled() throw()
  208338. {
  208339. return juce_screenSaverEnabled;
  208340. }
  208341. */
  208342. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  208343. {
  208344. if (enableOrDisable)
  208345. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  208346. }
  208347. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  208348. {
  208349. Array <Rectangle<int> >* const monitorCoords = (Array <Rectangle<int> >*) userInfo;
  208350. monitorCoords->add (Rectangle<int> (r->left, r->top, r->right - r->left, r->bottom - r->top));
  208351. return TRUE;
  208352. }
  208353. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  208354. {
  208355. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  208356. // make sure the first in the list is the main monitor
  208357. for (int i = 1; i < monitorCoords.size(); ++i)
  208358. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  208359. monitorCoords.swap (i, 0);
  208360. if (monitorCoords.size() == 0)
  208361. {
  208362. RECT r;
  208363. GetWindowRect (GetDesktopWindow(), &r);
  208364. monitorCoords.add (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  208365. }
  208366. if (clipToWorkArea)
  208367. {
  208368. // clip the main monitor to the active non-taskbar area
  208369. RECT r;
  208370. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  208371. Rectangle<int>& screen = monitorCoords.getReference (0);
  208372. screen.setPosition (jmax (screen.getX(), (int) r.left),
  208373. jmax (screen.getY(), (int) r.top));
  208374. screen.setSize (jmin (screen.getRight(), (int) r.right) - screen.getX(),
  208375. jmin (screen.getBottom(), (int) r.bottom) - screen.getY());
  208376. }
  208377. }
  208378. static const Image createImageFromHBITMAP (HBITMAP bitmap)
  208379. {
  208380. Image im;
  208381. if (bitmap != 0)
  208382. {
  208383. BITMAP bm;
  208384. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  208385. && bm.bmWidth > 0 && bm.bmHeight > 0)
  208386. {
  208387. HDC tempDC = GetDC (0);
  208388. HDC dc = CreateCompatibleDC (tempDC);
  208389. ReleaseDC (0, tempDC);
  208390. SelectObject (dc, bitmap);
  208391. im = Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  208392. Image::BitmapData imageData (im, true);
  208393. for (int y = bm.bmHeight; --y >= 0;)
  208394. {
  208395. for (int x = bm.bmWidth; --x >= 0;)
  208396. {
  208397. COLORREF col = GetPixel (dc, x, y);
  208398. imageData.setPixelColour (x, y, Colour ((uint8) GetRValue (col),
  208399. (uint8) GetGValue (col),
  208400. (uint8) GetBValue (col)));
  208401. }
  208402. }
  208403. DeleteDC (dc);
  208404. }
  208405. }
  208406. return im;
  208407. }
  208408. static const Image createImageFromHICON (HICON icon)
  208409. {
  208410. ICONINFO info;
  208411. if (GetIconInfo (icon, &info))
  208412. {
  208413. Image mask (createImageFromHBITMAP (info.hbmMask));
  208414. Image image (createImageFromHBITMAP (info.hbmColor));
  208415. if (mask.isValid() && image.isValid())
  208416. {
  208417. for (int y = image.getHeight(); --y >= 0;)
  208418. {
  208419. for (int x = image.getWidth(); --x >= 0;)
  208420. {
  208421. const float brightness = mask.getPixelAt (x, y).getBrightness();
  208422. if (brightness > 0.0f)
  208423. image.multiplyAlphaAt (x, y, 1.0f - brightness);
  208424. }
  208425. }
  208426. return image;
  208427. }
  208428. }
  208429. return Image::null;
  208430. }
  208431. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY)
  208432. {
  208433. WindowsBitmapImage* nativeBitmap = new WindowsBitmapImage (Image::ARGB, image.getWidth(), image.getHeight(), true);
  208434. Image bitmap (nativeBitmap);
  208435. {
  208436. Graphics g (bitmap);
  208437. g.drawImageAt (image, 0, 0);
  208438. }
  208439. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  208440. ICONINFO info;
  208441. info.fIcon = isIcon;
  208442. info.xHotspot = hotspotX;
  208443. info.yHotspot = hotspotY;
  208444. info.hbmMask = mask;
  208445. info.hbmColor = nativeBitmap->hBitmap;
  208446. HICON hi = CreateIconIndirect (&info);
  208447. DeleteObject (mask);
  208448. return hi;
  208449. }
  208450. const Image juce_createIconForFile (const File& file)
  208451. {
  208452. Image image;
  208453. WCHAR filename [1024];
  208454. file.getFullPathName().copyToUnicode (filename, 1023);
  208455. WORD iconNum = 0;
  208456. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  208457. filename, &iconNum);
  208458. if (icon != 0)
  208459. {
  208460. image = createImageFromHICON (icon);
  208461. DestroyIcon (icon);
  208462. }
  208463. return image;
  208464. }
  208465. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  208466. {
  208467. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  208468. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  208469. Image im (image);
  208470. if (im.getWidth() > maxW || im.getHeight() > maxH)
  208471. {
  208472. im = im.rescaled (maxW, maxH);
  208473. hotspotX = (hotspotX * maxW) / image.getWidth();
  208474. hotspotY = (hotspotY * maxH) / image.getHeight();
  208475. }
  208476. return createHICONFromImage (im, FALSE, hotspotX, hotspotY);
  208477. }
  208478. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  208479. {
  208480. if (cursorHandle != 0 && ! isStandard)
  208481. DestroyCursor ((HCURSOR) cursorHandle);
  208482. }
  208483. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  208484. {
  208485. LPCTSTR cursorName = IDC_ARROW;
  208486. switch (type)
  208487. {
  208488. case NormalCursor: break;
  208489. case NoCursor: return 0;
  208490. case WaitCursor: cursorName = IDC_WAIT; break;
  208491. case IBeamCursor: cursorName = IDC_IBEAM; break;
  208492. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  208493. case CrosshairCursor: cursorName = IDC_CROSS; break;
  208494. case CopyingCursor: break; // can't seem to find one of these in the win32 list..
  208495. case LeftRightResizeCursor:
  208496. case LeftEdgeResizeCursor:
  208497. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  208498. case UpDownResizeCursor:
  208499. case TopEdgeResizeCursor:
  208500. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  208501. case TopLeftCornerResizeCursor:
  208502. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  208503. case TopRightCornerResizeCursor:
  208504. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  208505. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  208506. case DraggingHandCursor:
  208507. {
  208508. static void* dragHandCursor = 0;
  208509. if (dragHandCursor == 0)
  208510. {
  208511. static const unsigned char dragHandData[] =
  208512. { 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,
  208513. 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,
  208514. 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 };
  208515. dragHandCursor = createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)), 8, 7);
  208516. }
  208517. return dragHandCursor;
  208518. }
  208519. default:
  208520. jassertfalse; break;
  208521. }
  208522. HCURSOR cursorH = LoadCursor (0, cursorName);
  208523. if (cursorH == 0)
  208524. cursorH = LoadCursor (0, IDC_ARROW);
  208525. return cursorH;
  208526. }
  208527. void MouseCursor::showInWindow (ComponentPeer*) const
  208528. {
  208529. SetCursor ((HCURSOR) getHandle());
  208530. }
  208531. void MouseCursor::showInAllWindows() const
  208532. {
  208533. showInWindow (0);
  208534. }
  208535. class JuceDropSource : public ComBaseClassHelper <IDropSource>
  208536. {
  208537. public:
  208538. JuceDropSource() {}
  208539. ~JuceDropSource() {}
  208540. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  208541. {
  208542. if (escapePressed)
  208543. return DRAGDROP_S_CANCEL;
  208544. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  208545. return DRAGDROP_S_DROP;
  208546. return S_OK;
  208547. }
  208548. HRESULT __stdcall GiveFeedback (DWORD)
  208549. {
  208550. return DRAGDROP_S_USEDEFAULTCURSORS;
  208551. }
  208552. };
  208553. class JuceEnumFormatEtc : public ComBaseClassHelper <IEnumFORMATETC>
  208554. {
  208555. public:
  208556. JuceEnumFormatEtc (const FORMATETC* const format_)
  208557. : format (format_),
  208558. index (0)
  208559. {
  208560. }
  208561. ~JuceEnumFormatEtc() {}
  208562. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  208563. {
  208564. if (result == 0)
  208565. return E_POINTER;
  208566. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  208567. newOne->index = index;
  208568. *result = newOne;
  208569. return S_OK;
  208570. }
  208571. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  208572. {
  208573. if (pceltFetched != 0)
  208574. *pceltFetched = 0;
  208575. else if (celt != 1)
  208576. return S_FALSE;
  208577. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  208578. {
  208579. copyFormatEtc (lpFormatEtc [0], *format);
  208580. ++index;
  208581. if (pceltFetched != 0)
  208582. *pceltFetched = 1;
  208583. return S_OK;
  208584. }
  208585. return S_FALSE;
  208586. }
  208587. HRESULT __stdcall Skip (ULONG celt)
  208588. {
  208589. if (index + (int) celt >= 1)
  208590. return S_FALSE;
  208591. index += celt;
  208592. return S_OK;
  208593. }
  208594. HRESULT __stdcall Reset()
  208595. {
  208596. index = 0;
  208597. return S_OK;
  208598. }
  208599. private:
  208600. const FORMATETC* const format;
  208601. int index;
  208602. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  208603. {
  208604. dest = source;
  208605. if (source.ptd != 0)
  208606. {
  208607. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  208608. *(dest.ptd) = *(source.ptd);
  208609. }
  208610. }
  208611. JuceEnumFormatEtc (const JuceEnumFormatEtc&);
  208612. JuceEnumFormatEtc& operator= (const JuceEnumFormatEtc&);
  208613. };
  208614. class JuceDataObject : public ComBaseClassHelper <IDataObject>
  208615. {
  208616. public:
  208617. JuceDataObject (JuceDropSource* const dropSource_,
  208618. const FORMATETC* const format_,
  208619. const STGMEDIUM* const medium_)
  208620. : dropSource (dropSource_),
  208621. format (format_),
  208622. medium (medium_)
  208623. {
  208624. }
  208625. virtual ~JuceDataObject()
  208626. {
  208627. jassert (refCount == 0);
  208628. }
  208629. HRESULT __stdcall GetData (FORMATETC __RPC_FAR* pFormatEtc, STGMEDIUM __RPC_FAR* pMedium)
  208630. {
  208631. if ((pFormatEtc->tymed & format->tymed) != 0
  208632. && pFormatEtc->cfFormat == format->cfFormat
  208633. && pFormatEtc->dwAspect == format->dwAspect)
  208634. {
  208635. pMedium->tymed = format->tymed;
  208636. pMedium->pUnkForRelease = 0;
  208637. if (format->tymed == TYMED_HGLOBAL)
  208638. {
  208639. const SIZE_T len = GlobalSize (medium->hGlobal);
  208640. void* const src = GlobalLock (medium->hGlobal);
  208641. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  208642. memcpy (dst, src, len);
  208643. GlobalUnlock (medium->hGlobal);
  208644. pMedium->hGlobal = dst;
  208645. return S_OK;
  208646. }
  208647. }
  208648. return DV_E_FORMATETC;
  208649. }
  208650. HRESULT __stdcall QueryGetData (FORMATETC __RPC_FAR* f)
  208651. {
  208652. if (f == 0)
  208653. return E_INVALIDARG;
  208654. if (f->tymed == format->tymed
  208655. && f->cfFormat == format->cfFormat
  208656. && f->dwAspect == format->dwAspect)
  208657. return S_OK;
  208658. return DV_E_FORMATETC;
  208659. }
  208660. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC __RPC_FAR*, FORMATETC __RPC_FAR* pFormatEtcOut)
  208661. {
  208662. pFormatEtcOut->ptd = 0;
  208663. return E_NOTIMPL;
  208664. }
  208665. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC __RPC_FAR *__RPC_FAR *result)
  208666. {
  208667. if (result == 0)
  208668. return E_POINTER;
  208669. if (direction == DATADIR_GET)
  208670. {
  208671. *result = new JuceEnumFormatEtc (format);
  208672. return S_OK;
  208673. }
  208674. *result = 0;
  208675. return E_NOTIMPL;
  208676. }
  208677. HRESULT __stdcall GetDataHere (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*) { return DATA_E_FORMATETC; }
  208678. HRESULT __stdcall SetData (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*, BOOL) { return E_NOTIMPL; }
  208679. HRESULT __stdcall DAdvise (FORMATETC __RPC_FAR*, DWORD, IAdviseSink __RPC_FAR*, DWORD __RPC_FAR*) { return OLE_E_ADVISENOTSUPPORTED; }
  208680. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  208681. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA __RPC_FAR *__RPC_FAR *) { return OLE_E_ADVISENOTSUPPORTED; }
  208682. private:
  208683. JuceDropSource* const dropSource;
  208684. const FORMATETC* const format;
  208685. const STGMEDIUM* const medium;
  208686. JuceDataObject (const JuceDataObject&);
  208687. JuceDataObject& operator= (const JuceDataObject&);
  208688. };
  208689. static HDROP createHDrop (const StringArray& fileNames)
  208690. {
  208691. int totalChars = 0;
  208692. for (int i = fileNames.size(); --i >= 0;)
  208693. totalChars += fileNames[i].length() + 1;
  208694. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  208695. sizeof (DROPFILES) + sizeof (WCHAR) * (totalChars + 2));
  208696. if (hDrop != 0)
  208697. {
  208698. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  208699. pDropFiles->pFiles = sizeof (DROPFILES);
  208700. pDropFiles->fWide = true;
  208701. WCHAR* fname = reinterpret_cast<WCHAR*> (addBytesToPointer (pDropFiles, sizeof (DROPFILES)));
  208702. for (int i = 0; i < fileNames.size(); ++i)
  208703. {
  208704. fileNames[i].copyToUnicode (fname, 2048);
  208705. fname += fileNames[i].length() + 1;
  208706. }
  208707. *fname = 0;
  208708. GlobalUnlock (hDrop);
  208709. }
  208710. return hDrop;
  208711. }
  208712. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo)
  208713. {
  208714. JuceDropSource* const source = new JuceDropSource();
  208715. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  208716. DWORD effect;
  208717. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  208718. data->Release();
  208719. source->Release();
  208720. return res == DRAGDROP_S_DROP;
  208721. }
  208722. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  208723. {
  208724. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208725. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208726. medium.hGlobal = createHDrop (files);
  208727. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  208728. : DROPEFFECT_COPY);
  208729. }
  208730. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  208731. {
  208732. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208733. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208734. const int numChars = text.length();
  208735. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  208736. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (medium.hGlobal));
  208737. text.copyToUnicode (data, numChars + 1);
  208738. format.cfFormat = CF_UNICODETEXT;
  208739. GlobalUnlock (medium.hGlobal);
  208740. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  208741. }
  208742. #endif
  208743. /*** End of inlined file: juce_win32_Windowing.cpp ***/
  208744. /*** Start of inlined file: juce_win32_FileChooser.cpp ***/
  208745. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208746. // compiled on its own).
  208747. #if JUCE_INCLUDED_FILE
  208748. namespace FileChooserHelpers
  208749. {
  208750. static bool areThereAnyAlwaysOnTopWindows()
  208751. {
  208752. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  208753. {
  208754. Component* c = Desktop::getInstance().getComponent (i);
  208755. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  208756. return true;
  208757. }
  208758. return false;
  208759. }
  208760. struct FileChooserCallbackInfo
  208761. {
  208762. String initialPath;
  208763. String returnedString; // need this to get non-existent pathnames from the directory chooser
  208764. ScopedPointer<Component> customComponent;
  208765. };
  208766. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM lpData)
  208767. {
  208768. FileChooserCallbackInfo* info = (FileChooserCallbackInfo*) lpData;
  208769. if (msg == BFFM_INITIALIZED)
  208770. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) static_cast <const WCHAR*> (info->initialPath));
  208771. else if (msg == BFFM_VALIDATEFAILEDW)
  208772. info->returnedString = (LPCWSTR) lParam;
  208773. else if (msg == BFFM_VALIDATEFAILEDA)
  208774. info->returnedString = (const char*) lParam;
  208775. return 0;
  208776. }
  208777. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  208778. {
  208779. if (uiMsg == WM_INITDIALOG)
  208780. {
  208781. Component* customComp = ((FileChooserCallbackInfo*) (((OPENFILENAMEW*) lParam)->lCustData))->customComponent;
  208782. HWND dialogH = GetParent (hdlg);
  208783. jassert (dialogH != 0);
  208784. if (dialogH == 0)
  208785. dialogH = hdlg;
  208786. RECT r, cr;
  208787. GetWindowRect (dialogH, &r);
  208788. GetClientRect (dialogH, &cr);
  208789. SetWindowPos (dialogH, 0,
  208790. r.left, r.top,
  208791. customComp->getWidth() + jmax (150, (int) (r.right - r.left)),
  208792. jmax (150, (int) (r.bottom - r.top)),
  208793. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  208794. customComp->setBounds (cr.right, cr.top, customComp->getWidth(), cr.bottom - cr.top);
  208795. customComp->addToDesktop (0, dialogH);
  208796. }
  208797. else if (uiMsg == WM_NOTIFY)
  208798. {
  208799. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  208800. if (ofn->hdr.code == CDN_SELCHANGE)
  208801. {
  208802. FileChooserCallbackInfo* info = (FileChooserCallbackInfo*) ofn->lpOFN->lCustData;
  208803. FilePreviewComponent* comp = static_cast<FilePreviewComponent*> (info->customComponent->getChildComponent(0));
  208804. if (comp != 0)
  208805. {
  208806. WCHAR path [MAX_PATH * 2];
  208807. zerostruct (path);
  208808. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  208809. comp->selectedFileChanged (File (path));
  208810. }
  208811. }
  208812. }
  208813. return 0;
  208814. }
  208815. class CustomComponentHolder : public Component
  208816. {
  208817. public:
  208818. CustomComponentHolder (Component* customComp)
  208819. {
  208820. setVisible (true);
  208821. setOpaque (true);
  208822. addAndMakeVisible (customComp);
  208823. setSize (jlimit (20, 800, customComp->getWidth()), customComp->getHeight());
  208824. }
  208825. void paint (Graphics& g)
  208826. {
  208827. g.fillAll (Colours::lightgrey);
  208828. }
  208829. void resized()
  208830. {
  208831. if (getNumChildComponents() > 0)
  208832. getChildComponent(0)->setBounds (getLocalBounds());
  208833. }
  208834. juce_UseDebuggingNewOperator
  208835. private:
  208836. CustomComponentHolder (const CustomComponentHolder&);
  208837. CustomComponentHolder& operator= (const CustomComponentHolder&);
  208838. };
  208839. }
  208840. void FileChooser::showPlatformDialog (Array<File>& results, const String& title, const File& currentFileOrDirectory,
  208841. const String& filter, bool selectsDirectory, bool /*selectsFiles*/,
  208842. bool isSaveDialogue, bool warnAboutOverwritingExistingFiles,
  208843. bool selectMultipleFiles, FilePreviewComponent* extraInfoComponent)
  208844. {
  208845. using namespace FileChooserHelpers;
  208846. HeapBlock<WCHAR> files;
  208847. const int charsAvailableForResult = 32768;
  208848. files.calloc (charsAvailableForResult + 1);
  208849. int filenameOffset = 0;
  208850. FileChooserCallbackInfo info;
  208851. // use a modal window as the parent for this dialog box
  208852. // to block input from other app windows
  208853. Component parentWindow (String::empty);
  208854. const Rectangle<int> mainMon (Desktop::getInstance().getMainMonitorArea());
  208855. parentWindow.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  208856. mainMon.getY() + mainMon.getHeight() / 4,
  208857. 0, 0);
  208858. parentWindow.setOpaque (true);
  208859. parentWindow.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  208860. parentWindow.addToDesktop (0);
  208861. if (extraInfoComponent == 0)
  208862. parentWindow.enterModalState();
  208863. if (currentFileOrDirectory.isDirectory())
  208864. {
  208865. info.initialPath = currentFileOrDirectory.getFullPathName();
  208866. }
  208867. else
  208868. {
  208869. currentFileOrDirectory.getFileName().copyToUnicode (files, charsAvailableForResult);
  208870. info.initialPath = currentFileOrDirectory.getParentDirectory().getFullPathName();
  208871. }
  208872. if (selectsDirectory)
  208873. {
  208874. BROWSEINFO bi;
  208875. zerostruct (bi);
  208876. bi.hwndOwner = (HWND) parentWindow.getWindowHandle();
  208877. bi.pszDisplayName = files;
  208878. bi.lpszTitle = title;
  208879. bi.lParam = (LPARAM) &info;
  208880. bi.lpfn = browseCallbackProc;
  208881. #ifdef BIF_USENEWUI
  208882. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  208883. #else
  208884. bi.ulFlags = 0x50;
  208885. #endif
  208886. LPITEMIDLIST list = SHBrowseForFolder (&bi);
  208887. if (! SHGetPathFromIDListW (list, files))
  208888. {
  208889. files[0] = 0;
  208890. info.returnedString = String::empty;
  208891. }
  208892. LPMALLOC al;
  208893. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  208894. al->Free (list);
  208895. if (info.returnedString.isNotEmpty())
  208896. {
  208897. results.add (File (String (files)).getSiblingFile (info.returnedString));
  208898. return;
  208899. }
  208900. }
  208901. else
  208902. {
  208903. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  208904. if (warnAboutOverwritingExistingFiles)
  208905. flags |= OFN_OVERWRITEPROMPT;
  208906. if (selectMultipleFiles)
  208907. flags |= OFN_ALLOWMULTISELECT;
  208908. if (extraInfoComponent != 0)
  208909. {
  208910. flags |= OFN_ENABLEHOOK;
  208911. info.customComponent = new CustomComponentHolder (extraInfoComponent);
  208912. info.customComponent->enterModalState();
  208913. }
  208914. WCHAR filters [1024];
  208915. zerostruct (filters);
  208916. filter.copyToUnicode (filters, 1024);
  208917. filter.copyToUnicode (filters + filter.length() + 1, 1022 - filter.length());
  208918. OPENFILENAMEW of;
  208919. zerostruct (of);
  208920. #ifdef OPENFILENAME_SIZE_VERSION_400W
  208921. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  208922. #else
  208923. of.lStructSize = sizeof (of);
  208924. #endif
  208925. of.hwndOwner = (HWND) parentWindow.getWindowHandle();
  208926. of.lpstrFilter = filters;
  208927. of.nFilterIndex = 1;
  208928. of.lpstrFile = files;
  208929. of.nMaxFile = charsAvailableForResult;
  208930. of.lpstrInitialDir = info.initialPath;
  208931. of.lpstrTitle = title;
  208932. of.Flags = flags;
  208933. of.lCustData = (LPARAM) &info;
  208934. if (extraInfoComponent != 0)
  208935. of.lpfnHook = &openCallback;
  208936. if (! (isSaveDialogue ? GetSaveFileName (&of)
  208937. : GetOpenFileName (&of)))
  208938. return;
  208939. filenameOffset = of.nFileOffset;
  208940. }
  208941. if (selectMultipleFiles && filenameOffset > 0 && files [filenameOffset - 1] == 0)
  208942. {
  208943. const WCHAR* filename = files + filenameOffset;
  208944. while (*filename != 0)
  208945. {
  208946. results.add (File (String (files) + "\\" + String (filename)));
  208947. filename += CharacterFunctions::length (filename) + 1;
  208948. }
  208949. }
  208950. else if (files[0] != 0)
  208951. {
  208952. results.add (File (String (files)));
  208953. }
  208954. }
  208955. #endif
  208956. /*** End of inlined file: juce_win32_FileChooser.cpp ***/
  208957. /*** Start of inlined file: juce_win32_Misc.cpp ***/
  208958. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208959. // compiled on its own).
  208960. #if JUCE_INCLUDED_FILE
  208961. void SystemClipboard::copyTextToClipboard (const String& text)
  208962. {
  208963. if (OpenClipboard (0) != 0)
  208964. {
  208965. if (EmptyClipboard() != 0)
  208966. {
  208967. const int len = text.length();
  208968. if (len > 0)
  208969. {
  208970. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE,
  208971. (len + 1) * sizeof (wchar_t));
  208972. if (bufH != 0)
  208973. {
  208974. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (bufH));
  208975. text.copyToUnicode (data, len);
  208976. GlobalUnlock (bufH);
  208977. SetClipboardData (CF_UNICODETEXT, bufH);
  208978. }
  208979. }
  208980. }
  208981. CloseClipboard();
  208982. }
  208983. }
  208984. const String SystemClipboard::getTextFromClipboard()
  208985. {
  208986. String result;
  208987. if (OpenClipboard (0) != 0)
  208988. {
  208989. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  208990. if (bufH != 0)
  208991. {
  208992. const wchar_t* const data = (const wchar_t*) GlobalLock (bufH);
  208993. if (data != 0)
  208994. {
  208995. result = String (data, (int) (GlobalSize (bufH) / sizeof (wchar_t)));
  208996. GlobalUnlock (bufH);
  208997. }
  208998. }
  208999. CloseClipboard();
  209000. }
  209001. return result;
  209002. }
  209003. #endif
  209004. /*** End of inlined file: juce_win32_Misc.cpp ***/
  209005. /*** Start of inlined file: juce_win32_ActiveXComponent.cpp ***/
  209006. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209007. // compiled on its own).
  209008. #if JUCE_INCLUDED_FILE
  209009. namespace ActiveXHelpers
  209010. {
  209011. class JuceIStorage : public ComBaseClassHelper <IStorage>
  209012. {
  209013. public:
  209014. JuceIStorage() {}
  209015. ~JuceIStorage() {}
  209016. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  209017. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  209018. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  209019. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  209020. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  209021. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  209022. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  209023. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  209024. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  209025. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  209026. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  209027. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  209028. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  209029. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  209030. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  209031. juce_UseDebuggingNewOperator
  209032. };
  209033. class JuceOleInPlaceFrame : public ComBaseClassHelper <IOleInPlaceFrame>
  209034. {
  209035. HWND window;
  209036. public:
  209037. JuceOleInPlaceFrame (HWND window_) : window (window_) {}
  209038. ~JuceOleInPlaceFrame() {}
  209039. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  209040. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  209041. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  209042. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  209043. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  209044. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  209045. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  209046. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  209047. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  209048. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  209049. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  209050. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  209051. juce_UseDebuggingNewOperator
  209052. };
  209053. class JuceIOleInPlaceSite : public ComBaseClassHelper <IOleInPlaceSite>
  209054. {
  209055. HWND window;
  209056. JuceOleInPlaceFrame* frame;
  209057. public:
  209058. JuceIOleInPlaceSite (HWND window_)
  209059. : window (window_),
  209060. frame (new JuceOleInPlaceFrame (window))
  209061. {}
  209062. ~JuceIOleInPlaceSite()
  209063. {
  209064. frame->Release();
  209065. }
  209066. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  209067. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  209068. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  209069. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  209070. HRESULT __stdcall OnUIActivate() { return S_OK; }
  209071. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  209072. {
  209073. /* Note: if you call AddRef on the frame here, then some types of object (e.g. web browser control) cause leaks..
  209074. If you don't call AddRef then others crash (e.g. QuickTime).. Bit of a catch-22, so letting it leak is probably preferable.
  209075. */
  209076. if (lplpFrame != 0) { frame->AddRef(); *lplpFrame = frame; }
  209077. if (lplpDoc != 0) *lplpDoc = 0;
  209078. lpFrameInfo->fMDIApp = FALSE;
  209079. lpFrameInfo->hwndFrame = window;
  209080. lpFrameInfo->haccel = 0;
  209081. lpFrameInfo->cAccelEntries = 0;
  209082. return S_OK;
  209083. }
  209084. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  209085. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  209086. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  209087. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  209088. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  209089. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  209090. juce_UseDebuggingNewOperator
  209091. };
  209092. class JuceIOleClientSite : public ComBaseClassHelper <IOleClientSite>
  209093. {
  209094. JuceIOleInPlaceSite* inplaceSite;
  209095. public:
  209096. JuceIOleClientSite (HWND window)
  209097. : inplaceSite (new JuceIOleInPlaceSite (window))
  209098. {}
  209099. ~JuceIOleClientSite()
  209100. {
  209101. inplaceSite->Release();
  209102. }
  209103. HRESULT __stdcall QueryInterface (REFIID type, void __RPC_FAR* __RPC_FAR* result)
  209104. {
  209105. if (type == IID_IOleInPlaceSite)
  209106. {
  209107. inplaceSite->AddRef();
  209108. *result = static_cast <IOleInPlaceSite*> (inplaceSite);
  209109. return S_OK;
  209110. }
  209111. return ComBaseClassHelper <IOleClientSite>::QueryInterface (type, result);
  209112. }
  209113. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  209114. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  209115. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  209116. HRESULT __stdcall ShowObject() { return S_OK; }
  209117. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  209118. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  209119. juce_UseDebuggingNewOperator
  209120. };
  209121. static Array<ActiveXControlComponent*> activeXComps;
  209122. static HWND getHWND (const ActiveXControlComponent* const component)
  209123. {
  209124. HWND hwnd = 0;
  209125. const IID iid = IID_IOleWindow;
  209126. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  209127. if (window != 0)
  209128. {
  209129. window->GetWindow (&hwnd);
  209130. window->Release();
  209131. }
  209132. return hwnd;
  209133. }
  209134. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  209135. {
  209136. RECT activeXRect, peerRect;
  209137. GetWindowRect (hwnd, &activeXRect);
  209138. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  209139. const Point<int> mousePos (GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left,
  209140. GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top);
  209141. const int64 mouseEventTime = Win32ComponentPeer::getMouseEventTime();
  209142. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  209143. switch (message)
  209144. {
  209145. case WM_MOUSEMOVE:
  209146. case WM_LBUTTONDOWN:
  209147. case WM_MBUTTONDOWN:
  209148. case WM_RBUTTONDOWN:
  209149. case WM_LBUTTONUP:
  209150. case WM_MBUTTONUP:
  209151. case WM_RBUTTONUP:
  209152. peer->handleMouseEvent (0, mousePos, Win32ComponentPeer::currentModifiers, mouseEventTime);
  209153. break;
  209154. default:
  209155. break;
  209156. }
  209157. }
  209158. }
  209159. class ActiveXControlComponent::Pimpl : public ComponentMovementWatcher
  209160. {
  209161. ActiveXControlComponent& owner;
  209162. bool wasShowing;
  209163. public:
  209164. HWND controlHWND;
  209165. IStorage* storage;
  209166. IOleClientSite* clientSite;
  209167. IOleObject* control;
  209168. Pimpl (HWND hwnd, ActiveXControlComponent& owner_)
  209169. : ComponentMovementWatcher (&owner_),
  209170. owner (owner_),
  209171. wasShowing (owner_.isShowing()),
  209172. controlHWND (0),
  209173. storage (new ActiveXHelpers::JuceIStorage()),
  209174. clientSite (new ActiveXHelpers::JuceIOleClientSite (hwnd)),
  209175. control (0)
  209176. {
  209177. }
  209178. ~Pimpl()
  209179. {
  209180. if (control != 0)
  209181. {
  209182. control->Close (OLECLOSE_NOSAVE);
  209183. control->Release();
  209184. }
  209185. clientSite->Release();
  209186. storage->Release();
  209187. }
  209188. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  209189. {
  209190. Component* const topComp = owner.getTopLevelComponent();
  209191. if (topComp->getPeer() != 0)
  209192. {
  209193. const Point<int> pos (owner.relativePositionToOtherComponent (topComp, Point<int>()));
  209194. owner.setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), owner.getWidth(), owner.getHeight()));
  209195. }
  209196. }
  209197. void componentPeerChanged()
  209198. {
  209199. const bool isShowingNow = owner.isShowing();
  209200. if (wasShowing != isShowingNow)
  209201. {
  209202. wasShowing = isShowingNow;
  209203. owner.setControlVisible (isShowingNow);
  209204. }
  209205. componentMovedOrResized (true, true);
  209206. }
  209207. void componentVisibilityChanged (Component&)
  209208. {
  209209. componentPeerChanged();
  209210. }
  209211. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  209212. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  209213. {
  209214. for (int i = ActiveXHelpers::activeXComps.size(); --i >= 0;)
  209215. {
  209216. const ActiveXControlComponent* const ax = ActiveXHelpers::activeXComps.getUnchecked(i);
  209217. if (ax->control != 0 && ax->control->controlHWND == hwnd)
  209218. {
  209219. switch (message)
  209220. {
  209221. case WM_MOUSEMOVE:
  209222. case WM_LBUTTONDOWN:
  209223. case WM_MBUTTONDOWN:
  209224. case WM_RBUTTONDOWN:
  209225. case WM_LBUTTONUP:
  209226. case WM_MBUTTONUP:
  209227. case WM_RBUTTONUP:
  209228. case WM_LBUTTONDBLCLK:
  209229. case WM_MBUTTONDBLCLK:
  209230. case WM_RBUTTONDBLCLK:
  209231. if (ax->isShowing())
  209232. {
  209233. ComponentPeer* const peer = ax->getPeer();
  209234. if (peer != 0)
  209235. {
  209236. ActiveXHelpers::offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  209237. if (! ax->areMouseEventsAllowed())
  209238. return 0;
  209239. }
  209240. }
  209241. break;
  209242. default:
  209243. break;
  209244. }
  209245. return CallWindowProc ((WNDPROC) ax->originalWndProc, hwnd, message, wParam, lParam);
  209246. }
  209247. }
  209248. return DefWindowProc (hwnd, message, wParam, lParam);
  209249. }
  209250. };
  209251. ActiveXControlComponent::ActiveXControlComponent()
  209252. : originalWndProc (0),
  209253. mouseEventsAllowed (true)
  209254. {
  209255. ActiveXHelpers::activeXComps.add (this);
  209256. }
  209257. ActiveXControlComponent::~ActiveXControlComponent()
  209258. {
  209259. deleteControl();
  209260. ActiveXHelpers::activeXComps.removeValue (this);
  209261. }
  209262. void ActiveXControlComponent::paint (Graphics& g)
  209263. {
  209264. if (control == 0)
  209265. g.fillAll (Colours::lightgrey);
  209266. }
  209267. bool ActiveXControlComponent::createControl (const void* controlIID)
  209268. {
  209269. deleteControl();
  209270. ComponentPeer* const peer = getPeer();
  209271. // the component must have already been added to a real window when you call this!
  209272. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  209273. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  209274. {
  209275. const Point<int> pos (relativePositionToOtherComponent (getTopLevelComponent(), Point<int>()));
  209276. HWND hwnd = (HWND) peer->getNativeHandle();
  209277. ScopedPointer<Pimpl> newControl (new Pimpl (hwnd, *this));
  209278. HRESULT hr;
  209279. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  209280. newControl->clientSite, newControl->storage,
  209281. (void**) &(newControl->control))) == S_OK)
  209282. {
  209283. newControl->control->SetHostNames (L"Juce", 0);
  209284. if (OleSetContainedObject (newControl->control, TRUE) == S_OK)
  209285. {
  209286. RECT rect;
  209287. rect.left = pos.getX();
  209288. rect.top = pos.getY();
  209289. rect.right = pos.getX() + getWidth();
  209290. rect.bottom = pos.getY() + getHeight();
  209291. if (newControl->control->DoVerb (OLEIVERB_SHOW, 0, newControl->clientSite, 0, hwnd, &rect) == S_OK)
  209292. {
  209293. control = newControl;
  209294. setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), getWidth(), getHeight()));
  209295. control->controlHWND = ActiveXHelpers::getHWND (this);
  209296. if (control->controlHWND != 0)
  209297. {
  209298. originalWndProc = (void*) (pointer_sized_int) GetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC);
  209299. SetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC, (LONG_PTR) Pimpl::activeXHookWndProc);
  209300. }
  209301. return true;
  209302. }
  209303. }
  209304. }
  209305. }
  209306. return false;
  209307. }
  209308. void ActiveXControlComponent::deleteControl()
  209309. {
  209310. control = 0;
  209311. originalWndProc = 0;
  209312. }
  209313. void* ActiveXControlComponent::queryInterface (const void* iid) const
  209314. {
  209315. void* result = 0;
  209316. if (control != 0 && control->control != 0
  209317. && SUCCEEDED (control->control->QueryInterface (*(const IID*) iid, &result)))
  209318. return result;
  209319. return 0;
  209320. }
  209321. void ActiveXControlComponent::setControlBounds (const Rectangle<int>& newBounds) const
  209322. {
  209323. if (control->controlHWND != 0)
  209324. MoveWindow (control->controlHWND, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  209325. }
  209326. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  209327. {
  209328. if (control->controlHWND != 0)
  209329. ShowWindow (control->controlHWND, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  209330. }
  209331. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  209332. {
  209333. mouseEventsAllowed = eventsCanReachControl;
  209334. }
  209335. #endif
  209336. /*** End of inlined file: juce_win32_ActiveXComponent.cpp ***/
  209337. /*** Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209338. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209339. // compiled on its own).
  209340. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  209341. using namespace QTOLibrary;
  209342. using namespace QTOControlLib;
  209343. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  209344. static bool isQTAvailable = false;
  209345. class QuickTimeMovieComponent::Pimpl
  209346. {
  209347. public:
  209348. Pimpl() : dataHandle (0)
  209349. {
  209350. }
  209351. ~Pimpl()
  209352. {
  209353. clearHandle();
  209354. }
  209355. void clearHandle()
  209356. {
  209357. if (dataHandle != 0)
  209358. {
  209359. DisposeHandle (dataHandle);
  209360. dataHandle = 0;
  209361. }
  209362. }
  209363. IQTControlPtr qtControl;
  209364. IQTMoviePtr qtMovie;
  209365. Handle dataHandle;
  209366. };
  209367. QuickTimeMovieComponent::QuickTimeMovieComponent()
  209368. : movieLoaded (false),
  209369. controllerVisible (true)
  209370. {
  209371. pimpl = new Pimpl();
  209372. setMouseEventsAllowed (false);
  209373. }
  209374. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  209375. {
  209376. closeMovie();
  209377. pimpl->qtControl = 0;
  209378. deleteControl();
  209379. pimpl = 0;
  209380. }
  209381. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  209382. {
  209383. if (! isQTAvailable)
  209384. isQTAvailable = (InitializeQTML (0) == noErr) && (EnterMovies() == noErr);
  209385. return isQTAvailable;
  209386. }
  209387. void QuickTimeMovieComponent::createControlIfNeeded()
  209388. {
  209389. if (isShowing() && ! isControlCreated())
  209390. {
  209391. const IID qtIID = __uuidof (QTControl);
  209392. if (createControl (&qtIID))
  209393. {
  209394. const IID qtInterfaceIID = __uuidof (IQTControl);
  209395. pimpl->qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  209396. if (pimpl->qtControl != 0)
  209397. {
  209398. pimpl->qtControl->Release(); // it has one ref too many at this point
  209399. pimpl->qtControl->QuickTimeInitialize();
  209400. pimpl->qtControl->PutSizing (qtMovieFitsControl);
  209401. if (movieFile != File::nonexistent)
  209402. loadMovie (movieFile, controllerVisible);
  209403. }
  209404. }
  209405. }
  209406. }
  209407. bool QuickTimeMovieComponent::isControlCreated() const
  209408. {
  209409. return isControlOpen();
  209410. }
  209411. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  209412. const bool isControllerVisible)
  209413. {
  209414. const ScopedPointer<InputStream> movieStreamDeleter (movieStream);
  209415. movieFile = File::nonexistent;
  209416. movieLoaded = false;
  209417. pimpl->qtMovie = 0;
  209418. controllerVisible = isControllerVisible;
  209419. createControlIfNeeded();
  209420. if (isControlCreated())
  209421. {
  209422. if (pimpl->qtControl != 0)
  209423. {
  209424. pimpl->qtControl->Put_MovieHandle (0);
  209425. pimpl->clearHandle();
  209426. Movie movie;
  209427. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, pimpl->dataHandle))
  209428. {
  209429. pimpl->qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  209430. pimpl->qtMovie = pimpl->qtControl->GetMovie();
  209431. if (pimpl->qtMovie != 0)
  209432. pimpl->qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  209433. : qtMovieControllerTypeNone);
  209434. }
  209435. if (movie == 0)
  209436. pimpl->clearHandle();
  209437. }
  209438. movieLoaded = (pimpl->qtMovie != 0);
  209439. }
  209440. else
  209441. {
  209442. // You're trying to open a movie when the control hasn't yet been created, probably because
  209443. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  209444. jassertfalse;
  209445. }
  209446. return movieLoaded;
  209447. }
  209448. void QuickTimeMovieComponent::closeMovie()
  209449. {
  209450. stop();
  209451. movieFile = File::nonexistent;
  209452. movieLoaded = false;
  209453. pimpl->qtMovie = 0;
  209454. if (pimpl->qtControl != 0)
  209455. pimpl->qtControl->Put_MovieHandle (0);
  209456. pimpl->clearHandle();
  209457. }
  209458. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  209459. {
  209460. return movieFile;
  209461. }
  209462. bool QuickTimeMovieComponent::isMovieOpen() const
  209463. {
  209464. return movieLoaded;
  209465. }
  209466. double QuickTimeMovieComponent::getMovieDuration() const
  209467. {
  209468. if (pimpl->qtMovie != 0)
  209469. return pimpl->qtMovie->GetDuration() / (double) pimpl->qtMovie->GetTimeScale();
  209470. return 0.0;
  209471. }
  209472. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  209473. {
  209474. if (pimpl->qtMovie != 0)
  209475. {
  209476. struct QTRECT r = pimpl->qtMovie->GetNaturalRect();
  209477. width = r.right - r.left;
  209478. height = r.bottom - r.top;
  209479. }
  209480. else
  209481. {
  209482. width = height = 0;
  209483. }
  209484. }
  209485. void QuickTimeMovieComponent::play()
  209486. {
  209487. if (pimpl->qtMovie != 0)
  209488. pimpl->qtMovie->Play();
  209489. }
  209490. void QuickTimeMovieComponent::stop()
  209491. {
  209492. if (pimpl->qtMovie != 0)
  209493. pimpl->qtMovie->Stop();
  209494. }
  209495. bool QuickTimeMovieComponent::isPlaying() const
  209496. {
  209497. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetRate() != 0.0f;
  209498. }
  209499. void QuickTimeMovieComponent::setPosition (const double seconds)
  209500. {
  209501. if (pimpl->qtMovie != 0)
  209502. pimpl->qtMovie->PutTime ((long) (seconds * pimpl->qtMovie->GetTimeScale()));
  209503. }
  209504. double QuickTimeMovieComponent::getPosition() const
  209505. {
  209506. if (pimpl->qtMovie != 0)
  209507. return pimpl->qtMovie->GetTime() / (double) pimpl->qtMovie->GetTimeScale();
  209508. return 0.0;
  209509. }
  209510. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  209511. {
  209512. if (pimpl->qtMovie != 0)
  209513. pimpl->qtMovie->PutRate (newSpeed);
  209514. }
  209515. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  209516. {
  209517. if (pimpl->qtMovie != 0)
  209518. {
  209519. pimpl->qtMovie->PutAudioVolume (newVolume);
  209520. pimpl->qtMovie->PutAudioMute (newVolume <= 0);
  209521. }
  209522. }
  209523. float QuickTimeMovieComponent::getMovieVolume() const
  209524. {
  209525. if (pimpl->qtMovie != 0)
  209526. return pimpl->qtMovie->GetAudioVolume();
  209527. return 0.0f;
  209528. }
  209529. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  209530. {
  209531. if (pimpl->qtMovie != 0)
  209532. pimpl->qtMovie->PutLoop (shouldLoop);
  209533. }
  209534. bool QuickTimeMovieComponent::isLooping() const
  209535. {
  209536. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetLoop();
  209537. }
  209538. bool QuickTimeMovieComponent::isControllerVisible() const
  209539. {
  209540. return controllerVisible;
  209541. }
  209542. void QuickTimeMovieComponent::parentHierarchyChanged()
  209543. {
  209544. createControlIfNeeded();
  209545. QTCompBaseClass::parentHierarchyChanged();
  209546. }
  209547. void QuickTimeMovieComponent::visibilityChanged()
  209548. {
  209549. createControlIfNeeded();
  209550. QTCompBaseClass::visibilityChanged();
  209551. }
  209552. void QuickTimeMovieComponent::paint (Graphics& g)
  209553. {
  209554. if (! isControlCreated())
  209555. g.fillAll (Colours::black);
  209556. }
  209557. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  209558. {
  209559. Handle dataRef = 0;
  209560. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  209561. if (err == noErr)
  209562. {
  209563. Str255 suffix;
  209564. CharacterFunctions::copy ((char*) suffix, fileName, 128);
  209565. StringPtr name = suffix;
  209566. err = PtrAndHand (name, dataRef, name[0] + 1);
  209567. if (err == noErr)
  209568. {
  209569. long atoms[3];
  209570. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  209571. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  209572. atoms[2] = EndianU32_NtoB (MovieFileType);
  209573. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  209574. if (err == noErr)
  209575. return dataRef;
  209576. }
  209577. DisposeHandle (dataRef);
  209578. }
  209579. return 0;
  209580. }
  209581. static CFStringRef juceStringToCFString (const String& s)
  209582. {
  209583. const int len = s.length();
  209584. const juce_wchar* const t = s;
  209585. HeapBlock <UniChar> temp (len + 2);
  209586. for (int i = 0; i <= len; ++i)
  209587. temp[i] = t[i];
  209588. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  209589. }
  209590. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  209591. {
  209592. Boolean trueBool = true;
  209593. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209594. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  209595. props[prop].propValueSize = sizeof (trueBool);
  209596. props[prop].propValueAddress = &trueBool;
  209597. ++prop;
  209598. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209599. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  209600. props[prop].propValueSize = sizeof (trueBool);
  209601. props[prop].propValueAddress = &trueBool;
  209602. ++prop;
  209603. Boolean isActive = true;
  209604. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  209605. props[prop].propID = kQTNewMoviePropertyID_Active;
  209606. props[prop].propValueSize = sizeof (isActive);
  209607. props[prop].propValueAddress = &isActive;
  209608. ++prop;
  209609. MacSetPort (0);
  209610. jassert (prop <= 5);
  209611. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  209612. return err == noErr;
  209613. }
  209614. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  209615. {
  209616. if (input == 0)
  209617. return false;
  209618. dataHandle = 0;
  209619. bool ok = false;
  209620. QTNewMoviePropertyElement props[5];
  209621. zeromem (props, sizeof (props));
  209622. int prop = 0;
  209623. DataReferenceRecord dr;
  209624. props[prop].propClass = kQTPropertyClass_DataLocation;
  209625. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  209626. props[prop].propValueSize = sizeof (dr);
  209627. props[prop].propValueAddress = &dr;
  209628. ++prop;
  209629. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  209630. if (fin != 0)
  209631. {
  209632. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  209633. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  209634. &dr.dataRef, &dr.dataRefType);
  209635. ok = openMovie (props, prop, movie);
  209636. DisposeHandle (dr.dataRef);
  209637. CFRelease (filePath);
  209638. }
  209639. else
  209640. {
  209641. // sanity-check because this currently needs to load the whole stream into memory..
  209642. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  209643. dataHandle = NewHandle ((Size) input->getTotalLength());
  209644. HLock (dataHandle);
  209645. // read the entire stream into memory - this is a pain, but can't get it to work
  209646. // properly using a custom callback to supply the data.
  209647. input->read (*dataHandle, (int) input->getTotalLength());
  209648. HUnlock (dataHandle);
  209649. // different types to get QT to try. (We should really be a bit smarter here by
  209650. // working out in advance which one the stream contains, rather than just trying
  209651. // each one)
  209652. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  209653. "\04.avi", "\04.m4a" };
  209654. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  209655. {
  209656. /* // this fails for some bizarre reason - it can be bodged to work with
  209657. // movies, but can't seem to do it for other file types..
  209658. QTNewMovieUserProcRecord procInfo;
  209659. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  209660. procInfo.getMovieUserProcRefcon = this;
  209661. procInfo.defaultDataRef.dataRef = dataRef;
  209662. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  209663. props[prop].propClass = kQTPropertyClass_DataLocation;
  209664. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  209665. props[prop].propValueSize = sizeof (procInfo);
  209666. props[prop].propValueAddress = (void*) &procInfo;
  209667. ++prop; */
  209668. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  209669. dr.dataRefType = HandleDataHandlerSubType;
  209670. ok = openMovie (props, prop, movie);
  209671. DisposeHandle (dr.dataRef);
  209672. }
  209673. }
  209674. return ok;
  209675. }
  209676. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  209677. const bool isControllerVisible)
  209678. {
  209679. const bool ok = loadMovie (static_cast <InputStream*> (movieFile_.createInputStream()), isControllerVisible);
  209680. movieFile = movieFile_;
  209681. return ok;
  209682. }
  209683. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  209684. const bool isControllerVisible)
  209685. {
  209686. return loadMovie (static_cast <InputStream*> (movieURL.createInputStream (false)), isControllerVisible);
  209687. }
  209688. void QuickTimeMovieComponent::goToStart()
  209689. {
  209690. setPosition (0.0);
  209691. }
  209692. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  209693. const RectanglePlacement& placement)
  209694. {
  209695. int normalWidth, normalHeight;
  209696. getMovieNormalSize (normalWidth, normalHeight);
  209697. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  209698. {
  209699. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  209700. placement.applyTo (x, y, w, h,
  209701. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  209702. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  209703. if (w > 0 && h > 0)
  209704. {
  209705. setBounds (roundToInt (x), roundToInt (y),
  209706. roundToInt (w), roundToInt (h));
  209707. }
  209708. }
  209709. else
  209710. {
  209711. setBounds (spaceToFitWithin);
  209712. }
  209713. }
  209714. #endif
  209715. /*** End of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209716. /*** Start of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  209717. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209718. // compiled on its own).
  209719. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  209720. class WebBrowserComponentInternal : public ActiveXControlComponent
  209721. {
  209722. public:
  209723. WebBrowserComponentInternal()
  209724. : browser (0),
  209725. connectionPoint (0),
  209726. adviseCookie (0)
  209727. {
  209728. }
  209729. ~WebBrowserComponentInternal()
  209730. {
  209731. if (connectionPoint != 0)
  209732. connectionPoint->Unadvise (adviseCookie);
  209733. if (browser != 0)
  209734. browser->Release();
  209735. }
  209736. void createBrowser()
  209737. {
  209738. createControl (&CLSID_WebBrowser);
  209739. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  209740. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  209741. if (connectionPointContainer != 0)
  209742. {
  209743. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  209744. &connectionPoint);
  209745. if (connectionPoint != 0)
  209746. {
  209747. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  209748. jassert (owner != 0);
  209749. EventHandler* handler = new EventHandler (owner);
  209750. connectionPoint->Advise (handler, &adviseCookie);
  209751. handler->Release();
  209752. }
  209753. }
  209754. }
  209755. void goToURL (const String& url,
  209756. const StringArray* headers,
  209757. const MemoryBlock* postData)
  209758. {
  209759. if (browser != 0)
  209760. {
  209761. LPSAFEARRAY sa = 0;
  209762. VARIANT flags, frame, postDataVar, headersVar; // (_variant_t isn't available in all compilers)
  209763. VariantInit (&flags);
  209764. VariantInit (&frame);
  209765. VariantInit (&postDataVar);
  209766. VariantInit (&headersVar);
  209767. if (headers != 0)
  209768. {
  209769. V_VT (&headersVar) = VT_BSTR;
  209770. V_BSTR (&headersVar) = SysAllocString ((const OLECHAR*) headers->joinIntoString ("\r\n"));
  209771. }
  209772. if (postData != 0 && postData->getSize() > 0)
  209773. {
  209774. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  209775. if (sa != 0)
  209776. {
  209777. void* data = 0;
  209778. SafeArrayAccessData (sa, &data);
  209779. jassert (data != 0);
  209780. if (data != 0)
  209781. {
  209782. postData->copyTo (data, 0, postData->getSize());
  209783. SafeArrayUnaccessData (sa);
  209784. VARIANT postDataVar2;
  209785. VariantInit (&postDataVar2);
  209786. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  209787. V_ARRAY (&postDataVar2) = sa;
  209788. postDataVar = postDataVar2;
  209789. }
  209790. }
  209791. }
  209792. browser->Navigate ((BSTR) (const OLECHAR*) url,
  209793. &flags, &frame,
  209794. &postDataVar, &headersVar);
  209795. if (sa != 0)
  209796. SafeArrayDestroy (sa);
  209797. VariantClear (&flags);
  209798. VariantClear (&frame);
  209799. VariantClear (&postDataVar);
  209800. VariantClear (&headersVar);
  209801. }
  209802. }
  209803. IWebBrowser2* browser;
  209804. juce_UseDebuggingNewOperator
  209805. private:
  209806. IConnectionPoint* connectionPoint;
  209807. DWORD adviseCookie;
  209808. class EventHandler : public ComBaseClassHelper <IDispatch>,
  209809. public ComponentMovementWatcher
  209810. {
  209811. public:
  209812. EventHandler (WebBrowserComponent* owner_)
  209813. : ComponentMovementWatcher (owner_),
  209814. owner (owner_)
  209815. {
  209816. }
  209817. ~EventHandler()
  209818. {
  209819. }
  209820. HRESULT __stdcall GetTypeInfoCount (UINT __RPC_FAR*) { return E_NOTIMPL; }
  209821. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo __RPC_FAR *__RPC_FAR*) { return E_NOTIMPL; }
  209822. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR __RPC_FAR*, UINT, LCID, DISPID __RPC_FAR*) { return E_NOTIMPL; }
  209823. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/,
  209824. WORD /*wFlags*/, DISPPARAMS __RPC_FAR* pDispParams,
  209825. VARIANT __RPC_FAR* /*pVarResult*/, EXCEPINFO __RPC_FAR* /*pExcepInfo*/,
  209826. UINT __RPC_FAR* /*puArgErr*/)
  209827. {
  209828. switch (dispIdMember)
  209829. {
  209830. case DISPID_BEFORENAVIGATE2:
  209831. {
  209832. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  209833. String url;
  209834. if ((vurl->vt & VT_BYREF) != 0)
  209835. url = *vurl->pbstrVal;
  209836. else
  209837. url = vurl->bstrVal;
  209838. *pDispParams->rgvarg->pboolVal
  209839. = owner->pageAboutToLoad (url) ? VARIANT_FALSE
  209840. : VARIANT_TRUE;
  209841. return S_OK;
  209842. }
  209843. default:
  209844. break;
  209845. }
  209846. return E_NOTIMPL;
  209847. }
  209848. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/) {}
  209849. void componentPeerChanged() {}
  209850. void componentVisibilityChanged (Component&)
  209851. {
  209852. owner->visibilityChanged();
  209853. }
  209854. juce_UseDebuggingNewOperator
  209855. private:
  209856. WebBrowserComponent* const owner;
  209857. EventHandler (const EventHandler&);
  209858. EventHandler& operator= (const EventHandler&);
  209859. };
  209860. };
  209861. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  209862. : browser (0),
  209863. blankPageShown (false),
  209864. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  209865. {
  209866. setOpaque (true);
  209867. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  209868. }
  209869. WebBrowserComponent::~WebBrowserComponent()
  209870. {
  209871. delete browser;
  209872. }
  209873. void WebBrowserComponent::goToURL (const String& url,
  209874. const StringArray* headers,
  209875. const MemoryBlock* postData)
  209876. {
  209877. lastURL = url;
  209878. lastHeaders.clear();
  209879. if (headers != 0)
  209880. lastHeaders = *headers;
  209881. lastPostData.setSize (0);
  209882. if (postData != 0)
  209883. lastPostData = *postData;
  209884. blankPageShown = false;
  209885. browser->goToURL (url, headers, postData);
  209886. }
  209887. void WebBrowserComponent::stop()
  209888. {
  209889. if (browser->browser != 0)
  209890. browser->browser->Stop();
  209891. }
  209892. void WebBrowserComponent::goBack()
  209893. {
  209894. lastURL = String::empty;
  209895. blankPageShown = false;
  209896. if (browser->browser != 0)
  209897. browser->browser->GoBack();
  209898. }
  209899. void WebBrowserComponent::goForward()
  209900. {
  209901. lastURL = String::empty;
  209902. if (browser->browser != 0)
  209903. browser->browser->GoForward();
  209904. }
  209905. void WebBrowserComponent::refresh()
  209906. {
  209907. if (browser->browser != 0)
  209908. browser->browser->Refresh();
  209909. }
  209910. void WebBrowserComponent::paint (Graphics& g)
  209911. {
  209912. if (browser->browser == 0)
  209913. g.fillAll (Colours::white);
  209914. }
  209915. void WebBrowserComponent::checkWindowAssociation()
  209916. {
  209917. if (isShowing())
  209918. {
  209919. if (browser->browser == 0 && getPeer() != 0)
  209920. {
  209921. browser->createBrowser();
  209922. reloadLastURL();
  209923. }
  209924. else
  209925. {
  209926. if (blankPageShown)
  209927. goBack();
  209928. }
  209929. }
  209930. else
  209931. {
  209932. if (browser != 0 && unloadPageWhenBrowserIsHidden && ! blankPageShown)
  209933. {
  209934. // when the component becomes invisible, some stuff like flash
  209935. // carries on playing audio, so we need to force it onto a blank
  209936. // page to avoid this..
  209937. blankPageShown = true;
  209938. browser->goToURL ("about:blank", 0, 0);
  209939. }
  209940. }
  209941. }
  209942. void WebBrowserComponent::reloadLastURL()
  209943. {
  209944. if (lastURL.isNotEmpty())
  209945. {
  209946. goToURL (lastURL, &lastHeaders, &lastPostData);
  209947. lastURL = String::empty;
  209948. }
  209949. }
  209950. void WebBrowserComponent::parentHierarchyChanged()
  209951. {
  209952. checkWindowAssociation();
  209953. }
  209954. void WebBrowserComponent::resized()
  209955. {
  209956. browser->setSize (getWidth(), getHeight());
  209957. }
  209958. void WebBrowserComponent::visibilityChanged()
  209959. {
  209960. checkWindowAssociation();
  209961. }
  209962. bool WebBrowserComponent::pageAboutToLoad (const String&)
  209963. {
  209964. return true;
  209965. }
  209966. #endif
  209967. /*** End of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  209968. /*** Start of inlined file: juce_win32_OpenGLComponent.cpp ***/
  209969. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209970. // compiled on its own).
  209971. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  209972. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  209973. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  209974. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  209975. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  209976. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  209977. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  209978. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  209979. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  209980. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  209981. #define WGL_ACCELERATION_ARB 0x2003
  209982. #define WGL_SWAP_METHOD_ARB 0x2007
  209983. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  209984. #define WGL_PIXEL_TYPE_ARB 0x2013
  209985. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  209986. #define WGL_COLOR_BITS_ARB 0x2014
  209987. #define WGL_RED_BITS_ARB 0x2015
  209988. #define WGL_GREEN_BITS_ARB 0x2017
  209989. #define WGL_BLUE_BITS_ARB 0x2019
  209990. #define WGL_ALPHA_BITS_ARB 0x201B
  209991. #define WGL_DEPTH_BITS_ARB 0x2022
  209992. #define WGL_STENCIL_BITS_ARB 0x2023
  209993. #define WGL_FULL_ACCELERATION_ARB 0x2027
  209994. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  209995. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  209996. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  209997. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  209998. #define WGL_STEREO_ARB 0x2012
  209999. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  210000. #define WGL_SAMPLES_ARB 0x2042
  210001. #define WGL_TYPE_RGBA_ARB 0x202B
  210002. static void getWglExtensions (HDC dc, StringArray& result) throw()
  210003. {
  210004. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  210005. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  210006. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  210007. else
  210008. jassertfalse; // If this fails, it may be because you didn't activate the openGL context
  210009. }
  210010. class WindowedGLContext : public OpenGLContext
  210011. {
  210012. public:
  210013. WindowedGLContext (Component* const component_,
  210014. HGLRC contextToShareWith,
  210015. const OpenGLPixelFormat& pixelFormat)
  210016. : renderContext (0),
  210017. dc (0),
  210018. component (component_)
  210019. {
  210020. jassert (component != 0);
  210021. createNativeWindow();
  210022. // Use a default pixel format that should be supported everywhere
  210023. PIXELFORMATDESCRIPTOR pfd;
  210024. zerostruct (pfd);
  210025. pfd.nSize = sizeof (pfd);
  210026. pfd.nVersion = 1;
  210027. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  210028. pfd.iPixelType = PFD_TYPE_RGBA;
  210029. pfd.cColorBits = 24;
  210030. pfd.cDepthBits = 16;
  210031. const int format = ChoosePixelFormat (dc, &pfd);
  210032. if (format != 0)
  210033. SetPixelFormat (dc, format, &pfd);
  210034. renderContext = wglCreateContext (dc);
  210035. makeActive();
  210036. setPixelFormat (pixelFormat);
  210037. if (contextToShareWith != 0 && renderContext != 0)
  210038. wglShareLists (contextToShareWith, renderContext);
  210039. }
  210040. ~WindowedGLContext()
  210041. {
  210042. deleteContext();
  210043. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  210044. nativeWindow = 0;
  210045. }
  210046. void deleteContext()
  210047. {
  210048. makeInactive();
  210049. if (renderContext != 0)
  210050. {
  210051. wglDeleteContext (renderContext);
  210052. renderContext = 0;
  210053. }
  210054. }
  210055. bool makeActive() const throw()
  210056. {
  210057. jassert (renderContext != 0);
  210058. return wglMakeCurrent (dc, renderContext) != 0;
  210059. }
  210060. bool makeInactive() const throw()
  210061. {
  210062. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  210063. }
  210064. bool isActive() const throw()
  210065. {
  210066. return wglGetCurrentContext() == renderContext;
  210067. }
  210068. const OpenGLPixelFormat getPixelFormat() const
  210069. {
  210070. OpenGLPixelFormat pf;
  210071. makeActive();
  210072. StringArray availableExtensions;
  210073. getWglExtensions (dc, availableExtensions);
  210074. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  210075. return pf;
  210076. }
  210077. void* getRawContext() const throw()
  210078. {
  210079. return renderContext;
  210080. }
  210081. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  210082. {
  210083. makeActive();
  210084. PIXELFORMATDESCRIPTOR pfd;
  210085. zerostruct (pfd);
  210086. pfd.nSize = sizeof (pfd);
  210087. pfd.nVersion = 1;
  210088. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  210089. pfd.iPixelType = PFD_TYPE_RGBA;
  210090. pfd.iLayerType = PFD_MAIN_PLANE;
  210091. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  210092. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  210093. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  210094. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  210095. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  210096. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  210097. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  210098. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  210099. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  210100. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  210101. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  210102. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  210103. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  210104. int format = 0;
  210105. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  210106. StringArray availableExtensions;
  210107. getWglExtensions (dc, availableExtensions);
  210108. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  210109. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  210110. {
  210111. int attributes[64];
  210112. int n = 0;
  210113. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  210114. attributes[n++] = GL_TRUE;
  210115. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  210116. attributes[n++] = GL_TRUE;
  210117. attributes[n++] = WGL_ACCELERATION_ARB;
  210118. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  210119. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  210120. attributes[n++] = GL_TRUE;
  210121. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  210122. attributes[n++] = WGL_TYPE_RGBA_ARB;
  210123. attributes[n++] = WGL_COLOR_BITS_ARB;
  210124. attributes[n++] = pfd.cColorBits;
  210125. attributes[n++] = WGL_RED_BITS_ARB;
  210126. attributes[n++] = pixelFormat.redBits;
  210127. attributes[n++] = WGL_GREEN_BITS_ARB;
  210128. attributes[n++] = pixelFormat.greenBits;
  210129. attributes[n++] = WGL_BLUE_BITS_ARB;
  210130. attributes[n++] = pixelFormat.blueBits;
  210131. attributes[n++] = WGL_ALPHA_BITS_ARB;
  210132. attributes[n++] = pixelFormat.alphaBits;
  210133. attributes[n++] = WGL_DEPTH_BITS_ARB;
  210134. attributes[n++] = pixelFormat.depthBufferBits;
  210135. if (pixelFormat.stencilBufferBits > 0)
  210136. {
  210137. attributes[n++] = WGL_STENCIL_BITS_ARB;
  210138. attributes[n++] = pixelFormat.stencilBufferBits;
  210139. }
  210140. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  210141. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  210142. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  210143. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  210144. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  210145. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  210146. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210147. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  210148. if (availableExtensions.contains ("WGL_ARB_multisample")
  210149. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  210150. {
  210151. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  210152. attributes[n++] = 1;
  210153. attributes[n++] = WGL_SAMPLES_ARB;
  210154. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  210155. }
  210156. attributes[n++] = 0;
  210157. UINT formatsCount;
  210158. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  210159. (void) ok;
  210160. jassert (ok);
  210161. }
  210162. else
  210163. {
  210164. format = ChoosePixelFormat (dc, &pfd);
  210165. }
  210166. if (format != 0)
  210167. {
  210168. makeInactive();
  210169. // win32 can't change the pixel format of a window, so need to delete the
  210170. // old one and create a new one..
  210171. jassert (nativeWindow != 0);
  210172. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  210173. nativeWindow = 0;
  210174. createNativeWindow();
  210175. if (SetPixelFormat (dc, format, &pfd))
  210176. {
  210177. wglDeleteContext (renderContext);
  210178. renderContext = wglCreateContext (dc);
  210179. jassert (renderContext != 0);
  210180. return renderContext != 0;
  210181. }
  210182. }
  210183. return false;
  210184. }
  210185. void updateWindowPosition (int x, int y, int w, int h, int)
  210186. {
  210187. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  210188. x, y, w, h,
  210189. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  210190. }
  210191. void repaint()
  210192. {
  210193. nativeWindow->repaint (nativeWindow->getBounds().withPosition (Point<int>()));
  210194. }
  210195. void swapBuffers()
  210196. {
  210197. SwapBuffers (dc);
  210198. }
  210199. bool setSwapInterval (int numFramesPerSwap)
  210200. {
  210201. makeActive();
  210202. StringArray availableExtensions;
  210203. getWglExtensions (dc, availableExtensions);
  210204. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  210205. return availableExtensions.contains ("WGL_EXT_swap_control")
  210206. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  210207. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  210208. }
  210209. int getSwapInterval() const
  210210. {
  210211. makeActive();
  210212. StringArray availableExtensions;
  210213. getWglExtensions (dc, availableExtensions);
  210214. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  210215. if (availableExtensions.contains ("WGL_EXT_swap_control")
  210216. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  210217. return wglGetSwapIntervalEXT();
  210218. return 0;
  210219. }
  210220. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  210221. {
  210222. jassert (isActive());
  210223. StringArray availableExtensions;
  210224. getWglExtensions (dc, availableExtensions);
  210225. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210226. int numTypes = 0;
  210227. if (availableExtensions.contains("WGL_ARB_pixel_format")
  210228. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210229. {
  210230. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  210231. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  210232. jassertfalse;
  210233. }
  210234. else
  210235. {
  210236. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  210237. }
  210238. OpenGLPixelFormat pf;
  210239. for (int i = 0; i < numTypes; ++i)
  210240. {
  210241. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  210242. {
  210243. bool alreadyListed = false;
  210244. for (int j = results.size(); --j >= 0;)
  210245. if (pf == *results.getUnchecked(j))
  210246. alreadyListed = true;
  210247. if (! alreadyListed)
  210248. results.add (new OpenGLPixelFormat (pf));
  210249. }
  210250. }
  210251. }
  210252. void* getNativeWindowHandle() const
  210253. {
  210254. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  210255. }
  210256. juce_UseDebuggingNewOperator
  210257. HGLRC renderContext;
  210258. private:
  210259. ScopedPointer<Win32ComponentPeer> nativeWindow;
  210260. Component* const component;
  210261. HDC dc;
  210262. void createNativeWindow()
  210263. {
  210264. Win32ComponentPeer* topLevelPeer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  210265. nativeWindow = new Win32ComponentPeer (component, ComponentPeer::windowIgnoresMouseClicks,
  210266. topLevelPeer == 0 ? 0 : (HWND) topLevelPeer->getNativeHandle());
  210267. nativeWindow->dontRepaint = true;
  210268. nativeWindow->setVisible (true);
  210269. dc = GetDC ((HWND) nativeWindow->getNativeHandle());
  210270. }
  210271. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  210272. OpenGLPixelFormat& result,
  210273. const StringArray& availableExtensions) const throw()
  210274. {
  210275. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210276. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  210277. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210278. {
  210279. int attributes[32];
  210280. int numAttributes = 0;
  210281. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  210282. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  210283. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  210284. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  210285. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  210286. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  210287. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  210288. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  210289. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  210290. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  210291. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  210292. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  210293. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  210294. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  210295. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210296. if (availableExtensions.contains ("WGL_ARB_multisample"))
  210297. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  210298. int values[32];
  210299. zeromem (values, sizeof (values));
  210300. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  210301. {
  210302. int n = 0;
  210303. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  210304. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  210305. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  210306. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  210307. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  210308. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  210309. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  210310. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  210311. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  210312. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  210313. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  210314. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  210315. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  210316. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  210317. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  210318. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  210319. return isValidFormat;
  210320. }
  210321. else
  210322. {
  210323. jassertfalse;
  210324. }
  210325. }
  210326. else
  210327. {
  210328. PIXELFORMATDESCRIPTOR pfd;
  210329. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  210330. {
  210331. result.redBits = pfd.cRedBits;
  210332. result.greenBits = pfd.cGreenBits;
  210333. result.blueBits = pfd.cBlueBits;
  210334. result.alphaBits = pfd.cAlphaBits;
  210335. result.depthBufferBits = pfd.cDepthBits;
  210336. result.stencilBufferBits = pfd.cStencilBits;
  210337. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  210338. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  210339. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  210340. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  210341. result.fullSceneAntiAliasingNumSamples = 0;
  210342. return true;
  210343. }
  210344. else
  210345. {
  210346. jassertfalse;
  210347. }
  210348. }
  210349. return false;
  210350. }
  210351. WindowedGLContext (const WindowedGLContext&);
  210352. WindowedGLContext& operator= (const WindowedGLContext&);
  210353. };
  210354. OpenGLContext* OpenGLComponent::createContext()
  210355. {
  210356. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this,
  210357. contextToShareListsWith != 0 ? (HGLRC) contextToShareListsWith->getRawContext() : 0,
  210358. preferredPixelFormat));
  210359. return (c->renderContext != 0) ? c.release() : 0;
  210360. }
  210361. void* OpenGLComponent::getNativeWindowHandle() const
  210362. {
  210363. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle() : 0;
  210364. }
  210365. void juce_glViewport (const int w, const int h)
  210366. {
  210367. glViewport (0, 0, w, h);
  210368. }
  210369. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  210370. OwnedArray <OpenGLPixelFormat>& results)
  210371. {
  210372. Component tempComp;
  210373. {
  210374. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  210375. wc.makeActive();
  210376. wc.findAlternativeOpenGLPixelFormats (results);
  210377. }
  210378. }
  210379. #endif
  210380. /*** End of inlined file: juce_win32_OpenGLComponent.cpp ***/
  210381. /*** Start of inlined file: juce_win32_AudioCDReader.cpp ***/
  210382. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210383. // compiled on its own).
  210384. #if JUCE_INCLUDED_FILE
  210385. #if JUCE_USE_CDREADER
  210386. namespace CDReaderHelpers
  210387. {
  210388. //***************************************************************************
  210389. // %%% TARGET STATUS VALUES %%%
  210390. //***************************************************************************
  210391. #define STATUS_GOOD 0x00 // Status Good
  210392. #define STATUS_CHKCOND 0x02 // Check Condition
  210393. #define STATUS_CONDMET 0x04 // Condition Met
  210394. #define STATUS_BUSY 0x08 // Busy
  210395. #define STATUS_INTERM 0x10 // Intermediate
  210396. #define STATUS_INTCDMET 0x14 // Intermediate-condition met
  210397. #define STATUS_RESCONF 0x18 // Reservation conflict
  210398. #define STATUS_COMTERM 0x22 // Command Terminated
  210399. #define STATUS_QFULL 0x28 // Queue full
  210400. //***************************************************************************
  210401. // %%% SCSI MISCELLANEOUS EQUATES %%%
  210402. //***************************************************************************
  210403. #define MAXLUN 7 // Maximum Logical Unit Id
  210404. #define MAXTARG 7 // Maximum Target Id
  210405. #define MAX_SCSI_LUNS 64 // Maximum Number of SCSI LUNs
  210406. #define MAX_NUM_HA 8 // Maximum Number of SCSI HA's
  210407. //***************************************************************************
  210408. // %%% Commands for all Device Types %%%
  210409. //***************************************************************************
  210410. #define SCSI_CHANGE_DEF 0x40 // Change Definition (Optional)
  210411. #define SCSI_COMPARE 0x39 // Compare (O)
  210412. #define SCSI_COPY 0x18 // Copy (O)
  210413. #define SCSI_COP_VERIFY 0x3A // Copy and Verify (O)
  210414. #define SCSI_INQUIRY 0x12 // Inquiry (MANDATORY)
  210415. #define SCSI_LOG_SELECT 0x4C // Log Select (O)
  210416. #define SCSI_LOG_SENSE 0x4D // Log Sense (O)
  210417. #define SCSI_MODE_SEL6 0x15 // Mode Select 6-byte (Device Specific)
  210418. #define SCSI_MODE_SEL10 0x55 // Mode Select 10-byte (Device Specific)
  210419. #define SCSI_MODE_SEN6 0x1A // Mode Sense 6-byte (Device Specific)
  210420. #define SCSI_MODE_SEN10 0x5A // Mode Sense 10-byte (Device Specific)
  210421. #define SCSI_READ_BUFF 0x3C // Read Buffer (O)
  210422. #define SCSI_REQ_SENSE 0x03 // Request Sense (MANDATORY)
  210423. #define SCSI_SEND_DIAG 0x1D // Send Diagnostic (O)
  210424. #define SCSI_TST_U_RDY 0x00 // Test Unit Ready (MANDATORY)
  210425. #define SCSI_WRITE_BUFF 0x3B // Write Buffer (O)
  210426. //***************************************************************************
  210427. // %%% Commands Unique to Direct Access Devices %%%
  210428. //***************************************************************************
  210429. #define SCSI_COMPARE 0x39 // Compare (O)
  210430. #define SCSI_FORMAT 0x04 // Format Unit (MANDATORY)
  210431. #define SCSI_LCK_UN_CAC 0x36 // Lock Unlock Cache (O)
  210432. #define SCSI_PREFETCH 0x34 // Prefetch (O)
  210433. #define SCSI_MED_REMOVL 0x1E // Prevent/Allow medium Removal (O)
  210434. #define SCSI_READ6 0x08 // Read 6-byte (MANDATORY)
  210435. #define SCSI_READ10 0x28 // Read 10-byte (MANDATORY)
  210436. #define SCSI_RD_CAPAC 0x25 // Read Capacity (MANDATORY)
  210437. #define SCSI_RD_DEFECT 0x37 // Read Defect Data (O)
  210438. #define SCSI_READ_LONG 0x3E // Read Long (O)
  210439. #define SCSI_REASS_BLK 0x07 // Reassign Blocks (O)
  210440. #define SCSI_RCV_DIAG 0x1C // Receive Diagnostic Results (O)
  210441. #define SCSI_RELEASE 0x17 // Release Unit (MANDATORY)
  210442. #define SCSI_REZERO 0x01 // Rezero Unit (O)
  210443. #define SCSI_SRCH_DAT_E 0x31 // Search Data Equal (O)
  210444. #define SCSI_SRCH_DAT_H 0x30 // Search Data High (O)
  210445. #define SCSI_SRCH_DAT_L 0x32 // Search Data Low (O)
  210446. #define SCSI_SEEK6 0x0B // Seek 6-Byte (O)
  210447. #define SCSI_SEEK10 0x2B // Seek 10-Byte (O)
  210448. #define SCSI_SEND_DIAG 0x1D // Send Diagnostics (MANDATORY)
  210449. #define SCSI_SET_LIMIT 0x33 // Set Limits (O)
  210450. #define SCSI_START_STP 0x1B // Start/Stop Unit (O)
  210451. #define SCSI_SYNC_CACHE 0x35 // Synchronize Cache (O)
  210452. #define SCSI_VERIFY 0x2F // Verify (O)
  210453. #define SCSI_WRITE6 0x0A // Write 6-Byte (MANDATORY)
  210454. #define SCSI_WRITE10 0x2A // Write 10-Byte (MANDATORY)
  210455. #define SCSI_WRT_VERIFY 0x2E // Write and Verify (O)
  210456. #define SCSI_WRITE_LONG 0x3F // Write Long (O)
  210457. #define SCSI_WRITE_SAME 0x41 // Write Same (O)
  210458. //***************************************************************************
  210459. // %%% Commands Unique to Sequential Access Devices %%%
  210460. //***************************************************************************
  210461. #define SCSI_ERASE 0x19 // Erase (MANDATORY)
  210462. #define SCSI_LOAD_UN 0x1b // Load/Unload (O)
  210463. #define SCSI_LOCATE 0x2B // Locate (O)
  210464. #define SCSI_RD_BLK_LIM 0x05 // Read Block Limits (MANDATORY)
  210465. #define SCSI_READ_POS 0x34 // Read Position (O)
  210466. #define SCSI_READ_REV 0x0F // Read Reverse (O)
  210467. #define SCSI_REC_BF_DAT 0x14 // Recover Buffer Data (O)
  210468. #define SCSI_RESERVE 0x16 // Reserve Unit (MANDATORY)
  210469. #define SCSI_REWIND 0x01 // Rewind (MANDATORY)
  210470. #define SCSI_SPACE 0x11 // Space (MANDATORY)
  210471. #define SCSI_VERIFY_T 0x13 // Verify (Tape) (O)
  210472. #define SCSI_WRT_FILE 0x10 // Write Filemarks (MANDATORY)
  210473. //***************************************************************************
  210474. // %%% Commands Unique to Printer Devices %%%
  210475. //***************************************************************************
  210476. #define SCSI_PRINT 0x0A // Print (MANDATORY)
  210477. #define SCSI_SLEW_PNT 0x0B // Slew and Print (O)
  210478. #define SCSI_STOP_PNT 0x1B // Stop Print (O)
  210479. #define SCSI_SYNC_BUFF 0x10 // Synchronize Buffer (O)
  210480. //***************************************************************************
  210481. // %%% Commands Unique to Processor Devices %%%
  210482. //***************************************************************************
  210483. #define SCSI_RECEIVE 0x08 // Receive (O)
  210484. #define SCSI_SEND 0x0A // Send (O)
  210485. //***************************************************************************
  210486. // %%% Commands Unique to Write-Once Devices %%%
  210487. //***************************************************************************
  210488. #define SCSI_MEDIUM_SCN 0x38 // Medium Scan (O)
  210489. #define SCSI_SRCHDATE10 0x31 // Search Data Equal 10-Byte (O)
  210490. #define SCSI_SRCHDATE12 0xB1 // Search Data Equal 12-Byte (O)
  210491. #define SCSI_SRCHDATH10 0x30 // Search Data High 10-Byte (O)
  210492. #define SCSI_SRCHDATH12 0xB0 // Search Data High 12-Byte (O)
  210493. #define SCSI_SRCHDATL10 0x32 // Search Data Low 10-Byte (O)
  210494. #define SCSI_SRCHDATL12 0xB2 // Search Data Low 12-Byte (O)
  210495. #define SCSI_SET_LIM_10 0x33 // Set Limits 10-Byte (O)
  210496. #define SCSI_SET_LIM_12 0xB3 // Set Limits 10-Byte (O)
  210497. #define SCSI_VERIFY10 0x2F // Verify 10-Byte (O)
  210498. #define SCSI_VERIFY12 0xAF // Verify 12-Byte (O)
  210499. #define SCSI_WRITE12 0xAA // Write 12-Byte (O)
  210500. #define SCSI_WRT_VER10 0x2E // Write and Verify 10-Byte (O)
  210501. #define SCSI_WRT_VER12 0xAE // Write and Verify 12-Byte (O)
  210502. //***************************************************************************
  210503. // %%% Commands Unique to CD-ROM Devices %%%
  210504. //***************************************************************************
  210505. #define SCSI_PLAYAUD_10 0x45 // Play Audio 10-Byte (O)
  210506. #define SCSI_PLAYAUD_12 0xA5 // Play Audio 12-Byte 12-Byte (O)
  210507. #define SCSI_PLAYAUDMSF 0x47 // Play Audio MSF (O)
  210508. #define SCSI_PLAYA_TKIN 0x48 // Play Audio Track/Index (O)
  210509. #define SCSI_PLYTKREL10 0x49 // Play Track Relative 10-Byte (O)
  210510. #define SCSI_PLYTKREL12 0xA9 // Play Track Relative 12-Byte (O)
  210511. #define SCSI_READCDCAP 0x25 // Read CD-ROM Capacity (MANDATORY)
  210512. #define SCSI_READHEADER 0x44 // Read Header (O)
  210513. #define SCSI_SUBCHANNEL 0x42 // Read Subchannel (O)
  210514. #define SCSI_READ_TOC 0x43 // Read TOC (O)
  210515. //***************************************************************************
  210516. // %%% Commands Unique to Scanner Devices %%%
  210517. //***************************************************************************
  210518. #define SCSI_GETDBSTAT 0x34 // Get Data Buffer Status (O)
  210519. #define SCSI_GETWINDOW 0x25 // Get Window (O)
  210520. #define SCSI_OBJECTPOS 0x31 // Object Postion (O)
  210521. #define SCSI_SCAN 0x1B // Scan (O)
  210522. #define SCSI_SETWINDOW 0x24 // Set Window (MANDATORY)
  210523. //***************************************************************************
  210524. // %%% Commands Unique to Optical Memory Devices %%%
  210525. //***************************************************************************
  210526. #define SCSI_UpdateBlk 0x3D // Update Block (O)
  210527. //***************************************************************************
  210528. // %%% Commands Unique to Medium Changer Devices %%%
  210529. //***************************************************************************
  210530. #define SCSI_EXCHMEDIUM 0xA6 // Exchange Medium (O)
  210531. #define SCSI_INITELSTAT 0x07 // Initialize Element Status (O)
  210532. #define SCSI_POSTOELEM 0x2B // Position to Element (O)
  210533. #define SCSI_REQ_VE_ADD 0xB5 // Request Volume Element Address (O)
  210534. #define SCSI_SENDVOLTAG 0xB6 // Send Volume Tag (O)
  210535. //***************************************************************************
  210536. // %%% Commands Unique to Communication Devices %%%
  210537. //***************************************************************************
  210538. #define SCSI_GET_MSG_6 0x08 // Get Message 6-Byte (MANDATORY)
  210539. #define SCSI_GET_MSG_10 0x28 // Get Message 10-Byte (O)
  210540. #define SCSI_GET_MSG_12 0xA8 // Get Message 12-Byte (O)
  210541. #define SCSI_SND_MSG_6 0x0A // Send Message 6-Byte (MANDATORY)
  210542. #define SCSI_SND_MSG_10 0x2A // Send Message 10-Byte (O)
  210543. #define SCSI_SND_MSG_12 0xAA // Send Message 12-Byte (O)
  210544. //***************************************************************************
  210545. // %%% Request Sense Data Format %%%
  210546. //***************************************************************************
  210547. typedef struct {
  210548. BYTE ErrorCode; // Error Code (70H or 71H)
  210549. BYTE SegmentNum; // Number of current segment descriptor
  210550. BYTE SenseKey; // Sense Key(See bit definitions too)
  210551. BYTE InfoByte0; // Information MSB
  210552. BYTE InfoByte1; // Information MID
  210553. BYTE InfoByte2; // Information MID
  210554. BYTE InfoByte3; // Information LSB
  210555. BYTE AddSenLen; // Additional Sense Length
  210556. BYTE ComSpecInf0; // Command Specific Information MSB
  210557. BYTE ComSpecInf1; // Command Specific Information MID
  210558. BYTE ComSpecInf2; // Command Specific Information MID
  210559. BYTE ComSpecInf3; // Command Specific Information LSB
  210560. BYTE AddSenseCode; // Additional Sense Code
  210561. BYTE AddSenQual; // Additional Sense Code Qualifier
  210562. BYTE FieldRepUCode; // Field Replaceable Unit Code
  210563. BYTE SenKeySpec15; // Sense Key Specific 15th byte
  210564. BYTE SenKeySpec16; // Sense Key Specific 16th byte
  210565. BYTE SenKeySpec17; // Sense Key Specific 17th byte
  210566. BYTE AddSenseBytes; // Additional Sense Bytes
  210567. } SENSE_DATA_FMT;
  210568. //***************************************************************************
  210569. // %%% REQUEST SENSE ERROR CODE %%%
  210570. //***************************************************************************
  210571. #define SERROR_CURRENT 0x70 // Current Errors
  210572. #define SERROR_DEFERED 0x71 // Deferred Errors
  210573. //***************************************************************************
  210574. // %%% REQUEST SENSE BIT DEFINITIONS %%%
  210575. //***************************************************************************
  210576. #define SENSE_VALID 0x80 // Byte 0 Bit 7
  210577. #define SENSE_FILEMRK 0x80 // Byte 2 Bit 7
  210578. #define SENSE_EOM 0x40 // Byte 2 Bit 6
  210579. #define SENSE_ILI 0x20 // Byte 2 Bit 5
  210580. //***************************************************************************
  210581. // %%% REQUEST SENSE SENSE KEY DEFINITIONS %%%
  210582. //***************************************************************************
  210583. #define KEY_NOSENSE 0x00 // No Sense
  210584. #define KEY_RECERROR 0x01 // Recovered Error
  210585. #define KEY_NOTREADY 0x02 // Not Ready
  210586. #define KEY_MEDIUMERR 0x03 // Medium Error
  210587. #define KEY_HARDERROR 0x04 // Hardware Error
  210588. #define KEY_ILLGLREQ 0x05 // Illegal Request
  210589. #define KEY_UNITATT 0x06 // Unit Attention
  210590. #define KEY_DATAPROT 0x07 // Data Protect
  210591. #define KEY_BLANKCHK 0x08 // Blank Check
  210592. #define KEY_VENDSPEC 0x09 // Vendor Specific
  210593. #define KEY_COPYABORT 0x0A // Copy Abort
  210594. #define KEY_EQUAL 0x0C // Equal (Search)
  210595. #define KEY_VOLOVRFLW 0x0D // Volume Overflow
  210596. #define KEY_MISCOMP 0x0E // Miscompare (Search)
  210597. #define KEY_RESERVED 0x0F // Reserved
  210598. //***************************************************************************
  210599. // %%% PERIPHERAL DEVICE TYPE DEFINITIONS %%%
  210600. //***************************************************************************
  210601. #define DTYPE_DASD 0x00 // Disk Device
  210602. #define DTYPE_SEQD 0x01 // Tape Device
  210603. #define DTYPE_PRNT 0x02 // Printer
  210604. #define DTYPE_PROC 0x03 // Processor
  210605. #define DTYPE_WORM 0x04 // Write-once read-multiple
  210606. #define DTYPE_CROM 0x05 // CD-ROM device
  210607. #define DTYPE_SCAN 0x06 // Scanner device
  210608. #define DTYPE_OPTI 0x07 // Optical memory device
  210609. #define DTYPE_JUKE 0x08 // Medium Changer device
  210610. #define DTYPE_COMM 0x09 // Communications device
  210611. #define DTYPE_RESL 0x0A // Reserved (low)
  210612. #define DTYPE_RESH 0x1E // Reserved (high)
  210613. #define DTYPE_UNKNOWN 0x1F // Unknown or no device type
  210614. //***************************************************************************
  210615. // %%% ANSI APPROVED VERSION DEFINITIONS %%%
  210616. //***************************************************************************
  210617. #define ANSI_MAYBE 0x0 // Device may or may not be ANSI approved stand
  210618. #define ANSI_SCSI1 0x1 // Device complies to ANSI X3.131-1986 (SCSI-1)
  210619. #define ANSI_SCSI2 0x2 // Device complies to SCSI-2
  210620. #define ANSI_RESLO 0x3 // Reserved (low)
  210621. #define ANSI_RESHI 0x7 // Reserved (high)
  210622. typedef struct
  210623. {
  210624. USHORT Length;
  210625. UCHAR ScsiStatus;
  210626. UCHAR PathId;
  210627. UCHAR TargetId;
  210628. UCHAR Lun;
  210629. UCHAR CdbLength;
  210630. UCHAR SenseInfoLength;
  210631. UCHAR DataIn;
  210632. ULONG DataTransferLength;
  210633. ULONG TimeOutValue;
  210634. ULONG DataBufferOffset;
  210635. ULONG SenseInfoOffset;
  210636. UCHAR Cdb[16];
  210637. } SCSI_PASS_THROUGH, *PSCSI_PASS_THROUGH;
  210638. typedef struct
  210639. {
  210640. USHORT Length;
  210641. UCHAR ScsiStatus;
  210642. UCHAR PathId;
  210643. UCHAR TargetId;
  210644. UCHAR Lun;
  210645. UCHAR CdbLength;
  210646. UCHAR SenseInfoLength;
  210647. UCHAR DataIn;
  210648. ULONG DataTransferLength;
  210649. ULONG TimeOutValue;
  210650. PVOID DataBuffer;
  210651. ULONG SenseInfoOffset;
  210652. UCHAR Cdb[16];
  210653. } SCSI_PASS_THROUGH_DIRECT, *PSCSI_PASS_THROUGH_DIRECT;
  210654. typedef struct
  210655. {
  210656. SCSI_PASS_THROUGH_DIRECT spt;
  210657. ULONG Filler;
  210658. UCHAR ucSenseBuf[32];
  210659. } SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, *PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER;
  210660. typedef struct
  210661. {
  210662. ULONG Length;
  210663. UCHAR PortNumber;
  210664. UCHAR PathId;
  210665. UCHAR TargetId;
  210666. UCHAR Lun;
  210667. } SCSI_ADDRESS, *PSCSI_ADDRESS;
  210668. #define METHOD_BUFFERED 0
  210669. #define METHOD_IN_DIRECT 1
  210670. #define METHOD_OUT_DIRECT 2
  210671. #define METHOD_NEITHER 3
  210672. #define FILE_ANY_ACCESS 0
  210673. #ifndef FILE_READ_ACCESS
  210674. #define FILE_READ_ACCESS (0x0001)
  210675. #endif
  210676. #ifndef FILE_WRITE_ACCESS
  210677. #define FILE_WRITE_ACCESS (0x0002)
  210678. #endif
  210679. #define IOCTL_SCSI_BASE 0x00000004
  210680. #define SCSI_IOCTL_DATA_OUT 0
  210681. #define SCSI_IOCTL_DATA_IN 1
  210682. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  210683. #define CTL_CODE2( DevType, Function, Method, Access ) ( \
  210684. ((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \
  210685. )
  210686. #define IOCTL_SCSI_PASS_THROUGH CTL_CODE2( IOCTL_SCSI_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  210687. #define IOCTL_SCSI_GET_CAPABILITIES CTL_CODE2( IOCTL_SCSI_BASE, 0x0404, METHOD_BUFFERED, FILE_ANY_ACCESS)
  210688. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  210689. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  210690. #define SENSE_LEN 14
  210691. #define SRB_DIR_SCSI 0x00
  210692. #define SRB_POSTING 0x01
  210693. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  210694. #define SRB_DIR_IN 0x08
  210695. #define SRB_DIR_OUT 0x10
  210696. #define SRB_EVENT_NOTIFY 0x40
  210697. #define RESIDUAL_COUNT_SUPPORTED 0x02
  210698. #define MAX_SRB_TIMEOUT 1080001u
  210699. #define DEFAULT_SRB_TIMEOUT 1080001u
  210700. #define SC_HA_INQUIRY 0x00
  210701. #define SC_GET_DEV_TYPE 0x01
  210702. #define SC_EXEC_SCSI_CMD 0x02
  210703. #define SC_ABORT_SRB 0x03
  210704. #define SC_RESET_DEV 0x04
  210705. #define SC_SET_HA_PARMS 0x05
  210706. #define SC_GET_DISK_INFO 0x06
  210707. #define SC_RESCAN_SCSI_BUS 0x07
  210708. #define SC_GETSET_TIMEOUTS 0x08
  210709. #define SS_PENDING 0x00
  210710. #define SS_COMP 0x01
  210711. #define SS_ABORTED 0x02
  210712. #define SS_ABORT_FAIL 0x03
  210713. #define SS_ERR 0x04
  210714. #define SS_INVALID_CMD 0x80
  210715. #define SS_INVALID_HA 0x81
  210716. #define SS_NO_DEVICE 0x82
  210717. #define SS_INVALID_SRB 0xE0
  210718. #define SS_OLD_MANAGER 0xE1
  210719. #define SS_BUFFER_ALIGN 0xE1
  210720. #define SS_ILLEGAL_MODE 0xE2
  210721. #define SS_NO_ASPI 0xE3
  210722. #define SS_FAILED_INIT 0xE4
  210723. #define SS_ASPI_IS_BUSY 0xE5
  210724. #define SS_BUFFER_TO_BIG 0xE6
  210725. #define SS_BUFFER_TOO_BIG 0xE6
  210726. #define SS_MISMATCHED_COMPONENTS 0xE7
  210727. #define SS_NO_ADAPTERS 0xE8
  210728. #define SS_INSUFFICIENT_RESOURCES 0xE9
  210729. #define SS_ASPI_IS_SHUTDOWN 0xEA
  210730. #define SS_BAD_INSTALL 0xEB
  210731. #define HASTAT_OK 0x00
  210732. #define HASTAT_SEL_TO 0x11
  210733. #define HASTAT_DO_DU 0x12
  210734. #define HASTAT_BUS_FREE 0x13
  210735. #define HASTAT_PHASE_ERR 0x14
  210736. #define HASTAT_TIMEOUT 0x09
  210737. #define HASTAT_COMMAND_TIMEOUT 0x0B
  210738. #define HASTAT_MESSAGE_REJECT 0x0D
  210739. #define HASTAT_BUS_RESET 0x0E
  210740. #define HASTAT_PARITY_ERROR 0x0F
  210741. #define HASTAT_REQUEST_SENSE_FAILED 0x10
  210742. #define PACKED
  210743. #pragma pack(1)
  210744. typedef struct
  210745. {
  210746. BYTE SRB_Cmd;
  210747. BYTE SRB_Status;
  210748. BYTE SRB_HaID;
  210749. BYTE SRB_Flags;
  210750. DWORD SRB_Hdr_Rsvd;
  210751. BYTE HA_Count;
  210752. BYTE HA_SCSI_ID;
  210753. BYTE HA_ManagerId[16];
  210754. BYTE HA_Identifier[16];
  210755. BYTE HA_Unique[16];
  210756. WORD HA_Rsvd1;
  210757. BYTE pad[20];
  210758. } PACKED SRB_HAInquiry, *PSRB_HAInquiry, FAR *LPSRB_HAInquiry;
  210759. typedef struct
  210760. {
  210761. BYTE SRB_Cmd;
  210762. BYTE SRB_Status;
  210763. BYTE SRB_HaID;
  210764. BYTE SRB_Flags;
  210765. DWORD SRB_Hdr_Rsvd;
  210766. BYTE SRB_Target;
  210767. BYTE SRB_Lun;
  210768. BYTE SRB_DeviceType;
  210769. BYTE SRB_Rsvd1;
  210770. BYTE pad[68];
  210771. } PACKED SRB_GDEVBlock, *PSRB_GDEVBlock, FAR *LPSRB_GDEVBlock;
  210772. typedef struct
  210773. {
  210774. BYTE SRB_Cmd;
  210775. BYTE SRB_Status;
  210776. BYTE SRB_HaID;
  210777. BYTE SRB_Flags;
  210778. DWORD SRB_Hdr_Rsvd;
  210779. BYTE SRB_Target;
  210780. BYTE SRB_Lun;
  210781. WORD SRB_Rsvd1;
  210782. DWORD SRB_BufLen;
  210783. BYTE FAR *SRB_BufPointer;
  210784. BYTE SRB_SenseLen;
  210785. BYTE SRB_CDBLen;
  210786. BYTE SRB_HaStat;
  210787. BYTE SRB_TargStat;
  210788. VOID FAR *SRB_PostProc;
  210789. BYTE SRB_Rsvd2[20];
  210790. BYTE CDBByte[16];
  210791. BYTE SenseArea[SENSE_LEN+2];
  210792. } PACKED SRB_ExecSCSICmd, *PSRB_ExecSCSICmd, FAR *LPSRB_ExecSCSICmd;
  210793. typedef struct
  210794. {
  210795. BYTE SRB_Cmd;
  210796. BYTE SRB_Status;
  210797. BYTE SRB_HaId;
  210798. BYTE SRB_Flags;
  210799. DWORD SRB_Hdr_Rsvd;
  210800. } PACKED SRB, *PSRB, FAR *LPSRB;
  210801. #pragma pack()
  210802. struct CDDeviceInfo
  210803. {
  210804. char vendor[9];
  210805. char productId[17];
  210806. char rev[5];
  210807. char vendorSpec[21];
  210808. BYTE ha;
  210809. BYTE tgt;
  210810. BYTE lun;
  210811. char scsiDriveLetter; // will be 0 if not using scsi
  210812. };
  210813. class CDReadBuffer
  210814. {
  210815. public:
  210816. int startFrame;
  210817. int numFrames;
  210818. int dataStartOffset;
  210819. int dataLength;
  210820. int bufferSize;
  210821. HeapBlock<BYTE> buffer;
  210822. int index;
  210823. bool wantsIndex;
  210824. CDReadBuffer (const int numberOfFrames)
  210825. : startFrame (0),
  210826. numFrames (0),
  210827. dataStartOffset (0),
  210828. dataLength (0),
  210829. bufferSize (2352 * numberOfFrames),
  210830. buffer (bufferSize),
  210831. index (0),
  210832. wantsIndex (false)
  210833. {
  210834. }
  210835. bool isZero() const throw()
  210836. {
  210837. BYTE* p = buffer + dataStartOffset;
  210838. for (int i = dataLength; --i >= 0;)
  210839. if (*p++ != 0)
  210840. return false;
  210841. return true;
  210842. }
  210843. };
  210844. class CDDeviceHandle;
  210845. class CDController
  210846. {
  210847. public:
  210848. CDController();
  210849. virtual ~CDController();
  210850. virtual bool read (CDReadBuffer* t) = 0;
  210851. virtual void shutDown();
  210852. bool readAudio (CDReadBuffer* t, CDReadBuffer* overlapBuffer = 0);
  210853. int getLastIndex();
  210854. public:
  210855. bool initialised;
  210856. CDDeviceHandle* deviceInfo;
  210857. int framesToCheck, framesOverlap;
  210858. void prepare (SRB_ExecSCSICmd& s);
  210859. void perform (SRB_ExecSCSICmd& s);
  210860. void setPaused (bool paused);
  210861. };
  210862. #pragma pack(1)
  210863. struct TOCTRACK
  210864. {
  210865. BYTE rsvd;
  210866. BYTE ADR;
  210867. BYTE trackNumber;
  210868. BYTE rsvd2;
  210869. BYTE addr[4];
  210870. };
  210871. struct TOC
  210872. {
  210873. WORD tocLen;
  210874. BYTE firstTrack;
  210875. BYTE lastTrack;
  210876. TOCTRACK tracks[100];
  210877. };
  210878. #pragma pack()
  210879. enum
  210880. {
  210881. READTYPE_ANY = 0,
  210882. READTYPE_ATAPI1 = 1,
  210883. READTYPE_ATAPI2 = 2,
  210884. READTYPE_READ6 = 3,
  210885. READTYPE_READ10 = 4,
  210886. READTYPE_READ_D8 = 5,
  210887. READTYPE_READ_D4 = 6,
  210888. READTYPE_READ_D4_1 = 7,
  210889. READTYPE_READ10_2 = 8
  210890. };
  210891. class CDDeviceHandle
  210892. {
  210893. public:
  210894. CDDeviceHandle (const CDDeviceInfo* const device)
  210895. : scsiHandle (0),
  210896. readType (READTYPE_ANY),
  210897. controller (0)
  210898. {
  210899. memcpy (&info, device, sizeof (info));
  210900. }
  210901. ~CDDeviceHandle()
  210902. {
  210903. if (controller != 0)
  210904. {
  210905. controller->shutDown();
  210906. controller = 0;
  210907. }
  210908. if (scsiHandle != 0)
  210909. CloseHandle (scsiHandle);
  210910. }
  210911. bool readTOC (TOC* lpToc);
  210912. bool readAudio (CDReadBuffer* buffer, CDReadBuffer* overlapBuffer = 0);
  210913. void openDrawer (bool shouldBeOpen);
  210914. CDDeviceInfo info;
  210915. HANDLE scsiHandle;
  210916. BYTE readType;
  210917. private:
  210918. ScopedPointer<CDController> controller;
  210919. bool testController (const int readType,
  210920. CDController* const newController,
  210921. CDReadBuffer* const bufferToUse);
  210922. };
  210923. DWORD (*fGetASPI32SupportInfo)(void);
  210924. DWORD (*fSendASPI32Command)(LPSRB);
  210925. static HINSTANCE winAspiLib = 0;
  210926. static bool usingScsi = false;
  210927. static bool initialised = false;
  210928. static bool InitialiseCDRipper()
  210929. {
  210930. if (! initialised)
  210931. {
  210932. initialised = true;
  210933. OSVERSIONINFO info;
  210934. info.dwOSVersionInfoSize = sizeof (info);
  210935. GetVersionEx (&info);
  210936. usingScsi = (info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4);
  210937. if (! usingScsi)
  210938. {
  210939. fGetASPI32SupportInfo = 0;
  210940. fSendASPI32Command = 0;
  210941. winAspiLib = LoadLibrary (_T("WNASPI32.DLL"));
  210942. if (winAspiLib != 0)
  210943. {
  210944. fGetASPI32SupportInfo = (DWORD(*)(void)) GetProcAddress (winAspiLib, "GetASPI32SupportInfo");
  210945. fSendASPI32Command = (DWORD(*)(LPSRB)) GetProcAddress (winAspiLib, "SendASPI32Command");
  210946. if (fGetASPI32SupportInfo == 0 || fSendASPI32Command == 0)
  210947. return false;
  210948. }
  210949. else
  210950. {
  210951. usingScsi = true;
  210952. }
  210953. }
  210954. }
  210955. return true;
  210956. }
  210957. static void DeinitialiseCDRipper()
  210958. {
  210959. if (winAspiLib != 0)
  210960. {
  210961. fGetASPI32SupportInfo = 0;
  210962. fSendASPI32Command = 0;
  210963. FreeLibrary (winAspiLib);
  210964. winAspiLib = 0;
  210965. }
  210966. initialised = false;
  210967. }
  210968. static HANDLE CreateSCSIDeviceHandle (char driveLetter)
  210969. {
  210970. TCHAR devicePath[] = { '\\', '\\', '.', '\\', driveLetter, ':', 0, 0 };
  210971. OSVERSIONINFO info;
  210972. info.dwOSVersionInfoSize = sizeof (info);
  210973. GetVersionEx (&info);
  210974. DWORD flags = GENERIC_READ;
  210975. if ((info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4))
  210976. flags = GENERIC_READ | GENERIC_WRITE;
  210977. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  210978. if (h == INVALID_HANDLE_VALUE)
  210979. {
  210980. flags ^= GENERIC_WRITE;
  210981. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  210982. }
  210983. return h;
  210984. }
  210985. static DWORD performScsiPassThroughCommand (const LPSRB_ExecSCSICmd srb,
  210986. const char driveLetter,
  210987. HANDLE& deviceHandle,
  210988. const bool retryOnFailure = true)
  210989. {
  210990. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  210991. zerostruct (s);
  210992. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  210993. s.spt.CdbLength = srb->SRB_CDBLen;
  210994. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  210995. ? SCSI_IOCTL_DATA_IN
  210996. : ((srb->SRB_Flags & SRB_DIR_OUT)
  210997. ? SCSI_IOCTL_DATA_OUT
  210998. : SCSI_IOCTL_DATA_UNSPECIFIED));
  210999. s.spt.DataTransferLength = srb->SRB_BufLen;
  211000. s.spt.TimeOutValue = 5;
  211001. s.spt.DataBuffer = srb->SRB_BufPointer;
  211002. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  211003. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  211004. srb->SRB_Status = SS_ERR;
  211005. srb->SRB_TargStat = 0x0004;
  211006. DWORD bytesReturned = 0;
  211007. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  211008. &s, sizeof (s),
  211009. &s, sizeof (s),
  211010. &bytesReturned, 0) != 0)
  211011. {
  211012. srb->SRB_Status = SS_COMP;
  211013. }
  211014. else if (retryOnFailure)
  211015. {
  211016. const DWORD error = GetLastError();
  211017. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  211018. {
  211019. if (error != ERROR_INVALID_HANDLE)
  211020. CloseHandle (deviceHandle);
  211021. deviceHandle = CreateSCSIDeviceHandle (driveLetter);
  211022. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  211023. }
  211024. }
  211025. return srb->SRB_Status;
  211026. }
  211027. // Controller types..
  211028. class ControllerType1 : public CDController
  211029. {
  211030. public:
  211031. ControllerType1() {}
  211032. ~ControllerType1() {}
  211033. bool read (CDReadBuffer* rb)
  211034. {
  211035. if (rb->numFrames * 2352 > rb->bufferSize)
  211036. return false;
  211037. SRB_ExecSCSICmd s;
  211038. prepare (s);
  211039. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211040. s.SRB_BufLen = rb->bufferSize;
  211041. s.SRB_BufPointer = rb->buffer;
  211042. s.SRB_CDBLen = 12;
  211043. s.CDBByte[0] = 0xBE;
  211044. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211045. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211046. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211047. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  211048. s.CDBByte[9] = (BYTE)((deviceInfo->readType == READTYPE_ATAPI1) ? 0x10 : 0xF0);
  211049. perform (s);
  211050. if (s.SRB_Status != SS_COMP)
  211051. return false;
  211052. rb->dataLength = rb->numFrames * 2352;
  211053. rb->dataStartOffset = 0;
  211054. return true;
  211055. }
  211056. };
  211057. class ControllerType2 : public CDController
  211058. {
  211059. public:
  211060. ControllerType2() {}
  211061. ~ControllerType2() {}
  211062. void shutDown()
  211063. {
  211064. if (initialised)
  211065. {
  211066. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  211067. SRB_ExecSCSICmd s;
  211068. prepare (s);
  211069. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  211070. s.SRB_BufLen = 0x0C;
  211071. s.SRB_BufPointer = bufPointer;
  211072. s.SRB_CDBLen = 6;
  211073. s.CDBByte[0] = 0x15;
  211074. s.CDBByte[4] = 0x0C;
  211075. perform (s);
  211076. }
  211077. }
  211078. bool init()
  211079. {
  211080. SRB_ExecSCSICmd s;
  211081. s.SRB_Status = SS_ERR;
  211082. if (deviceInfo->readType == READTYPE_READ10_2)
  211083. {
  211084. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  211085. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  211086. for (int i = 0; i < 2; ++i)
  211087. {
  211088. prepare (s);
  211089. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211090. s.SRB_BufLen = 0x14;
  211091. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  211092. s.SRB_CDBLen = 6;
  211093. s.CDBByte[0] = 0x15;
  211094. s.CDBByte[1] = 0x10;
  211095. s.CDBByte[4] = 0x14;
  211096. perform (s);
  211097. if (s.SRB_Status != SS_COMP)
  211098. return false;
  211099. }
  211100. }
  211101. else
  211102. {
  211103. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  211104. prepare (s);
  211105. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211106. s.SRB_BufLen = 0x0C;
  211107. s.SRB_BufPointer = bufPointer;
  211108. s.SRB_CDBLen = 6;
  211109. s.CDBByte[0] = 0x15;
  211110. s.CDBByte[4] = 0x0C;
  211111. perform (s);
  211112. }
  211113. return s.SRB_Status == SS_COMP;
  211114. }
  211115. bool read (CDReadBuffer* rb)
  211116. {
  211117. if (rb->numFrames * 2352 > rb->bufferSize)
  211118. return false;
  211119. if (!initialised)
  211120. {
  211121. initialised = init();
  211122. if (!initialised)
  211123. return false;
  211124. }
  211125. SRB_ExecSCSICmd s;
  211126. prepare (s);
  211127. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211128. s.SRB_BufLen = rb->bufferSize;
  211129. s.SRB_BufPointer = rb->buffer;
  211130. s.SRB_CDBLen = 10;
  211131. s.CDBByte[0] = 0x28;
  211132. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  211133. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211134. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211135. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211136. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  211137. perform (s);
  211138. if (s.SRB_Status != SS_COMP)
  211139. return false;
  211140. rb->dataLength = rb->numFrames * 2352;
  211141. rb->dataStartOffset = 0;
  211142. return true;
  211143. }
  211144. };
  211145. class ControllerType3 : public CDController
  211146. {
  211147. public:
  211148. ControllerType3() {}
  211149. ~ControllerType3() {}
  211150. bool read (CDReadBuffer* rb)
  211151. {
  211152. if (rb->numFrames * 2352 > rb->bufferSize)
  211153. return false;
  211154. if (!initialised)
  211155. {
  211156. setPaused (false);
  211157. initialised = true;
  211158. }
  211159. SRB_ExecSCSICmd s;
  211160. prepare (s);
  211161. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211162. s.SRB_BufLen = rb->numFrames * 2352;
  211163. s.SRB_BufPointer = rb->buffer;
  211164. s.SRB_CDBLen = 12;
  211165. s.CDBByte[0] = 0xD8;
  211166. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211167. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211168. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211169. s.CDBByte[9] = (BYTE)(rb->numFrames & 0xFF);
  211170. perform (s);
  211171. if (s.SRB_Status != SS_COMP)
  211172. return false;
  211173. rb->dataLength = rb->numFrames * 2352;
  211174. rb->dataStartOffset = 0;
  211175. return true;
  211176. }
  211177. };
  211178. class ControllerType4 : public CDController
  211179. {
  211180. public:
  211181. ControllerType4() {}
  211182. ~ControllerType4() {}
  211183. bool selectD4Mode()
  211184. {
  211185. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  211186. SRB_ExecSCSICmd s;
  211187. prepare (s);
  211188. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211189. s.SRB_CDBLen = 6;
  211190. s.SRB_BufLen = 12;
  211191. s.SRB_BufPointer = bufPointer;
  211192. s.CDBByte[0] = 0x15;
  211193. s.CDBByte[1] = 0x10;
  211194. s.CDBByte[4] = 0x08;
  211195. perform (s);
  211196. return s.SRB_Status == SS_COMP;
  211197. }
  211198. bool read (CDReadBuffer* rb)
  211199. {
  211200. if (rb->numFrames * 2352 > rb->bufferSize)
  211201. return false;
  211202. if (!initialised)
  211203. {
  211204. setPaused (true);
  211205. if (deviceInfo->readType == READTYPE_READ_D4_1)
  211206. selectD4Mode();
  211207. initialised = true;
  211208. }
  211209. SRB_ExecSCSICmd s;
  211210. prepare (s);
  211211. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211212. s.SRB_BufLen = rb->bufferSize;
  211213. s.SRB_BufPointer = rb->buffer;
  211214. s.SRB_CDBLen = 10;
  211215. s.CDBByte[0] = 0xD4;
  211216. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211217. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211218. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211219. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  211220. perform (s);
  211221. if (s.SRB_Status != SS_COMP)
  211222. return false;
  211223. rb->dataLength = rb->numFrames * 2352;
  211224. rb->dataStartOffset = 0;
  211225. return true;
  211226. }
  211227. };
  211228. CDController::CDController() : initialised (false)
  211229. {
  211230. }
  211231. CDController::~CDController()
  211232. {
  211233. }
  211234. void CDController::prepare (SRB_ExecSCSICmd& s)
  211235. {
  211236. zerostruct (s);
  211237. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211238. s.SRB_HaID = deviceInfo->info.ha;
  211239. s.SRB_Target = deviceInfo->info.tgt;
  211240. s.SRB_Lun = deviceInfo->info.lun;
  211241. s.SRB_SenseLen = SENSE_LEN;
  211242. }
  211243. void CDController::perform (SRB_ExecSCSICmd& s)
  211244. {
  211245. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211246. s.SRB_PostProc = event;
  211247. ResetEvent (event);
  211248. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s,
  211249. deviceInfo->info.scsiDriveLetter,
  211250. deviceInfo->scsiHandle)
  211251. : fSendASPI32Command ((LPSRB)&s);
  211252. if (status == SS_PENDING)
  211253. WaitForSingleObject (event, 4000);
  211254. CloseHandle (event);
  211255. }
  211256. void CDController::setPaused (bool paused)
  211257. {
  211258. SRB_ExecSCSICmd s;
  211259. prepare (s);
  211260. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211261. s.SRB_CDBLen = 10;
  211262. s.CDBByte[0] = 0x4B;
  211263. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  211264. perform (s);
  211265. }
  211266. void CDController::shutDown()
  211267. {
  211268. }
  211269. bool CDController::readAudio (CDReadBuffer* rb, CDReadBuffer* overlapBuffer)
  211270. {
  211271. if (overlapBuffer != 0)
  211272. {
  211273. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  211274. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  211275. if (doJitter
  211276. && overlapBuffer->startFrame > 0
  211277. && overlapBuffer->numFrames > 0
  211278. && overlapBuffer->dataLength > 0)
  211279. {
  211280. const int numFrames = rb->numFrames;
  211281. if (overlapBuffer->startFrame == (rb->startFrame - framesToCheck))
  211282. {
  211283. rb->startFrame -= framesOverlap;
  211284. if (framesToCheck < framesOverlap
  211285. && numFrames + framesOverlap <= rb->bufferSize / 2352)
  211286. rb->numFrames += framesOverlap;
  211287. }
  211288. else
  211289. {
  211290. overlapBuffer->dataLength = 0;
  211291. overlapBuffer->startFrame = 0;
  211292. overlapBuffer->numFrames = 0;
  211293. }
  211294. }
  211295. if (! read (rb))
  211296. return false;
  211297. if (doJitter)
  211298. {
  211299. const int checkLen = framesToCheck * 2352;
  211300. const int maxToCheck = rb->dataLength - checkLen;
  211301. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  211302. return true;
  211303. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  211304. bool found = false;
  211305. for (int i = 0; i < maxToCheck; ++i)
  211306. {
  211307. if (memcmp (p, rb->buffer + i, checkLen) == 0)
  211308. {
  211309. i += checkLen;
  211310. rb->dataStartOffset = i;
  211311. rb->dataLength -= i;
  211312. rb->startFrame = overlapBuffer->startFrame + framesToCheck;
  211313. found = true;
  211314. break;
  211315. }
  211316. }
  211317. rb->numFrames = rb->dataLength / 2352;
  211318. rb->dataLength = 2352 * rb->numFrames;
  211319. if (!found)
  211320. return false;
  211321. }
  211322. if (canDoJitter)
  211323. {
  211324. memcpy (overlapBuffer->buffer,
  211325. rb->buffer + rb->dataStartOffset + 2352 * (rb->numFrames - framesToCheck),
  211326. 2352 * framesToCheck);
  211327. overlapBuffer->startFrame = rb->startFrame + rb->numFrames - framesToCheck;
  211328. overlapBuffer->numFrames = framesToCheck;
  211329. overlapBuffer->dataLength = 2352 * framesToCheck;
  211330. overlapBuffer->dataStartOffset = 0;
  211331. }
  211332. else
  211333. {
  211334. overlapBuffer->startFrame = 0;
  211335. overlapBuffer->numFrames = 0;
  211336. overlapBuffer->dataLength = 0;
  211337. }
  211338. return true;
  211339. }
  211340. else
  211341. {
  211342. return read (rb);
  211343. }
  211344. }
  211345. int CDController::getLastIndex()
  211346. {
  211347. char qdata[100];
  211348. SRB_ExecSCSICmd s;
  211349. prepare (s);
  211350. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211351. s.SRB_BufLen = sizeof (qdata);
  211352. s.SRB_BufPointer = (BYTE*)qdata;
  211353. s.SRB_CDBLen = 12;
  211354. s.CDBByte[0] = 0x42;
  211355. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  211356. s.CDBByte[2] = 64;
  211357. s.CDBByte[3] = 1; // get current position
  211358. s.CDBByte[7] = 0;
  211359. s.CDBByte[8] = (BYTE)sizeof (qdata);
  211360. perform (s);
  211361. if (s.SRB_Status == SS_COMP)
  211362. return qdata[7];
  211363. return 0;
  211364. }
  211365. bool CDDeviceHandle::readTOC (TOC* lpToc)
  211366. {
  211367. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211368. SRB_ExecSCSICmd s;
  211369. zerostruct (s);
  211370. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211371. s.SRB_HaID = info.ha;
  211372. s.SRB_Target = info.tgt;
  211373. s.SRB_Lun = info.lun;
  211374. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211375. s.SRB_BufLen = 0x324;
  211376. s.SRB_BufPointer = (BYTE*)lpToc;
  211377. s.SRB_SenseLen = 0x0E;
  211378. s.SRB_CDBLen = 0x0A;
  211379. s.SRB_PostProc = event;
  211380. s.CDBByte[0] = 0x43;
  211381. s.CDBByte[1] = 0x00;
  211382. s.CDBByte[7] = 0x03;
  211383. s.CDBByte[8] = 0x24;
  211384. ResetEvent (event);
  211385. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  211386. : fSendASPI32Command ((LPSRB)&s);
  211387. if (status == SS_PENDING)
  211388. WaitForSingleObject (event, 4000);
  211389. CloseHandle (event);
  211390. return (s.SRB_Status == SS_COMP);
  211391. }
  211392. bool CDDeviceHandle::readAudio (CDReadBuffer* const buffer,
  211393. CDReadBuffer* const overlapBuffer)
  211394. {
  211395. if (controller == 0)
  211396. {
  211397. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  211398. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  211399. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  211400. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  211401. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  211402. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  211403. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  211404. }
  211405. buffer->index = 0;
  211406. if ((controller != 0)
  211407. && controller->readAudio (buffer, overlapBuffer))
  211408. {
  211409. if (buffer->wantsIndex)
  211410. buffer->index = controller->getLastIndex();
  211411. return true;
  211412. }
  211413. return false;
  211414. }
  211415. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  211416. {
  211417. if (shouldBeOpen)
  211418. {
  211419. if (controller != 0)
  211420. {
  211421. controller->shutDown();
  211422. controller = 0;
  211423. }
  211424. if (scsiHandle != 0)
  211425. {
  211426. CloseHandle (scsiHandle);
  211427. scsiHandle = 0;
  211428. }
  211429. }
  211430. SRB_ExecSCSICmd s;
  211431. zerostruct (s);
  211432. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211433. s.SRB_HaID = info.ha;
  211434. s.SRB_Target = info.tgt;
  211435. s.SRB_Lun = info.lun;
  211436. s.SRB_SenseLen = SENSE_LEN;
  211437. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211438. s.SRB_BufLen = 0;
  211439. s.SRB_BufPointer = 0;
  211440. s.SRB_CDBLen = 12;
  211441. s.CDBByte[0] = 0x1b;
  211442. s.CDBByte[1] = (BYTE)(info.lun << 5);
  211443. s.CDBByte[4] = (BYTE)((shouldBeOpen) ? 2 : 3);
  211444. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211445. s.SRB_PostProc = event;
  211446. ResetEvent (event);
  211447. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  211448. : fSendASPI32Command ((LPSRB)&s);
  211449. if (status == SS_PENDING)
  211450. WaitForSingleObject (event, 4000);
  211451. CloseHandle (event);
  211452. }
  211453. bool CDDeviceHandle::testController (const int type,
  211454. CDController* const newController,
  211455. CDReadBuffer* const rb)
  211456. {
  211457. controller = newController;
  211458. readType = (BYTE)type;
  211459. controller->deviceInfo = this;
  211460. controller->framesToCheck = 1;
  211461. controller->framesOverlap = 3;
  211462. bool passed = false;
  211463. memset (rb->buffer, 0xcd, rb->bufferSize);
  211464. if (controller->read (rb))
  211465. {
  211466. passed = true;
  211467. int* p = (int*) (rb->buffer + rb->dataStartOffset);
  211468. int wrong = 0;
  211469. for (int i = rb->dataLength / 4; --i >= 0;)
  211470. {
  211471. if (*p++ == (int) 0xcdcdcdcd)
  211472. {
  211473. if (++wrong == 4)
  211474. {
  211475. passed = false;
  211476. break;
  211477. }
  211478. }
  211479. else
  211480. {
  211481. wrong = 0;
  211482. }
  211483. }
  211484. }
  211485. if (! passed)
  211486. {
  211487. controller->shutDown();
  211488. controller = 0;
  211489. }
  211490. return passed;
  211491. }
  211492. static void GetAspiDeviceInfo (CDDeviceInfo* dev, BYTE ha, BYTE tgt, BYTE lun)
  211493. {
  211494. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211495. const int bufSize = 128;
  211496. BYTE buffer[bufSize];
  211497. zeromem (buffer, bufSize);
  211498. SRB_ExecSCSICmd s;
  211499. zerostruct (s);
  211500. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211501. s.SRB_HaID = ha;
  211502. s.SRB_Target = tgt;
  211503. s.SRB_Lun = lun;
  211504. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211505. s.SRB_BufLen = bufSize;
  211506. s.SRB_BufPointer = buffer;
  211507. s.SRB_SenseLen = SENSE_LEN;
  211508. s.SRB_CDBLen = 6;
  211509. s.SRB_PostProc = event;
  211510. s.CDBByte[0] = SCSI_INQUIRY;
  211511. s.CDBByte[4] = 100;
  211512. ResetEvent (event);
  211513. if (fSendASPI32Command ((LPSRB)&s) == SS_PENDING)
  211514. WaitForSingleObject (event, 4000);
  211515. CloseHandle (event);
  211516. if (s.SRB_Status == SS_COMP)
  211517. {
  211518. memcpy (dev->vendor, &buffer[8], 8);
  211519. memcpy (dev->productId, &buffer[16], 16);
  211520. memcpy (dev->rev, &buffer[32], 4);
  211521. memcpy (dev->vendorSpec, &buffer[36], 20);
  211522. }
  211523. }
  211524. static int FindCDDevices (CDDeviceInfo* const list,
  211525. int maxItems)
  211526. {
  211527. int count = 0;
  211528. if (usingScsi)
  211529. {
  211530. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  211531. {
  211532. TCHAR drivePath[8];
  211533. drivePath[0] = driveLetter;
  211534. drivePath[1] = ':';
  211535. drivePath[2] = '\\';
  211536. drivePath[3] = 0;
  211537. if (GetDriveType (drivePath) == DRIVE_CDROM)
  211538. {
  211539. HANDLE h = CreateSCSIDeviceHandle (driveLetter);
  211540. if (h != INVALID_HANDLE_VALUE)
  211541. {
  211542. BYTE buffer[100], passThroughStruct[1024];
  211543. zeromem (buffer, sizeof (buffer));
  211544. zeromem (passThroughStruct, sizeof (passThroughStruct));
  211545. PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p = (PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER)passThroughStruct;
  211546. p->spt.Length = sizeof (SCSI_PASS_THROUGH);
  211547. p->spt.CdbLength = 6;
  211548. p->spt.SenseInfoLength = 24;
  211549. p->spt.DataIn = SCSI_IOCTL_DATA_IN;
  211550. p->spt.DataTransferLength = 100;
  211551. p->spt.TimeOutValue = 2;
  211552. p->spt.DataBuffer = buffer;
  211553. p->spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  211554. p->spt.Cdb[0] = 0x12;
  211555. p->spt.Cdb[4] = 100;
  211556. DWORD bytesReturned = 0;
  211557. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  211558. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  211559. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  211560. &bytesReturned, 0) != 0)
  211561. {
  211562. zeromem (&list[count], sizeof (CDDeviceInfo));
  211563. list[count].scsiDriveLetter = driveLetter;
  211564. memcpy (list[count].vendor, &buffer[8], 8);
  211565. memcpy (list[count].productId, &buffer[16], 16);
  211566. memcpy (list[count].rev, &buffer[32], 4);
  211567. memcpy (list[count].vendorSpec, &buffer[36], 20);
  211568. zeromem (passThroughStruct, sizeof (passThroughStruct));
  211569. PSCSI_ADDRESS scsiAddr = (PSCSI_ADDRESS)passThroughStruct;
  211570. scsiAddr->Length = sizeof (SCSI_ADDRESS);
  211571. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  211572. 0, 0, scsiAddr, sizeof (SCSI_ADDRESS),
  211573. &bytesReturned, 0) != 0)
  211574. {
  211575. list[count].ha = scsiAddr->PortNumber;
  211576. list[count].tgt = scsiAddr->TargetId;
  211577. list[count].lun = scsiAddr->Lun;
  211578. ++count;
  211579. }
  211580. }
  211581. CloseHandle (h);
  211582. }
  211583. }
  211584. }
  211585. }
  211586. else
  211587. {
  211588. const DWORD d = fGetASPI32SupportInfo();
  211589. BYTE status = HIBYTE (LOWORD (d));
  211590. if (status != SS_COMP || status == SS_NO_ADAPTERS)
  211591. return 0;
  211592. const int numAdapters = LOBYTE (LOWORD (d));
  211593. for (BYTE ha = 0; ha < numAdapters; ++ha)
  211594. {
  211595. SRB_HAInquiry s;
  211596. zerostruct (s);
  211597. s.SRB_Cmd = SC_HA_INQUIRY;
  211598. s.SRB_HaID = ha;
  211599. fSendASPI32Command ((LPSRB)&s);
  211600. if (s.SRB_Status == SS_COMP)
  211601. {
  211602. maxItems = (int)s.HA_Unique[3];
  211603. if (maxItems == 0)
  211604. maxItems = 8;
  211605. for (BYTE tgt = 0; tgt < maxItems; ++tgt)
  211606. {
  211607. for (BYTE lun = 0; lun < 8; ++lun)
  211608. {
  211609. SRB_GDEVBlock sb;
  211610. zerostruct (sb);
  211611. sb.SRB_Cmd = SC_GET_DEV_TYPE;
  211612. sb.SRB_HaID = ha;
  211613. sb.SRB_Target = tgt;
  211614. sb.SRB_Lun = lun;
  211615. fSendASPI32Command ((LPSRB) &sb);
  211616. if (sb.SRB_Status == SS_COMP
  211617. && sb.SRB_DeviceType == DTYPE_CROM)
  211618. {
  211619. zeromem (&list[count], sizeof (CDDeviceInfo));
  211620. list[count].ha = ha;
  211621. list[count].tgt = tgt;
  211622. list[count].lun = lun;
  211623. GetAspiDeviceInfo (&(list[count]), ha, tgt, lun);
  211624. ++count;
  211625. }
  211626. }
  211627. }
  211628. }
  211629. }
  211630. }
  211631. return count;
  211632. }
  211633. static int ripperUsers = 0;
  211634. static bool initialisedOk = false;
  211635. class DeinitialiseTimer : private Timer,
  211636. private DeletedAtShutdown
  211637. {
  211638. DeinitialiseTimer (const DeinitialiseTimer&);
  211639. DeinitialiseTimer& operator= (const DeinitialiseTimer&);
  211640. public:
  211641. DeinitialiseTimer()
  211642. {
  211643. startTimer (4000);
  211644. }
  211645. ~DeinitialiseTimer()
  211646. {
  211647. if (--ripperUsers == 0)
  211648. DeinitialiseCDRipper();
  211649. }
  211650. void timerCallback()
  211651. {
  211652. delete this;
  211653. }
  211654. juce_UseDebuggingNewOperator
  211655. };
  211656. static void incUserCount()
  211657. {
  211658. if (ripperUsers++ == 0)
  211659. initialisedOk = InitialiseCDRipper();
  211660. }
  211661. static void decUserCount()
  211662. {
  211663. new DeinitialiseTimer();
  211664. }
  211665. struct CDDeviceWrapper
  211666. {
  211667. ScopedPointer<CDDeviceHandle> cdH;
  211668. ScopedPointer<CDReadBuffer> overlapBuffer;
  211669. bool jitter;
  211670. };
  211671. static int getAddressOf (const TOCTRACK* const t)
  211672. {
  211673. return (((DWORD)t->addr[0]) << 24) + (((DWORD)t->addr[1]) << 16) +
  211674. (((DWORD)t->addr[2]) << 8) + ((DWORD)t->addr[3]);
  211675. }
  211676. static const int samplesPerFrame = 44100 / 75;
  211677. static const int bytesPerFrame = samplesPerFrame * 4;
  211678. static CDDeviceHandle* openHandle (const CDDeviceInfo* const device)
  211679. {
  211680. SRB_GDEVBlock s;
  211681. zerostruct (s);
  211682. s.SRB_Cmd = SC_GET_DEV_TYPE;
  211683. s.SRB_HaID = device->ha;
  211684. s.SRB_Target = device->tgt;
  211685. s.SRB_Lun = device->lun;
  211686. if (usingScsi)
  211687. {
  211688. HANDLE h = CreateSCSIDeviceHandle (device->scsiDriveLetter);
  211689. if (h != INVALID_HANDLE_VALUE)
  211690. {
  211691. CDDeviceHandle* cdh = new CDDeviceHandle (device);
  211692. cdh->scsiHandle = h;
  211693. return cdh;
  211694. }
  211695. }
  211696. else
  211697. {
  211698. if (fSendASPI32Command ((LPSRB)&s) == SS_COMP
  211699. && s.SRB_DeviceType == DTYPE_CROM)
  211700. {
  211701. return new CDDeviceHandle (device);
  211702. }
  211703. }
  211704. return 0;
  211705. }
  211706. }
  211707. const StringArray AudioCDReader::getAvailableCDNames()
  211708. {
  211709. using namespace CDReaderHelpers;
  211710. StringArray results;
  211711. incUserCount();
  211712. if (initialisedOk)
  211713. {
  211714. CDDeviceInfo list[8];
  211715. const int num = FindCDDevices (list, 8);
  211716. decUserCount();
  211717. for (int i = 0; i < num; ++i)
  211718. {
  211719. String s;
  211720. if (list[i].scsiDriveLetter > 0)
  211721. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << ": ";
  211722. s << String (list[i].vendor).trim()
  211723. << ' ' << String (list[i].productId).trim()
  211724. << ' ' << String (list[i].rev).trim();
  211725. results.add (s);
  211726. }
  211727. }
  211728. return results;
  211729. }
  211730. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  211731. {
  211732. using namespace CDReaderHelpers;
  211733. incUserCount();
  211734. if (initialisedOk)
  211735. {
  211736. CDDeviceInfo list[8];
  211737. const int num = FindCDDevices (list, 8);
  211738. if (((unsigned int) deviceIndex) < (unsigned int) num)
  211739. {
  211740. CDDeviceHandle* const handle = openHandle (&(list[deviceIndex]));
  211741. if (handle != 0)
  211742. {
  211743. CDDeviceWrapper* const d = new CDDeviceWrapper();
  211744. d->cdH = handle;
  211745. d->overlapBuffer = new CDReadBuffer(3);
  211746. return new AudioCDReader (d);
  211747. }
  211748. }
  211749. }
  211750. decUserCount();
  211751. return 0;
  211752. }
  211753. AudioCDReader::AudioCDReader (void* handle_)
  211754. : AudioFormatReader (0, "CD Audio"),
  211755. handle (handle_),
  211756. indexingEnabled (false),
  211757. lastIndex (0),
  211758. firstFrameInBuffer (0),
  211759. samplesInBuffer (0)
  211760. {
  211761. using namespace CDReaderHelpers;
  211762. jassert (handle_ != 0);
  211763. refreshTrackLengths();
  211764. sampleRate = 44100.0;
  211765. bitsPerSample = 16;
  211766. numChannels = 2;
  211767. usesFloatingPointData = false;
  211768. buffer.setSize (4 * bytesPerFrame, true);
  211769. }
  211770. AudioCDReader::~AudioCDReader()
  211771. {
  211772. using namespace CDReaderHelpers;
  211773. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  211774. delete device;
  211775. decUserCount();
  211776. }
  211777. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  211778. int64 startSampleInFile, int numSamples)
  211779. {
  211780. using namespace CDReaderHelpers;
  211781. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  211782. bool ok = true;
  211783. while (numSamples > 0)
  211784. {
  211785. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  211786. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  211787. if (startSampleInFile >= bufferStartSample
  211788. && startSampleInFile < bufferEndSample)
  211789. {
  211790. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  211791. int* const l = destSamples[0] + startOffsetInDestBuffer;
  211792. int* const r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  211793. const short* src = (const short*) buffer.getData();
  211794. src += 2 * (startSampleInFile - bufferStartSample);
  211795. for (int i = 0; i < toDo; ++i)
  211796. {
  211797. l[i] = src [i << 1] << 16;
  211798. if (r != 0)
  211799. r[i] = src [(i << 1) + 1] << 16;
  211800. }
  211801. startOffsetInDestBuffer += toDo;
  211802. startSampleInFile += toDo;
  211803. numSamples -= toDo;
  211804. }
  211805. else
  211806. {
  211807. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  211808. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  211809. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  211810. {
  211811. device->overlapBuffer->dataLength = 0;
  211812. device->overlapBuffer->startFrame = 0;
  211813. device->overlapBuffer->numFrames = 0;
  211814. device->jitter = false;
  211815. }
  211816. firstFrameInBuffer = frameNeeded;
  211817. lastIndex = 0;
  211818. CDReadBuffer readBuffer (framesInBuffer + 4);
  211819. readBuffer.wantsIndex = indexingEnabled;
  211820. int i;
  211821. for (i = 5; --i >= 0;)
  211822. {
  211823. readBuffer.startFrame = frameNeeded;
  211824. readBuffer.numFrames = framesInBuffer;
  211825. if (device->cdH->readAudio (&readBuffer, (device->jitter) ? device->overlapBuffer : 0))
  211826. break;
  211827. else
  211828. device->overlapBuffer->dataLength = 0;
  211829. }
  211830. if (i >= 0)
  211831. {
  211832. memcpy ((char*) buffer.getData(),
  211833. readBuffer.buffer + readBuffer.dataStartOffset,
  211834. readBuffer.dataLength);
  211835. samplesInBuffer = readBuffer.dataLength >> 2;
  211836. lastIndex = readBuffer.index;
  211837. }
  211838. else
  211839. {
  211840. int* l = destSamples[0] + startOffsetInDestBuffer;
  211841. int* r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  211842. while (--numSamples >= 0)
  211843. {
  211844. *l++ = 0;
  211845. if (r != 0)
  211846. *r++ = 0;
  211847. }
  211848. // sometimes the read fails for just the very last couple of blocks, so
  211849. // we'll ignore and errors in the last half-second of the disk..
  211850. ok = startSampleInFile > (trackStartSamples [getNumTracks()] - 20000);
  211851. break;
  211852. }
  211853. }
  211854. }
  211855. return ok;
  211856. }
  211857. bool AudioCDReader::isCDStillPresent() const
  211858. {
  211859. using namespace CDReaderHelpers;
  211860. TOC toc;
  211861. zerostruct (toc);
  211862. return ((CDDeviceWrapper*) handle)->cdH->readTOC (&toc);
  211863. }
  211864. void AudioCDReader::refreshTrackLengths()
  211865. {
  211866. using namespace CDReaderHelpers;
  211867. trackStartSamples.clear();
  211868. zeromem (audioTracks, sizeof (audioTracks));
  211869. TOC toc;
  211870. zerostruct (toc);
  211871. if (((CDDeviceWrapper*)handle)->cdH->readTOC (&toc))
  211872. {
  211873. int numTracks = 1 + toc.lastTrack - toc.firstTrack;
  211874. for (int i = 0; i <= numTracks; ++i)
  211875. {
  211876. trackStartSamples.add (samplesPerFrame * getAddressOf (&toc.tracks [i]));
  211877. audioTracks [i] = ((toc.tracks[i].ADR & 4) == 0);
  211878. }
  211879. }
  211880. lengthInSamples = getPositionOfTrackStart (getNumTracks());
  211881. }
  211882. bool AudioCDReader::isTrackAudio (int trackNum) const
  211883. {
  211884. return trackNum >= 0 && trackNum < getNumTracks() && audioTracks [trackNum];
  211885. }
  211886. void AudioCDReader::enableIndexScanning (bool b)
  211887. {
  211888. indexingEnabled = b;
  211889. }
  211890. int AudioCDReader::getLastIndex() const
  211891. {
  211892. return lastIndex;
  211893. }
  211894. const int framesPerIndexRead = 4;
  211895. int AudioCDReader::getIndexAt (int samplePos)
  211896. {
  211897. using namespace CDReaderHelpers;
  211898. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  211899. const int frameNeeded = samplePos / samplesPerFrame;
  211900. device->overlapBuffer->dataLength = 0;
  211901. device->overlapBuffer->startFrame = 0;
  211902. device->overlapBuffer->numFrames = 0;
  211903. device->jitter = false;
  211904. firstFrameInBuffer = 0;
  211905. lastIndex = 0;
  211906. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  211907. readBuffer.wantsIndex = true;
  211908. int i;
  211909. for (i = 5; --i >= 0;)
  211910. {
  211911. readBuffer.startFrame = frameNeeded;
  211912. readBuffer.numFrames = framesPerIndexRead;
  211913. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  211914. break;
  211915. }
  211916. if (i >= 0)
  211917. return readBuffer.index;
  211918. return -1;
  211919. }
  211920. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  211921. {
  211922. using namespace CDReaderHelpers;
  211923. Array <int> indexes;
  211924. const int trackStart = getPositionOfTrackStart (trackNumber);
  211925. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  211926. bool needToScan = true;
  211927. if (trackEnd - trackStart > 20 * 44100)
  211928. {
  211929. // check the end of the track for indexes before scanning the whole thing
  211930. needToScan = false;
  211931. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  211932. bool seenAnIndex = false;
  211933. while (pos <= trackEnd - samplesPerFrame)
  211934. {
  211935. const int index = getIndexAt (pos);
  211936. if (index == 0)
  211937. {
  211938. // lead-out, so skip back a bit if we've not found any indexes yet..
  211939. if (seenAnIndex)
  211940. break;
  211941. pos -= 44100 * 5;
  211942. if (pos < trackStart)
  211943. break;
  211944. }
  211945. else
  211946. {
  211947. if (index > 0)
  211948. seenAnIndex = true;
  211949. if (index > 1)
  211950. {
  211951. needToScan = true;
  211952. break;
  211953. }
  211954. pos += samplesPerFrame * framesPerIndexRead;
  211955. }
  211956. }
  211957. }
  211958. if (needToScan)
  211959. {
  211960. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  211961. int pos = trackStart;
  211962. int last = -1;
  211963. while (pos < trackEnd - samplesPerFrame * 10)
  211964. {
  211965. const int frameNeeded = pos / samplesPerFrame;
  211966. device->overlapBuffer->dataLength = 0;
  211967. device->overlapBuffer->startFrame = 0;
  211968. device->overlapBuffer->numFrames = 0;
  211969. device->jitter = false;
  211970. firstFrameInBuffer = 0;
  211971. CDReadBuffer readBuffer (4);
  211972. readBuffer.wantsIndex = true;
  211973. int i;
  211974. for (i = 5; --i >= 0;)
  211975. {
  211976. readBuffer.startFrame = frameNeeded;
  211977. readBuffer.numFrames = framesPerIndexRead;
  211978. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  211979. break;
  211980. }
  211981. if (i < 0)
  211982. break;
  211983. if (readBuffer.index > last && readBuffer.index > 1)
  211984. {
  211985. last = readBuffer.index;
  211986. indexes.add (pos);
  211987. }
  211988. pos += samplesPerFrame * framesPerIndexRead;
  211989. }
  211990. indexes.removeValue (trackStart);
  211991. }
  211992. return indexes;
  211993. }
  211994. void AudioCDReader::ejectDisk()
  211995. {
  211996. using namespace CDReaderHelpers;
  211997. ((CDDeviceWrapper*) handle)->cdH->openDrawer (true);
  211998. }
  211999. #endif
  212000. #if JUCE_USE_CDBURNER
  212001. static IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  212002. {
  212003. CoInitialize (0);
  212004. IDiscMaster* dm;
  212005. IDiscRecorder* result = 0;
  212006. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  212007. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  212008. IID_IDiscMaster,
  212009. (void**) &dm)))
  212010. {
  212011. if (SUCCEEDED (dm->Open()))
  212012. {
  212013. IEnumDiscRecorders* drEnum = 0;
  212014. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  212015. {
  212016. IDiscRecorder* dr = 0;
  212017. DWORD dummy;
  212018. int index = 0;
  212019. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  212020. {
  212021. if (indexToOpen == index)
  212022. {
  212023. result = dr;
  212024. break;
  212025. }
  212026. else if (list != 0)
  212027. {
  212028. BSTR path;
  212029. if (SUCCEEDED (dr->GetPath (&path)))
  212030. list->add ((const WCHAR*) path);
  212031. }
  212032. ++index;
  212033. dr->Release();
  212034. }
  212035. drEnum->Release();
  212036. }
  212037. if (master == 0)
  212038. dm->Close();
  212039. }
  212040. if (master != 0)
  212041. *master = dm;
  212042. else
  212043. dm->Release();
  212044. }
  212045. return result;
  212046. }
  212047. class AudioCDBurner::Pimpl : public ComBaseClassHelper <IDiscMasterProgressEvents>,
  212048. public Timer
  212049. {
  212050. public:
  212051. Pimpl (AudioCDBurner& owner_, IDiscMaster* discMaster_, IDiscRecorder* discRecorder_)
  212052. : owner (owner_), discMaster (discMaster_), discRecorder (discRecorder_), redbook (0),
  212053. listener (0), progress (0), shouldCancel (false)
  212054. {
  212055. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  212056. jassert (SUCCEEDED (hr));
  212057. hr = discMaster->SetActiveDiscRecorder (discRecorder);
  212058. //jassert (SUCCEEDED (hr));
  212059. lastState = getDiskState();
  212060. startTimer (2000);
  212061. }
  212062. ~Pimpl() {}
  212063. void releaseObjects()
  212064. {
  212065. discRecorder->Close();
  212066. if (redbook != 0)
  212067. redbook->Release();
  212068. discRecorder->Release();
  212069. discMaster->Release();
  212070. Release();
  212071. }
  212072. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  212073. {
  212074. if (listener != 0 && ! shouldCancel)
  212075. shouldCancel = listener->audioCDBurnProgress (progress);
  212076. *pbCancel = shouldCancel;
  212077. return S_OK;
  212078. }
  212079. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  212080. {
  212081. progress = nCompleted / (float) nTotal;
  212082. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  212083. return E_NOTIMPL;
  212084. }
  212085. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  212086. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  212087. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  212088. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  212089. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  212090. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  212091. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  212092. class ScopedDiscOpener
  212093. {
  212094. public:
  212095. ScopedDiscOpener (Pimpl& p) : pimpl (p) { pimpl.discRecorder->OpenExclusive(); }
  212096. ~ScopedDiscOpener() { pimpl.discRecorder->Close(); }
  212097. private:
  212098. Pimpl& pimpl;
  212099. ScopedDiscOpener (const ScopedDiscOpener&);
  212100. ScopedDiscOpener& operator= (const ScopedDiscOpener&);
  212101. };
  212102. DiskState getDiskState()
  212103. {
  212104. const ScopedDiscOpener opener (*this);
  212105. long type, flags;
  212106. HRESULT hr = discRecorder->QueryMediaType (&type, &flags);
  212107. if (FAILED (hr))
  212108. return unknown;
  212109. if (type != 0 && (flags & MEDIA_WRITABLE) != 0)
  212110. return writableDiskPresent;
  212111. if (type == 0)
  212112. return noDisc;
  212113. else
  212114. return readOnlyDiskPresent;
  212115. }
  212116. int getIntProperty (const LPOLESTR name, const int defaultReturn) const
  212117. {
  212118. ComSmartPtr<IPropertyStorage> prop;
  212119. if (FAILED (discRecorder->GetRecorderProperties (prop.resetAndGetPointerAddress())))
  212120. return defaultReturn;
  212121. PROPSPEC iPropSpec;
  212122. iPropSpec.ulKind = PRSPEC_LPWSTR;
  212123. iPropSpec.lpwstr = name;
  212124. PROPVARIANT iPropVariant;
  212125. return FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant))
  212126. ? defaultReturn : (int) iPropVariant.lVal;
  212127. }
  212128. bool setIntProperty (const LPOLESTR name, const int value) const
  212129. {
  212130. ComSmartPtr<IPropertyStorage> prop;
  212131. if (FAILED (discRecorder->GetRecorderProperties (prop.resetAndGetPointerAddress())))
  212132. return false;
  212133. PROPSPEC iPropSpec;
  212134. iPropSpec.ulKind = PRSPEC_LPWSTR;
  212135. iPropSpec.lpwstr = name;
  212136. PROPVARIANT iPropVariant;
  212137. if (FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant)))
  212138. return false;
  212139. iPropVariant.lVal = (long) value;
  212140. return SUCCEEDED (prop->WriteMultiple (1, &iPropSpec, &iPropVariant, iPropVariant.vt))
  212141. && SUCCEEDED (discRecorder->SetRecorderProperties (prop));
  212142. }
  212143. void timerCallback()
  212144. {
  212145. const DiskState state = getDiskState();
  212146. if (state != lastState)
  212147. {
  212148. lastState = state;
  212149. owner.sendChangeMessage (&owner);
  212150. }
  212151. }
  212152. AudioCDBurner& owner;
  212153. DiskState lastState;
  212154. IDiscMaster* discMaster;
  212155. IDiscRecorder* discRecorder;
  212156. IRedbookDiscMaster* redbook;
  212157. AudioCDBurner::BurnProgressListener* listener;
  212158. float progress;
  212159. bool shouldCancel;
  212160. };
  212161. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  212162. {
  212163. IDiscMaster* discMaster = 0;
  212164. IDiscRecorder* discRecorder = enumCDBurners (0, deviceIndex, &discMaster);
  212165. if (discRecorder != 0)
  212166. pimpl = new Pimpl (*this, discMaster, discRecorder);
  212167. }
  212168. AudioCDBurner::~AudioCDBurner()
  212169. {
  212170. if (pimpl != 0)
  212171. pimpl.release()->releaseObjects();
  212172. }
  212173. const StringArray AudioCDBurner::findAvailableDevices()
  212174. {
  212175. StringArray devs;
  212176. enumCDBurners (&devs, -1, 0);
  212177. return devs;
  212178. }
  212179. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  212180. {
  212181. ScopedPointer<AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  212182. if (b->pimpl == 0)
  212183. b = 0;
  212184. return b.release();
  212185. }
  212186. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  212187. {
  212188. return pimpl->getDiskState();
  212189. }
  212190. bool AudioCDBurner::isDiskPresent() const
  212191. {
  212192. return getDiskState() == writableDiskPresent;
  212193. }
  212194. bool AudioCDBurner::openTray()
  212195. {
  212196. const Pimpl::ScopedDiscOpener opener (*pimpl);
  212197. return SUCCEEDED (pimpl->discRecorder->Eject());
  212198. }
  212199. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  212200. {
  212201. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  212202. DiskState oldState = getDiskState();
  212203. DiskState newState = oldState;
  212204. while (newState == oldState && Time::currentTimeMillis() < timeout)
  212205. {
  212206. newState = getDiskState();
  212207. Thread::sleep (jmin (250, (int) (timeout - Time::currentTimeMillis())));
  212208. }
  212209. return newState;
  212210. }
  212211. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  212212. {
  212213. Array<int> results;
  212214. const int maxSpeed = pimpl->getIntProperty (L"MaxWriteSpeed", 1);
  212215. const int speeds[] = { 1, 2, 4, 8, 12, 16, 20, 24, 32, 40, 64, 80 };
  212216. for (int i = 0; i < numElementsInArray (speeds); ++i)
  212217. if (speeds[i] <= maxSpeed)
  212218. results.add (speeds[i]);
  212219. results.addIfNotAlreadyThere (maxSpeed);
  212220. return results;
  212221. }
  212222. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  212223. {
  212224. if (pimpl->getIntProperty (L"BufferUnderrunFreeCapable", 0) == 0)
  212225. return false;
  212226. pimpl->setIntProperty (L"EnableBufferUnderrunFree", shouldBeEnabled ? -1 : 0);
  212227. return pimpl->getIntProperty (L"EnableBufferUnderrunFree", 0) != 0;
  212228. }
  212229. int AudioCDBurner::getNumAvailableAudioBlocks() const
  212230. {
  212231. long blocksFree = 0;
  212232. pimpl->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  212233. return blocksFree;
  212234. }
  212235. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener, bool ejectDiscAfterwards,
  212236. bool performFakeBurnForTesting, int writeSpeed)
  212237. {
  212238. pimpl->setIntProperty (L"WriteSpeed", writeSpeed > 0 ? writeSpeed : -1);
  212239. pimpl->listener = listener;
  212240. pimpl->progress = 0;
  212241. pimpl->shouldCancel = false;
  212242. UINT_PTR cookie;
  212243. HRESULT hr = pimpl->discMaster->ProgressAdvise ((AudioCDBurner::Pimpl*) pimpl, &cookie);
  212244. hr = pimpl->discMaster->RecordDisc (performFakeBurnForTesting,
  212245. ejectDiscAfterwards);
  212246. String error;
  212247. if (hr != S_OK)
  212248. {
  212249. const char* e = "Couldn't open or write to the CD device";
  212250. if (hr == IMAPI_E_USERABORT)
  212251. e = "User cancelled the write operation";
  212252. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  212253. e = "No Disk present";
  212254. error = e;
  212255. }
  212256. pimpl->discMaster->ProgressUnadvise (cookie);
  212257. pimpl->listener = 0;
  212258. return error;
  212259. }
  212260. bool AudioCDBurner::addAudioTrack (AudioSource* audioSource, int numSamples)
  212261. {
  212262. if (audioSource == 0)
  212263. return false;
  212264. ScopedPointer<AudioSource> source (audioSource);
  212265. long bytesPerBlock;
  212266. HRESULT hr = pimpl->redbook->GetAudioBlockSize (&bytesPerBlock);
  212267. const int samplesPerBlock = bytesPerBlock / 4;
  212268. bool ok = true;
  212269. hr = pimpl->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  212270. HeapBlock <byte> buffer (bytesPerBlock);
  212271. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  212272. int samplesDone = 0;
  212273. source->prepareToPlay (samplesPerBlock, 44100.0);
  212274. while (ok)
  212275. {
  212276. {
  212277. AudioSourceChannelInfo info;
  212278. info.buffer = &sourceBuffer;
  212279. info.numSamples = samplesPerBlock;
  212280. info.startSample = 0;
  212281. sourceBuffer.clear();
  212282. source->getNextAudioBlock (info);
  212283. }
  212284. zeromem (buffer, bytesPerBlock);
  212285. typedef AudioData::Pointer <AudioData::Int16, AudioData::LittleEndian,
  212286. AudioData::Interleaved, AudioData::NonConst> CDSampleFormat;
  212287. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian,
  212288. AudioData::NonInterleaved, AudioData::Const> SourceSampleFormat;
  212289. CDSampleFormat left (buffer, 2);
  212290. left.convertSamples (SourceSampleFormat (sourceBuffer.getSampleData (0)), samplesPerBlock);
  212291. CDSampleFormat right (buffer + 2, 2);
  212292. right.convertSamples (SourceSampleFormat (sourceBuffer.getSampleData (1)), samplesPerBlock);
  212293. hr = pimpl->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  212294. if (FAILED (hr))
  212295. ok = false;
  212296. samplesDone += samplesPerBlock;
  212297. if (samplesDone >= numSamples)
  212298. break;
  212299. }
  212300. hr = pimpl->redbook->CloseAudioTrack();
  212301. return ok && hr == S_OK;
  212302. }
  212303. #endif
  212304. #endif
  212305. /*** End of inlined file: juce_win32_AudioCDReader.cpp ***/
  212306. /*** Start of inlined file: juce_win32_Midi.cpp ***/
  212307. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212308. // compiled on its own).
  212309. #if JUCE_INCLUDED_FILE
  212310. class MidiInCollector
  212311. {
  212312. public:
  212313. MidiInCollector (MidiInput* const input_,
  212314. MidiInputCallback& callback_)
  212315. : deviceHandle (0),
  212316. input (input_),
  212317. callback (callback_),
  212318. concatenator (4096),
  212319. isStarted (false),
  212320. startTime (0)
  212321. {
  212322. }
  212323. ~MidiInCollector()
  212324. {
  212325. stop();
  212326. if (deviceHandle != 0)
  212327. {
  212328. int count = 5;
  212329. while (--count >= 0)
  212330. {
  212331. if (midiInClose (deviceHandle) == MMSYSERR_NOERROR)
  212332. break;
  212333. Sleep (20);
  212334. }
  212335. }
  212336. }
  212337. void handleMessage (const uint32 message, const uint32 timeStamp)
  212338. {
  212339. if ((message & 0xff) >= 0x80 && isStarted)
  212340. {
  212341. concatenator.pushMidiData (&message, 3, convertTimeStamp (timeStamp), input, callback);
  212342. writeFinishedBlocks();
  212343. }
  212344. }
  212345. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp)
  212346. {
  212347. if (isStarted)
  212348. {
  212349. concatenator.pushMidiData (hdr->lpData, hdr->dwBytesRecorded, convertTimeStamp (timeStamp), input, callback);
  212350. writeFinishedBlocks();
  212351. }
  212352. }
  212353. void start()
  212354. {
  212355. jassert (deviceHandle != 0);
  212356. if (deviceHandle != 0 && ! isStarted)
  212357. {
  212358. activeMidiCollectors.addIfNotAlreadyThere (this);
  212359. for (int i = 0; i < (int) numHeaders; ++i)
  212360. headers[i].write (deviceHandle);
  212361. startTime = Time::getMillisecondCounter();
  212362. MMRESULT res = midiInStart (deviceHandle);
  212363. if (res == MMSYSERR_NOERROR)
  212364. {
  212365. concatenator.reset();
  212366. isStarted = true;
  212367. }
  212368. else
  212369. {
  212370. unprepareAllHeaders();
  212371. }
  212372. }
  212373. }
  212374. void stop()
  212375. {
  212376. if (isStarted)
  212377. {
  212378. isStarted = false;
  212379. midiInReset (deviceHandle);
  212380. midiInStop (deviceHandle);
  212381. activeMidiCollectors.removeValue (this);
  212382. unprepareAllHeaders();
  212383. concatenator.reset();
  212384. }
  212385. }
  212386. static void CALLBACK midiInCallback (HMIDIIN, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR midiMessage, DWORD_PTR timeStamp)
  212387. {
  212388. MidiInCollector* const collector = reinterpret_cast <MidiInCollector*> (dwInstance);
  212389. if (activeMidiCollectors.contains (collector))
  212390. {
  212391. if (uMsg == MIM_DATA)
  212392. collector->handleMessage ((uint32) midiMessage, (uint32) timeStamp);
  212393. else if (uMsg == MIM_LONGDATA)
  212394. collector->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  212395. }
  212396. }
  212397. juce_UseDebuggingNewOperator
  212398. HMIDIIN deviceHandle;
  212399. private:
  212400. static Array <MidiInCollector*, CriticalSection> activeMidiCollectors;
  212401. MidiInput* input;
  212402. MidiInputCallback& callback;
  212403. MidiDataConcatenator concatenator;
  212404. bool volatile isStarted;
  212405. uint32 startTime;
  212406. class MidiHeader
  212407. {
  212408. public:
  212409. MidiHeader()
  212410. {
  212411. zerostruct (hdr);
  212412. hdr.lpData = data;
  212413. hdr.dwBufferLength = numElementsInArray (data);
  212414. }
  212415. void write (HMIDIIN deviceHandle)
  212416. {
  212417. hdr.dwBytesRecorded = 0;
  212418. MMRESULT res = midiInPrepareHeader (deviceHandle, &hdr, sizeof (hdr));
  212419. res = midiInAddBuffer (deviceHandle, &hdr, sizeof (hdr));
  212420. }
  212421. void writeIfFinished (HMIDIIN deviceHandle)
  212422. {
  212423. if ((hdr.dwFlags & WHDR_DONE) != 0)
  212424. {
  212425. MMRESULT res = midiInUnprepareHeader (deviceHandle, &hdr, sizeof (hdr));
  212426. (void) res;
  212427. write (deviceHandle);
  212428. }
  212429. }
  212430. void unprepare (HMIDIIN deviceHandle)
  212431. {
  212432. if ((hdr.dwFlags & WHDR_DONE) != 0)
  212433. {
  212434. int c = 10;
  212435. while (--c >= 0 && midiInUnprepareHeader (deviceHandle, &hdr, sizeof (hdr)) == MIDIERR_STILLPLAYING)
  212436. Thread::sleep (20);
  212437. jassert (c >= 0);
  212438. }
  212439. }
  212440. private:
  212441. MIDIHDR hdr;
  212442. char data [256];
  212443. MidiHeader (const MidiHeader&);
  212444. MidiHeader& operator= (const MidiHeader&);
  212445. };
  212446. enum { numHeaders = 32 };
  212447. MidiHeader headers [numHeaders];
  212448. void writeFinishedBlocks()
  212449. {
  212450. for (int i = 0; i < (int) numHeaders; ++i)
  212451. headers[i].writeIfFinished (deviceHandle);
  212452. }
  212453. void unprepareAllHeaders()
  212454. {
  212455. for (int i = 0; i < (int) numHeaders; ++i)
  212456. headers[i].unprepare (deviceHandle);
  212457. }
  212458. double convertTimeStamp (uint32 timeStamp)
  212459. {
  212460. timeStamp += startTime;
  212461. const uint32 now = Time::getMillisecondCounter();
  212462. if (timeStamp > now)
  212463. {
  212464. if (timeStamp > now + 2)
  212465. --startTime;
  212466. timeStamp = now;
  212467. }
  212468. return timeStamp * 0.001;
  212469. }
  212470. MidiInCollector (const MidiInCollector&);
  212471. MidiInCollector& operator= (const MidiInCollector&);
  212472. };
  212473. Array <MidiInCollector*, CriticalSection> MidiInCollector::activeMidiCollectors;
  212474. const StringArray MidiInput::getDevices()
  212475. {
  212476. StringArray s;
  212477. const int num = midiInGetNumDevs();
  212478. for (int i = 0; i < num; ++i)
  212479. {
  212480. MIDIINCAPS mc;
  212481. zerostruct (mc);
  212482. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212483. s.add (String (mc.szPname, sizeof (mc.szPname)));
  212484. }
  212485. return s;
  212486. }
  212487. int MidiInput::getDefaultDeviceIndex()
  212488. {
  212489. return 0;
  212490. }
  212491. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  212492. {
  212493. if (callback == 0)
  212494. return 0;
  212495. UINT deviceId = MIDI_MAPPER;
  212496. int n = 0;
  212497. String name;
  212498. const int num = midiInGetNumDevs();
  212499. for (int i = 0; i < num; ++i)
  212500. {
  212501. MIDIINCAPS mc;
  212502. zerostruct (mc);
  212503. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212504. {
  212505. if (index == n)
  212506. {
  212507. deviceId = i;
  212508. name = String (mc.szPname, numElementsInArray (mc.szPname));
  212509. break;
  212510. }
  212511. ++n;
  212512. }
  212513. }
  212514. ScopedPointer <MidiInput> in (new MidiInput (name));
  212515. ScopedPointer <MidiInCollector> collector (new MidiInCollector (in, *callback));
  212516. HMIDIIN h;
  212517. HRESULT err = midiInOpen (&h, deviceId,
  212518. (DWORD_PTR) &MidiInCollector::midiInCallback,
  212519. (DWORD_PTR) (MidiInCollector*) collector,
  212520. CALLBACK_FUNCTION);
  212521. if (err == MMSYSERR_NOERROR)
  212522. {
  212523. collector->deviceHandle = h;
  212524. in->internal = collector.release();
  212525. return in.release();
  212526. }
  212527. return 0;
  212528. }
  212529. MidiInput::MidiInput (const String& name_)
  212530. : name (name_),
  212531. internal (0)
  212532. {
  212533. }
  212534. MidiInput::~MidiInput()
  212535. {
  212536. delete static_cast <MidiInCollector*> (internal);
  212537. }
  212538. void MidiInput::start()
  212539. {
  212540. static_cast <MidiInCollector*> (internal)->start();
  212541. }
  212542. void MidiInput::stop()
  212543. {
  212544. static_cast <MidiInCollector*> (internal)->stop();
  212545. }
  212546. struct MidiOutHandle
  212547. {
  212548. int refCount;
  212549. UINT deviceId;
  212550. HMIDIOUT handle;
  212551. static Array<MidiOutHandle*> activeHandles;
  212552. juce_UseDebuggingNewOperator
  212553. };
  212554. Array<MidiOutHandle*> MidiOutHandle::activeHandles;
  212555. const StringArray MidiOutput::getDevices()
  212556. {
  212557. StringArray s;
  212558. const int num = midiOutGetNumDevs();
  212559. for (int i = 0; i < num; ++i)
  212560. {
  212561. MIDIOUTCAPS mc;
  212562. zerostruct (mc);
  212563. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212564. s.add (String (mc.szPname, sizeof (mc.szPname)));
  212565. }
  212566. return s;
  212567. }
  212568. int MidiOutput::getDefaultDeviceIndex()
  212569. {
  212570. const int num = midiOutGetNumDevs();
  212571. int n = 0;
  212572. for (int i = 0; i < num; ++i)
  212573. {
  212574. MIDIOUTCAPS mc;
  212575. zerostruct (mc);
  212576. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212577. {
  212578. if ((mc.wTechnology & MOD_MAPPER) != 0)
  212579. return n;
  212580. ++n;
  212581. }
  212582. }
  212583. return 0;
  212584. }
  212585. MidiOutput* MidiOutput::openDevice (int index)
  212586. {
  212587. UINT deviceId = MIDI_MAPPER;
  212588. const int num = midiOutGetNumDevs();
  212589. int i, n = 0;
  212590. for (i = 0; i < num; ++i)
  212591. {
  212592. MIDIOUTCAPS mc;
  212593. zerostruct (mc);
  212594. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212595. {
  212596. // use the microsoft sw synth as a default - best not to allow deviceId
  212597. // to be MIDI_MAPPER, or else device sharing breaks
  212598. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase ("microsoft"))
  212599. deviceId = i;
  212600. if (index == n)
  212601. {
  212602. deviceId = i;
  212603. break;
  212604. }
  212605. ++n;
  212606. }
  212607. }
  212608. for (i = MidiOutHandle::activeHandles.size(); --i >= 0;)
  212609. {
  212610. MidiOutHandle* const han = MidiOutHandle::activeHandles.getUnchecked(i);
  212611. if (han != 0 && han->deviceId == deviceId)
  212612. {
  212613. han->refCount++;
  212614. MidiOutput* const out = new MidiOutput();
  212615. out->internal = han;
  212616. return out;
  212617. }
  212618. }
  212619. for (i = 4; --i >= 0;)
  212620. {
  212621. HMIDIOUT h = 0;
  212622. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  212623. if (res == MMSYSERR_NOERROR)
  212624. {
  212625. MidiOutHandle* const han = new MidiOutHandle();
  212626. han->deviceId = deviceId;
  212627. han->refCount = 1;
  212628. han->handle = h;
  212629. MidiOutHandle::activeHandles.add (han);
  212630. MidiOutput* const out = new MidiOutput();
  212631. out->internal = han;
  212632. return out;
  212633. }
  212634. else if (res == MMSYSERR_ALLOCATED)
  212635. {
  212636. Sleep (100);
  212637. }
  212638. else
  212639. {
  212640. break;
  212641. }
  212642. }
  212643. return 0;
  212644. }
  212645. MidiOutput::~MidiOutput()
  212646. {
  212647. MidiOutHandle* const h = static_cast <MidiOutHandle*> (internal);
  212648. if (MidiOutHandle::activeHandles.contains (h) && --(h->refCount) == 0)
  212649. {
  212650. midiOutClose (h->handle);
  212651. MidiOutHandle::activeHandles.removeValue (h);
  212652. delete h;
  212653. }
  212654. }
  212655. void MidiOutput::reset()
  212656. {
  212657. const MidiOutHandle* const h = static_cast <const MidiOutHandle*> (internal);
  212658. midiOutReset (h->handle);
  212659. }
  212660. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  212661. {
  212662. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  212663. DWORD n;
  212664. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  212665. {
  212666. const unsigned short* const nn = reinterpret_cast<const unsigned short*> (&n);
  212667. rightVol = nn[0] / (float) 0xffff;
  212668. leftVol = nn[1] / (float) 0xffff;
  212669. return true;
  212670. }
  212671. else
  212672. {
  212673. rightVol = leftVol = 1.0f;
  212674. return false;
  212675. }
  212676. }
  212677. void MidiOutput::setVolume (float leftVol, float rightVol)
  212678. {
  212679. const MidiOutHandle* const handle = static_cast <MidiOutHandle*> (internal);
  212680. DWORD n;
  212681. unsigned short* const nn = reinterpret_cast<unsigned short*> (&n);
  212682. nn[0] = (unsigned short) jlimit (0, 0xffff, (int) (rightVol * 0xffff));
  212683. nn[1] = (unsigned short) jlimit (0, 0xffff, (int) (leftVol * 0xffff));
  212684. midiOutSetVolume (handle->handle, n);
  212685. }
  212686. void MidiOutput::sendMessageNow (const MidiMessage& message)
  212687. {
  212688. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  212689. if (message.getRawDataSize() > 3
  212690. || message.isSysEx())
  212691. {
  212692. MIDIHDR h;
  212693. zerostruct (h);
  212694. h.lpData = (char*) message.getRawData();
  212695. h.dwBufferLength = message.getRawDataSize();
  212696. h.dwBytesRecorded = message.getRawDataSize();
  212697. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  212698. {
  212699. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  212700. if (res == MMSYSERR_NOERROR)
  212701. {
  212702. while ((h.dwFlags & MHDR_DONE) == 0)
  212703. Sleep (1);
  212704. int count = 500; // 1 sec timeout
  212705. while (--count >= 0)
  212706. {
  212707. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  212708. if (res == MIDIERR_STILLPLAYING)
  212709. Sleep (2);
  212710. else
  212711. break;
  212712. }
  212713. }
  212714. }
  212715. }
  212716. else
  212717. {
  212718. midiOutShortMsg (handle->handle,
  212719. *(unsigned int*) message.getRawData());
  212720. }
  212721. }
  212722. #endif
  212723. /*** End of inlined file: juce_win32_Midi.cpp ***/
  212724. /*** Start of inlined file: juce_win32_ASIO.cpp ***/
  212725. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212726. // compiled on its own).
  212727. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  212728. #undef WINDOWS
  212729. // #define ASIO_DEBUGGING 1
  212730. #if ASIO_DEBUGGING
  212731. #define log(a) { Logger::writeToLog (a); DBG (a) }
  212732. #else
  212733. #define log(a) {}
  212734. #endif
  212735. #if ASIO_DEBUGGING
  212736. static void logError (const String& context, long error)
  212737. {
  212738. String err ("unknown error");
  212739. if (error == ASE_NotPresent) err = "Not Present";
  212740. else if (error == ASE_HWMalfunction) err = "Hardware Malfunction";
  212741. else if (error == ASE_InvalidParameter) err = "Invalid Parameter";
  212742. else if (error == ASE_InvalidMode) err = "Invalid Mode";
  212743. else if (error == ASE_SPNotAdvancing) err = "Sample position not advancing";
  212744. else if (error == ASE_NoClock) err = "No Clock";
  212745. else if (error == ASE_NoMemory) err = "Out of memory";
  212746. log ("!!error: " + context + " - " + err);
  212747. }
  212748. #else
  212749. #define logError(a, b) {}
  212750. #endif
  212751. class ASIOAudioIODevice;
  212752. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  212753. static const int maxASIOChannels = 160;
  212754. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  212755. private Timer
  212756. {
  212757. public:
  212758. Component ourWindow;
  212759. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber,
  212760. const String& optionalDllForDirectLoading_)
  212761. : AudioIODevice (name_, "ASIO"),
  212762. asioObject (0),
  212763. classId (classId_),
  212764. optionalDllForDirectLoading (optionalDllForDirectLoading_),
  212765. currentBitDepth (16),
  212766. currentSampleRate (0),
  212767. isOpen_ (false),
  212768. isStarted (false),
  212769. postOutput (true),
  212770. insideControlPanelModalLoop (false),
  212771. shouldUsePreferredSize (false)
  212772. {
  212773. name = name_;
  212774. ourWindow.addToDesktop (0);
  212775. windowHandle = ourWindow.getWindowHandle();
  212776. jassert (currentASIODev [slotNumber] == 0);
  212777. currentASIODev [slotNumber] = this;
  212778. openDevice();
  212779. }
  212780. ~ASIOAudioIODevice()
  212781. {
  212782. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  212783. if (currentASIODev[i] == this)
  212784. currentASIODev[i] = 0;
  212785. close();
  212786. log ("ASIO - exiting");
  212787. removeCurrentDriver();
  212788. }
  212789. void updateSampleRates()
  212790. {
  212791. // find a list of sample rates..
  212792. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  212793. sampleRates.clear();
  212794. if (asioObject != 0)
  212795. {
  212796. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  212797. {
  212798. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  212799. if (err == 0)
  212800. {
  212801. sampleRates.add ((int) possibleSampleRates[index]);
  212802. log ("rate: " + String ((int) possibleSampleRates[index]));
  212803. }
  212804. else if (err != ASE_NoClock)
  212805. {
  212806. logError ("CanSampleRate", err);
  212807. }
  212808. }
  212809. if (sampleRates.size() == 0)
  212810. {
  212811. double cr = 0;
  212812. const long err = asioObject->getSampleRate (&cr);
  212813. log ("No sample rates supported - current rate: " + String ((int) cr));
  212814. if (err == 0)
  212815. sampleRates.add ((int) cr);
  212816. }
  212817. }
  212818. }
  212819. const StringArray getOutputChannelNames()
  212820. {
  212821. return outputChannelNames;
  212822. }
  212823. const StringArray getInputChannelNames()
  212824. {
  212825. return inputChannelNames;
  212826. }
  212827. int getNumSampleRates()
  212828. {
  212829. return sampleRates.size();
  212830. }
  212831. double getSampleRate (int index)
  212832. {
  212833. return sampleRates [index];
  212834. }
  212835. int getNumBufferSizesAvailable()
  212836. {
  212837. return bufferSizes.size();
  212838. }
  212839. int getBufferSizeSamples (int index)
  212840. {
  212841. return bufferSizes [index];
  212842. }
  212843. int getDefaultBufferSize()
  212844. {
  212845. return preferredSize;
  212846. }
  212847. const String open (const BigInteger& inputChannels,
  212848. const BigInteger& outputChannels,
  212849. double sr,
  212850. int bufferSizeSamples)
  212851. {
  212852. close();
  212853. currentCallback = 0;
  212854. if (bufferSizeSamples <= 0)
  212855. shouldUsePreferredSize = true;
  212856. if (asioObject == 0 || ! isASIOOpen)
  212857. {
  212858. log ("Warning: device not open");
  212859. const String err (openDevice());
  212860. if (asioObject == 0 || ! isASIOOpen)
  212861. return err;
  212862. }
  212863. isStarted = false;
  212864. bufferIndex = -1;
  212865. long err = 0;
  212866. long newPreferredSize = 0;
  212867. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  212868. minSize = 0;
  212869. maxSize = 0;
  212870. newPreferredSize = 0;
  212871. granularity = 0;
  212872. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  212873. {
  212874. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  212875. shouldUsePreferredSize = true;
  212876. preferredSize = newPreferredSize;
  212877. }
  212878. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  212879. // dynamic changes to the buffer size...
  212880. shouldUsePreferredSize = shouldUsePreferredSize
  212881. || getName().containsIgnoreCase ("Digidesign");
  212882. if (shouldUsePreferredSize)
  212883. {
  212884. log ("Using preferred size for buffer..");
  212885. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  212886. {
  212887. bufferSizeSamples = preferredSize;
  212888. }
  212889. else
  212890. {
  212891. bufferSizeSamples = 1024;
  212892. logError ("GetBufferSize1", err);
  212893. }
  212894. shouldUsePreferredSize = false;
  212895. }
  212896. int sampleRate = roundDoubleToInt (sr);
  212897. currentSampleRate = sampleRate;
  212898. currentBlockSizeSamples = bufferSizeSamples;
  212899. currentChansOut.clear();
  212900. currentChansIn.clear();
  212901. zeromem (inBuffers, sizeof (inBuffers));
  212902. zeromem (outBuffers, sizeof (outBuffers));
  212903. updateSampleRates();
  212904. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  212905. sampleRate = sampleRates[0];
  212906. jassert (sampleRate != 0);
  212907. if (sampleRate == 0)
  212908. sampleRate = 44100;
  212909. long numSources = 32;
  212910. ASIOClockSource clocks[32];
  212911. zeromem (clocks, sizeof (clocks));
  212912. asioObject->getClockSources (clocks, &numSources);
  212913. bool isSourceSet = false;
  212914. // careful not to remove this loop because it does more than just logging!
  212915. int i;
  212916. for (i = 0; i < numSources; ++i)
  212917. {
  212918. String s ("clock: ");
  212919. s += clocks[i].name;
  212920. if (clocks[i].isCurrentSource)
  212921. {
  212922. isSourceSet = true;
  212923. s << " (cur)";
  212924. }
  212925. log (s);
  212926. }
  212927. if (numSources > 1 && ! isSourceSet)
  212928. {
  212929. log ("setting clock source");
  212930. asioObject->setClockSource (clocks[0].index);
  212931. Thread::sleep (20);
  212932. }
  212933. else
  212934. {
  212935. if (numSources == 0)
  212936. {
  212937. log ("ASIO - no clock sources!");
  212938. }
  212939. }
  212940. double cr = 0;
  212941. err = asioObject->getSampleRate (&cr);
  212942. if (err == 0)
  212943. {
  212944. currentSampleRate = cr;
  212945. }
  212946. else
  212947. {
  212948. logError ("GetSampleRate", err);
  212949. currentSampleRate = 0;
  212950. }
  212951. error = String::empty;
  212952. needToReset = false;
  212953. isReSync = false;
  212954. err = 0;
  212955. bool buffersCreated = false;
  212956. if (currentSampleRate != sampleRate)
  212957. {
  212958. log ("ASIO samplerate: " + String (currentSampleRate) + " to " + String (sampleRate));
  212959. err = asioObject->setSampleRate (sampleRate);
  212960. if (err == ASE_NoClock && numSources > 0)
  212961. {
  212962. log ("trying to set a clock source..");
  212963. Thread::sleep (10);
  212964. err = asioObject->setClockSource (clocks[0].index);
  212965. if (err != 0)
  212966. {
  212967. logError ("SetClock", err);
  212968. }
  212969. Thread::sleep (10);
  212970. err = asioObject->setSampleRate (sampleRate);
  212971. }
  212972. }
  212973. if (err == 0)
  212974. {
  212975. currentSampleRate = sampleRate;
  212976. if (needToReset)
  212977. {
  212978. if (isReSync)
  212979. {
  212980. log ("Resync request");
  212981. }
  212982. log ("! Resetting ASIO after sample rate change");
  212983. removeCurrentDriver();
  212984. loadDriver();
  212985. const String error (initDriver());
  212986. if (error.isNotEmpty())
  212987. {
  212988. log ("ASIOInit: " + error);
  212989. }
  212990. needToReset = false;
  212991. isReSync = false;
  212992. }
  212993. numActiveInputChans = 0;
  212994. numActiveOutputChans = 0;
  212995. ASIOBufferInfo* info = bufferInfos;
  212996. int i;
  212997. for (i = 0; i < totalNumInputChans; ++i)
  212998. {
  212999. if (inputChannels[i])
  213000. {
  213001. currentChansIn.setBit (i);
  213002. info->isInput = 1;
  213003. info->channelNum = i;
  213004. info->buffers[0] = info->buffers[1] = 0;
  213005. ++info;
  213006. ++numActiveInputChans;
  213007. }
  213008. }
  213009. for (i = 0; i < totalNumOutputChans; ++i)
  213010. {
  213011. if (outputChannels[i])
  213012. {
  213013. currentChansOut.setBit (i);
  213014. info->isInput = 0;
  213015. info->channelNum = i;
  213016. info->buffers[0] = info->buffers[1] = 0;
  213017. ++info;
  213018. ++numActiveOutputChans;
  213019. }
  213020. }
  213021. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  213022. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  213023. if (currentASIODev[0] == this)
  213024. {
  213025. callbacks.bufferSwitch = &bufferSwitchCallback0;
  213026. callbacks.asioMessage = &asioMessagesCallback0;
  213027. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  213028. }
  213029. else if (currentASIODev[1] == this)
  213030. {
  213031. callbacks.bufferSwitch = &bufferSwitchCallback1;
  213032. callbacks.asioMessage = &asioMessagesCallback1;
  213033. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  213034. }
  213035. else if (currentASIODev[2] == this)
  213036. {
  213037. callbacks.bufferSwitch = &bufferSwitchCallback2;
  213038. callbacks.asioMessage = &asioMessagesCallback2;
  213039. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  213040. }
  213041. else
  213042. {
  213043. jassertfalse;
  213044. }
  213045. log ("disposing buffers");
  213046. err = asioObject->disposeBuffers();
  213047. log ("creating buffers: " + String (totalBuffers) + ", " + String (currentBlockSizeSamples));
  213048. err = asioObject->createBuffers (bufferInfos,
  213049. totalBuffers,
  213050. currentBlockSizeSamples,
  213051. &callbacks);
  213052. if (err != 0)
  213053. {
  213054. currentBlockSizeSamples = preferredSize;
  213055. logError ("create buffers 2", err);
  213056. asioObject->disposeBuffers();
  213057. err = asioObject->createBuffers (bufferInfos,
  213058. totalBuffers,
  213059. currentBlockSizeSamples,
  213060. &callbacks);
  213061. }
  213062. if (err == 0)
  213063. {
  213064. buffersCreated = true;
  213065. tempBuffer.calloc (totalBuffers * currentBlockSizeSamples + 32);
  213066. int n = 0;
  213067. Array <int> types;
  213068. currentBitDepth = 16;
  213069. for (i = 0; i < jmin ((int) totalNumInputChans, maxASIOChannels); ++i)
  213070. {
  213071. if (inputChannels[i])
  213072. {
  213073. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  213074. ASIOChannelInfo channelInfo;
  213075. zerostruct (channelInfo);
  213076. channelInfo.channel = i;
  213077. channelInfo.isInput = 1;
  213078. asioObject->getChannelInfo (&channelInfo);
  213079. types.addIfNotAlreadyThere (channelInfo.type);
  213080. typeToFormatParameters (channelInfo.type,
  213081. inputChannelBitDepths[n],
  213082. inputChannelBytesPerSample[n],
  213083. inputChannelIsFloat[n],
  213084. inputChannelLittleEndian[n]);
  213085. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  213086. ++n;
  213087. }
  213088. }
  213089. jassert (numActiveInputChans == n);
  213090. n = 0;
  213091. for (i = 0; i < jmin ((int) totalNumOutputChans, maxASIOChannels); ++i)
  213092. {
  213093. if (outputChannels[i])
  213094. {
  213095. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  213096. ASIOChannelInfo channelInfo;
  213097. zerostruct (channelInfo);
  213098. channelInfo.channel = i;
  213099. channelInfo.isInput = 0;
  213100. asioObject->getChannelInfo (&channelInfo);
  213101. types.addIfNotAlreadyThere (channelInfo.type);
  213102. typeToFormatParameters (channelInfo.type,
  213103. outputChannelBitDepths[n],
  213104. outputChannelBytesPerSample[n],
  213105. outputChannelIsFloat[n],
  213106. outputChannelLittleEndian[n]);
  213107. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  213108. ++n;
  213109. }
  213110. }
  213111. jassert (numActiveOutputChans == n);
  213112. for (i = types.size(); --i >= 0;)
  213113. {
  213114. log ("channel format: " + String (types[i]));
  213115. }
  213116. jassert (n <= totalBuffers);
  213117. for (i = 0; i < numActiveOutputChans; ++i)
  213118. {
  213119. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  213120. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  213121. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  213122. {
  213123. log ("!! Null buffers");
  213124. }
  213125. else
  213126. {
  213127. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  213128. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  213129. }
  213130. }
  213131. inputLatency = outputLatency = 0;
  213132. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  213133. {
  213134. log ("ASIO - no latencies");
  213135. }
  213136. else
  213137. {
  213138. log ("ASIO latencies: " + String ((int) outputLatency) + ", " + String ((int) inputLatency));
  213139. }
  213140. isOpen_ = true;
  213141. log ("starting ASIO");
  213142. calledback = false;
  213143. err = asioObject->start();
  213144. if (err != 0)
  213145. {
  213146. isOpen_ = false;
  213147. log ("ASIO - stop on failure");
  213148. Thread::sleep (10);
  213149. asioObject->stop();
  213150. error = "Can't start device";
  213151. Thread::sleep (10);
  213152. }
  213153. else
  213154. {
  213155. int count = 300;
  213156. while (--count > 0 && ! calledback)
  213157. Thread::sleep (10);
  213158. isStarted = true;
  213159. if (! calledback)
  213160. {
  213161. error = "Device didn't start correctly";
  213162. log ("ASIO didn't callback - stopping..");
  213163. asioObject->stop();
  213164. }
  213165. }
  213166. }
  213167. else
  213168. {
  213169. error = "Can't create i/o buffers";
  213170. }
  213171. }
  213172. else
  213173. {
  213174. error = "Can't set sample rate: ";
  213175. error << sampleRate;
  213176. }
  213177. if (error.isNotEmpty())
  213178. {
  213179. logError (error, err);
  213180. if (asioObject != 0 && buffersCreated)
  213181. asioObject->disposeBuffers();
  213182. Thread::sleep (20);
  213183. isStarted = false;
  213184. isOpen_ = false;
  213185. const String errorCopy (error);
  213186. close(); // (this resets the error string)
  213187. error = errorCopy;
  213188. }
  213189. needToReset = false;
  213190. isReSync = false;
  213191. return error;
  213192. }
  213193. void close()
  213194. {
  213195. error = String::empty;
  213196. stopTimer();
  213197. stop();
  213198. if (isASIOOpen && isOpen_)
  213199. {
  213200. const ScopedLock sl (callbackLock);
  213201. isOpen_ = false;
  213202. isStarted = false;
  213203. needToReset = false;
  213204. isReSync = false;
  213205. log ("ASIO - stopping");
  213206. if (asioObject != 0)
  213207. {
  213208. Thread::sleep (20);
  213209. asioObject->stop();
  213210. Thread::sleep (10);
  213211. asioObject->disposeBuffers();
  213212. }
  213213. Thread::sleep (10);
  213214. }
  213215. }
  213216. bool isOpen()
  213217. {
  213218. return isOpen_ || insideControlPanelModalLoop;
  213219. }
  213220. int getCurrentBufferSizeSamples()
  213221. {
  213222. return currentBlockSizeSamples;
  213223. }
  213224. double getCurrentSampleRate()
  213225. {
  213226. return currentSampleRate;
  213227. }
  213228. const BigInteger getActiveOutputChannels() const
  213229. {
  213230. return currentChansOut;
  213231. }
  213232. const BigInteger getActiveInputChannels() const
  213233. {
  213234. return currentChansIn;
  213235. }
  213236. int getCurrentBitDepth()
  213237. {
  213238. return currentBitDepth;
  213239. }
  213240. int getOutputLatencyInSamples()
  213241. {
  213242. return outputLatency + currentBlockSizeSamples / 4;
  213243. }
  213244. int getInputLatencyInSamples()
  213245. {
  213246. return inputLatency + currentBlockSizeSamples / 4;
  213247. }
  213248. void start (AudioIODeviceCallback* callback)
  213249. {
  213250. if (callback != 0)
  213251. {
  213252. callback->audioDeviceAboutToStart (this);
  213253. const ScopedLock sl (callbackLock);
  213254. currentCallback = callback;
  213255. }
  213256. }
  213257. void stop()
  213258. {
  213259. AudioIODeviceCallback* const lastCallback = currentCallback;
  213260. {
  213261. const ScopedLock sl (callbackLock);
  213262. currentCallback = 0;
  213263. }
  213264. if (lastCallback != 0)
  213265. lastCallback->audioDeviceStopped();
  213266. }
  213267. bool isPlaying()
  213268. {
  213269. return isASIOOpen && (currentCallback != 0);
  213270. }
  213271. const String getLastError()
  213272. {
  213273. return error;
  213274. }
  213275. bool hasControlPanel() const
  213276. {
  213277. return true;
  213278. }
  213279. bool showControlPanel()
  213280. {
  213281. log ("ASIO - showing control panel");
  213282. Component modalWindow (String::empty);
  213283. modalWindow.setOpaque (true);
  213284. modalWindow.addToDesktop (0);
  213285. modalWindow.enterModalState();
  213286. bool done = false;
  213287. JUCE_TRY
  213288. {
  213289. // are there are devices that need to be closed before showing their control panel?
  213290. // close();
  213291. insideControlPanelModalLoop = true;
  213292. const uint32 started = Time::getMillisecondCounter();
  213293. if (asioObject != 0)
  213294. {
  213295. asioObject->controlPanel();
  213296. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  213297. log ("spent: " + String (spent));
  213298. if (spent > 300)
  213299. {
  213300. shouldUsePreferredSize = true;
  213301. done = true;
  213302. }
  213303. }
  213304. }
  213305. JUCE_CATCH_ALL
  213306. insideControlPanelModalLoop = false;
  213307. return done;
  213308. }
  213309. void resetRequest() throw()
  213310. {
  213311. needToReset = true;
  213312. }
  213313. void resyncRequest() throw()
  213314. {
  213315. needToReset = true;
  213316. isReSync = true;
  213317. }
  213318. void timerCallback()
  213319. {
  213320. if (! insideControlPanelModalLoop)
  213321. {
  213322. stopTimer();
  213323. // used to cause a reset
  213324. log ("! ASIO restart request!");
  213325. if (isOpen_)
  213326. {
  213327. AudioIODeviceCallback* const oldCallback = currentCallback;
  213328. close();
  213329. open (BigInteger (currentChansIn), BigInteger (currentChansOut),
  213330. currentSampleRate, currentBlockSizeSamples);
  213331. if (oldCallback != 0)
  213332. start (oldCallback);
  213333. }
  213334. }
  213335. else
  213336. {
  213337. startTimer (100);
  213338. }
  213339. }
  213340. juce_UseDebuggingNewOperator
  213341. private:
  213342. IASIO* volatile asioObject;
  213343. ASIOCallbacks callbacks;
  213344. void* windowHandle;
  213345. CLSID classId;
  213346. const String optionalDllForDirectLoading;
  213347. String error;
  213348. long totalNumInputChans, totalNumOutputChans;
  213349. StringArray inputChannelNames, outputChannelNames;
  213350. Array<int> sampleRates, bufferSizes;
  213351. long inputLatency, outputLatency;
  213352. long minSize, maxSize, preferredSize, granularity;
  213353. int volatile currentBlockSizeSamples;
  213354. int volatile currentBitDepth;
  213355. double volatile currentSampleRate;
  213356. BigInteger currentChansOut, currentChansIn;
  213357. AudioIODeviceCallback* volatile currentCallback;
  213358. CriticalSection callbackLock;
  213359. ASIOBufferInfo bufferInfos [maxASIOChannels];
  213360. float* inBuffers [maxASIOChannels];
  213361. float* outBuffers [maxASIOChannels];
  213362. int inputChannelBitDepths [maxASIOChannels];
  213363. int outputChannelBitDepths [maxASIOChannels];
  213364. int inputChannelBytesPerSample [maxASIOChannels];
  213365. int outputChannelBytesPerSample [maxASIOChannels];
  213366. bool inputChannelIsFloat [maxASIOChannels];
  213367. bool outputChannelIsFloat [maxASIOChannels];
  213368. bool inputChannelLittleEndian [maxASIOChannels];
  213369. bool outputChannelLittleEndian [maxASIOChannels];
  213370. WaitableEvent event1;
  213371. HeapBlock <float> tempBuffer;
  213372. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  213373. bool isOpen_, isStarted;
  213374. bool volatile isASIOOpen;
  213375. bool volatile calledback;
  213376. bool volatile littleEndian, postOutput, needToReset, isReSync;
  213377. bool volatile insideControlPanelModalLoop;
  213378. bool volatile shouldUsePreferredSize;
  213379. void removeCurrentDriver()
  213380. {
  213381. if (asioObject != 0)
  213382. {
  213383. asioObject->Release();
  213384. asioObject = 0;
  213385. }
  213386. }
  213387. bool loadDriver()
  213388. {
  213389. removeCurrentDriver();
  213390. JUCE_TRY
  213391. {
  213392. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  213393. classId, (void**) &asioObject) == S_OK)
  213394. {
  213395. return true;
  213396. }
  213397. // If a class isn't registered but we have a path for it, we can fallback to
  213398. // doing a direct load of the COM object (only available via the juce_createASIOAudioIODeviceForGUID function).
  213399. if (optionalDllForDirectLoading.isNotEmpty())
  213400. {
  213401. HMODULE h = LoadLibrary (optionalDllForDirectLoading);
  213402. if (h != 0)
  213403. {
  213404. typedef HRESULT (CALLBACK* DllGetClassObjectFunc) (REFCLSID clsid, REFIID iid, LPVOID* ppv);
  213405. DllGetClassObjectFunc dllGetClassObject = (DllGetClassObjectFunc) GetProcAddress (h, "DllGetClassObject");
  213406. if (dllGetClassObject != 0)
  213407. {
  213408. IClassFactory* classFactory = 0;
  213409. HRESULT hr = dllGetClassObject (classId, IID_IClassFactory, (void**) &classFactory);
  213410. if (classFactory != 0)
  213411. {
  213412. hr = classFactory->CreateInstance (0, classId, (void**) &asioObject);
  213413. classFactory->Release();
  213414. }
  213415. return asioObject != 0;
  213416. }
  213417. }
  213418. }
  213419. }
  213420. JUCE_CATCH_ALL
  213421. asioObject = 0;
  213422. return false;
  213423. }
  213424. const String initDriver()
  213425. {
  213426. if (asioObject != 0)
  213427. {
  213428. char buffer [256];
  213429. zeromem (buffer, sizeof (buffer));
  213430. if (! asioObject->init (windowHandle))
  213431. {
  213432. asioObject->getErrorMessage (buffer);
  213433. return String (buffer, sizeof (buffer) - 1);
  213434. }
  213435. // just in case any daft drivers expect this to be called..
  213436. asioObject->getDriverName (buffer);
  213437. return String::empty;
  213438. }
  213439. return "No Driver";
  213440. }
  213441. const String openDevice()
  213442. {
  213443. // use this in case the driver starts opening dialog boxes..
  213444. Component modalWindow (String::empty);
  213445. modalWindow.setOpaque (true);
  213446. modalWindow.addToDesktop (0);
  213447. modalWindow.enterModalState();
  213448. // open the device and get its info..
  213449. log ("opening ASIO device: " + getName());
  213450. needToReset = false;
  213451. isReSync = false;
  213452. outputChannelNames.clear();
  213453. inputChannelNames.clear();
  213454. bufferSizes.clear();
  213455. sampleRates.clear();
  213456. isASIOOpen = false;
  213457. isOpen_ = false;
  213458. totalNumInputChans = 0;
  213459. totalNumOutputChans = 0;
  213460. numActiveInputChans = 0;
  213461. numActiveOutputChans = 0;
  213462. currentCallback = 0;
  213463. error = String::empty;
  213464. if (getName().isEmpty())
  213465. return error;
  213466. long err = 0;
  213467. if (loadDriver())
  213468. {
  213469. if ((error = initDriver()).isEmpty())
  213470. {
  213471. numActiveInputChans = 0;
  213472. numActiveOutputChans = 0;
  213473. totalNumInputChans = 0;
  213474. totalNumOutputChans = 0;
  213475. if (asioObject != 0
  213476. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  213477. {
  213478. log (String ((int) totalNumInputChans) + " in, " + String ((int) totalNumOutputChans) + " out");
  213479. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  213480. {
  213481. // find a list of buffer sizes..
  213482. log (String ((int) minSize) + " " + String ((int) maxSize) + " " + String ((int) preferredSize) + " " + String ((int) granularity));
  213483. if (granularity >= 0)
  213484. {
  213485. granularity = jmax (1, (int) granularity);
  213486. for (int i = jmax ((int) minSize, (int) granularity); i < jmin (6400, (int) maxSize); i += granularity)
  213487. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  213488. }
  213489. else if (granularity < 0)
  213490. {
  213491. for (int i = 0; i < 18; ++i)
  213492. {
  213493. const int s = (1 << i);
  213494. if (s >= minSize && s <= maxSize)
  213495. bufferSizes.add (s);
  213496. }
  213497. }
  213498. if (! bufferSizes.contains (preferredSize))
  213499. bufferSizes.insert (0, preferredSize);
  213500. double currentRate = 0;
  213501. asioObject->getSampleRate (&currentRate);
  213502. if (currentRate <= 0.0 || currentRate > 192001.0)
  213503. {
  213504. log ("setting sample rate");
  213505. err = asioObject->setSampleRate (44100.0);
  213506. if (err != 0)
  213507. {
  213508. logError ("setting sample rate", err);
  213509. }
  213510. asioObject->getSampleRate (&currentRate);
  213511. }
  213512. currentSampleRate = currentRate;
  213513. postOutput = (asioObject->outputReady() == 0);
  213514. if (postOutput)
  213515. {
  213516. log ("ASIO outputReady = ok");
  213517. }
  213518. updateSampleRates();
  213519. // ..because cubase does it at this point
  213520. inputLatency = outputLatency = 0;
  213521. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  213522. {
  213523. log ("ASIO - no latencies");
  213524. }
  213525. log ("latencies: " + String ((int) inputLatency) + ", " + String ((int) outputLatency));
  213526. // create some dummy buffers now.. because cubase does..
  213527. numActiveInputChans = 0;
  213528. numActiveOutputChans = 0;
  213529. ASIOBufferInfo* info = bufferInfos;
  213530. int i, numChans = 0;
  213531. for (i = 0; i < jmin (2, (int) totalNumInputChans); ++i)
  213532. {
  213533. info->isInput = 1;
  213534. info->channelNum = i;
  213535. info->buffers[0] = info->buffers[1] = 0;
  213536. ++info;
  213537. ++numChans;
  213538. }
  213539. const int outputBufferIndex = numChans;
  213540. for (i = 0; i < jmin (2, (int) totalNumOutputChans); ++i)
  213541. {
  213542. info->isInput = 0;
  213543. info->channelNum = i;
  213544. info->buffers[0] = info->buffers[1] = 0;
  213545. ++info;
  213546. ++numChans;
  213547. }
  213548. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  213549. if (currentASIODev[0] == this)
  213550. {
  213551. callbacks.bufferSwitch = &bufferSwitchCallback0;
  213552. callbacks.asioMessage = &asioMessagesCallback0;
  213553. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  213554. }
  213555. else if (currentASIODev[1] == this)
  213556. {
  213557. callbacks.bufferSwitch = &bufferSwitchCallback1;
  213558. callbacks.asioMessage = &asioMessagesCallback1;
  213559. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  213560. }
  213561. else if (currentASIODev[2] == this)
  213562. {
  213563. callbacks.bufferSwitch = &bufferSwitchCallback2;
  213564. callbacks.asioMessage = &asioMessagesCallback2;
  213565. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  213566. }
  213567. else
  213568. {
  213569. jassertfalse;
  213570. }
  213571. log ("creating buffers (dummy): " + String (numChans) + ", " + String ((int) preferredSize));
  213572. if (preferredSize > 0)
  213573. {
  213574. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  213575. if (err != 0)
  213576. {
  213577. logError ("dummy buffers", err);
  213578. }
  213579. }
  213580. long newInps = 0, newOuts = 0;
  213581. asioObject->getChannels (&newInps, &newOuts);
  213582. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  213583. {
  213584. totalNumInputChans = newInps;
  213585. totalNumOutputChans = newOuts;
  213586. log (String ((int) totalNumInputChans) + " in; " + String ((int) totalNumOutputChans) + " out");
  213587. }
  213588. updateSampleRates();
  213589. ASIOChannelInfo channelInfo;
  213590. channelInfo.type = 0;
  213591. for (i = 0; i < totalNumInputChans; ++i)
  213592. {
  213593. zerostruct (channelInfo);
  213594. channelInfo.channel = i;
  213595. channelInfo.isInput = 1;
  213596. asioObject->getChannelInfo (&channelInfo);
  213597. inputChannelNames.add (String (channelInfo.name));
  213598. }
  213599. for (i = 0; i < totalNumOutputChans; ++i)
  213600. {
  213601. zerostruct (channelInfo);
  213602. channelInfo.channel = i;
  213603. channelInfo.isInput = 0;
  213604. asioObject->getChannelInfo (&channelInfo);
  213605. outputChannelNames.add (String (channelInfo.name));
  213606. typeToFormatParameters (channelInfo.type,
  213607. outputChannelBitDepths[i],
  213608. outputChannelBytesPerSample[i],
  213609. outputChannelIsFloat[i],
  213610. outputChannelLittleEndian[i]);
  213611. if (i < 2)
  213612. {
  213613. // clear the channels that are used with the dummy stuff
  213614. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  213615. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  213616. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  213617. }
  213618. }
  213619. outputChannelNames.trim();
  213620. inputChannelNames.trim();
  213621. outputChannelNames.appendNumbersToDuplicates (false, true);
  213622. inputChannelNames.appendNumbersToDuplicates (false, true);
  213623. // start and stop because cubase does it..
  213624. asioObject->getLatencies (&inputLatency, &outputLatency);
  213625. if ((err = asioObject->start()) != 0)
  213626. {
  213627. // ignore an error here, as it might start later after setting other stuff up
  213628. logError ("ASIO start", err);
  213629. }
  213630. Thread::sleep (100);
  213631. asioObject->stop();
  213632. }
  213633. else
  213634. {
  213635. error = "Can't detect buffer sizes";
  213636. }
  213637. }
  213638. else
  213639. {
  213640. error = "Can't detect asio channels";
  213641. }
  213642. }
  213643. }
  213644. else
  213645. {
  213646. error = "No such device";
  213647. }
  213648. if (error.isNotEmpty())
  213649. {
  213650. logError (error, err);
  213651. if (asioObject != 0)
  213652. asioObject->disposeBuffers();
  213653. removeCurrentDriver();
  213654. isASIOOpen = false;
  213655. }
  213656. else
  213657. {
  213658. isASIOOpen = true;
  213659. log ("ASIO device open");
  213660. }
  213661. isOpen_ = false;
  213662. needToReset = false;
  213663. isReSync = false;
  213664. return error;
  213665. }
  213666. void callback (const long index)
  213667. {
  213668. if (isStarted)
  213669. {
  213670. bufferIndex = index;
  213671. processBuffer();
  213672. }
  213673. else
  213674. {
  213675. if (postOutput && (asioObject != 0))
  213676. asioObject->outputReady();
  213677. }
  213678. calledback = true;
  213679. }
  213680. void processBuffer()
  213681. {
  213682. const ASIOBufferInfo* const infos = bufferInfos;
  213683. const int bi = bufferIndex;
  213684. const ScopedLock sl (callbackLock);
  213685. if (needToReset)
  213686. {
  213687. needToReset = false;
  213688. if (isReSync)
  213689. {
  213690. log ("! ASIO resync");
  213691. isReSync = false;
  213692. }
  213693. else
  213694. {
  213695. startTimer (20);
  213696. }
  213697. }
  213698. if (bi >= 0)
  213699. {
  213700. const int samps = currentBlockSizeSamples;
  213701. if (currentCallback != 0)
  213702. {
  213703. int i;
  213704. for (i = 0; i < numActiveInputChans; ++i)
  213705. {
  213706. float* const dst = inBuffers[i];
  213707. jassert (dst != 0);
  213708. const char* const src = (const char*) (infos[i].buffers[bi]);
  213709. if (inputChannelIsFloat[i])
  213710. {
  213711. memcpy (dst, src, samps * sizeof (float));
  213712. }
  213713. else
  213714. {
  213715. jassert (dst == tempBuffer + (samps * i));
  213716. switch (inputChannelBitDepths[i])
  213717. {
  213718. case 16:
  213719. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  213720. samps, inputChannelLittleEndian[i]);
  213721. break;
  213722. case 24:
  213723. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  213724. samps, inputChannelLittleEndian[i]);
  213725. break;
  213726. case 32:
  213727. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  213728. samps, inputChannelLittleEndian[i]);
  213729. break;
  213730. case 64:
  213731. jassertfalse;
  213732. break;
  213733. }
  213734. }
  213735. }
  213736. currentCallback->audioDeviceIOCallback ((const float**) inBuffers,
  213737. numActiveInputChans,
  213738. outBuffers,
  213739. numActiveOutputChans,
  213740. samps);
  213741. for (i = 0; i < numActiveOutputChans; ++i)
  213742. {
  213743. float* const src = outBuffers[i];
  213744. jassert (src != 0);
  213745. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  213746. if (outputChannelIsFloat[i])
  213747. {
  213748. memcpy (dst, src, samps * sizeof (float));
  213749. }
  213750. else
  213751. {
  213752. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  213753. switch (outputChannelBitDepths[i])
  213754. {
  213755. case 16:
  213756. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  213757. samps, outputChannelLittleEndian[i]);
  213758. break;
  213759. case 24:
  213760. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  213761. samps, outputChannelLittleEndian[i]);
  213762. break;
  213763. case 32:
  213764. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  213765. samps, outputChannelLittleEndian[i]);
  213766. break;
  213767. case 64:
  213768. jassertfalse;
  213769. break;
  213770. }
  213771. }
  213772. }
  213773. }
  213774. else
  213775. {
  213776. for (int i = 0; i < numActiveOutputChans; ++i)
  213777. {
  213778. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  213779. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  213780. }
  213781. }
  213782. }
  213783. if (postOutput)
  213784. asioObject->outputReady();
  213785. }
  213786. static ASIOTime* bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long)
  213787. {
  213788. if (currentASIODev[0] != 0)
  213789. currentASIODev[0]->callback (index);
  213790. return 0;
  213791. }
  213792. static ASIOTime* bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long)
  213793. {
  213794. if (currentASIODev[1] != 0)
  213795. currentASIODev[1]->callback (index);
  213796. return 0;
  213797. }
  213798. static ASIOTime* bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long)
  213799. {
  213800. if (currentASIODev[2] != 0)
  213801. currentASIODev[2]->callback (index);
  213802. return 0;
  213803. }
  213804. static void bufferSwitchCallback0 (long index, long)
  213805. {
  213806. if (currentASIODev[0] != 0)
  213807. currentASIODev[0]->callback (index);
  213808. }
  213809. static void bufferSwitchCallback1 (long index, long)
  213810. {
  213811. if (currentASIODev[1] != 0)
  213812. currentASIODev[1]->callback (index);
  213813. }
  213814. static void bufferSwitchCallback2 (long index, long)
  213815. {
  213816. if (currentASIODev[2] != 0)
  213817. currentASIODev[2]->callback (index);
  213818. }
  213819. static long asioMessagesCallback0 (long selector, long value, void*, double*)
  213820. {
  213821. return asioMessagesCallback (selector, value, 0);
  213822. }
  213823. static long asioMessagesCallback1 (long selector, long value, void*, double*)
  213824. {
  213825. return asioMessagesCallback (selector, value, 1);
  213826. }
  213827. static long asioMessagesCallback2 (long selector, long value, void*, double*)
  213828. {
  213829. return asioMessagesCallback (selector, value, 2);
  213830. }
  213831. static long asioMessagesCallback (long selector, long value, const int deviceIndex)
  213832. {
  213833. switch (selector)
  213834. {
  213835. case kAsioSelectorSupported:
  213836. if (value == kAsioResetRequest
  213837. || value == kAsioEngineVersion
  213838. || value == kAsioResyncRequest
  213839. || value == kAsioLatenciesChanged
  213840. || value == kAsioSupportsInputMonitor)
  213841. return 1;
  213842. break;
  213843. case kAsioBufferSizeChange:
  213844. break;
  213845. case kAsioResetRequest:
  213846. if (currentASIODev[deviceIndex] != 0)
  213847. currentASIODev[deviceIndex]->resetRequest();
  213848. return 1;
  213849. case kAsioResyncRequest:
  213850. if (currentASIODev[deviceIndex] != 0)
  213851. currentASIODev[deviceIndex]->resyncRequest();
  213852. return 1;
  213853. case kAsioLatenciesChanged:
  213854. return 1;
  213855. case kAsioEngineVersion:
  213856. return 2;
  213857. case kAsioSupportsTimeInfo:
  213858. case kAsioSupportsTimeCode:
  213859. return 0;
  213860. }
  213861. return 0;
  213862. }
  213863. static void sampleRateChangedCallback (ASIOSampleRate) throw()
  213864. {
  213865. }
  213866. static void convertInt16ToFloat (const char* src,
  213867. float* dest,
  213868. const int srcStrideBytes,
  213869. int numSamples,
  213870. const bool littleEndian) throw()
  213871. {
  213872. const double g = 1.0 / 32768.0;
  213873. if (littleEndian)
  213874. {
  213875. while (--numSamples >= 0)
  213876. {
  213877. *dest++ = (float) (g * (short) ByteOrder::littleEndianShort (src));
  213878. src += srcStrideBytes;
  213879. }
  213880. }
  213881. else
  213882. {
  213883. while (--numSamples >= 0)
  213884. {
  213885. *dest++ = (float) (g * (short) ByteOrder::bigEndianShort (src));
  213886. src += srcStrideBytes;
  213887. }
  213888. }
  213889. }
  213890. static void convertFloatToInt16 (const float* src,
  213891. char* dest,
  213892. const int dstStrideBytes,
  213893. int numSamples,
  213894. const bool littleEndian) throw()
  213895. {
  213896. const double maxVal = (double) 0x7fff;
  213897. if (littleEndian)
  213898. {
  213899. while (--numSamples >= 0)
  213900. {
  213901. *(uint16*) dest = ByteOrder::swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213902. dest += dstStrideBytes;
  213903. }
  213904. }
  213905. else
  213906. {
  213907. while (--numSamples >= 0)
  213908. {
  213909. *(uint16*) dest = ByteOrder::swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213910. dest += dstStrideBytes;
  213911. }
  213912. }
  213913. }
  213914. static void convertInt24ToFloat (const char* src,
  213915. float* dest,
  213916. const int srcStrideBytes,
  213917. int numSamples,
  213918. const bool littleEndian) throw()
  213919. {
  213920. const double g = 1.0 / 0x7fffff;
  213921. if (littleEndian)
  213922. {
  213923. while (--numSamples >= 0)
  213924. {
  213925. *dest++ = (float) (g * ByteOrder::littleEndian24Bit (src));
  213926. src += srcStrideBytes;
  213927. }
  213928. }
  213929. else
  213930. {
  213931. while (--numSamples >= 0)
  213932. {
  213933. *dest++ = (float) (g * ByteOrder::bigEndian24Bit (src));
  213934. src += srcStrideBytes;
  213935. }
  213936. }
  213937. }
  213938. static void convertFloatToInt24 (const float* src,
  213939. char* dest,
  213940. const int dstStrideBytes,
  213941. int numSamples,
  213942. const bool littleEndian) throw()
  213943. {
  213944. const double maxVal = (double) 0x7fffff;
  213945. if (littleEndian)
  213946. {
  213947. while (--numSamples >= 0)
  213948. {
  213949. ByteOrder::littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  213950. dest += dstStrideBytes;
  213951. }
  213952. }
  213953. else
  213954. {
  213955. while (--numSamples >= 0)
  213956. {
  213957. ByteOrder::bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  213958. dest += dstStrideBytes;
  213959. }
  213960. }
  213961. }
  213962. static void convertInt32ToFloat (const char* src,
  213963. float* dest,
  213964. const int srcStrideBytes,
  213965. int numSamples,
  213966. const bool littleEndian) throw()
  213967. {
  213968. const double g = 1.0 / 0x7fffffff;
  213969. if (littleEndian)
  213970. {
  213971. while (--numSamples >= 0)
  213972. {
  213973. *dest++ = (float) (g * (int) ByteOrder::littleEndianInt (src));
  213974. src += srcStrideBytes;
  213975. }
  213976. }
  213977. else
  213978. {
  213979. while (--numSamples >= 0)
  213980. {
  213981. *dest++ = (float) (g * (int) ByteOrder::bigEndianInt (src));
  213982. src += srcStrideBytes;
  213983. }
  213984. }
  213985. }
  213986. static void convertFloatToInt32 (const float* src,
  213987. char* dest,
  213988. const int dstStrideBytes,
  213989. int numSamples,
  213990. const bool littleEndian) throw()
  213991. {
  213992. const double maxVal = (double) 0x7fffffff;
  213993. if (littleEndian)
  213994. {
  213995. while (--numSamples >= 0)
  213996. {
  213997. *(uint32*) dest = ByteOrder::swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  213998. dest += dstStrideBytes;
  213999. }
  214000. }
  214001. else
  214002. {
  214003. while (--numSamples >= 0)
  214004. {
  214005. *(uint32*) dest = ByteOrder::swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  214006. dest += dstStrideBytes;
  214007. }
  214008. }
  214009. }
  214010. static void typeToFormatParameters (const long type,
  214011. int& bitDepth,
  214012. int& byteStride,
  214013. bool& formatIsFloat,
  214014. bool& littleEndian) throw()
  214015. {
  214016. bitDepth = 0;
  214017. littleEndian = false;
  214018. formatIsFloat = false;
  214019. switch (type)
  214020. {
  214021. case ASIOSTInt16MSB:
  214022. case ASIOSTInt16LSB:
  214023. case ASIOSTInt32MSB16:
  214024. case ASIOSTInt32LSB16:
  214025. bitDepth = 16; break;
  214026. case ASIOSTFloat32MSB:
  214027. case ASIOSTFloat32LSB:
  214028. formatIsFloat = true;
  214029. bitDepth = 32; break;
  214030. case ASIOSTInt32MSB:
  214031. case ASIOSTInt32LSB:
  214032. bitDepth = 32; break;
  214033. case ASIOSTInt24MSB:
  214034. case ASIOSTInt24LSB:
  214035. case ASIOSTInt32MSB24:
  214036. case ASIOSTInt32LSB24:
  214037. case ASIOSTInt32MSB18:
  214038. case ASIOSTInt32MSB20:
  214039. case ASIOSTInt32LSB18:
  214040. case ASIOSTInt32LSB20:
  214041. bitDepth = 24; break;
  214042. case ASIOSTFloat64MSB:
  214043. case ASIOSTFloat64LSB:
  214044. default:
  214045. bitDepth = 64;
  214046. break;
  214047. }
  214048. switch (type)
  214049. {
  214050. case ASIOSTInt16MSB:
  214051. case ASIOSTInt32MSB16:
  214052. case ASIOSTFloat32MSB:
  214053. case ASIOSTFloat64MSB:
  214054. case ASIOSTInt32MSB:
  214055. case ASIOSTInt32MSB18:
  214056. case ASIOSTInt32MSB20:
  214057. case ASIOSTInt32MSB24:
  214058. case ASIOSTInt24MSB:
  214059. littleEndian = false; break;
  214060. case ASIOSTInt16LSB:
  214061. case ASIOSTInt32LSB16:
  214062. case ASIOSTFloat32LSB:
  214063. case ASIOSTFloat64LSB:
  214064. case ASIOSTInt32LSB:
  214065. case ASIOSTInt32LSB18:
  214066. case ASIOSTInt32LSB20:
  214067. case ASIOSTInt32LSB24:
  214068. case ASIOSTInt24LSB:
  214069. littleEndian = true; break;
  214070. default:
  214071. break;
  214072. }
  214073. switch (type)
  214074. {
  214075. case ASIOSTInt16LSB:
  214076. case ASIOSTInt16MSB:
  214077. byteStride = 2; break;
  214078. case ASIOSTInt24LSB:
  214079. case ASIOSTInt24MSB:
  214080. byteStride = 3; break;
  214081. case ASIOSTInt32MSB16:
  214082. case ASIOSTInt32LSB16:
  214083. case ASIOSTInt32MSB:
  214084. case ASIOSTInt32MSB18:
  214085. case ASIOSTInt32MSB20:
  214086. case ASIOSTInt32MSB24:
  214087. case ASIOSTInt32LSB:
  214088. case ASIOSTInt32LSB18:
  214089. case ASIOSTInt32LSB20:
  214090. case ASIOSTInt32LSB24:
  214091. case ASIOSTFloat32LSB:
  214092. case ASIOSTFloat32MSB:
  214093. byteStride = 4; break;
  214094. case ASIOSTFloat64MSB:
  214095. case ASIOSTFloat64LSB:
  214096. byteStride = 8; break;
  214097. default:
  214098. break;
  214099. }
  214100. }
  214101. };
  214102. class ASIOAudioIODeviceType : public AudioIODeviceType
  214103. {
  214104. public:
  214105. ASIOAudioIODeviceType()
  214106. : AudioIODeviceType ("ASIO"),
  214107. hasScanned (false)
  214108. {
  214109. CoInitialize (0);
  214110. }
  214111. ~ASIOAudioIODeviceType()
  214112. {
  214113. }
  214114. void scanForDevices()
  214115. {
  214116. hasScanned = true;
  214117. deviceNames.clear();
  214118. classIds.clear();
  214119. HKEY hk = 0;
  214120. int index = 0;
  214121. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  214122. {
  214123. for (;;)
  214124. {
  214125. char name [256];
  214126. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  214127. {
  214128. addDriverInfo (name, hk);
  214129. }
  214130. else
  214131. {
  214132. break;
  214133. }
  214134. }
  214135. RegCloseKey (hk);
  214136. }
  214137. }
  214138. const StringArray getDeviceNames (bool /*wantInputNames*/) const
  214139. {
  214140. jassert (hasScanned); // need to call scanForDevices() before doing this
  214141. return deviceNames;
  214142. }
  214143. int getDefaultDeviceIndex (bool) const
  214144. {
  214145. jassert (hasScanned); // need to call scanForDevices() before doing this
  214146. for (int i = deviceNames.size(); --i >= 0;)
  214147. if (deviceNames[i].containsIgnoreCase ("asio4all"))
  214148. return i; // asio4all is a safe choice for a default..
  214149. #if JUCE_DEBUG
  214150. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase ("digidesign"))
  214151. return 1; // (the digi m-box driver crashes the app when you run
  214152. // it in the debugger, which can be a bit annoying)
  214153. #endif
  214154. return 0;
  214155. }
  214156. static int findFreeSlot()
  214157. {
  214158. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  214159. if (currentASIODev[i] == 0)
  214160. return i;
  214161. jassertfalse; // unfortunately you can only have a finite number
  214162. // of ASIO devices open at the same time..
  214163. return -1;
  214164. }
  214165. int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const
  214166. {
  214167. jassert (hasScanned); // need to call scanForDevices() before doing this
  214168. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  214169. }
  214170. bool hasSeparateInputsAndOutputs() const { return false; }
  214171. AudioIODevice* createDevice (const String& outputDeviceName,
  214172. const String& inputDeviceName)
  214173. {
  214174. // ASIO can't open two different devices for input and output - they must be the same one.
  214175. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  214176. jassert (hasScanned); // need to call scanForDevices() before doing this
  214177. const int index = deviceNames.indexOf (outputDeviceName.isNotEmpty() ? outputDeviceName
  214178. : inputDeviceName);
  214179. if (index >= 0)
  214180. {
  214181. const int freeSlot = findFreeSlot();
  214182. if (freeSlot >= 0)
  214183. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot, String::empty);
  214184. }
  214185. return 0;
  214186. }
  214187. juce_UseDebuggingNewOperator
  214188. private:
  214189. StringArray deviceNames;
  214190. OwnedArray <CLSID> classIds;
  214191. bool hasScanned;
  214192. static bool checkClassIsOk (const String& classId)
  214193. {
  214194. HKEY hk = 0;
  214195. bool ok = false;
  214196. if (RegOpenKey (HKEY_CLASSES_ROOT, _T("clsid"), &hk) == ERROR_SUCCESS)
  214197. {
  214198. int index = 0;
  214199. for (;;)
  214200. {
  214201. WCHAR buf [512];
  214202. if (RegEnumKey (hk, index++, buf, 512) == ERROR_SUCCESS)
  214203. {
  214204. if (classId.equalsIgnoreCase (buf))
  214205. {
  214206. HKEY subKey, pathKey;
  214207. if (RegOpenKeyEx (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  214208. {
  214209. if (RegOpenKeyEx (subKey, _T("InprocServer32"), 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  214210. {
  214211. WCHAR pathName [1024];
  214212. DWORD dtype = REG_SZ;
  214213. DWORD dsize = sizeof (pathName);
  214214. if (RegQueryValueEx (pathKey, 0, 0, &dtype, (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  214215. ok = File (pathName).exists();
  214216. RegCloseKey (pathKey);
  214217. }
  214218. RegCloseKey (subKey);
  214219. }
  214220. break;
  214221. }
  214222. }
  214223. else
  214224. {
  214225. break;
  214226. }
  214227. }
  214228. RegCloseKey (hk);
  214229. }
  214230. return ok;
  214231. }
  214232. void addDriverInfo (const String& keyName, HKEY hk)
  214233. {
  214234. HKEY subKey;
  214235. if (RegOpenKeyEx (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  214236. {
  214237. WCHAR buf [256];
  214238. zerostruct (buf);
  214239. DWORD dtype = REG_SZ;
  214240. DWORD dsize = sizeof (buf);
  214241. if (RegQueryValueEx (subKey, _T("clsid"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  214242. {
  214243. if (dsize > 0 && checkClassIsOk (buf))
  214244. {
  214245. CLSID classId;
  214246. if (CLSIDFromString ((LPOLESTR) buf, &classId) == S_OK)
  214247. {
  214248. dtype = REG_SZ;
  214249. dsize = sizeof (buf);
  214250. String deviceName;
  214251. if (RegQueryValueEx (subKey, _T("description"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  214252. deviceName = buf;
  214253. else
  214254. deviceName = keyName;
  214255. log ("found " + deviceName);
  214256. deviceNames.add (deviceName);
  214257. classIds.add (new CLSID (classId));
  214258. }
  214259. }
  214260. RegCloseKey (subKey);
  214261. }
  214262. }
  214263. }
  214264. ASIOAudioIODeviceType (const ASIOAudioIODeviceType&);
  214265. ASIOAudioIODeviceType& operator= (const ASIOAudioIODeviceType&);
  214266. };
  214267. AudioIODeviceType* juce_createAudioIODeviceType_ASIO()
  214268. {
  214269. return new ASIOAudioIODeviceType();
  214270. }
  214271. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  214272. void* guid,
  214273. const String& optionalDllForDirectLoading)
  214274. {
  214275. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  214276. if (freeSlot < 0)
  214277. return 0;
  214278. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading);
  214279. }
  214280. #undef log
  214281. #endif
  214282. /*** End of inlined file: juce_win32_ASIO.cpp ***/
  214283. /*** Start of inlined file: juce_win32_DirectSound.cpp ***/
  214284. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  214285. // compiled on its own).
  214286. #if JUCE_INCLUDED_FILE && JUCE_DIRECTSOUND
  214287. END_JUCE_NAMESPACE
  214288. extern "C"
  214289. {
  214290. // Declare just the minimum number of interfaces for the DSound objects that we need..
  214291. typedef struct typeDSBUFFERDESC
  214292. {
  214293. DWORD dwSize;
  214294. DWORD dwFlags;
  214295. DWORD dwBufferBytes;
  214296. DWORD dwReserved;
  214297. LPWAVEFORMATEX lpwfxFormat;
  214298. GUID guid3DAlgorithm;
  214299. } DSBUFFERDESC;
  214300. struct IDirectSoundBuffer;
  214301. #undef INTERFACE
  214302. #define INTERFACE IDirectSound
  214303. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  214304. {
  214305. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214306. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214307. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214308. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  214309. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214310. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  214311. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  214312. STDMETHOD(Compact) (THIS) PURE;
  214313. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  214314. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  214315. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  214316. };
  214317. #undef INTERFACE
  214318. #define INTERFACE IDirectSoundBuffer
  214319. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  214320. {
  214321. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214322. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214323. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214324. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214325. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  214326. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  214327. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  214328. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  214329. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  214330. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  214331. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  214332. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  214333. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  214334. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  214335. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  214336. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  214337. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  214338. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  214339. STDMETHOD(Stop) (THIS) PURE;
  214340. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  214341. STDMETHOD(Restore) (THIS) PURE;
  214342. };
  214343. typedef struct typeDSCBUFFERDESC
  214344. {
  214345. DWORD dwSize;
  214346. DWORD dwFlags;
  214347. DWORD dwBufferBytes;
  214348. DWORD dwReserved;
  214349. LPWAVEFORMATEX lpwfxFormat;
  214350. } DSCBUFFERDESC;
  214351. struct IDirectSoundCaptureBuffer;
  214352. #undef INTERFACE
  214353. #define INTERFACE IDirectSoundCapture
  214354. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  214355. {
  214356. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214357. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214358. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214359. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  214360. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214361. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  214362. };
  214363. #undef INTERFACE
  214364. #define INTERFACE IDirectSoundCaptureBuffer
  214365. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  214366. {
  214367. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214368. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214369. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214370. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214371. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  214372. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  214373. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  214374. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  214375. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  214376. STDMETHOD(Start) (THIS_ DWORD) PURE;
  214377. STDMETHOD(Stop) (THIS) PURE;
  214378. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  214379. };
  214380. };
  214381. BEGIN_JUCE_NAMESPACE
  214382. static const String getDSErrorMessage (HRESULT hr)
  214383. {
  214384. const char* result = 0;
  214385. switch (hr)
  214386. {
  214387. case MAKE_HRESULT(1, 0x878, 10): result = "Device already allocated"; break;
  214388. case MAKE_HRESULT(1, 0x878, 30): result = "Control unavailable"; break;
  214389. case E_INVALIDARG: result = "Invalid parameter"; break;
  214390. case MAKE_HRESULT(1, 0x878, 50): result = "Invalid call"; break;
  214391. case E_FAIL: result = "Generic error"; break;
  214392. case MAKE_HRESULT(1, 0x878, 70): result = "Priority level error"; break;
  214393. case E_OUTOFMEMORY: result = "Out of memory"; break;
  214394. case MAKE_HRESULT(1, 0x878, 100): result = "Bad format"; break;
  214395. case E_NOTIMPL: result = "Unsupported function"; break;
  214396. case MAKE_HRESULT(1, 0x878, 120): result = "No driver"; break;
  214397. case MAKE_HRESULT(1, 0x878, 130): result = "Already initialised"; break;
  214398. case CLASS_E_NOAGGREGATION: result = "No aggregation"; break;
  214399. case MAKE_HRESULT(1, 0x878, 150): result = "Buffer lost"; break;
  214400. case MAKE_HRESULT(1, 0x878, 160): result = "Another app has priority"; break;
  214401. case MAKE_HRESULT(1, 0x878, 170): result = "Uninitialised"; break;
  214402. case E_NOINTERFACE: result = "No interface"; break;
  214403. case S_OK: result = "No error"; break;
  214404. default: return "Unknown error: " + String ((int) hr);
  214405. }
  214406. return result;
  214407. }
  214408. #define DS_DEBUGGING 1
  214409. #ifdef DS_DEBUGGING
  214410. #define CATCH JUCE_CATCH_EXCEPTION
  214411. #undef log
  214412. #define log(a) Logger::writeToLog(a);
  214413. #undef logError
  214414. #define logError(a) logDSError(a, __LINE__);
  214415. static void logDSError (HRESULT hr, int lineNum)
  214416. {
  214417. if (hr != S_OK)
  214418. {
  214419. String error ("DS error at line ");
  214420. error << lineNum << " - " << getDSErrorMessage (hr);
  214421. log (error);
  214422. }
  214423. }
  214424. #else
  214425. #define CATCH JUCE_CATCH_ALL
  214426. #define log(a)
  214427. #define logError(a)
  214428. #endif
  214429. #define DSOUND_FUNCTION(functionName, params) \
  214430. typedef HRESULT (WINAPI *type##functionName) params; \
  214431. static type##functionName ds##functionName = 0;
  214432. #define DSOUND_FUNCTION_LOAD(functionName) \
  214433. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  214434. jassert (ds##functionName != 0);
  214435. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  214436. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  214437. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  214438. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  214439. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  214440. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  214441. static void initialiseDSoundFunctions()
  214442. {
  214443. if (dsDirectSoundCreate == 0)
  214444. {
  214445. HMODULE h = LoadLibraryA ("dsound.dll");
  214446. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  214447. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  214448. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  214449. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  214450. }
  214451. }
  214452. class DSoundInternalOutChannel
  214453. {
  214454. String name;
  214455. LPGUID guid;
  214456. int sampleRate, bufferSizeSamples;
  214457. float* leftBuffer;
  214458. float* rightBuffer;
  214459. IDirectSound* pDirectSound;
  214460. IDirectSoundBuffer* pOutputBuffer;
  214461. DWORD writeOffset;
  214462. int totalBytesPerBuffer;
  214463. int bytesPerBuffer;
  214464. unsigned int lastPlayCursor;
  214465. public:
  214466. int bitDepth;
  214467. bool doneFlag;
  214468. DSoundInternalOutChannel (const String& name_,
  214469. LPGUID guid_,
  214470. int rate,
  214471. int bufferSize,
  214472. float* left,
  214473. float* right)
  214474. : name (name_),
  214475. guid (guid_),
  214476. sampleRate (rate),
  214477. bufferSizeSamples (bufferSize),
  214478. leftBuffer (left),
  214479. rightBuffer (right),
  214480. pDirectSound (0),
  214481. pOutputBuffer (0),
  214482. bitDepth (16)
  214483. {
  214484. }
  214485. ~DSoundInternalOutChannel()
  214486. {
  214487. close();
  214488. }
  214489. void close()
  214490. {
  214491. HRESULT hr;
  214492. if (pOutputBuffer != 0)
  214493. {
  214494. JUCE_TRY
  214495. {
  214496. log ("closing dsound out: " + name);
  214497. hr = pOutputBuffer->Stop();
  214498. logError (hr);
  214499. }
  214500. CATCH
  214501. JUCE_TRY
  214502. {
  214503. hr = pOutputBuffer->Release();
  214504. logError (hr);
  214505. }
  214506. CATCH
  214507. pOutputBuffer = 0;
  214508. }
  214509. if (pDirectSound != 0)
  214510. {
  214511. JUCE_TRY
  214512. {
  214513. hr = pDirectSound->Release();
  214514. logError (hr);
  214515. }
  214516. CATCH
  214517. pDirectSound = 0;
  214518. }
  214519. }
  214520. const String open()
  214521. {
  214522. log ("opening dsound out device: " + name + " rate=" + String (sampleRate)
  214523. + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  214524. pDirectSound = 0;
  214525. pOutputBuffer = 0;
  214526. writeOffset = 0;
  214527. String error;
  214528. HRESULT hr = E_NOINTERFACE;
  214529. if (dsDirectSoundCreate != 0)
  214530. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  214531. if (hr == S_OK)
  214532. {
  214533. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  214534. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  214535. const int numChannels = 2;
  214536. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  214537. logError (hr);
  214538. if (hr == S_OK)
  214539. {
  214540. IDirectSoundBuffer* pPrimaryBuffer;
  214541. DSBUFFERDESC primaryDesc;
  214542. zerostruct (primaryDesc);
  214543. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  214544. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  214545. primaryDesc.dwBufferBytes = 0;
  214546. primaryDesc.lpwfxFormat = 0;
  214547. log ("opening dsound out step 2");
  214548. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  214549. logError (hr);
  214550. if (hr == S_OK)
  214551. {
  214552. WAVEFORMATEX wfFormat;
  214553. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  214554. wfFormat.nChannels = (unsigned short) numChannels;
  214555. wfFormat.nSamplesPerSec = sampleRate;
  214556. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  214557. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  214558. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  214559. wfFormat.cbSize = 0;
  214560. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  214561. logError (hr);
  214562. if (hr == S_OK)
  214563. {
  214564. DSBUFFERDESC secondaryDesc;
  214565. zerostruct (secondaryDesc);
  214566. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  214567. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  214568. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  214569. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  214570. secondaryDesc.lpwfxFormat = &wfFormat;
  214571. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  214572. logError (hr);
  214573. if (hr == S_OK)
  214574. {
  214575. log ("opening dsound out step 3");
  214576. DWORD dwDataLen;
  214577. unsigned char* pDSBuffData;
  214578. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  214579. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  214580. logError (hr);
  214581. if (hr == S_OK)
  214582. {
  214583. zeromem (pDSBuffData, dwDataLen);
  214584. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  214585. if (hr == S_OK)
  214586. {
  214587. hr = pOutputBuffer->SetCurrentPosition (0);
  214588. if (hr == S_OK)
  214589. {
  214590. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  214591. if (hr == S_OK)
  214592. return String::empty;
  214593. }
  214594. }
  214595. }
  214596. }
  214597. }
  214598. }
  214599. }
  214600. }
  214601. error = getDSErrorMessage (hr);
  214602. close();
  214603. return error;
  214604. }
  214605. void synchronisePosition()
  214606. {
  214607. if (pOutputBuffer != 0)
  214608. {
  214609. DWORD playCursor;
  214610. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  214611. }
  214612. }
  214613. bool service()
  214614. {
  214615. if (pOutputBuffer == 0)
  214616. return true;
  214617. DWORD playCursor, writeCursor;
  214618. for (;;)
  214619. {
  214620. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  214621. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  214622. {
  214623. pOutputBuffer->Restore();
  214624. continue;
  214625. }
  214626. if (hr == S_OK)
  214627. break;
  214628. logError (hr);
  214629. jassertfalse;
  214630. return true;
  214631. }
  214632. int playWriteGap = writeCursor - playCursor;
  214633. if (playWriteGap < 0)
  214634. playWriteGap += totalBytesPerBuffer;
  214635. int bytesEmpty = playCursor - writeOffset;
  214636. if (bytesEmpty < 0)
  214637. bytesEmpty += totalBytesPerBuffer;
  214638. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  214639. {
  214640. writeOffset = writeCursor;
  214641. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  214642. }
  214643. if (bytesEmpty >= bytesPerBuffer)
  214644. {
  214645. void* lpbuf1 = 0;
  214646. void* lpbuf2 = 0;
  214647. DWORD dwSize1 = 0;
  214648. DWORD dwSize2 = 0;
  214649. HRESULT hr = pOutputBuffer->Lock (writeOffset,
  214650. bytesPerBuffer,
  214651. &lpbuf1, &dwSize1,
  214652. &lpbuf2, &dwSize2, 0);
  214653. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  214654. {
  214655. pOutputBuffer->Restore();
  214656. hr = pOutputBuffer->Lock (writeOffset,
  214657. bytesPerBuffer,
  214658. &lpbuf1, &dwSize1,
  214659. &lpbuf2, &dwSize2, 0);
  214660. }
  214661. if (hr == S_OK)
  214662. {
  214663. if (bitDepth == 16)
  214664. {
  214665. const float gainL = 32767.0f;
  214666. const float gainR = 32767.0f;
  214667. int* dest = static_cast<int*> (lpbuf1);
  214668. const float* left = leftBuffer;
  214669. const float* right = rightBuffer;
  214670. int samples1 = dwSize1 >> 2;
  214671. int samples2 = dwSize2 >> 2;
  214672. if (left == 0)
  214673. {
  214674. while (--samples1 >= 0)
  214675. {
  214676. int r = roundToInt (gainR * *right++);
  214677. if (r < -32768)
  214678. r = -32768;
  214679. else if (r > 32767)
  214680. r = 32767;
  214681. *dest++ = (r << 16);
  214682. }
  214683. dest = static_cast<int*> (lpbuf2);
  214684. while (--samples2 >= 0)
  214685. {
  214686. int r = roundToInt (gainR * *right++);
  214687. if (r < -32768)
  214688. r = -32768;
  214689. else if (r > 32767)
  214690. r = 32767;
  214691. *dest++ = (r << 16);
  214692. }
  214693. }
  214694. else if (right == 0)
  214695. {
  214696. while (--samples1 >= 0)
  214697. {
  214698. int l = roundToInt (gainL * *left++);
  214699. if (l < -32768)
  214700. l = -32768;
  214701. else if (l > 32767)
  214702. l = 32767;
  214703. l &= 0xffff;
  214704. *dest++ = l;
  214705. }
  214706. dest = static_cast<int*> (lpbuf2);
  214707. while (--samples2 >= 0)
  214708. {
  214709. int l = roundToInt (gainL * *left++);
  214710. if (l < -32768)
  214711. l = -32768;
  214712. else if (l > 32767)
  214713. l = 32767;
  214714. l &= 0xffff;
  214715. *dest++ = l;
  214716. }
  214717. }
  214718. else
  214719. {
  214720. while (--samples1 >= 0)
  214721. {
  214722. int l = roundToInt (gainL * *left++);
  214723. if (l < -32768)
  214724. l = -32768;
  214725. else if (l > 32767)
  214726. l = 32767;
  214727. l &= 0xffff;
  214728. int r = roundToInt (gainR * *right++);
  214729. if (r < -32768)
  214730. r = -32768;
  214731. else if (r > 32767)
  214732. r = 32767;
  214733. *dest++ = (r << 16) | l;
  214734. }
  214735. dest = static_cast<int*> (lpbuf2);
  214736. while (--samples2 >= 0)
  214737. {
  214738. int l = roundToInt (gainL * *left++);
  214739. if (l < -32768)
  214740. l = -32768;
  214741. else if (l > 32767)
  214742. l = 32767;
  214743. l &= 0xffff;
  214744. int r = roundToInt (gainR * *right++);
  214745. if (r < -32768)
  214746. r = -32768;
  214747. else if (r > 32767)
  214748. r = 32767;
  214749. *dest++ = (r << 16) | l;
  214750. }
  214751. }
  214752. }
  214753. else
  214754. {
  214755. jassertfalse;
  214756. }
  214757. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  214758. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  214759. }
  214760. else
  214761. {
  214762. jassertfalse;
  214763. logError (hr);
  214764. }
  214765. bytesEmpty -= bytesPerBuffer;
  214766. return true;
  214767. }
  214768. else
  214769. {
  214770. return false;
  214771. }
  214772. }
  214773. };
  214774. struct DSoundInternalInChannel
  214775. {
  214776. String name;
  214777. LPGUID guid;
  214778. int sampleRate, bufferSizeSamples;
  214779. float* leftBuffer;
  214780. float* rightBuffer;
  214781. IDirectSound* pDirectSound;
  214782. IDirectSoundCapture* pDirectSoundCapture;
  214783. IDirectSoundCaptureBuffer* pInputBuffer;
  214784. public:
  214785. unsigned int readOffset;
  214786. int bytesPerBuffer, totalBytesPerBuffer;
  214787. int bitDepth;
  214788. bool doneFlag;
  214789. DSoundInternalInChannel (const String& name_,
  214790. LPGUID guid_,
  214791. int rate,
  214792. int bufferSize,
  214793. float* left,
  214794. float* right)
  214795. : name (name_),
  214796. guid (guid_),
  214797. sampleRate (rate),
  214798. bufferSizeSamples (bufferSize),
  214799. leftBuffer (left),
  214800. rightBuffer (right),
  214801. pDirectSound (0),
  214802. pDirectSoundCapture (0),
  214803. pInputBuffer (0),
  214804. bitDepth (16)
  214805. {
  214806. }
  214807. ~DSoundInternalInChannel()
  214808. {
  214809. close();
  214810. }
  214811. void close()
  214812. {
  214813. HRESULT hr;
  214814. if (pInputBuffer != 0)
  214815. {
  214816. JUCE_TRY
  214817. {
  214818. log ("closing dsound in: " + name);
  214819. hr = pInputBuffer->Stop();
  214820. logError (hr);
  214821. }
  214822. CATCH
  214823. JUCE_TRY
  214824. {
  214825. hr = pInputBuffer->Release();
  214826. logError (hr);
  214827. }
  214828. CATCH
  214829. pInputBuffer = 0;
  214830. }
  214831. if (pDirectSoundCapture != 0)
  214832. {
  214833. JUCE_TRY
  214834. {
  214835. hr = pDirectSoundCapture->Release();
  214836. logError (hr);
  214837. }
  214838. CATCH
  214839. pDirectSoundCapture = 0;
  214840. }
  214841. if (pDirectSound != 0)
  214842. {
  214843. JUCE_TRY
  214844. {
  214845. hr = pDirectSound->Release();
  214846. logError (hr);
  214847. }
  214848. CATCH
  214849. pDirectSound = 0;
  214850. }
  214851. }
  214852. const String open()
  214853. {
  214854. log ("opening dsound in device: " + name
  214855. + " rate=" + String (sampleRate) + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  214856. pDirectSound = 0;
  214857. pDirectSoundCapture = 0;
  214858. pInputBuffer = 0;
  214859. readOffset = 0;
  214860. totalBytesPerBuffer = 0;
  214861. String error;
  214862. HRESULT hr = E_NOINTERFACE;
  214863. if (dsDirectSoundCaptureCreate != 0)
  214864. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  214865. logError (hr);
  214866. if (hr == S_OK)
  214867. {
  214868. const int numChannels = 2;
  214869. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  214870. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  214871. WAVEFORMATEX wfFormat;
  214872. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  214873. wfFormat.nChannels = (unsigned short)numChannels;
  214874. wfFormat.nSamplesPerSec = sampleRate;
  214875. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  214876. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  214877. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  214878. wfFormat.cbSize = 0;
  214879. DSCBUFFERDESC captureDesc;
  214880. zerostruct (captureDesc);
  214881. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  214882. captureDesc.dwFlags = 0;
  214883. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  214884. captureDesc.lpwfxFormat = &wfFormat;
  214885. log ("opening dsound in step 2");
  214886. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  214887. logError (hr);
  214888. if (hr == S_OK)
  214889. {
  214890. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  214891. logError (hr);
  214892. if (hr == S_OK)
  214893. return String::empty;
  214894. }
  214895. }
  214896. error = getDSErrorMessage (hr);
  214897. close();
  214898. return error;
  214899. }
  214900. void synchronisePosition()
  214901. {
  214902. if (pInputBuffer != 0)
  214903. {
  214904. DWORD capturePos;
  214905. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  214906. }
  214907. }
  214908. bool service()
  214909. {
  214910. if (pInputBuffer == 0)
  214911. return true;
  214912. DWORD capturePos, readPos;
  214913. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  214914. logError (hr);
  214915. if (hr != S_OK)
  214916. return true;
  214917. int bytesFilled = readPos - readOffset;
  214918. if (bytesFilled < 0)
  214919. bytesFilled += totalBytesPerBuffer;
  214920. if (bytesFilled >= bytesPerBuffer)
  214921. {
  214922. LPBYTE lpbuf1 = 0;
  214923. LPBYTE lpbuf2 = 0;
  214924. DWORD dwsize1 = 0;
  214925. DWORD dwsize2 = 0;
  214926. HRESULT hr = pInputBuffer->Lock (readOffset,
  214927. bytesPerBuffer,
  214928. (void**) &lpbuf1, &dwsize1,
  214929. (void**) &lpbuf2, &dwsize2, 0);
  214930. if (hr == S_OK)
  214931. {
  214932. if (bitDepth == 16)
  214933. {
  214934. const float g = 1.0f / 32768.0f;
  214935. float* destL = leftBuffer;
  214936. float* destR = rightBuffer;
  214937. int samples1 = dwsize1 >> 2;
  214938. int samples2 = dwsize2 >> 2;
  214939. const short* src = (const short*)lpbuf1;
  214940. if (destL == 0)
  214941. {
  214942. while (--samples1 >= 0)
  214943. {
  214944. ++src;
  214945. *destR++ = *src++ * g;
  214946. }
  214947. src = (const short*)lpbuf2;
  214948. while (--samples2 >= 0)
  214949. {
  214950. ++src;
  214951. *destR++ = *src++ * g;
  214952. }
  214953. }
  214954. else if (destR == 0)
  214955. {
  214956. while (--samples1 >= 0)
  214957. {
  214958. *destL++ = *src++ * g;
  214959. ++src;
  214960. }
  214961. src = (const short*)lpbuf2;
  214962. while (--samples2 >= 0)
  214963. {
  214964. *destL++ = *src++ * g;
  214965. ++src;
  214966. }
  214967. }
  214968. else
  214969. {
  214970. while (--samples1 >= 0)
  214971. {
  214972. *destL++ = *src++ * g;
  214973. *destR++ = *src++ * g;
  214974. }
  214975. src = (const short*)lpbuf2;
  214976. while (--samples2 >= 0)
  214977. {
  214978. *destL++ = *src++ * g;
  214979. *destR++ = *src++ * g;
  214980. }
  214981. }
  214982. }
  214983. else
  214984. {
  214985. jassertfalse;
  214986. }
  214987. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  214988. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  214989. }
  214990. else
  214991. {
  214992. logError (hr);
  214993. jassertfalse;
  214994. }
  214995. bytesFilled -= bytesPerBuffer;
  214996. return true;
  214997. }
  214998. else
  214999. {
  215000. return false;
  215001. }
  215002. }
  215003. };
  215004. class DSoundAudioIODevice : public AudioIODevice,
  215005. public Thread
  215006. {
  215007. public:
  215008. DSoundAudioIODevice (const String& deviceName,
  215009. const int outputDeviceIndex_,
  215010. const int inputDeviceIndex_)
  215011. : AudioIODevice (deviceName, "DirectSound"),
  215012. Thread ("Juce DSound"),
  215013. isOpen_ (false),
  215014. isStarted (false),
  215015. outputDeviceIndex (outputDeviceIndex_),
  215016. inputDeviceIndex (inputDeviceIndex_),
  215017. totalSamplesOut (0),
  215018. sampleRate (0.0),
  215019. inputBuffers (1, 1),
  215020. outputBuffers (1, 1),
  215021. callback (0),
  215022. bufferSizeSamples (0)
  215023. {
  215024. if (outputDeviceIndex_ >= 0)
  215025. {
  215026. outChannels.add (TRANS("Left"));
  215027. outChannels.add (TRANS("Right"));
  215028. }
  215029. if (inputDeviceIndex_ >= 0)
  215030. {
  215031. inChannels.add (TRANS("Left"));
  215032. inChannels.add (TRANS("Right"));
  215033. }
  215034. }
  215035. ~DSoundAudioIODevice()
  215036. {
  215037. close();
  215038. }
  215039. const StringArray getOutputChannelNames()
  215040. {
  215041. return outChannels;
  215042. }
  215043. const StringArray getInputChannelNames()
  215044. {
  215045. return inChannels;
  215046. }
  215047. int getNumSampleRates()
  215048. {
  215049. return 4;
  215050. }
  215051. double getSampleRate (int index)
  215052. {
  215053. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  215054. return samps [jlimit (0, 3, index)];
  215055. }
  215056. int getNumBufferSizesAvailable()
  215057. {
  215058. return 50;
  215059. }
  215060. int getBufferSizeSamples (int index)
  215061. {
  215062. int n = 64;
  215063. for (int i = 0; i < index; ++i)
  215064. n += (n < 512) ? 32
  215065. : ((n < 1024) ? 64
  215066. : ((n < 2048) ? 128 : 256));
  215067. return n;
  215068. }
  215069. int getDefaultBufferSize()
  215070. {
  215071. return 2560;
  215072. }
  215073. const String open (const BigInteger& inputChannels,
  215074. const BigInteger& outputChannels,
  215075. double sampleRate,
  215076. int bufferSizeSamples)
  215077. {
  215078. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  215079. isOpen_ = lastError.isEmpty();
  215080. return lastError;
  215081. }
  215082. void close()
  215083. {
  215084. stop();
  215085. if (isOpen_)
  215086. {
  215087. closeDevice();
  215088. isOpen_ = false;
  215089. }
  215090. }
  215091. bool isOpen()
  215092. {
  215093. return isOpen_ && isThreadRunning();
  215094. }
  215095. int getCurrentBufferSizeSamples()
  215096. {
  215097. return bufferSizeSamples;
  215098. }
  215099. double getCurrentSampleRate()
  215100. {
  215101. return sampleRate;
  215102. }
  215103. int getCurrentBitDepth()
  215104. {
  215105. int i, bits = 256;
  215106. for (i = inChans.size(); --i >= 0;)
  215107. bits = jmin (bits, inChans[i]->bitDepth);
  215108. for (i = outChans.size(); --i >= 0;)
  215109. bits = jmin (bits, outChans[i]->bitDepth);
  215110. if (bits > 32)
  215111. bits = 16;
  215112. return bits;
  215113. }
  215114. const BigInteger getActiveOutputChannels() const
  215115. {
  215116. return enabledOutputs;
  215117. }
  215118. const BigInteger getActiveInputChannels() const
  215119. {
  215120. return enabledInputs;
  215121. }
  215122. int getOutputLatencyInSamples()
  215123. {
  215124. return (int) (getCurrentBufferSizeSamples() * 1.5);
  215125. }
  215126. int getInputLatencyInSamples()
  215127. {
  215128. return getOutputLatencyInSamples();
  215129. }
  215130. void start (AudioIODeviceCallback* call)
  215131. {
  215132. if (isOpen_ && call != 0 && ! isStarted)
  215133. {
  215134. if (! isThreadRunning())
  215135. {
  215136. // something gone wrong and the thread's stopped..
  215137. isOpen_ = false;
  215138. return;
  215139. }
  215140. call->audioDeviceAboutToStart (this);
  215141. const ScopedLock sl (startStopLock);
  215142. callback = call;
  215143. isStarted = true;
  215144. }
  215145. }
  215146. void stop()
  215147. {
  215148. if (isStarted)
  215149. {
  215150. AudioIODeviceCallback* const callbackLocal = callback;
  215151. {
  215152. const ScopedLock sl (startStopLock);
  215153. isStarted = false;
  215154. }
  215155. if (callbackLocal != 0)
  215156. callbackLocal->audioDeviceStopped();
  215157. }
  215158. }
  215159. bool isPlaying()
  215160. {
  215161. return isStarted && isOpen_ && isThreadRunning();
  215162. }
  215163. const String getLastError()
  215164. {
  215165. return lastError;
  215166. }
  215167. juce_UseDebuggingNewOperator
  215168. StringArray inChannels, outChannels;
  215169. int outputDeviceIndex, inputDeviceIndex;
  215170. private:
  215171. bool isOpen_;
  215172. bool isStarted;
  215173. String lastError;
  215174. OwnedArray <DSoundInternalInChannel> inChans;
  215175. OwnedArray <DSoundInternalOutChannel> outChans;
  215176. WaitableEvent startEvent;
  215177. int bufferSizeSamples;
  215178. int volatile totalSamplesOut;
  215179. int64 volatile lastBlockTime;
  215180. double sampleRate;
  215181. BigInteger enabledInputs, enabledOutputs;
  215182. AudioSampleBuffer inputBuffers, outputBuffers;
  215183. AudioIODeviceCallback* callback;
  215184. CriticalSection startStopLock;
  215185. DSoundAudioIODevice (const DSoundAudioIODevice&);
  215186. DSoundAudioIODevice& operator= (const DSoundAudioIODevice&);
  215187. const String openDevice (const BigInteger& inputChannels,
  215188. const BigInteger& outputChannels,
  215189. double sampleRate_,
  215190. int bufferSizeSamples_);
  215191. void closeDevice()
  215192. {
  215193. isStarted = false;
  215194. stopThread (5000);
  215195. inChans.clear();
  215196. outChans.clear();
  215197. inputBuffers.setSize (1, 1);
  215198. outputBuffers.setSize (1, 1);
  215199. }
  215200. void resync()
  215201. {
  215202. if (! threadShouldExit())
  215203. {
  215204. sleep (5);
  215205. int i;
  215206. for (i = 0; i < outChans.size(); ++i)
  215207. outChans.getUnchecked(i)->synchronisePosition();
  215208. for (i = 0; i < inChans.size(); ++i)
  215209. inChans.getUnchecked(i)->synchronisePosition();
  215210. }
  215211. }
  215212. public:
  215213. void run()
  215214. {
  215215. while (! threadShouldExit())
  215216. {
  215217. if (wait (100))
  215218. break;
  215219. }
  215220. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  215221. const int maxTimeMS = jmax (5, 3 * latencyMs);
  215222. while (! threadShouldExit())
  215223. {
  215224. int numToDo = 0;
  215225. uint32 startTime = Time::getMillisecondCounter();
  215226. int i;
  215227. for (i = inChans.size(); --i >= 0;)
  215228. {
  215229. inChans.getUnchecked(i)->doneFlag = false;
  215230. ++numToDo;
  215231. }
  215232. for (i = outChans.size(); --i >= 0;)
  215233. {
  215234. outChans.getUnchecked(i)->doneFlag = false;
  215235. ++numToDo;
  215236. }
  215237. if (numToDo > 0)
  215238. {
  215239. const int maxCount = 3;
  215240. int count = maxCount;
  215241. for (;;)
  215242. {
  215243. for (i = inChans.size(); --i >= 0;)
  215244. {
  215245. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  215246. if ((! in->doneFlag) && in->service())
  215247. {
  215248. in->doneFlag = true;
  215249. --numToDo;
  215250. }
  215251. }
  215252. for (i = outChans.size(); --i >= 0;)
  215253. {
  215254. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  215255. if ((! out->doneFlag) && out->service())
  215256. {
  215257. out->doneFlag = true;
  215258. --numToDo;
  215259. }
  215260. }
  215261. if (numToDo <= 0)
  215262. break;
  215263. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  215264. {
  215265. resync();
  215266. break;
  215267. }
  215268. if (--count <= 0)
  215269. {
  215270. Sleep (1);
  215271. count = maxCount;
  215272. }
  215273. if (threadShouldExit())
  215274. return;
  215275. }
  215276. }
  215277. else
  215278. {
  215279. sleep (1);
  215280. }
  215281. const ScopedLock sl (startStopLock);
  215282. if (isStarted)
  215283. {
  215284. JUCE_TRY
  215285. {
  215286. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers.getArrayOfChannels()),
  215287. inputBuffers.getNumChannels(),
  215288. outputBuffers.getArrayOfChannels(),
  215289. outputBuffers.getNumChannels(),
  215290. bufferSizeSamples);
  215291. }
  215292. JUCE_CATCH_EXCEPTION
  215293. totalSamplesOut += bufferSizeSamples;
  215294. }
  215295. else
  215296. {
  215297. outputBuffers.clear();
  215298. totalSamplesOut = 0;
  215299. sleep (1);
  215300. }
  215301. }
  215302. }
  215303. };
  215304. class DSoundAudioIODeviceType : public AudioIODeviceType
  215305. {
  215306. public:
  215307. DSoundAudioIODeviceType()
  215308. : AudioIODeviceType ("DirectSound"),
  215309. hasScanned (false)
  215310. {
  215311. initialiseDSoundFunctions();
  215312. }
  215313. ~DSoundAudioIODeviceType()
  215314. {
  215315. }
  215316. void scanForDevices()
  215317. {
  215318. hasScanned = true;
  215319. outputDeviceNames.clear();
  215320. outputGuids.clear();
  215321. inputDeviceNames.clear();
  215322. inputGuids.clear();
  215323. if (dsDirectSoundEnumerateW != 0)
  215324. {
  215325. dsDirectSoundEnumerateW (outputEnumProcW, this);
  215326. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  215327. }
  215328. }
  215329. const StringArray getDeviceNames (bool wantInputNames) const
  215330. {
  215331. jassert (hasScanned); // need to call scanForDevices() before doing this
  215332. return wantInputNames ? inputDeviceNames
  215333. : outputDeviceNames;
  215334. }
  215335. int getDefaultDeviceIndex (bool /*forInput*/) const
  215336. {
  215337. jassert (hasScanned); // need to call scanForDevices() before doing this
  215338. return 0;
  215339. }
  215340. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  215341. {
  215342. jassert (hasScanned); // need to call scanForDevices() before doing this
  215343. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  215344. if (d == 0)
  215345. return -1;
  215346. return asInput ? d->inputDeviceIndex
  215347. : d->outputDeviceIndex;
  215348. }
  215349. bool hasSeparateInputsAndOutputs() const { return true; }
  215350. AudioIODevice* createDevice (const String& outputDeviceName,
  215351. const String& inputDeviceName)
  215352. {
  215353. jassert (hasScanned); // need to call scanForDevices() before doing this
  215354. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  215355. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  215356. if (outputIndex >= 0 || inputIndex >= 0)
  215357. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  215358. : inputDeviceName,
  215359. outputIndex, inputIndex);
  215360. return 0;
  215361. }
  215362. juce_UseDebuggingNewOperator
  215363. StringArray outputDeviceNames;
  215364. OwnedArray <GUID> outputGuids;
  215365. StringArray inputDeviceNames;
  215366. OwnedArray <GUID> inputGuids;
  215367. private:
  215368. bool hasScanned;
  215369. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  215370. {
  215371. desc = desc.trim();
  215372. if (desc.isNotEmpty())
  215373. {
  215374. const String origDesc (desc);
  215375. int n = 2;
  215376. while (outputDeviceNames.contains (desc))
  215377. desc = origDesc + " (" + String (n++) + ")";
  215378. outputDeviceNames.add (desc);
  215379. if (lpGUID != 0)
  215380. outputGuids.add (new GUID (*lpGUID));
  215381. else
  215382. outputGuids.add (0);
  215383. }
  215384. return TRUE;
  215385. }
  215386. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  215387. {
  215388. return ((DSoundAudioIODeviceType*) object)
  215389. ->outputEnumProc (lpGUID, String (description));
  215390. }
  215391. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  215392. {
  215393. return ((DSoundAudioIODeviceType*) object)
  215394. ->outputEnumProc (lpGUID, String (description));
  215395. }
  215396. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  215397. {
  215398. desc = desc.trim();
  215399. if (desc.isNotEmpty())
  215400. {
  215401. const String origDesc (desc);
  215402. int n = 2;
  215403. while (inputDeviceNames.contains (desc))
  215404. desc = origDesc + " (" + String (n++) + ")";
  215405. inputDeviceNames.add (desc);
  215406. if (lpGUID != 0)
  215407. inputGuids.add (new GUID (*lpGUID));
  215408. else
  215409. inputGuids.add (0);
  215410. }
  215411. return TRUE;
  215412. }
  215413. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  215414. {
  215415. return ((DSoundAudioIODeviceType*) object)
  215416. ->inputEnumProc (lpGUID, String (description));
  215417. }
  215418. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  215419. {
  215420. return ((DSoundAudioIODeviceType*) object)
  215421. ->inputEnumProc (lpGUID, String (description));
  215422. }
  215423. DSoundAudioIODeviceType (const DSoundAudioIODeviceType&);
  215424. DSoundAudioIODeviceType& operator= (const DSoundAudioIODeviceType&);
  215425. };
  215426. const String DSoundAudioIODevice::openDevice (const BigInteger& inputChannels,
  215427. const BigInteger& outputChannels,
  215428. double sampleRate_,
  215429. int bufferSizeSamples_)
  215430. {
  215431. closeDevice();
  215432. totalSamplesOut = 0;
  215433. sampleRate = sampleRate_;
  215434. if (bufferSizeSamples_ <= 0)
  215435. bufferSizeSamples_ = 960; // use as a default size if none is set.
  215436. bufferSizeSamples = bufferSizeSamples_ & ~7;
  215437. DSoundAudioIODeviceType dlh;
  215438. dlh.scanForDevices();
  215439. enabledInputs = inputChannels;
  215440. enabledInputs.setRange (inChannels.size(),
  215441. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  215442. false);
  215443. inputBuffers.setSize (jmax (1, enabledInputs.countNumberOfSetBits()), bufferSizeSamples);
  215444. inputBuffers.clear();
  215445. int i, numIns = 0;
  215446. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  215447. {
  215448. float* left = 0;
  215449. if (enabledInputs[i])
  215450. left = inputBuffers.getSampleData (numIns++);
  215451. float* right = 0;
  215452. if (enabledInputs[i + 1])
  215453. right = inputBuffers.getSampleData (numIns++);
  215454. if (left != 0 || right != 0)
  215455. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  215456. dlh.inputGuids [inputDeviceIndex],
  215457. (int) sampleRate, bufferSizeSamples,
  215458. left, right));
  215459. }
  215460. enabledOutputs = outputChannels;
  215461. enabledOutputs.setRange (outChannels.size(),
  215462. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  215463. false);
  215464. outputBuffers.setSize (jmax (1, enabledOutputs.countNumberOfSetBits()), bufferSizeSamples);
  215465. outputBuffers.clear();
  215466. int numOuts = 0;
  215467. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  215468. {
  215469. float* left = 0;
  215470. if (enabledOutputs[i])
  215471. left = outputBuffers.getSampleData (numOuts++);
  215472. float* right = 0;
  215473. if (enabledOutputs[i + 1])
  215474. right = outputBuffers.getSampleData (numOuts++);
  215475. if (left != 0 || right != 0)
  215476. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  215477. dlh.outputGuids [outputDeviceIndex],
  215478. (int) sampleRate, bufferSizeSamples,
  215479. left, right));
  215480. }
  215481. String error;
  215482. // boost our priority while opening the devices to try to get better sync between them
  215483. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  215484. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  215485. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  215486. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  215487. for (i = 0; i < outChans.size(); ++i)
  215488. {
  215489. error = outChans[i]->open();
  215490. if (error.isNotEmpty())
  215491. {
  215492. error = "Error opening " + dlh.outputDeviceNames[i] + ": \"" + error + "\"";
  215493. break;
  215494. }
  215495. }
  215496. if (error.isEmpty())
  215497. {
  215498. for (i = 0; i < inChans.size(); ++i)
  215499. {
  215500. error = inChans[i]->open();
  215501. if (error.isNotEmpty())
  215502. {
  215503. error = "Error opening " + dlh.inputDeviceNames[i] + ": \"" + error + "\"";
  215504. break;
  215505. }
  215506. }
  215507. }
  215508. if (error.isEmpty())
  215509. {
  215510. totalSamplesOut = 0;
  215511. for (i = 0; i < outChans.size(); ++i)
  215512. outChans.getUnchecked(i)->synchronisePosition();
  215513. for (i = 0; i < inChans.size(); ++i)
  215514. inChans.getUnchecked(i)->synchronisePosition();
  215515. startThread (9);
  215516. sleep (10);
  215517. notify();
  215518. }
  215519. else
  215520. {
  215521. log (error);
  215522. }
  215523. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  215524. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  215525. return error;
  215526. }
  215527. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound()
  215528. {
  215529. return new DSoundAudioIODeviceType();
  215530. }
  215531. #undef log
  215532. #endif
  215533. /*** End of inlined file: juce_win32_DirectSound.cpp ***/
  215534. /*** Start of inlined file: juce_win32_WASAPI.cpp ***/
  215535. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  215536. // compiled on its own).
  215537. #if JUCE_INCLUDED_FILE && JUCE_WASAPI
  215538. #ifndef WASAPI_ENABLE_LOGGING
  215539. #define WASAPI_ENABLE_LOGGING 1
  215540. #endif
  215541. namespace WasapiClasses
  215542. {
  215543. static void logFailure (HRESULT hr)
  215544. {
  215545. (void) hr;
  215546. #if WASAPI_ENABLE_LOGGING
  215547. if (FAILED (hr))
  215548. {
  215549. String e;
  215550. e << Time::getCurrentTime().toString (true, true, true, true)
  215551. << " -- WASAPI error: ";
  215552. switch (hr)
  215553. {
  215554. case E_POINTER: e << "E_POINTER"; break;
  215555. case E_INVALIDARG: e << "E_INVALIDARG"; break;
  215556. case AUDCLNT_E_NOT_INITIALIZED: e << "AUDCLNT_E_NOT_INITIALIZED"; break;
  215557. case AUDCLNT_E_ALREADY_INITIALIZED: e << "AUDCLNT_E_ALREADY_INITIALIZED"; break;
  215558. case AUDCLNT_E_WRONG_ENDPOINT_TYPE: e << "AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
  215559. case AUDCLNT_E_DEVICE_INVALIDATED: e << "AUDCLNT_E_DEVICE_INVALIDATED"; break;
  215560. case AUDCLNT_E_NOT_STOPPED: e << "AUDCLNT_E_NOT_STOPPED"; break;
  215561. case AUDCLNT_E_BUFFER_TOO_LARGE: e << "AUDCLNT_E_BUFFER_TOO_LARGE"; break;
  215562. case AUDCLNT_E_OUT_OF_ORDER: e << "AUDCLNT_E_OUT_OF_ORDER"; break;
  215563. case AUDCLNT_E_UNSUPPORTED_FORMAT: e << "AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
  215564. case AUDCLNT_E_INVALID_SIZE: e << "AUDCLNT_E_INVALID_SIZE"; break;
  215565. case AUDCLNT_E_DEVICE_IN_USE: e << "AUDCLNT_E_DEVICE_IN_USE"; break;
  215566. case AUDCLNT_E_BUFFER_OPERATION_PENDING: e << "AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
  215567. case AUDCLNT_E_THREAD_NOT_REGISTERED: e << "AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
  215568. case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: e << "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
  215569. case AUDCLNT_E_ENDPOINT_CREATE_FAILED: e << "AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
  215570. case AUDCLNT_E_SERVICE_NOT_RUNNING: e << "AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
  215571. case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: e << "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
  215572. case AUDCLNT_E_EXCLUSIVE_MODE_ONLY: e << "AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
  215573. case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: e << "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
  215574. case AUDCLNT_E_EVENTHANDLE_NOT_SET: e << "AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
  215575. case AUDCLNT_E_INCORRECT_BUFFER_SIZE: e << "AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
  215576. case AUDCLNT_E_BUFFER_SIZE_ERROR: e << "AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
  215577. case AUDCLNT_S_BUFFER_EMPTY: e << "AUDCLNT_S_BUFFER_EMPTY"; break;
  215578. case AUDCLNT_S_THREAD_ALREADY_REGISTERED: e << "AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
  215579. default: e << String::toHexString ((int) hr); break;
  215580. }
  215581. DBG (e);
  215582. jassertfalse;
  215583. }
  215584. #endif
  215585. }
  215586. static bool check (HRESULT hr)
  215587. {
  215588. logFailure (hr);
  215589. return SUCCEEDED (hr);
  215590. }
  215591. static const String getDeviceID (IMMDevice* const device)
  215592. {
  215593. String s;
  215594. WCHAR* deviceId = 0;
  215595. if (check (device->GetId (&deviceId)))
  215596. {
  215597. s = String (deviceId);
  215598. CoTaskMemFree (deviceId);
  215599. }
  215600. return s;
  215601. }
  215602. static EDataFlow getDataFlow (const ComSmartPtr<IMMDevice>& device)
  215603. {
  215604. EDataFlow flow = eRender;
  215605. ComSmartPtr <IMMEndpoint> endPoint;
  215606. if (check (device.QueryInterface (__uuidof (IMMEndpoint), endPoint)))
  215607. (void) check (endPoint->GetDataFlow (&flow));
  215608. return flow;
  215609. }
  215610. static int refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw()
  215611. {
  215612. return roundDoubleToInt (sampleRate * ((double) t) * 0.0000001);
  215613. }
  215614. static void copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw()
  215615. {
  215616. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  215617. : sizeof (WAVEFORMATEX));
  215618. }
  215619. class WASAPIDeviceBase
  215620. {
  215621. public:
  215622. WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215623. : device (device_),
  215624. sampleRate (0),
  215625. numChannels (0),
  215626. actualNumChannels (0),
  215627. defaultSampleRate (0),
  215628. minBufferSize (0),
  215629. defaultBufferSize (0),
  215630. latencySamples (0),
  215631. useExclusiveMode (useExclusiveMode_)
  215632. {
  215633. clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));
  215634. ComSmartPtr <IAudioClient> tempClient (createClient());
  215635. if (tempClient == 0)
  215636. return;
  215637. REFERENCE_TIME defaultPeriod, minPeriod;
  215638. if (! check (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  215639. return;
  215640. WAVEFORMATEX* mixFormat = 0;
  215641. if (! check (tempClient->GetMixFormat (&mixFormat)))
  215642. return;
  215643. WAVEFORMATEXTENSIBLE format;
  215644. copyWavFormat (format, mixFormat);
  215645. CoTaskMemFree (mixFormat);
  215646. actualNumChannels = numChannels = format.Format.nChannels;
  215647. defaultSampleRate = format.Format.nSamplesPerSec;
  215648. minBufferSize = refTimeToSamples (minPeriod, defaultSampleRate);
  215649. defaultBufferSize = refTimeToSamples (defaultPeriod, defaultSampleRate);
  215650. rates.addUsingDefaultSort (defaultSampleRate);
  215651. static const double ratesToTest[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  215652. for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
  215653. {
  215654. if (ratesToTest[i] == defaultSampleRate)
  215655. continue;
  215656. format.Format.nSamplesPerSec = roundDoubleToInt (ratesToTest[i]);
  215657. if (SUCCEEDED (tempClient->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215658. (WAVEFORMATEX*) &format, 0)))
  215659. if (! rates.contains (ratesToTest[i]))
  215660. rates.addUsingDefaultSort (ratesToTest[i]);
  215661. }
  215662. }
  215663. ~WASAPIDeviceBase()
  215664. {
  215665. device = 0;
  215666. CloseHandle (clientEvent);
  215667. }
  215668. bool isOk() const throw() { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  215669. bool openClient (const double newSampleRate, const BigInteger& newChannels)
  215670. {
  215671. sampleRate = newSampleRate;
  215672. channels = newChannels;
  215673. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  215674. numChannels = channels.getHighestBit() + 1;
  215675. if (numChannels == 0)
  215676. return true;
  215677. client = createClient();
  215678. if (client != 0
  215679. && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
  215680. || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
  215681. {
  215682. channelMaps.clear();
  215683. for (int i = 0; i <= channels.getHighestBit(); ++i)
  215684. if (channels[i])
  215685. channelMaps.add (i);
  215686. REFERENCE_TIME latency;
  215687. if (check (client->GetStreamLatency (&latency)))
  215688. latencySamples = refTimeToSamples (latency, sampleRate);
  215689. (void) check (client->GetBufferSize (&actualBufferSize));
  215690. return check (client->SetEventHandle (clientEvent));
  215691. }
  215692. return false;
  215693. }
  215694. void closeClient()
  215695. {
  215696. if (client != 0)
  215697. client->Stop();
  215698. client = 0;
  215699. ResetEvent (clientEvent);
  215700. }
  215701. ComSmartPtr <IMMDevice> device;
  215702. ComSmartPtr <IAudioClient> client;
  215703. double sampleRate, defaultSampleRate;
  215704. int numChannels, actualNumChannels;
  215705. int minBufferSize, defaultBufferSize, latencySamples;
  215706. const bool useExclusiveMode;
  215707. Array <double> rates;
  215708. HANDLE clientEvent;
  215709. BigInteger channels;
  215710. Array <int> channelMaps;
  215711. UINT32 actualBufferSize;
  215712. int bytesPerSample;
  215713. virtual void updateFormat (bool isFloat) = 0;
  215714. private:
  215715. const ComSmartPtr <IAudioClient> createClient()
  215716. {
  215717. ComSmartPtr <IAudioClient> client;
  215718. if (device != 0)
  215719. {
  215720. HRESULT hr = device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER, 0, (void**) client.resetAndGetPointerAddress());
  215721. logFailure (hr);
  215722. }
  215723. return client;
  215724. }
  215725. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  215726. {
  215727. WAVEFORMATEXTENSIBLE format;
  215728. zerostruct (format);
  215729. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  215730. {
  215731. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  215732. }
  215733. else
  215734. {
  215735. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  215736. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  215737. }
  215738. format.Format.nSamplesPerSec = roundDoubleToInt (sampleRate);
  215739. format.Format.nChannels = (WORD) numChannels;
  215740. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  215741. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  215742. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  215743. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  215744. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  215745. switch (numChannels)
  215746. {
  215747. case 1: format.dwChannelMask = SPEAKER_FRONT_CENTER; break;
  215748. case 2: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  215749. case 4: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  215750. case 6: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  215751. 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;
  215752. default: break;
  215753. }
  215754. WAVEFORMATEXTENSIBLE* nearestFormat = 0;
  215755. HRESULT hr = client->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215756. (WAVEFORMATEX*) &format, useExclusiveMode ? 0 : (WAVEFORMATEX**) &nearestFormat);
  215757. logFailure (hr);
  215758. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  215759. {
  215760. copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  215761. hr = S_OK;
  215762. }
  215763. CoTaskMemFree (nearestFormat);
  215764. REFERENCE_TIME defaultPeriod = 0, minPeriod = 0;
  215765. if (useExclusiveMode)
  215766. check (client->GetDevicePeriod (&defaultPeriod, &minPeriod));
  215767. GUID session;
  215768. if (hr == S_OK
  215769. && check (client->Initialize (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215770. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  215771. defaultPeriod, defaultPeriod, (WAVEFORMATEX*) &format, &session)))
  215772. {
  215773. actualNumChannels = format.Format.nChannels;
  215774. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  215775. bytesPerSample = format.Format.wBitsPerSample / 8;
  215776. updateFormat (isFloat);
  215777. return true;
  215778. }
  215779. return false;
  215780. }
  215781. WASAPIDeviceBase (const WASAPIDeviceBase&);
  215782. WASAPIDeviceBase& operator= (const WASAPIDeviceBase&);
  215783. };
  215784. class WASAPIInputDevice : public WASAPIDeviceBase
  215785. {
  215786. public:
  215787. WASAPIInputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215788. : WASAPIDeviceBase (device_, useExclusiveMode_),
  215789. reservoir (1, 1)
  215790. {
  215791. }
  215792. ~WASAPIInputDevice()
  215793. {
  215794. close();
  215795. }
  215796. bool open (const double newSampleRate, const BigInteger& newChannels)
  215797. {
  215798. reservoirSize = 0;
  215799. reservoirCapacity = 16384;
  215800. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  215801. return openClient (newSampleRate, newChannels)
  215802. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioCaptureClient), (void**) captureClient.resetAndGetPointerAddress())));
  215803. }
  215804. void close()
  215805. {
  215806. closeClient();
  215807. captureClient = 0;
  215808. reservoir.setSize (0);
  215809. }
  215810. void updateFormat (bool isFloat)
  215811. {
  215812. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> NativeType;
  215813. if (isFloat)
  215814. converter = new AudioData::ConverterInstance <AudioData::Pointer <AudioData::Float32, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  215815. else if (bytesPerSample == 4)
  215816. converter = new AudioData::ConverterInstance <AudioData::Pointer <AudioData::Int32, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  215817. else if (bytesPerSample == 3)
  215818. converter = new AudioData::ConverterInstance <AudioData::Pointer <AudioData::Int24, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  215819. else
  215820. converter = new AudioData::ConverterInstance <AudioData::Pointer <AudioData::Int16, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  215821. }
  215822. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  215823. {
  215824. if (numChannels <= 0)
  215825. return;
  215826. int offset = 0;
  215827. while (bufferSize > 0)
  215828. {
  215829. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  215830. {
  215831. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  215832. for (int i = 0; i < numDestBuffers; ++i)
  215833. converter->convertSamples (destBuffers[i], offset, reservoir.getData(), channelMaps.getUnchecked(i), samplesToDo);
  215834. bufferSize -= samplesToDo;
  215835. offset += samplesToDo;
  215836. reservoirSize -= samplesToDo;
  215837. }
  215838. else
  215839. {
  215840. UINT32 packetLength = 0;
  215841. if (! check (captureClient->GetNextPacketSize (&packetLength)))
  215842. break;
  215843. if (packetLength == 0)
  215844. {
  215845. if (thread.threadShouldExit())
  215846. break;
  215847. Thread::sleep (1);
  215848. continue;
  215849. }
  215850. uint8* inputData = 0;
  215851. UINT32 numSamplesAvailable;
  215852. DWORD flags;
  215853. if (check (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  215854. {
  215855. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  215856. for (int i = 0; i < numDestBuffers; ++i)
  215857. converter->convertSamples (destBuffers[i], offset, inputData, channelMaps.getUnchecked(i), samplesToDo);
  215858. bufferSize -= samplesToDo;
  215859. offset += samplesToDo;
  215860. if (samplesToDo < (int) numSamplesAvailable)
  215861. {
  215862. reservoirSize = jmin ((int) (numSamplesAvailable - samplesToDo), reservoirCapacity);
  215863. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  215864. bytesPerSample * actualNumChannels * reservoirSize);
  215865. }
  215866. captureClient->ReleaseBuffer (numSamplesAvailable);
  215867. }
  215868. }
  215869. }
  215870. }
  215871. ComSmartPtr <IAudioCaptureClient> captureClient;
  215872. MemoryBlock reservoir;
  215873. int reservoirSize, reservoirCapacity;
  215874. ScopedPointer <AudioData::Converter> converter;
  215875. private:
  215876. WASAPIInputDevice (const WASAPIInputDevice&);
  215877. WASAPIInputDevice& operator= (const WASAPIInputDevice&);
  215878. };
  215879. class WASAPIOutputDevice : public WASAPIDeviceBase
  215880. {
  215881. public:
  215882. WASAPIOutputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215883. : WASAPIDeviceBase (device_, useExclusiveMode_)
  215884. {
  215885. }
  215886. ~WASAPIOutputDevice()
  215887. {
  215888. close();
  215889. }
  215890. bool open (const double newSampleRate, const BigInteger& newChannels)
  215891. {
  215892. return openClient (newSampleRate, newChannels)
  215893. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioRenderClient), (void**) renderClient.resetAndGetPointerAddress())));
  215894. }
  215895. void close()
  215896. {
  215897. closeClient();
  215898. renderClient = 0;
  215899. }
  215900. void updateFormat (bool isFloat)
  215901. {
  215902. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> NativeType;
  215903. if (isFloat)
  215904. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <AudioData::Float32, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  215905. else if (bytesPerSample == 4)
  215906. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <AudioData::Int32, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  215907. else if (bytesPerSample == 3)
  215908. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <AudioData::Int24, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  215909. else
  215910. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <AudioData::Int16, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  215911. }
  215912. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  215913. {
  215914. if (numChannels <= 0)
  215915. return;
  215916. int offset = 0;
  215917. while (bufferSize > 0)
  215918. {
  215919. UINT32 padding = 0;
  215920. if (! check (client->GetCurrentPadding (&padding)))
  215921. return;
  215922. int samplesToDo = useExclusiveMode ? bufferSize
  215923. : jmin ((int) (actualBufferSize - padding), bufferSize);
  215924. if (samplesToDo <= 0)
  215925. {
  215926. if (thread.threadShouldExit())
  215927. break;
  215928. Thread::sleep (0);
  215929. continue;
  215930. }
  215931. uint8* outputData = 0;
  215932. if (check (renderClient->GetBuffer (samplesToDo, &outputData)))
  215933. {
  215934. for (int i = 0; i < numSrcBuffers; ++i)
  215935. converter->convertSamples (outputData, channelMaps.getUnchecked(i), srcBuffers[i], offset, samplesToDo);
  215936. renderClient->ReleaseBuffer (samplesToDo, 0);
  215937. offset += samplesToDo;
  215938. bufferSize -= samplesToDo;
  215939. }
  215940. }
  215941. }
  215942. ComSmartPtr <IAudioRenderClient> renderClient;
  215943. ScopedPointer <AudioData::Converter> converter;
  215944. private:
  215945. WASAPIOutputDevice (const WASAPIOutputDevice&);
  215946. WASAPIOutputDevice& operator= (const WASAPIOutputDevice&);
  215947. };
  215948. class WASAPIAudioIODevice : public AudioIODevice,
  215949. public Thread
  215950. {
  215951. public:
  215952. WASAPIAudioIODevice (const String& deviceName,
  215953. const String& outputDeviceId_,
  215954. const String& inputDeviceId_,
  215955. const bool useExclusiveMode_)
  215956. : AudioIODevice (deviceName, "Windows Audio"),
  215957. Thread ("Juce WASAPI"),
  215958. isOpen_ (false),
  215959. isStarted (false),
  215960. outputDeviceId (outputDeviceId_),
  215961. inputDeviceId (inputDeviceId_),
  215962. useExclusiveMode (useExclusiveMode_),
  215963. currentBufferSizeSamples (0),
  215964. currentSampleRate (0),
  215965. callback (0)
  215966. {
  215967. }
  215968. ~WASAPIAudioIODevice()
  215969. {
  215970. close();
  215971. }
  215972. bool initialise()
  215973. {
  215974. double defaultSampleRateIn = 0, defaultSampleRateOut = 0;
  215975. int minBufferSizeIn = 0, defaultBufferSizeIn = 0, minBufferSizeOut = 0, defaultBufferSizeOut = 0;
  215976. latencyIn = latencyOut = 0;
  215977. Array <double> ratesIn, ratesOut;
  215978. if (createDevices())
  215979. {
  215980. jassert (inputDevice != 0 || outputDevice != 0);
  215981. if (inputDevice != 0 && outputDevice != 0)
  215982. {
  215983. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  215984. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  215985. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  215986. sampleRates = inputDevice->rates;
  215987. sampleRates.removeValuesNotIn (outputDevice->rates);
  215988. }
  215989. else
  215990. {
  215991. WASAPIDeviceBase* d = inputDevice != 0 ? static_cast<WASAPIDeviceBase*> (inputDevice)
  215992. : static_cast<WASAPIDeviceBase*> (outputDevice);
  215993. defaultSampleRate = d->defaultSampleRate;
  215994. minBufferSize = d->minBufferSize;
  215995. defaultBufferSize = d->defaultBufferSize;
  215996. sampleRates = d->rates;
  215997. }
  215998. bufferSizes.addUsingDefaultSort (defaultBufferSize);
  215999. if (minBufferSize != defaultBufferSize)
  216000. bufferSizes.addUsingDefaultSort (minBufferSize);
  216001. int n = 64;
  216002. for (int i = 0; i < 40; ++i)
  216003. {
  216004. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  216005. bufferSizes.addUsingDefaultSort (n);
  216006. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  216007. }
  216008. return true;
  216009. }
  216010. return false;
  216011. }
  216012. const StringArray getOutputChannelNames()
  216013. {
  216014. StringArray outChannels;
  216015. if (outputDevice != 0)
  216016. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  216017. outChannels.add ("Output channel " + String (i));
  216018. return outChannels;
  216019. }
  216020. const StringArray getInputChannelNames()
  216021. {
  216022. StringArray inChannels;
  216023. if (inputDevice != 0)
  216024. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  216025. inChannels.add ("Input channel " + String (i));
  216026. return inChannels;
  216027. }
  216028. int getNumSampleRates() { return sampleRates.size(); }
  216029. double getSampleRate (int index) { return sampleRates [index]; }
  216030. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  216031. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  216032. int getDefaultBufferSize() { return defaultBufferSize; }
  216033. int getCurrentBufferSizeSamples() { return currentBufferSizeSamples; }
  216034. double getCurrentSampleRate() { return currentSampleRate; }
  216035. int getCurrentBitDepth() { return 32; }
  216036. int getOutputLatencyInSamples() { return latencyOut; }
  216037. int getInputLatencyInSamples() { return latencyIn; }
  216038. const BigInteger getActiveOutputChannels() const { return outputDevice != 0 ? outputDevice->channels : BigInteger(); }
  216039. const BigInteger getActiveInputChannels() const { return inputDevice != 0 ? inputDevice->channels : BigInteger(); }
  216040. const String getLastError() { return lastError; }
  216041. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  216042. double sampleRate, int bufferSizeSamples)
  216043. {
  216044. close();
  216045. lastError = String::empty;
  216046. if (sampleRates.size() == 0 && inputDevice != 0 && outputDevice != 0)
  216047. {
  216048. lastError = "The input and output devices don't share a common sample rate!";
  216049. return lastError;
  216050. }
  216051. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  216052. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  216053. if (inputDevice != 0 && ! inputDevice->open (currentSampleRate, inputChannels))
  216054. {
  216055. lastError = "Couldn't open the input device!";
  216056. return lastError;
  216057. }
  216058. if (outputDevice != 0 && ! outputDevice->open (currentSampleRate, outputChannels))
  216059. {
  216060. close();
  216061. lastError = "Couldn't open the output device!";
  216062. return lastError;
  216063. }
  216064. if (inputDevice != 0)
  216065. ResetEvent (inputDevice->clientEvent);
  216066. if (outputDevice != 0)
  216067. ResetEvent (outputDevice->clientEvent);
  216068. startThread (8);
  216069. Thread::sleep (5);
  216070. if (inputDevice != 0 && inputDevice->client != 0)
  216071. {
  216072. latencyIn = inputDevice->latencySamples + inputDevice->actualBufferSize + inputDevice->minBufferSize;
  216073. HRESULT hr = inputDevice->client->Start();
  216074. logFailure (hr); //xxx handle this
  216075. }
  216076. if (outputDevice != 0 && outputDevice->client != 0)
  216077. {
  216078. latencyOut = outputDevice->latencySamples + outputDevice->actualBufferSize + outputDevice->minBufferSize;
  216079. HRESULT hr = outputDevice->client->Start();
  216080. logFailure (hr); //xxx handle this
  216081. }
  216082. isOpen_ = true;
  216083. return lastError;
  216084. }
  216085. void close()
  216086. {
  216087. stop();
  216088. if (inputDevice != 0)
  216089. SetEvent (inputDevice->clientEvent);
  216090. if (outputDevice != 0)
  216091. SetEvent (outputDevice->clientEvent);
  216092. stopThread (5000);
  216093. if (inputDevice != 0)
  216094. inputDevice->close();
  216095. if (outputDevice != 0)
  216096. outputDevice->close();
  216097. isOpen_ = false;
  216098. }
  216099. bool isOpen() { return isOpen_ && isThreadRunning(); }
  216100. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  216101. void start (AudioIODeviceCallback* call)
  216102. {
  216103. if (isOpen_ && call != 0 && ! isStarted)
  216104. {
  216105. if (! isThreadRunning())
  216106. {
  216107. // something's gone wrong and the thread's stopped..
  216108. isOpen_ = false;
  216109. return;
  216110. }
  216111. call->audioDeviceAboutToStart (this);
  216112. const ScopedLock sl (startStopLock);
  216113. callback = call;
  216114. isStarted = true;
  216115. }
  216116. }
  216117. void stop()
  216118. {
  216119. if (isStarted)
  216120. {
  216121. AudioIODeviceCallback* const callbackLocal = callback;
  216122. {
  216123. const ScopedLock sl (startStopLock);
  216124. isStarted = false;
  216125. }
  216126. if (callbackLocal != 0)
  216127. callbackLocal->audioDeviceStopped();
  216128. }
  216129. }
  216130. void setMMThreadPriority()
  216131. {
  216132. DynamicLibraryLoader dll ("avrt.dll");
  216133. DynamicLibraryImport (AvSetMmThreadCharacteristics, avSetMmThreadCharacteristics, HANDLE, dll, (LPCTSTR, LPDWORD))
  216134. DynamicLibraryImport (AvSetMmThreadPriority, avSetMmThreadPriority, HANDLE, dll, (HANDLE, AVRT_PRIORITY))
  216135. if (avSetMmThreadCharacteristics != 0 && avSetMmThreadPriority != 0)
  216136. {
  216137. DWORD dummy = 0;
  216138. HANDLE h = avSetMmThreadCharacteristics (_T("Pro Audio"), &dummy);
  216139. if (h != 0)
  216140. avSetMmThreadPriority (h, AVRT_PRIORITY_NORMAL);
  216141. }
  216142. }
  216143. void run()
  216144. {
  216145. setMMThreadPriority();
  216146. const int bufferSize = currentBufferSizeSamples;
  216147. HANDLE events[2];
  216148. int numEvents = 0;
  216149. if (inputDevice != 0)
  216150. events [numEvents++] = inputDevice->clientEvent;
  216151. if (outputDevice != 0)
  216152. events [numEvents++] = outputDevice->clientEvent;
  216153. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  216154. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  216155. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  216156. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  216157. float** const inputBuffers = ins.getArrayOfChannels();
  216158. float** const outputBuffers = outs.getArrayOfChannels();
  216159. ins.clear();
  216160. while (! threadShouldExit())
  216161. {
  216162. const DWORD result = useExclusiveMode ? (inputDevice != 0 ? WaitForSingleObject (inputDevice->clientEvent, 1000) : S_OK)
  216163. : WaitForMultipleObjects (numEvents, events, true, 1000);
  216164. if (result == WAIT_TIMEOUT)
  216165. continue;
  216166. if (threadShouldExit())
  216167. break;
  216168. if (inputDevice != 0)
  216169. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  216170. // Make the callback..
  216171. {
  216172. const ScopedLock sl (startStopLock);
  216173. if (isStarted)
  216174. {
  216175. JUCE_TRY
  216176. {
  216177. callback->audioDeviceIOCallback ((const float**) inputBuffers,
  216178. numInputBuffers,
  216179. outputBuffers,
  216180. numOutputBuffers,
  216181. bufferSize);
  216182. }
  216183. JUCE_CATCH_EXCEPTION
  216184. }
  216185. else
  216186. {
  216187. outs.clear();
  216188. }
  216189. }
  216190. if (useExclusiveMode && WaitForSingleObject (outputDevice->clientEvent, 1000) == WAIT_TIMEOUT)
  216191. continue;
  216192. if (outputDevice != 0)
  216193. outputDevice->copyBuffers ((const float**) outputBuffers, numOutputBuffers, bufferSize, *this);
  216194. }
  216195. }
  216196. juce_UseDebuggingNewOperator
  216197. String outputDeviceId, inputDeviceId;
  216198. String lastError;
  216199. private:
  216200. // Device stats...
  216201. ScopedPointer<WASAPIInputDevice> inputDevice;
  216202. ScopedPointer<WASAPIOutputDevice> outputDevice;
  216203. const bool useExclusiveMode;
  216204. double defaultSampleRate;
  216205. int minBufferSize, defaultBufferSize;
  216206. int latencyIn, latencyOut;
  216207. Array <double> sampleRates;
  216208. Array <int> bufferSizes;
  216209. // Active state...
  216210. bool isOpen_, isStarted;
  216211. int currentBufferSizeSamples;
  216212. double currentSampleRate;
  216213. AudioIODeviceCallback* callback;
  216214. CriticalSection startStopLock;
  216215. bool createDevices()
  216216. {
  216217. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  216218. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  216219. return false;
  216220. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  216221. if (! check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress())))
  216222. return false;
  216223. UINT32 numDevices = 0;
  216224. if (! check (deviceCollection->GetCount (&numDevices)))
  216225. return false;
  216226. for (UINT32 i = 0; i < numDevices; ++i)
  216227. {
  216228. ComSmartPtr <IMMDevice> device;
  216229. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  216230. continue;
  216231. const String deviceId (getDeviceID (device));
  216232. if (deviceId.isEmpty())
  216233. continue;
  216234. const EDataFlow flow = getDataFlow (device);
  216235. if (deviceId == inputDeviceId && flow == eCapture)
  216236. inputDevice = new WASAPIInputDevice (device, useExclusiveMode);
  216237. else if (deviceId == outputDeviceId && flow == eRender)
  216238. outputDevice = new WASAPIOutputDevice (device, useExclusiveMode);
  216239. }
  216240. return (outputDeviceId.isEmpty() || (outputDevice != 0 && outputDevice->isOk()))
  216241. && (inputDeviceId.isEmpty() || (inputDevice != 0 && inputDevice->isOk()));
  216242. }
  216243. WASAPIAudioIODevice (const WASAPIAudioIODevice&);
  216244. WASAPIAudioIODevice& operator= (const WASAPIAudioIODevice&);
  216245. };
  216246. class WASAPIAudioIODeviceType : public AudioIODeviceType
  216247. {
  216248. public:
  216249. WASAPIAudioIODeviceType()
  216250. : AudioIODeviceType ("Windows Audio"),
  216251. hasScanned (false)
  216252. {
  216253. }
  216254. ~WASAPIAudioIODeviceType()
  216255. {
  216256. }
  216257. void scanForDevices()
  216258. {
  216259. hasScanned = true;
  216260. outputDeviceNames.clear();
  216261. inputDeviceNames.clear();
  216262. outputDeviceIds.clear();
  216263. inputDeviceIds.clear();
  216264. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  216265. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  216266. return;
  216267. const String defaultRenderer = getDefaultEndpoint (enumerator, false);
  216268. const String defaultCapture = getDefaultEndpoint (enumerator, true);
  216269. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  216270. UINT32 numDevices = 0;
  216271. if (! (check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress()))
  216272. && check (deviceCollection->GetCount (&numDevices))))
  216273. return;
  216274. for (UINT32 i = 0; i < numDevices; ++i)
  216275. {
  216276. ComSmartPtr <IMMDevice> device;
  216277. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  216278. continue;
  216279. const String deviceId (getDeviceID (device));
  216280. DWORD state = 0;
  216281. if (! check (device->GetState (&state)))
  216282. continue;
  216283. if (state != DEVICE_STATE_ACTIVE)
  216284. continue;
  216285. String name;
  216286. {
  216287. ComSmartPtr <IPropertyStore> properties;
  216288. if (! check (device->OpenPropertyStore (STGM_READ, properties.resetAndGetPointerAddress())))
  216289. continue;
  216290. PROPVARIANT value;
  216291. PropVariantInit (&value);
  216292. if (check (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  216293. name = value.pwszVal;
  216294. PropVariantClear (&value);
  216295. }
  216296. const EDataFlow flow = getDataFlow (device);
  216297. if (flow == eRender)
  216298. {
  216299. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  216300. outputDeviceIds.insert (index, deviceId);
  216301. outputDeviceNames.insert (index, name);
  216302. }
  216303. else if (flow == eCapture)
  216304. {
  216305. const int index = (deviceId == defaultCapture) ? 0 : -1;
  216306. inputDeviceIds.insert (index, deviceId);
  216307. inputDeviceNames.insert (index, name);
  216308. }
  216309. }
  216310. inputDeviceNames.appendNumbersToDuplicates (false, false);
  216311. outputDeviceNames.appendNumbersToDuplicates (false, false);
  216312. }
  216313. const StringArray getDeviceNames (bool wantInputNames) const
  216314. {
  216315. jassert (hasScanned); // need to call scanForDevices() before doing this
  216316. return wantInputNames ? inputDeviceNames
  216317. : outputDeviceNames;
  216318. }
  216319. int getDefaultDeviceIndex (bool /*forInput*/) const
  216320. {
  216321. jassert (hasScanned); // need to call scanForDevices() before doing this
  216322. return 0;
  216323. }
  216324. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  216325. {
  216326. jassert (hasScanned); // need to call scanForDevices() before doing this
  216327. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  216328. return d == 0 ? -1 : (asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  216329. : outputDeviceIds.indexOf (d->outputDeviceId));
  216330. }
  216331. bool hasSeparateInputsAndOutputs() const { return true; }
  216332. AudioIODevice* createDevice (const String& outputDeviceName,
  216333. const String& inputDeviceName)
  216334. {
  216335. jassert (hasScanned); // need to call scanForDevices() before doing this
  216336. const bool useExclusiveMode = false;
  216337. ScopedPointer<WASAPIAudioIODevice> device;
  216338. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  216339. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  216340. if (outputIndex >= 0 || inputIndex >= 0)
  216341. {
  216342. device = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  216343. : inputDeviceName,
  216344. outputDeviceIds [outputIndex],
  216345. inputDeviceIds [inputIndex],
  216346. useExclusiveMode);
  216347. if (! device->initialise())
  216348. device = 0;
  216349. }
  216350. return device.release();
  216351. }
  216352. juce_UseDebuggingNewOperator
  216353. StringArray outputDeviceNames, outputDeviceIds;
  216354. StringArray inputDeviceNames, inputDeviceIds;
  216355. private:
  216356. bool hasScanned;
  216357. static const String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  216358. {
  216359. String s;
  216360. IMMDevice* dev = 0;
  216361. if (check (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  216362. eMultimedia, &dev)))
  216363. {
  216364. WCHAR* deviceId = 0;
  216365. if (check (dev->GetId (&deviceId)))
  216366. {
  216367. s = String (deviceId);
  216368. CoTaskMemFree (deviceId);
  216369. }
  216370. dev->Release();
  216371. }
  216372. return s;
  216373. }
  216374. WASAPIAudioIODeviceType (const WASAPIAudioIODeviceType&);
  216375. WASAPIAudioIODeviceType& operator= (const WASAPIAudioIODeviceType&);
  216376. };
  216377. }
  216378. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI()
  216379. {
  216380. return new WasapiClasses::WASAPIAudioIODeviceType();
  216381. }
  216382. #endif
  216383. /*** End of inlined file: juce_win32_WASAPI.cpp ***/
  216384. /*** Start of inlined file: juce_win32_CameraDevice.cpp ***/
  216385. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  216386. // compiled on its own).
  216387. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  216388. class DShowCameraDeviceInteral : public ChangeBroadcaster
  216389. {
  216390. public:
  216391. DShowCameraDeviceInteral (CameraDevice* const owner_,
  216392. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  216393. const ComSmartPtr <IBaseFilter>& filter_,
  216394. int minWidth, int minHeight,
  216395. int maxWidth, int maxHeight)
  216396. : owner (owner_),
  216397. captureGraphBuilder (captureGraphBuilder_),
  216398. filter (filter_),
  216399. ok (false),
  216400. imageNeedsFlipping (false),
  216401. width (0),
  216402. height (0),
  216403. activeUsers (0),
  216404. recordNextFrameTime (false)
  216405. {
  216406. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph);
  216407. if (FAILED (hr))
  216408. return;
  216409. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  216410. if (FAILED (hr))
  216411. return;
  216412. hr = graphBuilder.QueryInterface (IID_IMediaControl, mediaControl);
  216413. if (FAILED (hr))
  216414. return;
  216415. {
  216416. ComSmartPtr <IAMStreamConfig> streamConfig;
  216417. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE, 0, filter,
  216418. IID_IAMStreamConfig, (void**) streamConfig.resetAndGetPointerAddress());
  216419. if (streamConfig != 0)
  216420. {
  216421. getVideoSizes (streamConfig);
  216422. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  216423. return;
  216424. }
  216425. }
  216426. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  216427. if (FAILED (hr))
  216428. return;
  216429. hr = smartTee.CoCreateInstance (CLSID_SmartTee);
  216430. if (FAILED (hr))
  216431. return;
  216432. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  216433. if (FAILED (hr))
  216434. return;
  216435. if (! connectFilters (filter, smartTee))
  216436. return;
  216437. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  216438. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber);
  216439. if (FAILED (hr))
  216440. return;
  216441. hr = sampleGrabberBase.QueryInterface (IID_ISampleGrabber, sampleGrabber);
  216442. if (FAILED (hr))
  216443. return;
  216444. AM_MEDIA_TYPE mt;
  216445. zerostruct (mt);
  216446. mt.majortype = MEDIATYPE_Video;
  216447. mt.subtype = MEDIASUBTYPE_RGB24;
  216448. mt.formattype = FORMAT_VideoInfo;
  216449. sampleGrabber->SetMediaType (&mt);
  216450. callback = new GrabberCallback (*this);
  216451. hr = sampleGrabber->SetCallback (callback, 1);
  216452. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  216453. if (FAILED (hr))
  216454. return;
  216455. ComSmartPtr <IPin> grabberInputPin;
  216456. if (! (getPin (smartTee, PINDIR_OUTPUT, smartTeeCaptureOutputPin, "capture")
  216457. && getPin (smartTee, PINDIR_OUTPUT, smartTeePreviewOutputPin, "preview")
  216458. && getPin (sampleGrabberBase, PINDIR_INPUT, grabberInputPin)))
  216459. return;
  216460. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  216461. if (FAILED (hr))
  216462. return;
  216463. zerostruct (mt);
  216464. hr = sampleGrabber->GetConnectedMediaType (&mt);
  216465. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  216466. width = pVih->bmiHeader.biWidth;
  216467. height = pVih->bmiHeader.biHeight;
  216468. ComSmartPtr <IBaseFilter> nullFilter;
  216469. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer);
  216470. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  216471. if (connectFilters (sampleGrabberBase, nullFilter)
  216472. && addGraphToRot())
  216473. {
  216474. activeImage = Image (Image::RGB, width, height, true);
  216475. loadingImage = Image (Image::RGB, width, height, true);
  216476. ok = true;
  216477. }
  216478. }
  216479. ~DShowCameraDeviceInteral()
  216480. {
  216481. if (mediaControl != 0)
  216482. mediaControl->Stop();
  216483. removeGraphFromRot();
  216484. for (int i = viewerComps.size(); --i >= 0;)
  216485. viewerComps.getUnchecked(i)->ownerDeleted();
  216486. callback = 0;
  216487. graphBuilder = 0;
  216488. sampleGrabber = 0;
  216489. mediaControl = 0;
  216490. filter = 0;
  216491. captureGraphBuilder = 0;
  216492. smartTee = 0;
  216493. smartTeePreviewOutputPin = 0;
  216494. smartTeeCaptureOutputPin = 0;
  216495. asfWriter = 0;
  216496. }
  216497. void addUser()
  216498. {
  216499. if (ok && activeUsers++ == 0)
  216500. mediaControl->Run();
  216501. }
  216502. void removeUser()
  216503. {
  216504. if (ok && --activeUsers == 0)
  216505. mediaControl->Stop();
  216506. }
  216507. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  216508. {
  216509. if (recordNextFrameTime)
  216510. {
  216511. const double defaultCameraLatency = 0.1;
  216512. firstRecordedTime = Time::getCurrentTime() - RelativeTime (defaultCameraLatency);
  216513. recordNextFrameTime = false;
  216514. ComSmartPtr <IPin> pin;
  216515. if (getPin (filter, PINDIR_OUTPUT, pin))
  216516. {
  216517. ComSmartPtr <IAMPushSource> pushSource;
  216518. HRESULT hr = pin.QueryInterface (IID_IAMPushSource, pushSource);
  216519. if (pushSource != 0)
  216520. {
  216521. REFERENCE_TIME latency = 0;
  216522. hr = pushSource->GetLatency (&latency);
  216523. firstRecordedTime = firstRecordedTime - RelativeTime ((double) latency);
  216524. }
  216525. }
  216526. }
  216527. {
  216528. const int lineStride = width * 3;
  216529. const ScopedLock sl (imageSwapLock);
  216530. {
  216531. const Image::BitmapData destData (loadingImage, 0, 0, width, height, true);
  216532. for (int i = 0; i < height; ++i)
  216533. memcpy (destData.getLinePointer ((height - 1) - i),
  216534. buffer + lineStride * i,
  216535. lineStride);
  216536. }
  216537. imageNeedsFlipping = true;
  216538. }
  216539. if (listeners.size() > 0)
  216540. callListeners (loadingImage);
  216541. sendChangeMessage (this);
  216542. }
  216543. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  216544. {
  216545. if (imageNeedsFlipping)
  216546. {
  216547. const ScopedLock sl (imageSwapLock);
  216548. swapVariables (loadingImage, activeImage);
  216549. imageNeedsFlipping = false;
  216550. }
  216551. RectanglePlacement rp (RectanglePlacement::centred);
  216552. double dx = 0, dy = 0, dw = width, dh = height;
  216553. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  216554. const int rx = roundToInt (dx), ry = roundToInt (dy);
  216555. const int rw = roundToInt (dw), rh = roundToInt (dh);
  216556. g.saveState();
  216557. g.excludeClipRegion (Rectangle<int> (rx, ry, rw, rh));
  216558. g.fillAll (Colours::black);
  216559. g.restoreState();
  216560. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  216561. }
  216562. bool createFileCaptureFilter (const File& file)
  216563. {
  216564. removeFileCaptureFilter();
  216565. file.deleteFile();
  216566. mediaControl->Stop();
  216567. firstRecordedTime = Time();
  216568. recordNextFrameTime = true;
  216569. HRESULT hr = asfWriter.CoCreateInstance (CLSID_WMAsfWriter);
  216570. if (SUCCEEDED (hr))
  216571. {
  216572. ComSmartPtr <IFileSinkFilter> fileSink;
  216573. hr = asfWriter.QueryInterface (IID_IFileSinkFilter, fileSink);
  216574. if (SUCCEEDED (hr))
  216575. {
  216576. hr = fileSink->SetFileName (file.getFullPathName(), 0);
  216577. if (SUCCEEDED (hr))
  216578. {
  216579. hr = graphBuilder->AddFilter (asfWriter, _T("AsfWriter"));
  216580. if (SUCCEEDED (hr))
  216581. {
  216582. ComSmartPtr <IConfigAsfWriter> asfConfig;
  216583. hr = asfWriter.QueryInterface (IID_IConfigAsfWriter, asfConfig);
  216584. asfConfig->SetIndexMode (true);
  216585. ComSmartPtr <IWMProfileManager> profileManager;
  216586. hr = WMCreateProfileManager (profileManager.resetAndGetPointerAddress());
  216587. // This gibberish is the DirectShow profile for a video-only wmv file.
  216588. String prof ("<profile version=\"589824\" storageformat=\"1\" name=\"Quality\" description=\"Quality type for output.\"><streamconfig "
  216589. "majortype=\"{73646976-0000-0010-8000-00AA00389B71}\" streamnumber=\"1\" streamname=\"Video Stream\" inputname=\"Video409\" bitrate=\"894960\" "
  216590. "bufferwindow=\"0\" reliabletransport=\"1\" decodercomplexity=\"AU\" rfc1766langid=\"en-us\"><videomediaprops maxkeyframespacing=\"50000000\" quality=\"90\"/>"
  216591. "<wmmediatype subtype=\"{33564D57-0000-0010-8000-00AA00389B71}\" bfixedsizesamples=\"0\" btemporalcompression=\"1\" lsamplesize=\"0\"> <videoinfoheader "
  216592. "dwbitrate=\"894960\" dwbiterrorrate=\"0\" avgtimeperframe=\"100000\"><rcsource left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/> <rctarget "
  216593. "left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/> <bitmapinfoheader biwidth=\"$WIDTH\" biheight=\"$HEIGHT\" biplanes=\"1\" bibitcount=\"24\" "
  216594. "bicompression=\"WMV3\" bisizeimage=\"0\" bixpelspermeter=\"0\" biypelspermeter=\"0\" biclrused=\"0\" biclrimportant=\"0\"/> "
  216595. "</videoinfoheader></wmmediatype></streamconfig></profile>");
  216596. prof = prof.replace ("$WIDTH", String (width))
  216597. .replace ("$HEIGHT", String (height));
  216598. ComSmartPtr <IWMProfile> currentProfile;
  216599. hr = profileManager->LoadProfileByData ((const WCHAR*) prof, currentProfile.resetAndGetPointerAddress());
  216600. hr = asfConfig->ConfigureFilterUsingProfile (currentProfile);
  216601. if (SUCCEEDED (hr))
  216602. {
  216603. ComSmartPtr <IPin> asfWriterInputPin;
  216604. if (getPin (asfWriter, PINDIR_INPUT, asfWriterInputPin, "Video Input 01"))
  216605. {
  216606. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, asfWriterInputPin);
  216607. if (SUCCEEDED (hr)
  216608. && ok && activeUsers > 0
  216609. && SUCCEEDED (mediaControl->Run()))
  216610. {
  216611. return true;
  216612. }
  216613. }
  216614. }
  216615. }
  216616. }
  216617. }
  216618. }
  216619. removeFileCaptureFilter();
  216620. if (ok && activeUsers > 0)
  216621. mediaControl->Run();
  216622. return false;
  216623. }
  216624. void removeFileCaptureFilter()
  216625. {
  216626. mediaControl->Stop();
  216627. if (asfWriter != 0)
  216628. {
  216629. graphBuilder->RemoveFilter (asfWriter);
  216630. asfWriter = 0;
  216631. }
  216632. if (ok && activeUsers > 0)
  216633. mediaControl->Run();
  216634. }
  216635. void addListener (CameraDevice::Listener* listenerToAdd)
  216636. {
  216637. const ScopedLock sl (listenerLock);
  216638. if (listeners.size() == 0)
  216639. addUser();
  216640. listeners.addIfNotAlreadyThere (listenerToAdd);
  216641. }
  216642. void removeListener (CameraDevice::Listener* listenerToRemove)
  216643. {
  216644. const ScopedLock sl (listenerLock);
  216645. listeners.removeValue (listenerToRemove);
  216646. if (listeners.size() == 0)
  216647. removeUser();
  216648. }
  216649. void callListeners (const Image& image)
  216650. {
  216651. const ScopedLock sl (listenerLock);
  216652. for (int i = listeners.size(); --i >= 0;)
  216653. {
  216654. CameraDevice::Listener* const l = listeners[i];
  216655. if (l != 0)
  216656. l->imageReceived (image);
  216657. }
  216658. }
  216659. class DShowCaptureViewerComp : public Component,
  216660. public ChangeListener
  216661. {
  216662. public:
  216663. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  216664. : owner (owner_)
  216665. {
  216666. setOpaque (true);
  216667. owner->addChangeListener (this);
  216668. owner->addUser();
  216669. owner->viewerComps.add (this);
  216670. setSize (owner->width, owner->height);
  216671. }
  216672. ~DShowCaptureViewerComp()
  216673. {
  216674. if (owner != 0)
  216675. {
  216676. owner->viewerComps.removeValue (this);
  216677. owner->removeUser();
  216678. owner->removeChangeListener (this);
  216679. }
  216680. }
  216681. void ownerDeleted()
  216682. {
  216683. owner = 0;
  216684. }
  216685. void paint (Graphics& g)
  216686. {
  216687. g.setColour (Colours::black);
  216688. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  216689. if (owner != 0)
  216690. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  216691. else
  216692. g.fillAll (Colours::black);
  216693. }
  216694. void changeListenerCallback (void*)
  216695. {
  216696. repaint();
  216697. }
  216698. private:
  216699. DShowCameraDeviceInteral* owner;
  216700. };
  216701. bool ok;
  216702. int width, height;
  216703. Time firstRecordedTime;
  216704. Array <DShowCaptureViewerComp*> viewerComps;
  216705. private:
  216706. CameraDevice* const owner;
  216707. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  216708. ComSmartPtr <IBaseFilter> filter;
  216709. ComSmartPtr <IBaseFilter> smartTee;
  216710. ComSmartPtr <IGraphBuilder> graphBuilder;
  216711. ComSmartPtr <ISampleGrabber> sampleGrabber;
  216712. ComSmartPtr <IMediaControl> mediaControl;
  216713. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  216714. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  216715. ComSmartPtr <IBaseFilter> asfWriter;
  216716. int activeUsers;
  216717. Array <int> widths, heights;
  216718. DWORD graphRegistrationID;
  216719. CriticalSection imageSwapLock;
  216720. bool imageNeedsFlipping;
  216721. Image loadingImage;
  216722. Image activeImage;
  216723. bool recordNextFrameTime;
  216724. void getVideoSizes (IAMStreamConfig* const streamConfig)
  216725. {
  216726. widths.clear();
  216727. heights.clear();
  216728. int count = 0, size = 0;
  216729. streamConfig->GetNumberOfCapabilities (&count, &size);
  216730. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  216731. {
  216732. for (int i = 0; i < count; ++i)
  216733. {
  216734. VIDEO_STREAM_CONFIG_CAPS scc;
  216735. AM_MEDIA_TYPE* config;
  216736. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  216737. if (SUCCEEDED (hr))
  216738. {
  216739. const int w = scc.InputSize.cx;
  216740. const int h = scc.InputSize.cy;
  216741. bool duplicate = false;
  216742. for (int j = widths.size(); --j >= 0;)
  216743. {
  216744. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  216745. {
  216746. duplicate = true;
  216747. break;
  216748. }
  216749. }
  216750. if (! duplicate)
  216751. {
  216752. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  216753. widths.add (w);
  216754. heights.add (h);
  216755. }
  216756. deleteMediaType (config);
  216757. }
  216758. }
  216759. }
  216760. }
  216761. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  216762. const int minWidth, const int minHeight,
  216763. const int maxWidth, const int maxHeight)
  216764. {
  216765. int count = 0, size = 0, bestArea = 0, bestIndex = -1;
  216766. streamConfig->GetNumberOfCapabilities (&count, &size);
  216767. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  216768. {
  216769. AM_MEDIA_TYPE* config;
  216770. VIDEO_STREAM_CONFIG_CAPS scc;
  216771. for (int i = 0; i < count; ++i)
  216772. {
  216773. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  216774. if (SUCCEEDED (hr))
  216775. {
  216776. if (scc.InputSize.cx >= minWidth
  216777. && scc.InputSize.cy >= minHeight
  216778. && scc.InputSize.cx <= maxWidth
  216779. && scc.InputSize.cy <= maxHeight)
  216780. {
  216781. int area = scc.InputSize.cx * scc.InputSize.cy;
  216782. if (area > bestArea)
  216783. {
  216784. bestIndex = i;
  216785. bestArea = area;
  216786. }
  216787. }
  216788. deleteMediaType (config);
  216789. }
  216790. }
  216791. if (bestIndex >= 0)
  216792. {
  216793. HRESULT hr = streamConfig->GetStreamCaps (bestIndex, &config, (BYTE*) &scc);
  216794. hr = streamConfig->SetFormat (config);
  216795. deleteMediaType (config);
  216796. return SUCCEEDED (hr);
  216797. }
  216798. }
  216799. return false;
  216800. }
  216801. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection, ComSmartPtr<IPin>& result, const char* pinName = 0)
  216802. {
  216803. ComSmartPtr <IEnumPins> enumerator;
  216804. ComSmartPtr <IPin> pin;
  216805. filter->EnumPins (enumerator.resetAndGetPointerAddress());
  216806. while (enumerator->Next (1, pin.resetAndGetPointerAddress(), 0) == S_OK)
  216807. {
  216808. PIN_DIRECTION dir;
  216809. pin->QueryDirection (&dir);
  216810. if (wantedDirection == dir)
  216811. {
  216812. PIN_INFO info;
  216813. zerostruct (info);
  216814. pin->QueryPinInfo (&info);
  216815. if (pinName == 0 || String (pinName).equalsIgnoreCase (String (info.achName)))
  216816. {
  216817. result = pin;
  216818. return true;
  216819. }
  216820. }
  216821. }
  216822. return false;
  216823. }
  216824. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  216825. {
  216826. ComSmartPtr <IPin> in, out;
  216827. return getPin (first, PINDIR_OUTPUT, out)
  216828. && getPin (second, PINDIR_INPUT, in)
  216829. && SUCCEEDED (graphBuilder->Connect (out, in));
  216830. }
  216831. bool addGraphToRot()
  216832. {
  216833. ComSmartPtr <IRunningObjectTable> rot;
  216834. if (FAILED (GetRunningObjectTable (0, rot.resetAndGetPointerAddress())))
  216835. return false;
  216836. ComSmartPtr <IMoniker> moniker;
  216837. WCHAR buffer[128];
  216838. HRESULT hr = CreateItemMoniker (_T("!"), buffer, moniker.resetAndGetPointerAddress());
  216839. if (FAILED (hr))
  216840. return false;
  216841. graphRegistrationID = 0;
  216842. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  216843. }
  216844. void removeGraphFromRot()
  216845. {
  216846. ComSmartPtr <IRunningObjectTable> rot;
  216847. if (SUCCEEDED (GetRunningObjectTable (0, rot.resetAndGetPointerAddress())))
  216848. rot->Revoke (graphRegistrationID);
  216849. }
  216850. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  216851. {
  216852. if (pmt->cbFormat != 0)
  216853. CoTaskMemFree ((PVOID) pmt->pbFormat);
  216854. if (pmt->pUnk != 0)
  216855. pmt->pUnk->Release();
  216856. CoTaskMemFree (pmt);
  216857. }
  216858. class GrabberCallback : public ComBaseClassHelper <ISampleGrabberCB>
  216859. {
  216860. public:
  216861. GrabberCallback (DShowCameraDeviceInteral& owner_)
  216862. : owner (owner_)
  216863. {
  216864. }
  216865. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/)
  216866. {
  216867. return E_FAIL;
  216868. }
  216869. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  216870. {
  216871. owner.handleFrame (time, buffer, bufferSize);
  216872. return S_OK;
  216873. }
  216874. private:
  216875. DShowCameraDeviceInteral& owner;
  216876. GrabberCallback (const GrabberCallback&);
  216877. GrabberCallback& operator= (const GrabberCallback&);
  216878. };
  216879. ComSmartPtr <GrabberCallback> callback;
  216880. Array <CameraDevice::Listener*> listeners;
  216881. CriticalSection listenerLock;
  216882. DShowCameraDeviceInteral (const DShowCameraDeviceInteral&);
  216883. DShowCameraDeviceInteral& operator= (const DShowCameraDeviceInteral&);
  216884. };
  216885. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  216886. : name (name_)
  216887. {
  216888. isRecording = false;
  216889. }
  216890. CameraDevice::~CameraDevice()
  216891. {
  216892. stopRecording();
  216893. delete static_cast <DShowCameraDeviceInteral*> (internal);
  216894. internal = 0;
  216895. }
  216896. Component* CameraDevice::createViewerComponent()
  216897. {
  216898. return new DShowCameraDeviceInteral::DShowCaptureViewerComp (static_cast <DShowCameraDeviceInteral*> (internal));
  216899. }
  216900. const String CameraDevice::getFileExtension()
  216901. {
  216902. return ".wmv";
  216903. }
  216904. void CameraDevice::startRecordingToFile (const File& file, int quality)
  216905. {
  216906. stopRecording();
  216907. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216908. d->addUser();
  216909. isRecording = d->createFileCaptureFilter (file);
  216910. }
  216911. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  216912. {
  216913. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216914. return d->firstRecordedTime;
  216915. }
  216916. void CameraDevice::stopRecording()
  216917. {
  216918. if (isRecording)
  216919. {
  216920. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216921. d->removeFileCaptureFilter();
  216922. d->removeUser();
  216923. isRecording = false;
  216924. }
  216925. }
  216926. void CameraDevice::addListener (Listener* listenerToAdd)
  216927. {
  216928. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216929. if (listenerToAdd != 0)
  216930. d->addListener (listenerToAdd);
  216931. }
  216932. void CameraDevice::removeListener (Listener* listenerToRemove)
  216933. {
  216934. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  216935. if (listenerToRemove != 0)
  216936. d->removeListener (listenerToRemove);
  216937. }
  216938. static ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  216939. const int deviceIndexToOpen,
  216940. String& name)
  216941. {
  216942. int index = 0;
  216943. ComSmartPtr <IBaseFilter> result;
  216944. ComSmartPtr <ICreateDevEnum> pDevEnum;
  216945. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum);
  216946. if (SUCCEEDED (hr))
  216947. {
  216948. ComSmartPtr <IEnumMoniker> enumerator;
  216949. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, enumerator.resetAndGetPointerAddress(), 0);
  216950. if (SUCCEEDED (hr) && enumerator != 0)
  216951. {
  216952. ComSmartPtr <IMoniker> moniker;
  216953. ULONG fetched;
  216954. while (enumerator->Next (1, moniker.resetAndGetPointerAddress(), &fetched) == S_OK)
  216955. {
  216956. ComSmartPtr <IBaseFilter> captureFilter;
  216957. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) captureFilter.resetAndGetPointerAddress());
  216958. if (SUCCEEDED (hr))
  216959. {
  216960. ComSmartPtr <IPropertyBag> propertyBag;
  216961. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) propertyBag.resetAndGetPointerAddress());
  216962. if (SUCCEEDED (hr))
  216963. {
  216964. VARIANT var;
  216965. var.vt = VT_BSTR;
  216966. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  216967. propertyBag = 0;
  216968. if (SUCCEEDED (hr))
  216969. {
  216970. if (names != 0)
  216971. names->add (var.bstrVal);
  216972. if (index == deviceIndexToOpen)
  216973. {
  216974. name = var.bstrVal;
  216975. result = captureFilter;
  216976. break;
  216977. }
  216978. ++index;
  216979. }
  216980. }
  216981. }
  216982. }
  216983. }
  216984. }
  216985. return result;
  216986. }
  216987. const StringArray CameraDevice::getAvailableDevices()
  216988. {
  216989. StringArray devs;
  216990. String dummy;
  216991. enumerateCameras (&devs, -1, dummy);
  216992. return devs;
  216993. }
  216994. CameraDevice* CameraDevice::openDevice (int index,
  216995. int minWidth, int minHeight,
  216996. int maxWidth, int maxHeight)
  216997. {
  216998. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  216999. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2);
  217000. if (SUCCEEDED (hr))
  217001. {
  217002. String name;
  217003. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  217004. if (filter != 0)
  217005. {
  217006. ScopedPointer <CameraDevice> cam (new CameraDevice (name, index));
  217007. DShowCameraDeviceInteral* const intern
  217008. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  217009. minWidth, minHeight, maxWidth, maxHeight);
  217010. cam->internal = intern;
  217011. if (intern->ok)
  217012. return cam.release();
  217013. }
  217014. }
  217015. return 0;
  217016. }
  217017. #endif
  217018. /*** End of inlined file: juce_win32_CameraDevice.cpp ***/
  217019. #endif
  217020. // Auto-link the other win32 libs that are needed by library calls..
  217021. #if (JUCE_AMALGAMATED_TEMPLATE || defined (JUCE_DLL_BUILD)) && JUCE_MSVC && ! DONT_AUTOLINK_TO_WIN32_LIBRARIES
  217022. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  217023. // Auto-links to various win32 libs that are needed by library calls..
  217024. #pragma comment(lib, "kernel32.lib")
  217025. #pragma comment(lib, "user32.lib")
  217026. #pragma comment(lib, "shell32.lib")
  217027. #pragma comment(lib, "gdi32.lib")
  217028. #pragma comment(lib, "vfw32.lib")
  217029. #pragma comment(lib, "comdlg32.lib")
  217030. #pragma comment(lib, "winmm.lib")
  217031. #pragma comment(lib, "wininet.lib")
  217032. #pragma comment(lib, "ole32.lib")
  217033. #pragma comment(lib, "oleaut32.lib")
  217034. #pragma comment(lib, "advapi32.lib")
  217035. #pragma comment(lib, "ws2_32.lib")
  217036. #pragma comment(lib, "version.lib")
  217037. #ifdef _NATIVE_WCHAR_T_DEFINED
  217038. #ifdef _DEBUG
  217039. #pragma comment(lib, "comsuppwd.lib")
  217040. #else
  217041. #pragma comment(lib, "comsuppw.lib")
  217042. #endif
  217043. #else
  217044. #ifdef _DEBUG
  217045. #pragma comment(lib, "comsuppd.lib")
  217046. #else
  217047. #pragma comment(lib, "comsupp.lib")
  217048. #endif
  217049. #endif
  217050. #if JUCE_OPENGL
  217051. #pragma comment(lib, "OpenGL32.Lib")
  217052. #pragma comment(lib, "GlU32.Lib")
  217053. #endif
  217054. #if JUCE_QUICKTIME
  217055. #pragma comment (lib, "QTMLClient.lib")
  217056. #endif
  217057. #if JUCE_USE_CAMERA
  217058. #pragma comment (lib, "Strmiids.lib")
  217059. #pragma comment (lib, "wmvcore.lib")
  217060. #endif
  217061. #if JUCE_DIRECT2D
  217062. #pragma comment (lib, "Dwrite.lib")
  217063. #pragma comment (lib, "D2d1.lib")
  217064. #endif
  217065. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  217066. #endif
  217067. END_JUCE_NAMESPACE
  217068. #endif
  217069. /*** End of inlined file: juce_win32_NativeCode.cpp ***/
  217070. #endif
  217071. #if JUCE_LINUX
  217072. /*** Start of inlined file: juce_linux_NativeCode.cpp ***/
  217073. /*
  217074. This file wraps together all the mac-specific code, so that
  217075. we can include all the native headers just once, and compile all our
  217076. platform-specific stuff in one big lump, keeping it out of the way of
  217077. the rest of the codebase.
  217078. */
  217079. #if JUCE_LINUX
  217080. BEGIN_JUCE_NAMESPACE
  217081. #define JUCE_INCLUDED_FILE 1
  217082. // Now include the actual code files..
  217083. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  217084. /*
  217085. This file contains posix routines that are common to both the Linux and Mac builds.
  217086. It gets included directly in the cpp files for these platforms.
  217087. */
  217088. CriticalSection::CriticalSection() throw()
  217089. {
  217090. pthread_mutexattr_t atts;
  217091. pthread_mutexattr_init (&atts);
  217092. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  217093. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  217094. pthread_mutex_init (&internal, &atts);
  217095. }
  217096. CriticalSection::~CriticalSection() throw()
  217097. {
  217098. pthread_mutex_destroy (&internal);
  217099. }
  217100. void CriticalSection::enter() const throw()
  217101. {
  217102. pthread_mutex_lock (&internal);
  217103. }
  217104. bool CriticalSection::tryEnter() const throw()
  217105. {
  217106. return pthread_mutex_trylock (&internal) == 0;
  217107. }
  217108. void CriticalSection::exit() const throw()
  217109. {
  217110. pthread_mutex_unlock (&internal);
  217111. }
  217112. class WaitableEventImpl
  217113. {
  217114. public:
  217115. WaitableEventImpl (const bool manualReset_)
  217116. : triggered (false),
  217117. manualReset (manualReset_)
  217118. {
  217119. pthread_cond_init (&condition, 0);
  217120. pthread_mutexattr_t atts;
  217121. pthread_mutexattr_init (&atts);
  217122. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  217123. pthread_mutex_init (&mutex, &atts);
  217124. }
  217125. ~WaitableEventImpl()
  217126. {
  217127. pthread_cond_destroy (&condition);
  217128. pthread_mutex_destroy (&mutex);
  217129. }
  217130. bool wait (const int timeOutMillisecs) throw()
  217131. {
  217132. pthread_mutex_lock (&mutex);
  217133. if (! triggered)
  217134. {
  217135. if (timeOutMillisecs < 0)
  217136. {
  217137. do
  217138. {
  217139. pthread_cond_wait (&condition, &mutex);
  217140. }
  217141. while (! triggered);
  217142. }
  217143. else
  217144. {
  217145. struct timeval now;
  217146. gettimeofday (&now, 0);
  217147. struct timespec time;
  217148. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  217149. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  217150. if (time.tv_nsec >= 1000000000)
  217151. {
  217152. time.tv_nsec -= 1000000000;
  217153. time.tv_sec++;
  217154. }
  217155. do
  217156. {
  217157. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  217158. {
  217159. pthread_mutex_unlock (&mutex);
  217160. return false;
  217161. }
  217162. }
  217163. while (! triggered);
  217164. }
  217165. }
  217166. if (! manualReset)
  217167. triggered = false;
  217168. pthread_mutex_unlock (&mutex);
  217169. return true;
  217170. }
  217171. void signal() throw()
  217172. {
  217173. pthread_mutex_lock (&mutex);
  217174. triggered = true;
  217175. pthread_cond_broadcast (&condition);
  217176. pthread_mutex_unlock (&mutex);
  217177. }
  217178. void reset() throw()
  217179. {
  217180. pthread_mutex_lock (&mutex);
  217181. triggered = false;
  217182. pthread_mutex_unlock (&mutex);
  217183. }
  217184. private:
  217185. pthread_cond_t condition;
  217186. pthread_mutex_t mutex;
  217187. bool triggered;
  217188. const bool manualReset;
  217189. WaitableEventImpl (const WaitableEventImpl&);
  217190. WaitableEventImpl& operator= (const WaitableEventImpl&);
  217191. };
  217192. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  217193. : internal (new WaitableEventImpl (manualReset))
  217194. {
  217195. }
  217196. WaitableEvent::~WaitableEvent() throw()
  217197. {
  217198. delete static_cast <WaitableEventImpl*> (internal);
  217199. }
  217200. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  217201. {
  217202. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  217203. }
  217204. void WaitableEvent::signal() const throw()
  217205. {
  217206. static_cast <WaitableEventImpl*> (internal)->signal();
  217207. }
  217208. void WaitableEvent::reset() const throw()
  217209. {
  217210. static_cast <WaitableEventImpl*> (internal)->reset();
  217211. }
  217212. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  217213. {
  217214. struct timespec time;
  217215. time.tv_sec = millisecs / 1000;
  217216. time.tv_nsec = (millisecs % 1000) * 1000000;
  217217. nanosleep (&time, 0);
  217218. }
  217219. const juce_wchar File::separator = '/';
  217220. const String File::separatorString ("/");
  217221. const File File::getCurrentWorkingDirectory()
  217222. {
  217223. HeapBlock<char> heapBuffer;
  217224. char localBuffer [1024];
  217225. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  217226. int bufferSize = 4096;
  217227. while (cwd == 0 && errno == ERANGE)
  217228. {
  217229. heapBuffer.malloc (bufferSize);
  217230. cwd = getcwd (heapBuffer, bufferSize - 1);
  217231. bufferSize += 1024;
  217232. }
  217233. return File (String::fromUTF8 (cwd));
  217234. }
  217235. bool File::setAsCurrentWorkingDirectory() const
  217236. {
  217237. return chdir (getFullPathName().toUTF8()) == 0;
  217238. }
  217239. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  217240. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  217241. #else
  217242. typedef struct stat juce_statStruct;
  217243. #endif
  217244. static bool juce_stat (const String& fileName, juce_statStruct& info)
  217245. {
  217246. return fileName.isNotEmpty()
  217247. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  217248. && (stat64 (fileName.toUTF8(), &info) == 0);
  217249. #else
  217250. && (stat (fileName.toUTF8(), &info) == 0);
  217251. #endif
  217252. }
  217253. bool File::isDirectory() const
  217254. {
  217255. juce_statStruct info;
  217256. return fullPath.isEmpty()
  217257. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  217258. }
  217259. bool File::exists() const
  217260. {
  217261. juce_statStruct info;
  217262. return fullPath.isNotEmpty()
  217263. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  217264. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  217265. #else
  217266. && (lstat (fullPath.toUTF8(), &info) == 0);
  217267. #endif
  217268. }
  217269. bool File::existsAsFile() const
  217270. {
  217271. return exists() && ! isDirectory();
  217272. }
  217273. int64 File::getSize() const
  217274. {
  217275. juce_statStruct info;
  217276. return juce_stat (fullPath, info) ? info.st_size : 0;
  217277. }
  217278. bool File::hasWriteAccess() const
  217279. {
  217280. if (exists())
  217281. return access (fullPath.toUTF8(), W_OK) == 0;
  217282. if ((! isDirectory()) && fullPath.containsChar (separator))
  217283. return getParentDirectory().hasWriteAccess();
  217284. return false;
  217285. }
  217286. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  217287. {
  217288. juce_statStruct info;
  217289. if (! juce_stat (fullPath, info))
  217290. return false;
  217291. info.st_mode &= 0777; // Just permissions
  217292. if (shouldBeReadOnly)
  217293. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  217294. else
  217295. // Give everybody write permission?
  217296. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  217297. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  217298. }
  217299. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  217300. {
  217301. modificationTime = 0;
  217302. accessTime = 0;
  217303. creationTime = 0;
  217304. juce_statStruct info;
  217305. if (juce_stat (fullPath, info))
  217306. {
  217307. modificationTime = (int64) info.st_mtime * 1000;
  217308. accessTime = (int64) info.st_atime * 1000;
  217309. creationTime = (int64) info.st_ctime * 1000;
  217310. }
  217311. }
  217312. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  217313. {
  217314. struct utimbuf times;
  217315. times.actime = (time_t) (accessTime / 1000);
  217316. times.modtime = (time_t) (modificationTime / 1000);
  217317. return utime (fullPath.toUTF8(), &times) == 0;
  217318. }
  217319. bool File::deleteFile() const
  217320. {
  217321. if (! exists())
  217322. return true;
  217323. else if (isDirectory())
  217324. return rmdir (fullPath.toUTF8()) == 0;
  217325. else
  217326. return remove (fullPath.toUTF8()) == 0;
  217327. }
  217328. bool File::moveInternal (const File& dest) const
  217329. {
  217330. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  217331. return true;
  217332. if (hasWriteAccess() && copyInternal (dest))
  217333. {
  217334. if (deleteFile())
  217335. return true;
  217336. dest.deleteFile();
  217337. }
  217338. return false;
  217339. }
  217340. void File::createDirectoryInternal (const String& fileName) const
  217341. {
  217342. mkdir (fileName.toUTF8(), 0777);
  217343. }
  217344. int64 juce_fileSetPosition (void* handle, int64 pos)
  217345. {
  217346. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  217347. return pos;
  217348. return -1;
  217349. }
  217350. void FileInputStream::openHandle()
  217351. {
  217352. totalSize = file.getSize();
  217353. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  217354. if (f != -1)
  217355. fileHandle = (void*) f;
  217356. }
  217357. void FileInputStream::closeHandle()
  217358. {
  217359. if (fileHandle != 0)
  217360. {
  217361. close ((int) (pointer_sized_int) fileHandle);
  217362. fileHandle = 0;
  217363. }
  217364. }
  217365. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  217366. {
  217367. if (fileHandle != 0)
  217368. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  217369. return 0;
  217370. }
  217371. void FileOutputStream::openHandle()
  217372. {
  217373. if (file.exists())
  217374. {
  217375. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  217376. if (f != -1)
  217377. {
  217378. currentPosition = lseek (f, 0, SEEK_END);
  217379. if (currentPosition >= 0)
  217380. fileHandle = (void*) f;
  217381. else
  217382. close (f);
  217383. }
  217384. }
  217385. else
  217386. {
  217387. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  217388. if (f != -1)
  217389. fileHandle = (void*) f;
  217390. }
  217391. }
  217392. void FileOutputStream::closeHandle()
  217393. {
  217394. if (fileHandle != 0)
  217395. {
  217396. close ((int) (pointer_sized_int) fileHandle);
  217397. fileHandle = 0;
  217398. }
  217399. }
  217400. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  217401. {
  217402. if (fileHandle != 0)
  217403. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  217404. return 0;
  217405. }
  217406. void FileOutputStream::flushInternal()
  217407. {
  217408. if (fileHandle != 0)
  217409. fsync ((int) (pointer_sized_int) fileHandle);
  217410. }
  217411. const File juce_getExecutableFile()
  217412. {
  217413. Dl_info exeInfo;
  217414. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  217415. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  217416. }
  217417. // if this file doesn't exist, find a parent of it that does..
  217418. static bool juce_doStatFS (File f, struct statfs& result)
  217419. {
  217420. for (int i = 5; --i >= 0;)
  217421. {
  217422. if (f.exists())
  217423. break;
  217424. f = f.getParentDirectory();
  217425. }
  217426. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  217427. }
  217428. int64 File::getBytesFreeOnVolume() const
  217429. {
  217430. struct statfs buf;
  217431. if (juce_doStatFS (*this, buf))
  217432. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  217433. return 0;
  217434. }
  217435. int64 File::getVolumeTotalSize() const
  217436. {
  217437. struct statfs buf;
  217438. if (juce_doStatFS (*this, buf))
  217439. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  217440. return 0;
  217441. }
  217442. const String File::getVolumeLabel() const
  217443. {
  217444. #if JUCE_MAC
  217445. struct VolAttrBuf
  217446. {
  217447. u_int32_t length;
  217448. attrreference_t mountPointRef;
  217449. char mountPointSpace [MAXPATHLEN];
  217450. } attrBuf;
  217451. struct attrlist attrList;
  217452. zerostruct (attrList);
  217453. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  217454. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  217455. File f (*this);
  217456. for (;;)
  217457. {
  217458. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  217459. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  217460. (int) attrBuf.mountPointRef.attr_length);
  217461. const File parent (f.getParentDirectory());
  217462. if (f == parent)
  217463. break;
  217464. f = parent;
  217465. }
  217466. #endif
  217467. return String::empty;
  217468. }
  217469. int File::getVolumeSerialNumber() const
  217470. {
  217471. return 0; // xxx
  217472. }
  217473. void juce_runSystemCommand (const String& command)
  217474. {
  217475. int result = system (command.toUTF8());
  217476. (void) result;
  217477. }
  217478. const String juce_getOutputFromCommand (const String& command)
  217479. {
  217480. // slight bodge here, as we just pipe the output into a temp file and read it...
  217481. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  217482. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  217483. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  217484. String result (tempFile.loadFileAsString());
  217485. tempFile.deleteFile();
  217486. return result;
  217487. }
  217488. class InterProcessLock::Pimpl
  217489. {
  217490. public:
  217491. Pimpl (const String& name, const int timeOutMillisecs)
  217492. : handle (0), refCount (1)
  217493. {
  217494. #if JUCE_MAC
  217495. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  217496. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  217497. #else
  217498. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  217499. #endif
  217500. temp.create();
  217501. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  217502. if (handle != 0)
  217503. {
  217504. struct flock fl;
  217505. zerostruct (fl);
  217506. fl.l_whence = SEEK_SET;
  217507. fl.l_type = F_WRLCK;
  217508. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  217509. for (;;)
  217510. {
  217511. const int result = fcntl (handle, F_SETLK, &fl);
  217512. if (result >= 0)
  217513. return;
  217514. if (errno != EINTR)
  217515. {
  217516. if (timeOutMillisecs == 0
  217517. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  217518. break;
  217519. Thread::sleep (10);
  217520. }
  217521. }
  217522. }
  217523. closeFile();
  217524. }
  217525. ~Pimpl()
  217526. {
  217527. closeFile();
  217528. }
  217529. void closeFile()
  217530. {
  217531. if (handle != 0)
  217532. {
  217533. struct flock fl;
  217534. zerostruct (fl);
  217535. fl.l_whence = SEEK_SET;
  217536. fl.l_type = F_UNLCK;
  217537. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  217538. {}
  217539. close (handle);
  217540. handle = 0;
  217541. }
  217542. }
  217543. int handle, refCount;
  217544. };
  217545. InterProcessLock::InterProcessLock (const String& name_)
  217546. : name (name_)
  217547. {
  217548. }
  217549. InterProcessLock::~InterProcessLock()
  217550. {
  217551. }
  217552. bool InterProcessLock::enter (const int timeOutMillisecs)
  217553. {
  217554. const ScopedLock sl (lock);
  217555. if (pimpl == 0)
  217556. {
  217557. pimpl = new Pimpl (name, timeOutMillisecs);
  217558. if (pimpl->handle == 0)
  217559. pimpl = 0;
  217560. }
  217561. else
  217562. {
  217563. pimpl->refCount++;
  217564. }
  217565. return pimpl != 0;
  217566. }
  217567. void InterProcessLock::exit()
  217568. {
  217569. const ScopedLock sl (lock);
  217570. // Trying to release the lock too many times!
  217571. jassert (pimpl != 0);
  217572. if (pimpl != 0 && --(pimpl->refCount) == 0)
  217573. pimpl = 0;
  217574. }
  217575. void JUCE_API juce_threadEntryPoint (void*);
  217576. void* threadEntryProc (void* userData)
  217577. {
  217578. JUCE_AUTORELEASEPOOL
  217579. juce_threadEntryPoint (userData);
  217580. return 0;
  217581. }
  217582. void* juce_createThread (void* userData)
  217583. {
  217584. pthread_t handle = 0;
  217585. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  217586. {
  217587. pthread_detach (handle);
  217588. return (void*) handle;
  217589. }
  217590. return 0;
  217591. }
  217592. void juce_killThread (void* handle)
  217593. {
  217594. if (handle != 0)
  217595. pthread_cancel ((pthread_t) handle);
  217596. }
  217597. void juce_setCurrentThreadName (const String& /*name*/)
  217598. {
  217599. }
  217600. bool juce_setThreadPriority (void* handle, int priority)
  217601. {
  217602. struct sched_param param;
  217603. int policy;
  217604. priority = jlimit (0, 10, priority);
  217605. if (handle == 0)
  217606. handle = (void*) pthread_self();
  217607. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  217608. return false;
  217609. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  217610. const int minPriority = sched_get_priority_min (policy);
  217611. const int maxPriority = sched_get_priority_max (policy);
  217612. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  217613. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  217614. }
  217615. Thread::ThreadID Thread::getCurrentThreadId()
  217616. {
  217617. return (ThreadID) pthread_self();
  217618. }
  217619. void Thread::yield()
  217620. {
  217621. sched_yield();
  217622. }
  217623. /* Remove this macro if you're having problems compiling the cpu affinity
  217624. calls (the API for these has changed about quite a bit in various Linux
  217625. versions, and a lot of distros seem to ship with obsolete versions)
  217626. */
  217627. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  217628. #define SUPPORT_AFFINITIES 1
  217629. #endif
  217630. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  217631. {
  217632. #if SUPPORT_AFFINITIES
  217633. cpu_set_t affinity;
  217634. CPU_ZERO (&affinity);
  217635. for (int i = 0; i < 32; ++i)
  217636. if ((affinityMask & (1 << i)) != 0)
  217637. CPU_SET (i, &affinity);
  217638. /*
  217639. N.B. If this line causes a compile error, then you've probably not got the latest
  217640. version of glibc installed.
  217641. If you don't want to update your copy of glibc and don't care about cpu affinities,
  217642. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  217643. */
  217644. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  217645. sched_yield();
  217646. #else
  217647. /* affinities aren't supported because either the appropriate header files weren't found,
  217648. or the SUPPORT_AFFINITIES macro was turned off
  217649. */
  217650. jassertfalse;
  217651. #endif
  217652. }
  217653. /*** End of inlined file: juce_posix_SharedCode.h ***/
  217654. /*** Start of inlined file: juce_linux_Files.cpp ***/
  217655. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217656. // compiled on its own).
  217657. #if JUCE_INCLUDED_FILE
  217658. static const short U_ISOFS_SUPER_MAGIC = 0x9660; // linux/iso_fs.h
  217659. static const short U_MSDOS_SUPER_MAGIC = 0x4d44; // linux/msdos_fs.h
  217660. static const short U_NFS_SUPER_MAGIC = 0x6969; // linux/nfs_fs.h
  217661. static const short U_SMB_SUPER_MAGIC = 0x517B; // linux/smb_fs.h
  217662. bool File::copyInternal (const File& dest) const
  217663. {
  217664. FileInputStream in (*this);
  217665. if (dest.deleteFile())
  217666. {
  217667. {
  217668. FileOutputStream out (dest);
  217669. if (out.failedToOpen())
  217670. return false;
  217671. if (out.writeFromInputStream (in, -1) == getSize())
  217672. return true;
  217673. }
  217674. dest.deleteFile();
  217675. }
  217676. return false;
  217677. }
  217678. void File::findFileSystemRoots (Array<File>& destArray)
  217679. {
  217680. destArray.add (File ("/"));
  217681. }
  217682. bool File::isOnCDRomDrive() const
  217683. {
  217684. struct statfs buf;
  217685. return statfs (getFullPathName().toUTF8(), &buf) == 0
  217686. && buf.f_type == U_ISOFS_SUPER_MAGIC;
  217687. }
  217688. bool File::isOnHardDisk() const
  217689. {
  217690. struct statfs buf;
  217691. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  217692. {
  217693. switch (buf.f_type)
  217694. {
  217695. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  217696. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  217697. case U_NFS_SUPER_MAGIC: // Network NFS
  217698. case U_SMB_SUPER_MAGIC: // Network Samba
  217699. return false;
  217700. default:
  217701. // Assume anything else is a hard-disk (but note it could
  217702. // be a RAM disk. There isn't a good way of determining
  217703. // this for sure)
  217704. return true;
  217705. }
  217706. }
  217707. // Assume so if this fails for some reason
  217708. return true;
  217709. }
  217710. bool File::isOnRemovableDrive() const
  217711. {
  217712. jassertfalse; // xxx not implemented for linux!
  217713. return false;
  217714. }
  217715. bool File::isHidden() const
  217716. {
  217717. return getFileName().startsWithChar ('.');
  217718. }
  217719. static const File juce_readlink (const String& file, const File& defaultFile)
  217720. {
  217721. const int size = 8192;
  217722. HeapBlock<char> buffer;
  217723. buffer.malloc (size + 4);
  217724. const size_t numBytes = readlink (file.toUTF8(), buffer, size);
  217725. if (numBytes > 0 && numBytes <= size)
  217726. return File (file).getSiblingFile (String::fromUTF8 (buffer, (int) numBytes));
  217727. return defaultFile;
  217728. }
  217729. const File File::getLinkedTarget() const
  217730. {
  217731. return juce_readlink (getFullPathName().toUTF8(), *this);
  217732. }
  217733. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  217734. const File File::getSpecialLocation (const SpecialLocationType type)
  217735. {
  217736. switch (type)
  217737. {
  217738. case userHomeDirectory:
  217739. {
  217740. const char* homeDir = getenv ("HOME");
  217741. if (homeDir == 0)
  217742. {
  217743. struct passwd* const pw = getpwuid (getuid());
  217744. if (pw != 0)
  217745. homeDir = pw->pw_dir;
  217746. }
  217747. return File (String::fromUTF8 (homeDir));
  217748. }
  217749. case userDocumentsDirectory:
  217750. case userMusicDirectory:
  217751. case userMoviesDirectory:
  217752. case userApplicationDataDirectory:
  217753. return File ("~");
  217754. case userDesktopDirectory:
  217755. return File ("~/Desktop");
  217756. case commonApplicationDataDirectory:
  217757. return File ("/var");
  217758. case globalApplicationsDirectory:
  217759. return File ("/usr");
  217760. case tempDirectory:
  217761. {
  217762. File tmp ("/var/tmp");
  217763. if (! tmp.isDirectory())
  217764. {
  217765. tmp = "/tmp";
  217766. if (! tmp.isDirectory())
  217767. tmp = File::getCurrentWorkingDirectory();
  217768. }
  217769. return tmp;
  217770. }
  217771. case invokedExecutableFile:
  217772. if (juce_Argv0 != 0)
  217773. return File (String::fromUTF8 (juce_Argv0));
  217774. // deliberate fall-through...
  217775. case currentExecutableFile:
  217776. case currentApplicationFile:
  217777. return juce_getExecutableFile();
  217778. case hostApplicationPath:
  217779. return juce_readlink ("/proc/self/exe", juce_getExecutableFile());
  217780. default:
  217781. jassertfalse; // unknown type?
  217782. break;
  217783. }
  217784. return File::nonexistent;
  217785. }
  217786. const String File::getVersion() const
  217787. {
  217788. return String::empty; // xxx not yet implemented
  217789. }
  217790. bool File::moveToTrash() const
  217791. {
  217792. if (! exists())
  217793. return true;
  217794. File trashCan ("~/.Trash");
  217795. if (! trashCan.isDirectory())
  217796. trashCan = "~/.local/share/Trash/files";
  217797. if (! trashCan.isDirectory())
  217798. return false;
  217799. return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
  217800. getFileExtension()));
  217801. }
  217802. class DirectoryIterator::NativeIterator::Pimpl
  217803. {
  217804. public:
  217805. Pimpl (const File& directory, const String& wildCard_)
  217806. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  217807. wildCard (wildCard_),
  217808. dir (opendir (directory.getFullPathName().toUTF8()))
  217809. {
  217810. if (wildCard == "*.*")
  217811. wildCard = "*";
  217812. wildcardUTF8 = wildCard.toUTF8();
  217813. }
  217814. ~Pimpl()
  217815. {
  217816. if (dir != 0)
  217817. closedir (dir);
  217818. }
  217819. bool next (String& filenameFound,
  217820. bool* const isDir, bool* const isHidden, int64* const fileSize,
  217821. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  217822. {
  217823. if (dir == 0)
  217824. return false;
  217825. for (;;)
  217826. {
  217827. struct dirent* const de = readdir (dir);
  217828. if (de == 0)
  217829. return false;
  217830. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  217831. {
  217832. filenameFound = String::fromUTF8 (de->d_name);
  217833. const String path (parentDir + filenameFound);
  217834. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  217835. {
  217836. struct stat info;
  217837. const bool statOk = juce_stat (path, info);
  217838. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  217839. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  217840. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  217841. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  217842. }
  217843. if (isHidden != 0)
  217844. *isHidden = filenameFound.startsWithChar ('.');
  217845. if (isReadOnly != 0)
  217846. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  217847. return true;
  217848. }
  217849. }
  217850. }
  217851. private:
  217852. String parentDir, wildCard;
  217853. const char* wildcardUTF8;
  217854. DIR* dir;
  217855. Pimpl (const Pimpl&);
  217856. Pimpl& operator= (const Pimpl&);
  217857. };
  217858. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  217859. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  217860. {
  217861. }
  217862. DirectoryIterator::NativeIterator::~NativeIterator()
  217863. {
  217864. }
  217865. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  217866. bool* const isDir, bool* const isHidden, int64* const fileSize,
  217867. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  217868. {
  217869. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  217870. }
  217871. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  217872. {
  217873. String cmdString (fileName.replace (" ", "\\ ",false));
  217874. cmdString << " " << parameters;
  217875. if (URL::isProbablyAWebsiteURL (fileName)
  217876. || cmdString.startsWithIgnoreCase ("file:")
  217877. || URL::isProbablyAnEmailAddress (fileName))
  217878. {
  217879. // create a command that tries to launch a bunch of likely browsers
  217880. const char* const browserNames[] = { "xdg-open", "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  217881. StringArray cmdLines;
  217882. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  217883. cmdLines.add (String (browserNames[i]) + " " + cmdString.trim().quoted());
  217884. cmdString = cmdLines.joinIntoString (" || ");
  217885. }
  217886. const char* const argv[4] = { "/bin/sh", "-c", cmdString.toUTF8(), 0 };
  217887. const int cpid = fork();
  217888. if (cpid == 0)
  217889. {
  217890. setsid();
  217891. // Child process
  217892. execve (argv[0], (char**) argv, environ);
  217893. exit (0);
  217894. }
  217895. return cpid >= 0;
  217896. }
  217897. void File::revealToUser() const
  217898. {
  217899. if (isDirectory())
  217900. startAsProcess();
  217901. else if (getParentDirectory().exists())
  217902. getParentDirectory().startAsProcess();
  217903. }
  217904. #endif
  217905. /*** End of inlined file: juce_linux_Files.cpp ***/
  217906. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  217907. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  217908. // compiled on its own).
  217909. #if JUCE_INCLUDED_FILE
  217910. struct NamedPipeInternal
  217911. {
  217912. String pipeInName, pipeOutName;
  217913. int pipeIn, pipeOut;
  217914. bool volatile createdPipe, blocked, stopReadOperation;
  217915. static void signalHandler (int) {}
  217916. };
  217917. void NamedPipe::cancelPendingReads()
  217918. {
  217919. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  217920. {
  217921. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217922. intern->stopReadOperation = true;
  217923. char buffer [1] = { 0 };
  217924. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  217925. (void) bytesWritten;
  217926. int timeout = 2000;
  217927. while (intern->blocked && --timeout >= 0)
  217928. Thread::sleep (2);
  217929. intern->stopReadOperation = false;
  217930. }
  217931. }
  217932. void NamedPipe::close()
  217933. {
  217934. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217935. if (intern != 0)
  217936. {
  217937. internal = 0;
  217938. if (intern->pipeIn != -1)
  217939. ::close (intern->pipeIn);
  217940. if (intern->pipeOut != -1)
  217941. ::close (intern->pipeOut);
  217942. if (intern->createdPipe)
  217943. {
  217944. unlink (intern->pipeInName.toUTF8());
  217945. unlink (intern->pipeOutName.toUTF8());
  217946. }
  217947. delete intern;
  217948. }
  217949. }
  217950. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  217951. {
  217952. close();
  217953. NamedPipeInternal* const intern = new NamedPipeInternal();
  217954. internal = intern;
  217955. intern->createdPipe = createPipe;
  217956. intern->blocked = false;
  217957. intern->stopReadOperation = false;
  217958. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  217959. siginterrupt (SIGPIPE, 1);
  217960. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  217961. intern->pipeInName = pipePath + "_in";
  217962. intern->pipeOutName = pipePath + "_out";
  217963. intern->pipeIn = -1;
  217964. intern->pipeOut = -1;
  217965. if (createPipe)
  217966. {
  217967. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  217968. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  217969. {
  217970. delete intern;
  217971. internal = 0;
  217972. return false;
  217973. }
  217974. }
  217975. return true;
  217976. }
  217977. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  217978. {
  217979. int bytesRead = -1;
  217980. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  217981. if (intern != 0)
  217982. {
  217983. intern->blocked = true;
  217984. if (intern->pipeIn == -1)
  217985. {
  217986. if (intern->createdPipe)
  217987. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  217988. else
  217989. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  217990. if (intern->pipeIn == -1)
  217991. {
  217992. intern->blocked = false;
  217993. return -1;
  217994. }
  217995. }
  217996. bytesRead = 0;
  217997. char* p = static_cast<char*> (destBuffer);
  217998. while (bytesRead < maxBytesToRead)
  217999. {
  218000. const int bytesThisTime = maxBytesToRead - bytesRead;
  218001. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  218002. if (numRead <= 0 || intern->stopReadOperation)
  218003. {
  218004. bytesRead = -1;
  218005. break;
  218006. }
  218007. bytesRead += numRead;
  218008. p += bytesRead;
  218009. }
  218010. intern->blocked = false;
  218011. }
  218012. return bytesRead;
  218013. }
  218014. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  218015. {
  218016. int bytesWritten = -1;
  218017. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  218018. if (intern != 0)
  218019. {
  218020. if (intern->pipeOut == -1)
  218021. {
  218022. if (intern->createdPipe)
  218023. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  218024. else
  218025. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  218026. if (intern->pipeOut == -1)
  218027. {
  218028. return -1;
  218029. }
  218030. }
  218031. const char* p = static_cast<const char*> (sourceBuffer);
  218032. bytesWritten = 0;
  218033. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  218034. while (bytesWritten < numBytesToWrite
  218035. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  218036. {
  218037. const int bytesThisTime = numBytesToWrite - bytesWritten;
  218038. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  218039. if (numWritten <= 0)
  218040. {
  218041. bytesWritten = -1;
  218042. break;
  218043. }
  218044. bytesWritten += numWritten;
  218045. p += bytesWritten;
  218046. }
  218047. }
  218048. return bytesWritten;
  218049. }
  218050. #endif
  218051. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  218052. /*** Start of inlined file: juce_linux_Network.cpp ***/
  218053. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218054. // compiled on its own).
  218055. #if JUCE_INCLUDED_FILE
  218056. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  218057. {
  218058. int numResults = 0;
  218059. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  218060. if (s != -1)
  218061. {
  218062. char buf [1024];
  218063. struct ifconf ifc;
  218064. ifc.ifc_len = sizeof (buf);
  218065. ifc.ifc_buf = buf;
  218066. ioctl (s, SIOCGIFCONF, &ifc);
  218067. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  218068. {
  218069. struct ifreq ifr;
  218070. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  218071. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  218072. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  218073. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0
  218074. && numResults < maxNum)
  218075. {
  218076. int64 a = 0;
  218077. for (int j = 6; --j >= 0;)
  218078. a = (a << 8) | (uint8) ifr.ifr_hwaddr.sa_data [littleEndian ? j : (5 - j)];
  218079. *addresses++ = a;
  218080. ++numResults;
  218081. }
  218082. }
  218083. close (s);
  218084. }
  218085. return numResults;
  218086. }
  218087. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  218088. const String& emailSubject,
  218089. const String& bodyText,
  218090. const StringArray& filesToAttach)
  218091. {
  218092. jassertfalse; // xxx todo
  218093. return false;
  218094. }
  218095. /** A HTTP input stream that uses sockets.
  218096. */
  218097. class JUCE_HTTPSocketStream
  218098. {
  218099. public:
  218100. JUCE_HTTPSocketStream()
  218101. : readPosition (0),
  218102. socketHandle (-1),
  218103. levelsOfRedirection (0),
  218104. timeoutSeconds (15)
  218105. {
  218106. }
  218107. ~JUCE_HTTPSocketStream()
  218108. {
  218109. closeSocket();
  218110. }
  218111. bool open (const String& url,
  218112. const String& headers,
  218113. const MemoryBlock& postData,
  218114. const bool isPost,
  218115. URL::OpenStreamProgressCallback* callback,
  218116. void* callbackContext,
  218117. int timeOutMs)
  218118. {
  218119. closeSocket();
  218120. uint32 timeOutTime = Time::getMillisecondCounter();
  218121. if (timeOutMs == 0)
  218122. timeOutTime += 60000;
  218123. else if (timeOutMs < 0)
  218124. timeOutTime = 0xffffffff;
  218125. else
  218126. timeOutTime += timeOutMs;
  218127. String hostName, hostPath;
  218128. int hostPort;
  218129. if (! decomposeURL (url, hostName, hostPath, hostPort))
  218130. return false;
  218131. const struct hostent* host = 0;
  218132. int port = 0;
  218133. String proxyName, proxyPath;
  218134. int proxyPort = 0;
  218135. String proxyURL (getenv ("http_proxy"));
  218136. if (proxyURL.startsWithIgnoreCase ("http://"))
  218137. {
  218138. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  218139. return false;
  218140. host = gethostbyname (proxyName.toUTF8());
  218141. port = proxyPort;
  218142. }
  218143. else
  218144. {
  218145. host = gethostbyname (hostName.toUTF8());
  218146. port = hostPort;
  218147. }
  218148. if (host == 0)
  218149. return false;
  218150. struct sockaddr_in address;
  218151. zerostruct (address);
  218152. memcpy (&address.sin_addr, host->h_addr, host->h_length);
  218153. address.sin_family = host->h_addrtype;
  218154. address.sin_port = htons (port);
  218155. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  218156. if (socketHandle == -1)
  218157. return false;
  218158. int receiveBufferSize = 16384;
  218159. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  218160. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  218161. #if JUCE_MAC
  218162. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  218163. #endif
  218164. if (connect (socketHandle, (struct sockaddr*) &address, sizeof (address)) == -1)
  218165. {
  218166. closeSocket();
  218167. return false;
  218168. }
  218169. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort,
  218170. proxyName, proxyPort,
  218171. hostPath, url,
  218172. headers, postData,
  218173. isPost));
  218174. size_t totalHeaderSent = 0;
  218175. while (totalHeaderSent < requestHeader.getSize())
  218176. {
  218177. if (Time::getMillisecondCounter() > timeOutTime)
  218178. {
  218179. closeSocket();
  218180. return false;
  218181. }
  218182. const int numToSend = jmin (1024, (int) (requestHeader.getSize() - totalHeaderSent));
  218183. if (send (socketHandle,
  218184. ((const char*) requestHeader.getData()) + totalHeaderSent,
  218185. numToSend, 0)
  218186. != numToSend)
  218187. {
  218188. closeSocket();
  218189. return false;
  218190. }
  218191. totalHeaderSent += numToSend;
  218192. if (callback != 0 && ! callback (callbackContext, totalHeaderSent, requestHeader.getSize()))
  218193. {
  218194. closeSocket();
  218195. return false;
  218196. }
  218197. }
  218198. const String responseHeader (readResponse (timeOutTime));
  218199. if (responseHeader.isNotEmpty())
  218200. {
  218201. //DBG (responseHeader);
  218202. headerLines.clear();
  218203. headerLines.addLines (responseHeader);
  218204. const int statusCode = responseHeader.fromFirstOccurrenceOf (" ", false, false)
  218205. .substring (0, 3).getIntValue();
  218206. //int contentLength = findHeaderItem (lines, "Content-Length:").getIntValue();
  218207. //bool isChunked = findHeaderItem (lines, "Transfer-Encoding:").equalsIgnoreCase ("chunked");
  218208. String location (findHeaderItem (headerLines, "Location:"));
  218209. if (statusCode >= 300 && statusCode < 400
  218210. && location.isNotEmpty())
  218211. {
  218212. if (! location.startsWithIgnoreCase ("http://"))
  218213. location = "http://" + location;
  218214. if (levelsOfRedirection++ < 3)
  218215. return open (location, headers, postData, isPost, callback, callbackContext, timeOutMs);
  218216. }
  218217. else
  218218. {
  218219. levelsOfRedirection = 0;
  218220. return true;
  218221. }
  218222. }
  218223. closeSocket();
  218224. return false;
  218225. }
  218226. int read (void* buffer, int bytesToRead)
  218227. {
  218228. fd_set readbits;
  218229. FD_ZERO (&readbits);
  218230. FD_SET (socketHandle, &readbits);
  218231. struct timeval tv;
  218232. tv.tv_sec = timeoutSeconds;
  218233. tv.tv_usec = 0;
  218234. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  218235. return 0; // (timeout)
  218236. const int bytesRead = jmax (0, (int) recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  218237. readPosition += bytesRead;
  218238. return bytesRead;
  218239. }
  218240. int readPosition;
  218241. StringArray headerLines;
  218242. juce_UseDebuggingNewOperator
  218243. private:
  218244. int socketHandle, levelsOfRedirection;
  218245. const int timeoutSeconds;
  218246. void closeSocket()
  218247. {
  218248. if (socketHandle >= 0)
  218249. close (socketHandle);
  218250. socketHandle = -1;
  218251. }
  218252. const MemoryBlock createRequestHeader (const String& hostName,
  218253. const int hostPort,
  218254. const String& proxyName,
  218255. const int proxyPort,
  218256. const String& hostPath,
  218257. const String& originalURL,
  218258. const String& headers,
  218259. const MemoryBlock& postData,
  218260. const bool isPost)
  218261. {
  218262. String header (isPost ? "POST " : "GET ");
  218263. if (proxyName.isEmpty())
  218264. {
  218265. header << hostPath << " HTTP/1.0\r\nHost: "
  218266. << hostName << ':' << hostPort;
  218267. }
  218268. else
  218269. {
  218270. header << originalURL << " HTTP/1.0\r\nHost: "
  218271. << proxyName << ':' << proxyPort;
  218272. }
  218273. header << "\r\nUser-Agent: JUCE/"
  218274. << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  218275. << "\r\nConnection: Close\r\nContent-Length: "
  218276. << postData.getSize() << "\r\n"
  218277. << headers << "\r\n";
  218278. MemoryBlock mb;
  218279. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  218280. mb.append (postData.getData(), postData.getSize());
  218281. return mb;
  218282. }
  218283. const String readResponse (const uint32 timeOutTime)
  218284. {
  218285. int bytesRead = 0, numConsecutiveLFs = 0;
  218286. MemoryBlock buffer (1024, true);
  218287. while (numConsecutiveLFs < 2 && bytesRead < 32768
  218288. && Time::getMillisecondCounter() <= timeOutTime)
  218289. {
  218290. fd_set readbits;
  218291. FD_ZERO (&readbits);
  218292. FD_SET (socketHandle, &readbits);
  218293. struct timeval tv;
  218294. tv.tv_sec = timeoutSeconds;
  218295. tv.tv_usec = 0;
  218296. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  218297. return String::empty; // (timeout)
  218298. buffer.ensureSize (bytesRead + 8, true);
  218299. char* const dest = (char*) buffer.getData() + bytesRead;
  218300. if (recv (socketHandle, dest, 1, 0) == -1)
  218301. return String::empty;
  218302. const char lastByte = *dest;
  218303. ++bytesRead;
  218304. if (lastByte == '\n')
  218305. ++numConsecutiveLFs;
  218306. else if (lastByte != '\r')
  218307. numConsecutiveLFs = 0;
  218308. }
  218309. const String header (String::fromUTF8 ((const char*) buffer.getData()));
  218310. if (header.startsWithIgnoreCase ("HTTP/"))
  218311. return header.trimEnd();
  218312. return String::empty;
  218313. }
  218314. static bool decomposeURL (const String& url,
  218315. String& host, String& path, int& port)
  218316. {
  218317. if (! url.startsWithIgnoreCase ("http://"))
  218318. return false;
  218319. const int nextSlash = url.indexOfChar (7, '/');
  218320. int nextColon = url.indexOfChar (7, ':');
  218321. if (nextColon > nextSlash && nextSlash > 0)
  218322. nextColon = -1;
  218323. if (nextColon >= 0)
  218324. {
  218325. host = url.substring (7, nextColon);
  218326. if (nextSlash >= 0)
  218327. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  218328. else
  218329. port = url.substring (nextColon + 1).getIntValue();
  218330. }
  218331. else
  218332. {
  218333. port = 80;
  218334. if (nextSlash >= 0)
  218335. host = url.substring (7, nextSlash);
  218336. else
  218337. host = url.substring (7);
  218338. }
  218339. if (nextSlash >= 0)
  218340. path = url.substring (nextSlash);
  218341. else
  218342. path = "/";
  218343. return true;
  218344. }
  218345. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  218346. {
  218347. for (int i = 0; i < lines.size(); ++i)
  218348. if (lines[i].startsWithIgnoreCase (itemName))
  218349. return lines[i].substring (itemName.length()).trim();
  218350. return String::empty;
  218351. }
  218352. };
  218353. void* juce_openInternetFile (const String& url,
  218354. const String& headers,
  218355. const MemoryBlock& postData,
  218356. const bool isPost,
  218357. URL::OpenStreamProgressCallback* callback,
  218358. void* callbackContext,
  218359. int timeOutMs)
  218360. {
  218361. ScopedPointer<JUCE_HTTPSocketStream> s (new JUCE_HTTPSocketStream());
  218362. if (s->open (url, headers, postData, isPost, callback, callbackContext, timeOutMs))
  218363. return s.release();
  218364. return 0;
  218365. }
  218366. void juce_closeInternetFile (void* handle)
  218367. {
  218368. delete static_cast <JUCE_HTTPSocketStream*> (handle);
  218369. }
  218370. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  218371. {
  218372. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218373. return s != 0 ? s->read (buffer, bytesToRead) : 0;
  218374. }
  218375. int64 juce_getInternetFileContentLength (void* handle)
  218376. {
  218377. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218378. if (s != 0)
  218379. {
  218380. //xxx todo
  218381. jassertfalse
  218382. }
  218383. return -1;
  218384. }
  218385. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  218386. {
  218387. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218388. if (s != 0)
  218389. {
  218390. for (int i = 0; i < s->headerLines.size(); ++i)
  218391. {
  218392. const String& headersEntry = s->headerLines[i];
  218393. const String key (headersEntry.upToFirstOccurrenceOf (": ", false, false));
  218394. const String value (headersEntry.fromFirstOccurrenceOf (": ", false, false));
  218395. const String previousValue (headers [key]);
  218396. headers.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  218397. }
  218398. }
  218399. }
  218400. int juce_seekInInternetFile (void* handle, int newPosition)
  218401. {
  218402. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218403. return s != 0 ? s->readPosition : 0;
  218404. }
  218405. #endif
  218406. /*** End of inlined file: juce_linux_Network.cpp ***/
  218407. /*** Start of inlined file: juce_linux_SystemStats.cpp ***/
  218408. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218409. // compiled on its own).
  218410. #if JUCE_INCLUDED_FILE
  218411. void Logger::outputDebugString (const String& text)
  218412. {
  218413. std::cerr << text << std::endl;
  218414. }
  218415. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  218416. {
  218417. return Linux;
  218418. }
  218419. const String SystemStats::getOperatingSystemName()
  218420. {
  218421. return "Linux";
  218422. }
  218423. bool SystemStats::isOperatingSystem64Bit()
  218424. {
  218425. #if JUCE_64BIT
  218426. return true;
  218427. #else
  218428. //xxx not sure how to find this out?..
  218429. return false;
  218430. #endif
  218431. }
  218432. static const String juce_getCpuInfo (const char* const key)
  218433. {
  218434. StringArray lines;
  218435. lines.addLines (File ("/proc/cpuinfo").loadFileAsString());
  218436. for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
  218437. if (lines[i].startsWithIgnoreCase (key))
  218438. return lines[i].fromFirstOccurrenceOf (":", false, false).trim();
  218439. return String::empty;
  218440. }
  218441. const String SystemStats::getCpuVendor()
  218442. {
  218443. return juce_getCpuInfo ("vendor_id");
  218444. }
  218445. int SystemStats::getCpuSpeedInMegaherz()
  218446. {
  218447. return roundToInt (juce_getCpuInfo ("cpu MHz").getFloatValue());
  218448. }
  218449. int SystemStats::getMemorySizeInMegabytes()
  218450. {
  218451. struct sysinfo sysi;
  218452. if (sysinfo (&sysi) == 0)
  218453. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  218454. return 0;
  218455. }
  218456. int SystemStats::getPageSize()
  218457. {
  218458. return sysconf (_SC_PAGESIZE);
  218459. }
  218460. const String SystemStats::getLogonName()
  218461. {
  218462. const char* user = getenv ("USER");
  218463. if (user == 0)
  218464. {
  218465. struct passwd* const pw = getpwuid (getuid());
  218466. if (pw != 0)
  218467. user = pw->pw_name;
  218468. }
  218469. return String::fromUTF8 (user);
  218470. }
  218471. const String SystemStats::getFullUserName()
  218472. {
  218473. return getLogonName();
  218474. }
  218475. void SystemStats::initialiseStats()
  218476. {
  218477. const String flags (juce_getCpuInfo ("flags"));
  218478. cpuFlags.hasMMX = flags.contains ("mmx");
  218479. cpuFlags.hasSSE = flags.contains ("sse");
  218480. cpuFlags.hasSSE2 = flags.contains ("sse2");
  218481. cpuFlags.has3DNow = flags.contains ("3dnow");
  218482. cpuFlags.numCpus = juce_getCpuInfo ("processor").getIntValue() + 1;
  218483. }
  218484. void PlatformUtilities::fpuReset()
  218485. {
  218486. }
  218487. static bool juce_getTimeSinceStartup (timeval* const t) throw()
  218488. {
  218489. if (gettimeofday (t, 0) != 0)
  218490. return false;
  218491. static unsigned int calibrate = 0;
  218492. static bool calibrated = false;
  218493. if (! calibrated)
  218494. {
  218495. calibrated = true;
  218496. struct sysinfo sysi;
  218497. if (sysinfo (&sysi) == 0)
  218498. calibrate = t->tv_sec - sysi.uptime; // Safe to assume system was not brought up earlier than 1970!
  218499. }
  218500. t->tv_sec -= calibrate;
  218501. return true;
  218502. }
  218503. uint32 juce_millisecondsSinceStartup() throw()
  218504. {
  218505. timeval t;
  218506. if (juce_getTimeSinceStartup (&t))
  218507. return (uint32) (t.tv_sec * 1000 + (t.tv_usec / 1000));
  218508. return 0;
  218509. }
  218510. int64 Time::getHighResolutionTicks() throw()
  218511. {
  218512. timeval t;
  218513. if (juce_getTimeSinceStartup (&t))
  218514. return ((int64) t.tv_sec * (int64) 1000000) + (int64) t.tv_usec;
  218515. return 0;
  218516. }
  218517. int64 Time::getHighResolutionTicksPerSecond() throw()
  218518. {
  218519. return 1000000; // (microseconds)
  218520. }
  218521. double Time::getMillisecondCounterHiRes() throw()
  218522. {
  218523. return getHighResolutionTicks() * 0.001;
  218524. }
  218525. bool Time::setSystemTimeToThisTime() const
  218526. {
  218527. timeval t;
  218528. t.tv_sec = millisSinceEpoch % 1000000;
  218529. t.tv_usec = millisSinceEpoch - t.tv_sec;
  218530. return settimeofday (&t, 0) ? false : true;
  218531. }
  218532. #endif
  218533. /*** End of inlined file: juce_linux_SystemStats.cpp ***/
  218534. /*** Start of inlined file: juce_linux_Threads.cpp ***/
  218535. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218536. // compiled on its own).
  218537. #if JUCE_INCLUDED_FILE
  218538. /*
  218539. Note that a lot of methods that you'd expect to find in this file actually
  218540. live in juce_posix_SharedCode.h!
  218541. */
  218542. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  218543. void Process::setPriority (ProcessPriority prior)
  218544. {
  218545. struct sched_param param;
  218546. int policy, maxp, minp;
  218547. const int p = (int) prior;
  218548. if (p <= 1)
  218549. policy = SCHED_OTHER;
  218550. else
  218551. policy = SCHED_RR;
  218552. minp = sched_get_priority_min (policy);
  218553. maxp = sched_get_priority_max (policy);
  218554. if (p < 2)
  218555. param.sched_priority = 0;
  218556. else if (p == 2 )
  218557. // Set to middle of lower realtime priority range
  218558. param.sched_priority = minp + (maxp - minp) / 4;
  218559. else
  218560. // Set to middle of higher realtime priority range
  218561. param.sched_priority = minp + (3 * (maxp - minp) / 4);
  218562. pthread_setschedparam (pthread_self(), policy, &param);
  218563. }
  218564. void Process::terminate()
  218565. {
  218566. exit (0);
  218567. }
  218568. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  218569. {
  218570. static char testResult = 0;
  218571. if (testResult == 0)
  218572. {
  218573. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  218574. if (testResult >= 0)
  218575. {
  218576. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  218577. testResult = 1;
  218578. }
  218579. }
  218580. return testResult < 0;
  218581. }
  218582. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  218583. {
  218584. return juce_isRunningUnderDebugger();
  218585. }
  218586. void Process::raisePrivilege()
  218587. {
  218588. // If running suid root, change effective user
  218589. // to root
  218590. if (geteuid() != 0 && getuid() == 0)
  218591. {
  218592. setreuid (geteuid(), getuid());
  218593. setregid (getegid(), getgid());
  218594. }
  218595. }
  218596. void Process::lowerPrivilege()
  218597. {
  218598. // If runing suid root, change effective user
  218599. // back to real user
  218600. if (geteuid() == 0 && getuid() != 0)
  218601. {
  218602. setreuid (geteuid(), getuid());
  218603. setregid (getegid(), getgid());
  218604. }
  218605. }
  218606. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  218607. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  218608. {
  218609. return dlopen (name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  218610. }
  218611. void PlatformUtilities::freeDynamicLibrary (void* handle)
  218612. {
  218613. dlclose(handle);
  218614. }
  218615. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  218616. {
  218617. return dlsym (libraryHandle, procedureName.toCString());
  218618. }
  218619. #endif
  218620. #endif
  218621. /*** End of inlined file: juce_linux_Threads.cpp ***/
  218622. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  218623. /*** Start of inlined file: juce_linux_Clipboard.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. extern Display* display;
  218628. extern Window juce_messageWindowHandle;
  218629. namespace ClipboardHelpers
  218630. {
  218631. static String localClipboardContent;
  218632. static Atom atom_UTF8_STRING;
  218633. static Atom atom_CLIPBOARD;
  218634. static Atom atom_TARGETS;
  218635. static void initSelectionAtoms()
  218636. {
  218637. static bool isInitialised = false;
  218638. if (! isInitialised)
  218639. {
  218640. atom_UTF8_STRING = XInternAtom (display, "UTF8_STRING", False);
  218641. atom_CLIPBOARD = XInternAtom (display, "CLIPBOARD", False);
  218642. atom_TARGETS = XInternAtom (display, "TARGETS", False);
  218643. }
  218644. }
  218645. // Read the content of a window property as either a locale-dependent string or an utf8 string
  218646. // works only for strings shorter than 1000000 bytes
  218647. static String readWindowProperty (Window window, Atom prop, Atom fmt)
  218648. {
  218649. String returnData;
  218650. char* clipData;
  218651. Atom actualType;
  218652. int actualFormat;
  218653. unsigned long numItems, bytesLeft;
  218654. if (XGetWindowProperty (display, window, prop,
  218655. 0L /* offset */, 1000000 /* length (max) */, False,
  218656. AnyPropertyType /* format */,
  218657. &actualType, &actualFormat, &numItems, &bytesLeft,
  218658. (unsigned char**) &clipData) == Success)
  218659. {
  218660. if (actualType == atom_UTF8_STRING && actualFormat == 8)
  218661. returnData = String::fromUTF8 (clipData, numItems);
  218662. else if (actualType == XA_STRING && actualFormat == 8)
  218663. returnData = String (clipData, numItems);
  218664. if (clipData != 0)
  218665. XFree (clipData);
  218666. jassert (bytesLeft == 0 || numItems == 1000000);
  218667. }
  218668. XDeleteProperty (display, window, prop);
  218669. return returnData;
  218670. }
  218671. // Send a SelectionRequest to the window owning the selection and waits for its answer (with a timeout) */
  218672. static bool requestSelectionContent (String& selectionContent, Atom selection, Atom requestedFormat)
  218673. {
  218674. Atom property_name = XInternAtom (display, "JUCE_SEL", false);
  218675. // The selection owner will be asked to set the JUCE_SEL property on the
  218676. // juce_messageWindowHandle with the selection content
  218677. XConvertSelection (display, selection, requestedFormat, property_name,
  218678. juce_messageWindowHandle, CurrentTime);
  218679. int count = 50; // will wait at most for 200 ms
  218680. while (--count >= 0)
  218681. {
  218682. XEvent event;
  218683. if (XCheckTypedWindowEvent (display, juce_messageWindowHandle, SelectionNotify, &event))
  218684. {
  218685. if (event.xselection.property == property_name)
  218686. {
  218687. jassert (event.xselection.requestor == juce_messageWindowHandle);
  218688. selectionContent = readWindowProperty (event.xselection.requestor,
  218689. event.xselection.property,
  218690. requestedFormat);
  218691. return true;
  218692. }
  218693. else
  218694. {
  218695. return false; // the format we asked for was denied.. (event.xselection.property == None)
  218696. }
  218697. }
  218698. // not very elegant.. we could do a select() or something like that...
  218699. // however clipboard content requesting is inherently slow on x11, it
  218700. // often takes 50ms or more so...
  218701. Thread::sleep (4);
  218702. }
  218703. return false;
  218704. }
  218705. }
  218706. // Called from the event loop in juce_linux_Messaging in response to SelectionRequest events
  218707. void juce_handleSelectionRequest (XSelectionRequestEvent &evt)
  218708. {
  218709. ClipboardHelpers::initSelectionAtoms();
  218710. // the selection content is sent to the target window as a window property
  218711. XSelectionEvent reply;
  218712. reply.type = SelectionNotify;
  218713. reply.display = evt.display;
  218714. reply.requestor = evt.requestor;
  218715. reply.selection = evt.selection;
  218716. reply.target = evt.target;
  218717. reply.property = None; // == "fail"
  218718. reply.time = evt.time;
  218719. HeapBlock <char> data;
  218720. int propertyFormat = 0, numDataItems = 0;
  218721. if (evt.selection == XA_PRIMARY || evt.selection == ClipboardHelpers::atom_CLIPBOARD)
  218722. {
  218723. if (evt.target == XA_STRING)
  218724. {
  218725. // format data according to system locale
  218726. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsCString() + 1;
  218727. data.calloc (numDataItems + 1);
  218728. ClipboardHelpers::localClipboardContent.copyToCString (data, numDataItems);
  218729. propertyFormat = 8; // bits/item
  218730. }
  218731. else if (evt.target == ClipboardHelpers::atom_UTF8_STRING)
  218732. {
  218733. // translate to utf8
  218734. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsUTF8() + 1;
  218735. data.calloc (numDataItems + 1);
  218736. ClipboardHelpers::localClipboardContent.copyToUTF8 (data, numDataItems);
  218737. propertyFormat = 8; // bits/item
  218738. }
  218739. else if (evt.target == ClipboardHelpers::atom_TARGETS)
  218740. {
  218741. // another application wants to know what we are able to send
  218742. numDataItems = 2;
  218743. propertyFormat = 32; // atoms are 32-bit
  218744. data.calloc (numDataItems * 4);
  218745. Atom* atoms = reinterpret_cast<Atom*> (data.getData());
  218746. atoms[0] = ClipboardHelpers::atom_UTF8_STRING;
  218747. atoms[1] = XA_STRING;
  218748. }
  218749. }
  218750. else
  218751. {
  218752. DBG ("requested unsupported clipboard");
  218753. }
  218754. if (data != 0)
  218755. {
  218756. const int maxReasonableSelectionSize = 1000000;
  218757. // for very big chunks of data, we should use the "INCR" protocol , which is a pain in the *ss
  218758. if (evt.property != None && numDataItems < maxReasonableSelectionSize)
  218759. {
  218760. XChangeProperty (evt.display, evt.requestor,
  218761. evt.property, evt.target,
  218762. propertyFormat /* 8 or 32 */, PropModeReplace,
  218763. reinterpret_cast<const unsigned char*> (data.getData()), numDataItems);
  218764. reply.property = evt.property; // " == success"
  218765. }
  218766. }
  218767. XSendEvent (evt.display, evt.requestor, 0, NoEventMask, (XEvent*) &reply);
  218768. }
  218769. void SystemClipboard::copyTextToClipboard (const String& clipText)
  218770. {
  218771. ClipboardHelpers::initSelectionAtoms();
  218772. ClipboardHelpers::localClipboardContent = clipText;
  218773. XSetSelectionOwner (display, XA_PRIMARY, juce_messageWindowHandle, CurrentTime);
  218774. XSetSelectionOwner (display, ClipboardHelpers::atom_CLIPBOARD, juce_messageWindowHandle, CurrentTime);
  218775. }
  218776. const String SystemClipboard::getTextFromClipboard()
  218777. {
  218778. ClipboardHelpers::initSelectionAtoms();
  218779. /* 1) try to read from the "CLIPBOARD" selection first (the "high
  218780. level" clipboard that is supposed to be filled by ctrl-C
  218781. etc). When a clipboard manager is running, the content of this
  218782. selection is preserved even when the original selection owner
  218783. exits.
  218784. 2) and then try to read from "PRIMARY" selection (the "legacy" selection
  218785. filled by good old x11 apps such as xterm)
  218786. */
  218787. String content;
  218788. Atom selection = XA_PRIMARY;
  218789. Window selectionOwner = None;
  218790. if ((selectionOwner = XGetSelectionOwner (display, selection)) == None)
  218791. {
  218792. selection = ClipboardHelpers::atom_CLIPBOARD;
  218793. selectionOwner = XGetSelectionOwner (display, selection);
  218794. }
  218795. if (selectionOwner != None)
  218796. {
  218797. if (selectionOwner == juce_messageWindowHandle)
  218798. {
  218799. content = ClipboardHelpers::localClipboardContent;
  218800. }
  218801. else
  218802. {
  218803. // first try: we want an utf8 string
  218804. bool ok = ClipboardHelpers::requestSelectionContent (content, selection, ClipboardHelpers::atom_UTF8_STRING);
  218805. if (! ok)
  218806. {
  218807. // second chance, ask for a good old locale-dependent string ..
  218808. ok = ClipboardHelpers::requestSelectionContent (content, selection, XA_STRING);
  218809. }
  218810. }
  218811. }
  218812. return content;
  218813. }
  218814. #endif
  218815. /*** End of inlined file: juce_linux_Clipboard.cpp ***/
  218816. /*** Start of inlined file: juce_linux_Messaging.cpp ***/
  218817. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218818. // compiled on its own).
  218819. #if JUCE_INCLUDED_FILE
  218820. #if JUCE_DEBUG && ! defined (JUCE_DEBUG_XERRORS)
  218821. #define JUCE_DEBUG_XERRORS 1
  218822. #endif
  218823. Display* display = 0;
  218824. Window juce_messageWindowHandle = None;
  218825. XContext windowHandleXContext; // This is referenced from Windowing.cpp
  218826. extern void juce_windowMessageReceive (XEvent* event); // Defined in Windowing.cpp
  218827. extern void juce_handleSelectionRequest (XSelectionRequestEvent &evt); // Defined in Clipboard.cpp
  218828. ScopedXLock::ScopedXLock() { XLockDisplay (display); }
  218829. ScopedXLock::~ScopedXLock() { XUnlockDisplay (display); }
  218830. class InternalMessageQueue
  218831. {
  218832. public:
  218833. InternalMessageQueue()
  218834. : bytesInSocket (0),
  218835. totalEventCount (0)
  218836. {
  218837. int ret = ::socketpair (AF_LOCAL, SOCK_STREAM, 0, fd);
  218838. (void) ret; jassert (ret == 0);
  218839. //setNonBlocking (fd[0]);
  218840. //setNonBlocking (fd[1]);
  218841. }
  218842. ~InternalMessageQueue()
  218843. {
  218844. close (fd[0]);
  218845. close (fd[1]);
  218846. clearSingletonInstance();
  218847. }
  218848. void postMessage (Message* msg)
  218849. {
  218850. const int maxBytesInSocketQueue = 128;
  218851. ScopedLock sl (lock);
  218852. queue.add (msg);
  218853. if (bytesInSocket < maxBytesInSocketQueue)
  218854. {
  218855. ++bytesInSocket;
  218856. ScopedUnlock ul (lock);
  218857. const unsigned char x = 0xff;
  218858. size_t bytesWritten = write (fd[0], &x, 1);
  218859. (void) bytesWritten;
  218860. }
  218861. }
  218862. bool isEmpty() const
  218863. {
  218864. ScopedLock sl (lock);
  218865. return queue.size() == 0;
  218866. }
  218867. bool dispatchNextEvent()
  218868. {
  218869. // This alternates between giving priority to XEvents or internal messages,
  218870. // to keep everything running smoothly..
  218871. if ((++totalEventCount & 1) != 0)
  218872. return dispatchNextXEvent() || dispatchNextInternalMessage();
  218873. else
  218874. return dispatchNextInternalMessage() || dispatchNextXEvent();
  218875. }
  218876. // Wait for an event (either XEvent, or an internal Message)
  218877. bool sleepUntilEvent (const int timeoutMs)
  218878. {
  218879. if (! isEmpty())
  218880. return true;
  218881. if (display != 0)
  218882. {
  218883. ScopedXLock xlock;
  218884. if (XPending (display))
  218885. return true;
  218886. }
  218887. struct timeval tv;
  218888. tv.tv_sec = 0;
  218889. tv.tv_usec = timeoutMs * 1000;
  218890. int fd0 = getWaitHandle();
  218891. int fdmax = fd0;
  218892. fd_set readset;
  218893. FD_ZERO (&readset);
  218894. FD_SET (fd0, &readset);
  218895. if (display != 0)
  218896. {
  218897. ScopedXLock xlock;
  218898. int fd1 = XConnectionNumber (display);
  218899. FD_SET (fd1, &readset);
  218900. fdmax = jmax (fd0, fd1);
  218901. }
  218902. const int ret = select (fdmax + 1, &readset, 0, 0, &tv);
  218903. return (ret > 0); // ret <= 0 if error or timeout
  218904. }
  218905. struct MessageThreadFuncCall
  218906. {
  218907. enum { uniqueID = 0x73774623 };
  218908. MessageCallbackFunction* func;
  218909. void* parameter;
  218910. void* result;
  218911. CriticalSection lock;
  218912. WaitableEvent event;
  218913. };
  218914. juce_DeclareSingleton_SingleThreaded_Minimal (InternalMessageQueue);
  218915. private:
  218916. CriticalSection lock;
  218917. OwnedArray <Message> queue;
  218918. int fd[2];
  218919. int bytesInSocket;
  218920. int totalEventCount;
  218921. int getWaitHandle() const throw() { return fd[1]; }
  218922. static bool setNonBlocking (int handle)
  218923. {
  218924. int socketFlags = fcntl (handle, F_GETFL, 0);
  218925. if (socketFlags == -1)
  218926. return false;
  218927. socketFlags |= O_NONBLOCK;
  218928. return fcntl (handle, F_SETFL, socketFlags) == 0;
  218929. }
  218930. static bool dispatchNextXEvent()
  218931. {
  218932. if (display == 0)
  218933. return false;
  218934. XEvent evt;
  218935. {
  218936. ScopedXLock xlock;
  218937. if (! XPending (display))
  218938. return false;
  218939. XNextEvent (display, &evt);
  218940. }
  218941. if (evt.type == SelectionRequest && evt.xany.window == juce_messageWindowHandle)
  218942. juce_handleSelectionRequest (evt.xselectionrequest);
  218943. else if (evt.xany.window != juce_messageWindowHandle)
  218944. juce_windowMessageReceive (&evt);
  218945. return true;
  218946. }
  218947. Message* popNextMessage()
  218948. {
  218949. ScopedLock sl (lock);
  218950. if (bytesInSocket > 0)
  218951. {
  218952. --bytesInSocket;
  218953. ScopedUnlock ul (lock);
  218954. unsigned char x;
  218955. size_t numBytes = read (fd[1], &x, 1);
  218956. (void) numBytes;
  218957. }
  218958. return queue.removeAndReturn (0);
  218959. }
  218960. bool dispatchNextInternalMessage()
  218961. {
  218962. ScopedPointer <Message> msg (popNextMessage());
  218963. if (msg == 0)
  218964. return false;
  218965. if (msg->intParameter1 == MessageThreadFuncCall::uniqueID)
  218966. {
  218967. // Handle callback message
  218968. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) msg->pointerParameter;
  218969. call->result = (*(call->func)) (call->parameter);
  218970. call->event.signal();
  218971. }
  218972. else
  218973. {
  218974. // Handle "normal" messages
  218975. MessageManager::getInstance()->deliverMessage (msg.release());
  218976. }
  218977. return true;
  218978. }
  218979. };
  218980. juce_ImplementSingleton_SingleThreaded (InternalMessageQueue);
  218981. namespace LinuxErrorHandling
  218982. {
  218983. static bool errorOccurred = false;
  218984. static bool keyboardBreakOccurred = false;
  218985. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  218986. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  218987. // Usually happens when client-server connection is broken
  218988. static int ioErrorHandler (Display* display)
  218989. {
  218990. DBG ("ERROR: connection to X server broken.. terminating.");
  218991. if (JUCEApplication::isStandaloneApp())
  218992. MessageManager::getInstance()->stopDispatchLoop();
  218993. errorOccurred = true;
  218994. return 0;
  218995. }
  218996. // A protocol error has occurred
  218997. static int juce_XErrorHandler (Display* display, XErrorEvent* event)
  218998. {
  218999. #if JUCE_DEBUG_XERRORS
  219000. char errorStr[64] = { 0 };
  219001. char requestStr[64] = { 0 };
  219002. XGetErrorText (display, event->error_code, errorStr, 64);
  219003. XGetErrorDatabaseText (display, "XRequest", String (event->request_code).toCString(), "Unknown", requestStr, 64);
  219004. DBG ("ERROR: X returned " + String (errorStr) + " for operation " + String (requestStr));
  219005. #endif
  219006. return 0;
  219007. }
  219008. static void installXErrorHandlers()
  219009. {
  219010. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  219011. oldErrorHandler = XSetErrorHandler (juce_XErrorHandler);
  219012. }
  219013. static void removeXErrorHandlers()
  219014. {
  219015. XSetIOErrorHandler (oldIOErrorHandler);
  219016. oldIOErrorHandler = 0;
  219017. XSetErrorHandler (oldErrorHandler);
  219018. oldErrorHandler = 0;
  219019. }
  219020. static void keyboardBreakSignalHandler (int sig)
  219021. {
  219022. if (sig == SIGINT)
  219023. keyboardBreakOccurred = true;
  219024. }
  219025. static void installKeyboardBreakHandler()
  219026. {
  219027. struct sigaction saction;
  219028. sigset_t maskSet;
  219029. sigemptyset (&maskSet);
  219030. saction.sa_handler = keyboardBreakSignalHandler;
  219031. saction.sa_mask = maskSet;
  219032. saction.sa_flags = 0;
  219033. sigaction (SIGINT, &saction, 0);
  219034. }
  219035. }
  219036. void MessageManager::doPlatformSpecificInitialisation()
  219037. {
  219038. // Initialise xlib for multiple thread support
  219039. static bool initThreadCalled = false;
  219040. if (! initThreadCalled)
  219041. {
  219042. if (! XInitThreads())
  219043. {
  219044. // This is fatal! Print error and closedown
  219045. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  219046. if (JUCEApplication::isStandaloneApp())
  219047. Process::terminate();
  219048. return;
  219049. }
  219050. initThreadCalled = true;
  219051. }
  219052. LinuxErrorHandling::installXErrorHandlers();
  219053. LinuxErrorHandling::installKeyboardBreakHandler();
  219054. // Create the internal message queue
  219055. InternalMessageQueue::getInstance();
  219056. // Try to connect to a display
  219057. String displayName (getenv ("DISPLAY"));
  219058. if (displayName.isEmpty())
  219059. displayName = ":0.0";
  219060. display = XOpenDisplay (displayName.toCString());
  219061. if (display != 0) // This is not fatal! we can run headless.
  219062. {
  219063. // Create a context to store user data associated with Windows we create in WindowDriver
  219064. windowHandleXContext = XUniqueContext();
  219065. // We're only interested in client messages for this window, which are always sent
  219066. XSetWindowAttributes swa;
  219067. swa.event_mask = NoEventMask;
  219068. // Create our message window (this will never be mapped)
  219069. const int screen = DefaultScreen (display);
  219070. juce_messageWindowHandle = XCreateWindow (display, RootWindow (display, screen),
  219071. 0, 0, 1, 1, 0, 0, InputOnly,
  219072. DefaultVisual (display, screen),
  219073. CWEventMask, &swa);
  219074. }
  219075. }
  219076. void MessageManager::doPlatformSpecificShutdown()
  219077. {
  219078. InternalMessageQueue::deleteInstance();
  219079. if (display != 0 && ! LinuxErrorHandling::errorOccurred)
  219080. {
  219081. XDestroyWindow (display, juce_messageWindowHandle);
  219082. XCloseDisplay (display);
  219083. juce_messageWindowHandle = 0;
  219084. display = 0;
  219085. LinuxErrorHandling::removeXErrorHandlers();
  219086. }
  219087. }
  219088. bool juce_postMessageToSystemQueue (Message* message)
  219089. {
  219090. if (LinuxErrorHandling::errorOccurred)
  219091. return false;
  219092. InternalMessageQueue::getInstanceWithoutCreating()->postMessage (message);
  219093. return true;
  219094. }
  219095. void MessageManager::broadcastMessage (const String& value)
  219096. {
  219097. /* TODO */
  219098. }
  219099. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func, void* parameter)
  219100. {
  219101. if (LinuxErrorHandling::errorOccurred)
  219102. return 0;
  219103. if (isThisTheMessageThread())
  219104. return func (parameter);
  219105. InternalMessageQueue::MessageThreadFuncCall messageCallContext;
  219106. messageCallContext.func = func;
  219107. messageCallContext.parameter = parameter;
  219108. InternalMessageQueue::getInstanceWithoutCreating()
  219109. ->postMessage (new Message (InternalMessageQueue::MessageThreadFuncCall::uniqueID,
  219110. 0, 0, &messageCallContext));
  219111. // Wait for it to complete before continuing
  219112. messageCallContext.event.wait();
  219113. return messageCallContext.result;
  219114. }
  219115. // this function expects that it will NEVER be called simultaneously for two concurrent threads
  219116. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  219117. {
  219118. while (! LinuxErrorHandling::errorOccurred)
  219119. {
  219120. if (LinuxErrorHandling::keyboardBreakOccurred)
  219121. {
  219122. LinuxErrorHandling::errorOccurred = true;
  219123. if (JUCEApplication::isStandaloneApp())
  219124. Process::terminate();
  219125. break;
  219126. }
  219127. if (InternalMessageQueue::getInstanceWithoutCreating()->dispatchNextEvent())
  219128. return true;
  219129. if (returnIfNoPendingMessages)
  219130. break;
  219131. InternalMessageQueue::getInstanceWithoutCreating()->sleepUntilEvent (2000);
  219132. }
  219133. return false;
  219134. }
  219135. #endif
  219136. /*** End of inlined file: juce_linux_Messaging.cpp ***/
  219137. /*** Start of inlined file: juce_linux_Fonts.cpp ***/
  219138. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219139. // compiled on its own).
  219140. #if JUCE_INCLUDED_FILE
  219141. class FreeTypeFontFace
  219142. {
  219143. public:
  219144. enum FontStyle
  219145. {
  219146. Plain = 0,
  219147. Bold = 1,
  219148. Italic = 2
  219149. };
  219150. FreeTypeFontFace (const String& familyName)
  219151. : hasSerif (false),
  219152. monospaced (false)
  219153. {
  219154. family = familyName;
  219155. }
  219156. void setFileName (const String& name, const int faceIndex, FontStyle style)
  219157. {
  219158. if (names [(int) style].fileName.isEmpty())
  219159. {
  219160. names [(int) style].fileName = name;
  219161. names [(int) style].faceIndex = faceIndex;
  219162. }
  219163. }
  219164. const String& getFamilyName() const throw() { return family; }
  219165. const String& getFileName (const int style, int& faceIndex) const throw()
  219166. {
  219167. faceIndex = names[style].faceIndex;
  219168. return names[style].fileName;
  219169. }
  219170. void setMonospaced (bool mono) throw() { monospaced = mono; }
  219171. bool getMonospaced() const throw() { return monospaced; }
  219172. void setSerif (const bool serif) throw() { hasSerif = serif; }
  219173. bool getSerif() const throw() { return hasSerif; }
  219174. private:
  219175. String family;
  219176. struct FontNameIndex
  219177. {
  219178. String fileName;
  219179. int faceIndex;
  219180. };
  219181. FontNameIndex names[4];
  219182. bool hasSerif, monospaced;
  219183. };
  219184. class FreeTypeInterface : public DeletedAtShutdown
  219185. {
  219186. public:
  219187. FreeTypeInterface()
  219188. : ftLib (0),
  219189. lastFace (0),
  219190. lastBold (false),
  219191. lastItalic (false)
  219192. {
  219193. if (FT_Init_FreeType (&ftLib) != 0)
  219194. {
  219195. ftLib = 0;
  219196. DBG ("Failed to initialize FreeType");
  219197. }
  219198. StringArray fontDirs;
  219199. fontDirs.addTokens (String::fromUTF8 (getenv ("JUCE_FONT_PATH")), ";,", String::empty);
  219200. fontDirs.removeEmptyStrings (true);
  219201. if (fontDirs.size() == 0)
  219202. {
  219203. XmlDocument fontsConfig (File ("/etc/fonts/fonts.conf"));
  219204. const ScopedPointer<XmlElement> fontsInfo (fontsConfig.getDocumentElement());
  219205. if (fontsInfo != 0)
  219206. {
  219207. forEachXmlChildElementWithTagName (*fontsInfo, e, "dir")
  219208. {
  219209. fontDirs.add (e->getAllSubText().trim());
  219210. }
  219211. }
  219212. }
  219213. if (fontDirs.size() == 0)
  219214. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  219215. for (int i = 0; i < fontDirs.size(); ++i)
  219216. enumerateFaces (fontDirs[i]);
  219217. }
  219218. ~FreeTypeInterface()
  219219. {
  219220. if (lastFace != 0)
  219221. FT_Done_Face (lastFace);
  219222. if (ftLib != 0)
  219223. FT_Done_FreeType (ftLib);
  219224. clearSingletonInstance();
  219225. }
  219226. FreeTypeFontFace* findOrCreate (const String& familyName, const bool create = false)
  219227. {
  219228. for (int i = 0; i < faces.size(); i++)
  219229. if (faces[i]->getFamilyName() == familyName)
  219230. return faces[i];
  219231. if (! create)
  219232. return 0;
  219233. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  219234. faces.add (newFace);
  219235. return newFace;
  219236. }
  219237. // Enumerate all font faces available in a given directory
  219238. void enumerateFaces (const String& path)
  219239. {
  219240. File dirPath (path);
  219241. if (path.isEmpty() || ! dirPath.isDirectory())
  219242. return;
  219243. DirectoryIterator di (dirPath, true);
  219244. while (di.next())
  219245. {
  219246. File possible (di.getFile());
  219247. if (possible.hasFileExtension ("ttf")
  219248. || possible.hasFileExtension ("pfb")
  219249. || possible.hasFileExtension ("pcf"))
  219250. {
  219251. FT_Face face;
  219252. int faceIndex = 0;
  219253. int numFaces = 0;
  219254. do
  219255. {
  219256. if (FT_New_Face (ftLib, possible.getFullPathName().toUTF8(),
  219257. faceIndex, &face) == 0)
  219258. {
  219259. if (faceIndex == 0)
  219260. numFaces = face->num_faces;
  219261. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  219262. {
  219263. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  219264. int style = (int) FreeTypeFontFace::Plain;
  219265. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  219266. style |= (int) FreeTypeFontFace::Bold;
  219267. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  219268. style |= (int) FreeTypeFontFace::Italic;
  219269. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  219270. newFace->setMonospaced ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0);
  219271. // Surely there must be a better way to do this?
  219272. const String name (face->family_name);
  219273. newFace->setSerif (! (name.containsIgnoreCase ("Sans")
  219274. || name.containsIgnoreCase ("Verdana")
  219275. || name.containsIgnoreCase ("Arial")));
  219276. }
  219277. FT_Done_Face (face);
  219278. }
  219279. ++faceIndex;
  219280. }
  219281. while (faceIndex < numFaces);
  219282. }
  219283. }
  219284. }
  219285. // Create a FreeType face object for a given font
  219286. FT_Face createFT_Face (const String& fontName, const bool bold, const bool italic)
  219287. {
  219288. FT_Face face = 0;
  219289. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  219290. {
  219291. face = lastFace;
  219292. }
  219293. else
  219294. {
  219295. if (lastFace != 0)
  219296. {
  219297. FT_Done_Face (lastFace);
  219298. lastFace = 0;
  219299. }
  219300. lastFontName = fontName;
  219301. lastBold = bold;
  219302. lastItalic = italic;
  219303. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  219304. if (ftFace != 0)
  219305. {
  219306. int style = (int) FreeTypeFontFace::Plain;
  219307. if (bold)
  219308. style |= (int) FreeTypeFontFace::Bold;
  219309. if (italic)
  219310. style |= (int) FreeTypeFontFace::Italic;
  219311. int faceIndex;
  219312. String fileName (ftFace->getFileName (style, faceIndex));
  219313. if (fileName.isEmpty())
  219314. {
  219315. style ^= (int) FreeTypeFontFace::Bold;
  219316. fileName = ftFace->getFileName (style, faceIndex);
  219317. if (fileName.isEmpty())
  219318. {
  219319. style ^= (int) FreeTypeFontFace::Bold;
  219320. style ^= (int) FreeTypeFontFace::Italic;
  219321. fileName = ftFace->getFileName (style, faceIndex);
  219322. if (! fileName.length())
  219323. {
  219324. style ^= (int) FreeTypeFontFace::Bold;
  219325. fileName = ftFace->getFileName (style, faceIndex);
  219326. }
  219327. }
  219328. }
  219329. if (! FT_New_Face (ftLib, fileName.toUTF8(), faceIndex, &lastFace))
  219330. {
  219331. face = lastFace;
  219332. // If there isn't a unicode charmap then select the first one.
  219333. if (FT_Select_Charmap (face, ft_encoding_unicode))
  219334. FT_Set_Charmap (face, face->charmaps[0]);
  219335. }
  219336. }
  219337. }
  219338. return face;
  219339. }
  219340. bool addGlyph (FT_Face face, CustomTypeface& dest, uint32 character)
  219341. {
  219342. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  219343. const float height = (float) (face->ascender - face->descender);
  219344. const float scaleX = 1.0f / height;
  219345. const float scaleY = -1.0f / height;
  219346. Path destShape;
  219347. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_TRANSFORM) != 0
  219348. || face->glyph->format != ft_glyph_format_outline)
  219349. {
  219350. return false;
  219351. }
  219352. const FT_Outline* const outline = &face->glyph->outline;
  219353. const short* const contours = outline->contours;
  219354. const char* const tags = outline->tags;
  219355. FT_Vector* const points = outline->points;
  219356. for (int c = 0; c < outline->n_contours; c++)
  219357. {
  219358. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  219359. const int endPoint = contours[c];
  219360. for (int p = startPoint; p <= endPoint; p++)
  219361. {
  219362. const float x = scaleX * points[p].x;
  219363. const float y = scaleY * points[p].y;
  219364. if (p == startPoint)
  219365. {
  219366. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  219367. {
  219368. float x2 = scaleX * points [endPoint].x;
  219369. float y2 = scaleY * points [endPoint].y;
  219370. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  219371. {
  219372. x2 = (x + x2) * 0.5f;
  219373. y2 = (y + y2) * 0.5f;
  219374. }
  219375. destShape.startNewSubPath (x2, y2);
  219376. }
  219377. else
  219378. {
  219379. destShape.startNewSubPath (x, y);
  219380. }
  219381. }
  219382. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  219383. {
  219384. if (p != startPoint)
  219385. destShape.lineTo (x, y);
  219386. }
  219387. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  219388. {
  219389. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  219390. float x2 = scaleX * points [nextIndex].x;
  219391. float y2 = scaleY * points [nextIndex].y;
  219392. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  219393. {
  219394. x2 = (x + x2) * 0.5f;
  219395. y2 = (y + y2) * 0.5f;
  219396. }
  219397. else
  219398. {
  219399. ++p;
  219400. }
  219401. destShape.quadraticTo (x, y, x2, y2);
  219402. }
  219403. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  219404. {
  219405. if (p >= endPoint)
  219406. return false;
  219407. const int next1 = p + 1;
  219408. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  219409. const float x2 = scaleX * points [next1].x;
  219410. const float y2 = scaleY * points [next1].y;
  219411. const float x3 = scaleX * points [next2].x;
  219412. const float y3 = scaleY * points [next2].y;
  219413. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  219414. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  219415. return false;
  219416. destShape.cubicTo (x, y, x2, y2, x3, y3);
  219417. p += 2;
  219418. }
  219419. }
  219420. destShape.closeSubPath();
  219421. }
  219422. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance / height);
  219423. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  219424. addKerning (face, dest, character, glyphIndex);
  219425. return true;
  219426. }
  219427. void addKerning (FT_Face face, CustomTypeface& dest, const uint32 character, const uint32 glyphIndex)
  219428. {
  219429. const float height = (float) (face->ascender - face->descender);
  219430. uint32 rightGlyphIndex;
  219431. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  219432. while (rightGlyphIndex != 0)
  219433. {
  219434. FT_Vector kerning;
  219435. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  219436. {
  219437. if (kerning.x != 0)
  219438. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  219439. }
  219440. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  219441. }
  219442. }
  219443. // Add a glyph to a font
  219444. bool addGlyphToFont (const uint32 character, const String& fontName,
  219445. bool bold, bool italic, CustomTypeface& dest)
  219446. {
  219447. FT_Face face = createFT_Face (fontName, bold, italic);
  219448. return face != 0 && addGlyph (face, dest, character);
  219449. }
  219450. void getFamilyNames (StringArray& familyNames) const
  219451. {
  219452. for (int i = 0; i < faces.size(); i++)
  219453. familyNames.add (faces[i]->getFamilyName());
  219454. }
  219455. void getMonospacedNames (StringArray& monoSpaced) const
  219456. {
  219457. for (int i = 0; i < faces.size(); i++)
  219458. if (faces[i]->getMonospaced())
  219459. monoSpaced.add (faces[i]->getFamilyName());
  219460. }
  219461. void getSerifNames (StringArray& serif) const
  219462. {
  219463. for (int i = 0; i < faces.size(); i++)
  219464. if (faces[i]->getSerif())
  219465. serif.add (faces[i]->getFamilyName());
  219466. }
  219467. void getSansSerifNames (StringArray& sansSerif) const
  219468. {
  219469. for (int i = 0; i < faces.size(); i++)
  219470. if (! faces[i]->getSerif())
  219471. sansSerif.add (faces[i]->getFamilyName());
  219472. }
  219473. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  219474. private:
  219475. FT_Library ftLib;
  219476. FT_Face lastFace;
  219477. String lastFontName;
  219478. bool lastBold, lastItalic;
  219479. OwnedArray<FreeTypeFontFace> faces;
  219480. };
  219481. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  219482. class FreetypeTypeface : public CustomTypeface
  219483. {
  219484. public:
  219485. FreetypeTypeface (const Font& font)
  219486. {
  219487. FT_Face face = FreeTypeInterface::getInstance()
  219488. ->createFT_Face (font.getTypefaceName(), font.isBold(), font.isItalic());
  219489. if (face == 0)
  219490. {
  219491. #if JUCE_DEBUG
  219492. String msg ("Failed to create typeface: ");
  219493. msg << font.getTypefaceName() << " " << (font.isBold() ? 'B' : ' ') << (font.isItalic() ? 'I' : ' ');
  219494. DBG (msg);
  219495. #endif
  219496. }
  219497. else
  219498. {
  219499. setCharacteristics (font.getTypefaceName(),
  219500. face->ascender / (float) (face->ascender - face->descender),
  219501. font.isBold(), font.isItalic(),
  219502. L' ');
  219503. }
  219504. }
  219505. bool loadGlyphIfPossible (juce_wchar character)
  219506. {
  219507. return FreeTypeInterface::getInstance()
  219508. ->addGlyphToFont (character, name, isBold, isItalic, *this);
  219509. }
  219510. };
  219511. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  219512. {
  219513. return new FreetypeTypeface (font);
  219514. }
  219515. const StringArray Font::findAllTypefaceNames()
  219516. {
  219517. StringArray s;
  219518. FreeTypeInterface::getInstance()->getFamilyNames (s);
  219519. s.sort (true);
  219520. return s;
  219521. }
  219522. static const String pickBestFont (const StringArray& names,
  219523. const char* const choicesString)
  219524. {
  219525. StringArray choices;
  219526. choices.addTokens (String (choicesString), ",", String::empty);
  219527. choices.trim();
  219528. choices.removeEmptyStrings();
  219529. int i, j;
  219530. for (j = 0; j < choices.size(); ++j)
  219531. if (names.contains (choices[j], true))
  219532. return choices[j];
  219533. for (j = 0; j < choices.size(); ++j)
  219534. for (i = 0; i < names.size(); i++)
  219535. if (names[i].startsWithIgnoreCase (choices[j]))
  219536. return names[i];
  219537. for (j = 0; j < choices.size(); ++j)
  219538. for (i = 0; i < names.size(); i++)
  219539. if (names[i].containsIgnoreCase (choices[j]))
  219540. return names[i];
  219541. return names[0];
  219542. }
  219543. static const String linux_getDefaultSansSerifFontName()
  219544. {
  219545. StringArray allFonts;
  219546. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  219547. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  219548. }
  219549. static const String linux_getDefaultSerifFontName()
  219550. {
  219551. StringArray allFonts;
  219552. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  219553. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  219554. }
  219555. static const String linux_getDefaultMonospacedFontName()
  219556. {
  219557. StringArray allFonts;
  219558. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  219559. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  219560. }
  219561. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  219562. {
  219563. defaultSans = linux_getDefaultSansSerifFontName();
  219564. defaultSerif = linux_getDefaultSerifFontName();
  219565. defaultFixed = linux_getDefaultMonospacedFontName();
  219566. }
  219567. #endif
  219568. /*** End of inlined file: juce_linux_Fonts.cpp ***/
  219569. /*** Start of inlined file: juce_linux_Windowing.cpp ***/
  219570. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219571. // compiled on its own).
  219572. #if JUCE_INCLUDED_FILE
  219573. // These are defined in juce_linux_Messaging.cpp
  219574. extern Display* display;
  219575. extern XContext windowHandleXContext;
  219576. namespace Atoms
  219577. {
  219578. enum ProtocolItems
  219579. {
  219580. TAKE_FOCUS = 0,
  219581. DELETE_WINDOW = 1,
  219582. PING = 2
  219583. };
  219584. static Atom Protocols, ProtocolList[3], ChangeState, State,
  219585. ActiveWin, Pid, WindowType, WindowState,
  219586. XdndAware, XdndEnter, XdndLeave, XdndPosition, XdndStatus,
  219587. XdndDrop, XdndFinished, XdndSelection, XdndTypeList, XdndActionList,
  219588. XdndActionDescription, XdndActionCopy,
  219589. allowedActions[5],
  219590. allowedMimeTypes[2];
  219591. const unsigned long DndVersion = 3;
  219592. static void initialiseAtoms()
  219593. {
  219594. static bool atomsInitialised = false;
  219595. if (! atomsInitialised)
  219596. {
  219597. atomsInitialised = true;
  219598. Protocols = XInternAtom (display, "WM_PROTOCOLS", True);
  219599. ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", True);
  219600. ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", True);
  219601. ProtocolList [PING] = XInternAtom (display, "_NET_WM_PING", True);
  219602. ChangeState = XInternAtom (display, "WM_CHANGE_STATE", True);
  219603. State = XInternAtom (display, "WM_STATE", True);
  219604. ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  219605. Pid = XInternAtom (display, "_NET_WM_PID", False);
  219606. WindowType = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  219607. WindowState = XInternAtom (display, "_NET_WM_STATE", True);
  219608. XdndAware = XInternAtom (display, "XdndAware", False);
  219609. XdndEnter = XInternAtom (display, "XdndEnter", False);
  219610. XdndLeave = XInternAtom (display, "XdndLeave", False);
  219611. XdndPosition = XInternAtom (display, "XdndPosition", False);
  219612. XdndStatus = XInternAtom (display, "XdndStatus", False);
  219613. XdndDrop = XInternAtom (display, "XdndDrop", False);
  219614. XdndFinished = XInternAtom (display, "XdndFinished", False);
  219615. XdndSelection = XInternAtom (display, "XdndSelection", False);
  219616. XdndTypeList = XInternAtom (display, "XdndTypeList", False);
  219617. XdndActionList = XInternAtom (display, "XdndActionList", False);
  219618. XdndActionCopy = XInternAtom (display, "XdndActionCopy", False);
  219619. XdndActionDescription = XInternAtom (display, "XdndActionDescription", False);
  219620. allowedMimeTypes[0] = XInternAtom (display, "text/plain", False);
  219621. allowedMimeTypes[1] = XInternAtom (display, "text/uri-list", False);
  219622. allowedActions[0] = XInternAtom (display, "XdndActionMove", False);
  219623. allowedActions[1] = XdndActionCopy;
  219624. allowedActions[2] = XInternAtom (display, "XdndActionLink", False);
  219625. allowedActions[3] = XInternAtom (display, "XdndActionAsk", False);
  219626. allowedActions[4] = XInternAtom (display, "XdndActionPrivate", False);
  219627. }
  219628. }
  219629. }
  219630. namespace Keys
  219631. {
  219632. enum MouseButtons
  219633. {
  219634. NoButton = 0,
  219635. LeftButton = 1,
  219636. MiddleButton = 2,
  219637. RightButton = 3,
  219638. WheelUp = 4,
  219639. WheelDown = 5
  219640. };
  219641. static int AltMask = 0;
  219642. static int NumLockMask = 0;
  219643. static bool numLock = false;
  219644. static bool capsLock = false;
  219645. static char keyStates [32];
  219646. static const int extendedKeyModifier = 0x10000000;
  219647. }
  219648. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  219649. {
  219650. int keysym;
  219651. if (keyCode & Keys::extendedKeyModifier)
  219652. {
  219653. keysym = 0xff00 | (keyCode & 0xff);
  219654. }
  219655. else
  219656. {
  219657. keysym = keyCode;
  219658. if (keysym == (XK_Tab & 0xff)
  219659. || keysym == (XK_Return & 0xff)
  219660. || keysym == (XK_Escape & 0xff)
  219661. || keysym == (XK_BackSpace & 0xff))
  219662. {
  219663. keysym |= 0xff00;
  219664. }
  219665. }
  219666. ScopedXLock xlock;
  219667. const int keycode = XKeysymToKeycode (display, keysym);
  219668. const int keybyte = keycode >> 3;
  219669. const int keybit = (1 << (keycode & 7));
  219670. return (Keys::keyStates [keybyte] & keybit) != 0;
  219671. }
  219672. #if JUCE_USE_XSHM
  219673. namespace XSHMHelpers
  219674. {
  219675. static int trappedErrorCode = 0;
  219676. extern "C" int errorTrapHandler (Display*, XErrorEvent* err)
  219677. {
  219678. trappedErrorCode = err->error_code;
  219679. return 0;
  219680. }
  219681. static bool isShmAvailable() throw()
  219682. {
  219683. static bool isChecked = false;
  219684. static bool isAvailable = false;
  219685. if (! isChecked)
  219686. {
  219687. isChecked = true;
  219688. int major, minor;
  219689. Bool pixmaps;
  219690. ScopedXLock xlock;
  219691. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  219692. {
  219693. trappedErrorCode = 0;
  219694. XErrorHandler oldHandler = XSetErrorHandler (errorTrapHandler);
  219695. XShmSegmentInfo segmentInfo;
  219696. zerostruct (segmentInfo);
  219697. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  219698. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  219699. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  219700. xImage->bytes_per_line * xImage->height,
  219701. IPC_CREAT | 0777)) >= 0)
  219702. {
  219703. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  219704. if (segmentInfo.shmaddr != (void*) -1)
  219705. {
  219706. segmentInfo.readOnly = False;
  219707. xImage->data = segmentInfo.shmaddr;
  219708. XSync (display, False);
  219709. if (XShmAttach (display, &segmentInfo) != 0)
  219710. {
  219711. XSync (display, False);
  219712. XShmDetach (display, &segmentInfo);
  219713. isAvailable = true;
  219714. }
  219715. }
  219716. XFlush (display);
  219717. XDestroyImage (xImage);
  219718. shmdt (segmentInfo.shmaddr);
  219719. }
  219720. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219721. XSetErrorHandler (oldHandler);
  219722. if (trappedErrorCode != 0)
  219723. isAvailable = false;
  219724. }
  219725. }
  219726. return isAvailable;
  219727. }
  219728. }
  219729. #endif
  219730. #if JUCE_USE_XRENDER
  219731. namespace XRender
  219732. {
  219733. typedef Status (*tXRenderQueryVersion) (Display*, int*, int*);
  219734. typedef XRenderPictFormat* (*tXrenderFindStandardFormat) (Display*, int);
  219735. typedef XRenderPictFormat* (*tXRenderFindFormat) (Display*, unsigned long, XRenderPictFormat*, int);
  219736. typedef XRenderPictFormat* (*tXRenderFindVisualFormat) (Display*, Visual*);
  219737. static tXRenderQueryVersion xRenderQueryVersion = 0;
  219738. static tXrenderFindStandardFormat xRenderFindStandardFormat = 0;
  219739. static tXRenderFindFormat xRenderFindFormat = 0;
  219740. static tXRenderFindVisualFormat xRenderFindVisualFormat = 0;
  219741. static bool isAvailable()
  219742. {
  219743. static bool hasLoaded = false;
  219744. if (! hasLoaded)
  219745. {
  219746. ScopedXLock xlock;
  219747. hasLoaded = true;
  219748. void* h = dlopen ("libXrender.so", RTLD_GLOBAL | RTLD_NOW);
  219749. if (h != 0)
  219750. {
  219751. xRenderQueryVersion = (tXRenderQueryVersion) dlsym (h, "XRenderQueryVersion");
  219752. xRenderFindStandardFormat = (tXrenderFindStandardFormat) dlsym (h, "XrenderFindStandardFormat");
  219753. xRenderFindFormat = (tXRenderFindFormat) dlsym (h, "XRenderFindFormat");
  219754. xRenderFindVisualFormat = (tXRenderFindVisualFormat) dlsym (h, "XRenderFindVisualFormat");
  219755. }
  219756. if (xRenderQueryVersion != 0
  219757. && xRenderFindStandardFormat != 0
  219758. && xRenderFindFormat != 0
  219759. && xRenderFindVisualFormat != 0)
  219760. {
  219761. int major, minor;
  219762. if (xRenderQueryVersion (display, &major, &minor))
  219763. return true;
  219764. }
  219765. xRenderQueryVersion = 0;
  219766. }
  219767. return xRenderQueryVersion != 0;
  219768. }
  219769. static XRenderPictFormat* findPictureFormat()
  219770. {
  219771. ScopedXLock xlock;
  219772. XRenderPictFormat* pictFormat = 0;
  219773. if (isAvailable())
  219774. {
  219775. pictFormat = xRenderFindStandardFormat (display, PictStandardARGB32);
  219776. if (pictFormat == 0)
  219777. {
  219778. XRenderPictFormat desiredFormat;
  219779. desiredFormat.type = PictTypeDirect;
  219780. desiredFormat.depth = 32;
  219781. desiredFormat.direct.alphaMask = 0xff;
  219782. desiredFormat.direct.redMask = 0xff;
  219783. desiredFormat.direct.greenMask = 0xff;
  219784. desiredFormat.direct.blueMask = 0xff;
  219785. desiredFormat.direct.alpha = 24;
  219786. desiredFormat.direct.red = 16;
  219787. desiredFormat.direct.green = 8;
  219788. desiredFormat.direct.blue = 0;
  219789. pictFormat = xRenderFindFormat (display,
  219790. PictFormatType | PictFormatDepth
  219791. | PictFormatRedMask | PictFormatRed
  219792. | PictFormatGreenMask | PictFormatGreen
  219793. | PictFormatBlueMask | PictFormatBlue
  219794. | PictFormatAlphaMask | PictFormatAlpha,
  219795. &desiredFormat,
  219796. 0);
  219797. }
  219798. }
  219799. return pictFormat;
  219800. }
  219801. }
  219802. #endif
  219803. namespace Visuals
  219804. {
  219805. static Visual* findVisualWithDepth (const int desiredDepth) throw()
  219806. {
  219807. ScopedXLock xlock;
  219808. Visual* visual = 0;
  219809. int numVisuals = 0;
  219810. long desiredMask = VisualNoMask;
  219811. XVisualInfo desiredVisual;
  219812. desiredVisual.screen = DefaultScreen (display);
  219813. desiredVisual.depth = desiredDepth;
  219814. desiredMask = VisualScreenMask | VisualDepthMask;
  219815. if (desiredDepth == 32)
  219816. {
  219817. desiredVisual.c_class = TrueColor;
  219818. desiredVisual.red_mask = 0x00FF0000;
  219819. desiredVisual.green_mask = 0x0000FF00;
  219820. desiredVisual.blue_mask = 0x000000FF;
  219821. desiredVisual.bits_per_rgb = 8;
  219822. desiredMask |= VisualClassMask;
  219823. desiredMask |= VisualRedMaskMask;
  219824. desiredMask |= VisualGreenMaskMask;
  219825. desiredMask |= VisualBlueMaskMask;
  219826. desiredMask |= VisualBitsPerRGBMask;
  219827. }
  219828. XVisualInfo* xvinfos = XGetVisualInfo (display,
  219829. desiredMask,
  219830. &desiredVisual,
  219831. &numVisuals);
  219832. if (xvinfos != 0)
  219833. {
  219834. for (int i = 0; i < numVisuals; i++)
  219835. {
  219836. if (xvinfos[i].depth == desiredDepth)
  219837. {
  219838. visual = xvinfos[i].visual;
  219839. break;
  219840. }
  219841. }
  219842. XFree (xvinfos);
  219843. }
  219844. return visual;
  219845. }
  219846. static Visual* findVisualFormat (const int desiredDepth, int& matchedDepth) throw()
  219847. {
  219848. Visual* visual = 0;
  219849. if (desiredDepth == 32)
  219850. {
  219851. #if JUCE_USE_XSHM
  219852. if (XSHMHelpers::isShmAvailable())
  219853. {
  219854. #if JUCE_USE_XRENDER
  219855. if (XRender::isAvailable())
  219856. {
  219857. XRenderPictFormat* pictFormat = XRender::findPictureFormat();
  219858. if (pictFormat != 0)
  219859. {
  219860. int numVisuals = 0;
  219861. XVisualInfo desiredVisual;
  219862. desiredVisual.screen = DefaultScreen (display);
  219863. desiredVisual.depth = 32;
  219864. desiredVisual.bits_per_rgb = 8;
  219865. XVisualInfo* xvinfos = XGetVisualInfo (display,
  219866. VisualScreenMask | VisualDepthMask | VisualBitsPerRGBMask,
  219867. &desiredVisual, &numVisuals);
  219868. if (xvinfos != 0)
  219869. {
  219870. for (int i = 0; i < numVisuals; ++i)
  219871. {
  219872. XRenderPictFormat* pictVisualFormat = XRender::xRenderFindVisualFormat (display, xvinfos[i].visual);
  219873. if (pictVisualFormat != 0
  219874. && pictVisualFormat->type == PictTypeDirect
  219875. && pictVisualFormat->direct.alphaMask)
  219876. {
  219877. visual = xvinfos[i].visual;
  219878. matchedDepth = 32;
  219879. break;
  219880. }
  219881. }
  219882. XFree (xvinfos);
  219883. }
  219884. }
  219885. }
  219886. #endif
  219887. if (visual == 0)
  219888. {
  219889. visual = findVisualWithDepth (32);
  219890. if (visual != 0)
  219891. matchedDepth = 32;
  219892. }
  219893. }
  219894. #endif
  219895. }
  219896. if (visual == 0 && desiredDepth >= 24)
  219897. {
  219898. visual = findVisualWithDepth (24);
  219899. if (visual != 0)
  219900. matchedDepth = 24;
  219901. }
  219902. if (visual == 0 && desiredDepth >= 16)
  219903. {
  219904. visual = findVisualWithDepth (16);
  219905. if (visual != 0)
  219906. matchedDepth = 16;
  219907. }
  219908. return visual;
  219909. }
  219910. }
  219911. class XBitmapImage : public Image::SharedImage
  219912. {
  219913. public:
  219914. XBitmapImage (const Image::PixelFormat format_, const int w, const int h,
  219915. const bool clearImage, const int imageDepth_, Visual* visual)
  219916. : Image::SharedImage (format_, w, h),
  219917. imageDepth (imageDepth_),
  219918. gc (None)
  219919. {
  219920. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  219921. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  219922. lineStride = ((w * pixelStride + 3) & ~3);
  219923. ScopedXLock xlock;
  219924. #if JUCE_USE_XSHM
  219925. usingXShm = false;
  219926. if ((imageDepth > 16) && XSHMHelpers::isShmAvailable())
  219927. {
  219928. zerostruct (segmentInfo);
  219929. segmentInfo.shmid = -1;
  219930. segmentInfo.shmaddr = (char *) -1;
  219931. segmentInfo.readOnly = False;
  219932. xImage = XShmCreateImage (display, visual, imageDepth, ZPixmap, 0, &segmentInfo, w, h);
  219933. if (xImage != 0)
  219934. {
  219935. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  219936. xImage->bytes_per_line * xImage->height,
  219937. IPC_CREAT | 0777)) >= 0)
  219938. {
  219939. if (segmentInfo.shmid != -1)
  219940. {
  219941. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  219942. if (segmentInfo.shmaddr != (void*) -1)
  219943. {
  219944. segmentInfo.readOnly = False;
  219945. xImage->data = segmentInfo.shmaddr;
  219946. imageData = (uint8*) segmentInfo.shmaddr;
  219947. if (XShmAttach (display, &segmentInfo) != 0)
  219948. usingXShm = true;
  219949. else
  219950. jassertfalse;
  219951. }
  219952. else
  219953. {
  219954. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  219955. }
  219956. }
  219957. }
  219958. }
  219959. }
  219960. if (! usingXShm)
  219961. #endif
  219962. {
  219963. imageDataAllocated.malloc (lineStride * h);
  219964. imageData = imageDataAllocated;
  219965. if (format_ == Image::ARGB && clearImage)
  219966. zeromem (imageData, h * lineStride);
  219967. xImage = (XImage*) juce_calloc (sizeof (XImage));
  219968. xImage->width = w;
  219969. xImage->height = h;
  219970. xImage->xoffset = 0;
  219971. xImage->format = ZPixmap;
  219972. xImage->data = (char*) imageData;
  219973. xImage->byte_order = ImageByteOrder (display);
  219974. xImage->bitmap_unit = BitmapUnit (display);
  219975. xImage->bitmap_bit_order = BitmapBitOrder (display);
  219976. xImage->bitmap_pad = 32;
  219977. xImage->depth = pixelStride * 8;
  219978. xImage->bytes_per_line = lineStride;
  219979. xImage->bits_per_pixel = pixelStride * 8;
  219980. xImage->red_mask = 0x00FF0000;
  219981. xImage->green_mask = 0x0000FF00;
  219982. xImage->blue_mask = 0x000000FF;
  219983. if (imageDepth == 16)
  219984. {
  219985. const int pixelStride = 2;
  219986. const int lineStride = ((w * pixelStride + 3) & ~3);
  219987. imageData16Bit.malloc (lineStride * h);
  219988. xImage->data = imageData16Bit;
  219989. xImage->bitmap_pad = 16;
  219990. xImage->depth = pixelStride * 8;
  219991. xImage->bytes_per_line = lineStride;
  219992. xImage->bits_per_pixel = pixelStride * 8;
  219993. xImage->red_mask = visual->red_mask;
  219994. xImage->green_mask = visual->green_mask;
  219995. xImage->blue_mask = visual->blue_mask;
  219996. }
  219997. if (! XInitImage (xImage))
  219998. jassertfalse;
  219999. }
  220000. }
  220001. ~XBitmapImage()
  220002. {
  220003. ScopedXLock xlock;
  220004. if (gc != None)
  220005. XFreeGC (display, gc);
  220006. #if JUCE_USE_XSHM
  220007. if (usingXShm)
  220008. {
  220009. XShmDetach (display, &segmentInfo);
  220010. XFlush (display);
  220011. XDestroyImage (xImage);
  220012. shmdt (segmentInfo.shmaddr);
  220013. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  220014. }
  220015. else
  220016. #endif
  220017. {
  220018. xImage->data = 0;
  220019. XDestroyImage (xImage);
  220020. }
  220021. }
  220022. Image::ImageType getType() const { return Image::NativeImage; }
  220023. LowLevelGraphicsContext* createLowLevelContext()
  220024. {
  220025. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  220026. }
  220027. SharedImage* clone()
  220028. {
  220029. jassertfalse;
  220030. return 0;
  220031. }
  220032. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  220033. {
  220034. ScopedXLock xlock;
  220035. if (gc == None)
  220036. {
  220037. XGCValues gcvalues;
  220038. gcvalues.foreground = None;
  220039. gcvalues.background = None;
  220040. gcvalues.function = GXcopy;
  220041. gcvalues.plane_mask = AllPlanes;
  220042. gcvalues.clip_mask = None;
  220043. gcvalues.graphics_exposures = False;
  220044. gc = XCreateGC (display, window,
  220045. GCBackground | GCForeground | GCFunction | GCPlaneMask | GCClipMask | GCGraphicsExposures,
  220046. &gcvalues);
  220047. }
  220048. if (imageDepth == 16)
  220049. {
  220050. const uint32 rMask = xImage->red_mask;
  220051. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  220052. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  220053. const uint32 gMask = xImage->green_mask;
  220054. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  220055. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  220056. const uint32 bMask = xImage->blue_mask;
  220057. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  220058. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  220059. const Image::BitmapData srcData (Image (this), false);
  220060. for (int y = sy; y < sy + dh; ++y)
  220061. {
  220062. const uint8* p = srcData.getPixelPointer (sx, y);
  220063. for (int x = sx; x < sx + dw; ++x)
  220064. {
  220065. const PixelRGB* const pixel = (const PixelRGB*) p;
  220066. p += srcData.pixelStride;
  220067. XPutPixel (xImage, x, y,
  220068. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  220069. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  220070. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  220071. }
  220072. }
  220073. }
  220074. // blit results to screen.
  220075. #if JUCE_USE_XSHM
  220076. if (usingXShm)
  220077. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, True);
  220078. else
  220079. #endif
  220080. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  220081. }
  220082. juce_UseDebuggingNewOperator
  220083. private:
  220084. XImage* xImage;
  220085. const int imageDepth;
  220086. HeapBlock <uint8> imageDataAllocated;
  220087. HeapBlock <char> imageData16Bit;
  220088. GC gc;
  220089. #if JUCE_USE_XSHM
  220090. XShmSegmentInfo segmentInfo;
  220091. bool usingXShm;
  220092. #endif
  220093. static int getShiftNeeded (const uint32 mask) throw()
  220094. {
  220095. for (int i = 32; --i >= 0;)
  220096. if (((mask >> i) & 1) != 0)
  220097. return i - 7;
  220098. jassertfalse;
  220099. return 0;
  220100. }
  220101. };
  220102. class LinuxComponentPeer : public ComponentPeer
  220103. {
  220104. public:
  220105. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  220106. : ComponentPeer (component, windowStyleFlags),
  220107. windowH (0),
  220108. parentWindow (0),
  220109. wx (0),
  220110. wy (0),
  220111. ww (0),
  220112. wh (0),
  220113. fullScreen (false),
  220114. mapped (false),
  220115. visual (0),
  220116. depth (0)
  220117. {
  220118. // it's dangerous to create a window on a thread other than the message thread..
  220119. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  220120. repainter = new LinuxRepaintManager (this);
  220121. createWindow();
  220122. setTitle (component->getName());
  220123. }
  220124. ~LinuxComponentPeer()
  220125. {
  220126. // it's dangerous to delete a window on a thread other than the message thread..
  220127. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  220128. deleteIconPixmaps();
  220129. destroyWindow();
  220130. windowH = 0;
  220131. }
  220132. void* getNativeHandle() const
  220133. {
  220134. return (void*) windowH;
  220135. }
  220136. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  220137. {
  220138. XPointer peer = 0;
  220139. ScopedXLock xlock;
  220140. if (! XFindContext (display, (XID) windowHandle, windowHandleXContext, &peer))
  220141. {
  220142. if (peer != 0 && ! ComponentPeer::isValidPeer ((LinuxComponentPeer*) peer))
  220143. peer = 0;
  220144. }
  220145. return (LinuxComponentPeer*) peer;
  220146. }
  220147. void setVisible (bool shouldBeVisible)
  220148. {
  220149. ScopedXLock xlock;
  220150. if (shouldBeVisible)
  220151. XMapWindow (display, windowH);
  220152. else
  220153. XUnmapWindow (display, windowH);
  220154. }
  220155. void setTitle (const String& title)
  220156. {
  220157. setWindowTitle (windowH, title);
  220158. }
  220159. void setPosition (int x, int y)
  220160. {
  220161. setBounds (x, y, ww, wh, false);
  220162. }
  220163. void setSize (int w, int h)
  220164. {
  220165. setBounds (wx, wy, w, h, false);
  220166. }
  220167. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  220168. {
  220169. fullScreen = isNowFullScreen;
  220170. if (windowH != 0)
  220171. {
  220172. Component::SafePointer<Component> deletionChecker (component);
  220173. wx = x;
  220174. wy = y;
  220175. ww = jmax (1, w);
  220176. wh = jmax (1, h);
  220177. ScopedXLock xlock;
  220178. // Make sure the Window manager does what we want
  220179. XSizeHints* hints = XAllocSizeHints();
  220180. hints->flags = USSize | USPosition;
  220181. hints->width = ww;
  220182. hints->height = wh;
  220183. hints->x = wx;
  220184. hints->y = wy;
  220185. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  220186. {
  220187. hints->min_width = hints->max_width = hints->width;
  220188. hints->min_height = hints->max_height = hints->height;
  220189. hints->flags |= PMinSize | PMaxSize;
  220190. }
  220191. XSetWMNormalHints (display, windowH, hints);
  220192. XFree (hints);
  220193. XMoveResizeWindow (display, windowH,
  220194. wx - windowBorder.getLeft(),
  220195. wy - windowBorder.getTop(), ww, wh);
  220196. if (deletionChecker != 0)
  220197. {
  220198. updateBorderSize();
  220199. handleMovedOrResized();
  220200. }
  220201. }
  220202. }
  220203. const Rectangle<int> getBounds() const { return Rectangle<int> (wx, wy, ww, wh); }
  220204. const Point<int> getScreenPosition() const { return Point<int> (wx, wy); }
  220205. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  220206. {
  220207. return relativePosition + getScreenPosition();
  220208. }
  220209. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  220210. {
  220211. return screenPosition - getScreenPosition();
  220212. }
  220213. void setMinimised (bool shouldBeMinimised)
  220214. {
  220215. if (shouldBeMinimised)
  220216. {
  220217. Window root = RootWindow (display, DefaultScreen (display));
  220218. XClientMessageEvent clientMsg;
  220219. clientMsg.display = display;
  220220. clientMsg.window = windowH;
  220221. clientMsg.type = ClientMessage;
  220222. clientMsg.format = 32;
  220223. clientMsg.message_type = Atoms::ChangeState;
  220224. clientMsg.data.l[0] = IconicState;
  220225. ScopedXLock xlock;
  220226. XSendEvent (display, root, false, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*) &clientMsg);
  220227. }
  220228. else
  220229. {
  220230. setVisible (true);
  220231. }
  220232. }
  220233. bool isMinimised() const
  220234. {
  220235. bool minimised = false;
  220236. unsigned char* stateProp;
  220237. unsigned long nitems, bytesLeft;
  220238. Atom actualType;
  220239. int actualFormat;
  220240. ScopedXLock xlock;
  220241. if (XGetWindowProperty (display, windowH, Atoms::State, 0, 64, False,
  220242. Atoms::State, &actualType, &actualFormat, &nitems, &bytesLeft,
  220243. &stateProp) == Success
  220244. && actualType == Atoms::State
  220245. && actualFormat == 32
  220246. && nitems > 0)
  220247. {
  220248. if (((unsigned long*) stateProp)[0] == IconicState)
  220249. minimised = true;
  220250. XFree (stateProp);
  220251. }
  220252. return minimised;
  220253. }
  220254. void setFullScreen (const bool shouldBeFullScreen)
  220255. {
  220256. Rectangle<int> r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  220257. setMinimised (false);
  220258. if (fullScreen != shouldBeFullScreen)
  220259. {
  220260. if (shouldBeFullScreen)
  220261. r = Desktop::getInstance().getMainMonitorArea();
  220262. if (! r.isEmpty())
  220263. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  220264. getComponent()->repaint();
  220265. }
  220266. }
  220267. bool isFullScreen() const
  220268. {
  220269. return fullScreen;
  220270. }
  220271. bool isChildWindowOf (Window possibleParent) const
  220272. {
  220273. Window* windowList = 0;
  220274. uint32 windowListSize = 0;
  220275. Window parent, root;
  220276. ScopedXLock xlock;
  220277. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  220278. {
  220279. if (windowList != 0)
  220280. XFree (windowList);
  220281. return parent == possibleParent;
  220282. }
  220283. return false;
  220284. }
  220285. bool isFrontWindow() const
  220286. {
  220287. Window* windowList = 0;
  220288. uint32 windowListSize = 0;
  220289. bool result = false;
  220290. ScopedXLock xlock;
  220291. Window parent, root = RootWindow (display, DefaultScreen (display));
  220292. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  220293. {
  220294. for (int i = windowListSize; --i >= 0;)
  220295. {
  220296. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  220297. if (peer != 0)
  220298. {
  220299. result = (peer == this);
  220300. break;
  220301. }
  220302. }
  220303. }
  220304. if (windowList != 0)
  220305. XFree (windowList);
  220306. return result;
  220307. }
  220308. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  220309. {
  220310. int x = position.getX();
  220311. int y = position.getY();
  220312. if (((unsigned int) x) >= (unsigned int) ww
  220313. || ((unsigned int) y) >= (unsigned int) wh)
  220314. return false;
  220315. bool inFront = false;
  220316. for (int i = 0; i < Desktop::getInstance().getNumComponents(); ++i)
  220317. {
  220318. Component* const c = Desktop::getInstance().getComponent (i);
  220319. if (inFront)
  220320. {
  220321. if (c->contains (x + wx - c->getScreenX(),
  220322. y + wy - c->getScreenY()))
  220323. {
  220324. return false;
  220325. }
  220326. }
  220327. else if (c == getComponent())
  220328. {
  220329. inFront = true;
  220330. }
  220331. }
  220332. if (trueIfInAChildWindow)
  220333. return true;
  220334. ::Window root, child;
  220335. unsigned int bw, depth;
  220336. int wx, wy, w, h;
  220337. ScopedXLock xlock;
  220338. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  220339. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  220340. &bw, &depth))
  220341. {
  220342. return false;
  220343. }
  220344. if (! XTranslateCoordinates (display, windowH, windowH, x, y, &wx, &wy, &child))
  220345. return false;
  220346. return child == None;
  220347. }
  220348. const BorderSize getFrameSize() const
  220349. {
  220350. return BorderSize();
  220351. }
  220352. bool setAlwaysOnTop (bool alwaysOnTop)
  220353. {
  220354. return false;
  220355. }
  220356. void toFront (bool makeActive)
  220357. {
  220358. if (makeActive)
  220359. {
  220360. setVisible (true);
  220361. grabFocus();
  220362. }
  220363. XEvent ev;
  220364. ev.xclient.type = ClientMessage;
  220365. ev.xclient.serial = 0;
  220366. ev.xclient.send_event = True;
  220367. ev.xclient.message_type = Atoms::ActiveWin;
  220368. ev.xclient.window = windowH;
  220369. ev.xclient.format = 32;
  220370. ev.xclient.data.l[0] = 2;
  220371. ev.xclient.data.l[1] = CurrentTime;
  220372. ev.xclient.data.l[2] = 0;
  220373. ev.xclient.data.l[3] = 0;
  220374. ev.xclient.data.l[4] = 0;
  220375. {
  220376. ScopedXLock xlock;
  220377. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  220378. False, SubstructureRedirectMask | SubstructureNotifyMask, &ev);
  220379. XWindowAttributes attr;
  220380. XGetWindowAttributes (display, windowH, &attr);
  220381. if (component->isAlwaysOnTop())
  220382. XRaiseWindow (display, windowH);
  220383. XSync (display, False);
  220384. }
  220385. handleBroughtToFront();
  220386. }
  220387. void toBehind (ComponentPeer* other)
  220388. {
  220389. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  220390. jassert (otherPeer != 0); // wrong type of window?
  220391. if (otherPeer != 0)
  220392. {
  220393. setMinimised (false);
  220394. Window newStack[] = { otherPeer->windowH, windowH };
  220395. ScopedXLock xlock;
  220396. XRestackWindows (display, newStack, 2);
  220397. }
  220398. }
  220399. bool isFocused() const
  220400. {
  220401. int revert = 0;
  220402. Window focusedWindow = 0;
  220403. ScopedXLock xlock;
  220404. XGetInputFocus (display, &focusedWindow, &revert);
  220405. return focusedWindow == windowH;
  220406. }
  220407. void grabFocus()
  220408. {
  220409. XWindowAttributes atts;
  220410. ScopedXLock xlock;
  220411. if (windowH != 0
  220412. && XGetWindowAttributes (display, windowH, &atts)
  220413. && atts.map_state == IsViewable
  220414. && ! isFocused())
  220415. {
  220416. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  220417. isActiveApplication = true;
  220418. }
  220419. }
  220420. void textInputRequired (const Point<int>&)
  220421. {
  220422. }
  220423. void repaint (const Rectangle<int>& area)
  220424. {
  220425. repainter->repaint (area.getIntersection (getComponent()->getLocalBounds()));
  220426. }
  220427. void performAnyPendingRepaintsNow()
  220428. {
  220429. repainter->performAnyPendingRepaintsNow();
  220430. }
  220431. static Pixmap juce_createColourPixmapFromImage (Display* display, const Image& image)
  220432. {
  220433. ScopedXLock xlock;
  220434. const int width = image.getWidth();
  220435. const int height = image.getHeight();
  220436. HeapBlock <char> colour (width * height);
  220437. int index = 0;
  220438. for (int y = 0; y < height; ++y)
  220439. for (int x = 0; x < width; ++x)
  220440. colour[index++] = static_cast<char> (image.getPixelAt (x, y).getARGB());
  220441. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  220442. 0, colour.getData(),
  220443. width, height, 32, 0);
  220444. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  220445. width, height, 24);
  220446. GC gc = XCreateGC (display, pixmap, 0, 0);
  220447. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  220448. XFreeGC (display, gc);
  220449. return pixmap;
  220450. }
  220451. static Pixmap juce_createMaskPixmapFromImage (Display* display, const Image& image)
  220452. {
  220453. ScopedXLock xlock;
  220454. const int width = image.getWidth();
  220455. const int height = image.getHeight();
  220456. const int stride = (width + 7) >> 3;
  220457. HeapBlock <char> mask;
  220458. mask.calloc (stride * height);
  220459. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  220460. for (int y = 0; y < height; ++y)
  220461. {
  220462. for (int x = 0; x < width; ++x)
  220463. {
  220464. const char bit = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  220465. const int offset = y * stride + (x >> 3);
  220466. if (image.getPixelAt (x, y).getAlpha() >= 128)
  220467. mask[offset] |= bit;
  220468. }
  220469. }
  220470. return XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  220471. mask.getData(), width, height, 1, 0, 1);
  220472. }
  220473. void setIcon (const Image& newIcon)
  220474. {
  220475. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  220476. HeapBlock <unsigned long> data (dataSize);
  220477. int index = 0;
  220478. data[index++] = newIcon.getWidth();
  220479. data[index++] = newIcon.getHeight();
  220480. for (int y = 0; y < newIcon.getHeight(); ++y)
  220481. for (int x = 0; x < newIcon.getWidth(); ++x)
  220482. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  220483. ScopedXLock xlock;
  220484. XChangeProperty (display, windowH,
  220485. XInternAtom (display, "_NET_WM_ICON", False),
  220486. XA_CARDINAL, 32, PropModeReplace,
  220487. reinterpret_cast<unsigned char*> (data.getData()), dataSize);
  220488. deleteIconPixmaps();
  220489. XWMHints* wmHints = XGetWMHints (display, windowH);
  220490. if (wmHints == 0)
  220491. wmHints = XAllocWMHints();
  220492. wmHints->flags |= IconPixmapHint | IconMaskHint;
  220493. wmHints->icon_pixmap = juce_createColourPixmapFromImage (display, newIcon);
  220494. wmHints->icon_mask = juce_createMaskPixmapFromImage (display, newIcon);
  220495. XSetWMHints (display, windowH, wmHints);
  220496. XFree (wmHints);
  220497. XSync (display, False);
  220498. }
  220499. void deleteIconPixmaps()
  220500. {
  220501. ScopedXLock xlock;
  220502. XWMHints* wmHints = XGetWMHints (display, windowH);
  220503. if (wmHints != 0)
  220504. {
  220505. if ((wmHints->flags & IconPixmapHint) != 0)
  220506. {
  220507. wmHints->flags &= ~IconPixmapHint;
  220508. XFreePixmap (display, wmHints->icon_pixmap);
  220509. }
  220510. if ((wmHints->flags & IconMaskHint) != 0)
  220511. {
  220512. wmHints->flags &= ~IconMaskHint;
  220513. XFreePixmap (display, wmHints->icon_mask);
  220514. }
  220515. XSetWMHints (display, windowH, wmHints);
  220516. XFree (wmHints);
  220517. }
  220518. }
  220519. void handleWindowMessage (XEvent* event)
  220520. {
  220521. switch (event->xany.type)
  220522. {
  220523. case 2: // 'KeyPress'
  220524. {
  220525. ScopedXLock xlock;
  220526. XKeyEvent* const keyEvent = (XKeyEvent*) &event->xkey;
  220527. updateKeyStates (keyEvent->keycode, true);
  220528. char utf8 [64];
  220529. zeromem (utf8, sizeof (utf8));
  220530. KeySym sym;
  220531. {
  220532. const char* oldLocale = ::setlocale (LC_ALL, 0);
  220533. ::setlocale (LC_ALL, "");
  220534. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  220535. ::setlocale (LC_ALL, oldLocale);
  220536. }
  220537. const juce_wchar unicodeChar = String::fromUTF8 (utf8, sizeof (utf8) - 1) [0];
  220538. int keyCode = (int) unicodeChar;
  220539. if (keyCode < 0x20)
  220540. keyCode = XKeycodeToKeysym (display, keyEvent->keycode, currentModifiers.isShiftDown() ? 1 : 0);
  220541. const ModifierKeys oldMods (currentModifiers);
  220542. bool keyPressed = false;
  220543. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  220544. if ((sym & 0xff00) == 0xff00)
  220545. {
  220546. // Translate keypad
  220547. if (sym == XK_KP_Divide)
  220548. keyCode = XK_slash;
  220549. else if (sym == XK_KP_Multiply)
  220550. keyCode = XK_asterisk;
  220551. else if (sym == XK_KP_Subtract)
  220552. keyCode = XK_hyphen;
  220553. else if (sym == XK_KP_Add)
  220554. keyCode = XK_plus;
  220555. else if (sym == XK_KP_Enter)
  220556. keyCode = XK_Return;
  220557. else if (sym == XK_KP_Decimal)
  220558. keyCode = Keys::numLock ? XK_period : XK_Delete;
  220559. else if (sym == XK_KP_0)
  220560. keyCode = Keys::numLock ? XK_0 : XK_Insert;
  220561. else if (sym == XK_KP_1)
  220562. keyCode = Keys::numLock ? XK_1 : XK_End;
  220563. else if (sym == XK_KP_2)
  220564. keyCode = Keys::numLock ? XK_2 : XK_Down;
  220565. else if (sym == XK_KP_3)
  220566. keyCode = Keys::numLock ? XK_3 : XK_Page_Down;
  220567. else if (sym == XK_KP_4)
  220568. keyCode = Keys::numLock ? XK_4 : XK_Left;
  220569. else if (sym == XK_KP_5)
  220570. keyCode = XK_5;
  220571. else if (sym == XK_KP_6)
  220572. keyCode = Keys::numLock ? XK_6 : XK_Right;
  220573. else if (sym == XK_KP_7)
  220574. keyCode = Keys::numLock ? XK_7 : XK_Home;
  220575. else if (sym == XK_KP_8)
  220576. keyCode = Keys::numLock ? XK_8 : XK_Up;
  220577. else if (sym == XK_KP_9)
  220578. keyCode = Keys::numLock ? XK_9 : XK_Page_Up;
  220579. switch (sym)
  220580. {
  220581. case XK_Left:
  220582. case XK_Right:
  220583. case XK_Up:
  220584. case XK_Down:
  220585. case XK_Page_Up:
  220586. case XK_Page_Down:
  220587. case XK_End:
  220588. case XK_Home:
  220589. case XK_Delete:
  220590. case XK_Insert:
  220591. keyPressed = true;
  220592. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  220593. break;
  220594. case XK_Tab:
  220595. case XK_Return:
  220596. case XK_Escape:
  220597. case XK_BackSpace:
  220598. keyPressed = true;
  220599. keyCode &= 0xff;
  220600. break;
  220601. default:
  220602. {
  220603. if (sym >= XK_F1 && sym <= XK_F16)
  220604. {
  220605. keyPressed = true;
  220606. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  220607. }
  220608. break;
  220609. }
  220610. }
  220611. }
  220612. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  220613. keyPressed = true;
  220614. if (oldMods != currentModifiers)
  220615. handleModifierKeysChange();
  220616. if (keyDownChange)
  220617. handleKeyUpOrDown (true);
  220618. if (keyPressed)
  220619. handleKeyPress (keyCode, unicodeChar);
  220620. break;
  220621. }
  220622. case KeyRelease:
  220623. {
  220624. const XKeyEvent* const keyEvent = (const XKeyEvent*) &event->xkey;
  220625. updateKeyStates (keyEvent->keycode, false);
  220626. KeySym sym;
  220627. {
  220628. ScopedXLock xlock;
  220629. sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  220630. }
  220631. const ModifierKeys oldMods (currentModifiers);
  220632. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  220633. if (oldMods != currentModifiers)
  220634. handleModifierKeysChange();
  220635. if (keyDownChange)
  220636. handleKeyUpOrDown (false);
  220637. break;
  220638. }
  220639. case ButtonPress:
  220640. {
  220641. const XButtonPressedEvent* const buttonPressEvent = (const XButtonPressedEvent*) &event->xbutton;
  220642. updateKeyModifiers (buttonPressEvent->state);
  220643. bool buttonMsg = false;
  220644. const int map = pointerMap [buttonPressEvent->button - Button1];
  220645. if (map == Keys::WheelUp || map == Keys::WheelDown)
  220646. {
  220647. handleMouseWheel (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y),
  220648. getEventTime (buttonPressEvent->time), 0, map == Keys::WheelDown ? -84.0f : 84.0f);
  220649. }
  220650. if (map == Keys::LeftButton)
  220651. {
  220652. currentModifiers = currentModifiers.withFlags (ModifierKeys::leftButtonModifier);
  220653. buttonMsg = true;
  220654. }
  220655. else if (map == Keys::RightButton)
  220656. {
  220657. currentModifiers = currentModifiers.withFlags (ModifierKeys::rightButtonModifier);
  220658. buttonMsg = true;
  220659. }
  220660. else if (map == Keys::MiddleButton)
  220661. {
  220662. currentModifiers = currentModifiers.withFlags (ModifierKeys::middleButtonModifier);
  220663. buttonMsg = true;
  220664. }
  220665. if (buttonMsg)
  220666. {
  220667. toFront (true);
  220668. handleMouseEvent (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y), currentModifiers,
  220669. getEventTime (buttonPressEvent->time));
  220670. }
  220671. clearLastMousePos();
  220672. break;
  220673. }
  220674. case ButtonRelease:
  220675. {
  220676. const XButtonReleasedEvent* const buttonRelEvent = (const XButtonReleasedEvent*) &event->xbutton;
  220677. updateKeyModifiers (buttonRelEvent->state);
  220678. const int map = pointerMap [buttonRelEvent->button - Button1];
  220679. if (map == Keys::LeftButton)
  220680. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier);
  220681. else if (map == Keys::RightButton)
  220682. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier);
  220683. else if (map == Keys::MiddleButton)
  220684. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier);
  220685. handleMouseEvent (0, Point<int> (buttonRelEvent->x, buttonRelEvent->y), currentModifiers,
  220686. getEventTime (buttonRelEvent->time));
  220687. clearLastMousePos();
  220688. break;
  220689. }
  220690. case MotionNotify:
  220691. {
  220692. const XPointerMovedEvent* const movedEvent = (const XPointerMovedEvent*) &event->xmotion;
  220693. updateKeyModifiers (movedEvent->state);
  220694. const Point<int> mousePos (Desktop::getMousePosition());
  220695. if (lastMousePos != mousePos)
  220696. {
  220697. lastMousePos = mousePos;
  220698. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  220699. {
  220700. Window wRoot = 0, wParent = 0;
  220701. {
  220702. ScopedXLock xlock;
  220703. unsigned int numChildren;
  220704. Window* wChild = 0;
  220705. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  220706. }
  220707. if (wParent != 0
  220708. && wParent != windowH
  220709. && wParent != wRoot)
  220710. {
  220711. parentWindow = wParent;
  220712. updateBounds();
  220713. }
  220714. else
  220715. {
  220716. parentWindow = 0;
  220717. }
  220718. }
  220719. handleMouseEvent (0, mousePos - getScreenPosition(), currentModifiers, getEventTime (movedEvent->time));
  220720. }
  220721. break;
  220722. }
  220723. case EnterNotify:
  220724. {
  220725. clearLastMousePos();
  220726. const XEnterWindowEvent* const enterEvent = (const XEnterWindowEvent*) &event->xcrossing;
  220727. if (! currentModifiers.isAnyMouseButtonDown())
  220728. {
  220729. updateKeyModifiers (enterEvent->state);
  220730. handleMouseEvent (0, Point<int> (enterEvent->x, enterEvent->y), currentModifiers, getEventTime (enterEvent->time));
  220731. }
  220732. break;
  220733. }
  220734. case LeaveNotify:
  220735. {
  220736. const XLeaveWindowEvent* const leaveEvent = (const XLeaveWindowEvent*) &event->xcrossing;
  220737. // Suppress the normal leave if we've got a pointer grab, or if
  220738. // it's a bogus one caused by clicking a mouse button when running
  220739. // in a Window manager
  220740. if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent->mode == NotifyNormal)
  220741. || leaveEvent->mode == NotifyUngrab)
  220742. {
  220743. updateKeyModifiers (leaveEvent->state);
  220744. handleMouseEvent (0, Point<int> (leaveEvent->x, leaveEvent->y), currentModifiers, getEventTime (leaveEvent->time));
  220745. }
  220746. break;
  220747. }
  220748. case FocusIn:
  220749. {
  220750. isActiveApplication = true;
  220751. if (isFocused())
  220752. handleFocusGain();
  220753. break;
  220754. }
  220755. case FocusOut:
  220756. {
  220757. isActiveApplication = false;
  220758. if (! isFocused())
  220759. handleFocusLoss();
  220760. break;
  220761. }
  220762. case Expose:
  220763. {
  220764. // Batch together all pending expose events
  220765. XExposeEvent* exposeEvent = (XExposeEvent*) &event->xexpose;
  220766. XEvent nextEvent;
  220767. ScopedXLock xlock;
  220768. if (exposeEvent->window != windowH)
  220769. {
  220770. Window child;
  220771. XTranslateCoordinates (display, exposeEvent->window, windowH,
  220772. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  220773. &child);
  220774. }
  220775. repaint (Rectangle<int> (exposeEvent->x, exposeEvent->y,
  220776. exposeEvent->width, exposeEvent->height));
  220777. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  220778. {
  220779. XPeekEvent (display, (XEvent*) &nextEvent);
  220780. if (nextEvent.type != Expose || nextEvent.xany.window != event->xany.window)
  220781. break;
  220782. XNextEvent (display, (XEvent*) &nextEvent);
  220783. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  220784. repaint (Rectangle<int> (nextExposeEvent->x, nextExposeEvent->y,
  220785. nextExposeEvent->width, nextExposeEvent->height));
  220786. }
  220787. break;
  220788. }
  220789. case CirculateNotify:
  220790. case CreateNotify:
  220791. case DestroyNotify:
  220792. // Think we can ignore these
  220793. break;
  220794. case ConfigureNotify:
  220795. {
  220796. updateBounds();
  220797. updateBorderSize();
  220798. handleMovedOrResized();
  220799. // if the native title bar is dragged, need to tell any active menus, etc.
  220800. if ((styleFlags & windowHasTitleBar) != 0
  220801. && component->isCurrentlyBlockedByAnotherModalComponent())
  220802. {
  220803. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  220804. if (currentModalComp != 0)
  220805. currentModalComp->inputAttemptWhenModal();
  220806. }
  220807. XConfigureEvent* const confEvent = (XConfigureEvent*) &event->xconfigure;
  220808. if (confEvent->window == windowH
  220809. && confEvent->above != 0
  220810. && isFrontWindow())
  220811. {
  220812. handleBroughtToFront();
  220813. }
  220814. break;
  220815. }
  220816. case ReparentNotify:
  220817. {
  220818. parentWindow = 0;
  220819. Window wRoot = 0;
  220820. Window* wChild = 0;
  220821. unsigned int numChildren;
  220822. {
  220823. ScopedXLock xlock;
  220824. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  220825. }
  220826. if (parentWindow == windowH || parentWindow == wRoot)
  220827. parentWindow = 0;
  220828. updateBounds();
  220829. updateBorderSize();
  220830. handleMovedOrResized();
  220831. break;
  220832. }
  220833. case GravityNotify:
  220834. {
  220835. updateBounds();
  220836. updateBorderSize();
  220837. handleMovedOrResized();
  220838. break;
  220839. }
  220840. case MapNotify:
  220841. mapped = true;
  220842. handleBroughtToFront();
  220843. break;
  220844. case UnmapNotify:
  220845. mapped = false;
  220846. break;
  220847. case MappingNotify:
  220848. {
  220849. XMappingEvent* mappingEvent = (XMappingEvent*) &event->xmapping;
  220850. if (mappingEvent->request != MappingPointer)
  220851. {
  220852. // Deal with modifier/keyboard mapping
  220853. ScopedXLock xlock;
  220854. XRefreshKeyboardMapping (mappingEvent);
  220855. updateModifierMappings();
  220856. }
  220857. break;
  220858. }
  220859. case ClientMessage:
  220860. {
  220861. const XClientMessageEvent* const clientMsg = (const XClientMessageEvent*) &event->xclient;
  220862. if (clientMsg->message_type == Atoms::Protocols && clientMsg->format == 32)
  220863. {
  220864. const Atom atom = (Atom) clientMsg->data.l[0];
  220865. if (atom == Atoms::ProtocolList [Atoms::PING])
  220866. {
  220867. Window root = RootWindow (display, DefaultScreen (display));
  220868. event->xclient.window = root;
  220869. XSendEvent (display, root, False, NoEventMask, event);
  220870. XFlush (display);
  220871. }
  220872. else if (atom == Atoms::ProtocolList [Atoms::TAKE_FOCUS])
  220873. {
  220874. XWindowAttributes atts;
  220875. ScopedXLock xlock;
  220876. if (clientMsg->window != 0
  220877. && XGetWindowAttributes (display, clientMsg->window, &atts))
  220878. {
  220879. if (atts.map_state == IsViewable)
  220880. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  220881. }
  220882. }
  220883. else if (atom == Atoms::ProtocolList [Atoms::DELETE_WINDOW])
  220884. {
  220885. handleUserClosingWindow();
  220886. }
  220887. }
  220888. else if (clientMsg->message_type == Atoms::XdndEnter)
  220889. {
  220890. handleDragAndDropEnter (clientMsg);
  220891. }
  220892. else if (clientMsg->message_type == Atoms::XdndLeave)
  220893. {
  220894. resetDragAndDrop();
  220895. }
  220896. else if (clientMsg->message_type == Atoms::XdndPosition)
  220897. {
  220898. handleDragAndDropPosition (clientMsg);
  220899. }
  220900. else if (clientMsg->message_type == Atoms::XdndDrop)
  220901. {
  220902. handleDragAndDropDrop (clientMsg);
  220903. }
  220904. else if (clientMsg->message_type == Atoms::XdndStatus)
  220905. {
  220906. handleDragAndDropStatus (clientMsg);
  220907. }
  220908. else if (clientMsg->message_type == Atoms::XdndFinished)
  220909. {
  220910. resetDragAndDrop();
  220911. }
  220912. break;
  220913. }
  220914. case SelectionNotify:
  220915. handleDragAndDropSelection (event);
  220916. break;
  220917. case SelectionClear:
  220918. case SelectionRequest:
  220919. break;
  220920. default:
  220921. #if JUCE_USE_XSHM
  220922. {
  220923. ScopedXLock xlock;
  220924. if (event->xany.type == XShmGetEventBase (display))
  220925. repainter->notifyPaintCompleted();
  220926. }
  220927. #endif
  220928. break;
  220929. }
  220930. }
  220931. void showMouseCursor (Cursor cursor) throw()
  220932. {
  220933. ScopedXLock xlock;
  220934. XDefineCursor (display, windowH, cursor);
  220935. }
  220936. void setTaskBarIcon (const Image& image)
  220937. {
  220938. ScopedXLock xlock;
  220939. taskbarImage = image;
  220940. Screen* const screen = XDefaultScreenOfDisplay (display);
  220941. const int screenNumber = XScreenNumberOfScreen (screen);
  220942. String screenAtom ("_NET_SYSTEM_TRAY_S");
  220943. screenAtom << screenNumber;
  220944. Atom selectionAtom = XInternAtom (display, screenAtom.toUTF8(), false);
  220945. XGrabServer (display);
  220946. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  220947. if (managerWin != None)
  220948. XSelectInput (display, managerWin, StructureNotifyMask);
  220949. XUngrabServer (display);
  220950. XFlush (display);
  220951. if (managerWin != None)
  220952. {
  220953. XEvent ev;
  220954. zerostruct (ev);
  220955. ev.xclient.type = ClientMessage;
  220956. ev.xclient.window = managerWin;
  220957. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  220958. ev.xclient.format = 32;
  220959. ev.xclient.data.l[0] = CurrentTime;
  220960. ev.xclient.data.l[1] = 0 /*SYSTEM_TRAY_REQUEST_DOCK*/;
  220961. ev.xclient.data.l[2] = windowH;
  220962. ev.xclient.data.l[3] = 0;
  220963. ev.xclient.data.l[4] = 0;
  220964. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  220965. XSync (display, False);
  220966. }
  220967. // For older KDE's ...
  220968. long atomData = 1;
  220969. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  220970. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  220971. // For more recent KDE's...
  220972. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  220973. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  220974. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  220975. XSizeHints* hints = XAllocSizeHints();
  220976. hints->flags = PMinSize;
  220977. hints->min_width = 22;
  220978. hints->min_height = 22;
  220979. XSetWMNormalHints (display, windowH, hints);
  220980. XFree (hints);
  220981. }
  220982. const Image& getTaskbarIcon() const throw() { return taskbarImage; }
  220983. juce_UseDebuggingNewOperator
  220984. bool dontRepaint;
  220985. static ModifierKeys currentModifiers;
  220986. static bool isActiveApplication;
  220987. private:
  220988. class LinuxRepaintManager : public Timer
  220989. {
  220990. public:
  220991. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  220992. : peer (peer_),
  220993. lastTimeImageUsed (0)
  220994. {
  220995. #if JUCE_USE_XSHM
  220996. shmCompletedDrawing = true;
  220997. useARGBImagesForRendering = XSHMHelpers::isShmAvailable();
  220998. if (useARGBImagesForRendering)
  220999. {
  221000. ScopedXLock xlock;
  221001. XShmSegmentInfo segmentinfo;
  221002. XImage* const testImage
  221003. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  221004. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  221005. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  221006. XDestroyImage (testImage);
  221007. }
  221008. #endif
  221009. }
  221010. ~LinuxRepaintManager()
  221011. {
  221012. }
  221013. void timerCallback()
  221014. {
  221015. #if JUCE_USE_XSHM
  221016. if (! shmCompletedDrawing)
  221017. return;
  221018. #endif
  221019. if (! regionsNeedingRepaint.isEmpty())
  221020. {
  221021. stopTimer();
  221022. performAnyPendingRepaintsNow();
  221023. }
  221024. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  221025. {
  221026. stopTimer();
  221027. image = Image::null;
  221028. }
  221029. }
  221030. void repaint (const Rectangle<int>& area)
  221031. {
  221032. if (! isTimerRunning())
  221033. startTimer (repaintTimerPeriod);
  221034. regionsNeedingRepaint.add (area);
  221035. }
  221036. void performAnyPendingRepaintsNow()
  221037. {
  221038. #if JUCE_USE_XSHM
  221039. if (! shmCompletedDrawing)
  221040. {
  221041. startTimer (repaintTimerPeriod);
  221042. return;
  221043. }
  221044. #endif
  221045. peer->clearMaskedRegion();
  221046. RectangleList originalRepaintRegion (regionsNeedingRepaint);
  221047. regionsNeedingRepaint.clear();
  221048. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  221049. if (! totalArea.isEmpty())
  221050. {
  221051. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  221052. || image.getHeight() < totalArea.getHeight())
  221053. {
  221054. #if JUCE_USE_XSHM
  221055. image = Image (new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  221056. : Image::RGB,
  221057. #else
  221058. image = Image (new XBitmapImage (Image::RGB,
  221059. #endif
  221060. (totalArea.getWidth() + 31) & ~31,
  221061. (totalArea.getHeight() + 31) & ~31,
  221062. false, peer->depth, peer->visual));
  221063. }
  221064. startTimer (repaintTimerPeriod);
  221065. RectangleList adjustedList (originalRepaintRegion);
  221066. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  221067. LowLevelGraphicsSoftwareRenderer context (image, -totalArea.getX(), -totalArea.getY(), adjustedList);
  221068. if (peer->depth == 32)
  221069. {
  221070. RectangleList::Iterator i (originalRepaintRegion);
  221071. while (i.next())
  221072. image.clear (*i.getRectangle() - totalArea.getPosition());
  221073. }
  221074. peer->handlePaint (context);
  221075. if (! peer->maskedRegion.isEmpty())
  221076. originalRepaintRegion.subtract (peer->maskedRegion);
  221077. for (RectangleList::Iterator i (originalRepaintRegion); i.next();)
  221078. {
  221079. #if JUCE_USE_XSHM
  221080. shmCompletedDrawing = false;
  221081. #endif
  221082. const Rectangle<int>& r = *i.getRectangle();
  221083. static_cast<XBitmapImage*> (image.getSharedImage())
  221084. ->blitToWindow (peer->windowH,
  221085. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  221086. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  221087. }
  221088. }
  221089. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  221090. startTimer (repaintTimerPeriod);
  221091. }
  221092. #if JUCE_USE_XSHM
  221093. void notifyPaintCompleted() { shmCompletedDrawing = true; }
  221094. #endif
  221095. private:
  221096. enum { repaintTimerPeriod = 1000 / 100 };
  221097. LinuxComponentPeer* const peer;
  221098. Image image;
  221099. uint32 lastTimeImageUsed;
  221100. RectangleList regionsNeedingRepaint;
  221101. #if JUCE_USE_XSHM
  221102. bool useARGBImagesForRendering, shmCompletedDrawing;
  221103. #endif
  221104. LinuxRepaintManager (const LinuxRepaintManager&);
  221105. LinuxRepaintManager& operator= (const LinuxRepaintManager&);
  221106. };
  221107. ScopedPointer <LinuxRepaintManager> repainter;
  221108. friend class LinuxRepaintManager;
  221109. Window windowH, parentWindow;
  221110. int wx, wy, ww, wh;
  221111. Image taskbarImage;
  221112. bool fullScreen, mapped;
  221113. Visual* visual;
  221114. int depth;
  221115. BorderSize windowBorder;
  221116. struct MotifWmHints
  221117. {
  221118. unsigned long flags;
  221119. unsigned long functions;
  221120. unsigned long decorations;
  221121. long input_mode;
  221122. unsigned long status;
  221123. };
  221124. static void updateKeyStates (const int keycode, const bool press) throw()
  221125. {
  221126. const int keybyte = keycode >> 3;
  221127. const int keybit = (1 << (keycode & 7));
  221128. if (press)
  221129. Keys::keyStates [keybyte] |= keybit;
  221130. else
  221131. Keys::keyStates [keybyte] &= ~keybit;
  221132. }
  221133. static void updateKeyModifiers (const int status) throw()
  221134. {
  221135. int keyMods = 0;
  221136. if (status & ShiftMask) keyMods |= ModifierKeys::shiftModifier;
  221137. if (status & ControlMask) keyMods |= ModifierKeys::ctrlModifier;
  221138. if (status & Keys::AltMask) keyMods |= ModifierKeys::altModifier;
  221139. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  221140. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  221141. Keys::capsLock = ((status & LockMask) != 0);
  221142. }
  221143. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  221144. {
  221145. int modifier = 0;
  221146. bool isModifier = true;
  221147. switch (sym)
  221148. {
  221149. case XK_Shift_L:
  221150. case XK_Shift_R:
  221151. modifier = ModifierKeys::shiftModifier;
  221152. break;
  221153. case XK_Control_L:
  221154. case XK_Control_R:
  221155. modifier = ModifierKeys::ctrlModifier;
  221156. break;
  221157. case XK_Alt_L:
  221158. case XK_Alt_R:
  221159. modifier = ModifierKeys::altModifier;
  221160. break;
  221161. case XK_Num_Lock:
  221162. if (press)
  221163. Keys::numLock = ! Keys::numLock;
  221164. break;
  221165. case XK_Caps_Lock:
  221166. if (press)
  221167. Keys::capsLock = ! Keys::capsLock;
  221168. break;
  221169. case XK_Scroll_Lock:
  221170. break;
  221171. default:
  221172. isModifier = false;
  221173. break;
  221174. }
  221175. if (modifier != 0)
  221176. {
  221177. if (press)
  221178. currentModifiers = currentModifiers.withFlags (modifier);
  221179. else
  221180. currentModifiers = currentModifiers.withoutFlags (modifier);
  221181. }
  221182. return isModifier;
  221183. }
  221184. // Alt and Num lock are not defined by standard X
  221185. // modifier constants: check what they're mapped to
  221186. static void updateModifierMappings() throw()
  221187. {
  221188. ScopedXLock xlock;
  221189. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  221190. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  221191. Keys::AltMask = 0;
  221192. Keys::NumLockMask = 0;
  221193. XModifierKeymap* mapping = XGetModifierMapping (display);
  221194. if (mapping)
  221195. {
  221196. for (int i = 0; i < 8; i++)
  221197. {
  221198. if (mapping->modifiermap [i << 1] == altLeftCode)
  221199. Keys::AltMask = 1 << i;
  221200. else if (mapping->modifiermap [i << 1] == numLockCode)
  221201. Keys::NumLockMask = 1 << i;
  221202. }
  221203. XFreeModifiermap (mapping);
  221204. }
  221205. }
  221206. void removeWindowDecorations (Window wndH)
  221207. {
  221208. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  221209. if (hints != None)
  221210. {
  221211. MotifWmHints motifHints;
  221212. zerostruct (motifHints);
  221213. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  221214. motifHints.decorations = 0;
  221215. ScopedXLock xlock;
  221216. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  221217. (unsigned char*) &motifHints, 4);
  221218. }
  221219. hints = XInternAtom (display, "_WIN_HINTS", True);
  221220. if (hints != None)
  221221. {
  221222. long gnomeHints = 0;
  221223. ScopedXLock xlock;
  221224. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  221225. (unsigned char*) &gnomeHints, 1);
  221226. }
  221227. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  221228. if (hints != None)
  221229. {
  221230. long kwmHints = 2; /*KDE_tinyDecoration*/
  221231. ScopedXLock xlock;
  221232. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  221233. (unsigned char*) &kwmHints, 1);
  221234. }
  221235. }
  221236. void addWindowButtons (Window wndH)
  221237. {
  221238. ScopedXLock xlock;
  221239. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  221240. if (hints != None)
  221241. {
  221242. MotifWmHints motifHints;
  221243. zerostruct (motifHints);
  221244. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  221245. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  221246. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  221247. if ((styleFlags & windowHasCloseButton) != 0)
  221248. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  221249. if ((styleFlags & windowHasMinimiseButton) != 0)
  221250. {
  221251. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  221252. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  221253. }
  221254. if ((styleFlags & windowHasMaximiseButton) != 0)
  221255. {
  221256. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  221257. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  221258. }
  221259. if ((styleFlags & windowIsResizable) != 0)
  221260. {
  221261. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  221262. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  221263. }
  221264. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  221265. }
  221266. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  221267. if (hints != None)
  221268. {
  221269. int netHints [6];
  221270. int num = 0;
  221271. if ((styleFlags & windowIsResizable) != 0)
  221272. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", True);
  221273. if ((styleFlags & windowHasMaximiseButton) != 0)
  221274. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", True);
  221275. if ((styleFlags & windowHasMinimiseButton) != 0)
  221276. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", True);
  221277. if ((styleFlags & windowHasCloseButton) != 0)
  221278. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", True);
  221279. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace, (unsigned char*) &netHints, num);
  221280. }
  221281. }
  221282. void setWindowType()
  221283. {
  221284. int netHints [2];
  221285. int numHints = 0;
  221286. if ((styleFlags & windowIsTemporary) != 0
  221287. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  221288. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_COMBO", True);
  221289. else
  221290. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  221291. netHints[numHints++] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  221292. XChangeProperty (display, windowH, Atoms::WindowType, XA_ATOM, 32, PropModeReplace,
  221293. (unsigned char*) &netHints, numHints);
  221294. numHints = 0;
  221295. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  221296. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_SKIP_TASKBAR", True);
  221297. if (component->isAlwaysOnTop())
  221298. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_ABOVE", True);
  221299. if (numHints > 0)
  221300. XChangeProperty (display, windowH, Atoms::WindowState, XA_ATOM, 32, PropModeReplace,
  221301. (unsigned char*) &netHints, numHints);
  221302. }
  221303. void createWindow()
  221304. {
  221305. ScopedXLock xlock;
  221306. Atoms::initialiseAtoms();
  221307. resetDragAndDrop();
  221308. // Get defaults for various properties
  221309. const int screen = DefaultScreen (display);
  221310. Window root = RootWindow (display, screen);
  221311. // Try to obtain a 32-bit visual or fallback to 24 or 16
  221312. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  221313. if (visual == 0)
  221314. {
  221315. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  221316. Process::terminate();
  221317. }
  221318. // Create and install a colormap suitable fr our visual
  221319. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  221320. XInstallColormap (display, colormap);
  221321. // Set up the window attributes
  221322. XSetWindowAttributes swa;
  221323. swa.border_pixel = 0;
  221324. swa.background_pixmap = None;
  221325. swa.colormap = colormap;
  221326. swa.event_mask = getAllEventsMask();
  221327. windowH = XCreateWindow (display, root,
  221328. 0, 0, 1, 1,
  221329. 0, depth, InputOutput, visual,
  221330. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask,
  221331. &swa);
  221332. XGrabButton (display, AnyButton, AnyModifier, windowH, False,
  221333. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  221334. GrabModeAsync, GrabModeAsync, None, None);
  221335. // Set the window context to identify the window handle object
  221336. if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
  221337. {
  221338. // Failed
  221339. jassertfalse;
  221340. Logger::outputDebugString ("Failed to create context information for window.\n");
  221341. XDestroyWindow (display, windowH);
  221342. windowH = 0;
  221343. return;
  221344. }
  221345. // Set window manager hints
  221346. XWMHints* wmHints = XAllocWMHints();
  221347. wmHints->flags = InputHint | StateHint;
  221348. wmHints->input = True; // Locally active input model
  221349. wmHints->initial_state = NormalState;
  221350. XSetWMHints (display, windowH, wmHints);
  221351. XFree (wmHints);
  221352. // Set the window type
  221353. setWindowType();
  221354. // Define decoration
  221355. if ((styleFlags & windowHasTitleBar) == 0)
  221356. removeWindowDecorations (windowH);
  221357. else
  221358. addWindowButtons (windowH);
  221359. // Set window name
  221360. setWindowTitle (windowH, getComponent()->getName());
  221361. // Associate the PID, allowing to be shut down when something goes wrong
  221362. unsigned long pid = getpid();
  221363. XChangeProperty (display, windowH, Atoms::Pid, XA_CARDINAL, 32, PropModeReplace,
  221364. (unsigned char*) &pid, 1);
  221365. // Set window manager protocols
  221366. XChangeProperty (display, windowH, Atoms::Protocols, XA_ATOM, 32, PropModeReplace,
  221367. (unsigned char*) Atoms::ProtocolList, 2);
  221368. // Set drag and drop flags
  221369. XChangeProperty (display, windowH, Atoms::XdndTypeList, XA_ATOM, 32, PropModeReplace,
  221370. (const unsigned char*) Atoms::allowedMimeTypes, numElementsInArray (Atoms::allowedMimeTypes));
  221371. XChangeProperty (display, windowH, Atoms::XdndActionList, XA_ATOM, 32, PropModeReplace,
  221372. (const unsigned char*) Atoms::allowedActions, numElementsInArray (Atoms::allowedActions));
  221373. XChangeProperty (display, windowH, Atoms::XdndActionDescription, XA_STRING, 8, PropModeReplace,
  221374. (const unsigned char*) "", 0);
  221375. unsigned long dndVersion = Atoms::DndVersion;
  221376. XChangeProperty (display, windowH, Atoms::XdndAware, XA_ATOM, 32, PropModeReplace,
  221377. (const unsigned char*) &dndVersion, 1);
  221378. // Initialise the pointer and keyboard mapping
  221379. // This is not the same as the logical pointer mapping the X server uses:
  221380. // we don't mess with this.
  221381. static bool mappingInitialised = false;
  221382. if (! mappingInitialised)
  221383. {
  221384. mappingInitialised = true;
  221385. const int numButtons = XGetPointerMapping (display, 0, 0);
  221386. if (numButtons == 2)
  221387. {
  221388. pointerMap[0] = Keys::LeftButton;
  221389. pointerMap[1] = Keys::RightButton;
  221390. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  221391. }
  221392. else if (numButtons >= 3)
  221393. {
  221394. pointerMap[0] = Keys::LeftButton;
  221395. pointerMap[1] = Keys::MiddleButton;
  221396. pointerMap[2] = Keys::RightButton;
  221397. if (numButtons >= 5)
  221398. {
  221399. pointerMap[3] = Keys::WheelUp;
  221400. pointerMap[4] = Keys::WheelDown;
  221401. }
  221402. }
  221403. updateModifierMappings();
  221404. }
  221405. }
  221406. void destroyWindow()
  221407. {
  221408. ScopedXLock xlock;
  221409. XPointer handlePointer;
  221410. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  221411. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  221412. XDestroyWindow (display, windowH);
  221413. // Wait for it to complete and then remove any events for this
  221414. // window from the event queue.
  221415. XSync (display, false);
  221416. XEvent event;
  221417. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  221418. {}
  221419. }
  221420. static int getAllEventsMask() throw()
  221421. {
  221422. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  221423. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  221424. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  221425. }
  221426. static int64 getEventTime (::Time t)
  221427. {
  221428. static int64 eventTimeOffset = 0x12345678;
  221429. const int64 thisMessageTime = t;
  221430. if (eventTimeOffset == 0x12345678)
  221431. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  221432. return eventTimeOffset + thisMessageTime;
  221433. }
  221434. static void setWindowTitle (Window xwin, const String& title)
  221435. {
  221436. XTextProperty nameProperty;
  221437. char* strings[] = { const_cast <char*> (title.toUTF8()) };
  221438. ScopedXLock xlock;
  221439. if (XStringListToTextProperty (strings, 1, &nameProperty))
  221440. {
  221441. XSetWMName (display, xwin, &nameProperty);
  221442. XSetWMIconName (display, xwin, &nameProperty);
  221443. XFree (nameProperty.value);
  221444. }
  221445. }
  221446. void updateBorderSize()
  221447. {
  221448. if ((styleFlags & windowHasTitleBar) == 0)
  221449. {
  221450. windowBorder = BorderSize (0);
  221451. }
  221452. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  221453. {
  221454. ScopedXLock xlock;
  221455. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  221456. if (hints != None)
  221457. {
  221458. unsigned char* data = 0;
  221459. unsigned long nitems, bytesLeft;
  221460. Atom actualType;
  221461. int actualFormat;
  221462. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  221463. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  221464. &data) == Success)
  221465. {
  221466. const unsigned long* const sizes = (const unsigned long*) data;
  221467. if (actualFormat == 32)
  221468. windowBorder = BorderSize ((int) sizes[2], (int) sizes[0],
  221469. (int) sizes[3], (int) sizes[1]);
  221470. XFree (data);
  221471. }
  221472. }
  221473. }
  221474. }
  221475. void updateBounds()
  221476. {
  221477. jassert (windowH != 0);
  221478. if (windowH != 0)
  221479. {
  221480. Window root, child;
  221481. unsigned int bw, depth;
  221482. ScopedXLock xlock;
  221483. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  221484. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  221485. &bw, &depth))
  221486. {
  221487. wx = wy = ww = wh = 0;
  221488. }
  221489. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  221490. {
  221491. wx = wy = 0;
  221492. }
  221493. }
  221494. }
  221495. void resetDragAndDrop()
  221496. {
  221497. dragAndDropFiles.clear();
  221498. lastDropPos = Point<int> (-1, -1);
  221499. dragAndDropCurrentMimeType = 0;
  221500. dragAndDropSourceWindow = 0;
  221501. srcMimeTypeAtomList.clear();
  221502. }
  221503. void sendDragAndDropMessage (XClientMessageEvent& msg)
  221504. {
  221505. msg.type = ClientMessage;
  221506. msg.display = display;
  221507. msg.window = dragAndDropSourceWindow;
  221508. msg.format = 32;
  221509. msg.data.l[0] = windowH;
  221510. ScopedXLock xlock;
  221511. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  221512. }
  221513. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  221514. {
  221515. XClientMessageEvent msg;
  221516. zerostruct (msg);
  221517. msg.message_type = Atoms::XdndStatus;
  221518. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  221519. msg.data.l[4] = dropAction;
  221520. sendDragAndDropMessage (msg);
  221521. }
  221522. void sendDragAndDropLeave()
  221523. {
  221524. XClientMessageEvent msg;
  221525. zerostruct (msg);
  221526. msg.message_type = Atoms::XdndLeave;
  221527. sendDragAndDropMessage (msg);
  221528. }
  221529. void sendDragAndDropFinish()
  221530. {
  221531. XClientMessageEvent msg;
  221532. zerostruct (msg);
  221533. msg.message_type = Atoms::XdndFinished;
  221534. sendDragAndDropMessage (msg);
  221535. }
  221536. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  221537. {
  221538. if ((clientMsg->data.l[1] & 1) == 0)
  221539. {
  221540. sendDragAndDropLeave();
  221541. if (dragAndDropFiles.size() > 0)
  221542. handleFileDragExit (dragAndDropFiles);
  221543. dragAndDropFiles.clear();
  221544. }
  221545. }
  221546. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  221547. {
  221548. if (dragAndDropSourceWindow == 0)
  221549. return;
  221550. dragAndDropSourceWindow = clientMsg->data.l[0];
  221551. Point<int> dropPos ((int) clientMsg->data.l[2] >> 16,
  221552. (int) clientMsg->data.l[2] & 0xffff);
  221553. dropPos -= getScreenPosition();
  221554. if (lastDropPos != dropPos)
  221555. {
  221556. lastDropPos = dropPos;
  221557. dragAndDropTimestamp = clientMsg->data.l[3];
  221558. Atom targetAction = Atoms::XdndActionCopy;
  221559. for (int i = numElementsInArray (Atoms::allowedActions); --i >= 0;)
  221560. {
  221561. if ((Atom) clientMsg->data.l[4] == Atoms::allowedActions[i])
  221562. {
  221563. targetAction = Atoms::allowedActions[i];
  221564. break;
  221565. }
  221566. }
  221567. sendDragAndDropStatus (true, targetAction);
  221568. if (dragAndDropFiles.size() == 0)
  221569. updateDraggedFileList (clientMsg);
  221570. if (dragAndDropFiles.size() > 0)
  221571. handleFileDragMove (dragAndDropFiles, dropPos);
  221572. }
  221573. }
  221574. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  221575. {
  221576. if (dragAndDropFiles.size() == 0)
  221577. updateDraggedFileList (clientMsg);
  221578. const StringArray files (dragAndDropFiles);
  221579. const Point<int> lastPos (lastDropPos);
  221580. sendDragAndDropFinish();
  221581. resetDragAndDrop();
  221582. if (files.size() > 0)
  221583. handleFileDragDrop (files, lastPos);
  221584. }
  221585. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  221586. {
  221587. dragAndDropFiles.clear();
  221588. srcMimeTypeAtomList.clear();
  221589. dragAndDropCurrentMimeType = 0;
  221590. const unsigned long dndCurrentVersion = static_cast <unsigned long> (clientMsg->data.l[1] & 0xff000000) >> 24;
  221591. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  221592. {
  221593. dragAndDropSourceWindow = 0;
  221594. return;
  221595. }
  221596. dragAndDropSourceWindow = clientMsg->data.l[0];
  221597. if ((clientMsg->data.l[1] & 1) != 0)
  221598. {
  221599. Atom actual;
  221600. int format;
  221601. unsigned long count = 0, remaining = 0;
  221602. unsigned char* data = 0;
  221603. ScopedXLock xlock;
  221604. XGetWindowProperty (display, dragAndDropSourceWindow, Atoms::XdndTypeList,
  221605. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  221606. &count, &remaining, &data);
  221607. if (data != 0)
  221608. {
  221609. if (actual == XA_ATOM && format == 32 && count != 0)
  221610. {
  221611. const unsigned long* const types = (const unsigned long*) data;
  221612. for (unsigned int i = 0; i < count; ++i)
  221613. if (types[i] != None)
  221614. srcMimeTypeAtomList.add (types[i]);
  221615. }
  221616. XFree (data);
  221617. }
  221618. }
  221619. if (srcMimeTypeAtomList.size() == 0)
  221620. {
  221621. for (int i = 2; i < 5; ++i)
  221622. if (clientMsg->data.l[i] != None)
  221623. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  221624. if (srcMimeTypeAtomList.size() == 0)
  221625. {
  221626. dragAndDropSourceWindow = 0;
  221627. return;
  221628. }
  221629. }
  221630. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  221631. for (int j = 0; j < numElementsInArray (Atoms::allowedMimeTypes); ++j)
  221632. if (srcMimeTypeAtomList[i] == Atoms::allowedMimeTypes[j])
  221633. dragAndDropCurrentMimeType = Atoms::allowedMimeTypes[j];
  221634. handleDragAndDropPosition (clientMsg);
  221635. }
  221636. void handleDragAndDropSelection (const XEvent* const evt)
  221637. {
  221638. dragAndDropFiles.clear();
  221639. if (evt->xselection.property != 0)
  221640. {
  221641. StringArray lines;
  221642. {
  221643. MemoryBlock dropData;
  221644. for (;;)
  221645. {
  221646. Atom actual;
  221647. uint8* data = 0;
  221648. unsigned long count = 0, remaining = 0;
  221649. int format = 0;
  221650. ScopedXLock xlock;
  221651. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  221652. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  221653. &format, &count, &remaining, &data) == Success)
  221654. {
  221655. dropData.append (data, count * format / 8);
  221656. XFree (data);
  221657. if (remaining == 0)
  221658. break;
  221659. }
  221660. else
  221661. {
  221662. XFree (data);
  221663. break;
  221664. }
  221665. }
  221666. lines.addLines (dropData.toString());
  221667. }
  221668. for (int i = 0; i < lines.size(); ++i)
  221669. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf ("file://", false, true)));
  221670. dragAndDropFiles.trim();
  221671. dragAndDropFiles.removeEmptyStrings();
  221672. }
  221673. }
  221674. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  221675. {
  221676. dragAndDropFiles.clear();
  221677. if (dragAndDropSourceWindow != None
  221678. && dragAndDropCurrentMimeType != 0)
  221679. {
  221680. dragAndDropTimestamp = clientMsg->data.l[2];
  221681. ScopedXLock xlock;
  221682. XConvertSelection (display,
  221683. Atoms::XdndSelection,
  221684. dragAndDropCurrentMimeType,
  221685. XInternAtom (display, "JXSelectionWindowProperty", 0),
  221686. windowH,
  221687. dragAndDropTimestamp);
  221688. }
  221689. }
  221690. StringArray dragAndDropFiles;
  221691. int dragAndDropTimestamp;
  221692. Point<int> lastDropPos;
  221693. Atom dragAndDropCurrentMimeType;
  221694. Window dragAndDropSourceWindow;
  221695. Array <Atom> srcMimeTypeAtomList;
  221696. static int pointerMap[5];
  221697. static Point<int> lastMousePos;
  221698. static void clearLastMousePos() throw()
  221699. {
  221700. lastMousePos = Point<int> (0x100000, 0x100000);
  221701. }
  221702. };
  221703. ModifierKeys LinuxComponentPeer::currentModifiers;
  221704. bool LinuxComponentPeer::isActiveApplication = false;
  221705. int LinuxComponentPeer::pointerMap[5];
  221706. Point<int> LinuxComponentPeer::lastMousePos;
  221707. bool Process::isForegroundProcess()
  221708. {
  221709. return LinuxComponentPeer::isActiveApplication;
  221710. }
  221711. void ModifierKeys::updateCurrentModifiers() throw()
  221712. {
  221713. currentModifiers = LinuxComponentPeer::currentModifiers;
  221714. }
  221715. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  221716. {
  221717. Window root, child;
  221718. int x, y, winx, winy;
  221719. unsigned int mask;
  221720. int mouseMods = 0;
  221721. ScopedXLock xlock;
  221722. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  221723. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  221724. {
  221725. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  221726. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  221727. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  221728. }
  221729. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  221730. return LinuxComponentPeer::currentModifiers;
  221731. }
  221732. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  221733. {
  221734. if (enableOrDisable)
  221735. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  221736. }
  221737. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  221738. {
  221739. return new LinuxComponentPeer (this, styleFlags);
  221740. }
  221741. // (this callback is hooked up in the messaging code)
  221742. void juce_windowMessageReceive (XEvent* event)
  221743. {
  221744. if (event->xany.window != None)
  221745. {
  221746. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  221747. if (ComponentPeer::isValidPeer (peer))
  221748. peer->handleWindowMessage (event);
  221749. }
  221750. else
  221751. {
  221752. switch (event->xany.type)
  221753. {
  221754. case KeymapNotify:
  221755. {
  221756. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  221757. memcpy (Keys::keyStates, keymapEvent->key_vector, 32);
  221758. break;
  221759. }
  221760. default:
  221761. break;
  221762. }
  221763. }
  221764. }
  221765. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool /*clipToWorkArea*/)
  221766. {
  221767. if (display == 0)
  221768. return;
  221769. #if JUCE_USE_XINERAMA
  221770. int major_opcode, first_event, first_error;
  221771. ScopedXLock xlock;
  221772. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
  221773. {
  221774. typedef Bool (*tXineramaIsActive) (Display*);
  221775. typedef XineramaScreenInfo* (*tXineramaQueryScreens) (Display*, int*);
  221776. static tXineramaIsActive xXineramaIsActive = 0;
  221777. static tXineramaQueryScreens xXineramaQueryScreens = 0;
  221778. if (xXineramaIsActive == 0 || xXineramaQueryScreens == 0)
  221779. {
  221780. void* h = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
  221781. if (h == 0)
  221782. h = dlopen ("libXinerama.so.1", RTLD_GLOBAL | RTLD_NOW);
  221783. if (h != 0)
  221784. {
  221785. xXineramaIsActive = (tXineramaIsActive) dlsym (h, "XineramaIsActive");
  221786. xXineramaQueryScreens = (tXineramaQueryScreens) dlsym (h, "XineramaQueryScreens");
  221787. }
  221788. }
  221789. if (xXineramaIsActive != 0
  221790. && xXineramaQueryScreens != 0
  221791. && xXineramaIsActive (display))
  221792. {
  221793. int numMonitors = 0;
  221794. XineramaScreenInfo* const screens = xXineramaQueryScreens (display, &numMonitors);
  221795. if (screens != 0)
  221796. {
  221797. for (int i = numMonitors; --i >= 0;)
  221798. {
  221799. int index = screens[i].screen_number;
  221800. if (index >= 0)
  221801. {
  221802. while (monitorCoords.size() < index)
  221803. monitorCoords.add (Rectangle<int>());
  221804. monitorCoords.set (index, Rectangle<int> (screens[i].x_org,
  221805. screens[i].y_org,
  221806. screens[i].width,
  221807. screens[i].height));
  221808. }
  221809. }
  221810. XFree (screens);
  221811. }
  221812. }
  221813. }
  221814. if (monitorCoords.size() == 0)
  221815. #endif
  221816. {
  221817. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  221818. if (hints != None)
  221819. {
  221820. const int numMonitors = ScreenCount (display);
  221821. for (int i = 0; i < numMonitors; ++i)
  221822. {
  221823. Window root = RootWindow (display, i);
  221824. unsigned long nitems, bytesLeft;
  221825. Atom actualType;
  221826. int actualFormat;
  221827. unsigned char* data = 0;
  221828. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  221829. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  221830. &data) == Success)
  221831. {
  221832. const long* const position = (const long*) data;
  221833. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  221834. monitorCoords.add (Rectangle<int> (position[0], position[1],
  221835. position[2], position[3]));
  221836. XFree (data);
  221837. }
  221838. }
  221839. }
  221840. if (monitorCoords.size() == 0)
  221841. {
  221842. monitorCoords.add (Rectangle<int> (DisplayWidth (display, DefaultScreen (display)),
  221843. DisplayHeight (display, DefaultScreen (display))));
  221844. }
  221845. }
  221846. }
  221847. void Desktop::createMouseInputSources()
  221848. {
  221849. mouseSources.add (new MouseInputSource (0, true));
  221850. }
  221851. bool Desktop::canUseSemiTransparentWindows() throw()
  221852. {
  221853. int matchedDepth = 0;
  221854. const int desiredDepth = 32;
  221855. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  221856. && (matchedDepth == desiredDepth);
  221857. }
  221858. const Point<int> Desktop::getMousePosition()
  221859. {
  221860. Window root, child;
  221861. int x, y, winx, winy;
  221862. unsigned int mask;
  221863. ScopedXLock xlock;
  221864. if (XQueryPointer (display,
  221865. RootWindow (display, DefaultScreen (display)),
  221866. &root, &child,
  221867. &x, &y, &winx, &winy, &mask) == False)
  221868. {
  221869. // Pointer not on the default screen
  221870. x = y = -1;
  221871. }
  221872. return Point<int> (x, y);
  221873. }
  221874. void Desktop::setMousePosition (const Point<int>& newPosition)
  221875. {
  221876. ScopedXLock xlock;
  221877. Window root = RootWindow (display, DefaultScreen (display));
  221878. XWarpPointer (display, None, root, 0, 0, 0, 0, newPosition.getX(), newPosition.getY());
  221879. }
  221880. static bool screenSaverAllowed = true;
  221881. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  221882. {
  221883. if (screenSaverAllowed != isEnabled)
  221884. {
  221885. screenSaverAllowed = isEnabled;
  221886. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  221887. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  221888. if (xScreenSaverSuspend == 0)
  221889. {
  221890. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  221891. if (h != 0)
  221892. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  221893. }
  221894. ScopedXLock xlock;
  221895. if (xScreenSaverSuspend != 0)
  221896. xScreenSaverSuspend (display, ! isEnabled);
  221897. }
  221898. }
  221899. bool Desktop::isScreenSaverEnabled()
  221900. {
  221901. return screenSaverAllowed;
  221902. }
  221903. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  221904. {
  221905. ScopedXLock xlock;
  221906. const unsigned int imageW = image.getWidth();
  221907. const unsigned int imageH = image.getHeight();
  221908. #if JUCE_USE_XCURSOR
  221909. {
  221910. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  221911. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  221912. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  221913. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  221914. static tXcursorSupportsARGB xXcursorSupportsARGB = 0;
  221915. static tXcursorImageCreate xXcursorImageCreate = 0;
  221916. static tXcursorImageDestroy xXcursorImageDestroy = 0;
  221917. static tXcursorImageLoadCursor xXcursorImageLoadCursor = 0;
  221918. static bool hasBeenLoaded = false;
  221919. if (! hasBeenLoaded)
  221920. {
  221921. hasBeenLoaded = true;
  221922. void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW);
  221923. if (h != 0)
  221924. {
  221925. xXcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  221926. xXcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  221927. xXcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  221928. xXcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  221929. if (xXcursorSupportsARGB == 0 || xXcursorImageCreate == 0
  221930. || xXcursorImageLoadCursor == 0 || xXcursorImageDestroy == 0
  221931. || ! xXcursorSupportsARGB (display))
  221932. xXcursorSupportsARGB = 0;
  221933. }
  221934. }
  221935. if (xXcursorSupportsARGB != 0)
  221936. {
  221937. XcursorImage* xcImage = xXcursorImageCreate (imageW, imageH);
  221938. if (xcImage != 0)
  221939. {
  221940. xcImage->xhot = hotspotX;
  221941. xcImage->yhot = hotspotY;
  221942. XcursorPixel* dest = xcImage->pixels;
  221943. for (int y = 0; y < (int) imageH; ++y)
  221944. for (int x = 0; x < (int) imageW; ++x)
  221945. *dest++ = image.getPixelAt (x, y).getARGB();
  221946. void* result = (void*) xXcursorImageLoadCursor (display, xcImage);
  221947. xXcursorImageDestroy (xcImage);
  221948. if (result != 0)
  221949. return result;
  221950. }
  221951. }
  221952. }
  221953. #endif
  221954. Window root = RootWindow (display, DefaultScreen (display));
  221955. unsigned int cursorW, cursorH;
  221956. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  221957. return 0;
  221958. Image im (Image::ARGB, cursorW, cursorH, true);
  221959. {
  221960. Graphics g (im);
  221961. if (imageW > cursorW || imageH > cursorH)
  221962. {
  221963. hotspotX = (hotspotX * cursorW) / imageW;
  221964. hotspotY = (hotspotY * cursorH) / imageH;
  221965. g.drawImageWithin (image, 0, 0, imageW, imageH,
  221966. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  221967. false);
  221968. }
  221969. else
  221970. {
  221971. g.drawImageAt (image, 0, 0);
  221972. }
  221973. }
  221974. const int stride = (cursorW + 7) >> 3;
  221975. HeapBlock <char> maskPlane, sourcePlane;
  221976. maskPlane.calloc (stride * cursorH);
  221977. sourcePlane.calloc (stride * cursorH);
  221978. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  221979. for (int y = cursorH; --y >= 0;)
  221980. {
  221981. for (int x = cursorW; --x >= 0;)
  221982. {
  221983. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  221984. const int offset = y * stride + (x >> 3);
  221985. const Colour c (im.getPixelAt (x, y));
  221986. if (c.getAlpha() >= 128)
  221987. maskPlane[offset] |= mask;
  221988. if (c.getBrightness() >= 0.5f)
  221989. sourcePlane[offset] |= mask;
  221990. }
  221991. }
  221992. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  221993. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  221994. XColor white, black;
  221995. black.red = black.green = black.blue = 0;
  221996. white.red = white.green = white.blue = 0xffff;
  221997. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  221998. XFreePixmap (display, sourcePixmap);
  221999. XFreePixmap (display, maskPixmap);
  222000. return result;
  222001. }
  222002. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  222003. {
  222004. ScopedXLock xlock;
  222005. if (cursorHandle != 0)
  222006. XFreeCursor (display, (Cursor) cursorHandle);
  222007. }
  222008. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  222009. {
  222010. unsigned int shape;
  222011. switch (type)
  222012. {
  222013. case NormalCursor: return None; // Use parent cursor
  222014. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 16, 16, true), 0, 0);
  222015. case WaitCursor: shape = XC_watch; break;
  222016. case IBeamCursor: shape = XC_xterm; break;
  222017. case PointingHandCursor: shape = XC_hand2; break;
  222018. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  222019. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  222020. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  222021. case TopEdgeResizeCursor: shape = XC_top_side; break;
  222022. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  222023. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  222024. case RightEdgeResizeCursor: shape = XC_right_side; break;
  222025. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  222026. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  222027. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  222028. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  222029. case CrosshairCursor: shape = XC_crosshair; break;
  222030. case DraggingHandCursor:
  222031. {
  222032. static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  222033. 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,
  222034. 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 };
  222035. const int dragHandDataSize = 99;
  222036. return createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize), 8, 7);
  222037. }
  222038. case CopyingCursor:
  222039. {
  222040. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  222041. 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,
  222042. 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,
  222043. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  222044. const int copyCursorSize = 119;
  222045. return createMouseCursorFromImage (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3);
  222046. }
  222047. default:
  222048. jassertfalse;
  222049. return None;
  222050. }
  222051. ScopedXLock xlock;
  222052. return (void*) XCreateFontCursor (display, shape);
  222053. }
  222054. void MouseCursor::showInWindow (ComponentPeer* peer) const
  222055. {
  222056. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  222057. if (lp != 0)
  222058. lp->showMouseCursor ((Cursor) getHandle());
  222059. }
  222060. void MouseCursor::showInAllWindows() const
  222061. {
  222062. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  222063. showInWindow (ComponentPeer::getPeer (i));
  222064. }
  222065. const Image juce_createIconForFile (const File& file)
  222066. {
  222067. return Image::null;
  222068. }
  222069. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  222070. {
  222071. return createSoftwareImage (format, width, height, clearImage);
  222072. }
  222073. #if JUCE_OPENGL
  222074. class WindowedGLContext : public OpenGLContext
  222075. {
  222076. public:
  222077. WindowedGLContext (Component* const component,
  222078. const OpenGLPixelFormat& pixelFormat_,
  222079. GLXContext sharedContext)
  222080. : renderContext (0),
  222081. embeddedWindow (0),
  222082. pixelFormat (pixelFormat_),
  222083. swapInterval (0)
  222084. {
  222085. jassert (component != 0);
  222086. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  222087. if (peer == 0)
  222088. return;
  222089. ScopedXLock xlock;
  222090. XSync (display, False);
  222091. GLint attribs [64];
  222092. int n = 0;
  222093. attribs[n++] = GLX_RGBA;
  222094. attribs[n++] = GLX_DOUBLEBUFFER;
  222095. attribs[n++] = GLX_RED_SIZE;
  222096. attribs[n++] = pixelFormat.redBits;
  222097. attribs[n++] = GLX_GREEN_SIZE;
  222098. attribs[n++] = pixelFormat.greenBits;
  222099. attribs[n++] = GLX_BLUE_SIZE;
  222100. attribs[n++] = pixelFormat.blueBits;
  222101. attribs[n++] = GLX_ALPHA_SIZE;
  222102. attribs[n++] = pixelFormat.alphaBits;
  222103. attribs[n++] = GLX_DEPTH_SIZE;
  222104. attribs[n++] = pixelFormat.depthBufferBits;
  222105. attribs[n++] = GLX_STENCIL_SIZE;
  222106. attribs[n++] = pixelFormat.stencilBufferBits;
  222107. attribs[n++] = GLX_ACCUM_RED_SIZE;
  222108. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  222109. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  222110. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  222111. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  222112. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  222113. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  222114. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  222115. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  222116. attribs[n++] = None;
  222117. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  222118. if (bestVisual == 0)
  222119. return;
  222120. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  222121. Window windowH = (Window) peer->getNativeHandle();
  222122. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  222123. XSetWindowAttributes swa;
  222124. swa.colormap = colourMap;
  222125. swa.border_pixel = 0;
  222126. swa.event_mask = ExposureMask | StructureNotifyMask;
  222127. embeddedWindow = XCreateWindow (display, windowH,
  222128. 0, 0, 1, 1, 0,
  222129. bestVisual->depth,
  222130. InputOutput,
  222131. bestVisual->visual,
  222132. CWBorderPixel | CWColormap | CWEventMask,
  222133. &swa);
  222134. XSaveContext (display, (XID) embeddedWindow, windowHandleXContext, (XPointer) peer);
  222135. XMapWindow (display, embeddedWindow);
  222136. XFreeColormap (display, colourMap);
  222137. XFree (bestVisual);
  222138. XSync (display, False);
  222139. }
  222140. ~WindowedGLContext()
  222141. {
  222142. ScopedXLock xlock;
  222143. deleteContext();
  222144. XUnmapWindow (display, embeddedWindow);
  222145. XDestroyWindow (display, embeddedWindow);
  222146. }
  222147. void deleteContext()
  222148. {
  222149. makeInactive();
  222150. if (renderContext != 0)
  222151. {
  222152. ScopedXLock xlock;
  222153. glXDestroyContext (display, renderContext);
  222154. renderContext = 0;
  222155. }
  222156. }
  222157. bool makeActive() const throw()
  222158. {
  222159. jassert (renderContext != 0);
  222160. ScopedXLock xlock;
  222161. return glXMakeCurrent (display, embeddedWindow, renderContext)
  222162. && XSync (display, False);
  222163. }
  222164. bool makeInactive() const throw()
  222165. {
  222166. ScopedXLock xlock;
  222167. return (! isActive()) || glXMakeCurrent (display, None, 0);
  222168. }
  222169. bool isActive() const throw()
  222170. {
  222171. ScopedXLock xlock;
  222172. return glXGetCurrentContext() == renderContext;
  222173. }
  222174. const OpenGLPixelFormat getPixelFormat() const
  222175. {
  222176. return pixelFormat;
  222177. }
  222178. void* getRawContext() const throw()
  222179. {
  222180. return renderContext;
  222181. }
  222182. void updateWindowPosition (int x, int y, int w, int h, int)
  222183. {
  222184. ScopedXLock xlock;
  222185. XMoveResizeWindow (display, embeddedWindow,
  222186. x, y, jmax (1, w), jmax (1, h));
  222187. }
  222188. void swapBuffers()
  222189. {
  222190. ScopedXLock xlock;
  222191. glXSwapBuffers (display, embeddedWindow);
  222192. }
  222193. bool setSwapInterval (const int numFramesPerSwap)
  222194. {
  222195. static PFNGLXSWAPINTERVALSGIPROC GLXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC) glXGetProcAddress ((const GLubyte*) "glXSwapIntervalSGI");
  222196. if (GLXSwapIntervalSGI != 0)
  222197. {
  222198. swapInterval = numFramesPerSwap;
  222199. GLXSwapIntervalSGI (numFramesPerSwap);
  222200. return true;
  222201. }
  222202. return false;
  222203. }
  222204. int getSwapInterval() const
  222205. {
  222206. return swapInterval;
  222207. }
  222208. void repaint()
  222209. {
  222210. }
  222211. juce_UseDebuggingNewOperator
  222212. GLXContext renderContext;
  222213. private:
  222214. Window embeddedWindow;
  222215. OpenGLPixelFormat pixelFormat;
  222216. int swapInterval;
  222217. WindowedGLContext (const WindowedGLContext&);
  222218. WindowedGLContext& operator= (const WindowedGLContext&);
  222219. };
  222220. OpenGLContext* OpenGLComponent::createContext()
  222221. {
  222222. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  222223. contextToShareListsWith != 0 ? (GLXContext) contextToShareListsWith->getRawContext() : 0));
  222224. return (c->renderContext != 0) ? c.release() : 0;
  222225. }
  222226. void juce_glViewport (const int w, const int h)
  222227. {
  222228. glViewport (0, 0, w, h);
  222229. }
  222230. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  222231. OwnedArray <OpenGLPixelFormat>& results)
  222232. {
  222233. results.add (new OpenGLPixelFormat()); // xxx
  222234. }
  222235. #endif
  222236. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  222237. {
  222238. jassertfalse; // not implemented!
  222239. return false;
  222240. }
  222241. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  222242. {
  222243. jassertfalse; // not implemented!
  222244. return false;
  222245. }
  222246. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  222247. {
  222248. if (! isOnDesktop ())
  222249. addToDesktop (0);
  222250. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  222251. if (wp != 0)
  222252. {
  222253. wp->setTaskBarIcon (newImage);
  222254. setVisible (true);
  222255. toFront (false);
  222256. repaint();
  222257. }
  222258. }
  222259. void SystemTrayIconComponent::paint (Graphics& g)
  222260. {
  222261. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  222262. if (wp != 0)
  222263. {
  222264. g.drawImageWithin (wp->getTaskbarIcon(), 0, 0, getWidth(), getHeight(),
  222265. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  222266. false);
  222267. }
  222268. }
  222269. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  222270. {
  222271. // xxx not yet implemented!
  222272. }
  222273. void PlatformUtilities::beep()
  222274. {
  222275. std::cout << "\a" << std::flush;
  222276. }
  222277. bool AlertWindow::showNativeDialogBox (const String& title,
  222278. const String& bodyText,
  222279. bool isOkCancel)
  222280. {
  222281. // use a non-native one for the time being..
  222282. if (isOkCancel)
  222283. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  222284. else
  222285. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  222286. return true;
  222287. }
  222288. const int KeyPress::spaceKey = XK_space & 0xff;
  222289. const int KeyPress::returnKey = XK_Return & 0xff;
  222290. const int KeyPress::escapeKey = XK_Escape & 0xff;
  222291. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  222292. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  222293. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  222294. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  222295. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  222296. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  222297. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  222298. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  222299. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  222300. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  222301. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  222302. const int KeyPress::tabKey = XK_Tab & 0xff;
  222303. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  222304. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  222305. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  222306. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  222307. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  222308. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  222309. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  222310. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  222311. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  222312. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  222313. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  222314. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  222315. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  222316. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  222317. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  222318. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  222319. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  222320. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  222321. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  222322. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  222323. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  222324. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  222325. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  222326. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  222327. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  222328. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  222329. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  222330. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  222331. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  222332. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  222333. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  222334. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  222335. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  222336. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  222337. const int KeyPress::playKey = (0xffeeff00) | Keys::extendedKeyModifier;
  222338. const int KeyPress::stopKey = (0xffeeff01) | Keys::extendedKeyModifier;
  222339. const int KeyPress::fastForwardKey = (0xffeeff02) | Keys::extendedKeyModifier;
  222340. const int KeyPress::rewindKey = (0xffeeff03) | Keys::extendedKeyModifier;
  222341. #endif
  222342. /*** End of inlined file: juce_linux_Windowing.cpp ***/
  222343. /*** Start of inlined file: juce_linux_Audio.cpp ***/
  222344. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222345. // compiled on its own).
  222346. #if JUCE_INCLUDED_FILE && JUCE_ALSA
  222347. static void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  222348. {
  222349. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  222350. snd_pcm_hw_params_t* hwParams;
  222351. snd_pcm_hw_params_alloca (&hwParams);
  222352. for (int i = 0; ratesToTry[i] != 0; ++i)
  222353. {
  222354. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  222355. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  222356. {
  222357. rates.addIfNotAlreadyThere (ratesToTry[i]);
  222358. }
  222359. }
  222360. }
  222361. static void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  222362. {
  222363. snd_pcm_hw_params_t *params;
  222364. snd_pcm_hw_params_alloca (&params);
  222365. if (snd_pcm_hw_params_any (handle, params) >= 0)
  222366. {
  222367. snd_pcm_hw_params_get_channels_min (params, minChans);
  222368. snd_pcm_hw_params_get_channels_max (params, maxChans);
  222369. }
  222370. }
  222371. static void getDeviceProperties (const String& deviceID,
  222372. unsigned int& minChansOut,
  222373. unsigned int& maxChansOut,
  222374. unsigned int& minChansIn,
  222375. unsigned int& maxChansIn,
  222376. Array <int>& rates)
  222377. {
  222378. if (deviceID.isEmpty())
  222379. return;
  222380. snd_ctl_t* handle;
  222381. if (snd_ctl_open (&handle, deviceID.upToLastOccurrenceOf (",", false, false).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  222382. {
  222383. snd_pcm_info_t* info;
  222384. snd_pcm_info_alloca (&info);
  222385. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  222386. snd_pcm_info_set_device (info, deviceID.fromLastOccurrenceOf (",", false, false).getIntValue());
  222387. snd_pcm_info_set_subdevice (info, 0);
  222388. if (snd_ctl_pcm_info (handle, info) >= 0)
  222389. {
  222390. snd_pcm_t* pcmHandle;
  222391. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0)
  222392. {
  222393. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  222394. getDeviceSampleRates (pcmHandle, rates);
  222395. snd_pcm_close (pcmHandle);
  222396. }
  222397. }
  222398. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  222399. if (snd_ctl_pcm_info (handle, info) >= 0)
  222400. {
  222401. snd_pcm_t* pcmHandle;
  222402. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0)
  222403. {
  222404. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  222405. if (rates.size() == 0)
  222406. getDeviceSampleRates (pcmHandle, rates);
  222407. snd_pcm_close (pcmHandle);
  222408. }
  222409. }
  222410. snd_ctl_close (handle);
  222411. }
  222412. }
  222413. class ALSADevice
  222414. {
  222415. public:
  222416. ALSADevice (const String& deviceID, bool forInput)
  222417. : handle (0),
  222418. bitDepth (16),
  222419. numChannelsRunning (0),
  222420. latency (0),
  222421. isInput (forInput)
  222422. {
  222423. failed (snd_pcm_open (&handle, deviceID.toUTF8(),
  222424. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  222425. SND_PCM_ASYNC));
  222426. }
  222427. ~ALSADevice()
  222428. {
  222429. if (handle != 0)
  222430. snd_pcm_close (handle);
  222431. }
  222432. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  222433. {
  222434. if (handle == 0)
  222435. return false;
  222436. snd_pcm_hw_params_t* hwParams;
  222437. snd_pcm_hw_params_alloca (&hwParams);
  222438. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  222439. return false;
  222440. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  222441. isInterleaved = false;
  222442. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  222443. isInterleaved = true;
  222444. else
  222445. {
  222446. jassertfalse;
  222447. return false;
  222448. }
  222449. enum { isFloatBit = 1 << 16, isLittleEndianBit = 1 << 17 };
  222450. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32 | isFloatBit | isLittleEndianBit,
  222451. SND_PCM_FORMAT_FLOAT_BE, 32 | isFloatBit,
  222452. SND_PCM_FORMAT_S32_LE, 32 | isLittleEndianBit,
  222453. SND_PCM_FORMAT_S32_BE, 32,
  222454. SND_PCM_FORMAT_S24_3LE, 24 | isLittleEndianBit,
  222455. SND_PCM_FORMAT_S24_3BE, 24,
  222456. SND_PCM_FORMAT_S16_LE, 16 | isLittleEndianBit,
  222457. SND_PCM_FORMAT_S16_BE, 16 };
  222458. bitDepth = 0;
  222459. for (int i = 0; i < numElementsInArray (formatsToTry); i += 2)
  222460. {
  222461. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  222462. {
  222463. bitDepth = formatsToTry [i + 1] & 255;
  222464. const bool isFloat = (formatsToTry [i + 1] & isFloatBit) != 0;
  222465. const bool isLittleEndian = (formatsToTry [i + 1] & isLittleEndianBit) != 0;
  222466. converter = createConverter (isInput, bitDepth, isFloat, isLittleEndian, numChannels);
  222467. break;
  222468. }
  222469. }
  222470. if (bitDepth == 0)
  222471. {
  222472. error = "device doesn't support a compatible PCM format";
  222473. DBG ("ALSA error: " + error + "\n");
  222474. return false;
  222475. }
  222476. int dir = 0;
  222477. unsigned int periods = 4;
  222478. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  222479. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  222480. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  222481. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  222482. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  222483. || failed (snd_pcm_hw_params (handle, hwParams)))
  222484. {
  222485. return false;
  222486. }
  222487. snd_pcm_uframes_t frames = 0;
  222488. if (failed (snd_pcm_hw_params_get_period_size (hwParams, &frames, &dir))
  222489. || failed (snd_pcm_hw_params_get_periods (hwParams, &periods, &dir)))
  222490. latency = 0;
  222491. else
  222492. latency = frames * (periods - 1); // (this is the method JACK uses to guess the latency..)
  222493. snd_pcm_sw_params_t* swParams;
  222494. snd_pcm_sw_params_alloca (&swParams);
  222495. snd_pcm_uframes_t boundary;
  222496. if (failed (snd_pcm_sw_params_current (handle, swParams))
  222497. || failed (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  222498. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  222499. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  222500. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  222501. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  222502. || failed (snd_pcm_sw_params (handle, swParams)))
  222503. {
  222504. return false;
  222505. }
  222506. /*
  222507. #if JUCE_DEBUG
  222508. // enable this to dump the config of the devices that get opened
  222509. snd_output_t* out;
  222510. snd_output_stdio_attach (&out, stderr, 0);
  222511. snd_pcm_hw_params_dump (hwParams, out);
  222512. snd_pcm_sw_params_dump (swParams, out);
  222513. #endif
  222514. */
  222515. numChannelsRunning = numChannels;
  222516. return true;
  222517. }
  222518. bool writeToOutputDevice (AudioSampleBuffer& outputChannelBuffer, const int numSamples)
  222519. {
  222520. jassert (numChannelsRunning <= outputChannelBuffer.getNumChannels());
  222521. float** const data = outputChannelBuffer.getArrayOfChannels();
  222522. snd_pcm_sframes_t numDone = 0;
  222523. if (isInterleaved)
  222524. {
  222525. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  222526. for (int i = 0; i < numChannelsRunning; ++i)
  222527. converter->convertSamples (scratch.getData(), i, data[i], 0, numSamples);
  222528. numDone = snd_pcm_writei (handle, scratch.getData(), numSamples);
  222529. }
  222530. else
  222531. {
  222532. for (int i = 0; i < numChannelsRunning; ++i)
  222533. converter->convertSamples (data[i], data[i], numSamples);
  222534. numDone = snd_pcm_writen (handle, (void**) data, numSamples);
  222535. }
  222536. if (failed (numDone))
  222537. {
  222538. if (numDone == -EPIPE)
  222539. {
  222540. if (failed (snd_pcm_prepare (handle)))
  222541. return false;
  222542. }
  222543. else if (numDone != -ESTRPIPE)
  222544. return false;
  222545. }
  222546. return true;
  222547. }
  222548. bool readFromInputDevice (AudioSampleBuffer& inputChannelBuffer, const int numSamples)
  222549. {
  222550. jassert (numChannelsRunning <= inputChannelBuffer.getNumChannels());
  222551. float** const data = inputChannelBuffer.getArrayOfChannels();
  222552. if (isInterleaved)
  222553. {
  222554. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  222555. snd_pcm_sframes_t num = snd_pcm_readi (handle, scratch.getData(), numSamples);
  222556. if (failed (num))
  222557. {
  222558. if (num == -EPIPE)
  222559. {
  222560. if (failed (snd_pcm_prepare (handle)))
  222561. return false;
  222562. }
  222563. else if (num != -ESTRPIPE)
  222564. return false;
  222565. }
  222566. for (int i = 0; i < numChannelsRunning; ++i)
  222567. converter->convertSamples (data[i], 0, scratch.getData(), i, numSamples);
  222568. }
  222569. else
  222570. {
  222571. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  222572. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  222573. return false;
  222574. for (int i = 0; i < numChannelsRunning; ++i)
  222575. converter->convertSamples (data[i], data[i], numSamples);
  222576. }
  222577. return true;
  222578. }
  222579. juce_UseDebuggingNewOperator
  222580. snd_pcm_t* handle;
  222581. String error;
  222582. int bitDepth, numChannelsRunning, latency;
  222583. private:
  222584. const bool isInput;
  222585. bool isInterleaved;
  222586. MemoryBlock scratch;
  222587. ScopedPointer<AudioData::Converter> converter;
  222588. template <class SampleType>
  222589. struct ConverterHelper
  222590. {
  222591. static AudioData::Converter* createConverter (const bool forInput, const bool isLittleEndian, const int numInterleavedChannels)
  222592. {
  222593. if (forInput)
  222594. {
  222595. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestType;
  222596. if (isLittleEndian)
  222597. return new AudioData::ConverterInstance <AudioData::Pointer <SampleType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, DestType> (numInterleavedChannels, 1);
  222598. else
  222599. return new AudioData::ConverterInstance <AudioData::Pointer <SampleType, AudioData::BigEndian, AudioData::Interleaved, AudioData::Const>, DestType> (numInterleavedChannels, 1);
  222600. }
  222601. else
  222602. {
  222603. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceType;
  222604. if (isLittleEndian)
  222605. return new AudioData::ConverterInstance <SourceType, AudioData::Pointer <SampleType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, numInterleavedChannels);
  222606. else
  222607. return new AudioData::ConverterInstance <SourceType, AudioData::Pointer <SampleType, AudioData::BigEndian, AudioData::Interleaved, AudioData::NonConst> > (1, numInterleavedChannels);
  222608. }
  222609. }
  222610. };
  222611. static AudioData::Converter* createConverter (const bool forInput, const int bitDepth, const bool isFloat, const bool isLittleEndian, const int numInterleavedChannels)
  222612. {
  222613. switch (bitDepth)
  222614. {
  222615. case 16: return ConverterHelper <AudioData::Int16>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  222616. case 24: return ConverterHelper <AudioData::Int24>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  222617. case 32: return isFloat ? ConverterHelper <AudioData::Float32>::createConverter (forInput, isLittleEndian, numInterleavedChannels)
  222618. : ConverterHelper <AudioData::Int32>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  222619. default: jassertfalse; break; // unsupported format!
  222620. }
  222621. return 0;
  222622. }
  222623. bool failed (const int errorNum)
  222624. {
  222625. if (errorNum >= 0)
  222626. return false;
  222627. error = snd_strerror (errorNum);
  222628. DBG ("ALSA error: " + error + "\n");
  222629. return true;
  222630. }
  222631. };
  222632. class ALSAThread : public Thread
  222633. {
  222634. public:
  222635. ALSAThread (const String& inputId_,
  222636. const String& outputId_)
  222637. : Thread ("Juce ALSA"),
  222638. sampleRate (0),
  222639. bufferSize (0),
  222640. outputLatency (0),
  222641. inputLatency (0),
  222642. callback (0),
  222643. inputId (inputId_),
  222644. outputId (outputId_),
  222645. numCallbacks (0),
  222646. inputChannelBuffer (1, 1),
  222647. outputChannelBuffer (1, 1)
  222648. {
  222649. initialiseRatesAndChannels();
  222650. }
  222651. ~ALSAThread()
  222652. {
  222653. close();
  222654. }
  222655. void open (BigInteger inputChannels,
  222656. BigInteger outputChannels,
  222657. const double sampleRate_,
  222658. const int bufferSize_)
  222659. {
  222660. close();
  222661. error = String::empty;
  222662. sampleRate = sampleRate_;
  222663. bufferSize = bufferSize_;
  222664. inputChannelBuffer.setSize (jmax ((int) minChansIn, inputChannels.getHighestBit()) + 1, bufferSize);
  222665. inputChannelBuffer.clear();
  222666. inputChannelDataForCallback.clear();
  222667. currentInputChans.clear();
  222668. if (inputChannels.getHighestBit() >= 0)
  222669. {
  222670. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), (int) minChansIn); ++i)
  222671. {
  222672. if (inputChannels[i])
  222673. {
  222674. inputChannelDataForCallback.add (inputChannelBuffer.getSampleData (i));
  222675. currentInputChans.setBit (i);
  222676. }
  222677. }
  222678. }
  222679. outputChannelBuffer.setSize (jmax ((int) minChansOut, outputChannels.getHighestBit()) + 1, bufferSize);
  222680. outputChannelBuffer.clear();
  222681. outputChannelDataForCallback.clear();
  222682. currentOutputChans.clear();
  222683. if (outputChannels.getHighestBit() >= 0)
  222684. {
  222685. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), (int) minChansOut); ++i)
  222686. {
  222687. if (outputChannels[i])
  222688. {
  222689. outputChannelDataForCallback.add (outputChannelBuffer.getSampleData (i));
  222690. currentOutputChans.setBit (i);
  222691. }
  222692. }
  222693. }
  222694. if (outputChannelDataForCallback.size() > 0 && outputId.isNotEmpty())
  222695. {
  222696. outputDevice = new ALSADevice (outputId, false);
  222697. if (outputDevice->error.isNotEmpty())
  222698. {
  222699. error = outputDevice->error;
  222700. outputDevice = 0;
  222701. return;
  222702. }
  222703. currentOutputChans.setRange (0, minChansOut, true);
  222704. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  222705. jlimit ((int) minChansOut, (int) maxChansOut, currentOutputChans.getHighestBit() + 1),
  222706. bufferSize))
  222707. {
  222708. error = outputDevice->error;
  222709. outputDevice = 0;
  222710. return;
  222711. }
  222712. outputLatency = outputDevice->latency;
  222713. }
  222714. if (inputChannelDataForCallback.size() > 0 && inputId.isNotEmpty())
  222715. {
  222716. inputDevice = new ALSADevice (inputId, true);
  222717. if (inputDevice->error.isNotEmpty())
  222718. {
  222719. error = inputDevice->error;
  222720. inputDevice = 0;
  222721. return;
  222722. }
  222723. currentInputChans.setRange (0, minChansIn, true);
  222724. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  222725. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  222726. bufferSize))
  222727. {
  222728. error = inputDevice->error;
  222729. inputDevice = 0;
  222730. return;
  222731. }
  222732. inputLatency = inputDevice->latency;
  222733. }
  222734. if (outputDevice == 0 && inputDevice == 0)
  222735. {
  222736. error = "no channels";
  222737. return;
  222738. }
  222739. if (outputDevice != 0 && inputDevice != 0)
  222740. {
  222741. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  222742. }
  222743. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  222744. return;
  222745. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  222746. return;
  222747. startThread (9);
  222748. int count = 1000;
  222749. while (numCallbacks == 0)
  222750. {
  222751. sleep (5);
  222752. if (--count < 0 || ! isThreadRunning())
  222753. {
  222754. error = "device didn't start";
  222755. break;
  222756. }
  222757. }
  222758. }
  222759. void close()
  222760. {
  222761. stopThread (6000);
  222762. inputDevice = 0;
  222763. outputDevice = 0;
  222764. inputChannelBuffer.setSize (1, 1);
  222765. outputChannelBuffer.setSize (1, 1);
  222766. numCallbacks = 0;
  222767. }
  222768. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  222769. {
  222770. const ScopedLock sl (callbackLock);
  222771. callback = newCallback;
  222772. }
  222773. void run()
  222774. {
  222775. while (! threadShouldExit())
  222776. {
  222777. if (inputDevice != 0)
  222778. {
  222779. if (! inputDevice->readFromInputDevice (inputChannelBuffer, bufferSize))
  222780. {
  222781. DBG ("ALSA: read failure");
  222782. break;
  222783. }
  222784. }
  222785. if (threadShouldExit())
  222786. break;
  222787. {
  222788. const ScopedLock sl (callbackLock);
  222789. ++numCallbacks;
  222790. if (callback != 0)
  222791. {
  222792. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback.getRawDataPointer(),
  222793. inputChannelDataForCallback.size(),
  222794. outputChannelDataForCallback.getRawDataPointer(),
  222795. outputChannelDataForCallback.size(),
  222796. bufferSize);
  222797. }
  222798. else
  222799. {
  222800. for (int i = 0; i < outputChannelDataForCallback.size(); ++i)
  222801. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  222802. }
  222803. }
  222804. if (outputDevice != 0)
  222805. {
  222806. failed (snd_pcm_wait (outputDevice->handle, 2000));
  222807. if (threadShouldExit())
  222808. break;
  222809. failed (snd_pcm_avail_update (outputDevice->handle));
  222810. if (! outputDevice->writeToOutputDevice (outputChannelBuffer, bufferSize))
  222811. {
  222812. DBG ("ALSA: write failure");
  222813. break;
  222814. }
  222815. }
  222816. }
  222817. }
  222818. int getBitDepth() const throw()
  222819. {
  222820. if (outputDevice != 0)
  222821. return outputDevice->bitDepth;
  222822. if (inputDevice != 0)
  222823. return inputDevice->bitDepth;
  222824. return 16;
  222825. }
  222826. juce_UseDebuggingNewOperator
  222827. String error;
  222828. double sampleRate;
  222829. int bufferSize, outputLatency, inputLatency;
  222830. BigInteger currentInputChans, currentOutputChans;
  222831. Array <int> sampleRates;
  222832. StringArray channelNamesOut, channelNamesIn;
  222833. AudioIODeviceCallback* callback;
  222834. private:
  222835. const String inputId, outputId;
  222836. ScopedPointer<ALSADevice> outputDevice, inputDevice;
  222837. int numCallbacks;
  222838. CriticalSection callbackLock;
  222839. AudioSampleBuffer inputChannelBuffer, outputChannelBuffer;
  222840. Array<float*> inputChannelDataForCallback, outputChannelDataForCallback;
  222841. unsigned int minChansOut, maxChansOut;
  222842. unsigned int minChansIn, maxChansIn;
  222843. bool failed (const int errorNum)
  222844. {
  222845. if (errorNum >= 0)
  222846. return false;
  222847. error = snd_strerror (errorNum);
  222848. DBG ("ALSA error: " + error + "\n");
  222849. return true;
  222850. }
  222851. void initialiseRatesAndChannels()
  222852. {
  222853. sampleRates.clear();
  222854. channelNamesOut.clear();
  222855. channelNamesIn.clear();
  222856. minChansOut = 0;
  222857. maxChansOut = 0;
  222858. minChansIn = 0;
  222859. maxChansIn = 0;
  222860. unsigned int dummy = 0;
  222861. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  222862. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  222863. unsigned int i;
  222864. for (i = 0; i < maxChansOut; ++i)
  222865. channelNamesOut.add ("channel " + String ((int) i + 1));
  222866. for (i = 0; i < maxChansIn; ++i)
  222867. channelNamesIn.add ("channel " + String ((int) i + 1));
  222868. }
  222869. };
  222870. class ALSAAudioIODevice : public AudioIODevice
  222871. {
  222872. public:
  222873. ALSAAudioIODevice (const String& deviceName,
  222874. const String& inputId_,
  222875. const String& outputId_)
  222876. : AudioIODevice (deviceName, "ALSA"),
  222877. inputId (inputId_),
  222878. outputId (outputId_),
  222879. isOpen_ (false),
  222880. isStarted (false),
  222881. internal (inputId_, outputId_)
  222882. {
  222883. }
  222884. ~ALSAAudioIODevice()
  222885. {
  222886. }
  222887. const StringArray getOutputChannelNames() { return internal.channelNamesOut; }
  222888. const StringArray getInputChannelNames() { return internal.channelNamesIn; }
  222889. int getNumSampleRates() { return internal.sampleRates.size(); }
  222890. double getSampleRate (int index) { return internal.sampleRates [index]; }
  222891. int getDefaultBufferSize() { return 512; }
  222892. int getNumBufferSizesAvailable() { return 50; }
  222893. int getBufferSizeSamples (int index)
  222894. {
  222895. int n = 16;
  222896. for (int i = 0; i < index; ++i)
  222897. n += n < 64 ? 16
  222898. : (n < 512 ? 32
  222899. : (n < 1024 ? 64
  222900. : (n < 2048 ? 128 : 256)));
  222901. return n;
  222902. }
  222903. const String open (const BigInteger& inputChannels,
  222904. const BigInteger& outputChannels,
  222905. double sampleRate,
  222906. int bufferSizeSamples)
  222907. {
  222908. close();
  222909. if (bufferSizeSamples <= 0)
  222910. bufferSizeSamples = getDefaultBufferSize();
  222911. if (sampleRate <= 0)
  222912. {
  222913. for (int i = 0; i < getNumSampleRates(); ++i)
  222914. {
  222915. if (getSampleRate (i) >= 44100)
  222916. {
  222917. sampleRate = getSampleRate (i);
  222918. break;
  222919. }
  222920. }
  222921. }
  222922. internal.open (inputChannels, outputChannels,
  222923. sampleRate, bufferSizeSamples);
  222924. isOpen_ = internal.error.isEmpty();
  222925. return internal.error;
  222926. }
  222927. void close()
  222928. {
  222929. stop();
  222930. internal.close();
  222931. isOpen_ = false;
  222932. }
  222933. bool isOpen() { return isOpen_; }
  222934. bool isPlaying() { return isStarted && internal.error.isEmpty(); }
  222935. const String getLastError() { return internal.error; }
  222936. int getCurrentBufferSizeSamples() { return internal.bufferSize; }
  222937. double getCurrentSampleRate() { return internal.sampleRate; }
  222938. int getCurrentBitDepth() { return internal.getBitDepth(); }
  222939. const BigInteger getActiveOutputChannels() const { return internal.currentOutputChans; }
  222940. const BigInteger getActiveInputChannels() const { return internal.currentInputChans; }
  222941. int getOutputLatencyInSamples() { return internal.outputLatency; }
  222942. int getInputLatencyInSamples() { return internal.inputLatency; }
  222943. void start (AudioIODeviceCallback* callback)
  222944. {
  222945. if (! isOpen_)
  222946. callback = 0;
  222947. if (callback != 0)
  222948. callback->audioDeviceAboutToStart (this);
  222949. internal.setCallback (callback);
  222950. isStarted = (callback != 0);
  222951. }
  222952. void stop()
  222953. {
  222954. AudioIODeviceCallback* const oldCallback = internal.callback;
  222955. start (0);
  222956. if (oldCallback != 0)
  222957. oldCallback->audioDeviceStopped();
  222958. }
  222959. String inputId, outputId;
  222960. private:
  222961. bool isOpen_, isStarted;
  222962. ALSAThread internal;
  222963. };
  222964. class ALSAAudioIODeviceType : public AudioIODeviceType
  222965. {
  222966. public:
  222967. ALSAAudioIODeviceType()
  222968. : AudioIODeviceType ("ALSA"),
  222969. hasScanned (false)
  222970. {
  222971. }
  222972. ~ALSAAudioIODeviceType()
  222973. {
  222974. }
  222975. void scanForDevices()
  222976. {
  222977. if (hasScanned)
  222978. return;
  222979. hasScanned = true;
  222980. inputNames.clear();
  222981. inputIds.clear();
  222982. outputNames.clear();
  222983. outputIds.clear();
  222984. /* void** hints = 0;
  222985. if (snd_device_name_hint (-1, "pcm", &hints) >= 0)
  222986. {
  222987. for (void** hint = hints; *hint != 0; ++hint)
  222988. {
  222989. const String name (getHint (*hint, "NAME"));
  222990. if (name.isNotEmpty())
  222991. {
  222992. const String ioid (getHint (*hint, "IOID"));
  222993. String desc (getHint (*hint, "DESC"));
  222994. if (desc.isEmpty())
  222995. desc = name;
  222996. desc = desc.replaceCharacters ("\n\r", " ");
  222997. DBG ("name: " << name << "\ndesc: " << desc << "\nIO: " << ioid);
  222998. if (ioid.isEmpty() || ioid == "Input")
  222999. {
  223000. inputNames.add (desc);
  223001. inputIds.add (name);
  223002. }
  223003. if (ioid.isEmpty() || ioid == "Output")
  223004. {
  223005. outputNames.add (desc);
  223006. outputIds.add (name);
  223007. }
  223008. }
  223009. }
  223010. snd_device_name_free_hint (hints);
  223011. }
  223012. */
  223013. snd_ctl_t* handle = 0;
  223014. snd_ctl_card_info_t* info = 0;
  223015. snd_ctl_card_info_alloca (&info);
  223016. int cardNum = -1;
  223017. while (outputIds.size() + inputIds.size() <= 32)
  223018. {
  223019. snd_card_next (&cardNum);
  223020. if (cardNum < 0)
  223021. break;
  223022. if (snd_ctl_open (&handle, ("hw:" + String (cardNum)).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  223023. {
  223024. if (snd_ctl_card_info (handle, info) >= 0)
  223025. {
  223026. String cardId (snd_ctl_card_info_get_id (info));
  223027. if (cardId.removeCharacters ("0123456789").isEmpty())
  223028. cardId = String (cardNum);
  223029. int device = -1;
  223030. for (;;)
  223031. {
  223032. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  223033. break;
  223034. String id, name;
  223035. id << "hw:" << cardId << ',' << device;
  223036. bool isInput, isOutput;
  223037. if (testDevice (id, isInput, isOutput))
  223038. {
  223039. name << snd_ctl_card_info_get_name (info);
  223040. if (name.isEmpty())
  223041. name = id;
  223042. if (isInput)
  223043. {
  223044. inputNames.add (name);
  223045. inputIds.add (id);
  223046. }
  223047. if (isOutput)
  223048. {
  223049. outputNames.add (name);
  223050. outputIds.add (id);
  223051. }
  223052. }
  223053. }
  223054. }
  223055. snd_ctl_close (handle);
  223056. }
  223057. }
  223058. inputNames.appendNumbersToDuplicates (false, true);
  223059. outputNames.appendNumbersToDuplicates (false, true);
  223060. }
  223061. const StringArray getDeviceNames (bool wantInputNames) const
  223062. {
  223063. jassert (hasScanned); // need to call scanForDevices() before doing this
  223064. return wantInputNames ? inputNames : outputNames;
  223065. }
  223066. int getDefaultDeviceIndex (bool forInput) const
  223067. {
  223068. jassert (hasScanned); // need to call scanForDevices() before doing this
  223069. return 0;
  223070. }
  223071. bool hasSeparateInputsAndOutputs() const { return true; }
  223072. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  223073. {
  223074. jassert (hasScanned); // need to call scanForDevices() before doing this
  223075. ALSAAudioIODevice* d = dynamic_cast <ALSAAudioIODevice*> (device);
  223076. if (d == 0)
  223077. return -1;
  223078. return asInput ? inputIds.indexOf (d->inputId)
  223079. : outputIds.indexOf (d->outputId);
  223080. }
  223081. AudioIODevice* createDevice (const String& outputDeviceName,
  223082. const String& inputDeviceName)
  223083. {
  223084. jassert (hasScanned); // need to call scanForDevices() before doing this
  223085. const int inputIndex = inputNames.indexOf (inputDeviceName);
  223086. const int outputIndex = outputNames.indexOf (outputDeviceName);
  223087. String deviceName (outputIndex >= 0 ? outputDeviceName
  223088. : inputDeviceName);
  223089. if (inputIndex >= 0 || outputIndex >= 0)
  223090. return new ALSAAudioIODevice (deviceName,
  223091. inputIds [inputIndex],
  223092. outputIds [outputIndex]);
  223093. return 0;
  223094. }
  223095. juce_UseDebuggingNewOperator
  223096. private:
  223097. StringArray inputNames, outputNames, inputIds, outputIds;
  223098. bool hasScanned;
  223099. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  223100. {
  223101. unsigned int minChansOut = 0, maxChansOut = 0;
  223102. unsigned int minChansIn = 0, maxChansIn = 0;
  223103. Array <int> rates;
  223104. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  223105. DBG ("ALSA device: " + id
  223106. + " outs=" + String ((int) minChansOut) + "-" + String ((int) maxChansOut)
  223107. + " ins=" + String ((int) minChansIn) + "-" + String ((int) maxChansIn)
  223108. + " rates=" + String (rates.size()));
  223109. isInput = maxChansIn > 0;
  223110. isOutput = maxChansOut > 0;
  223111. return (isInput || isOutput) && rates.size() > 0;
  223112. }
  223113. /*static const String getHint (void* hint, const char* type)
  223114. {
  223115. char* const n = snd_device_name_get_hint (hint, type);
  223116. const String s ((const char*) n);
  223117. free (n);
  223118. return s;
  223119. }*/
  223120. ALSAAudioIODeviceType (const ALSAAudioIODeviceType&);
  223121. ALSAAudioIODeviceType& operator= (const ALSAAudioIODeviceType&);
  223122. };
  223123. AudioIODeviceType* juce_createAudioIODeviceType_ALSA()
  223124. {
  223125. return new ALSAAudioIODeviceType();
  223126. }
  223127. #endif
  223128. /*** End of inlined file: juce_linux_Audio.cpp ***/
  223129. /*** Start of inlined file: juce_linux_JackAudio.cpp ***/
  223130. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223131. // compiled on its own).
  223132. #ifdef JUCE_INCLUDED_FILE
  223133. #if JUCE_JACK
  223134. static void* juce_libjack_handle = 0;
  223135. void* juce_load_jack_function (const char* const name)
  223136. {
  223137. if (juce_libjack_handle == 0)
  223138. return 0;
  223139. return dlsym (juce_libjack_handle, name);
  223140. }
  223141. #define JUCE_DECL_JACK_FUNCTION(return_type, fn_name, argument_types, arguments) \
  223142. typedef return_type (*fn_name##_ptr_t)argument_types; \
  223143. return_type fn_name argument_types { \
  223144. static fn_name##_ptr_t fn = 0; \
  223145. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  223146. if (fn) return (*fn)arguments; \
  223147. else return 0; \
  223148. }
  223149. #define JUCE_DECL_VOID_JACK_FUNCTION(fn_name, argument_types, arguments) \
  223150. typedef void (*fn_name##_ptr_t)argument_types; \
  223151. void fn_name argument_types { \
  223152. static fn_name##_ptr_t fn = 0; \
  223153. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  223154. if (fn) (*fn)arguments; \
  223155. }
  223156. 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));
  223157. JUCE_DECL_JACK_FUNCTION (int, jack_client_close, (jack_client_t *client), (client));
  223158. JUCE_DECL_JACK_FUNCTION (int, jack_activate, (jack_client_t* client), (client));
  223159. JUCE_DECL_JACK_FUNCTION (int, jack_deactivate, (jack_client_t* client), (client));
  223160. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_buffer_size, (jack_client_t* client), (client));
  223161. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_sample_rate, (jack_client_t* client), (client));
  223162. JUCE_DECL_VOID_JACK_FUNCTION (jack_on_shutdown, (jack_client_t* client, void (*function)(void* arg), void* arg), (client, function, arg));
  223163. JUCE_DECL_JACK_FUNCTION (void* , jack_port_get_buffer, (jack_port_t* port, jack_nframes_t nframes), (port, nframes));
  223164. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_port_get_total_latency, (jack_client_t* client, jack_port_t* port), (client, port));
  223165. 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));
  223166. JUCE_DECL_VOID_JACK_FUNCTION (jack_set_error_function, (void (*func)(const char*)), (func));
  223167. JUCE_DECL_JACK_FUNCTION (int, jack_set_process_callback, (jack_client_t* client, JackProcessCallback process_callback, void* arg), (client, process_callback, arg));
  223168. 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));
  223169. JUCE_DECL_JACK_FUNCTION (int, jack_connect, (jack_client_t* client, const char* source_port, const char* destination_port), (client, source_port, destination_port));
  223170. JUCE_DECL_JACK_FUNCTION (const char*, jack_port_name, (const jack_port_t* port), (port));
  223171. JUCE_DECL_JACK_FUNCTION (int, jack_set_port_connect_callback, (jack_client_t* client, JackPortConnectCallback connect_callback, void* arg), (client, connect_callback, arg));
  223172. JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_by_id, (jack_client_t* client, jack_port_id_t port_id), (client, port_id));
  223173. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected, (const jack_port_t* port), (port));
  223174. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected_to, (const jack_port_t* port, const char* port_name), (port, port_name));
  223175. #if JUCE_DEBUG
  223176. #define JACK_LOGGING_ENABLED 1
  223177. #endif
  223178. #if JACK_LOGGING_ENABLED
  223179. static void jack_Log (const String& s)
  223180. {
  223181. std::cerr << s << std::endl;
  223182. }
  223183. static void dumpJackErrorMessage (const jack_status_t status)
  223184. {
  223185. if (status & JackServerFailed || status & JackServerError) jack_Log ("Unable to connect to JACK server");
  223186. if (status & JackVersionError) jack_Log ("Client's protocol version does not match");
  223187. if (status & JackInvalidOption) jack_Log ("The operation contained an invalid or unsupported option");
  223188. if (status & JackNameNotUnique) jack_Log ("The desired client name was not unique");
  223189. if (status & JackNoSuchClient) jack_Log ("Requested client does not exist");
  223190. if (status & JackInitFailure) jack_Log ("Unable to initialize client");
  223191. }
  223192. #else
  223193. #define dumpJackErrorMessage(a) {}
  223194. #define jack_Log(...) {}
  223195. #endif
  223196. #ifndef JUCE_JACK_CLIENT_NAME
  223197. #define JUCE_JACK_CLIENT_NAME "JuceJack"
  223198. #endif
  223199. class JackAudioIODevice : public AudioIODevice
  223200. {
  223201. public:
  223202. JackAudioIODevice (const String& deviceName,
  223203. const String& inputId_,
  223204. const String& outputId_)
  223205. : AudioIODevice (deviceName, "JACK"),
  223206. inputId (inputId_),
  223207. outputId (outputId_),
  223208. isOpen_ (false),
  223209. callback (0),
  223210. totalNumberOfInputChannels (0),
  223211. totalNumberOfOutputChannels (0)
  223212. {
  223213. jassert (deviceName.isNotEmpty());
  223214. jack_status_t status;
  223215. client = JUCE_NAMESPACE::jack_client_open (JUCE_JACK_CLIENT_NAME, JackNoStartServer, &status);
  223216. if (client == 0)
  223217. {
  223218. dumpJackErrorMessage (status);
  223219. }
  223220. else
  223221. {
  223222. JUCE_NAMESPACE::jack_set_error_function (errorCallback);
  223223. // open input ports
  223224. const StringArray inputChannels (getInputChannelNames());
  223225. for (int i = 0; i < inputChannels.size(); i++)
  223226. {
  223227. String inputName;
  223228. inputName << "in_" << ++totalNumberOfInputChannels;
  223229. inputPorts.add (JUCE_NAMESPACE::jack_port_register (client, inputName.toUTF8(),
  223230. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0));
  223231. }
  223232. // open output ports
  223233. const StringArray outputChannels (getOutputChannelNames());
  223234. for (int i = 0; i < outputChannels.size (); i++)
  223235. {
  223236. String outputName;
  223237. outputName << "out_" << ++totalNumberOfOutputChannels;
  223238. outputPorts.add (JUCE_NAMESPACE::jack_port_register (client, outputName.toUTF8(),
  223239. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0));
  223240. }
  223241. inChans.calloc (totalNumberOfInputChannels + 2);
  223242. outChans.calloc (totalNumberOfOutputChannels + 2);
  223243. }
  223244. }
  223245. ~JackAudioIODevice()
  223246. {
  223247. close();
  223248. if (client != 0)
  223249. {
  223250. JUCE_NAMESPACE::jack_client_close (client);
  223251. client = 0;
  223252. }
  223253. }
  223254. const StringArray getChannelNames (bool forInput) const
  223255. {
  223256. StringArray names;
  223257. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */
  223258. forInput ? JackPortIsInput : JackPortIsOutput);
  223259. if (ports != 0)
  223260. {
  223261. int j = 0;
  223262. while (ports[j] != 0)
  223263. {
  223264. const String portName (ports [j++]);
  223265. if (portName.upToFirstOccurrenceOf (":", false, false) == getName())
  223266. names.add (portName.fromFirstOccurrenceOf (":", false, false));
  223267. }
  223268. free (ports);
  223269. }
  223270. return names;
  223271. }
  223272. const StringArray getOutputChannelNames() { return getChannelNames (false); }
  223273. const StringArray getInputChannelNames() { return getChannelNames (true); }
  223274. int getNumSampleRates() { return client != 0 ? 1 : 0; }
  223275. double getSampleRate (int index) { return client != 0 ? JUCE_NAMESPACE::jack_get_sample_rate (client) : 0; }
  223276. int getNumBufferSizesAvailable() { return client != 0 ? 1 : 0; }
  223277. int getBufferSizeSamples (int index) { return getDefaultBufferSize(); }
  223278. int getDefaultBufferSize() { return client != 0 ? JUCE_NAMESPACE::jack_get_buffer_size (client) : 0; }
  223279. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  223280. double sampleRate, int bufferSizeSamples)
  223281. {
  223282. if (client == 0)
  223283. {
  223284. lastError = "No JACK client running";
  223285. return lastError;
  223286. }
  223287. lastError = String::empty;
  223288. close();
  223289. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, this);
  223290. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, this);
  223291. JUCE_NAMESPACE::jack_activate (client);
  223292. isOpen_ = true;
  223293. if (! inputChannels.isZero())
  223294. {
  223295. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  223296. if (ports != 0)
  223297. {
  223298. const int numInputChannels = inputChannels.getHighestBit() + 1;
  223299. for (int i = 0; i < numInputChannels; ++i)
  223300. {
  223301. const String portName (ports[i]);
  223302. if (inputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  223303. {
  223304. int error = JUCE_NAMESPACE::jack_connect (client, ports[i], JUCE_NAMESPACE::jack_port_name ((jack_port_t*) inputPorts[i]));
  223305. if (error != 0)
  223306. jack_Log ("Cannot connect input port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  223307. }
  223308. }
  223309. free (ports);
  223310. }
  223311. }
  223312. if (! outputChannels.isZero())
  223313. {
  223314. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  223315. if (ports != 0)
  223316. {
  223317. const int numOutputChannels = outputChannels.getHighestBit() + 1;
  223318. for (int i = 0; i < numOutputChannels; ++i)
  223319. {
  223320. const String portName (ports[i]);
  223321. if (outputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  223322. {
  223323. int error = JUCE_NAMESPACE::jack_connect (client, JUCE_NAMESPACE::jack_port_name ((jack_port_t*) outputPorts[i]), ports[i]);
  223324. if (error != 0)
  223325. jack_Log ("Cannot connect output port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  223326. }
  223327. }
  223328. free (ports);
  223329. }
  223330. }
  223331. return lastError;
  223332. }
  223333. void close()
  223334. {
  223335. stop();
  223336. if (client != 0)
  223337. {
  223338. JUCE_NAMESPACE::jack_deactivate (client);
  223339. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, 0);
  223340. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, 0);
  223341. }
  223342. isOpen_ = false;
  223343. }
  223344. void start (AudioIODeviceCallback* newCallback)
  223345. {
  223346. if (isOpen_ && newCallback != callback)
  223347. {
  223348. if (newCallback != 0)
  223349. newCallback->audioDeviceAboutToStart (this);
  223350. AudioIODeviceCallback* const oldCallback = callback;
  223351. {
  223352. const ScopedLock sl (callbackLock);
  223353. callback = newCallback;
  223354. }
  223355. if (oldCallback != 0)
  223356. oldCallback->audioDeviceStopped();
  223357. }
  223358. }
  223359. void stop()
  223360. {
  223361. start (0);
  223362. }
  223363. bool isOpen() { return isOpen_; }
  223364. bool isPlaying() { return callback != 0; }
  223365. int getCurrentBufferSizeSamples() { return getBufferSizeSamples (0); }
  223366. double getCurrentSampleRate() { return getSampleRate (0); }
  223367. int getCurrentBitDepth() { return 32; }
  223368. const String getLastError() { return lastError; }
  223369. const BigInteger getActiveOutputChannels() const
  223370. {
  223371. BigInteger outputBits;
  223372. for (int i = 0; i < outputPorts.size(); i++)
  223373. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) outputPorts [i]))
  223374. outputBits.setBit (i);
  223375. return outputBits;
  223376. }
  223377. const BigInteger getActiveInputChannels() const
  223378. {
  223379. BigInteger inputBits;
  223380. for (int i = 0; i < inputPorts.size(); i++)
  223381. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) inputPorts [i]))
  223382. inputBits.setBit (i);
  223383. return inputBits;
  223384. }
  223385. int getOutputLatencyInSamples()
  223386. {
  223387. int latency = 0;
  223388. for (int i = 0; i < outputPorts.size(); i++)
  223389. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) outputPorts [i]));
  223390. return latency;
  223391. }
  223392. int getInputLatencyInSamples()
  223393. {
  223394. int latency = 0;
  223395. for (int i = 0; i < inputPorts.size(); i++)
  223396. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) inputPorts [i]));
  223397. return latency;
  223398. }
  223399. String inputId, outputId;
  223400. private:
  223401. void process (const int numSamples)
  223402. {
  223403. int i, numActiveInChans = 0, numActiveOutChans = 0;
  223404. for (i = 0; i < totalNumberOfInputChannels; ++i)
  223405. {
  223406. jack_default_audio_sample_t* in
  223407. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) inputPorts.getUnchecked(i), numSamples);
  223408. if (in != 0)
  223409. inChans [numActiveInChans++] = (float*) in;
  223410. }
  223411. for (i = 0; i < totalNumberOfOutputChannels; ++i)
  223412. {
  223413. jack_default_audio_sample_t* out
  223414. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) outputPorts.getUnchecked(i), numSamples);
  223415. if (out != 0)
  223416. outChans [numActiveOutChans++] = (float*) out;
  223417. }
  223418. const ScopedLock sl (callbackLock);
  223419. if (callback != 0)
  223420. {
  223421. callback->audioDeviceIOCallback (const_cast<const float**> (inChans.getData()), numActiveInChans,
  223422. outChans, numActiveOutChans, numSamples);
  223423. }
  223424. else
  223425. {
  223426. for (i = 0; i < numActiveOutChans; ++i)
  223427. zeromem (outChans[i], sizeof (float) * numSamples);
  223428. }
  223429. }
  223430. static int processCallback (jack_nframes_t nframes, void* callbackArgument)
  223431. {
  223432. if (callbackArgument != 0)
  223433. ((JackAudioIODevice*) callbackArgument)->process (nframes);
  223434. return 0;
  223435. }
  223436. static void threadInitCallback (void* callbackArgument)
  223437. {
  223438. jack_Log ("JackAudioIODevice::initialise");
  223439. }
  223440. static void shutdownCallback (void* callbackArgument)
  223441. {
  223442. jack_Log ("JackAudioIODevice::shutdown");
  223443. JackAudioIODevice* device = (JackAudioIODevice*) callbackArgument;
  223444. if (device != 0)
  223445. {
  223446. device->client = 0;
  223447. device->close();
  223448. }
  223449. }
  223450. static void errorCallback (const char* msg)
  223451. {
  223452. jack_Log ("JackAudioIODevice::errorCallback " + String (msg));
  223453. }
  223454. bool isOpen_;
  223455. jack_client_t* client;
  223456. String lastError;
  223457. AudioIODeviceCallback* callback;
  223458. CriticalSection callbackLock;
  223459. HeapBlock <float*> inChans, outChans;
  223460. int totalNumberOfInputChannels;
  223461. int totalNumberOfOutputChannels;
  223462. Array<void*> inputPorts, outputPorts;
  223463. };
  223464. class JackAudioIODeviceType : public AudioIODeviceType
  223465. {
  223466. public:
  223467. JackAudioIODeviceType()
  223468. : AudioIODeviceType ("JACK"),
  223469. hasScanned (false)
  223470. {
  223471. }
  223472. ~JackAudioIODeviceType()
  223473. {
  223474. }
  223475. void scanForDevices()
  223476. {
  223477. hasScanned = true;
  223478. inputNames.clear();
  223479. inputIds.clear();
  223480. outputNames.clear();
  223481. outputIds.clear();
  223482. if (juce_libjack_handle == 0)
  223483. {
  223484. juce_libjack_handle = dlopen ("libjack.so", RTLD_LAZY);
  223485. if (juce_libjack_handle == 0)
  223486. return;
  223487. }
  223488. // open a dummy client
  223489. jack_status_t status;
  223490. jack_client_t* client = JUCE_NAMESPACE::jack_client_open ("JuceJackDummy", JackNoStartServer, &status);
  223491. if (client == 0)
  223492. {
  223493. dumpJackErrorMessage (status);
  223494. }
  223495. else
  223496. {
  223497. // scan for output devices
  223498. const char** ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  223499. if (ports != 0)
  223500. {
  223501. int j = 0;
  223502. while (ports[j] != 0)
  223503. {
  223504. String clientName (ports[j]);
  223505. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  223506. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  223507. && ! inputNames.contains (clientName))
  223508. {
  223509. inputNames.add (clientName);
  223510. inputIds.add (ports [j]);
  223511. }
  223512. ++j;
  223513. }
  223514. free (ports);
  223515. }
  223516. // scan for input devices
  223517. ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  223518. if (ports != 0)
  223519. {
  223520. int j = 0;
  223521. while (ports[j] != 0)
  223522. {
  223523. String clientName (ports[j]);
  223524. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  223525. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  223526. && ! outputNames.contains (clientName))
  223527. {
  223528. outputNames.add (clientName);
  223529. outputIds.add (ports [j]);
  223530. }
  223531. ++j;
  223532. }
  223533. free (ports);
  223534. }
  223535. JUCE_NAMESPACE::jack_client_close (client);
  223536. }
  223537. }
  223538. const StringArray getDeviceNames (bool wantInputNames) const
  223539. {
  223540. jassert (hasScanned); // need to call scanForDevices() before doing this
  223541. return wantInputNames ? inputNames : outputNames;
  223542. }
  223543. int getDefaultDeviceIndex (bool forInput) const
  223544. {
  223545. jassert (hasScanned); // need to call scanForDevices() before doing this
  223546. return 0;
  223547. }
  223548. bool hasSeparateInputsAndOutputs() const { return true; }
  223549. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  223550. {
  223551. jassert (hasScanned); // need to call scanForDevices() before doing this
  223552. JackAudioIODevice* d = dynamic_cast <JackAudioIODevice*> (device);
  223553. if (d == 0)
  223554. return -1;
  223555. return asInput ? inputIds.indexOf (d->inputId)
  223556. : outputIds.indexOf (d->outputId);
  223557. }
  223558. AudioIODevice* createDevice (const String& outputDeviceName,
  223559. const String& inputDeviceName)
  223560. {
  223561. jassert (hasScanned); // need to call scanForDevices() before doing this
  223562. const int inputIndex = inputNames.indexOf (inputDeviceName);
  223563. const int outputIndex = outputNames.indexOf (outputDeviceName);
  223564. if (inputIndex >= 0 || outputIndex >= 0)
  223565. return new JackAudioIODevice (outputIndex >= 0 ? outputDeviceName
  223566. : inputDeviceName,
  223567. inputIds [inputIndex],
  223568. outputIds [outputIndex]);
  223569. return 0;
  223570. }
  223571. juce_UseDebuggingNewOperator
  223572. private:
  223573. StringArray inputNames, outputNames, inputIds, outputIds;
  223574. bool hasScanned;
  223575. JackAudioIODeviceType (const JackAudioIODeviceType&);
  223576. JackAudioIODeviceType& operator= (const JackAudioIODeviceType&);
  223577. };
  223578. AudioIODeviceType* juce_createAudioIODeviceType_JACK()
  223579. {
  223580. return new JackAudioIODeviceType();
  223581. }
  223582. #else // if JACK is turned off..
  223583. AudioIODeviceType* juce_createAudioIODeviceType_JACK() { return 0; }
  223584. #endif
  223585. #endif
  223586. /*** End of inlined file: juce_linux_JackAudio.cpp ***/
  223587. /*** Start of inlined file: juce_linux_Midi.cpp ***/
  223588. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223589. // compiled on its own).
  223590. #if JUCE_INCLUDED_FILE
  223591. #if JUCE_ALSA
  223592. static snd_seq_t* iterateMidiDevices (const bool forInput,
  223593. StringArray& deviceNamesFound,
  223594. const int deviceIndexToOpen)
  223595. {
  223596. snd_seq_t* returnedHandle = 0;
  223597. snd_seq_t* seqHandle;
  223598. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  223599. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  223600. {
  223601. snd_seq_system_info_t* systemInfo;
  223602. snd_seq_client_info_t* clientInfo;
  223603. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  223604. {
  223605. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  223606. && snd_seq_client_info_malloc (&clientInfo) == 0)
  223607. {
  223608. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  223609. while (--numClients >= 0 && returnedHandle == 0)
  223610. {
  223611. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  223612. {
  223613. snd_seq_port_info_t* portInfo;
  223614. if (snd_seq_port_info_malloc (&portInfo) == 0)
  223615. {
  223616. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  223617. const int client = snd_seq_client_info_get_client (clientInfo);
  223618. snd_seq_port_info_set_client (portInfo, client);
  223619. snd_seq_port_info_set_port (portInfo, -1);
  223620. while (--numPorts >= 0)
  223621. {
  223622. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  223623. && (snd_seq_port_info_get_capability (portInfo)
  223624. & (forInput ? SND_SEQ_PORT_CAP_READ
  223625. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  223626. {
  223627. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  223628. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  223629. {
  223630. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  223631. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  223632. if (sourcePort != -1)
  223633. {
  223634. snd_seq_set_client_name (seqHandle,
  223635. forInput ? "Juce Midi Input"
  223636. : "Juce Midi Output");
  223637. const int portId
  223638. = snd_seq_create_simple_port (seqHandle,
  223639. forInput ? "Juce Midi In Port"
  223640. : "Juce Midi Out Port",
  223641. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  223642. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  223643. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  223644. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  223645. returnedHandle = seqHandle;
  223646. }
  223647. }
  223648. }
  223649. }
  223650. snd_seq_port_info_free (portInfo);
  223651. }
  223652. }
  223653. }
  223654. snd_seq_client_info_free (clientInfo);
  223655. }
  223656. snd_seq_system_info_free (systemInfo);
  223657. }
  223658. if (returnedHandle == 0)
  223659. snd_seq_close (seqHandle);
  223660. }
  223661. deviceNamesFound.appendNumbersToDuplicates (true, true);
  223662. return returnedHandle;
  223663. }
  223664. static snd_seq_t* createMidiDevice (const bool forInput,
  223665. const String& deviceNameToOpen)
  223666. {
  223667. snd_seq_t* seqHandle = 0;
  223668. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  223669. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  223670. {
  223671. snd_seq_set_client_name (seqHandle,
  223672. (deviceNameToOpen + (forInput ? " Input" : " Output")).toCString());
  223673. const int portId
  223674. = snd_seq_create_simple_port (seqHandle,
  223675. forInput ? "in"
  223676. : "out",
  223677. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  223678. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  223679. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  223680. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  223681. if (portId < 0)
  223682. {
  223683. snd_seq_close (seqHandle);
  223684. seqHandle = 0;
  223685. }
  223686. }
  223687. return seqHandle;
  223688. }
  223689. class MidiOutputDevice
  223690. {
  223691. public:
  223692. MidiOutputDevice (MidiOutput* const midiOutput_,
  223693. snd_seq_t* const seqHandle_)
  223694. :
  223695. midiOutput (midiOutput_),
  223696. seqHandle (seqHandle_),
  223697. maxEventSize (16 * 1024)
  223698. {
  223699. jassert (seqHandle != 0 && midiOutput != 0);
  223700. snd_midi_event_new (maxEventSize, &midiParser);
  223701. }
  223702. ~MidiOutputDevice()
  223703. {
  223704. snd_midi_event_free (midiParser);
  223705. snd_seq_close (seqHandle);
  223706. }
  223707. void sendMessageNow (const MidiMessage& message)
  223708. {
  223709. if (message.getRawDataSize() > maxEventSize)
  223710. {
  223711. maxEventSize = message.getRawDataSize();
  223712. snd_midi_event_free (midiParser);
  223713. snd_midi_event_new (maxEventSize, &midiParser);
  223714. }
  223715. snd_seq_event_t event;
  223716. snd_seq_ev_clear (&event);
  223717. snd_midi_event_encode (midiParser,
  223718. message.getRawData(),
  223719. message.getRawDataSize(),
  223720. &event);
  223721. snd_midi_event_reset_encode (midiParser);
  223722. snd_seq_ev_set_source (&event, 0);
  223723. snd_seq_ev_set_subs (&event);
  223724. snd_seq_ev_set_direct (&event);
  223725. snd_seq_event_output (seqHandle, &event);
  223726. snd_seq_drain_output (seqHandle);
  223727. }
  223728. juce_UseDebuggingNewOperator
  223729. private:
  223730. MidiOutput* const midiOutput;
  223731. snd_seq_t* const seqHandle;
  223732. snd_midi_event_t* midiParser;
  223733. int maxEventSize;
  223734. };
  223735. const StringArray MidiOutput::getDevices()
  223736. {
  223737. StringArray devices;
  223738. iterateMidiDevices (false, devices, -1);
  223739. return devices;
  223740. }
  223741. int MidiOutput::getDefaultDeviceIndex()
  223742. {
  223743. return 0;
  223744. }
  223745. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  223746. {
  223747. MidiOutput* newDevice = 0;
  223748. StringArray devices;
  223749. snd_seq_t* const handle = iterateMidiDevices (false, devices, deviceIndex);
  223750. if (handle != 0)
  223751. {
  223752. newDevice = new MidiOutput();
  223753. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  223754. }
  223755. return newDevice;
  223756. }
  223757. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  223758. {
  223759. MidiOutput* newDevice = 0;
  223760. snd_seq_t* const handle = createMidiDevice (false, deviceName);
  223761. if (handle != 0)
  223762. {
  223763. newDevice = new MidiOutput();
  223764. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  223765. }
  223766. return newDevice;
  223767. }
  223768. MidiOutput::~MidiOutput()
  223769. {
  223770. delete static_cast <MidiOutputDevice*> (internal);
  223771. }
  223772. void MidiOutput::reset()
  223773. {
  223774. }
  223775. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  223776. {
  223777. return false;
  223778. }
  223779. void MidiOutput::setVolume (float leftVol, float rightVol)
  223780. {
  223781. }
  223782. void MidiOutput::sendMessageNow (const MidiMessage& message)
  223783. {
  223784. static_cast <MidiOutputDevice*> (internal)->sendMessageNow (message);
  223785. }
  223786. class MidiInputThread : public Thread
  223787. {
  223788. public:
  223789. MidiInputThread (MidiInput* const midiInput_,
  223790. snd_seq_t* const seqHandle_,
  223791. MidiInputCallback* const callback_)
  223792. : Thread ("Juce MIDI Input"),
  223793. midiInput (midiInput_),
  223794. seqHandle (seqHandle_),
  223795. callback (callback_)
  223796. {
  223797. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  223798. }
  223799. ~MidiInputThread()
  223800. {
  223801. snd_seq_close (seqHandle);
  223802. }
  223803. void run()
  223804. {
  223805. const int maxEventSize = 16 * 1024;
  223806. snd_midi_event_t* midiParser;
  223807. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  223808. {
  223809. HeapBlock <uint8> buffer (maxEventSize);
  223810. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  223811. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  223812. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  223813. while (! threadShouldExit())
  223814. {
  223815. if (poll (pfd, numPfds, 500) > 0)
  223816. {
  223817. snd_seq_event_t* inputEvent = 0;
  223818. snd_seq_nonblock (seqHandle, 1);
  223819. do
  223820. {
  223821. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  223822. {
  223823. // xxx what about SYSEXes that are too big for the buffer?
  223824. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  223825. snd_midi_event_reset_decode (midiParser);
  223826. if (numBytes > 0)
  223827. {
  223828. const MidiMessage message ((const uint8*) buffer,
  223829. numBytes,
  223830. Time::getMillisecondCounter() * 0.001);
  223831. callback->handleIncomingMidiMessage (midiInput, message);
  223832. }
  223833. snd_seq_free_event (inputEvent);
  223834. }
  223835. }
  223836. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  223837. snd_seq_free_event (inputEvent);
  223838. }
  223839. }
  223840. snd_midi_event_free (midiParser);
  223841. }
  223842. };
  223843. juce_UseDebuggingNewOperator
  223844. private:
  223845. MidiInput* const midiInput;
  223846. snd_seq_t* const seqHandle;
  223847. MidiInputCallback* const callback;
  223848. };
  223849. MidiInput::MidiInput (const String& name_)
  223850. : name (name_),
  223851. internal (0)
  223852. {
  223853. }
  223854. MidiInput::~MidiInput()
  223855. {
  223856. stop();
  223857. delete static_cast <MidiInputThread*> (internal);
  223858. }
  223859. void MidiInput::start()
  223860. {
  223861. static_cast <MidiInputThread*> (internal)->startThread();
  223862. }
  223863. void MidiInput::stop()
  223864. {
  223865. static_cast <MidiInputThread*> (internal)->stopThread (3000);
  223866. }
  223867. int MidiInput::getDefaultDeviceIndex()
  223868. {
  223869. return 0;
  223870. }
  223871. const StringArray MidiInput::getDevices()
  223872. {
  223873. StringArray devices;
  223874. iterateMidiDevices (true, devices, -1);
  223875. return devices;
  223876. }
  223877. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  223878. {
  223879. MidiInput* newDevice = 0;
  223880. StringArray devices;
  223881. snd_seq_t* const handle = iterateMidiDevices (true, devices, deviceIndex);
  223882. if (handle != 0)
  223883. {
  223884. newDevice = new MidiInput (devices [deviceIndex]);
  223885. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  223886. }
  223887. return newDevice;
  223888. }
  223889. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  223890. {
  223891. MidiInput* newDevice = 0;
  223892. snd_seq_t* const handle = createMidiDevice (true, deviceName);
  223893. if (handle != 0)
  223894. {
  223895. newDevice = new MidiInput (deviceName);
  223896. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  223897. }
  223898. return newDevice;
  223899. }
  223900. #else
  223901. // (These are just stub functions if ALSA is unavailable...)
  223902. const StringArray MidiOutput::getDevices() { return StringArray(); }
  223903. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  223904. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  223905. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  223906. MidiOutput::~MidiOutput() {}
  223907. void MidiOutput::reset() {}
  223908. bool MidiOutput::getVolume (float&, float&) { return false; }
  223909. void MidiOutput::setVolume (float, float) {}
  223910. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  223911. MidiInput::MidiInput (const String& name_) : name (name_), internal (0) {}
  223912. MidiInput::~MidiInput() {}
  223913. void MidiInput::start() {}
  223914. void MidiInput::stop() {}
  223915. int MidiInput::getDefaultDeviceIndex() { return 0; }
  223916. const StringArray MidiInput::getDevices() { return StringArray(); }
  223917. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  223918. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  223919. #endif
  223920. #endif
  223921. /*** End of inlined file: juce_linux_Midi.cpp ***/
  223922. /*** Start of inlined file: juce_linux_AudioCDReader.cpp ***/
  223923. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223924. // compiled on its own).
  223925. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  223926. AudioCDReader::AudioCDReader()
  223927. : AudioFormatReader (0, "CD Audio")
  223928. {
  223929. }
  223930. const StringArray AudioCDReader::getAvailableCDNames()
  223931. {
  223932. StringArray names;
  223933. return names;
  223934. }
  223935. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  223936. {
  223937. return 0;
  223938. }
  223939. AudioCDReader::~AudioCDReader()
  223940. {
  223941. }
  223942. void AudioCDReader::refreshTrackLengths()
  223943. {
  223944. }
  223945. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  223946. int64 startSampleInFile, int numSamples)
  223947. {
  223948. return false;
  223949. }
  223950. bool AudioCDReader::isCDStillPresent() const
  223951. {
  223952. return false;
  223953. }
  223954. bool AudioCDReader::isTrackAudio (int trackNum) const
  223955. {
  223956. return false;
  223957. }
  223958. void AudioCDReader::enableIndexScanning (bool b)
  223959. {
  223960. }
  223961. int AudioCDReader::getLastIndex() const
  223962. {
  223963. return 0;
  223964. }
  223965. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  223966. {
  223967. return Array<int>();
  223968. }
  223969. #endif
  223970. /*** End of inlined file: juce_linux_AudioCDReader.cpp ***/
  223971. /*** Start of inlined file: juce_linux_FileChooser.cpp ***/
  223972. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223973. // compiled on its own).
  223974. #if JUCE_INCLUDED_FILE
  223975. void FileChooser::showPlatformDialog (Array<File>& results,
  223976. const String& title,
  223977. const File& file,
  223978. const String& filters,
  223979. bool isDirectory,
  223980. bool selectsFiles,
  223981. bool isSave,
  223982. bool warnAboutOverwritingExistingFiles,
  223983. bool selectMultipleFiles,
  223984. FilePreviewComponent* previewComponent)
  223985. {
  223986. const String separator (":");
  223987. String command ("zenity --file-selection");
  223988. if (title.isNotEmpty())
  223989. command << " --title=\"" << title << "\"";
  223990. if (file != File::nonexistent)
  223991. command << " --filename=\"" << file.getFullPathName () << "\"";
  223992. if (isDirectory)
  223993. command << " --directory";
  223994. if (isSave)
  223995. command << " --save";
  223996. if (selectMultipleFiles)
  223997. command << " --multiple --separator=\"" << separator << "\"";
  223998. command << " 2>&1";
  223999. MemoryOutputStream result;
  224000. int status = -1;
  224001. FILE* stream = popen (command.toUTF8(), "r");
  224002. if (stream != 0)
  224003. {
  224004. for (;;)
  224005. {
  224006. char buffer [1024];
  224007. const int bytesRead = fread (buffer, 1, sizeof (buffer), stream);
  224008. if (bytesRead <= 0)
  224009. break;
  224010. result.write (buffer, bytesRead);
  224011. }
  224012. status = pclose (stream);
  224013. }
  224014. if (status == 0)
  224015. {
  224016. StringArray tokens;
  224017. if (selectMultipleFiles)
  224018. tokens.addTokens (result.toUTF8(), separator, String::empty);
  224019. else
  224020. tokens.add (result.toUTF8());
  224021. for (int i = 0; i < tokens.size(); i++)
  224022. results.add (File (tokens[i]));
  224023. return;
  224024. }
  224025. //xxx ain't got one!
  224026. jassertfalse;
  224027. }
  224028. #endif
  224029. /*** End of inlined file: juce_linux_FileChooser.cpp ***/
  224030. /*** Start of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  224031. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  224032. // compiled on its own).
  224033. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  224034. /*
  224035. Sorry.. This class isn't implemented on Linux!
  224036. */
  224037. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  224038. : browser (0),
  224039. blankPageShown (false),
  224040. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  224041. {
  224042. setOpaque (true);
  224043. }
  224044. WebBrowserComponent::~WebBrowserComponent()
  224045. {
  224046. }
  224047. void WebBrowserComponent::goToURL (const String& url,
  224048. const StringArray* headers,
  224049. const MemoryBlock* postData)
  224050. {
  224051. lastURL = url;
  224052. lastHeaders.clear();
  224053. if (headers != 0)
  224054. lastHeaders = *headers;
  224055. lastPostData.setSize (0);
  224056. if (postData != 0)
  224057. lastPostData = *postData;
  224058. blankPageShown = false;
  224059. }
  224060. void WebBrowserComponent::stop()
  224061. {
  224062. }
  224063. void WebBrowserComponent::goBack()
  224064. {
  224065. lastURL = String::empty;
  224066. blankPageShown = false;
  224067. }
  224068. void WebBrowserComponent::goForward()
  224069. {
  224070. lastURL = String::empty;
  224071. }
  224072. void WebBrowserComponent::refresh()
  224073. {
  224074. }
  224075. void WebBrowserComponent::paint (Graphics& g)
  224076. {
  224077. g.fillAll (Colours::white);
  224078. }
  224079. void WebBrowserComponent::checkWindowAssociation()
  224080. {
  224081. }
  224082. void WebBrowserComponent::reloadLastURL()
  224083. {
  224084. if (lastURL.isNotEmpty())
  224085. {
  224086. goToURL (lastURL, &lastHeaders, &lastPostData);
  224087. lastURL = String::empty;
  224088. }
  224089. }
  224090. void WebBrowserComponent::parentHierarchyChanged()
  224091. {
  224092. checkWindowAssociation();
  224093. }
  224094. void WebBrowserComponent::resized()
  224095. {
  224096. }
  224097. void WebBrowserComponent::visibilityChanged()
  224098. {
  224099. checkWindowAssociation();
  224100. }
  224101. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  224102. {
  224103. return true;
  224104. }
  224105. #endif
  224106. /*** End of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  224107. #endif
  224108. END_JUCE_NAMESPACE
  224109. #endif
  224110. /*** End of inlined file: juce_linux_NativeCode.cpp ***/
  224111. #endif
  224112. #if JUCE_MAC || JUCE_IPHONE
  224113. /*** Start of inlined file: juce_mac_NativeCode.mm ***/
  224114. /*
  224115. This file wraps together all the mac-specific code, so that
  224116. we can include all the native headers just once, and compile all our
  224117. platform-specific stuff in one big lump, keeping it out of the way of
  224118. the rest of the codebase.
  224119. */
  224120. #if JUCE_MAC || JUCE_IOS
  224121. BEGIN_JUCE_NAMESPACE
  224122. #undef Point
  224123. #define JUCE_INCLUDED_FILE 1
  224124. // Now include the actual code files..
  224125. /*** Start of inlined file: juce_mac_ObjCSuffix.h ***/
  224126. /** This suffix is used for naming all Obj-C classes that are used inside juce.
  224127. Because of the flat naming structure used by Obj-C, you can get horrible situations where
  224128. two DLLs are loaded into a host, each of which uses classes with the same names, and these get
  224129. cross-linked so that when you make a call to a class that you thought was private, it ends up
  224130. actually calling into a similarly named class in the other module's address space.
  224131. By changing this macro to a unique value, you ensure that all the obj-C classes in your app
  224132. have unique names, and should avoid this problem.
  224133. If you're using the amalgamated version, you can just set this macro to something unique before
  224134. you include juce_amalgamated.cpp.
  224135. */
  224136. #ifndef JUCE_ObjCExtraSuffix
  224137. #define JUCE_ObjCExtraSuffix 3
  224138. #endif
  224139. #define appendMacro1(a, b, c, d, e) a ## _ ## b ## _ ## c ## _ ## d ## _ ## e
  224140. #define appendMacro2(a, b, c, d, e) appendMacro1(a, b, c, d, e)
  224141. #define MakeObjCClassName(rootName) appendMacro2 (rootName, JUCE_MAJOR_VERSION, JUCE_MINOR_VERSION, JUCE_BUILDNUMBER, JUCE_ObjCExtraSuffix)
  224142. /*** End of inlined file: juce_mac_ObjCSuffix.h ***/
  224143. /*** Start of inlined file: juce_mac_Strings.mm ***/
  224144. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224145. // compiled on its own).
  224146. #if JUCE_INCLUDED_FILE
  224147. static const String nsStringToJuce (NSString* s)
  224148. {
  224149. return String::fromUTF8 ([s UTF8String]);
  224150. }
  224151. static NSString* juceStringToNS (const String& s)
  224152. {
  224153. return [NSString stringWithUTF8String: s.toUTF8()];
  224154. }
  224155. static const String convertUTF16ToString (const UniChar* utf16)
  224156. {
  224157. String s;
  224158. while (*utf16 != 0)
  224159. s += (juce_wchar) *utf16++;
  224160. return s;
  224161. }
  224162. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  224163. {
  224164. String result;
  224165. if (cfString != 0)
  224166. {
  224167. CFRange range = { 0, CFStringGetLength (cfString) };
  224168. HeapBlock <UniChar> u (range.length + 1);
  224169. CFStringGetCharacters (cfString, range, u);
  224170. u[range.length] = 0;
  224171. result = convertUTF16ToString (u);
  224172. }
  224173. return result;
  224174. }
  224175. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  224176. {
  224177. const int len = s.length();
  224178. HeapBlock <UniChar> temp (len + 2);
  224179. for (int i = 0; i <= len; ++i)
  224180. temp[i] = s[i];
  224181. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  224182. }
  224183. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  224184. {
  224185. #if JUCE_IOS
  224186. const ScopedAutoReleasePool pool;
  224187. return nsStringToJuce ([juceStringToNS (s) precomposedStringWithCanonicalMapping]);
  224188. #else
  224189. UnicodeMapping map;
  224190. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  224191. kUnicodeNoSubset,
  224192. kTextEncodingDefaultFormat);
  224193. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  224194. kUnicodeCanonicalCompVariant,
  224195. kTextEncodingDefaultFormat);
  224196. map.mappingVersion = kUnicodeUseLatestMapping;
  224197. UnicodeToTextInfo conversionInfo = 0;
  224198. String result;
  224199. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  224200. {
  224201. const int len = s.length();
  224202. HeapBlock <UniChar> tempIn, tempOut;
  224203. tempIn.calloc (len + 2);
  224204. tempOut.calloc (len + 2);
  224205. for (int i = 0; i <= len; ++i)
  224206. tempIn[i] = s[i];
  224207. ByteCount bytesRead = 0;
  224208. ByteCount outputBufferSize = 0;
  224209. if (ConvertFromUnicodeToText (conversionInfo,
  224210. len * sizeof (UniChar), tempIn,
  224211. kUnicodeDefaultDirectionMask,
  224212. 0, 0, 0, 0,
  224213. len * sizeof (UniChar), &bytesRead,
  224214. &outputBufferSize, tempOut) == noErr)
  224215. {
  224216. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  224217. juce_wchar* t = result;
  224218. unsigned int i;
  224219. for (i = 0; i < bytesRead / sizeof (UniChar); ++i)
  224220. t[i] = (juce_wchar) tempOut[i];
  224221. t[i] = 0;
  224222. }
  224223. DisposeUnicodeToTextInfo (&conversionInfo);
  224224. }
  224225. return result;
  224226. #endif
  224227. }
  224228. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  224229. void SystemClipboard::copyTextToClipboard (const String& text)
  224230. {
  224231. #if JUCE_IOS
  224232. [[UIPasteboard generalPasteboard] setValue: juceStringToNS (text)
  224233. forPasteboardType: @"public.text"];
  224234. #else
  224235. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  224236. owner: nil];
  224237. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  224238. forType: NSStringPboardType];
  224239. #endif
  224240. }
  224241. const String SystemClipboard::getTextFromClipboard()
  224242. {
  224243. #if JUCE_IOS
  224244. NSString* text = [[UIPasteboard generalPasteboard] valueForPasteboardType: @"public.text"];
  224245. #else
  224246. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  224247. #endif
  224248. return text == 0 ? String::empty
  224249. : nsStringToJuce (text);
  224250. }
  224251. #endif
  224252. #endif
  224253. /*** End of inlined file: juce_mac_Strings.mm ***/
  224254. /*** Start of inlined file: juce_mac_SystemStats.mm ***/
  224255. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224256. // compiled on its own).
  224257. #if JUCE_INCLUDED_FILE
  224258. namespace SystemStatsHelpers
  224259. {
  224260. static int64 highResTimerFrequency = 0;
  224261. static double highResTimerToMillisecRatio = 0;
  224262. #if JUCE_INTEL
  224263. static void juce_getCpuVendor (char* const v) throw()
  224264. {
  224265. int vendor[4];
  224266. zerostruct (vendor);
  224267. int dummy = 0;
  224268. asm ("mov %%ebx, %%esi \n\t"
  224269. "cpuid \n\t"
  224270. "xchg %%esi, %%ebx"
  224271. : "=a" (dummy), "=S" (vendor[0]), "=c" (vendor[2]), "=d" (vendor[1]) : "a" (0));
  224272. memcpy (v, vendor, 16);
  224273. }
  224274. static unsigned int getCPUIDWord (unsigned int& familyModel, unsigned int& extFeatures)
  224275. {
  224276. unsigned int cpu = 0;
  224277. unsigned int ext = 0;
  224278. unsigned int family = 0;
  224279. unsigned int dummy = 0;
  224280. asm ("mov %%ebx, %%esi \n\t"
  224281. "cpuid \n\t"
  224282. "xchg %%esi, %%ebx"
  224283. : "=a" (family), "=S" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  224284. familyModel = family;
  224285. extFeatures = ext;
  224286. return cpu;
  224287. }
  224288. #endif
  224289. }
  224290. void SystemStats::initialiseStats()
  224291. {
  224292. using namespace SystemStatsHelpers;
  224293. static bool initialised = false;
  224294. if (! initialised)
  224295. {
  224296. initialised = true;
  224297. #if JUCE_MAC
  224298. [NSApplication sharedApplication];
  224299. #endif
  224300. #if JUCE_INTEL
  224301. unsigned int familyModel, extFeatures;
  224302. const unsigned int features = getCPUIDWord (familyModel, extFeatures);
  224303. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  224304. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  224305. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  224306. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  224307. #else
  224308. cpuFlags.hasMMX = false;
  224309. cpuFlags.hasSSE = false;
  224310. cpuFlags.hasSSE2 = false;
  224311. cpuFlags.has3DNow = false;
  224312. #endif
  224313. #if JUCE_IOS || (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
  224314. cpuFlags.numCpus = (int) [[NSProcessInfo processInfo] activeProcessorCount];
  224315. #else
  224316. cpuFlags.numCpus = (int) MPProcessors();
  224317. #endif
  224318. mach_timebase_info_data_t timebase;
  224319. (void) mach_timebase_info (&timebase);
  224320. highResTimerFrequency = (int64) (1.0e9 * timebase.denom / timebase.numer);
  224321. highResTimerToMillisecRatio = timebase.numer / (1.0e6 * timebase.denom);
  224322. String s (SystemStats::getJUCEVersion());
  224323. rlimit lim;
  224324. getrlimit (RLIMIT_NOFILE, &lim);
  224325. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  224326. setrlimit (RLIMIT_NOFILE, &lim);
  224327. }
  224328. }
  224329. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  224330. {
  224331. return MacOSX;
  224332. }
  224333. const String SystemStats::getOperatingSystemName()
  224334. {
  224335. return "Mac OS X";
  224336. }
  224337. #if ! JUCE_IOS
  224338. int PlatformUtilities::getOSXMinorVersionNumber()
  224339. {
  224340. SInt32 versionMinor = 0;
  224341. OSErr err = Gestalt (gestaltSystemVersionMinor, &versionMinor);
  224342. (void) err;
  224343. jassert (err == noErr);
  224344. return (int) versionMinor;
  224345. }
  224346. #endif
  224347. bool SystemStats::isOperatingSystem64Bit()
  224348. {
  224349. #if JUCE_IOS
  224350. return false;
  224351. #elif JUCE_64BIT
  224352. return true;
  224353. #else
  224354. return PlatformUtilities::getOSXMinorVersionNumber() >= 6;
  224355. #endif
  224356. }
  224357. int SystemStats::getMemorySizeInMegabytes()
  224358. {
  224359. uint64 mem = 0;
  224360. size_t memSize = sizeof (mem);
  224361. int mib[] = { CTL_HW, HW_MEMSIZE };
  224362. sysctl (mib, 2, &mem, &memSize, 0, 0);
  224363. return (int) (mem / (1024 * 1024));
  224364. }
  224365. const String SystemStats::getCpuVendor()
  224366. {
  224367. #if JUCE_INTEL
  224368. char v [16];
  224369. SystemStatsHelpers::juce_getCpuVendor (v);
  224370. return String (v, 16);
  224371. #else
  224372. return String::empty;
  224373. #endif
  224374. }
  224375. int SystemStats::getCpuSpeedInMegaherz()
  224376. {
  224377. uint64 speedHz = 0;
  224378. size_t speedSize = sizeof (speedHz);
  224379. int mib[] = { CTL_HW, HW_CPU_FREQ };
  224380. sysctl (mib, 2, &speedHz, &speedSize, 0, 0);
  224381. #if JUCE_BIG_ENDIAN
  224382. if (speedSize == 4)
  224383. speedHz >>= 32;
  224384. #endif
  224385. return (int) (speedHz / 1000000);
  224386. }
  224387. const String SystemStats::getLogonName()
  224388. {
  224389. return nsStringToJuce (NSUserName());
  224390. }
  224391. const String SystemStats::getFullUserName()
  224392. {
  224393. return nsStringToJuce (NSFullUserName());
  224394. }
  224395. uint32 juce_millisecondsSinceStartup() throw()
  224396. {
  224397. return (uint32) (mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio);
  224398. }
  224399. double Time::getMillisecondCounterHiRes() throw()
  224400. {
  224401. return mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio;
  224402. }
  224403. int64 Time::getHighResolutionTicks() throw()
  224404. {
  224405. return (int64) mach_absolute_time();
  224406. }
  224407. int64 Time::getHighResolutionTicksPerSecond() throw()
  224408. {
  224409. return SystemStatsHelpers::highResTimerFrequency;
  224410. }
  224411. bool Time::setSystemTimeToThisTime() const
  224412. {
  224413. jassertfalse;
  224414. return false;
  224415. }
  224416. int SystemStats::getPageSize()
  224417. {
  224418. return (int) NSPageSize();
  224419. }
  224420. void PlatformUtilities::fpuReset()
  224421. {
  224422. }
  224423. #endif
  224424. /*** End of inlined file: juce_mac_SystemStats.mm ***/
  224425. /*** Start of inlined file: juce_mac_Network.mm ***/
  224426. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224427. // compiled on its own).
  224428. #if JUCE_INCLUDED_FILE
  224429. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  224430. {
  224431. #ifndef IFT_ETHER
  224432. #define IFT_ETHER 6
  224433. #endif
  224434. ifaddrs* addrs = 0;
  224435. int numResults = 0;
  224436. if (getifaddrs (&addrs) == 0)
  224437. {
  224438. const ifaddrs* cursor = addrs;
  224439. while (cursor != 0 && numResults < maxNum)
  224440. {
  224441. sockaddr_storage* sto = (sockaddr_storage*) cursor->ifa_addr;
  224442. if (sto->ss_family == AF_LINK)
  224443. {
  224444. const sockaddr_dl* const sadd = (const sockaddr_dl*) cursor->ifa_addr;
  224445. if (sadd->sdl_type == IFT_ETHER)
  224446. {
  224447. const uint8* const addr = ((const uint8*) sadd->sdl_data) + sadd->sdl_nlen;
  224448. uint64 a = 0;
  224449. for (int i = 6; --i >= 0;)
  224450. a = (a << 8) | addr [littleEndian ? i : (5 - i)];
  224451. *addresses++ = (int64) a;
  224452. ++numResults;
  224453. }
  224454. }
  224455. cursor = cursor->ifa_next;
  224456. }
  224457. freeifaddrs (addrs);
  224458. }
  224459. return numResults;
  224460. }
  224461. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  224462. const String& emailSubject,
  224463. const String& bodyText,
  224464. const StringArray& filesToAttach)
  224465. {
  224466. #if JUCE_IOS
  224467. //xxx probably need to use MFMailComposeViewController
  224468. jassertfalse;
  224469. return false;
  224470. #else
  224471. const ScopedAutoReleasePool pool;
  224472. String script;
  224473. script << "tell application \"Mail\"\r\n"
  224474. "set newMessage to make new outgoing message with properties {subject:\""
  224475. << emailSubject.replace ("\"", "\\\"")
  224476. << "\", content:\""
  224477. << bodyText.replace ("\"", "\\\"")
  224478. << "\" & return & return}\r\n"
  224479. "tell newMessage\r\n"
  224480. "set visible to true\r\n"
  224481. "set sender to \"sdfsdfsdfewf\"\r\n"
  224482. "make new to recipient at end of to recipients with properties {address:\""
  224483. << targetEmailAddress
  224484. << "\"}\r\n";
  224485. for (int i = 0; i < filesToAttach.size(); ++i)
  224486. {
  224487. script << "tell content\r\n"
  224488. "make new attachment with properties {file name:\""
  224489. << filesToAttach[i].replace ("\"", "\\\"")
  224490. << "\"} at after the last paragraph\r\n"
  224491. "end tell\r\n";
  224492. }
  224493. script << "end tell\r\n"
  224494. "end tell\r\n";
  224495. NSAppleScript* s = [[NSAppleScript alloc]
  224496. initWithSource: juceStringToNS (script)];
  224497. NSDictionary* error = 0;
  224498. const bool ok = [s executeAndReturnError: &error] != nil;
  224499. [s release];
  224500. return ok;
  224501. #endif
  224502. }
  224503. END_JUCE_NAMESPACE
  224504. using namespace JUCE_NAMESPACE;
  224505. #define JuceURLConnection MakeObjCClassName(JuceURLConnection)
  224506. @interface JuceURLConnection : NSObject
  224507. {
  224508. @public
  224509. NSURLRequest* request;
  224510. NSURLConnection* connection;
  224511. NSMutableData* data;
  224512. Thread* runLoopThread;
  224513. bool initialised, hasFailed, hasFinished;
  224514. int position;
  224515. int64 contentLength;
  224516. NSDictionary* headers;
  224517. NSLock* dataLock;
  224518. }
  224519. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  224520. - (void) dealloc;
  224521. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  224522. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  224523. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  224524. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  224525. - (BOOL) isOpen;
  224526. - (int) read: (char*) dest numBytes: (int) num;
  224527. - (int) readPosition;
  224528. - (void) stop;
  224529. - (void) createConnection;
  224530. @end
  224531. class JuceURLConnectionMessageThread : public Thread
  224532. {
  224533. JuceURLConnection* owner;
  224534. public:
  224535. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  224536. : Thread ("http connection"),
  224537. owner (owner_)
  224538. {
  224539. }
  224540. ~JuceURLConnectionMessageThread()
  224541. {
  224542. stopThread (10000);
  224543. }
  224544. void run()
  224545. {
  224546. [owner createConnection];
  224547. while (! threadShouldExit())
  224548. {
  224549. const ScopedAutoReleasePool pool;
  224550. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  224551. }
  224552. }
  224553. };
  224554. @implementation JuceURLConnection
  224555. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  224556. withCallback: (URL::OpenStreamProgressCallback*) callback
  224557. withContext: (void*) context;
  224558. {
  224559. [super init];
  224560. request = req;
  224561. [request retain];
  224562. data = [[NSMutableData data] retain];
  224563. dataLock = [[NSLock alloc] init];
  224564. connection = 0;
  224565. initialised = false;
  224566. hasFailed = false;
  224567. hasFinished = false;
  224568. contentLength = -1;
  224569. headers = 0;
  224570. runLoopThread = new JuceURLConnectionMessageThread (self);
  224571. runLoopThread->startThread();
  224572. while (runLoopThread->isThreadRunning() && ! initialised)
  224573. {
  224574. if (callback != 0)
  224575. callback (context, -1, (int) [[request HTTPBody] length]);
  224576. Thread::sleep (1);
  224577. }
  224578. return self;
  224579. }
  224580. - (void) dealloc
  224581. {
  224582. [self stop];
  224583. deleteAndZero (runLoopThread);
  224584. [connection release];
  224585. [data release];
  224586. [dataLock release];
  224587. [request release];
  224588. [headers release];
  224589. [super dealloc];
  224590. }
  224591. - (void) createConnection
  224592. {
  224593. NSUInteger oldRetainCount = [self retainCount];
  224594. connection = [[NSURLConnection alloc] initWithRequest: request
  224595. delegate: self];
  224596. if (oldRetainCount == [self retainCount])
  224597. [self retain]; // newer SDK should already retain this, but there were problems in older versions..
  224598. if (connection == nil)
  224599. runLoopThread->signalThreadShouldExit();
  224600. }
  224601. - (void) connection: (NSURLConnection*) conn didReceiveResponse: (NSURLResponse*) response
  224602. {
  224603. (void) conn;
  224604. [dataLock lock];
  224605. [data setLength: 0];
  224606. [dataLock unlock];
  224607. initialised = true;
  224608. contentLength = [response expectedContentLength];
  224609. [headers release];
  224610. headers = 0;
  224611. if ([response isKindOfClass: [NSHTTPURLResponse class]])
  224612. headers = [[((NSHTTPURLResponse*) response) allHeaderFields] retain];
  224613. }
  224614. - (void) connection: (NSURLConnection*) conn didFailWithError: (NSError*) error
  224615. {
  224616. (void) conn;
  224617. DBG (nsStringToJuce ([error description]));
  224618. hasFailed = true;
  224619. initialised = true;
  224620. if (runLoopThread != 0)
  224621. runLoopThread->signalThreadShouldExit();
  224622. }
  224623. - (void) connection: (NSURLConnection*) conn didReceiveData: (NSData*) newData
  224624. {
  224625. (void) conn;
  224626. [dataLock lock];
  224627. [data appendData: newData];
  224628. [dataLock unlock];
  224629. initialised = true;
  224630. }
  224631. - (void) connectionDidFinishLoading: (NSURLConnection*) conn
  224632. {
  224633. (void) conn;
  224634. hasFinished = true;
  224635. initialised = true;
  224636. if (runLoopThread != 0)
  224637. runLoopThread->signalThreadShouldExit();
  224638. }
  224639. - (BOOL) isOpen
  224640. {
  224641. return connection != 0 && ! hasFailed;
  224642. }
  224643. - (int) readPosition
  224644. {
  224645. return position;
  224646. }
  224647. - (int) read: (char*) dest numBytes: (int) numNeeded
  224648. {
  224649. int numDone = 0;
  224650. while (numNeeded > 0)
  224651. {
  224652. int available = jmin (numNeeded, (int) [data length]);
  224653. if (available > 0)
  224654. {
  224655. [dataLock lock];
  224656. [data getBytes: dest length: available];
  224657. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  224658. [dataLock unlock];
  224659. numDone += available;
  224660. numNeeded -= available;
  224661. dest += available;
  224662. }
  224663. else
  224664. {
  224665. if (hasFailed || hasFinished)
  224666. break;
  224667. Thread::sleep (1);
  224668. }
  224669. }
  224670. position += numDone;
  224671. return numDone;
  224672. }
  224673. - (void) stop
  224674. {
  224675. [connection cancel];
  224676. if (runLoopThread != 0)
  224677. runLoopThread->stopThread (10000);
  224678. }
  224679. @end
  224680. BEGIN_JUCE_NAMESPACE
  224681. void* juce_openInternetFile (const String& url,
  224682. const String& headers,
  224683. const MemoryBlock& postData,
  224684. const bool isPost,
  224685. URL::OpenStreamProgressCallback* callback,
  224686. void* callbackContext,
  224687. int timeOutMs)
  224688. {
  224689. const ScopedAutoReleasePool pool;
  224690. NSMutableURLRequest* req = [NSMutableURLRequest
  224691. requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  224692. cachePolicy: NSURLRequestUseProtocolCachePolicy
  224693. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  224694. if (req == nil)
  224695. return 0;
  224696. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  224697. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  224698. StringArray headerLines;
  224699. headerLines.addLines (headers);
  224700. headerLines.removeEmptyStrings (true);
  224701. for (int i = 0; i < headerLines.size(); ++i)
  224702. {
  224703. const String key (headerLines[i].upToFirstOccurrenceOf (":", false, false).trim());
  224704. const String value (headerLines[i].fromFirstOccurrenceOf (":", false, false).trim());
  224705. if (key.isNotEmpty() && value.isNotEmpty())
  224706. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  224707. }
  224708. if (isPost && postData.getSize() > 0)
  224709. {
  224710. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  224711. length: postData.getSize()]];
  224712. }
  224713. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  224714. withCallback: callback
  224715. withContext: callbackContext];
  224716. if ([s isOpen])
  224717. return s;
  224718. [s release];
  224719. return 0;
  224720. }
  224721. void juce_closeInternetFile (void* handle)
  224722. {
  224723. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224724. if (s != 0)
  224725. {
  224726. const ScopedAutoReleasePool pool;
  224727. [s stop];
  224728. [s release];
  224729. }
  224730. }
  224731. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  224732. {
  224733. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224734. if (s != 0)
  224735. {
  224736. const ScopedAutoReleasePool pool;
  224737. return [s read: (char*) buffer numBytes: bytesToRead];
  224738. }
  224739. return 0;
  224740. }
  224741. int64 juce_getInternetFileContentLength (void* handle)
  224742. {
  224743. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224744. if (s != 0)
  224745. return s->contentLength;
  224746. return -1;
  224747. }
  224748. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  224749. {
  224750. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224751. if (s != 0 && s->headers != 0)
  224752. {
  224753. NSEnumerator* enumerator = [s->headers keyEnumerator];
  224754. NSString* key;
  224755. while ((key = [enumerator nextObject]) != nil)
  224756. headers.set (nsStringToJuce (key),
  224757. nsStringToJuce ((NSString*) [s->headers objectForKey: key]));
  224758. }
  224759. }
  224760. int juce_seekInInternetFile (void* handle, int /*newPosition*/)
  224761. {
  224762. JuceURLConnection* const s = (JuceURLConnection*) handle;
  224763. if (s != 0)
  224764. return [s readPosition];
  224765. return 0;
  224766. }
  224767. #endif
  224768. /*** End of inlined file: juce_mac_Network.mm ***/
  224769. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  224770. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224771. // compiled on its own).
  224772. #if JUCE_INCLUDED_FILE
  224773. struct NamedPipeInternal
  224774. {
  224775. String pipeInName, pipeOutName;
  224776. int pipeIn, pipeOut;
  224777. bool volatile createdPipe, blocked, stopReadOperation;
  224778. static void signalHandler (int) {}
  224779. };
  224780. void NamedPipe::cancelPendingReads()
  224781. {
  224782. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  224783. {
  224784. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224785. intern->stopReadOperation = true;
  224786. char buffer [1] = { 0 };
  224787. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  224788. (void) bytesWritten;
  224789. int timeout = 2000;
  224790. while (intern->blocked && --timeout >= 0)
  224791. Thread::sleep (2);
  224792. intern->stopReadOperation = false;
  224793. }
  224794. }
  224795. void NamedPipe::close()
  224796. {
  224797. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224798. if (intern != 0)
  224799. {
  224800. internal = 0;
  224801. if (intern->pipeIn != -1)
  224802. ::close (intern->pipeIn);
  224803. if (intern->pipeOut != -1)
  224804. ::close (intern->pipeOut);
  224805. if (intern->createdPipe)
  224806. {
  224807. unlink (intern->pipeInName.toUTF8());
  224808. unlink (intern->pipeOutName.toUTF8());
  224809. }
  224810. delete intern;
  224811. }
  224812. }
  224813. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  224814. {
  224815. close();
  224816. NamedPipeInternal* const intern = new NamedPipeInternal();
  224817. internal = intern;
  224818. intern->createdPipe = createPipe;
  224819. intern->blocked = false;
  224820. intern->stopReadOperation = false;
  224821. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  224822. siginterrupt (SIGPIPE, 1);
  224823. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  224824. intern->pipeInName = pipePath + "_in";
  224825. intern->pipeOutName = pipePath + "_out";
  224826. intern->pipeIn = -1;
  224827. intern->pipeOut = -1;
  224828. if (createPipe)
  224829. {
  224830. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  224831. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  224832. {
  224833. delete intern;
  224834. internal = 0;
  224835. return false;
  224836. }
  224837. }
  224838. return true;
  224839. }
  224840. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  224841. {
  224842. int bytesRead = -1;
  224843. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224844. if (intern != 0)
  224845. {
  224846. intern->blocked = true;
  224847. if (intern->pipeIn == -1)
  224848. {
  224849. if (intern->createdPipe)
  224850. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  224851. else
  224852. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  224853. if (intern->pipeIn == -1)
  224854. {
  224855. intern->blocked = false;
  224856. return -1;
  224857. }
  224858. }
  224859. bytesRead = 0;
  224860. char* p = static_cast<char*> (destBuffer);
  224861. while (bytesRead < maxBytesToRead)
  224862. {
  224863. const int bytesThisTime = maxBytesToRead - bytesRead;
  224864. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  224865. if (numRead <= 0 || intern->stopReadOperation)
  224866. {
  224867. bytesRead = -1;
  224868. break;
  224869. }
  224870. bytesRead += numRead;
  224871. p += bytesRead;
  224872. }
  224873. intern->blocked = false;
  224874. }
  224875. return bytesRead;
  224876. }
  224877. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  224878. {
  224879. int bytesWritten = -1;
  224880. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  224881. if (intern != 0)
  224882. {
  224883. if (intern->pipeOut == -1)
  224884. {
  224885. if (intern->createdPipe)
  224886. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  224887. else
  224888. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  224889. if (intern->pipeOut == -1)
  224890. {
  224891. return -1;
  224892. }
  224893. }
  224894. const char* p = static_cast<const char*> (sourceBuffer);
  224895. bytesWritten = 0;
  224896. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  224897. while (bytesWritten < numBytesToWrite
  224898. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  224899. {
  224900. const int bytesThisTime = numBytesToWrite - bytesWritten;
  224901. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  224902. if (numWritten <= 0)
  224903. {
  224904. bytesWritten = -1;
  224905. break;
  224906. }
  224907. bytesWritten += numWritten;
  224908. p += bytesWritten;
  224909. }
  224910. }
  224911. return bytesWritten;
  224912. }
  224913. #endif
  224914. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  224915. /*** Start of inlined file: juce_mac_Threads.mm ***/
  224916. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224917. // compiled on its own).
  224918. #if JUCE_INCLUDED_FILE
  224919. /*
  224920. Note that a lot of methods that you'd expect to find in this file actually
  224921. live in juce_posix_SharedCode.h!
  224922. */
  224923. bool Process::isForegroundProcess()
  224924. {
  224925. #if JUCE_MAC
  224926. return [NSApp isActive];
  224927. #else
  224928. return true; // xxx change this if more than one app is ever possible on the iPhone!
  224929. #endif
  224930. }
  224931. void Process::raisePrivilege()
  224932. {
  224933. jassertfalse;
  224934. }
  224935. void Process::lowerPrivilege()
  224936. {
  224937. jassertfalse;
  224938. }
  224939. void Process::terminate()
  224940. {
  224941. exit (0);
  224942. }
  224943. void Process::setPriority (ProcessPriority)
  224944. {
  224945. // xxx
  224946. }
  224947. #endif
  224948. /*** End of inlined file: juce_mac_Threads.mm ***/
  224949. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  224950. /*
  224951. This file contains posix routines that are common to both the Linux and Mac builds.
  224952. It gets included directly in the cpp files for these platforms.
  224953. */
  224954. CriticalSection::CriticalSection() throw()
  224955. {
  224956. pthread_mutexattr_t atts;
  224957. pthread_mutexattr_init (&atts);
  224958. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  224959. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  224960. pthread_mutex_init (&internal, &atts);
  224961. }
  224962. CriticalSection::~CriticalSection() throw()
  224963. {
  224964. pthread_mutex_destroy (&internal);
  224965. }
  224966. void CriticalSection::enter() const throw()
  224967. {
  224968. pthread_mutex_lock (&internal);
  224969. }
  224970. bool CriticalSection::tryEnter() const throw()
  224971. {
  224972. return pthread_mutex_trylock (&internal) == 0;
  224973. }
  224974. void CriticalSection::exit() const throw()
  224975. {
  224976. pthread_mutex_unlock (&internal);
  224977. }
  224978. class WaitableEventImpl
  224979. {
  224980. public:
  224981. WaitableEventImpl (const bool manualReset_)
  224982. : triggered (false),
  224983. manualReset (manualReset_)
  224984. {
  224985. pthread_cond_init (&condition, 0);
  224986. pthread_mutexattr_t atts;
  224987. pthread_mutexattr_init (&atts);
  224988. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  224989. pthread_mutex_init (&mutex, &atts);
  224990. }
  224991. ~WaitableEventImpl()
  224992. {
  224993. pthread_cond_destroy (&condition);
  224994. pthread_mutex_destroy (&mutex);
  224995. }
  224996. bool wait (const int timeOutMillisecs) throw()
  224997. {
  224998. pthread_mutex_lock (&mutex);
  224999. if (! triggered)
  225000. {
  225001. if (timeOutMillisecs < 0)
  225002. {
  225003. do
  225004. {
  225005. pthread_cond_wait (&condition, &mutex);
  225006. }
  225007. while (! triggered);
  225008. }
  225009. else
  225010. {
  225011. struct timeval now;
  225012. gettimeofday (&now, 0);
  225013. struct timespec time;
  225014. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  225015. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  225016. if (time.tv_nsec >= 1000000000)
  225017. {
  225018. time.tv_nsec -= 1000000000;
  225019. time.tv_sec++;
  225020. }
  225021. do
  225022. {
  225023. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  225024. {
  225025. pthread_mutex_unlock (&mutex);
  225026. return false;
  225027. }
  225028. }
  225029. while (! triggered);
  225030. }
  225031. }
  225032. if (! manualReset)
  225033. triggered = false;
  225034. pthread_mutex_unlock (&mutex);
  225035. return true;
  225036. }
  225037. void signal() throw()
  225038. {
  225039. pthread_mutex_lock (&mutex);
  225040. triggered = true;
  225041. pthread_cond_broadcast (&condition);
  225042. pthread_mutex_unlock (&mutex);
  225043. }
  225044. void reset() throw()
  225045. {
  225046. pthread_mutex_lock (&mutex);
  225047. triggered = false;
  225048. pthread_mutex_unlock (&mutex);
  225049. }
  225050. private:
  225051. pthread_cond_t condition;
  225052. pthread_mutex_t mutex;
  225053. bool triggered;
  225054. const bool manualReset;
  225055. WaitableEventImpl (const WaitableEventImpl&);
  225056. WaitableEventImpl& operator= (const WaitableEventImpl&);
  225057. };
  225058. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  225059. : internal (new WaitableEventImpl (manualReset))
  225060. {
  225061. }
  225062. WaitableEvent::~WaitableEvent() throw()
  225063. {
  225064. delete static_cast <WaitableEventImpl*> (internal);
  225065. }
  225066. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  225067. {
  225068. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  225069. }
  225070. void WaitableEvent::signal() const throw()
  225071. {
  225072. static_cast <WaitableEventImpl*> (internal)->signal();
  225073. }
  225074. void WaitableEvent::reset() const throw()
  225075. {
  225076. static_cast <WaitableEventImpl*> (internal)->reset();
  225077. }
  225078. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  225079. {
  225080. struct timespec time;
  225081. time.tv_sec = millisecs / 1000;
  225082. time.tv_nsec = (millisecs % 1000) * 1000000;
  225083. nanosleep (&time, 0);
  225084. }
  225085. const juce_wchar File::separator = '/';
  225086. const String File::separatorString ("/");
  225087. const File File::getCurrentWorkingDirectory()
  225088. {
  225089. HeapBlock<char> heapBuffer;
  225090. char localBuffer [1024];
  225091. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  225092. int bufferSize = 4096;
  225093. while (cwd == 0 && errno == ERANGE)
  225094. {
  225095. heapBuffer.malloc (bufferSize);
  225096. cwd = getcwd (heapBuffer, bufferSize - 1);
  225097. bufferSize += 1024;
  225098. }
  225099. return File (String::fromUTF8 (cwd));
  225100. }
  225101. bool File::setAsCurrentWorkingDirectory() const
  225102. {
  225103. return chdir (getFullPathName().toUTF8()) == 0;
  225104. }
  225105. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  225106. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  225107. #else
  225108. typedef struct stat juce_statStruct;
  225109. #endif
  225110. static bool juce_stat (const String& fileName, juce_statStruct& info)
  225111. {
  225112. return fileName.isNotEmpty()
  225113. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  225114. && (stat64 (fileName.toUTF8(), &info) == 0);
  225115. #else
  225116. && (stat (fileName.toUTF8(), &info) == 0);
  225117. #endif
  225118. }
  225119. bool File::isDirectory() const
  225120. {
  225121. juce_statStruct info;
  225122. return fullPath.isEmpty()
  225123. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  225124. }
  225125. bool File::exists() const
  225126. {
  225127. juce_statStruct info;
  225128. return fullPath.isNotEmpty()
  225129. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  225130. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  225131. #else
  225132. && (lstat (fullPath.toUTF8(), &info) == 0);
  225133. #endif
  225134. }
  225135. bool File::existsAsFile() const
  225136. {
  225137. return exists() && ! isDirectory();
  225138. }
  225139. int64 File::getSize() const
  225140. {
  225141. juce_statStruct info;
  225142. return juce_stat (fullPath, info) ? info.st_size : 0;
  225143. }
  225144. bool File::hasWriteAccess() const
  225145. {
  225146. if (exists())
  225147. return access (fullPath.toUTF8(), W_OK) == 0;
  225148. if ((! isDirectory()) && fullPath.containsChar (separator))
  225149. return getParentDirectory().hasWriteAccess();
  225150. return false;
  225151. }
  225152. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  225153. {
  225154. juce_statStruct info;
  225155. if (! juce_stat (fullPath, info))
  225156. return false;
  225157. info.st_mode &= 0777; // Just permissions
  225158. if (shouldBeReadOnly)
  225159. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  225160. else
  225161. // Give everybody write permission?
  225162. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  225163. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  225164. }
  225165. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  225166. {
  225167. modificationTime = 0;
  225168. accessTime = 0;
  225169. creationTime = 0;
  225170. juce_statStruct info;
  225171. if (juce_stat (fullPath, info))
  225172. {
  225173. modificationTime = (int64) info.st_mtime * 1000;
  225174. accessTime = (int64) info.st_atime * 1000;
  225175. creationTime = (int64) info.st_ctime * 1000;
  225176. }
  225177. }
  225178. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  225179. {
  225180. struct utimbuf times;
  225181. times.actime = (time_t) (accessTime / 1000);
  225182. times.modtime = (time_t) (modificationTime / 1000);
  225183. return utime (fullPath.toUTF8(), &times) == 0;
  225184. }
  225185. bool File::deleteFile() const
  225186. {
  225187. if (! exists())
  225188. return true;
  225189. else if (isDirectory())
  225190. return rmdir (fullPath.toUTF8()) == 0;
  225191. else
  225192. return remove (fullPath.toUTF8()) == 0;
  225193. }
  225194. bool File::moveInternal (const File& dest) const
  225195. {
  225196. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  225197. return true;
  225198. if (hasWriteAccess() && copyInternal (dest))
  225199. {
  225200. if (deleteFile())
  225201. return true;
  225202. dest.deleteFile();
  225203. }
  225204. return false;
  225205. }
  225206. void File::createDirectoryInternal (const String& fileName) const
  225207. {
  225208. mkdir (fileName.toUTF8(), 0777);
  225209. }
  225210. int64 juce_fileSetPosition (void* handle, int64 pos)
  225211. {
  225212. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  225213. return pos;
  225214. return -1;
  225215. }
  225216. void FileInputStream::openHandle()
  225217. {
  225218. totalSize = file.getSize();
  225219. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  225220. if (f != -1)
  225221. fileHandle = (void*) f;
  225222. }
  225223. void FileInputStream::closeHandle()
  225224. {
  225225. if (fileHandle != 0)
  225226. {
  225227. close ((int) (pointer_sized_int) fileHandle);
  225228. fileHandle = 0;
  225229. }
  225230. }
  225231. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  225232. {
  225233. if (fileHandle != 0)
  225234. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  225235. return 0;
  225236. }
  225237. void FileOutputStream::openHandle()
  225238. {
  225239. if (file.exists())
  225240. {
  225241. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  225242. if (f != -1)
  225243. {
  225244. currentPosition = lseek (f, 0, SEEK_END);
  225245. if (currentPosition >= 0)
  225246. fileHandle = (void*) f;
  225247. else
  225248. close (f);
  225249. }
  225250. }
  225251. else
  225252. {
  225253. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  225254. if (f != -1)
  225255. fileHandle = (void*) f;
  225256. }
  225257. }
  225258. void FileOutputStream::closeHandle()
  225259. {
  225260. if (fileHandle != 0)
  225261. {
  225262. close ((int) (pointer_sized_int) fileHandle);
  225263. fileHandle = 0;
  225264. }
  225265. }
  225266. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  225267. {
  225268. if (fileHandle != 0)
  225269. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  225270. return 0;
  225271. }
  225272. void FileOutputStream::flushInternal()
  225273. {
  225274. if (fileHandle != 0)
  225275. fsync ((int) (pointer_sized_int) fileHandle);
  225276. }
  225277. const File juce_getExecutableFile()
  225278. {
  225279. Dl_info exeInfo;
  225280. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  225281. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  225282. }
  225283. // if this file doesn't exist, find a parent of it that does..
  225284. static bool juce_doStatFS (File f, struct statfs& result)
  225285. {
  225286. for (int i = 5; --i >= 0;)
  225287. {
  225288. if (f.exists())
  225289. break;
  225290. f = f.getParentDirectory();
  225291. }
  225292. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  225293. }
  225294. int64 File::getBytesFreeOnVolume() const
  225295. {
  225296. struct statfs buf;
  225297. if (juce_doStatFS (*this, buf))
  225298. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  225299. return 0;
  225300. }
  225301. int64 File::getVolumeTotalSize() const
  225302. {
  225303. struct statfs buf;
  225304. if (juce_doStatFS (*this, buf))
  225305. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  225306. return 0;
  225307. }
  225308. const String File::getVolumeLabel() const
  225309. {
  225310. #if JUCE_MAC
  225311. struct VolAttrBuf
  225312. {
  225313. u_int32_t length;
  225314. attrreference_t mountPointRef;
  225315. char mountPointSpace [MAXPATHLEN];
  225316. } attrBuf;
  225317. struct attrlist attrList;
  225318. zerostruct (attrList);
  225319. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  225320. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  225321. File f (*this);
  225322. for (;;)
  225323. {
  225324. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  225325. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  225326. (int) attrBuf.mountPointRef.attr_length);
  225327. const File parent (f.getParentDirectory());
  225328. if (f == parent)
  225329. break;
  225330. f = parent;
  225331. }
  225332. #endif
  225333. return String::empty;
  225334. }
  225335. int File::getVolumeSerialNumber() const
  225336. {
  225337. return 0; // xxx
  225338. }
  225339. void juce_runSystemCommand (const String& command)
  225340. {
  225341. int result = system (command.toUTF8());
  225342. (void) result;
  225343. }
  225344. const String juce_getOutputFromCommand (const String& command)
  225345. {
  225346. // slight bodge here, as we just pipe the output into a temp file and read it...
  225347. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  225348. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  225349. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  225350. String result (tempFile.loadFileAsString());
  225351. tempFile.deleteFile();
  225352. return result;
  225353. }
  225354. class InterProcessLock::Pimpl
  225355. {
  225356. public:
  225357. Pimpl (const String& name, const int timeOutMillisecs)
  225358. : handle (0), refCount (1)
  225359. {
  225360. #if JUCE_MAC
  225361. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  225362. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  225363. #else
  225364. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  225365. #endif
  225366. temp.create();
  225367. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  225368. if (handle != 0)
  225369. {
  225370. struct flock fl;
  225371. zerostruct (fl);
  225372. fl.l_whence = SEEK_SET;
  225373. fl.l_type = F_WRLCK;
  225374. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  225375. for (;;)
  225376. {
  225377. const int result = fcntl (handle, F_SETLK, &fl);
  225378. if (result >= 0)
  225379. return;
  225380. if (errno != EINTR)
  225381. {
  225382. if (timeOutMillisecs == 0
  225383. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  225384. break;
  225385. Thread::sleep (10);
  225386. }
  225387. }
  225388. }
  225389. closeFile();
  225390. }
  225391. ~Pimpl()
  225392. {
  225393. closeFile();
  225394. }
  225395. void closeFile()
  225396. {
  225397. if (handle != 0)
  225398. {
  225399. struct flock fl;
  225400. zerostruct (fl);
  225401. fl.l_whence = SEEK_SET;
  225402. fl.l_type = F_UNLCK;
  225403. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  225404. {}
  225405. close (handle);
  225406. handle = 0;
  225407. }
  225408. }
  225409. int handle, refCount;
  225410. };
  225411. InterProcessLock::InterProcessLock (const String& name_)
  225412. : name (name_)
  225413. {
  225414. }
  225415. InterProcessLock::~InterProcessLock()
  225416. {
  225417. }
  225418. bool InterProcessLock::enter (const int timeOutMillisecs)
  225419. {
  225420. const ScopedLock sl (lock);
  225421. if (pimpl == 0)
  225422. {
  225423. pimpl = new Pimpl (name, timeOutMillisecs);
  225424. if (pimpl->handle == 0)
  225425. pimpl = 0;
  225426. }
  225427. else
  225428. {
  225429. pimpl->refCount++;
  225430. }
  225431. return pimpl != 0;
  225432. }
  225433. void InterProcessLock::exit()
  225434. {
  225435. const ScopedLock sl (lock);
  225436. // Trying to release the lock too many times!
  225437. jassert (pimpl != 0);
  225438. if (pimpl != 0 && --(pimpl->refCount) == 0)
  225439. pimpl = 0;
  225440. }
  225441. void JUCE_API juce_threadEntryPoint (void*);
  225442. void* threadEntryProc (void* userData)
  225443. {
  225444. JUCE_AUTORELEASEPOOL
  225445. juce_threadEntryPoint (userData);
  225446. return 0;
  225447. }
  225448. void* juce_createThread (void* userData)
  225449. {
  225450. pthread_t handle = 0;
  225451. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  225452. {
  225453. pthread_detach (handle);
  225454. return (void*) handle;
  225455. }
  225456. return 0;
  225457. }
  225458. void juce_killThread (void* handle)
  225459. {
  225460. if (handle != 0)
  225461. pthread_cancel ((pthread_t) handle);
  225462. }
  225463. void juce_setCurrentThreadName (const String& /*name*/)
  225464. {
  225465. }
  225466. bool juce_setThreadPriority (void* handle, int priority)
  225467. {
  225468. struct sched_param param;
  225469. int policy;
  225470. priority = jlimit (0, 10, priority);
  225471. if (handle == 0)
  225472. handle = (void*) pthread_self();
  225473. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  225474. return false;
  225475. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  225476. const int minPriority = sched_get_priority_min (policy);
  225477. const int maxPriority = sched_get_priority_max (policy);
  225478. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  225479. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  225480. }
  225481. Thread::ThreadID Thread::getCurrentThreadId()
  225482. {
  225483. return (ThreadID) pthread_self();
  225484. }
  225485. void Thread::yield()
  225486. {
  225487. sched_yield();
  225488. }
  225489. /* Remove this macro if you're having problems compiling the cpu affinity
  225490. calls (the API for these has changed about quite a bit in various Linux
  225491. versions, and a lot of distros seem to ship with obsolete versions)
  225492. */
  225493. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  225494. #define SUPPORT_AFFINITIES 1
  225495. #endif
  225496. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  225497. {
  225498. #if SUPPORT_AFFINITIES
  225499. cpu_set_t affinity;
  225500. CPU_ZERO (&affinity);
  225501. for (int i = 0; i < 32; ++i)
  225502. if ((affinityMask & (1 << i)) != 0)
  225503. CPU_SET (i, &affinity);
  225504. /*
  225505. N.B. If this line causes a compile error, then you've probably not got the latest
  225506. version of glibc installed.
  225507. If you don't want to update your copy of glibc and don't care about cpu affinities,
  225508. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  225509. */
  225510. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  225511. sched_yield();
  225512. #else
  225513. /* affinities aren't supported because either the appropriate header files weren't found,
  225514. or the SUPPORT_AFFINITIES macro was turned off
  225515. */
  225516. jassertfalse;
  225517. #endif
  225518. }
  225519. /*** End of inlined file: juce_posix_SharedCode.h ***/
  225520. /*** Start of inlined file: juce_mac_Files.mm ***/
  225521. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225522. // compiled on its own).
  225523. #if JUCE_INCLUDED_FILE
  225524. /*
  225525. Note that a lot of methods that you'd expect to find in this file actually
  225526. live in juce_posix_SharedCode.h!
  225527. */
  225528. bool File::copyInternal (const File& dest) const
  225529. {
  225530. const ScopedAutoReleasePool pool;
  225531. NSFileManager* fm = [NSFileManager defaultManager];
  225532. return [fm fileExistsAtPath: juceStringToNS (fullPath)]
  225533. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  225534. && [fm copyItemAtPath: juceStringToNS (fullPath)
  225535. toPath: juceStringToNS (dest.getFullPathName())
  225536. error: nil];
  225537. #else
  225538. && [fm copyPath: juceStringToNS (fullPath)
  225539. toPath: juceStringToNS (dest.getFullPathName())
  225540. handler: nil];
  225541. #endif
  225542. }
  225543. void File::findFileSystemRoots (Array<File>& destArray)
  225544. {
  225545. destArray.add (File ("/"));
  225546. }
  225547. static bool isFileOnDriveType (const File& f, const char* const* types)
  225548. {
  225549. struct statfs buf;
  225550. if (juce_doStatFS (f, buf))
  225551. {
  225552. const String type (buf.f_fstypename);
  225553. while (*types != 0)
  225554. if (type.equalsIgnoreCase (*types++))
  225555. return true;
  225556. }
  225557. return false;
  225558. }
  225559. bool File::isOnCDRomDrive() const
  225560. {
  225561. const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  225562. return isFileOnDriveType (*this, cdTypes);
  225563. }
  225564. bool File::isOnHardDisk() const
  225565. {
  225566. const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  225567. return ! (isOnCDRomDrive() || isFileOnDriveType (*this, nonHDTypes));
  225568. }
  225569. bool File::isOnRemovableDrive() const
  225570. {
  225571. #if JUCE_IOS
  225572. return false; // xxx is this possible?
  225573. #else
  225574. const ScopedAutoReleasePool pool;
  225575. BOOL removable = false;
  225576. [[NSWorkspace sharedWorkspace]
  225577. getFileSystemInfoForPath: juceStringToNS (getFullPathName())
  225578. isRemovable: &removable
  225579. isWritable: nil
  225580. isUnmountable: nil
  225581. description: nil
  225582. type: nil];
  225583. return removable;
  225584. #endif
  225585. }
  225586. static bool juce_isHiddenFile (const String& path)
  225587. {
  225588. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  225589. const ScopedAutoReleasePool pool;
  225590. NSNumber* hidden = nil;
  225591. NSError* err = nil;
  225592. return [[NSURL fileURLWithPath: juceStringToNS (path)]
  225593. getResourceValue: &hidden forKey: NSURLIsHiddenKey error: &err]
  225594. && [hidden boolValue];
  225595. #else
  225596. #if JUCE_IOS
  225597. return File (path).getFileName().startsWithChar ('.');
  225598. #else
  225599. FSRef ref;
  225600. LSItemInfoRecord info;
  225601. return FSPathMakeRefWithOptions ((const UInt8*) path.toUTF8(), kFSPathMakeRefDoNotFollowLeafSymlink, &ref, 0) == noErr
  225602. && LSCopyItemInfoForRef (&ref, kLSRequestBasicFlagsOnly, &info) == noErr
  225603. && (info.flags & kLSItemInfoIsInvisible) != 0;
  225604. #endif
  225605. #endif
  225606. }
  225607. bool File::isHidden() const
  225608. {
  225609. return juce_isHiddenFile (getFullPathName());
  225610. }
  225611. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  225612. const File File::getSpecialLocation (const SpecialLocationType type)
  225613. {
  225614. const ScopedAutoReleasePool pool;
  225615. String resultPath;
  225616. switch (type)
  225617. {
  225618. case userHomeDirectory: resultPath = nsStringToJuce (NSHomeDirectory()); break;
  225619. case userDocumentsDirectory: resultPath = "~/Documents"; break;
  225620. case userDesktopDirectory: resultPath = "~/Desktop"; break;
  225621. case userApplicationDataDirectory: resultPath = "~/Library"; break;
  225622. case commonApplicationDataDirectory: resultPath = "/Library"; break;
  225623. case globalApplicationsDirectory: resultPath = "/Applications"; break;
  225624. case userMusicDirectory: resultPath = "~/Music"; break;
  225625. case userMoviesDirectory: resultPath = "~/Movies"; break;
  225626. case tempDirectory:
  225627. {
  225628. File tmp ("~/Library/Caches/" + juce_getExecutableFile().getFileNameWithoutExtension());
  225629. tmp.createDirectory();
  225630. return tmp.getFullPathName();
  225631. }
  225632. case invokedExecutableFile:
  225633. if (juce_Argv0 != 0)
  225634. return File (String::fromUTF8 (juce_Argv0));
  225635. // deliberate fall-through...
  225636. case currentExecutableFile:
  225637. return juce_getExecutableFile();
  225638. case currentApplicationFile:
  225639. {
  225640. const File exe (juce_getExecutableFile());
  225641. const File parent (exe.getParentDirectory());
  225642. return parent.getFullPathName().endsWithIgnoreCase ("Contents/MacOS")
  225643. ? parent.getParentDirectory().getParentDirectory()
  225644. : exe;
  225645. }
  225646. case hostApplicationPath:
  225647. {
  225648. unsigned int size = 8192;
  225649. HeapBlock<char> buffer;
  225650. buffer.calloc (size + 8);
  225651. _NSGetExecutablePath (buffer.getData(), &size);
  225652. return String::fromUTF8 (buffer, size);
  225653. }
  225654. default:
  225655. jassertfalse; // unknown type?
  225656. break;
  225657. }
  225658. if (resultPath.isNotEmpty())
  225659. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  225660. return File::nonexistent;
  225661. }
  225662. const String File::getVersion() const
  225663. {
  225664. const ScopedAutoReleasePool pool;
  225665. String result;
  225666. NSBundle* bundle = [NSBundle bundleWithPath: juceStringToNS (getFullPathName())];
  225667. if (bundle != 0)
  225668. {
  225669. NSDictionary* info = [bundle infoDictionary];
  225670. if (info != 0)
  225671. {
  225672. NSString* name = [info valueForKey: @"CFBundleShortVersionString"];
  225673. if (name != nil)
  225674. result = nsStringToJuce (name);
  225675. }
  225676. }
  225677. return result;
  225678. }
  225679. const File File::getLinkedTarget() const
  225680. {
  225681. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5)
  225682. NSString* dest = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath: juceStringToNS (getFullPathName()) error: nil];
  225683. #else
  225684. // (the cast here avoids a deprecation warning)
  225685. NSString* dest = [((id) [NSFileManager defaultManager]) pathContentOfSymbolicLinkAtPath: juceStringToNS (getFullPathName())];
  225686. #endif
  225687. if (dest != nil)
  225688. return File (nsStringToJuce (dest));
  225689. return *this;
  225690. }
  225691. bool File::moveToTrash() const
  225692. {
  225693. if (! exists())
  225694. return true;
  225695. #if JUCE_IOS
  225696. return deleteFile(); //xxx is there a trashcan on the iPhone?
  225697. #else
  225698. const ScopedAutoReleasePool pool;
  225699. NSString* p = juceStringToNS (getFullPathName());
  225700. return [[NSWorkspace sharedWorkspace]
  225701. performFileOperation: NSWorkspaceRecycleOperation
  225702. source: [p stringByDeletingLastPathComponent]
  225703. destination: @""
  225704. files: [NSArray arrayWithObject: [p lastPathComponent]]
  225705. tag: nil ];
  225706. #endif
  225707. }
  225708. class DirectoryIterator::NativeIterator::Pimpl
  225709. {
  225710. public:
  225711. Pimpl (const File& directory, const String& wildCard_)
  225712. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  225713. wildCard (wildCard_),
  225714. enumerator (0)
  225715. {
  225716. const ScopedAutoReleasePool pool;
  225717. enumerator = [[[NSFileManager defaultManager] enumeratorAtPath: juceStringToNS (directory.getFullPathName())] retain];
  225718. wildcardUTF8 = wildCard.toUTF8();
  225719. }
  225720. ~Pimpl()
  225721. {
  225722. [enumerator release];
  225723. }
  225724. bool next (String& filenameFound,
  225725. bool* const isDir, bool* const isHidden, int64* const fileSize,
  225726. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  225727. {
  225728. const ScopedAutoReleasePool pool;
  225729. for (;;)
  225730. {
  225731. NSString* file;
  225732. if (enumerator == 0 || (file = [enumerator nextObject]) == 0)
  225733. return false;
  225734. [enumerator skipDescendents];
  225735. filenameFound = nsStringToJuce (file);
  225736. if (fnmatch (wildcardUTF8, filenameFound.toUTF8(), FNM_CASEFOLD) != 0)
  225737. continue;
  225738. const String path (parentDir + filenameFound);
  225739. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  225740. {
  225741. juce_statStruct info;
  225742. const bool statOk = juce_stat (path, info);
  225743. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  225744. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  225745. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  225746. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  225747. }
  225748. if (isHidden != 0)
  225749. *isHidden = juce_isHiddenFile (path);
  225750. if (isReadOnly != 0)
  225751. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  225752. return true;
  225753. }
  225754. }
  225755. private:
  225756. String parentDir, wildCard;
  225757. const char* wildcardUTF8;
  225758. NSDirectoryEnumerator* enumerator;
  225759. Pimpl (const Pimpl&);
  225760. Pimpl& operator= (const Pimpl&);
  225761. };
  225762. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  225763. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  225764. {
  225765. }
  225766. DirectoryIterator::NativeIterator::~NativeIterator()
  225767. {
  225768. }
  225769. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  225770. bool* const isDir, bool* const isHidden, int64* const fileSize,
  225771. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  225772. {
  225773. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  225774. }
  225775. bool juce_launchExecutable (const String& pathAndArguments)
  225776. {
  225777. const char* const argv[4] = { "/bin/sh", "-c", pathAndArguments.toUTF8(), 0 };
  225778. const int cpid = fork();
  225779. if (cpid == 0)
  225780. {
  225781. // Child process
  225782. if (execve (argv[0], (char**) argv, 0) < 0)
  225783. exit (0);
  225784. }
  225785. else
  225786. {
  225787. if (cpid < 0)
  225788. return false;
  225789. }
  225790. return true;
  225791. }
  225792. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  225793. {
  225794. #if JUCE_IOS
  225795. return [[UIApplication sharedApplication] openURL: [NSURL fileURLWithPath: juceStringToNS (fileName)]];
  225796. #else
  225797. const ScopedAutoReleasePool pool;
  225798. if (parameters.isEmpty())
  225799. {
  225800. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)]
  225801. || [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: juceStringToNS (fileName)]];
  225802. }
  225803. bool ok = false;
  225804. if (PlatformUtilities::isBundle (fileName))
  225805. {
  225806. NSMutableArray* urls = [NSMutableArray array];
  225807. StringArray docs;
  225808. docs.addTokens (parameters, true);
  225809. for (int i = 0; i < docs.size(); ++i)
  225810. [urls addObject: juceStringToNS (docs[i])];
  225811. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  225812. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  225813. options: 0
  225814. additionalEventParamDescriptor: nil
  225815. launchIdentifiers: nil];
  225816. }
  225817. else if (File (fileName).exists())
  225818. {
  225819. ok = juce_launchExecutable ("\"" + fileName + "\" " + parameters);
  225820. }
  225821. return ok;
  225822. #endif
  225823. }
  225824. void File::revealToUser() const
  225825. {
  225826. #if ! JUCE_IOS
  225827. if (exists())
  225828. [[NSWorkspace sharedWorkspace] selectFile: juceStringToNS (getFullPathName()) inFileViewerRootedAtPath: @""];
  225829. else if (getParentDirectory().exists())
  225830. getParentDirectory().revealToUser();
  225831. #endif
  225832. }
  225833. #if ! JUCE_IOS
  225834. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  225835. {
  225836. return FSPathMakeRef ((const UInt8*) path.toUTF8(), destFSRef, 0) == noErr;
  225837. }
  225838. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  225839. {
  225840. char path [2048];
  225841. zerostruct (path);
  225842. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  225843. return PlatformUtilities::convertToPrecomposedUnicode (String::fromUTF8 (path));
  225844. return String::empty;
  225845. }
  225846. #endif
  225847. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  225848. {
  225849. const ScopedAutoReleasePool pool;
  225850. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5)
  225851. NSDictionary* fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath: juceStringToNS (filename) error: nil];
  225852. #else
  225853. // (the cast here avoids a deprecation warning)
  225854. NSDictionary* fileDict = [((id) [NSFileManager defaultManager]) fileAttributesAtPath: juceStringToNS (filename) traverseLink: NO];
  225855. #endif
  225856. return [fileDict fileHFSTypeCode];
  225857. }
  225858. bool PlatformUtilities::isBundle (const String& filename)
  225859. {
  225860. #if JUCE_IOS
  225861. return false; // xxx can't find a sensible way to do this without trying to open the bundle..
  225862. #else
  225863. const ScopedAutoReleasePool pool;
  225864. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  225865. #endif
  225866. }
  225867. #endif
  225868. /*** End of inlined file: juce_mac_Files.mm ***/
  225869. #if JUCE_IOS
  225870. /*** Start of inlined file: juce_iphone_MiscUtilities.mm ***/
  225871. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225872. // compiled on its own).
  225873. #if JUCE_INCLUDED_FILE
  225874. END_JUCE_NAMESPACE
  225875. @interface JuceAppStartupDelegate : NSObject <UIApplicationDelegate>
  225876. {
  225877. }
  225878. - (void) applicationDidFinishLaunching: (UIApplication*) application;
  225879. - (void) applicationWillTerminate: (UIApplication*) application;
  225880. @end
  225881. @implementation JuceAppStartupDelegate
  225882. - (void) applicationDidFinishLaunching: (UIApplication*) application
  225883. {
  225884. initialiseJuce_GUI();
  225885. if (! JUCEApplication::createInstance()->initialiseApp (String::empty))
  225886. exit (0);
  225887. }
  225888. - (void) applicationWillTerminate: (UIApplication*) application
  225889. {
  225890. JUCEApplication::appWillTerminateByForce();
  225891. }
  225892. @end
  225893. BEGIN_JUCE_NAMESPACE
  225894. int juce_iOSMain (int argc, const char* argv[])
  225895. {
  225896. return UIApplicationMain (argc, const_cast<char**> (argv), nil, @"JuceAppStartupDelegate");
  225897. }
  225898. ScopedAutoReleasePool::ScopedAutoReleasePool()
  225899. {
  225900. pool = [[NSAutoreleasePool alloc] init];
  225901. }
  225902. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  225903. {
  225904. [((NSAutoreleasePool*) pool) release];
  225905. }
  225906. void PlatformUtilities::beep()
  225907. {
  225908. //xxx
  225909. //AudioServicesPlaySystemSound ();
  225910. }
  225911. void PlatformUtilities::addItemToDock (const File& file)
  225912. {
  225913. }
  225914. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  225915. END_JUCE_NAMESPACE
  225916. @interface JuceAlertBoxDelegate : NSObject
  225917. {
  225918. @public
  225919. bool clickedOk;
  225920. }
  225921. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex;
  225922. @end
  225923. @implementation JuceAlertBoxDelegate
  225924. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex
  225925. {
  225926. clickedOk = (buttonIndex == 0);
  225927. alertView.hidden = true;
  225928. }
  225929. @end
  225930. BEGIN_JUCE_NAMESPACE
  225931. // (This function is used directly by other bits of code)
  225932. bool juce_iPhoneShowModalAlert (const String& title,
  225933. const String& bodyText,
  225934. NSString* okButtonText,
  225935. NSString* cancelButtonText)
  225936. {
  225937. const ScopedAutoReleasePool pool;
  225938. JuceAlertBoxDelegate* callback = [[JuceAlertBoxDelegate alloc] init];
  225939. UIAlertView* alert = [[UIAlertView alloc] initWithTitle: juceStringToNS (title)
  225940. message: juceStringToNS (bodyText)
  225941. delegate: callback
  225942. cancelButtonTitle: okButtonText
  225943. otherButtonTitles: cancelButtonText, nil];
  225944. [alert retain];
  225945. [alert show];
  225946. while (! alert.hidden && alert.superview != nil)
  225947. [[NSRunLoop mainRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  225948. const bool result = callback->clickedOk;
  225949. [alert release];
  225950. [callback release];
  225951. return result;
  225952. }
  225953. bool AlertWindow::showNativeDialogBox (const String& title,
  225954. const String& bodyText,
  225955. bool isOkCancel)
  225956. {
  225957. return juce_iPhoneShowModalAlert (title, bodyText,
  225958. @"OK",
  225959. isOkCancel ? @"Cancel" : nil);
  225960. }
  225961. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  225962. {
  225963. jassertfalse; // no such thing on the iphone!
  225964. return false;
  225965. }
  225966. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  225967. {
  225968. jassertfalse; // no such thing on the iphone!
  225969. return false;
  225970. }
  225971. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  225972. {
  225973. [[UIApplication sharedApplication] setIdleTimerDisabled: ! isEnabled];
  225974. }
  225975. bool Desktop::isScreenSaverEnabled()
  225976. {
  225977. return ! [[UIApplication sharedApplication] isIdleTimerDisabled];
  225978. }
  225979. void juce_updateMultiMonitorInfo (Array <Rectangle <int> >& monitorCoords, const bool clipToWorkArea)
  225980. {
  225981. const ScopedAutoReleasePool pool;
  225982. monitorCoords.clear();
  225983. CGRect r = clipToWorkArea ? [[UIScreen mainScreen] applicationFrame]
  225984. : [[UIScreen mainScreen] bounds];
  225985. monitorCoords.add (Rectangle<int> ((int) r.origin.x,
  225986. (int) r.origin.y,
  225987. (int) r.size.width,
  225988. (int) r.size.height));
  225989. }
  225990. #endif
  225991. #endif
  225992. /*** End of inlined file: juce_iphone_MiscUtilities.mm ***/
  225993. #else
  225994. /*** Start of inlined file: juce_mac_MiscUtilities.mm ***/
  225995. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225996. // compiled on its own).
  225997. #if JUCE_INCLUDED_FILE
  225998. ScopedAutoReleasePool::ScopedAutoReleasePool()
  225999. {
  226000. pool = [[NSAutoreleasePool alloc] init];
  226001. }
  226002. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  226003. {
  226004. [((NSAutoreleasePool*) pool) release];
  226005. }
  226006. void PlatformUtilities::beep()
  226007. {
  226008. NSBeep();
  226009. }
  226010. void PlatformUtilities::addItemToDock (const File& file)
  226011. {
  226012. // check that it's not already there...
  226013. if (! juce_getOutputFromCommand ("defaults read com.apple.dock persistent-apps")
  226014. .containsIgnoreCase (file.getFullPathName()))
  226015. {
  226016. 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>"
  226017. + file.getFullPathName() + "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\"");
  226018. juce_runSystemCommand ("osascript -e \"tell application \\\"Dock\\\" to quit\"");
  226019. }
  226020. }
  226021. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  226022. bool AlertWindow::showNativeDialogBox (const String& title,
  226023. const String& bodyText,
  226024. bool isOkCancel)
  226025. {
  226026. const ScopedAutoReleasePool pool;
  226027. return NSRunAlertPanel (juceStringToNS (title),
  226028. juceStringToNS (bodyText),
  226029. @"Ok",
  226030. isOkCancel ? @"Cancel" : nil,
  226031. nil) == NSAlertDefaultReturn;
  226032. }
  226033. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool /*canMoveFiles*/)
  226034. {
  226035. if (files.size() == 0)
  226036. return false;
  226037. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0);
  226038. if (draggingSource == 0)
  226039. {
  226040. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  226041. return false;
  226042. }
  226043. Component* sourceComp = draggingSource->getComponentUnderMouse();
  226044. if (sourceComp == 0)
  226045. {
  226046. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  226047. return false;
  226048. }
  226049. const ScopedAutoReleasePool pool;
  226050. NSView* view = (NSView*) sourceComp->getWindowHandle();
  226051. if (view == 0)
  226052. return false;
  226053. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  226054. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  226055. owner: nil];
  226056. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  226057. for (int i = 0; i < files.size(); ++i)
  226058. [filesArray addObject: juceStringToNS (files[i])];
  226059. [pboard setPropertyList: filesArray
  226060. forType: NSFilenamesPboardType];
  226061. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  226062. fromView: nil];
  226063. dragPosition.x -= 16;
  226064. dragPosition.y -= 16;
  226065. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  226066. at: dragPosition
  226067. offset: NSMakeSize (0, 0)
  226068. event: [[view window] currentEvent]
  226069. pasteboard: pboard
  226070. source: view
  226071. slideBack: YES];
  226072. return true;
  226073. }
  226074. bool DragAndDropContainer::performExternalDragDropOfText (const String& /*text*/)
  226075. {
  226076. jassertfalse; // not implemented!
  226077. return false;
  226078. }
  226079. bool Desktop::canUseSemiTransparentWindows() throw()
  226080. {
  226081. return true;
  226082. }
  226083. const Point<int> Desktop::getMousePosition()
  226084. {
  226085. const ScopedAutoReleasePool pool;
  226086. const NSPoint p ([NSEvent mouseLocation]);
  226087. return Point<int> (roundToInt (p.x), roundToInt ([[[NSScreen screens] objectAtIndex: 0] frame].size.height - p.y));
  226088. }
  226089. void Desktop::setMousePosition (const Point<int>& newPosition)
  226090. {
  226091. // this rubbish needs to be done around the warp call, to avoid causing a
  226092. // bizarre glitch..
  226093. CGAssociateMouseAndMouseCursorPosition (false);
  226094. CGWarpMouseCursorPosition (CGPointMake (newPosition.getX(), newPosition.getY()));
  226095. CGAssociateMouseAndMouseCursorPosition (true);
  226096. }
  226097. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226098. class ScreenSaverDefeater : public Timer,
  226099. public DeletedAtShutdown
  226100. {
  226101. public:
  226102. ScreenSaverDefeater()
  226103. {
  226104. startTimer (10000);
  226105. timerCallback();
  226106. }
  226107. ~ScreenSaverDefeater() {}
  226108. void timerCallback()
  226109. {
  226110. if (Process::isForegroundProcess())
  226111. UpdateSystemActivity (UsrActivity);
  226112. }
  226113. };
  226114. static ScreenSaverDefeater* screenSaverDefeater = 0;
  226115. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  226116. {
  226117. if (isEnabled)
  226118. deleteAndZero (screenSaverDefeater);
  226119. else if (screenSaverDefeater == 0)
  226120. screenSaverDefeater = new ScreenSaverDefeater();
  226121. }
  226122. bool Desktop::isScreenSaverEnabled()
  226123. {
  226124. return screenSaverDefeater == 0;
  226125. }
  226126. #else
  226127. static IOPMAssertionID screenSaverDisablerID = 0;
  226128. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  226129. {
  226130. if (isEnabled)
  226131. {
  226132. if (screenSaverDisablerID != 0)
  226133. {
  226134. IOPMAssertionRelease (screenSaverDisablerID);
  226135. screenSaverDisablerID = 0;
  226136. }
  226137. }
  226138. else
  226139. {
  226140. if (screenSaverDisablerID == 0)
  226141. {
  226142. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  226143. IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  226144. CFSTR ("Juce"), &screenSaverDisablerID);
  226145. #else
  226146. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  226147. &screenSaverDisablerID);
  226148. #endif
  226149. }
  226150. }
  226151. }
  226152. bool Desktop::isScreenSaverEnabled()
  226153. {
  226154. return screenSaverDisablerID == 0;
  226155. }
  226156. #endif
  226157. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  226158. {
  226159. const ScopedAutoReleasePool pool;
  226160. monitorCoords.clear();
  226161. NSArray* screens = [NSScreen screens];
  226162. const CGFloat mainScreenBottom = [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  226163. for (unsigned int i = 0; i < [screens count]; ++i)
  226164. {
  226165. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  226166. NSRect r = clipToWorkArea ? [s visibleFrame]
  226167. : [s frame];
  226168. monitorCoords.add (Rectangle<int> ((int) r.origin.x,
  226169. (int) (mainScreenBottom - (r.origin.y + r.size.height)),
  226170. (int) r.size.width,
  226171. (int) r.size.height));
  226172. }
  226173. jassert (monitorCoords.size() > 0);
  226174. }
  226175. #endif
  226176. #endif
  226177. /*** End of inlined file: juce_mac_MiscUtilities.mm ***/
  226178. #endif
  226179. /*** Start of inlined file: juce_mac_Debugging.mm ***/
  226180. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226181. // compiled on its own).
  226182. #if JUCE_INCLUDED_FILE
  226183. void Logger::outputDebugString (const String& text)
  226184. {
  226185. std::cerr << text << std::endl;
  226186. }
  226187. bool JUCE_PUBLIC_FUNCTION juce_isRunningUnderDebugger()
  226188. {
  226189. static char testResult = 0;
  226190. if (testResult == 0)
  226191. {
  226192. struct kinfo_proc info;
  226193. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  226194. size_t sz = sizeof (info);
  226195. sysctl (m, 4, &info, &sz, 0, 0);
  226196. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  226197. }
  226198. return testResult > 0;
  226199. }
  226200. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  226201. {
  226202. return juce_isRunningUnderDebugger();
  226203. }
  226204. #endif
  226205. /*** End of inlined file: juce_mac_Debugging.mm ***/
  226206. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  226207. #if JUCE_IOS
  226208. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  226209. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226210. // compiled on its own).
  226211. #if JUCE_INCLUDED_FILE
  226212. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226213. #define SUPPORT_10_4_FONTS 1
  226214. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  226215. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  226216. #define SUPPORT_ONLY_10_4_FONTS 1
  226217. #endif
  226218. END_JUCE_NAMESPACE
  226219. @interface NSFont (PrivateHack)
  226220. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  226221. @end
  226222. BEGIN_JUCE_NAMESPACE
  226223. #endif
  226224. class MacTypeface : public Typeface
  226225. {
  226226. public:
  226227. MacTypeface (const Font& font)
  226228. : Typeface (font.getTypefaceName())
  226229. {
  226230. const ScopedAutoReleasePool pool;
  226231. renderingTransform = CGAffineTransformIdentity;
  226232. bool needsItalicTransform = false;
  226233. #if JUCE_IOS
  226234. NSString* fontName = juceStringToNS (font.getTypefaceName());
  226235. if (font.isItalic() || font.isBold())
  226236. {
  226237. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  226238. for (NSString* i in familyFonts)
  226239. {
  226240. const String fn (nsStringToJuce (i));
  226241. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  226242. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  226243. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  226244. || afterDash.containsIgnoreCase ("italic")
  226245. || fn.endsWithIgnoreCase ("oblique")
  226246. || fn.endsWithIgnoreCase ("italic");
  226247. if (probablyBold == font.isBold()
  226248. && probablyItalic == font.isItalic())
  226249. {
  226250. fontName = i;
  226251. needsItalicTransform = false;
  226252. break;
  226253. }
  226254. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  226255. {
  226256. fontName = i;
  226257. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  226258. }
  226259. }
  226260. if (needsItalicTransform)
  226261. renderingTransform.c = 0.15f;
  226262. }
  226263. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  226264. const int ascender = abs (CGFontGetAscent (fontRef));
  226265. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  226266. ascent = ascender / totalHeight;
  226267. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226268. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  226269. #else
  226270. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  226271. if (font.isItalic())
  226272. {
  226273. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  226274. toHaveTrait: NSItalicFontMask];
  226275. if (newFont == nsFont)
  226276. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  226277. nsFont = newFont;
  226278. }
  226279. if (font.isBold())
  226280. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  226281. [nsFont retain];
  226282. ascent = std::abs ((float) [nsFont ascender]);
  226283. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  226284. ascent /= totalSize;
  226285. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  226286. if (needsItalicTransform)
  226287. {
  226288. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  226289. renderingTransform.c = 0.15f;
  226290. }
  226291. #if SUPPORT_ONLY_10_4_FONTS
  226292. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226293. if (atsFont == 0)
  226294. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226295. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  226296. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  226297. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226298. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  226299. #else
  226300. #if SUPPORT_10_4_FONTS
  226301. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226302. {
  226303. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226304. if (atsFont == 0)
  226305. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226306. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  226307. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  226308. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226309. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  226310. }
  226311. else
  226312. #endif
  226313. {
  226314. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  226315. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  226316. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226317. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  226318. }
  226319. #endif
  226320. #endif
  226321. }
  226322. ~MacTypeface()
  226323. {
  226324. #if ! JUCE_IOS
  226325. [nsFont release];
  226326. #endif
  226327. if (fontRef != 0)
  226328. CGFontRelease (fontRef);
  226329. }
  226330. float getAscent() const
  226331. {
  226332. return ascent;
  226333. }
  226334. float getDescent() const
  226335. {
  226336. return 1.0f - ascent;
  226337. }
  226338. float getStringWidth (const String& text)
  226339. {
  226340. if (fontRef == 0 || text.isEmpty())
  226341. return 0;
  226342. const int length = text.length();
  226343. HeapBlock <CGGlyph> glyphs;
  226344. createGlyphsForString (text, length, glyphs);
  226345. float x = 0;
  226346. #if SUPPORT_ONLY_10_4_FONTS
  226347. HeapBlock <NSSize> advances (length);
  226348. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  226349. for (int i = 0; i < length; ++i)
  226350. x += advances[i].width;
  226351. #else
  226352. #if SUPPORT_10_4_FONTS
  226353. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226354. {
  226355. HeapBlock <NSSize> advances (length);
  226356. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  226357. for (int i = 0; i < length; ++i)
  226358. x += advances[i].width;
  226359. }
  226360. else
  226361. #endif
  226362. {
  226363. HeapBlock <int> advances (length);
  226364. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  226365. for (int i = 0; i < length; ++i)
  226366. x += advances[i];
  226367. }
  226368. #endif
  226369. return x * unitsToHeightScaleFactor;
  226370. }
  226371. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  226372. {
  226373. xOffsets.add (0);
  226374. if (fontRef == 0 || text.isEmpty())
  226375. return;
  226376. const int length = text.length();
  226377. HeapBlock <CGGlyph> glyphs;
  226378. createGlyphsForString (text, length, glyphs);
  226379. #if SUPPORT_ONLY_10_4_FONTS
  226380. HeapBlock <NSSize> advances (length);
  226381. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  226382. int x = 0;
  226383. for (int i = 0; i < length; ++i)
  226384. {
  226385. x += advances[i].width;
  226386. xOffsets.add (x * unitsToHeightScaleFactor);
  226387. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  226388. }
  226389. #else
  226390. #if SUPPORT_10_4_FONTS
  226391. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226392. {
  226393. HeapBlock <NSSize> advances (length);
  226394. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  226395. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  226396. float x = 0;
  226397. for (int i = 0; i < length; ++i)
  226398. {
  226399. x += advances[i].width;
  226400. xOffsets.add (x * unitsToHeightScaleFactor);
  226401. resultGlyphs.add (nsGlyphs[i]);
  226402. }
  226403. }
  226404. else
  226405. #endif
  226406. {
  226407. HeapBlock <int> advances (length);
  226408. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  226409. {
  226410. int x = 0;
  226411. for (int i = 0; i < length; ++i)
  226412. {
  226413. x += advances [i];
  226414. xOffsets.add (x * unitsToHeightScaleFactor);
  226415. resultGlyphs.add (glyphs[i]);
  226416. }
  226417. }
  226418. }
  226419. #endif
  226420. }
  226421. bool getOutlineForGlyph (int glyphNumber, Path& path)
  226422. {
  226423. #if JUCE_IOS
  226424. return false;
  226425. #else
  226426. if (nsFont == 0)
  226427. return false;
  226428. // we might need to apply a transform to the path, so it mustn't have anything else in it
  226429. jassert (path.isEmpty());
  226430. const ScopedAutoReleasePool pool;
  226431. NSBezierPath* bez = [NSBezierPath bezierPath];
  226432. [bez moveToPoint: NSMakePoint (0, 0)];
  226433. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  226434. inFont: nsFont];
  226435. for (int i = 0; i < [bez elementCount]; ++i)
  226436. {
  226437. NSPoint p[3];
  226438. switch ([bez elementAtIndex: i associatedPoints: p])
  226439. {
  226440. case NSMoveToBezierPathElement:
  226441. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  226442. break;
  226443. case NSLineToBezierPathElement:
  226444. path.lineTo ((float) p[0].x, (float) -p[0].y);
  226445. break;
  226446. case NSCurveToBezierPathElement:
  226447. 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);
  226448. break;
  226449. case NSClosePathBezierPathElement:
  226450. path.closeSubPath();
  226451. break;
  226452. default:
  226453. jassertfalse;
  226454. break;
  226455. }
  226456. }
  226457. path.applyTransform (pathTransform);
  226458. return true;
  226459. #endif
  226460. }
  226461. juce_UseDebuggingNewOperator
  226462. CGFontRef fontRef;
  226463. float fontHeightToCGSizeFactor;
  226464. CGAffineTransform renderingTransform;
  226465. private:
  226466. float ascent, unitsToHeightScaleFactor;
  226467. #if JUCE_IOS
  226468. #else
  226469. NSFont* nsFont;
  226470. AffineTransform pathTransform;
  226471. #endif
  226472. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  226473. {
  226474. #if SUPPORT_10_4_FONTS
  226475. #if ! SUPPORT_ONLY_10_4_FONTS
  226476. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226477. #endif
  226478. {
  226479. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  226480. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  226481. for (int i = 0; i < length; ++i)
  226482. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  226483. return;
  226484. }
  226485. #endif
  226486. #if ! SUPPORT_ONLY_10_4_FONTS
  226487. if (charToGlyphMapper == 0)
  226488. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  226489. glyphs.malloc (length);
  226490. for (int i = 0; i < length; ++i)
  226491. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  226492. #endif
  226493. }
  226494. #if ! SUPPORT_ONLY_10_4_FONTS
  226495. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  226496. class CharToGlyphMapper
  226497. {
  226498. public:
  226499. CharToGlyphMapper (CGFontRef fontRef)
  226500. : segCount (0), endCode (0), startCode (0), idDelta (0),
  226501. idRangeOffset (0), glyphIndexes (0)
  226502. {
  226503. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  226504. if (cmapTable != 0)
  226505. {
  226506. const int numSubtables = getValue16 (cmapTable, 2);
  226507. for (int i = 0; i < numSubtables; ++i)
  226508. {
  226509. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  226510. {
  226511. const int offset = getValue32 (cmapTable, i * 8 + 8);
  226512. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  226513. {
  226514. const int length = getValue16 (cmapTable, offset + 2);
  226515. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  226516. segCount = segCountX2 / 2;
  226517. const int endCodeOffset = offset + 14;
  226518. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  226519. const int idDeltaOffset = startCodeOffset + segCountX2;
  226520. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  226521. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  226522. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  226523. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  226524. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  226525. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  226526. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  226527. }
  226528. break;
  226529. }
  226530. }
  226531. CFRelease (cmapTable);
  226532. }
  226533. }
  226534. ~CharToGlyphMapper()
  226535. {
  226536. if (endCode != 0)
  226537. {
  226538. CFRelease (endCode);
  226539. CFRelease (startCode);
  226540. CFRelease (idDelta);
  226541. CFRelease (idRangeOffset);
  226542. CFRelease (glyphIndexes);
  226543. }
  226544. }
  226545. int getGlyphForCharacter (const juce_wchar c) const
  226546. {
  226547. for (int i = 0; i < segCount; ++i)
  226548. {
  226549. if (getValue16 (endCode, i * 2) >= c)
  226550. {
  226551. const int start = getValue16 (startCode, i * 2);
  226552. if (start > c)
  226553. break;
  226554. const int delta = getValue16 (idDelta, i * 2);
  226555. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  226556. if (rangeOffset == 0)
  226557. return delta + c;
  226558. else
  226559. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  226560. }
  226561. }
  226562. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  226563. return jmax (-1, (int) c - 29);
  226564. }
  226565. private:
  226566. int segCount;
  226567. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  226568. static uint16 getValue16 (CFDataRef data, const int index)
  226569. {
  226570. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  226571. }
  226572. static uint32 getValue32 (CFDataRef data, const int index)
  226573. {
  226574. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  226575. }
  226576. };
  226577. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  226578. #endif
  226579. MacTypeface (const MacTypeface&);
  226580. MacTypeface& operator= (const MacTypeface&);
  226581. };
  226582. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  226583. {
  226584. return new MacTypeface (font);
  226585. }
  226586. const StringArray Font::findAllTypefaceNames()
  226587. {
  226588. StringArray names;
  226589. const ScopedAutoReleasePool pool;
  226590. #if JUCE_IOS
  226591. NSArray* fonts = [UIFont familyNames];
  226592. #else
  226593. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  226594. #endif
  226595. for (unsigned int i = 0; i < [fonts count]; ++i)
  226596. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  226597. names.sort (true);
  226598. return names;
  226599. }
  226600. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  226601. {
  226602. #if JUCE_IOS
  226603. defaultSans = "Helvetica";
  226604. defaultSerif = "Times New Roman";
  226605. defaultFixed = "Courier New";
  226606. #else
  226607. defaultSans = "Lucida Grande";
  226608. defaultSerif = "Times New Roman";
  226609. defaultFixed = "Monaco";
  226610. #endif
  226611. }
  226612. #endif
  226613. /*** End of inlined file: juce_mac_Fonts.mm ***/
  226614. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  226615. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226616. // compiled on its own).
  226617. #if JUCE_INCLUDED_FILE
  226618. class CoreGraphicsImage : public Image::SharedImage
  226619. {
  226620. public:
  226621. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  226622. : Image::SharedImage (format_, width_, height_)
  226623. {
  226624. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  226625. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  226626. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  226627. imageData = imageDataAllocated;
  226628. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  226629. : CGColorSpaceCreateDeviceRGB();
  226630. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  226631. colourSpace, getCGImageFlags (format_));
  226632. CGColorSpaceRelease (colourSpace);
  226633. }
  226634. ~CoreGraphicsImage()
  226635. {
  226636. CGContextRelease (context);
  226637. }
  226638. Image::ImageType getType() const { return Image::NativeImage; }
  226639. LowLevelGraphicsContext* createLowLevelContext();
  226640. SharedImage* clone()
  226641. {
  226642. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  226643. memcpy (im->imageData, imageData, lineStride * height);
  226644. return im;
  226645. }
  226646. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  226647. {
  226648. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  226649. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  226650. {
  226651. return CGBitmapContextCreateImage (nativeImage->context);
  226652. }
  226653. else
  226654. {
  226655. const Image::BitmapData srcData (juceImage, false);
  226656. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  226657. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  226658. 8, srcData.pixelStride * 8, srcData.lineStride,
  226659. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  226660. 0, true, kCGRenderingIntentDefault);
  226661. CGDataProviderRelease (provider);
  226662. return imageRef;
  226663. }
  226664. }
  226665. #if JUCE_MAC
  226666. static NSImage* createNSImage (const Image& image)
  226667. {
  226668. const ScopedAutoReleasePool pool;
  226669. NSImage* im = [[NSImage alloc] init];
  226670. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  226671. [im lockFocus];
  226672. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  226673. CGImageRef imageRef = createImage (image, false, colourSpace);
  226674. CGColorSpaceRelease (colourSpace);
  226675. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  226676. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  226677. CGImageRelease (imageRef);
  226678. [im unlockFocus];
  226679. return im;
  226680. }
  226681. #endif
  226682. CGContextRef context;
  226683. HeapBlock<uint8> imageDataAllocated;
  226684. private:
  226685. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  226686. {
  226687. #if JUCE_BIG_ENDIAN
  226688. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  226689. #else
  226690. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  226691. #endif
  226692. }
  226693. };
  226694. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  226695. {
  226696. #if USE_COREGRAPHICS_RENDERING
  226697. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  226698. #else
  226699. return createSoftwareImage (format, width, height, clearImage);
  226700. #endif
  226701. }
  226702. class CoreGraphicsContext : public LowLevelGraphicsContext
  226703. {
  226704. public:
  226705. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  226706. : context (context_),
  226707. flipHeight (flipHeight_),
  226708. state (new SavedState()),
  226709. numGradientLookupEntries (0),
  226710. lastClipRectIsValid (false)
  226711. {
  226712. CGContextRetain (context);
  226713. CGContextSaveGState(context);
  226714. CGContextSetShouldSmoothFonts (context, true);
  226715. CGContextSetShouldAntialias (context, true);
  226716. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226717. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  226718. greyColourSpace = CGColorSpaceCreateDeviceGray();
  226719. gradientCallbacks.version = 0;
  226720. gradientCallbacks.evaluate = gradientCallback;
  226721. gradientCallbacks.releaseInfo = 0;
  226722. setFont (Font());
  226723. }
  226724. ~CoreGraphicsContext()
  226725. {
  226726. CGContextRestoreGState (context);
  226727. CGContextRelease (context);
  226728. CGColorSpaceRelease (rgbColourSpace);
  226729. CGColorSpaceRelease (greyColourSpace);
  226730. }
  226731. bool isVectorDevice() const { return false; }
  226732. void setOrigin (int x, int y)
  226733. {
  226734. CGContextTranslateCTM (context, x, -y);
  226735. if (lastClipRectIsValid)
  226736. lastClipRect.translate (-x, -y);
  226737. }
  226738. bool clipToRectangle (const Rectangle<int>& r)
  226739. {
  226740. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  226741. if (lastClipRectIsValid)
  226742. {
  226743. // This is actually incorrect, because the actual clip region may be complex, and
  226744. // clipping its bounds to a rect may not be right... But, removing this shortcut
  226745. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  226746. // when calculating the resultant clip bounds, and makes the same mistake!
  226747. lastClipRect = lastClipRect.getIntersection (r);
  226748. return ! lastClipRect.isEmpty();
  226749. }
  226750. return ! isClipEmpty();
  226751. }
  226752. bool clipToRectangleList (const RectangleList& clipRegion)
  226753. {
  226754. if (clipRegion.isEmpty())
  226755. {
  226756. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  226757. lastClipRectIsValid = true;
  226758. lastClipRect = Rectangle<int>();
  226759. return false;
  226760. }
  226761. else
  226762. {
  226763. const int numRects = clipRegion.getNumRectangles();
  226764. HeapBlock <CGRect> rects (numRects);
  226765. for (int i = 0; i < numRects; ++i)
  226766. {
  226767. const Rectangle<int>& r = clipRegion.getRectangle(i);
  226768. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  226769. }
  226770. CGContextClipToRects (context, rects, numRects);
  226771. lastClipRectIsValid = false;
  226772. return ! isClipEmpty();
  226773. }
  226774. }
  226775. void excludeClipRectangle (const Rectangle<int>& r)
  226776. {
  226777. RectangleList remaining (getClipBounds());
  226778. remaining.subtract (r);
  226779. clipToRectangleList (remaining);
  226780. lastClipRectIsValid = false;
  226781. }
  226782. void clipToPath (const Path& path, const AffineTransform& transform)
  226783. {
  226784. createPath (path, transform);
  226785. CGContextClip (context);
  226786. lastClipRectIsValid = false;
  226787. }
  226788. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  226789. {
  226790. if (! transform.isSingularity())
  226791. {
  226792. Image singleChannelImage (sourceImage);
  226793. if (sourceImage.getFormat() != Image::SingleChannel)
  226794. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  226795. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  226796. flip();
  226797. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  226798. applyTransform (t);
  226799. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  226800. CGContextClipToMask (context, r, image);
  226801. applyTransform (t.inverted());
  226802. flip();
  226803. CGImageRelease (image);
  226804. lastClipRectIsValid = false;
  226805. }
  226806. }
  226807. bool clipRegionIntersects (const Rectangle<int>& r)
  226808. {
  226809. return getClipBounds().intersects (r);
  226810. }
  226811. const Rectangle<int> getClipBounds() const
  226812. {
  226813. if (! lastClipRectIsValid)
  226814. {
  226815. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  226816. lastClipRectIsValid = true;
  226817. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  226818. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  226819. roundToInt (bounds.size.width),
  226820. roundToInt (bounds.size.height));
  226821. }
  226822. return lastClipRect;
  226823. }
  226824. bool isClipEmpty() const
  226825. {
  226826. return getClipBounds().isEmpty();
  226827. }
  226828. void saveState()
  226829. {
  226830. CGContextSaveGState (context);
  226831. stateStack.add (new SavedState (*state));
  226832. }
  226833. void restoreState()
  226834. {
  226835. CGContextRestoreGState (context);
  226836. SavedState* const top = stateStack.getLast();
  226837. if (top != 0)
  226838. {
  226839. state = top;
  226840. stateStack.removeLast (1, false);
  226841. lastClipRectIsValid = false;
  226842. }
  226843. else
  226844. {
  226845. jassertfalse; // trying to pop with an empty stack!
  226846. }
  226847. }
  226848. void setFill (const FillType& fillType)
  226849. {
  226850. state->fillType = fillType;
  226851. if (fillType.isColour())
  226852. {
  226853. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  226854. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  226855. CGContextSetAlpha (context, 1.0f);
  226856. }
  226857. }
  226858. void setOpacity (float newOpacity)
  226859. {
  226860. state->fillType.setOpacity (newOpacity);
  226861. setFill (state->fillType);
  226862. }
  226863. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  226864. {
  226865. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  226866. ? kCGInterpolationLow
  226867. : kCGInterpolationHigh);
  226868. }
  226869. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  226870. {
  226871. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  226872. }
  226873. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  226874. {
  226875. if (replaceExistingContents)
  226876. {
  226877. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  226878. CGContextClearRect (context, cgRect);
  226879. #else
  226880. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226881. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  226882. CGContextClearRect (context, cgRect);
  226883. else
  226884. #endif
  226885. CGContextSetBlendMode (context, kCGBlendModeCopy);
  226886. #endif
  226887. fillCGRect (cgRect, false);
  226888. CGContextSetBlendMode (context, kCGBlendModeNormal);
  226889. }
  226890. else
  226891. {
  226892. if (state->fillType.isColour())
  226893. {
  226894. CGContextFillRect (context, cgRect);
  226895. }
  226896. else if (state->fillType.isGradient())
  226897. {
  226898. CGContextSaveGState (context);
  226899. CGContextClipToRect (context, cgRect);
  226900. drawGradient();
  226901. CGContextRestoreGState (context);
  226902. }
  226903. else
  226904. {
  226905. CGContextSaveGState (context);
  226906. CGContextClipToRect (context, cgRect);
  226907. drawImage (state->fillType.image, state->fillType.transform, true);
  226908. CGContextRestoreGState (context);
  226909. }
  226910. }
  226911. }
  226912. void fillPath (const Path& path, const AffineTransform& transform)
  226913. {
  226914. CGContextSaveGState (context);
  226915. if (state->fillType.isColour())
  226916. {
  226917. flip();
  226918. applyTransform (transform);
  226919. createPath (path);
  226920. if (path.isUsingNonZeroWinding())
  226921. CGContextFillPath (context);
  226922. else
  226923. CGContextEOFillPath (context);
  226924. }
  226925. else
  226926. {
  226927. createPath (path, transform);
  226928. if (path.isUsingNonZeroWinding())
  226929. CGContextClip (context);
  226930. else
  226931. CGContextEOClip (context);
  226932. if (state->fillType.isGradient())
  226933. drawGradient();
  226934. else
  226935. drawImage (state->fillType.image, state->fillType.transform, true);
  226936. }
  226937. CGContextRestoreGState (context);
  226938. }
  226939. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  226940. {
  226941. const int iw = sourceImage.getWidth();
  226942. const int ih = sourceImage.getHeight();
  226943. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  226944. CGContextSaveGState (context);
  226945. CGContextSetAlpha (context, state->fillType.getOpacity());
  226946. flip();
  226947. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  226948. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  226949. if (fillEntireClipAsTiles)
  226950. {
  226951. #if JUCE_IOS
  226952. CGContextDrawTiledImage (context, imageRect, image);
  226953. #else
  226954. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  226955. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  226956. // if it's doing a transformation - it's quicker to just draw lots of images manually
  226957. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  226958. CGContextDrawTiledImage (context, imageRect, image);
  226959. else
  226960. #endif
  226961. {
  226962. // Fallback to manually doing a tiled fill on 10.4
  226963. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  226964. int x = 0, y = 0;
  226965. while (x > clip.origin.x) x -= iw;
  226966. while (y > clip.origin.y) y -= ih;
  226967. const int right = (int) (clip.origin.x + clip.size.width);
  226968. const int bottom = (int) (clip.origin.y + clip.size.height);
  226969. while (y < bottom)
  226970. {
  226971. for (int x2 = x; x2 < right; x2 += iw)
  226972. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  226973. y += ih;
  226974. }
  226975. }
  226976. #endif
  226977. }
  226978. else
  226979. {
  226980. CGContextDrawImage (context, imageRect, image);
  226981. }
  226982. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  226983. CGContextRestoreGState (context);
  226984. }
  226985. void drawLine (const Line<float>& line)
  226986. {
  226987. if (state->fillType.isColour())
  226988. {
  226989. CGContextSetLineCap (context, kCGLineCapSquare);
  226990. CGContextSetLineWidth (context, 1.0f);
  226991. CGContextSetRGBStrokeColor (context,
  226992. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  226993. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  226994. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  226995. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  226996. CGContextStrokeLineSegments (context, cgLine, 1);
  226997. }
  226998. else
  226999. {
  227000. Path p;
  227001. p.addLineSegment (line, 1.0f);
  227002. fillPath (p, AffineTransform::identity);
  227003. }
  227004. }
  227005. void drawVerticalLine (const int x, float top, float bottom)
  227006. {
  227007. if (state->fillType.isColour())
  227008. {
  227009. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  227010. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  227011. #else
  227012. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  227013. // the x co-ord slightly to trick it..
  227014. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  227015. #endif
  227016. }
  227017. else
  227018. {
  227019. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  227020. }
  227021. }
  227022. void drawHorizontalLine (const int y, float left, float right)
  227023. {
  227024. if (state->fillType.isColour())
  227025. {
  227026. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  227027. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  227028. #else
  227029. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  227030. // the x co-ord slightly to trick it..
  227031. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  227032. #endif
  227033. }
  227034. else
  227035. {
  227036. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  227037. }
  227038. }
  227039. void setFont (const Font& newFont)
  227040. {
  227041. if (state->font != newFont)
  227042. {
  227043. state->fontRef = 0;
  227044. state->font = newFont;
  227045. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  227046. if (mf != 0)
  227047. {
  227048. state->fontRef = mf->fontRef;
  227049. CGContextSetFont (context, state->fontRef);
  227050. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  227051. state->fontTransform = mf->renderingTransform;
  227052. state->fontTransform.a *= state->font.getHorizontalScale();
  227053. CGContextSetTextMatrix (context, state->fontTransform);
  227054. }
  227055. }
  227056. }
  227057. const Font getFont()
  227058. {
  227059. return state->font;
  227060. }
  227061. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  227062. {
  227063. if (state->fontRef != 0 && state->fillType.isColour())
  227064. {
  227065. if (transform.isOnlyTranslation())
  227066. {
  227067. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  227068. CGGlyph g = glyphNumber;
  227069. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  227070. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  227071. }
  227072. else
  227073. {
  227074. CGContextSaveGState (context);
  227075. flip();
  227076. applyTransform (transform);
  227077. CGAffineTransform t = state->fontTransform;
  227078. t.d = -t.d;
  227079. CGContextSetTextMatrix (context, t);
  227080. CGGlyph g = glyphNumber;
  227081. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  227082. CGContextRestoreGState (context);
  227083. }
  227084. }
  227085. else
  227086. {
  227087. Path p;
  227088. Font& f = state->font;
  227089. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  227090. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  227091. .followedBy (transform));
  227092. }
  227093. }
  227094. private:
  227095. CGContextRef context;
  227096. const CGFloat flipHeight;
  227097. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  227098. CGFunctionCallbacks gradientCallbacks;
  227099. mutable Rectangle<int> lastClipRect;
  227100. mutable bool lastClipRectIsValid;
  227101. struct SavedState
  227102. {
  227103. SavedState()
  227104. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  227105. {
  227106. }
  227107. SavedState (const SavedState& other)
  227108. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  227109. fontTransform (other.fontTransform)
  227110. {
  227111. }
  227112. ~SavedState()
  227113. {
  227114. }
  227115. FillType fillType;
  227116. Font font;
  227117. CGFontRef fontRef;
  227118. CGAffineTransform fontTransform;
  227119. };
  227120. ScopedPointer <SavedState> state;
  227121. OwnedArray <SavedState> stateStack;
  227122. HeapBlock <PixelARGB> gradientLookupTable;
  227123. int numGradientLookupEntries;
  227124. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  227125. {
  227126. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  227127. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  227128. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  227129. colour.unpremultiply();
  227130. outData[0] = colour.getRed() / 255.0f;
  227131. outData[1] = colour.getGreen() / 255.0f;
  227132. outData[2] = colour.getBlue() / 255.0f;
  227133. outData[3] = colour.getAlpha() / 255.0f;
  227134. }
  227135. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  227136. {
  227137. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  227138. --numGradientLookupEntries;
  227139. CGShadingRef result = 0;
  227140. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  227141. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  227142. if (gradient.isRadial)
  227143. {
  227144. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  227145. p1, gradient.point1.getDistanceFrom (gradient.point2),
  227146. function, true, true);
  227147. }
  227148. else
  227149. {
  227150. result = CGShadingCreateAxial (rgbColourSpace, p1,
  227151. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  227152. function, true, true);
  227153. }
  227154. CGFunctionRelease (function);
  227155. return result;
  227156. }
  227157. void drawGradient()
  227158. {
  227159. flip();
  227160. applyTransform (state->fillType.transform);
  227161. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  227162. // you draw a gradient with high quality interp enabled).
  227163. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  227164. CGContextSetAlpha (context, state->fillType.getOpacity());
  227165. CGContextDrawShading (context, shading);
  227166. CGShadingRelease (shading);
  227167. }
  227168. void createPath (const Path& path) const
  227169. {
  227170. CGContextBeginPath (context);
  227171. Path::Iterator i (path);
  227172. while (i.next())
  227173. {
  227174. switch (i.elementType)
  227175. {
  227176. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  227177. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  227178. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  227179. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  227180. case Path::Iterator::closePath: CGContextClosePath (context); break;
  227181. default: jassertfalse; break;
  227182. }
  227183. }
  227184. }
  227185. void createPath (const Path& path, const AffineTransform& transform) const
  227186. {
  227187. CGContextBeginPath (context);
  227188. Path::Iterator i (path);
  227189. while (i.next())
  227190. {
  227191. switch (i.elementType)
  227192. {
  227193. case Path::Iterator::startNewSubPath:
  227194. transform.transformPoint (i.x1, i.y1);
  227195. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  227196. break;
  227197. case Path::Iterator::lineTo:
  227198. transform.transformPoint (i.x1, i.y1);
  227199. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  227200. break;
  227201. case Path::Iterator::quadraticTo:
  227202. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  227203. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  227204. break;
  227205. case Path::Iterator::cubicTo:
  227206. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  227207. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  227208. break;
  227209. case Path::Iterator::closePath:
  227210. CGContextClosePath (context); break;
  227211. default:
  227212. jassertfalse;
  227213. break;
  227214. }
  227215. }
  227216. }
  227217. void flip() const
  227218. {
  227219. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  227220. }
  227221. void applyTransform (const AffineTransform& transform) const
  227222. {
  227223. CGAffineTransform t;
  227224. t.a = transform.mat00;
  227225. t.b = transform.mat10;
  227226. t.c = transform.mat01;
  227227. t.d = transform.mat11;
  227228. t.tx = transform.mat02;
  227229. t.ty = transform.mat12;
  227230. CGContextConcatCTM (context, t);
  227231. }
  227232. CoreGraphicsContext (const CoreGraphicsContext&);
  227233. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  227234. };
  227235. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  227236. {
  227237. return new CoreGraphicsContext (context, height);
  227238. }
  227239. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  227240. const Image juce_loadWithCoreImage (InputStream& input)
  227241. {
  227242. MemoryBlock data;
  227243. input.readIntoMemoryBlock (data, -1);
  227244. #if JUCE_IOS
  227245. JUCE_AUTORELEASEPOOL
  227246. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData()
  227247. length: data.getSize()
  227248. freeWhenDone: NO]];
  227249. if (image != nil)
  227250. {
  227251. CGImageRef loadedImage = image.CGImage;
  227252. #else
  227253. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  227254. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  227255. CGDataProviderRelease (provider);
  227256. if (imageSource != 0)
  227257. {
  227258. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  227259. CFRelease (imageSource);
  227260. #endif
  227261. if (loadedImage != 0)
  227262. {
  227263. const bool hasAlphaChan = CGImageGetAlphaInfo (loadedImage) != kCGImageAlphaNone;
  227264. Image image (hasAlphaChan ? Image::ARGB : Image::RGB,
  227265. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  227266. hasAlphaChan, Image::NativeImage);
  227267. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  227268. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  227269. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  227270. CGContextFlush (cgImage->context);
  227271. #if ! JUCE_IOS
  227272. CFRelease (loadedImage);
  227273. #endif
  227274. return image;
  227275. }
  227276. }
  227277. return Image::null;
  227278. }
  227279. #endif
  227280. #endif
  227281. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  227282. /*** Start of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  227283. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227284. // compiled on its own).
  227285. #if JUCE_INCLUDED_FILE
  227286. class UIViewComponentPeer;
  227287. END_JUCE_NAMESPACE
  227288. #define JuceUIView MakeObjCClassName(JuceUIView)
  227289. @interface JuceUIView : UIView <UITextViewDelegate>
  227290. {
  227291. @public
  227292. UIViewComponentPeer* owner;
  227293. UITextView* hiddenTextView;
  227294. }
  227295. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner withFrame: (CGRect) frame;
  227296. - (void) dealloc;
  227297. - (void) drawRect: (CGRect) r;
  227298. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event;
  227299. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event;
  227300. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event;
  227301. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event;
  227302. - (BOOL) becomeFirstResponder;
  227303. - (BOOL) resignFirstResponder;
  227304. - (BOOL) canBecomeFirstResponder;
  227305. - (void) asyncRepaint: (id) rect;
  227306. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text;
  227307. @end
  227308. #define JuceUIWindow MakeObjCClassName(JuceUIWindow)
  227309. @interface JuceUIWindow : UIWindow
  227310. {
  227311. @private
  227312. UIViewComponentPeer* owner;
  227313. bool isZooming;
  227314. }
  227315. - (void) setOwner: (UIViewComponentPeer*) owner;
  227316. - (void) becomeKeyWindow;
  227317. @end
  227318. BEGIN_JUCE_NAMESPACE
  227319. class UIViewComponentPeer : public ComponentPeer,
  227320. public FocusChangeListener
  227321. {
  227322. public:
  227323. UIViewComponentPeer (Component* const component,
  227324. const int windowStyleFlags,
  227325. UIView* viewToAttachTo);
  227326. ~UIViewComponentPeer();
  227327. void* getNativeHandle() const;
  227328. void setVisible (bool shouldBeVisible);
  227329. void setTitle (const String& title);
  227330. void setPosition (int x, int y);
  227331. void setSize (int w, int h);
  227332. void setBounds (int x, int y, int w, int h, bool isNowFullScreen);
  227333. const Rectangle<int> getBounds() const;
  227334. const Rectangle<int> getBounds (const bool global) const;
  227335. const Point<int> getScreenPosition() const;
  227336. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  227337. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  227338. void setMinimised (bool shouldBeMinimised);
  227339. bool isMinimised() const;
  227340. void setFullScreen (bool shouldBeFullScreen);
  227341. bool isFullScreen() const;
  227342. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  227343. const BorderSize getFrameSize() const;
  227344. bool setAlwaysOnTop (bool alwaysOnTop);
  227345. void toFront (bool makeActiveWindow);
  227346. void toBehind (ComponentPeer* other);
  227347. void setIcon (const Image& newIcon);
  227348. virtual void drawRect (CGRect r);
  227349. virtual bool canBecomeKeyWindow();
  227350. virtual bool windowShouldClose();
  227351. virtual void redirectMovedOrResized();
  227352. virtual CGRect constrainRect (CGRect r);
  227353. virtual void viewFocusGain();
  227354. virtual void viewFocusLoss();
  227355. bool isFocused() const;
  227356. void grabFocus();
  227357. void textInputRequired (const Point<int>& position);
  227358. virtual BOOL textViewReplaceCharacters (const Range<int>& range, const String& text);
  227359. void updateHiddenTextContent (TextInputTarget* target);
  227360. void globalFocusChanged (Component*);
  227361. void handleTouches (UIEvent* e, bool isDown, bool isUp, bool isCancel);
  227362. void repaint (const Rectangle<int>& area);
  227363. void performAnyPendingRepaintsNow();
  227364. juce_UseDebuggingNewOperator
  227365. UIWindow* window;
  227366. JuceUIView* view;
  227367. bool isSharedWindow, fullScreen, insideDrawRect;
  227368. static ModifierKeys currentModifiers;
  227369. static int64 getMouseTime (UIEvent* e)
  227370. {
  227371. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  227372. + (int64) ([e timestamp] * 1000.0);
  227373. }
  227374. Array <UITouch*> currentTouches;
  227375. };
  227376. END_JUCE_NAMESPACE
  227377. @implementation JuceUIView
  227378. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner_
  227379. withFrame: (CGRect) frame
  227380. {
  227381. [super initWithFrame: frame];
  227382. owner = owner_;
  227383. hiddenTextView = [[UITextView alloc] initWithFrame: CGRectMake (0, 0, 0, 0)];
  227384. [self addSubview: hiddenTextView];
  227385. hiddenTextView.delegate = self;
  227386. hiddenTextView.autocapitalizationType = UITextAutocapitalizationTypeNone;
  227387. hiddenTextView.autocorrectionType = UITextAutocorrectionTypeNo;
  227388. return self;
  227389. }
  227390. - (void) dealloc
  227391. {
  227392. [hiddenTextView removeFromSuperview];
  227393. [hiddenTextView release];
  227394. [super dealloc];
  227395. }
  227396. - (void) drawRect: (CGRect) r
  227397. {
  227398. if (owner != 0)
  227399. owner->drawRect (r);
  227400. }
  227401. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  227402. {
  227403. return false;
  227404. }
  227405. ModifierKeys UIViewComponentPeer::currentModifiers;
  227406. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  227407. {
  227408. return UIViewComponentPeer::currentModifiers;
  227409. }
  227410. void ModifierKeys::updateCurrentModifiers() throw()
  227411. {
  227412. currentModifiers = UIViewComponentPeer::currentModifiers;
  227413. }
  227414. JUCE_NAMESPACE::Point<int> juce_lastMousePos;
  227415. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event
  227416. {
  227417. if (owner != 0)
  227418. owner->handleTouches (event, true, false, false);
  227419. }
  227420. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event
  227421. {
  227422. if (owner != 0)
  227423. owner->handleTouches (event, false, false, false);
  227424. }
  227425. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event
  227426. {
  227427. if (owner != 0)
  227428. owner->handleTouches (event, false, true, false);
  227429. }
  227430. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event
  227431. {
  227432. if (owner != 0)
  227433. owner->handleTouches (event, false, true, true);
  227434. [self touchesEnded: touches withEvent: event];
  227435. }
  227436. - (BOOL) becomeFirstResponder
  227437. {
  227438. if (owner != 0)
  227439. owner->viewFocusGain();
  227440. return true;
  227441. }
  227442. - (BOOL) resignFirstResponder
  227443. {
  227444. if (owner != 0)
  227445. owner->viewFocusLoss();
  227446. return true;
  227447. }
  227448. - (BOOL) canBecomeFirstResponder
  227449. {
  227450. return owner != 0 && owner->canBecomeKeyWindow();
  227451. }
  227452. - (void) asyncRepaint: (id) rect
  227453. {
  227454. CGRect* r = (CGRect*) [((NSData*) rect) bytes];
  227455. [self setNeedsDisplayInRect: *r];
  227456. }
  227457. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text
  227458. {
  227459. return owner->textViewReplaceCharacters (Range<int> (range.location, range.location + range.length),
  227460. nsStringToJuce (text));
  227461. }
  227462. @end
  227463. @implementation JuceUIWindow
  227464. - (void) setOwner: (UIViewComponentPeer*) owner_
  227465. {
  227466. owner = owner_;
  227467. isZooming = false;
  227468. }
  227469. - (void) becomeKeyWindow
  227470. {
  227471. [super becomeKeyWindow];
  227472. if (owner != 0)
  227473. owner->grabFocus();
  227474. }
  227475. @end
  227476. BEGIN_JUCE_NAMESPACE
  227477. UIViewComponentPeer::UIViewComponentPeer (Component* const component,
  227478. const int windowStyleFlags,
  227479. UIView* viewToAttachTo)
  227480. : ComponentPeer (component, windowStyleFlags),
  227481. window (0),
  227482. view (0),
  227483. isSharedWindow (viewToAttachTo != 0),
  227484. fullScreen (false),
  227485. insideDrawRect (false)
  227486. {
  227487. CGRect r = CGRectMake (0, 0, (float) component->getWidth(), (float) component->getHeight());
  227488. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  227489. if (isSharedWindow)
  227490. {
  227491. window = [viewToAttachTo window];
  227492. [viewToAttachTo addSubview: view];
  227493. setVisible (component->isVisible());
  227494. }
  227495. else
  227496. {
  227497. r.origin.x = (float) component->getX();
  227498. r.origin.y = (float) component->getY();
  227499. r.origin.y = [[UIScreen mainScreen] bounds].size.height - (r.origin.y + r.size.height);
  227500. window = [[JuceUIWindow alloc] init];
  227501. window.frame = r;
  227502. window.opaque = component->isOpaque();
  227503. view.opaque = component->isOpaque();
  227504. window.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  227505. view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  227506. [((JuceUIWindow*) window) setOwner: this];
  227507. if (component->isAlwaysOnTop())
  227508. window.windowLevel = UIWindowLevelAlert;
  227509. [window addSubview: view];
  227510. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  227511. view.hidden = ! component->isVisible();
  227512. window.hidden = ! component->isVisible();
  227513. view.multipleTouchEnabled = YES;
  227514. }
  227515. setTitle (component->getName());
  227516. Desktop::getInstance().addFocusChangeListener (this);
  227517. }
  227518. UIViewComponentPeer::~UIViewComponentPeer()
  227519. {
  227520. Desktop::getInstance().removeFocusChangeListener (this);
  227521. view->owner = 0;
  227522. [view removeFromSuperview];
  227523. [view release];
  227524. if (! isSharedWindow)
  227525. {
  227526. [((JuceUIWindow*) window) setOwner: 0];
  227527. [window release];
  227528. }
  227529. }
  227530. void* UIViewComponentPeer::getNativeHandle() const
  227531. {
  227532. return view;
  227533. }
  227534. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  227535. {
  227536. view.hidden = ! shouldBeVisible;
  227537. if (! isSharedWindow)
  227538. window.hidden = ! shouldBeVisible;
  227539. }
  227540. void UIViewComponentPeer::setTitle (const String& title)
  227541. {
  227542. // xxx is this possible?
  227543. }
  227544. void UIViewComponentPeer::setPosition (int x, int y)
  227545. {
  227546. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  227547. }
  227548. void UIViewComponentPeer::setSize (int w, int h)
  227549. {
  227550. setBounds (component->getX(), component->getY(), w, h, false);
  227551. }
  227552. void UIViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  227553. {
  227554. fullScreen = isNowFullScreen;
  227555. w = jmax (0, w);
  227556. h = jmax (0, h);
  227557. CGRect r;
  227558. r.origin.x = (float) x;
  227559. r.origin.y = (float) y;
  227560. r.size.width = (float) w;
  227561. r.size.height = (float) h;
  227562. if (isSharedWindow)
  227563. {
  227564. //r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  227565. if ([view frame].size.width != r.size.width
  227566. || [view frame].size.height != r.size.height)
  227567. [view setNeedsDisplay];
  227568. view.frame = r;
  227569. }
  227570. else
  227571. {
  227572. window.frame = r;
  227573. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  227574. }
  227575. }
  227576. const Rectangle<int> UIViewComponentPeer::getBounds (const bool global) const
  227577. {
  227578. CGRect r = [view frame];
  227579. if (global && [view window] != 0)
  227580. {
  227581. r = [view convertRect: r toView: nil];
  227582. CGRect wr = [[view window] frame];
  227583. r.origin.x += wr.origin.x;
  227584. r.origin.y += wr.origin.y;
  227585. }
  227586. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y,
  227587. (int) r.size.width, (int) r.size.height);
  227588. }
  227589. const Rectangle<int> UIViewComponentPeer::getBounds() const
  227590. {
  227591. return getBounds (! isSharedWindow);
  227592. }
  227593. const Point<int> UIViewComponentPeer::getScreenPosition() const
  227594. {
  227595. return getBounds (true).getPosition();
  227596. }
  227597. const Point<int> UIViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  227598. {
  227599. return relativePosition + getScreenPosition();
  227600. }
  227601. const Point<int> UIViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  227602. {
  227603. return screenPosition - getScreenPosition();
  227604. }
  227605. CGRect UIViewComponentPeer::constrainRect (CGRect r)
  227606. {
  227607. if (constrainer != 0)
  227608. {
  227609. CGRect current = [window frame];
  227610. current.origin.y = [[UIScreen mainScreen] bounds].size.height - current.origin.y - current.size.height;
  227611. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.origin.y - r.size.height;
  227612. Rectangle<int> pos ((int) r.origin.x, (int) r.origin.y,
  227613. (int) r.size.width, (int) r.size.height);
  227614. Rectangle<int> original ((int) current.origin.x, (int) current.origin.y,
  227615. (int) current.size.width, (int) current.size.height);
  227616. constrainer->checkBounds (pos, original,
  227617. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  227618. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  227619. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  227620. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  227621. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  227622. r.origin.x = pos.getX();
  227623. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.size.height - pos.getY();
  227624. r.size.width = pos.getWidth();
  227625. r.size.height = pos.getHeight();
  227626. }
  227627. return r;
  227628. }
  227629. void UIViewComponentPeer::setMinimised (bool shouldBeMinimised)
  227630. {
  227631. // xxx
  227632. }
  227633. bool UIViewComponentPeer::isMinimised() const
  227634. {
  227635. return false;
  227636. }
  227637. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  227638. {
  227639. if (! isSharedWindow)
  227640. {
  227641. Rectangle<int> r (lastNonFullscreenBounds);
  227642. setMinimised (false);
  227643. if (fullScreen != shouldBeFullScreen)
  227644. {
  227645. if (shouldBeFullScreen)
  227646. r = Desktop::getInstance().getMainMonitorArea();
  227647. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  227648. if (r != getComponent()->getBounds() && ! r.isEmpty())
  227649. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  227650. }
  227651. }
  227652. }
  227653. bool UIViewComponentPeer::isFullScreen() const
  227654. {
  227655. return fullScreen;
  227656. }
  227657. bool UIViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  227658. {
  227659. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  227660. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  227661. return false;
  227662. CGPoint p;
  227663. p.x = (float) position.getX();
  227664. p.y = (float) position.getY();
  227665. UIView* v = [view hitTest: p withEvent: nil];
  227666. if (trueIfInAChildWindow)
  227667. return v != nil;
  227668. return v == view;
  227669. }
  227670. const BorderSize UIViewComponentPeer::getFrameSize() const
  227671. {
  227672. BorderSize b;
  227673. if (! isSharedWindow)
  227674. {
  227675. CGRect v = [view convertRect: [view frame] toView: nil];
  227676. CGRect w = [window frame];
  227677. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  227678. b.setBottom ((int) v.origin.y);
  227679. b.setLeft ((int) v.origin.x);
  227680. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  227681. }
  227682. return b;
  227683. }
  227684. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  227685. {
  227686. if (! isSharedWindow)
  227687. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  227688. return true;
  227689. }
  227690. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  227691. {
  227692. if (isSharedWindow)
  227693. [[view superview] bringSubviewToFront: view];
  227694. if (window != 0 && component->isVisible())
  227695. [window makeKeyAndVisible];
  227696. }
  227697. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  227698. {
  227699. UIViewComponentPeer* const otherPeer = dynamic_cast <UIViewComponentPeer*> (other);
  227700. jassert (otherPeer != 0); // wrong type of window?
  227701. if (otherPeer != 0)
  227702. {
  227703. if (isSharedWindow)
  227704. {
  227705. [[view superview] insertSubview: view belowSubview: otherPeer->view];
  227706. }
  227707. else
  227708. {
  227709. jassertfalse; // don't know how to do this
  227710. }
  227711. }
  227712. }
  227713. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  227714. {
  227715. // to do..
  227716. }
  227717. void UIViewComponentPeer::handleTouches (UIEvent* event, const bool isDown, const bool isUp, bool isCancel)
  227718. {
  227719. NSArray* touches = [[event touchesForView: view] allObjects];
  227720. for (unsigned int i = 0; i < [touches count]; ++i)
  227721. {
  227722. UITouch* touch = [touches objectAtIndex: i];
  227723. CGPoint p = [touch locationInView: view];
  227724. const Point<int> pos ((int) p.x, (int) p.y);
  227725. juce_lastMousePos = pos + getScreenPosition();
  227726. const int64 time = getMouseTime (event);
  227727. int touchIndex = currentTouches.indexOf (touch);
  227728. if (touchIndex < 0)
  227729. {
  227730. touchIndex = currentTouches.size();
  227731. currentTouches.add (touch);
  227732. }
  227733. if (isDown)
  227734. {
  227735. currentModifiers = currentModifiers.withoutMouseButtons();
  227736. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  227737. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  227738. }
  227739. else if (isUp)
  227740. {
  227741. currentModifiers = currentModifiers.withoutMouseButtons();
  227742. currentTouches.remove (touchIndex);
  227743. }
  227744. if (isCancel)
  227745. currentTouches.clear();
  227746. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  227747. }
  227748. }
  227749. static UIViewComponentPeer* currentlyFocusedPeer = 0;
  227750. void UIViewComponentPeer::viewFocusGain()
  227751. {
  227752. if (currentlyFocusedPeer != this)
  227753. {
  227754. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  227755. currentlyFocusedPeer->handleFocusLoss();
  227756. currentlyFocusedPeer = this;
  227757. handleFocusGain();
  227758. }
  227759. }
  227760. void UIViewComponentPeer::viewFocusLoss()
  227761. {
  227762. if (currentlyFocusedPeer == this)
  227763. {
  227764. currentlyFocusedPeer = 0;
  227765. handleFocusLoss();
  227766. }
  227767. }
  227768. void juce_HandleProcessFocusChange()
  227769. {
  227770. if (UIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  227771. {
  227772. if (Process::isForegroundProcess())
  227773. {
  227774. currentlyFocusedPeer->handleFocusGain();
  227775. ComponentPeer::bringModalComponentToFront();
  227776. }
  227777. else
  227778. {
  227779. currentlyFocusedPeer->handleFocusLoss();
  227780. // turn kiosk mode off if we lose focus..
  227781. Desktop::getInstance().setKioskModeComponent (0);
  227782. }
  227783. }
  227784. }
  227785. bool UIViewComponentPeer::isFocused() const
  227786. {
  227787. return isSharedWindow ? this == currentlyFocusedPeer
  227788. : (window != 0 && [window isKeyWindow]);
  227789. }
  227790. void UIViewComponentPeer::grabFocus()
  227791. {
  227792. if (window != 0)
  227793. {
  227794. [window makeKeyWindow];
  227795. viewFocusGain();
  227796. }
  227797. }
  227798. void UIViewComponentPeer::textInputRequired (const Point<int>&)
  227799. {
  227800. }
  227801. void UIViewComponentPeer::updateHiddenTextContent (TextInputTarget* target)
  227802. {
  227803. view->hiddenTextView.text = juceStringToNS (target->getTextInRange (Range<int> (0, target->getHighlightedRegion().getStart())));
  227804. view->hiddenTextView.selectedRange = NSMakeRange (target->getHighlightedRegion().getStart(), 0);
  227805. }
  227806. BOOL UIViewComponentPeer::textViewReplaceCharacters (const Range<int>& range, const String& text)
  227807. {
  227808. TextInputTarget* const target = findCurrentTextInputTarget();
  227809. if (target != 0)
  227810. {
  227811. const Range<int> currentSelection (target->getHighlightedRegion());
  227812. if (range.getLength() == 1 && text.isEmpty()) // (detect backspace)
  227813. if (currentSelection.isEmpty())
  227814. target->setHighlightedRegion (currentSelection.withStart (currentSelection.getStart() - 1));
  227815. target->insertTextAtCaret (text);
  227816. updateHiddenTextContent (target);
  227817. }
  227818. return NO;
  227819. }
  227820. void UIViewComponentPeer::globalFocusChanged (Component*)
  227821. {
  227822. TextInputTarget* const target = findCurrentTextInputTarget();
  227823. if (target != 0)
  227824. {
  227825. Component* comp = dynamic_cast<Component*> (target);
  227826. Point<int> pos (comp->relativePositionToOtherComponent (component, Point<int>()));
  227827. view->hiddenTextView.frame = CGRectMake (pos.getX(), pos.getY(), 0, 0);
  227828. updateHiddenTextContent (target);
  227829. [view->hiddenTextView becomeFirstResponder];
  227830. }
  227831. else
  227832. {
  227833. [view->hiddenTextView resignFirstResponder];
  227834. }
  227835. }
  227836. void UIViewComponentPeer::drawRect (CGRect r)
  227837. {
  227838. if (r.size.width < 1.0f || r.size.height < 1.0f)
  227839. return;
  227840. CGContextRef cg = UIGraphicsGetCurrentContext();
  227841. if (! component->isOpaque())
  227842. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  227843. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, view.bounds.size.height));
  227844. CoreGraphicsContext g (cg, view.bounds.size.height);
  227845. insideDrawRect = true;
  227846. handlePaint (g);
  227847. insideDrawRect = false;
  227848. }
  227849. bool UIViewComponentPeer::canBecomeKeyWindow()
  227850. {
  227851. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  227852. }
  227853. bool UIViewComponentPeer::windowShouldClose()
  227854. {
  227855. if (! isValidPeer (this))
  227856. return YES;
  227857. handleUserClosingWindow();
  227858. return NO;
  227859. }
  227860. void UIViewComponentPeer::redirectMovedOrResized()
  227861. {
  227862. handleMovedOrResized();
  227863. }
  227864. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  227865. {
  227866. }
  227867. class AsyncRepaintMessage : public CallbackMessage
  227868. {
  227869. public:
  227870. UIViewComponentPeer* const peer;
  227871. const Rectangle<int> rect;
  227872. AsyncRepaintMessage (UIViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  227873. : peer (peer_), rect (rect_)
  227874. {
  227875. }
  227876. void messageCallback()
  227877. {
  227878. if (ComponentPeer::isValidPeer (peer))
  227879. peer->repaint (rect);
  227880. }
  227881. };
  227882. void UIViewComponentPeer::repaint (const Rectangle<int>& area)
  227883. {
  227884. if (insideDrawRect || ! MessageManager::getInstance()->isThisTheMessageThread())
  227885. {
  227886. (new AsyncRepaintMessage (this, area))->post();
  227887. }
  227888. else
  227889. {
  227890. [view setNeedsDisplayInRect: CGRectMake ((float) area.getX(), (float) area.getY(),
  227891. (float) area.getWidth(), (float) area.getHeight())];
  227892. }
  227893. }
  227894. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  227895. {
  227896. }
  227897. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  227898. {
  227899. return new UIViewComponentPeer (this, styleFlags, (UIView*) windowToAttachTo);
  227900. }
  227901. const Image juce_createIconForFile (const File& file)
  227902. {
  227903. return Image::null;
  227904. }
  227905. void Desktop::createMouseInputSources()
  227906. {
  227907. for (int i = 0; i < 10; ++i)
  227908. mouseSources.add (new MouseInputSource (i, false));
  227909. }
  227910. bool Desktop::canUseSemiTransparentWindows() throw()
  227911. {
  227912. return true;
  227913. }
  227914. const Point<int> Desktop::getMousePosition()
  227915. {
  227916. return juce_lastMousePos;
  227917. }
  227918. void Desktop::setMousePosition (const Point<int>&)
  227919. {
  227920. }
  227921. const int KeyPress::spaceKey = ' ';
  227922. const int KeyPress::returnKey = 0x0d;
  227923. const int KeyPress::escapeKey = 0x1b;
  227924. const int KeyPress::backspaceKey = 0x7f;
  227925. const int KeyPress::leftKey = 0x1000;
  227926. const int KeyPress::rightKey = 0x1001;
  227927. const int KeyPress::upKey = 0x1002;
  227928. const int KeyPress::downKey = 0x1003;
  227929. const int KeyPress::pageUpKey = 0x1004;
  227930. const int KeyPress::pageDownKey = 0x1005;
  227931. const int KeyPress::endKey = 0x1006;
  227932. const int KeyPress::homeKey = 0x1007;
  227933. const int KeyPress::deleteKey = 0x1008;
  227934. const int KeyPress::insertKey = -1;
  227935. const int KeyPress::tabKey = 9;
  227936. const int KeyPress::F1Key = 0x2001;
  227937. const int KeyPress::F2Key = 0x2002;
  227938. const int KeyPress::F3Key = 0x2003;
  227939. const int KeyPress::F4Key = 0x2004;
  227940. const int KeyPress::F5Key = 0x2005;
  227941. const int KeyPress::F6Key = 0x2006;
  227942. const int KeyPress::F7Key = 0x2007;
  227943. const int KeyPress::F8Key = 0x2008;
  227944. const int KeyPress::F9Key = 0x2009;
  227945. const int KeyPress::F10Key = 0x200a;
  227946. const int KeyPress::F11Key = 0x200b;
  227947. const int KeyPress::F12Key = 0x200c;
  227948. const int KeyPress::F13Key = 0x200d;
  227949. const int KeyPress::F14Key = 0x200e;
  227950. const int KeyPress::F15Key = 0x200f;
  227951. const int KeyPress::F16Key = 0x2010;
  227952. const int KeyPress::numberPad0 = 0x30020;
  227953. const int KeyPress::numberPad1 = 0x30021;
  227954. const int KeyPress::numberPad2 = 0x30022;
  227955. const int KeyPress::numberPad3 = 0x30023;
  227956. const int KeyPress::numberPad4 = 0x30024;
  227957. const int KeyPress::numberPad5 = 0x30025;
  227958. const int KeyPress::numberPad6 = 0x30026;
  227959. const int KeyPress::numberPad7 = 0x30027;
  227960. const int KeyPress::numberPad8 = 0x30028;
  227961. const int KeyPress::numberPad9 = 0x30029;
  227962. const int KeyPress::numberPadAdd = 0x3002a;
  227963. const int KeyPress::numberPadSubtract = 0x3002b;
  227964. const int KeyPress::numberPadMultiply = 0x3002c;
  227965. const int KeyPress::numberPadDivide = 0x3002d;
  227966. const int KeyPress::numberPadSeparator = 0x3002e;
  227967. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  227968. const int KeyPress::numberPadEquals = 0x30030;
  227969. const int KeyPress::numberPadDelete = 0x30031;
  227970. const int KeyPress::playKey = 0x30000;
  227971. const int KeyPress::stopKey = 0x30001;
  227972. const int KeyPress::fastForwardKey = 0x30002;
  227973. const int KeyPress::rewindKey = 0x30003;
  227974. #endif
  227975. /*** End of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  227976. /*** Start of inlined file: juce_iphone_MessageManager.mm ***/
  227977. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227978. // compiled on its own).
  227979. #if JUCE_INCLUDED_FILE
  227980. struct CallbackMessagePayload
  227981. {
  227982. MessageCallbackFunction* function;
  227983. void* parameter;
  227984. void* volatile result;
  227985. bool volatile hasBeenExecuted;
  227986. };
  227987. END_JUCE_NAMESPACE
  227988. @interface JuceCustomMessageHandler : NSObject
  227989. {
  227990. }
  227991. - (void) performCallback: (id) info;
  227992. @end
  227993. @implementation JuceCustomMessageHandler
  227994. - (void) performCallback: (id) info
  227995. {
  227996. if ([info isKindOfClass: [NSData class]])
  227997. {
  227998. JUCE_NAMESPACE::CallbackMessagePayload* pl = (JUCE_NAMESPACE::CallbackMessagePayload*) [((NSData*) info) bytes];
  227999. if (pl != 0)
  228000. {
  228001. pl->result = (*pl->function) (pl->parameter);
  228002. pl->hasBeenExecuted = true;
  228003. }
  228004. }
  228005. else
  228006. {
  228007. jassertfalse; // should never get here!
  228008. }
  228009. }
  228010. @end
  228011. BEGIN_JUCE_NAMESPACE
  228012. void MessageManager::runDispatchLoop()
  228013. {
  228014. jassert (isThisTheMessageThread()); // must only be called by the message thread
  228015. runDispatchLoopUntil (-1);
  228016. }
  228017. void MessageManager::stopDispatchLoop()
  228018. {
  228019. [[[UIApplication sharedApplication] delegate] applicationWillTerminate: [UIApplication sharedApplication]];
  228020. exit (0); // iPhone apps get no mercy..
  228021. }
  228022. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  228023. {
  228024. const ScopedAutoReleasePool pool;
  228025. jassert (isThisTheMessageThread()); // must only be called by the message thread
  228026. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  228027. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  228028. while (! quitMessagePosted)
  228029. {
  228030. const ScopedAutoReleasePool pool;
  228031. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  228032. beforeDate: endDate];
  228033. if (millisecondsToRunFor >= 0 && Time::getMillisecondCounter() >= endTime)
  228034. break;
  228035. }
  228036. return ! quitMessagePosted;
  228037. }
  228038. static CFRunLoopRef runLoop = 0;
  228039. static CFRunLoopSourceRef runLoopSource = 0;
  228040. static OwnedArray <Message, CriticalSection>* pendingMessages = 0;
  228041. static JuceCustomMessageHandler* juceCustomMessageHandler = 0;
  228042. static void runLoopSourceCallback (void*)
  228043. {
  228044. if (pendingMessages != 0)
  228045. {
  228046. int numDispatched = 0;
  228047. do
  228048. {
  228049. Message* const nextMessage = pendingMessages->removeAndReturn (0);
  228050. if (nextMessage == 0)
  228051. return;
  228052. const ScopedAutoReleasePool pool;
  228053. MessageManager::getInstance()->deliverMessage (nextMessage);
  228054. } while (++numDispatched <= 4);
  228055. CFRunLoopSourceSignal (runLoopSource);
  228056. CFRunLoopWakeUp (runLoop);
  228057. }
  228058. }
  228059. void MessageManager::doPlatformSpecificInitialisation()
  228060. {
  228061. pendingMessages = new OwnedArray <Message, CriticalSection>();
  228062. runLoop = CFRunLoopGetCurrent();
  228063. CFRunLoopSourceContext sourceContext;
  228064. zerostruct (sourceContext);
  228065. sourceContext.perform = runLoopSourceCallback;
  228066. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  228067. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  228068. if (juceCustomMessageHandler == 0)
  228069. juceCustomMessageHandler = [[JuceCustomMessageHandler alloc] init];
  228070. }
  228071. void MessageManager::doPlatformSpecificShutdown()
  228072. {
  228073. CFRunLoopSourceInvalidate (runLoopSource);
  228074. CFRelease (runLoopSource);
  228075. runLoopSource = 0;
  228076. deleteAndZero (pendingMessages);
  228077. if (juceCustomMessageHandler != 0)
  228078. {
  228079. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceCustomMessageHandler];
  228080. [juceCustomMessageHandler release];
  228081. juceCustomMessageHandler = 0;
  228082. }
  228083. }
  228084. bool juce_postMessageToSystemQueue (Message* message)
  228085. {
  228086. if (pendingMessages != 0)
  228087. {
  228088. pendingMessages->add (message);
  228089. CFRunLoopSourceSignal (runLoopSource);
  228090. CFRunLoopWakeUp (runLoop);
  228091. }
  228092. return true;
  228093. }
  228094. void MessageManager::broadcastMessage (const String& value)
  228095. {
  228096. }
  228097. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  228098. {
  228099. if (isThisTheMessageThread())
  228100. {
  228101. return (*callback) (data);
  228102. }
  228103. else
  228104. {
  228105. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  228106. // deadlock because the message manager is blocked from running, so can never
  228107. // call your function..
  228108. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  228109. const ScopedAutoReleasePool pool;
  228110. CallbackMessagePayload cmp;
  228111. cmp.function = callback;
  228112. cmp.parameter = data;
  228113. cmp.result = 0;
  228114. cmp.hasBeenExecuted = false;
  228115. [juceCustomMessageHandler performSelectorOnMainThread: @selector (performCallback:)
  228116. withObject: [NSData dataWithBytesNoCopy: &cmp
  228117. length: sizeof (cmp)
  228118. freeWhenDone: NO]
  228119. waitUntilDone: YES];
  228120. return cmp.result;
  228121. }
  228122. }
  228123. #endif
  228124. /*** End of inlined file: juce_iphone_MessageManager.mm ***/
  228125. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  228126. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228127. // compiled on its own).
  228128. #if JUCE_INCLUDED_FILE
  228129. #if JUCE_MAC
  228130. END_JUCE_NAMESPACE
  228131. using namespace JUCE_NAMESPACE;
  228132. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  228133. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  228134. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  228135. #else
  228136. @interface JuceFileChooserDelegate : NSObject
  228137. #endif
  228138. {
  228139. StringArray* filters;
  228140. }
  228141. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  228142. - (void) dealloc;
  228143. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  228144. @end
  228145. @implementation JuceFileChooserDelegate
  228146. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  228147. {
  228148. [super init];
  228149. filters = filters_;
  228150. return self;
  228151. }
  228152. - (void) dealloc
  228153. {
  228154. delete filters;
  228155. [super dealloc];
  228156. }
  228157. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  228158. {
  228159. (void) sender;
  228160. const File f (nsStringToJuce (filename));
  228161. for (int i = filters->size(); --i >= 0;)
  228162. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  228163. return true;
  228164. return f.isDirectory();
  228165. }
  228166. @end
  228167. BEGIN_JUCE_NAMESPACE
  228168. void FileChooser::showPlatformDialog (Array<File>& results,
  228169. const String& title,
  228170. const File& currentFileOrDirectory,
  228171. const String& filter,
  228172. bool selectsDirectory,
  228173. bool selectsFiles,
  228174. bool isSaveDialogue,
  228175. bool warnAboutOverwritingExistingFiles,
  228176. bool selectMultipleFiles,
  228177. FilePreviewComponent* extraInfoComponent)
  228178. {
  228179. const ScopedAutoReleasePool pool;
  228180. StringArray* filters = new StringArray();
  228181. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  228182. filters->trim();
  228183. filters->removeEmptyStrings();
  228184. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  228185. [delegate autorelease];
  228186. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  228187. : [NSOpenPanel openPanel];
  228188. [panel setTitle: juceStringToNS (title)];
  228189. if (! isSaveDialogue)
  228190. {
  228191. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  228192. [openPanel setCanChooseDirectories: selectsDirectory];
  228193. [openPanel setCanChooseFiles: selectsFiles];
  228194. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  228195. }
  228196. [panel setDelegate: delegate];
  228197. if (isSaveDialogue || selectsDirectory)
  228198. [panel setCanCreateDirectories: YES];
  228199. String directory, filename;
  228200. if (currentFileOrDirectory.isDirectory())
  228201. {
  228202. directory = currentFileOrDirectory.getFullPathName();
  228203. }
  228204. else
  228205. {
  228206. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  228207. filename = currentFileOrDirectory.getFileName();
  228208. }
  228209. if ([panel runModalForDirectory: juceStringToNS (directory)
  228210. file: juceStringToNS (filename)]
  228211. == NSOKButton)
  228212. {
  228213. if (isSaveDialogue)
  228214. {
  228215. results.add (File (nsStringToJuce ([panel filename])));
  228216. }
  228217. else
  228218. {
  228219. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  228220. NSArray* urls = [openPanel filenames];
  228221. for (unsigned int i = 0; i < [urls count]; ++i)
  228222. {
  228223. NSString* f = [urls objectAtIndex: i];
  228224. results.add (File (nsStringToJuce (f)));
  228225. }
  228226. }
  228227. }
  228228. [panel setDelegate: nil];
  228229. }
  228230. #else
  228231. void FileChooser::showPlatformDialog (Array<File>& results,
  228232. const String& title,
  228233. const File& currentFileOrDirectory,
  228234. const String& filter,
  228235. bool selectsDirectory,
  228236. bool selectsFiles,
  228237. bool isSaveDialogue,
  228238. bool warnAboutOverwritingExistingFiles,
  228239. bool selectMultipleFiles,
  228240. FilePreviewComponent* extraInfoComponent)
  228241. {
  228242. const ScopedAutoReleasePool pool;
  228243. jassertfalse; //xxx to do
  228244. }
  228245. #endif
  228246. #endif
  228247. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  228248. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  228249. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228250. // compiled on its own).
  228251. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  228252. #if JUCE_MAC
  228253. END_JUCE_NAMESPACE
  228254. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  228255. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  228256. {
  228257. CriticalSection* contextLock;
  228258. bool needsUpdate;
  228259. }
  228260. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  228261. - (bool) makeActive;
  228262. - (void) makeInactive;
  228263. - (void) reshape;
  228264. @end
  228265. @implementation ThreadSafeNSOpenGLView
  228266. - (id) initWithFrame: (NSRect) frameRect
  228267. pixelFormat: (NSOpenGLPixelFormat*) format
  228268. {
  228269. contextLock = new CriticalSection();
  228270. self = [super initWithFrame: frameRect pixelFormat: format];
  228271. if (self != nil)
  228272. [[NSNotificationCenter defaultCenter] addObserver: self
  228273. selector: @selector (_surfaceNeedsUpdate:)
  228274. name: NSViewGlobalFrameDidChangeNotification
  228275. object: self];
  228276. return self;
  228277. }
  228278. - (void) dealloc
  228279. {
  228280. [[NSNotificationCenter defaultCenter] removeObserver: self];
  228281. delete contextLock;
  228282. [super dealloc];
  228283. }
  228284. - (bool) makeActive
  228285. {
  228286. const ScopedLock sl (*contextLock);
  228287. if ([self openGLContext] == 0)
  228288. return false;
  228289. [[self openGLContext] makeCurrentContext];
  228290. if (needsUpdate)
  228291. {
  228292. [super update];
  228293. needsUpdate = false;
  228294. }
  228295. return true;
  228296. }
  228297. - (void) makeInactive
  228298. {
  228299. const ScopedLock sl (*contextLock);
  228300. [NSOpenGLContext clearCurrentContext];
  228301. }
  228302. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  228303. {
  228304. const ScopedLock sl (*contextLock);
  228305. needsUpdate = true;
  228306. }
  228307. - (void) update
  228308. {
  228309. const ScopedLock sl (*contextLock);
  228310. needsUpdate = true;
  228311. }
  228312. - (void) reshape
  228313. {
  228314. const ScopedLock sl (*contextLock);
  228315. needsUpdate = true;
  228316. }
  228317. @end
  228318. BEGIN_JUCE_NAMESPACE
  228319. class WindowedGLContext : public OpenGLContext
  228320. {
  228321. public:
  228322. WindowedGLContext (Component* const component,
  228323. const OpenGLPixelFormat& pixelFormat_,
  228324. NSOpenGLContext* sharedContext)
  228325. : renderContext (0),
  228326. pixelFormat (pixelFormat_)
  228327. {
  228328. jassert (component != 0);
  228329. NSOpenGLPixelFormatAttribute attribs [64];
  228330. int n = 0;
  228331. attribs[n++] = NSOpenGLPFADoubleBuffer;
  228332. attribs[n++] = NSOpenGLPFAAccelerated;
  228333. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  228334. attribs[n++] = NSOpenGLPFAColorSize;
  228335. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  228336. pixelFormat.greenBits,
  228337. pixelFormat.blueBits);
  228338. attribs[n++] = NSOpenGLPFAAlphaSize;
  228339. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  228340. attribs[n++] = NSOpenGLPFADepthSize;
  228341. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  228342. attribs[n++] = NSOpenGLPFAStencilSize;
  228343. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  228344. attribs[n++] = NSOpenGLPFAAccumSize;
  228345. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  228346. pixelFormat.accumulationBufferGreenBits,
  228347. pixelFormat.accumulationBufferBlueBits,
  228348. pixelFormat.accumulationBufferAlphaBits);
  228349. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  228350. attribs[n++] = NSOpenGLPFASampleBuffers;
  228351. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  228352. attribs[n++] = NSOpenGLPFAClosestPolicy;
  228353. attribs[n++] = NSOpenGLPFANoRecovery;
  228354. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  228355. NSOpenGLPixelFormat* format
  228356. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  228357. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  228358. pixelFormat: format];
  228359. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  228360. shareContext: sharedContext] autorelease];
  228361. const GLint swapInterval = 1;
  228362. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  228363. [view setOpenGLContext: renderContext];
  228364. [format release];
  228365. viewHolder = new NSViewComponentInternal (view, component);
  228366. }
  228367. ~WindowedGLContext()
  228368. {
  228369. deleteContext();
  228370. viewHolder = 0;
  228371. }
  228372. void deleteContext()
  228373. {
  228374. makeInactive();
  228375. [renderContext clearDrawable];
  228376. [renderContext setView: nil];
  228377. [view setOpenGLContext: nil];
  228378. renderContext = nil;
  228379. }
  228380. bool makeActive() const throw()
  228381. {
  228382. jassert (renderContext != 0);
  228383. if ([renderContext view] != view)
  228384. [renderContext setView: view];
  228385. [view makeActive];
  228386. return isActive();
  228387. }
  228388. bool makeInactive() const throw()
  228389. {
  228390. [view makeInactive];
  228391. return true;
  228392. }
  228393. bool isActive() const throw()
  228394. {
  228395. return [NSOpenGLContext currentContext] == renderContext;
  228396. }
  228397. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  228398. void* getRawContext() const throw() { return renderContext; }
  228399. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  228400. {
  228401. }
  228402. void swapBuffers()
  228403. {
  228404. [renderContext flushBuffer];
  228405. }
  228406. bool setSwapInterval (const int numFramesPerSwap)
  228407. {
  228408. [renderContext setValues: (const GLint*) &numFramesPerSwap
  228409. forParameter: NSOpenGLCPSwapInterval];
  228410. return true;
  228411. }
  228412. int getSwapInterval() const
  228413. {
  228414. GLint numFrames = 0;
  228415. [renderContext getValues: &numFrames
  228416. forParameter: NSOpenGLCPSwapInterval];
  228417. return numFrames;
  228418. }
  228419. void repaint()
  228420. {
  228421. // we need to invalidate the juce view that holds this gl view, to make it
  228422. // cause a repaint callback
  228423. NSView* v = (NSView*) viewHolder->view;
  228424. NSRect r = [v frame];
  228425. // bit of a bodge here.. if we only invalidate the area of the gl component,
  228426. // it's completely covered by the NSOpenGLView, so the OS throws away the
  228427. // repaint message, thus never causing our paint() callback, and never repainting
  228428. // the comp. So invalidating just a little bit around the edge helps..
  228429. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  228430. }
  228431. void* getNativeWindowHandle() const { return viewHolder->view; }
  228432. juce_UseDebuggingNewOperator
  228433. NSOpenGLContext* renderContext;
  228434. ThreadSafeNSOpenGLView* view;
  228435. private:
  228436. OpenGLPixelFormat pixelFormat;
  228437. ScopedPointer <NSViewComponentInternal> viewHolder;
  228438. WindowedGLContext (const WindowedGLContext&);
  228439. WindowedGLContext& operator= (const WindowedGLContext&);
  228440. };
  228441. OpenGLContext* OpenGLComponent::createContext()
  228442. {
  228443. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  228444. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  228445. return (c->renderContext != 0) ? c.release() : 0;
  228446. }
  228447. void* OpenGLComponent::getNativeWindowHandle() const
  228448. {
  228449. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  228450. : 0;
  228451. }
  228452. void juce_glViewport (const int w, const int h)
  228453. {
  228454. glViewport (0, 0, w, h);
  228455. }
  228456. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  228457. OwnedArray <OpenGLPixelFormat>& results)
  228458. {
  228459. /* GLint attribs [64];
  228460. int n = 0;
  228461. attribs[n++] = AGL_RGBA;
  228462. attribs[n++] = AGL_DOUBLEBUFFER;
  228463. attribs[n++] = AGL_ACCELERATED;
  228464. attribs[n++] = AGL_NO_RECOVERY;
  228465. attribs[n++] = AGL_NONE;
  228466. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  228467. while (p != 0)
  228468. {
  228469. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  228470. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  228471. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  228472. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  228473. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  228474. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  228475. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  228476. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  228477. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  228478. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  228479. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  228480. results.add (pf);
  228481. p = aglNextPixelFormat (p);
  228482. }*/
  228483. //jassertfalse // can't see how you do this in cocoa!
  228484. }
  228485. #else
  228486. END_JUCE_NAMESPACE
  228487. @interface JuceGLView : UIView
  228488. {
  228489. }
  228490. + (Class) layerClass;
  228491. @end
  228492. @implementation JuceGLView
  228493. + (Class) layerClass
  228494. {
  228495. return [CAEAGLLayer class];
  228496. }
  228497. @end
  228498. BEGIN_JUCE_NAMESPACE
  228499. class GLESContext : public OpenGLContext
  228500. {
  228501. public:
  228502. GLESContext (UIViewComponentPeer* peer,
  228503. Component* const component_,
  228504. const OpenGLPixelFormat& pixelFormat_,
  228505. const GLESContext* const sharedContext,
  228506. NSUInteger apiType)
  228507. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  228508. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  228509. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  228510. {
  228511. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  228512. view.opaque = YES;
  228513. view.hidden = NO;
  228514. view.backgroundColor = [UIColor blackColor];
  228515. view.userInteractionEnabled = NO;
  228516. glLayer = (CAEAGLLayer*) [view layer];
  228517. [peer->view addSubview: view];
  228518. if (sharedContext != 0)
  228519. context = [[EAGLContext alloc] initWithAPI: apiType
  228520. sharegroup: [sharedContext->context sharegroup]];
  228521. else
  228522. context = [[EAGLContext alloc] initWithAPI: apiType];
  228523. createGLBuffers();
  228524. }
  228525. ~GLESContext()
  228526. {
  228527. deleteContext();
  228528. [view removeFromSuperview];
  228529. [view release];
  228530. freeGLBuffers();
  228531. }
  228532. void deleteContext()
  228533. {
  228534. makeInactive();
  228535. [context release];
  228536. context = nil;
  228537. }
  228538. bool makeActive() const throw()
  228539. {
  228540. jassert (context != 0);
  228541. [EAGLContext setCurrentContext: context];
  228542. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  228543. return true;
  228544. }
  228545. void swapBuffers()
  228546. {
  228547. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228548. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  228549. }
  228550. bool makeInactive() const throw()
  228551. {
  228552. return [EAGLContext setCurrentContext: nil];
  228553. }
  228554. bool isActive() const throw()
  228555. {
  228556. return [EAGLContext currentContext] == context;
  228557. }
  228558. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  228559. void* getRawContext() const throw() { return glLayer; }
  228560. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  228561. {
  228562. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  228563. if (lastWidth != w || lastHeight != h)
  228564. {
  228565. lastWidth = w;
  228566. lastHeight = h;
  228567. freeGLBuffers();
  228568. createGLBuffers();
  228569. }
  228570. }
  228571. bool setSwapInterval (const int numFramesPerSwap)
  228572. {
  228573. numFrames = numFramesPerSwap;
  228574. return true;
  228575. }
  228576. int getSwapInterval() const
  228577. {
  228578. return numFrames;
  228579. }
  228580. void repaint()
  228581. {
  228582. }
  228583. void createGLBuffers()
  228584. {
  228585. makeActive();
  228586. glGenFramebuffersOES (1, &frameBufferHandle);
  228587. glGenRenderbuffersOES (1, &colorBufferHandle);
  228588. glGenRenderbuffersOES (1, &depthBufferHandle);
  228589. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228590. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  228591. GLint width, height;
  228592. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  228593. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  228594. if (useDepthBuffer)
  228595. {
  228596. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  228597. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  228598. }
  228599. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  228600. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  228601. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  228602. if (useDepthBuffer)
  228603. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  228604. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  228605. }
  228606. void freeGLBuffers()
  228607. {
  228608. if (frameBufferHandle != 0)
  228609. {
  228610. glDeleteFramebuffersOES (1, &frameBufferHandle);
  228611. frameBufferHandle = 0;
  228612. }
  228613. if (colorBufferHandle != 0)
  228614. {
  228615. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  228616. colorBufferHandle = 0;
  228617. }
  228618. if (depthBufferHandle != 0)
  228619. {
  228620. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  228621. depthBufferHandle = 0;
  228622. }
  228623. }
  228624. juce_UseDebuggingNewOperator
  228625. private:
  228626. Component::SafePointer<Component> component;
  228627. OpenGLPixelFormat pixelFormat;
  228628. JuceGLView* view;
  228629. CAEAGLLayer* glLayer;
  228630. EAGLContext* context;
  228631. bool useDepthBuffer;
  228632. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  228633. int numFrames;
  228634. int lastWidth, lastHeight;
  228635. GLESContext (const GLESContext&);
  228636. GLESContext& operator= (const GLESContext&);
  228637. };
  228638. OpenGLContext* OpenGLComponent::createContext()
  228639. {
  228640. ScopedAutoReleasePool pool;
  228641. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  228642. if (peer != 0)
  228643. return new GLESContext (peer, this, preferredPixelFormat,
  228644. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  228645. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  228646. return 0;
  228647. }
  228648. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  228649. OwnedArray <OpenGLPixelFormat>& /*results*/)
  228650. {
  228651. }
  228652. void juce_glViewport (const int w, const int h)
  228653. {
  228654. glViewport (0, 0, w, h);
  228655. }
  228656. #endif
  228657. #endif
  228658. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  228659. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  228660. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228661. // compiled on its own).
  228662. #if JUCE_INCLUDED_FILE
  228663. #if JUCE_MAC
  228664. namespace MouseCursorHelpers
  228665. {
  228666. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  228667. {
  228668. NSImage* im = CoreGraphicsImage::createNSImage (image);
  228669. NSCursor* c = [[NSCursor alloc] initWithImage: im
  228670. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  228671. [im release];
  228672. return c;
  228673. }
  228674. static void* fromWebKitFile (const char* filename, float hx, float hy)
  228675. {
  228676. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  228677. BufferedInputStream buf (&fileStream, 4096, false);
  228678. PNGImageFormat pngFormat;
  228679. Image im (pngFormat.decodeImage (buf));
  228680. if (im.isValid())
  228681. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  228682. jassertfalse;
  228683. return 0;
  228684. }
  228685. }
  228686. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  228687. {
  228688. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  228689. }
  228690. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  228691. {
  228692. const ScopedAutoReleasePool pool;
  228693. NSCursor* c = 0;
  228694. switch (type)
  228695. {
  228696. case NormalCursor: c = [NSCursor arrowCursor]; break;
  228697. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  228698. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  228699. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  228700. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  228701. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  228702. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  228703. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  228704. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  228705. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  228706. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  228707. case UpDownResizeCursor:
  228708. case TopEdgeResizeCursor:
  228709. case BottomEdgeResizeCursor:
  228710. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  228711. case TopLeftCornerResizeCursor:
  228712. case BottomRightCornerResizeCursor:
  228713. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  228714. case TopRightCornerResizeCursor:
  228715. case BottomLeftCornerResizeCursor:
  228716. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  228717. case UpDownLeftRightResizeCursor:
  228718. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  228719. default:
  228720. jassertfalse;
  228721. break;
  228722. }
  228723. [c retain];
  228724. return c;
  228725. }
  228726. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  228727. {
  228728. [((NSCursor*) cursorHandle) release];
  228729. }
  228730. void MouseCursor::showInAllWindows() const
  228731. {
  228732. showInWindow (0);
  228733. }
  228734. void MouseCursor::showInWindow (ComponentPeer*) const
  228735. {
  228736. [((NSCursor*) getHandle()) set];
  228737. }
  228738. #else
  228739. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  228740. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  228741. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  228742. void MouseCursor::showInAllWindows() const {}
  228743. void MouseCursor::showInWindow (ComponentPeer*) const {}
  228744. #endif
  228745. #endif
  228746. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  228747. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  228748. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228749. // compiled on its own).
  228750. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  228751. #if JUCE_MAC
  228752. END_JUCE_NAMESPACE
  228753. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  228754. @interface DownloadClickDetector : NSObject
  228755. {
  228756. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  228757. }
  228758. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  228759. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  228760. request: (NSURLRequest*) request
  228761. frame: (WebFrame*) frame
  228762. decisionListener: (id<WebPolicyDecisionListener>) listener;
  228763. @end
  228764. @implementation DownloadClickDetector
  228765. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  228766. {
  228767. [super init];
  228768. ownerComponent = ownerComponent_;
  228769. return self;
  228770. }
  228771. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  228772. request: (NSURLRequest*) request
  228773. frame: (WebFrame*) frame
  228774. decisionListener: (id <WebPolicyDecisionListener>) listener
  228775. {
  228776. (void) sender;
  228777. (void) request;
  228778. (void) frame;
  228779. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  228780. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  228781. [listener use];
  228782. else
  228783. [listener ignore];
  228784. }
  228785. @end
  228786. BEGIN_JUCE_NAMESPACE
  228787. class WebBrowserComponentInternal : public NSViewComponent
  228788. {
  228789. public:
  228790. WebBrowserComponentInternal (WebBrowserComponent* owner)
  228791. {
  228792. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  228793. frameName: @""
  228794. groupName: @""];
  228795. setView (webView);
  228796. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  228797. [webView setPolicyDelegate: clickListener];
  228798. }
  228799. ~WebBrowserComponentInternal()
  228800. {
  228801. [webView setPolicyDelegate: nil];
  228802. [clickListener release];
  228803. setView (0);
  228804. }
  228805. void goToURL (const String& url,
  228806. const StringArray* headers,
  228807. const MemoryBlock* postData)
  228808. {
  228809. NSMutableURLRequest* r
  228810. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  228811. cachePolicy: NSURLRequestUseProtocolCachePolicy
  228812. timeoutInterval: 30.0];
  228813. if (postData != 0 && postData->getSize() > 0)
  228814. {
  228815. [r setHTTPMethod: @"POST"];
  228816. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  228817. length: postData->getSize()]];
  228818. }
  228819. if (headers != 0)
  228820. {
  228821. for (int i = 0; i < headers->size(); ++i)
  228822. {
  228823. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  228824. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  228825. [r setValue: juceStringToNS (headerValue)
  228826. forHTTPHeaderField: juceStringToNS (headerName)];
  228827. }
  228828. }
  228829. stop();
  228830. [[webView mainFrame] loadRequest: r];
  228831. }
  228832. void goBack()
  228833. {
  228834. [webView goBack];
  228835. }
  228836. void goForward()
  228837. {
  228838. [webView goForward];
  228839. }
  228840. void stop()
  228841. {
  228842. [webView stopLoading: nil];
  228843. }
  228844. void refresh()
  228845. {
  228846. [webView reload: nil];
  228847. }
  228848. private:
  228849. WebView* webView;
  228850. DownloadClickDetector* clickListener;
  228851. };
  228852. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  228853. : browser (0),
  228854. blankPageShown (false),
  228855. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  228856. {
  228857. setOpaque (true);
  228858. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  228859. }
  228860. WebBrowserComponent::~WebBrowserComponent()
  228861. {
  228862. deleteAndZero (browser);
  228863. }
  228864. void WebBrowserComponent::goToURL (const String& url,
  228865. const StringArray* headers,
  228866. const MemoryBlock* postData)
  228867. {
  228868. lastURL = url;
  228869. lastHeaders.clear();
  228870. if (headers != 0)
  228871. lastHeaders = *headers;
  228872. lastPostData.setSize (0);
  228873. if (postData != 0)
  228874. lastPostData = *postData;
  228875. blankPageShown = false;
  228876. browser->goToURL (url, headers, postData);
  228877. }
  228878. void WebBrowserComponent::stop()
  228879. {
  228880. browser->stop();
  228881. }
  228882. void WebBrowserComponent::goBack()
  228883. {
  228884. lastURL = String::empty;
  228885. blankPageShown = false;
  228886. browser->goBack();
  228887. }
  228888. void WebBrowserComponent::goForward()
  228889. {
  228890. lastURL = String::empty;
  228891. browser->goForward();
  228892. }
  228893. void WebBrowserComponent::refresh()
  228894. {
  228895. browser->refresh();
  228896. }
  228897. void WebBrowserComponent::paint (Graphics&)
  228898. {
  228899. }
  228900. void WebBrowserComponent::checkWindowAssociation()
  228901. {
  228902. if (isShowing())
  228903. {
  228904. if (blankPageShown)
  228905. goBack();
  228906. }
  228907. else
  228908. {
  228909. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  228910. {
  228911. // when the component becomes invisible, some stuff like flash
  228912. // carries on playing audio, so we need to force it onto a blank
  228913. // page to avoid this, (and send it back when it's made visible again).
  228914. blankPageShown = true;
  228915. browser->goToURL ("about:blank", 0, 0);
  228916. }
  228917. }
  228918. }
  228919. void WebBrowserComponent::reloadLastURL()
  228920. {
  228921. if (lastURL.isNotEmpty())
  228922. {
  228923. goToURL (lastURL, &lastHeaders, &lastPostData);
  228924. lastURL = String::empty;
  228925. }
  228926. }
  228927. void WebBrowserComponent::parentHierarchyChanged()
  228928. {
  228929. checkWindowAssociation();
  228930. }
  228931. void WebBrowserComponent::resized()
  228932. {
  228933. browser->setSize (getWidth(), getHeight());
  228934. }
  228935. void WebBrowserComponent::visibilityChanged()
  228936. {
  228937. checkWindowAssociation();
  228938. }
  228939. bool WebBrowserComponent::pageAboutToLoad (const String&)
  228940. {
  228941. return true;
  228942. }
  228943. #else
  228944. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  228945. {
  228946. }
  228947. WebBrowserComponent::~WebBrowserComponent()
  228948. {
  228949. }
  228950. void WebBrowserComponent::goToURL (const String& url,
  228951. const StringArray* headers,
  228952. const MemoryBlock* postData)
  228953. {
  228954. }
  228955. void WebBrowserComponent::stop()
  228956. {
  228957. }
  228958. void WebBrowserComponent::goBack()
  228959. {
  228960. }
  228961. void WebBrowserComponent::goForward()
  228962. {
  228963. }
  228964. void WebBrowserComponent::refresh()
  228965. {
  228966. }
  228967. void WebBrowserComponent::paint (Graphics& g)
  228968. {
  228969. }
  228970. void WebBrowserComponent::checkWindowAssociation()
  228971. {
  228972. }
  228973. void WebBrowserComponent::reloadLastURL()
  228974. {
  228975. }
  228976. void WebBrowserComponent::parentHierarchyChanged()
  228977. {
  228978. }
  228979. void WebBrowserComponent::resized()
  228980. {
  228981. }
  228982. void WebBrowserComponent::visibilityChanged()
  228983. {
  228984. }
  228985. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  228986. {
  228987. return true;
  228988. }
  228989. #endif
  228990. #endif
  228991. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  228992. /*** Start of inlined file: juce_iphone_Audio.cpp ***/
  228993. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228994. // compiled on its own).
  228995. #if JUCE_INCLUDED_FILE
  228996. class IPhoneAudioIODevice : public AudioIODevice
  228997. {
  228998. public:
  228999. IPhoneAudioIODevice (const String& deviceName)
  229000. : AudioIODevice (deviceName, "Audio"),
  229001. audioUnit (0),
  229002. isRunning (false),
  229003. callback (0),
  229004. actualBufferSize (0),
  229005. floatData (1, 2)
  229006. {
  229007. numInputChannels = 2;
  229008. numOutputChannels = 2;
  229009. preferredBufferSize = 0;
  229010. AudioSessionInitialize (0, 0, interruptionListenerStatic, this);
  229011. updateDeviceInfo();
  229012. }
  229013. ~IPhoneAudioIODevice()
  229014. {
  229015. close();
  229016. }
  229017. const StringArray getOutputChannelNames()
  229018. {
  229019. StringArray s;
  229020. s.add ("Left");
  229021. s.add ("Right");
  229022. return s;
  229023. }
  229024. const StringArray getInputChannelNames()
  229025. {
  229026. StringArray s;
  229027. if (audioInputIsAvailable)
  229028. {
  229029. s.add ("Left");
  229030. s.add ("Right");
  229031. }
  229032. return s;
  229033. }
  229034. int getNumSampleRates()
  229035. {
  229036. return 1;
  229037. }
  229038. double getSampleRate (int index)
  229039. {
  229040. return sampleRate;
  229041. }
  229042. int getNumBufferSizesAvailable()
  229043. {
  229044. return 1;
  229045. }
  229046. int getBufferSizeSamples (int index)
  229047. {
  229048. return getDefaultBufferSize();
  229049. }
  229050. int getDefaultBufferSize()
  229051. {
  229052. return 1024;
  229053. }
  229054. const String open (const BigInteger& inputChannels,
  229055. const BigInteger& outputChannels,
  229056. double sampleRate,
  229057. int bufferSize)
  229058. {
  229059. close();
  229060. lastError = String::empty;
  229061. preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  229062. // xxx set up channel mapping
  229063. activeOutputChans = outputChannels;
  229064. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  229065. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  229066. monoOutputChannelNumber = activeOutputChans.findNextSetBit (0);
  229067. activeInputChans = inputChannels;
  229068. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  229069. numInputChannels = activeInputChans.countNumberOfSetBits();
  229070. monoInputChannelNumber = activeInputChans.findNextSetBit (0);
  229071. AudioSessionSetActive (true);
  229072. UInt32 audioCategory = audioInputIsAvailable ? kAudioSessionCategory_PlayAndRecord
  229073. : kAudioSessionCategory_MediaPlayback;
  229074. AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (audioCategory), &audioCategory);
  229075. AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, propertyChangedStatic, this);
  229076. fixAudioRouteIfSetToReceiver();
  229077. updateDeviceInfo();
  229078. Float32 bufferDuration = preferredBufferSize / sampleRate;
  229079. AudioSessionSetProperty (kAudioSessionProperty_PreferredHardwareIOBufferDuration, sizeof (bufferDuration), &bufferDuration);
  229080. actualBufferSize = preferredBufferSize;
  229081. prepareFloatBuffers();
  229082. isRunning = true;
  229083. propertyChanged (0, 0, 0); // creates and starts the AU
  229084. lastError = audioUnit != 0 ? "" : "Couldn't open the device";
  229085. return lastError;
  229086. }
  229087. void close()
  229088. {
  229089. if (isRunning)
  229090. {
  229091. isRunning = false;
  229092. AudioSessionSetActive (false);
  229093. if (audioUnit != 0)
  229094. {
  229095. AudioComponentInstanceDispose (audioUnit);
  229096. audioUnit = 0;
  229097. }
  229098. }
  229099. }
  229100. bool isOpen()
  229101. {
  229102. return isRunning;
  229103. }
  229104. int getCurrentBufferSizeSamples()
  229105. {
  229106. return actualBufferSize;
  229107. }
  229108. double getCurrentSampleRate()
  229109. {
  229110. return sampleRate;
  229111. }
  229112. int getCurrentBitDepth()
  229113. {
  229114. return 16;
  229115. }
  229116. const BigInteger getActiveOutputChannels() const
  229117. {
  229118. return activeOutputChans;
  229119. }
  229120. const BigInteger getActiveInputChannels() const
  229121. {
  229122. return activeInputChans;
  229123. }
  229124. int getOutputLatencyInSamples()
  229125. {
  229126. return 0; //xxx
  229127. }
  229128. int getInputLatencyInSamples()
  229129. {
  229130. return 0; //xxx
  229131. }
  229132. void start (AudioIODeviceCallback* callback_)
  229133. {
  229134. if (isRunning && callback != callback_)
  229135. {
  229136. if (callback_ != 0)
  229137. callback_->audioDeviceAboutToStart (this);
  229138. const ScopedLock sl (callbackLock);
  229139. callback = callback_;
  229140. }
  229141. }
  229142. void stop()
  229143. {
  229144. if (isRunning)
  229145. {
  229146. AudioIODeviceCallback* lastCallback;
  229147. {
  229148. const ScopedLock sl (callbackLock);
  229149. lastCallback = callback;
  229150. callback = 0;
  229151. }
  229152. if (lastCallback != 0)
  229153. lastCallback->audioDeviceStopped();
  229154. }
  229155. }
  229156. bool isPlaying()
  229157. {
  229158. return isRunning && callback != 0;
  229159. }
  229160. const String getLastError()
  229161. {
  229162. return lastError;
  229163. }
  229164. private:
  229165. CriticalSection callbackLock;
  229166. Float64 sampleRate;
  229167. int numInputChannels, numOutputChannels;
  229168. int preferredBufferSize;
  229169. int actualBufferSize;
  229170. bool isRunning;
  229171. String lastError;
  229172. AudioStreamBasicDescription format;
  229173. AudioUnit audioUnit;
  229174. UInt32 audioInputIsAvailable;
  229175. AudioIODeviceCallback* callback;
  229176. BigInteger activeOutputChans, activeInputChans;
  229177. AudioSampleBuffer floatData;
  229178. float* inputChannels[3];
  229179. float* outputChannels[3];
  229180. bool monoInputChannelNumber, monoOutputChannelNumber;
  229181. void prepareFloatBuffers()
  229182. {
  229183. floatData.setSize (numInputChannels + numOutputChannels, actualBufferSize);
  229184. zerostruct (inputChannels);
  229185. zerostruct (outputChannels);
  229186. for (int i = 0; i < numInputChannels; ++i)
  229187. inputChannels[i] = floatData.getSampleData (i);
  229188. for (int i = 0; i < numOutputChannels; ++i)
  229189. outputChannels[i] = floatData.getSampleData (i + numInputChannels);
  229190. }
  229191. OSStatus process (AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  229192. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  229193. {
  229194. OSStatus err = noErr;
  229195. if (audioInputIsAvailable)
  229196. err = AudioUnitRender (audioUnit, ioActionFlags, inTimeStamp, 1, inNumberFrames, ioData);
  229197. const ScopedLock sl (callbackLock);
  229198. if (callback != 0)
  229199. {
  229200. if (audioInputIsAvailable && numInputChannels > 0)
  229201. {
  229202. short* shortData = (short*) ioData->mBuffers[0].mData;
  229203. if (numInputChannels >= 2)
  229204. {
  229205. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229206. {
  229207. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  229208. inputChannels[1][i] = *shortData++ * (1.0f / 32768.0f);
  229209. }
  229210. }
  229211. else
  229212. {
  229213. if (monoInputChannelNumber > 0)
  229214. ++shortData;
  229215. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229216. {
  229217. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  229218. ++shortData;
  229219. }
  229220. }
  229221. }
  229222. else
  229223. {
  229224. for (int i = numInputChannels; --i >= 0;)
  229225. zeromem (inputChannels[i], sizeof (float) * inNumberFrames);
  229226. }
  229227. callback->audioDeviceIOCallback ((const float**) inputChannels, numInputChannels,
  229228. outputChannels, numOutputChannels,
  229229. (int) inNumberFrames);
  229230. short* shortData = (short*) ioData->mBuffers[0].mData;
  229231. int n = 0;
  229232. if (numOutputChannels >= 2)
  229233. {
  229234. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229235. {
  229236. shortData [n++] = (short) (outputChannels[0][i] * 32767.0f);
  229237. shortData [n++] = (short) (outputChannels[1][i] * 32767.0f);
  229238. }
  229239. }
  229240. else if (numOutputChannels == 1)
  229241. {
  229242. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229243. {
  229244. const short s = (short) (outputChannels[monoOutputChannelNumber][i] * 32767.0f);
  229245. shortData [n++] = s;
  229246. shortData [n++] = s;
  229247. }
  229248. }
  229249. else
  229250. {
  229251. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  229252. }
  229253. }
  229254. else
  229255. {
  229256. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  229257. }
  229258. return err;
  229259. }
  229260. void updateDeviceInfo()
  229261. {
  229262. UInt32 size = sizeof (sampleRate);
  229263. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareSampleRate, &size, &sampleRate);
  229264. size = sizeof (audioInputIsAvailable);
  229265. AudioSessionGetProperty (kAudioSessionProperty_AudioInputAvailable, &size, &audioInputIsAvailable);
  229266. }
  229267. void propertyChanged (AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  229268. {
  229269. if (! isRunning)
  229270. return;
  229271. if (inPropertyValue != 0)
  229272. {
  229273. CFDictionaryRef routeChangeDictionary = (CFDictionaryRef) inPropertyValue;
  229274. CFNumberRef routeChangeReasonRef = (CFNumberRef) CFDictionaryGetValue (routeChangeDictionary,
  229275. CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
  229276. SInt32 routeChangeReason;
  229277. CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
  229278. if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable)
  229279. fixAudioRouteIfSetToReceiver();
  229280. }
  229281. updateDeviceInfo();
  229282. createAudioUnit();
  229283. AudioSessionSetActive (true);
  229284. if (audioUnit != 0)
  229285. {
  229286. UInt32 formatSize = sizeof (format);
  229287. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, &formatSize);
  229288. Float32 bufferDuration = preferredBufferSize / sampleRate;
  229289. UInt32 bufferDurationSize = sizeof (bufferDuration);
  229290. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareIOBufferDuration, &bufferDurationSize, &bufferDurationSize);
  229291. actualBufferSize = (int) (sampleRate * bufferDuration + 0.5);
  229292. AudioOutputUnitStart (audioUnit);
  229293. }
  229294. }
  229295. void interruptionListener (UInt32 inInterruption)
  229296. {
  229297. /*if (inInterruption == kAudioSessionBeginInterruption)
  229298. {
  229299. isRunning = false;
  229300. AudioOutputUnitStop (audioUnit);
  229301. if (juce_iPhoneShowModalAlert ("Audio Interrupted",
  229302. "This could have been interrupted by another application or by unplugging a headset",
  229303. @"Resume",
  229304. @"Cancel"))
  229305. {
  229306. isRunning = true;
  229307. propertyChanged (0, 0, 0);
  229308. }
  229309. }*/
  229310. if (inInterruption == kAudioSessionEndInterruption)
  229311. {
  229312. isRunning = true;
  229313. AudioSessionSetActive (true);
  229314. AudioOutputUnitStart (audioUnit);
  229315. }
  229316. }
  229317. static OSStatus processStatic (void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  229318. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  229319. {
  229320. return ((IPhoneAudioIODevice*) inRefCon)->process (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  229321. }
  229322. static void propertyChangedStatic (void* inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  229323. {
  229324. ((IPhoneAudioIODevice*) inClientData)->propertyChanged (inID, inDataSize, inPropertyValue);
  229325. }
  229326. static void interruptionListenerStatic (void* inClientData, UInt32 inInterruption)
  229327. {
  229328. ((IPhoneAudioIODevice*) inClientData)->interruptionListener (inInterruption);
  229329. }
  229330. void resetFormat (const int numChannels)
  229331. {
  229332. memset (&format, 0, sizeof (format));
  229333. format.mFormatID = kAudioFormatLinearPCM;
  229334. format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
  229335. format.mBitsPerChannel = 8 * sizeof (short);
  229336. format.mChannelsPerFrame = 2;
  229337. format.mFramesPerPacket = 1;
  229338. format.mBytesPerFrame = format.mBytesPerPacket = 2 * sizeof (short);
  229339. }
  229340. bool createAudioUnit()
  229341. {
  229342. if (audioUnit != 0)
  229343. {
  229344. AudioComponentInstanceDispose (audioUnit);
  229345. audioUnit = 0;
  229346. }
  229347. resetFormat (2);
  229348. AudioComponentDescription desc;
  229349. desc.componentType = kAudioUnitType_Output;
  229350. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  229351. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  229352. desc.componentFlags = 0;
  229353. desc.componentFlagsMask = 0;
  229354. AudioComponent comp = AudioComponentFindNext (0, &desc);
  229355. AudioComponentInstanceNew (comp, &audioUnit);
  229356. if (audioUnit == 0)
  229357. return false;
  229358. const UInt32 one = 1;
  229359. AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &one, sizeof (one));
  229360. AudioChannelLayout layout;
  229361. layout.mChannelBitmap = 0;
  229362. layout.mNumberChannelDescriptions = 0;
  229363. layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  229364. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input, 0, &layout, sizeof (layout));
  229365. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Output, 0, &layout, sizeof (layout));
  229366. AURenderCallbackStruct inputProc;
  229367. inputProc.inputProc = processStatic;
  229368. inputProc.inputProcRefCon = this;
  229369. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &inputProc, sizeof (inputProc));
  229370. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof (format));
  229371. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, sizeof (format));
  229372. AudioUnitInitialize (audioUnit);
  229373. return true;
  229374. }
  229375. // If the routing is set to go through the receiver (i.e. the speaker, but quiet), this re-routes it
  229376. // to make it loud. Needed because by default when using an input + output, the output is kept quiet.
  229377. static void fixAudioRouteIfSetToReceiver()
  229378. {
  229379. CFStringRef audioRoute = 0;
  229380. UInt32 propertySize = sizeof (audioRoute);
  229381. if (AudioSessionGetProperty (kAudioSessionProperty_AudioRoute, &propertySize, &audioRoute) == noErr)
  229382. {
  229383. NSString* route = (NSString*) audioRoute;
  229384. //DBG ("audio route: " + nsStringToJuce (route));
  229385. if ([route hasPrefix: @"Receiver"])
  229386. {
  229387. UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
  229388. AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
  229389. }
  229390. CFRelease (audioRoute);
  229391. }
  229392. }
  229393. IPhoneAudioIODevice (const IPhoneAudioIODevice&);
  229394. IPhoneAudioIODevice& operator= (const IPhoneAudioIODevice&);
  229395. };
  229396. class IPhoneAudioIODeviceType : public AudioIODeviceType
  229397. {
  229398. public:
  229399. IPhoneAudioIODeviceType()
  229400. : AudioIODeviceType ("iPhone Audio")
  229401. {
  229402. }
  229403. ~IPhoneAudioIODeviceType()
  229404. {
  229405. }
  229406. void scanForDevices()
  229407. {
  229408. }
  229409. const StringArray getDeviceNames (bool wantInputNames) const
  229410. {
  229411. StringArray s;
  229412. s.add ("iPhone Audio");
  229413. return s;
  229414. }
  229415. int getDefaultDeviceIndex (bool forInput) const
  229416. {
  229417. return 0;
  229418. }
  229419. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  229420. {
  229421. return device != 0 ? 0 : -1;
  229422. }
  229423. bool hasSeparateInputsAndOutputs() const { return false; }
  229424. AudioIODevice* createDevice (const String& outputDeviceName,
  229425. const String& inputDeviceName)
  229426. {
  229427. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  229428. {
  229429. return new IPhoneAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  229430. : inputDeviceName);
  229431. }
  229432. return 0;
  229433. }
  229434. juce_UseDebuggingNewOperator
  229435. private:
  229436. IPhoneAudioIODeviceType (const IPhoneAudioIODeviceType&);
  229437. IPhoneAudioIODeviceType& operator= (const IPhoneAudioIODeviceType&);
  229438. };
  229439. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio()
  229440. {
  229441. return new IPhoneAudioIODeviceType();
  229442. }
  229443. #endif
  229444. /*** End of inlined file: juce_iphone_Audio.cpp ***/
  229445. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  229446. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229447. // compiled on its own).
  229448. #if JUCE_INCLUDED_FILE
  229449. #if JUCE_MAC
  229450. namespace CoreMidiHelpers
  229451. {
  229452. static bool logError (const OSStatus err, const int lineNum)
  229453. {
  229454. if (err == noErr)
  229455. return true;
  229456. Logger::writeToLog ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  229457. jassertfalse;
  229458. return false;
  229459. }
  229460. #undef CHECK_ERROR
  229461. #define CHECK_ERROR(a) CoreMidiHelpers::logError (a, __LINE__)
  229462. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  229463. {
  229464. String result;
  229465. CFStringRef str = 0;
  229466. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  229467. if (str != 0)
  229468. {
  229469. result = PlatformUtilities::cfStringToJuceString (str);
  229470. CFRelease (str);
  229471. str = 0;
  229472. }
  229473. MIDIEntityRef entity = 0;
  229474. MIDIEndpointGetEntity (endpoint, &entity);
  229475. if (entity == 0)
  229476. return result; // probably virtual
  229477. if (result.isEmpty())
  229478. {
  229479. // endpoint name has zero length - try the entity
  229480. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  229481. if (str != 0)
  229482. {
  229483. result += PlatformUtilities::cfStringToJuceString (str);
  229484. CFRelease (str);
  229485. str = 0;
  229486. }
  229487. }
  229488. // now consider the device's name
  229489. MIDIDeviceRef device = 0;
  229490. MIDIEntityGetDevice (entity, &device);
  229491. if (device == 0)
  229492. return result;
  229493. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  229494. if (str != 0)
  229495. {
  229496. const String s (PlatformUtilities::cfStringToJuceString (str));
  229497. CFRelease (str);
  229498. // if an external device has only one entity, throw away
  229499. // the endpoint name and just use the device name
  229500. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  229501. {
  229502. result = s;
  229503. }
  229504. else if (! result.startsWithIgnoreCase (s))
  229505. {
  229506. // prepend the device name to the entity name
  229507. result = (s + " " + result).trimEnd();
  229508. }
  229509. }
  229510. return result;
  229511. }
  229512. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  229513. {
  229514. String result;
  229515. // Does the endpoint have connections?
  229516. CFDataRef connections = 0;
  229517. int numConnections = 0;
  229518. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  229519. if (connections != 0)
  229520. {
  229521. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  229522. if (numConnections > 0)
  229523. {
  229524. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  229525. for (int i = 0; i < numConnections; ++i, ++pid)
  229526. {
  229527. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  229528. MIDIObjectRef connObject;
  229529. MIDIObjectType connObjectType;
  229530. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  229531. if (err == noErr)
  229532. {
  229533. String s;
  229534. if (connObjectType == kMIDIObjectType_ExternalSource
  229535. || connObjectType == kMIDIObjectType_ExternalDestination)
  229536. {
  229537. // Connected to an external device's endpoint (10.3 and later).
  229538. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  229539. }
  229540. else
  229541. {
  229542. // Connected to an external device (10.2) (or something else, catch-all)
  229543. CFStringRef str = 0;
  229544. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  229545. if (str != 0)
  229546. {
  229547. s = PlatformUtilities::cfStringToJuceString (str);
  229548. CFRelease (str);
  229549. }
  229550. }
  229551. if (s.isNotEmpty())
  229552. {
  229553. if (result.isNotEmpty())
  229554. result += ", ";
  229555. result += s;
  229556. }
  229557. }
  229558. }
  229559. }
  229560. CFRelease (connections);
  229561. }
  229562. if (result.isNotEmpty())
  229563. return result;
  229564. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  229565. return getEndpointName (endpoint, false);
  229566. }
  229567. static MIDIClientRef getGlobalMidiClient()
  229568. {
  229569. static MIDIClientRef globalMidiClient = 0;
  229570. if (globalMidiClient == 0)
  229571. {
  229572. String name ("JUCE");
  229573. if (JUCEApplication::getInstance() != 0)
  229574. name = JUCEApplication::getInstance()->getApplicationName();
  229575. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  229576. CHECK_ERROR (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  229577. CFRelease (appName);
  229578. }
  229579. return globalMidiClient;
  229580. }
  229581. class MidiPortAndEndpoint
  229582. {
  229583. public:
  229584. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  229585. : port (port_), endPoint (endPoint_)
  229586. {
  229587. }
  229588. ~MidiPortAndEndpoint()
  229589. {
  229590. if (port != 0)
  229591. MIDIPortDispose (port);
  229592. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  229593. MIDIEndpointDispose (endPoint);
  229594. }
  229595. void send (const MIDIPacketList* const packets)
  229596. {
  229597. if (port != 0)
  229598. MIDISend (port, endPoint, packets);
  229599. else
  229600. MIDIReceived (endPoint, packets);
  229601. }
  229602. MIDIPortRef port;
  229603. MIDIEndpointRef endPoint;
  229604. };
  229605. class MidiPortAndCallback;
  229606. static CriticalSection callbackLock;
  229607. static Array<MidiPortAndCallback*> activeCallbacks;
  229608. class MidiPortAndCallback
  229609. {
  229610. public:
  229611. MidiPortAndCallback (MidiInputCallback& callback_)
  229612. : input (0), active (false), callback (callback_), concatenator (2048)
  229613. {
  229614. }
  229615. ~MidiPortAndCallback()
  229616. {
  229617. active = false;
  229618. {
  229619. const ScopedLock sl (callbackLock);
  229620. activeCallbacks.removeValue (this);
  229621. }
  229622. if (portAndEndpoint != 0 && portAndEndpoint->port != 0)
  229623. CHECK_ERROR (MIDIPortDisconnectSource (portAndEndpoint->port, portAndEndpoint->endPoint));
  229624. }
  229625. void handlePackets (const MIDIPacketList* const pktlist)
  229626. {
  229627. const double time = Time::getMillisecondCounterHiRes() * 0.001;
  229628. const ScopedLock sl (callbackLock);
  229629. if (activeCallbacks.contains (this) && active)
  229630. {
  229631. const MIDIPacket* packet = &pktlist->packet[0];
  229632. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  229633. {
  229634. concatenator.pushMidiData (packet->data, (int) packet->length, time,
  229635. input, callback);
  229636. packet = MIDIPacketNext (packet);
  229637. }
  229638. }
  229639. }
  229640. MidiInput* input;
  229641. ScopedPointer<MidiPortAndEndpoint> portAndEndpoint;
  229642. volatile bool active;
  229643. private:
  229644. MidiInputCallback& callback;
  229645. MidiDataConcatenator concatenator;
  229646. };
  229647. static void midiInputProc (const MIDIPacketList* pktlist, void* readProcRefCon, void* /*srcConnRefCon*/)
  229648. {
  229649. static_cast <MidiPortAndCallback*> (readProcRefCon)->handlePackets (pktlist);
  229650. }
  229651. }
  229652. const StringArray MidiOutput::getDevices()
  229653. {
  229654. StringArray s;
  229655. const ItemCount num = MIDIGetNumberOfDestinations();
  229656. for (ItemCount i = 0; i < num; ++i)
  229657. {
  229658. MIDIEndpointRef dest = MIDIGetDestination (i);
  229659. if (dest != 0)
  229660. {
  229661. String name (CoreMidiHelpers::getConnectedEndpointName (dest));
  229662. if (name.isEmpty())
  229663. name = "<error>";
  229664. s.add (name);
  229665. }
  229666. else
  229667. {
  229668. s.add ("<error>");
  229669. }
  229670. }
  229671. return s;
  229672. }
  229673. int MidiOutput::getDefaultDeviceIndex()
  229674. {
  229675. return 0;
  229676. }
  229677. MidiOutput* MidiOutput::openDevice (int index)
  229678. {
  229679. MidiOutput* mo = 0;
  229680. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  229681. {
  229682. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  229683. CFStringRef pname;
  229684. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  229685. {
  229686. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  229687. MIDIPortRef port;
  229688. if (client != 0 && CHECK_ERROR (MIDIOutputPortCreate (client, pname, &port)))
  229689. {
  229690. mo = new MidiOutput();
  229691. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (port, endPoint);
  229692. }
  229693. CFRelease (pname);
  229694. }
  229695. }
  229696. return mo;
  229697. }
  229698. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  229699. {
  229700. MidiOutput* mo = 0;
  229701. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  229702. MIDIEndpointRef endPoint;
  229703. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  229704. if (client != 0 && CHECK_ERROR (MIDISourceCreate (client, name, &endPoint)))
  229705. {
  229706. mo = new MidiOutput();
  229707. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (0, endPoint);
  229708. }
  229709. CFRelease (name);
  229710. return mo;
  229711. }
  229712. MidiOutput::~MidiOutput()
  229713. {
  229714. delete static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  229715. }
  229716. void MidiOutput::reset()
  229717. {
  229718. }
  229719. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  229720. {
  229721. return false;
  229722. }
  229723. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  229724. {
  229725. }
  229726. void MidiOutput::sendMessageNow (const MidiMessage& message)
  229727. {
  229728. CoreMidiHelpers::MidiPortAndEndpoint* const mpe = static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  229729. if (message.isSysEx())
  229730. {
  229731. const int maxPacketSize = 256;
  229732. int pos = 0, bytesLeft = message.getRawDataSize();
  229733. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  229734. HeapBlock <MIDIPacketList> packets;
  229735. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  229736. packets->numPackets = numPackets;
  229737. MIDIPacket* p = packets->packet;
  229738. for (int i = 0; i < numPackets; ++i)
  229739. {
  229740. p->timeStamp = 0;
  229741. p->length = jmin (maxPacketSize, bytesLeft);
  229742. memcpy (p->data, message.getRawData() + pos, p->length);
  229743. pos += p->length;
  229744. bytesLeft -= p->length;
  229745. p = MIDIPacketNext (p);
  229746. }
  229747. mpe->send (packets);
  229748. }
  229749. else
  229750. {
  229751. MIDIPacketList packets;
  229752. packets.numPackets = 1;
  229753. packets.packet[0].timeStamp = 0;
  229754. packets.packet[0].length = message.getRawDataSize();
  229755. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  229756. mpe->send (&packets);
  229757. }
  229758. }
  229759. const StringArray MidiInput::getDevices()
  229760. {
  229761. StringArray s;
  229762. const ItemCount num = MIDIGetNumberOfSources();
  229763. for (ItemCount i = 0; i < num; ++i)
  229764. {
  229765. MIDIEndpointRef source = MIDIGetSource (i);
  229766. if (source != 0)
  229767. {
  229768. String name (CoreMidiHelpers::getConnectedEndpointName (source));
  229769. if (name.isEmpty())
  229770. name = "<error>";
  229771. s.add (name);
  229772. }
  229773. else
  229774. {
  229775. s.add ("<error>");
  229776. }
  229777. }
  229778. return s;
  229779. }
  229780. int MidiInput::getDefaultDeviceIndex()
  229781. {
  229782. return 0;
  229783. }
  229784. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  229785. {
  229786. jassert (callback != 0);
  229787. using namespace CoreMidiHelpers;
  229788. MidiInput* newInput = 0;
  229789. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  229790. {
  229791. MIDIEndpointRef endPoint = MIDIGetSource (index);
  229792. if (endPoint != 0)
  229793. {
  229794. CFStringRef name;
  229795. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &name)))
  229796. {
  229797. MIDIClientRef client = getGlobalMidiClient();
  229798. if (client != 0)
  229799. {
  229800. MIDIPortRef port;
  229801. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  229802. if (CHECK_ERROR (MIDIInputPortCreate (client, name, midiInputProc, mpc, &port)))
  229803. {
  229804. if (CHECK_ERROR (MIDIPortConnectSource (port, endPoint, 0)))
  229805. {
  229806. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  229807. newInput = new MidiInput (getDevices() [index]);
  229808. mpc->input = newInput;
  229809. newInput->internal = mpc;
  229810. const ScopedLock sl (callbackLock);
  229811. activeCallbacks.add (mpc.release());
  229812. }
  229813. else
  229814. {
  229815. CHECK_ERROR (MIDIPortDispose (port));
  229816. }
  229817. }
  229818. }
  229819. }
  229820. CFRelease (name);
  229821. }
  229822. }
  229823. return newInput;
  229824. }
  229825. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  229826. {
  229827. jassert (callback != 0);
  229828. using namespace CoreMidiHelpers;
  229829. MidiInput* mi = 0;
  229830. MIDIClientRef client = getGlobalMidiClient();
  229831. if (client != 0)
  229832. {
  229833. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  229834. mpc->active = false;
  229835. MIDIEndpointRef endPoint;
  229836. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  229837. if (CHECK_ERROR (MIDIDestinationCreate (client, name, midiInputProc, mpc, &endPoint)))
  229838. {
  229839. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  229840. mi = new MidiInput (deviceName);
  229841. mpc->input = mi;
  229842. mi->internal = mpc;
  229843. const ScopedLock sl (callbackLock);
  229844. activeCallbacks.add (mpc.release());
  229845. }
  229846. CFRelease (name);
  229847. }
  229848. return mi;
  229849. }
  229850. MidiInput::MidiInput (const String& name_)
  229851. : name (name_)
  229852. {
  229853. }
  229854. MidiInput::~MidiInput()
  229855. {
  229856. delete static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal);
  229857. }
  229858. void MidiInput::start()
  229859. {
  229860. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  229861. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = true;
  229862. }
  229863. void MidiInput::stop()
  229864. {
  229865. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  229866. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = false;
  229867. }
  229868. #undef CHECK_ERROR
  229869. #else // Stubs for iOS...
  229870. MidiOutput::~MidiOutput() {}
  229871. void MidiOutput::reset() {}
  229872. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/) { return false; }
  229873. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/) {}
  229874. void MidiOutput::sendMessageNow (const MidiMessage& message) {}
  229875. const StringArray MidiOutput::getDevices() { return StringArray(); }
  229876. MidiOutput* MidiOutput::openDevice (int index) { return 0; }
  229877. const StringArray MidiInput::getDevices() { return StringArray(); }
  229878. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback) { return 0; }
  229879. #endif
  229880. #endif
  229881. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  229882. #else
  229883. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  229884. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229885. // compiled on its own).
  229886. #if JUCE_INCLUDED_FILE
  229887. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  229888. #define SUPPORT_10_4_FONTS 1
  229889. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  229890. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  229891. #define SUPPORT_ONLY_10_4_FONTS 1
  229892. #endif
  229893. END_JUCE_NAMESPACE
  229894. @interface NSFont (PrivateHack)
  229895. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  229896. @end
  229897. BEGIN_JUCE_NAMESPACE
  229898. #endif
  229899. class MacTypeface : public Typeface
  229900. {
  229901. public:
  229902. MacTypeface (const Font& font)
  229903. : Typeface (font.getTypefaceName())
  229904. {
  229905. const ScopedAutoReleasePool pool;
  229906. renderingTransform = CGAffineTransformIdentity;
  229907. bool needsItalicTransform = false;
  229908. #if JUCE_IOS
  229909. NSString* fontName = juceStringToNS (font.getTypefaceName());
  229910. if (font.isItalic() || font.isBold())
  229911. {
  229912. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  229913. for (NSString* i in familyFonts)
  229914. {
  229915. const String fn (nsStringToJuce (i));
  229916. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  229917. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  229918. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  229919. || afterDash.containsIgnoreCase ("italic")
  229920. || fn.endsWithIgnoreCase ("oblique")
  229921. || fn.endsWithIgnoreCase ("italic");
  229922. if (probablyBold == font.isBold()
  229923. && probablyItalic == font.isItalic())
  229924. {
  229925. fontName = i;
  229926. needsItalicTransform = false;
  229927. break;
  229928. }
  229929. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  229930. {
  229931. fontName = i;
  229932. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  229933. }
  229934. }
  229935. if (needsItalicTransform)
  229936. renderingTransform.c = 0.15f;
  229937. }
  229938. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  229939. const int ascender = abs (CGFontGetAscent (fontRef));
  229940. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  229941. ascent = ascender / totalHeight;
  229942. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229943. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  229944. #else
  229945. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  229946. if (font.isItalic())
  229947. {
  229948. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  229949. toHaveTrait: NSItalicFontMask];
  229950. if (newFont == nsFont)
  229951. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  229952. nsFont = newFont;
  229953. }
  229954. if (font.isBold())
  229955. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  229956. [nsFont retain];
  229957. ascent = std::abs ((float) [nsFont ascender]);
  229958. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  229959. ascent /= totalSize;
  229960. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  229961. if (needsItalicTransform)
  229962. {
  229963. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  229964. renderingTransform.c = 0.15f;
  229965. }
  229966. #if SUPPORT_ONLY_10_4_FONTS
  229967. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229968. if (atsFont == 0)
  229969. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229970. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  229971. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  229972. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229973. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  229974. #else
  229975. #if SUPPORT_10_4_FONTS
  229976. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  229977. {
  229978. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229979. if (atsFont == 0)
  229980. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  229981. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  229982. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  229983. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229984. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  229985. }
  229986. else
  229987. #endif
  229988. {
  229989. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  229990. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  229991. unitsToHeightScaleFactor = 1.0f / totalHeight;
  229992. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  229993. }
  229994. #endif
  229995. #endif
  229996. }
  229997. ~MacTypeface()
  229998. {
  229999. #if ! JUCE_IOS
  230000. [nsFont release];
  230001. #endif
  230002. if (fontRef != 0)
  230003. CGFontRelease (fontRef);
  230004. }
  230005. float getAscent() const
  230006. {
  230007. return ascent;
  230008. }
  230009. float getDescent() const
  230010. {
  230011. return 1.0f - ascent;
  230012. }
  230013. float getStringWidth (const String& text)
  230014. {
  230015. if (fontRef == 0 || text.isEmpty())
  230016. return 0;
  230017. const int length = text.length();
  230018. HeapBlock <CGGlyph> glyphs;
  230019. createGlyphsForString (text, length, glyphs);
  230020. float x = 0;
  230021. #if SUPPORT_ONLY_10_4_FONTS
  230022. HeapBlock <NSSize> advances (length);
  230023. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  230024. for (int i = 0; i < length; ++i)
  230025. x += advances[i].width;
  230026. #else
  230027. #if SUPPORT_10_4_FONTS
  230028. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230029. {
  230030. HeapBlock <NSSize> advances (length);
  230031. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  230032. for (int i = 0; i < length; ++i)
  230033. x += advances[i].width;
  230034. }
  230035. else
  230036. #endif
  230037. {
  230038. HeapBlock <int> advances (length);
  230039. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  230040. for (int i = 0; i < length; ++i)
  230041. x += advances[i];
  230042. }
  230043. #endif
  230044. return x * unitsToHeightScaleFactor;
  230045. }
  230046. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  230047. {
  230048. xOffsets.add (0);
  230049. if (fontRef == 0 || text.isEmpty())
  230050. return;
  230051. const int length = text.length();
  230052. HeapBlock <CGGlyph> glyphs;
  230053. createGlyphsForString (text, length, glyphs);
  230054. #if SUPPORT_ONLY_10_4_FONTS
  230055. HeapBlock <NSSize> advances (length);
  230056. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  230057. int x = 0;
  230058. for (int i = 0; i < length; ++i)
  230059. {
  230060. x += advances[i].width;
  230061. xOffsets.add (x * unitsToHeightScaleFactor);
  230062. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  230063. }
  230064. #else
  230065. #if SUPPORT_10_4_FONTS
  230066. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230067. {
  230068. HeapBlock <NSSize> advances (length);
  230069. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  230070. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  230071. float x = 0;
  230072. for (int i = 0; i < length; ++i)
  230073. {
  230074. x += advances[i].width;
  230075. xOffsets.add (x * unitsToHeightScaleFactor);
  230076. resultGlyphs.add (nsGlyphs[i]);
  230077. }
  230078. }
  230079. else
  230080. #endif
  230081. {
  230082. HeapBlock <int> advances (length);
  230083. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  230084. {
  230085. int x = 0;
  230086. for (int i = 0; i < length; ++i)
  230087. {
  230088. x += advances [i];
  230089. xOffsets.add (x * unitsToHeightScaleFactor);
  230090. resultGlyphs.add (glyphs[i]);
  230091. }
  230092. }
  230093. }
  230094. #endif
  230095. }
  230096. bool getOutlineForGlyph (int glyphNumber, Path& path)
  230097. {
  230098. #if JUCE_IOS
  230099. return false;
  230100. #else
  230101. if (nsFont == 0)
  230102. return false;
  230103. // we might need to apply a transform to the path, so it mustn't have anything else in it
  230104. jassert (path.isEmpty());
  230105. const ScopedAutoReleasePool pool;
  230106. NSBezierPath* bez = [NSBezierPath bezierPath];
  230107. [bez moveToPoint: NSMakePoint (0, 0)];
  230108. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  230109. inFont: nsFont];
  230110. for (int i = 0; i < [bez elementCount]; ++i)
  230111. {
  230112. NSPoint p[3];
  230113. switch ([bez elementAtIndex: i associatedPoints: p])
  230114. {
  230115. case NSMoveToBezierPathElement:
  230116. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  230117. break;
  230118. case NSLineToBezierPathElement:
  230119. path.lineTo ((float) p[0].x, (float) -p[0].y);
  230120. break;
  230121. case NSCurveToBezierPathElement:
  230122. 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);
  230123. break;
  230124. case NSClosePathBezierPathElement:
  230125. path.closeSubPath();
  230126. break;
  230127. default:
  230128. jassertfalse;
  230129. break;
  230130. }
  230131. }
  230132. path.applyTransform (pathTransform);
  230133. return true;
  230134. #endif
  230135. }
  230136. juce_UseDebuggingNewOperator
  230137. CGFontRef fontRef;
  230138. float fontHeightToCGSizeFactor;
  230139. CGAffineTransform renderingTransform;
  230140. private:
  230141. float ascent, unitsToHeightScaleFactor;
  230142. #if JUCE_IOS
  230143. #else
  230144. NSFont* nsFont;
  230145. AffineTransform pathTransform;
  230146. #endif
  230147. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  230148. {
  230149. #if SUPPORT_10_4_FONTS
  230150. #if ! SUPPORT_ONLY_10_4_FONTS
  230151. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230152. #endif
  230153. {
  230154. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  230155. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  230156. for (int i = 0; i < length; ++i)
  230157. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  230158. return;
  230159. }
  230160. #endif
  230161. #if ! SUPPORT_ONLY_10_4_FONTS
  230162. if (charToGlyphMapper == 0)
  230163. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  230164. glyphs.malloc (length);
  230165. for (int i = 0; i < length; ++i)
  230166. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  230167. #endif
  230168. }
  230169. #if ! SUPPORT_ONLY_10_4_FONTS
  230170. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  230171. class CharToGlyphMapper
  230172. {
  230173. public:
  230174. CharToGlyphMapper (CGFontRef fontRef)
  230175. : segCount (0), endCode (0), startCode (0), idDelta (0),
  230176. idRangeOffset (0), glyphIndexes (0)
  230177. {
  230178. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  230179. if (cmapTable != 0)
  230180. {
  230181. const int numSubtables = getValue16 (cmapTable, 2);
  230182. for (int i = 0; i < numSubtables; ++i)
  230183. {
  230184. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  230185. {
  230186. const int offset = getValue32 (cmapTable, i * 8 + 8);
  230187. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  230188. {
  230189. const int length = getValue16 (cmapTable, offset + 2);
  230190. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  230191. segCount = segCountX2 / 2;
  230192. const int endCodeOffset = offset + 14;
  230193. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  230194. const int idDeltaOffset = startCodeOffset + segCountX2;
  230195. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  230196. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  230197. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  230198. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  230199. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  230200. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  230201. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  230202. }
  230203. break;
  230204. }
  230205. }
  230206. CFRelease (cmapTable);
  230207. }
  230208. }
  230209. ~CharToGlyphMapper()
  230210. {
  230211. if (endCode != 0)
  230212. {
  230213. CFRelease (endCode);
  230214. CFRelease (startCode);
  230215. CFRelease (idDelta);
  230216. CFRelease (idRangeOffset);
  230217. CFRelease (glyphIndexes);
  230218. }
  230219. }
  230220. int getGlyphForCharacter (const juce_wchar c) const
  230221. {
  230222. for (int i = 0; i < segCount; ++i)
  230223. {
  230224. if (getValue16 (endCode, i * 2) >= c)
  230225. {
  230226. const int start = getValue16 (startCode, i * 2);
  230227. if (start > c)
  230228. break;
  230229. const int delta = getValue16 (idDelta, i * 2);
  230230. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  230231. if (rangeOffset == 0)
  230232. return delta + c;
  230233. else
  230234. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  230235. }
  230236. }
  230237. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  230238. return jmax (-1, (int) c - 29);
  230239. }
  230240. private:
  230241. int segCount;
  230242. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  230243. static uint16 getValue16 (CFDataRef data, const int index)
  230244. {
  230245. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  230246. }
  230247. static uint32 getValue32 (CFDataRef data, const int index)
  230248. {
  230249. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  230250. }
  230251. };
  230252. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  230253. #endif
  230254. MacTypeface (const MacTypeface&);
  230255. MacTypeface& operator= (const MacTypeface&);
  230256. };
  230257. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  230258. {
  230259. return new MacTypeface (font);
  230260. }
  230261. const StringArray Font::findAllTypefaceNames()
  230262. {
  230263. StringArray names;
  230264. const ScopedAutoReleasePool pool;
  230265. #if JUCE_IOS
  230266. NSArray* fonts = [UIFont familyNames];
  230267. #else
  230268. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  230269. #endif
  230270. for (unsigned int i = 0; i < [fonts count]; ++i)
  230271. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  230272. names.sort (true);
  230273. return names;
  230274. }
  230275. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  230276. {
  230277. #if JUCE_IOS
  230278. defaultSans = "Helvetica";
  230279. defaultSerif = "Times New Roman";
  230280. defaultFixed = "Courier New";
  230281. #else
  230282. defaultSans = "Lucida Grande";
  230283. defaultSerif = "Times New Roman";
  230284. defaultFixed = "Monaco";
  230285. #endif
  230286. }
  230287. #endif
  230288. /*** End of inlined file: juce_mac_Fonts.mm ***/
  230289. // (must go before juce_mac_CoreGraphicsContext.mm)
  230290. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  230291. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230292. // compiled on its own).
  230293. #if JUCE_INCLUDED_FILE
  230294. class CoreGraphicsImage : public Image::SharedImage
  230295. {
  230296. public:
  230297. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  230298. : Image::SharedImage (format_, width_, height_)
  230299. {
  230300. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  230301. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  230302. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  230303. imageData = imageDataAllocated;
  230304. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  230305. : CGColorSpaceCreateDeviceRGB();
  230306. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  230307. colourSpace, getCGImageFlags (format_));
  230308. CGColorSpaceRelease (colourSpace);
  230309. }
  230310. ~CoreGraphicsImage()
  230311. {
  230312. CGContextRelease (context);
  230313. }
  230314. Image::ImageType getType() const { return Image::NativeImage; }
  230315. LowLevelGraphicsContext* createLowLevelContext();
  230316. SharedImage* clone()
  230317. {
  230318. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  230319. memcpy (im->imageData, imageData, lineStride * height);
  230320. return im;
  230321. }
  230322. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  230323. {
  230324. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  230325. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  230326. {
  230327. return CGBitmapContextCreateImage (nativeImage->context);
  230328. }
  230329. else
  230330. {
  230331. const Image::BitmapData srcData (juceImage, false);
  230332. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  230333. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  230334. 8, srcData.pixelStride * 8, srcData.lineStride,
  230335. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  230336. 0, true, kCGRenderingIntentDefault);
  230337. CGDataProviderRelease (provider);
  230338. return imageRef;
  230339. }
  230340. }
  230341. #if JUCE_MAC
  230342. static NSImage* createNSImage (const Image& image)
  230343. {
  230344. const ScopedAutoReleasePool pool;
  230345. NSImage* im = [[NSImage alloc] init];
  230346. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  230347. [im lockFocus];
  230348. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  230349. CGImageRef imageRef = createImage (image, false, colourSpace);
  230350. CGColorSpaceRelease (colourSpace);
  230351. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  230352. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  230353. CGImageRelease (imageRef);
  230354. [im unlockFocus];
  230355. return im;
  230356. }
  230357. #endif
  230358. CGContextRef context;
  230359. HeapBlock<uint8> imageDataAllocated;
  230360. private:
  230361. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  230362. {
  230363. #if JUCE_BIG_ENDIAN
  230364. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  230365. #else
  230366. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  230367. #endif
  230368. }
  230369. };
  230370. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  230371. {
  230372. #if USE_COREGRAPHICS_RENDERING
  230373. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  230374. #else
  230375. return createSoftwareImage (format, width, height, clearImage);
  230376. #endif
  230377. }
  230378. class CoreGraphicsContext : public LowLevelGraphicsContext
  230379. {
  230380. public:
  230381. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  230382. : context (context_),
  230383. flipHeight (flipHeight_),
  230384. state (new SavedState()),
  230385. numGradientLookupEntries (0),
  230386. lastClipRectIsValid (false)
  230387. {
  230388. CGContextRetain (context);
  230389. CGContextSaveGState(context);
  230390. CGContextSetShouldSmoothFonts (context, true);
  230391. CGContextSetShouldAntialias (context, true);
  230392. CGContextSetBlendMode (context, kCGBlendModeNormal);
  230393. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  230394. greyColourSpace = CGColorSpaceCreateDeviceGray();
  230395. gradientCallbacks.version = 0;
  230396. gradientCallbacks.evaluate = gradientCallback;
  230397. gradientCallbacks.releaseInfo = 0;
  230398. setFont (Font());
  230399. }
  230400. ~CoreGraphicsContext()
  230401. {
  230402. CGContextRestoreGState (context);
  230403. CGContextRelease (context);
  230404. CGColorSpaceRelease (rgbColourSpace);
  230405. CGColorSpaceRelease (greyColourSpace);
  230406. }
  230407. bool isVectorDevice() const { return false; }
  230408. void setOrigin (int x, int y)
  230409. {
  230410. CGContextTranslateCTM (context, x, -y);
  230411. if (lastClipRectIsValid)
  230412. lastClipRect.translate (-x, -y);
  230413. }
  230414. bool clipToRectangle (const Rectangle<int>& r)
  230415. {
  230416. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  230417. if (lastClipRectIsValid)
  230418. {
  230419. // This is actually incorrect, because the actual clip region may be complex, and
  230420. // clipping its bounds to a rect may not be right... But, removing this shortcut
  230421. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  230422. // when calculating the resultant clip bounds, and makes the same mistake!
  230423. lastClipRect = lastClipRect.getIntersection (r);
  230424. return ! lastClipRect.isEmpty();
  230425. }
  230426. return ! isClipEmpty();
  230427. }
  230428. bool clipToRectangleList (const RectangleList& clipRegion)
  230429. {
  230430. if (clipRegion.isEmpty())
  230431. {
  230432. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  230433. lastClipRectIsValid = true;
  230434. lastClipRect = Rectangle<int>();
  230435. return false;
  230436. }
  230437. else
  230438. {
  230439. const int numRects = clipRegion.getNumRectangles();
  230440. HeapBlock <CGRect> rects (numRects);
  230441. for (int i = 0; i < numRects; ++i)
  230442. {
  230443. const Rectangle<int>& r = clipRegion.getRectangle(i);
  230444. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  230445. }
  230446. CGContextClipToRects (context, rects, numRects);
  230447. lastClipRectIsValid = false;
  230448. return ! isClipEmpty();
  230449. }
  230450. }
  230451. void excludeClipRectangle (const Rectangle<int>& r)
  230452. {
  230453. RectangleList remaining (getClipBounds());
  230454. remaining.subtract (r);
  230455. clipToRectangleList (remaining);
  230456. lastClipRectIsValid = false;
  230457. }
  230458. void clipToPath (const Path& path, const AffineTransform& transform)
  230459. {
  230460. createPath (path, transform);
  230461. CGContextClip (context);
  230462. lastClipRectIsValid = false;
  230463. }
  230464. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  230465. {
  230466. if (! transform.isSingularity())
  230467. {
  230468. Image singleChannelImage (sourceImage);
  230469. if (sourceImage.getFormat() != Image::SingleChannel)
  230470. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  230471. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  230472. flip();
  230473. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  230474. applyTransform (t);
  230475. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  230476. CGContextClipToMask (context, r, image);
  230477. applyTransform (t.inverted());
  230478. flip();
  230479. CGImageRelease (image);
  230480. lastClipRectIsValid = false;
  230481. }
  230482. }
  230483. bool clipRegionIntersects (const Rectangle<int>& r)
  230484. {
  230485. return getClipBounds().intersects (r);
  230486. }
  230487. const Rectangle<int> getClipBounds() const
  230488. {
  230489. if (! lastClipRectIsValid)
  230490. {
  230491. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  230492. lastClipRectIsValid = true;
  230493. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  230494. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  230495. roundToInt (bounds.size.width),
  230496. roundToInt (bounds.size.height));
  230497. }
  230498. return lastClipRect;
  230499. }
  230500. bool isClipEmpty() const
  230501. {
  230502. return getClipBounds().isEmpty();
  230503. }
  230504. void saveState()
  230505. {
  230506. CGContextSaveGState (context);
  230507. stateStack.add (new SavedState (*state));
  230508. }
  230509. void restoreState()
  230510. {
  230511. CGContextRestoreGState (context);
  230512. SavedState* const top = stateStack.getLast();
  230513. if (top != 0)
  230514. {
  230515. state = top;
  230516. stateStack.removeLast (1, false);
  230517. lastClipRectIsValid = false;
  230518. }
  230519. else
  230520. {
  230521. jassertfalse; // trying to pop with an empty stack!
  230522. }
  230523. }
  230524. void setFill (const FillType& fillType)
  230525. {
  230526. state->fillType = fillType;
  230527. if (fillType.isColour())
  230528. {
  230529. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  230530. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  230531. CGContextSetAlpha (context, 1.0f);
  230532. }
  230533. }
  230534. void setOpacity (float newOpacity)
  230535. {
  230536. state->fillType.setOpacity (newOpacity);
  230537. setFill (state->fillType);
  230538. }
  230539. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  230540. {
  230541. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  230542. ? kCGInterpolationLow
  230543. : kCGInterpolationHigh);
  230544. }
  230545. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  230546. {
  230547. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  230548. }
  230549. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  230550. {
  230551. if (replaceExistingContents)
  230552. {
  230553. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  230554. CGContextClearRect (context, cgRect);
  230555. #else
  230556. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230557. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  230558. CGContextClearRect (context, cgRect);
  230559. else
  230560. #endif
  230561. CGContextSetBlendMode (context, kCGBlendModeCopy);
  230562. #endif
  230563. fillCGRect (cgRect, false);
  230564. CGContextSetBlendMode (context, kCGBlendModeNormal);
  230565. }
  230566. else
  230567. {
  230568. if (state->fillType.isColour())
  230569. {
  230570. CGContextFillRect (context, cgRect);
  230571. }
  230572. else if (state->fillType.isGradient())
  230573. {
  230574. CGContextSaveGState (context);
  230575. CGContextClipToRect (context, cgRect);
  230576. drawGradient();
  230577. CGContextRestoreGState (context);
  230578. }
  230579. else
  230580. {
  230581. CGContextSaveGState (context);
  230582. CGContextClipToRect (context, cgRect);
  230583. drawImage (state->fillType.image, state->fillType.transform, true);
  230584. CGContextRestoreGState (context);
  230585. }
  230586. }
  230587. }
  230588. void fillPath (const Path& path, const AffineTransform& transform)
  230589. {
  230590. CGContextSaveGState (context);
  230591. if (state->fillType.isColour())
  230592. {
  230593. flip();
  230594. applyTransform (transform);
  230595. createPath (path);
  230596. if (path.isUsingNonZeroWinding())
  230597. CGContextFillPath (context);
  230598. else
  230599. CGContextEOFillPath (context);
  230600. }
  230601. else
  230602. {
  230603. createPath (path, transform);
  230604. if (path.isUsingNonZeroWinding())
  230605. CGContextClip (context);
  230606. else
  230607. CGContextEOClip (context);
  230608. if (state->fillType.isGradient())
  230609. drawGradient();
  230610. else
  230611. drawImage (state->fillType.image, state->fillType.transform, true);
  230612. }
  230613. CGContextRestoreGState (context);
  230614. }
  230615. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  230616. {
  230617. const int iw = sourceImage.getWidth();
  230618. const int ih = sourceImage.getHeight();
  230619. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  230620. CGContextSaveGState (context);
  230621. CGContextSetAlpha (context, state->fillType.getOpacity());
  230622. flip();
  230623. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  230624. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  230625. if (fillEntireClipAsTiles)
  230626. {
  230627. #if JUCE_IOS
  230628. CGContextDrawTiledImage (context, imageRect, image);
  230629. #else
  230630. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  230631. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  230632. // if it's doing a transformation - it's quicker to just draw lots of images manually
  230633. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  230634. CGContextDrawTiledImage (context, imageRect, image);
  230635. else
  230636. #endif
  230637. {
  230638. // Fallback to manually doing a tiled fill on 10.4
  230639. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  230640. int x = 0, y = 0;
  230641. while (x > clip.origin.x) x -= iw;
  230642. while (y > clip.origin.y) y -= ih;
  230643. const int right = (int) (clip.origin.x + clip.size.width);
  230644. const int bottom = (int) (clip.origin.y + clip.size.height);
  230645. while (y < bottom)
  230646. {
  230647. for (int x2 = x; x2 < right; x2 += iw)
  230648. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  230649. y += ih;
  230650. }
  230651. }
  230652. #endif
  230653. }
  230654. else
  230655. {
  230656. CGContextDrawImage (context, imageRect, image);
  230657. }
  230658. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  230659. CGContextRestoreGState (context);
  230660. }
  230661. void drawLine (const Line<float>& line)
  230662. {
  230663. if (state->fillType.isColour())
  230664. {
  230665. CGContextSetLineCap (context, kCGLineCapSquare);
  230666. CGContextSetLineWidth (context, 1.0f);
  230667. CGContextSetRGBStrokeColor (context,
  230668. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  230669. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  230670. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  230671. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  230672. CGContextStrokeLineSegments (context, cgLine, 1);
  230673. }
  230674. else
  230675. {
  230676. Path p;
  230677. p.addLineSegment (line, 1.0f);
  230678. fillPath (p, AffineTransform::identity);
  230679. }
  230680. }
  230681. void drawVerticalLine (const int x, float top, float bottom)
  230682. {
  230683. if (state->fillType.isColour())
  230684. {
  230685. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  230686. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  230687. #else
  230688. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  230689. // the x co-ord slightly to trick it..
  230690. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  230691. #endif
  230692. }
  230693. else
  230694. {
  230695. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  230696. }
  230697. }
  230698. void drawHorizontalLine (const int y, float left, float right)
  230699. {
  230700. if (state->fillType.isColour())
  230701. {
  230702. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  230703. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  230704. #else
  230705. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  230706. // the x co-ord slightly to trick it..
  230707. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  230708. #endif
  230709. }
  230710. else
  230711. {
  230712. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  230713. }
  230714. }
  230715. void setFont (const Font& newFont)
  230716. {
  230717. if (state->font != newFont)
  230718. {
  230719. state->fontRef = 0;
  230720. state->font = newFont;
  230721. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  230722. if (mf != 0)
  230723. {
  230724. state->fontRef = mf->fontRef;
  230725. CGContextSetFont (context, state->fontRef);
  230726. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  230727. state->fontTransform = mf->renderingTransform;
  230728. state->fontTransform.a *= state->font.getHorizontalScale();
  230729. CGContextSetTextMatrix (context, state->fontTransform);
  230730. }
  230731. }
  230732. }
  230733. const Font getFont()
  230734. {
  230735. return state->font;
  230736. }
  230737. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  230738. {
  230739. if (state->fontRef != 0 && state->fillType.isColour())
  230740. {
  230741. if (transform.isOnlyTranslation())
  230742. {
  230743. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  230744. CGGlyph g = glyphNumber;
  230745. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  230746. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  230747. }
  230748. else
  230749. {
  230750. CGContextSaveGState (context);
  230751. flip();
  230752. applyTransform (transform);
  230753. CGAffineTransform t = state->fontTransform;
  230754. t.d = -t.d;
  230755. CGContextSetTextMatrix (context, t);
  230756. CGGlyph g = glyphNumber;
  230757. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  230758. CGContextRestoreGState (context);
  230759. }
  230760. }
  230761. else
  230762. {
  230763. Path p;
  230764. Font& f = state->font;
  230765. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  230766. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  230767. .followedBy (transform));
  230768. }
  230769. }
  230770. private:
  230771. CGContextRef context;
  230772. const CGFloat flipHeight;
  230773. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  230774. CGFunctionCallbacks gradientCallbacks;
  230775. mutable Rectangle<int> lastClipRect;
  230776. mutable bool lastClipRectIsValid;
  230777. struct SavedState
  230778. {
  230779. SavedState()
  230780. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  230781. {
  230782. }
  230783. SavedState (const SavedState& other)
  230784. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  230785. fontTransform (other.fontTransform)
  230786. {
  230787. }
  230788. ~SavedState()
  230789. {
  230790. }
  230791. FillType fillType;
  230792. Font font;
  230793. CGFontRef fontRef;
  230794. CGAffineTransform fontTransform;
  230795. };
  230796. ScopedPointer <SavedState> state;
  230797. OwnedArray <SavedState> stateStack;
  230798. HeapBlock <PixelARGB> gradientLookupTable;
  230799. int numGradientLookupEntries;
  230800. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  230801. {
  230802. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  230803. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  230804. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  230805. colour.unpremultiply();
  230806. outData[0] = colour.getRed() / 255.0f;
  230807. outData[1] = colour.getGreen() / 255.0f;
  230808. outData[2] = colour.getBlue() / 255.0f;
  230809. outData[3] = colour.getAlpha() / 255.0f;
  230810. }
  230811. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  230812. {
  230813. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  230814. --numGradientLookupEntries;
  230815. CGShadingRef result = 0;
  230816. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  230817. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  230818. if (gradient.isRadial)
  230819. {
  230820. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  230821. p1, gradient.point1.getDistanceFrom (gradient.point2),
  230822. function, true, true);
  230823. }
  230824. else
  230825. {
  230826. result = CGShadingCreateAxial (rgbColourSpace, p1,
  230827. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  230828. function, true, true);
  230829. }
  230830. CGFunctionRelease (function);
  230831. return result;
  230832. }
  230833. void drawGradient()
  230834. {
  230835. flip();
  230836. applyTransform (state->fillType.transform);
  230837. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  230838. // you draw a gradient with high quality interp enabled).
  230839. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  230840. CGContextSetAlpha (context, state->fillType.getOpacity());
  230841. CGContextDrawShading (context, shading);
  230842. CGShadingRelease (shading);
  230843. }
  230844. void createPath (const Path& path) const
  230845. {
  230846. CGContextBeginPath (context);
  230847. Path::Iterator i (path);
  230848. while (i.next())
  230849. {
  230850. switch (i.elementType)
  230851. {
  230852. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  230853. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  230854. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  230855. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  230856. case Path::Iterator::closePath: CGContextClosePath (context); break;
  230857. default: jassertfalse; break;
  230858. }
  230859. }
  230860. }
  230861. void createPath (const Path& path, const AffineTransform& transform) const
  230862. {
  230863. CGContextBeginPath (context);
  230864. Path::Iterator i (path);
  230865. while (i.next())
  230866. {
  230867. switch (i.elementType)
  230868. {
  230869. case Path::Iterator::startNewSubPath:
  230870. transform.transformPoint (i.x1, i.y1);
  230871. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  230872. break;
  230873. case Path::Iterator::lineTo:
  230874. transform.transformPoint (i.x1, i.y1);
  230875. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  230876. break;
  230877. case Path::Iterator::quadraticTo:
  230878. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  230879. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  230880. break;
  230881. case Path::Iterator::cubicTo:
  230882. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  230883. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  230884. break;
  230885. case Path::Iterator::closePath:
  230886. CGContextClosePath (context); break;
  230887. default:
  230888. jassertfalse;
  230889. break;
  230890. }
  230891. }
  230892. }
  230893. void flip() const
  230894. {
  230895. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  230896. }
  230897. void applyTransform (const AffineTransform& transform) const
  230898. {
  230899. CGAffineTransform t;
  230900. t.a = transform.mat00;
  230901. t.b = transform.mat10;
  230902. t.c = transform.mat01;
  230903. t.d = transform.mat11;
  230904. t.tx = transform.mat02;
  230905. t.ty = transform.mat12;
  230906. CGContextConcatCTM (context, t);
  230907. }
  230908. CoreGraphicsContext (const CoreGraphicsContext&);
  230909. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  230910. };
  230911. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  230912. {
  230913. return new CoreGraphicsContext (context, height);
  230914. }
  230915. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  230916. const Image juce_loadWithCoreImage (InputStream& input)
  230917. {
  230918. MemoryBlock data;
  230919. input.readIntoMemoryBlock (data, -1);
  230920. #if JUCE_IOS
  230921. JUCE_AUTORELEASEPOOL
  230922. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData()
  230923. length: data.getSize()
  230924. freeWhenDone: NO]];
  230925. if (image != nil)
  230926. {
  230927. CGImageRef loadedImage = image.CGImage;
  230928. #else
  230929. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  230930. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  230931. CGDataProviderRelease (provider);
  230932. if (imageSource != 0)
  230933. {
  230934. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  230935. CFRelease (imageSource);
  230936. #endif
  230937. if (loadedImage != 0)
  230938. {
  230939. const bool hasAlphaChan = CGImageGetAlphaInfo (loadedImage) != kCGImageAlphaNone;
  230940. Image image (hasAlphaChan ? Image::ARGB : Image::RGB,
  230941. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  230942. hasAlphaChan, Image::NativeImage);
  230943. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  230944. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  230945. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  230946. CGContextFlush (cgImage->context);
  230947. #if ! JUCE_IOS
  230948. CFRelease (loadedImage);
  230949. #endif
  230950. return image;
  230951. }
  230952. }
  230953. return Image::null;
  230954. }
  230955. #endif
  230956. #endif
  230957. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  230958. /*** Start of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  230959. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230960. // compiled on its own).
  230961. #if JUCE_INCLUDED_FILE
  230962. class NSViewComponentPeer;
  230963. END_JUCE_NAMESPACE
  230964. @interface NSEvent (JuceDeviceDelta)
  230965. - (float) deviceDeltaX;
  230966. - (float) deviceDeltaY;
  230967. @end
  230968. #define JuceNSView MakeObjCClassName(JuceNSView)
  230969. @interface JuceNSView : NSView<NSTextInput>
  230970. {
  230971. @public
  230972. NSViewComponentPeer* owner;
  230973. NSNotificationCenter* notificationCenter;
  230974. String* stringBeingComposed;
  230975. bool textWasInserted;
  230976. }
  230977. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  230978. - (void) dealloc;
  230979. - (BOOL) isOpaque;
  230980. - (void) drawRect: (NSRect) r;
  230981. - (void) mouseDown: (NSEvent*) ev;
  230982. - (void) asyncMouseDown: (NSEvent*) ev;
  230983. - (void) mouseUp: (NSEvent*) ev;
  230984. - (void) asyncMouseUp: (NSEvent*) ev;
  230985. - (void) mouseDragged: (NSEvent*) ev;
  230986. - (void) mouseMoved: (NSEvent*) ev;
  230987. - (void) mouseEntered: (NSEvent*) ev;
  230988. - (void) mouseExited: (NSEvent*) ev;
  230989. - (void) rightMouseDown: (NSEvent*) ev;
  230990. - (void) rightMouseDragged: (NSEvent*) ev;
  230991. - (void) rightMouseUp: (NSEvent*) ev;
  230992. - (void) otherMouseDown: (NSEvent*) ev;
  230993. - (void) otherMouseDragged: (NSEvent*) ev;
  230994. - (void) otherMouseUp: (NSEvent*) ev;
  230995. - (void) scrollWheel: (NSEvent*) ev;
  230996. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  230997. - (void) frameChanged: (NSNotification*) n;
  230998. - (void) viewDidMoveToWindow;
  230999. - (void) keyDown: (NSEvent*) ev;
  231000. - (void) keyUp: (NSEvent*) ev;
  231001. // NSTextInput Methods
  231002. - (void) insertText: (id) aString;
  231003. - (void) doCommandBySelector: (SEL) aSelector;
  231004. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selRange;
  231005. - (void) unmarkText;
  231006. - (BOOL) hasMarkedText;
  231007. - (long) conversationIdentifier;
  231008. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange;
  231009. - (NSRange) markedRange;
  231010. - (NSRange) selectedRange;
  231011. - (NSRect) firstRectForCharacterRange: (NSRange) theRange;
  231012. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint;
  231013. - (NSArray*) validAttributesForMarkedText;
  231014. - (void) flagsChanged: (NSEvent*) ev;
  231015. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231016. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  231017. #endif
  231018. - (BOOL) becomeFirstResponder;
  231019. - (BOOL) resignFirstResponder;
  231020. - (BOOL) acceptsFirstResponder;
  231021. - (void) asyncRepaint: (id) rect;
  231022. - (NSArray*) getSupportedDragTypes;
  231023. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  231024. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  231025. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  231026. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  231027. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  231028. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  231029. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  231030. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  231031. @end
  231032. #define JuceNSWindow MakeObjCClassName(JuceNSWindow)
  231033. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  231034. @interface JuceNSWindow : NSWindow <NSWindowDelegate>
  231035. #else
  231036. @interface JuceNSWindow : NSWindow
  231037. #endif
  231038. {
  231039. @private
  231040. NSViewComponentPeer* owner;
  231041. bool isZooming;
  231042. }
  231043. - (void) setOwner: (NSViewComponentPeer*) owner;
  231044. - (BOOL) canBecomeKeyWindow;
  231045. - (void) becomeKeyWindow;
  231046. - (BOOL) windowShouldClose: (id) window;
  231047. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  231048. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  231049. - (void) zoom: (id) sender;
  231050. @end
  231051. BEGIN_JUCE_NAMESPACE
  231052. class NSViewComponentPeer : public ComponentPeer
  231053. {
  231054. public:
  231055. NSViewComponentPeer (Component* const component,
  231056. const int windowStyleFlags,
  231057. NSView* viewToAttachTo);
  231058. ~NSViewComponentPeer();
  231059. void* getNativeHandle() const;
  231060. void setVisible (bool shouldBeVisible);
  231061. void setTitle (const String& title);
  231062. void setPosition (int x, int y);
  231063. void setSize (int w, int h);
  231064. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  231065. const Rectangle<int> getBounds (const bool global) const;
  231066. const Rectangle<int> getBounds() const;
  231067. const Point<int> getScreenPosition() const;
  231068. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  231069. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  231070. void setMinimised (bool shouldBeMinimised);
  231071. bool isMinimised() const;
  231072. void setFullScreen (bool shouldBeFullScreen);
  231073. bool isFullScreen() const;
  231074. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  231075. const BorderSize getFrameSize() const;
  231076. bool setAlwaysOnTop (bool alwaysOnTop);
  231077. void toFront (bool makeActiveWindow);
  231078. void toBehind (ComponentPeer* other);
  231079. void setIcon (const Image& newIcon);
  231080. const StringArray getAvailableRenderingEngines();
  231081. int getCurrentRenderingEngine() throw();
  231082. void setCurrentRenderingEngine (int index);
  231083. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  231084. for example having more than one juce plugin loaded into a host, then when a
  231085. method is called, the actual code that runs might actually be in a different module
  231086. than the one you expect... So any calls to library functions or statics that are
  231087. made inside obj-c methods will probably end up getting executed in a different DLL's
  231088. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  231089. To work around this insanity, I'm only allowing obj-c methods to make calls to
  231090. virtual methods of an object that's known to live inside the right module's space.
  231091. */
  231092. virtual void redirectMouseDown (NSEvent* ev);
  231093. virtual void redirectMouseUp (NSEvent* ev);
  231094. virtual void redirectMouseDrag (NSEvent* ev);
  231095. virtual void redirectMouseMove (NSEvent* ev);
  231096. virtual void redirectMouseEnter (NSEvent* ev);
  231097. virtual void redirectMouseExit (NSEvent* ev);
  231098. virtual void redirectMouseWheel (NSEvent* ev);
  231099. void sendMouseEvent (NSEvent* ev);
  231100. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  231101. virtual bool redirectKeyDown (NSEvent* ev);
  231102. virtual bool redirectKeyUp (NSEvent* ev);
  231103. virtual void redirectModKeyChange (NSEvent* ev);
  231104. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231105. virtual bool redirectPerformKeyEquivalent (NSEvent* ev);
  231106. #endif
  231107. virtual BOOL sendDragCallback (int type, id <NSDraggingInfo> sender);
  231108. virtual bool isOpaque();
  231109. virtual void drawRect (NSRect r);
  231110. virtual bool canBecomeKeyWindow();
  231111. virtual bool windowShouldClose();
  231112. virtual void redirectMovedOrResized();
  231113. virtual void viewMovedToWindow();
  231114. virtual NSRect constrainRect (NSRect r);
  231115. static void showArrowCursorIfNeeded();
  231116. static void updateModifiers (NSEvent* e);
  231117. static void updateKeysDown (NSEvent* ev, bool isKeyDown);
  231118. static int getKeyCodeFromEvent (NSEvent* ev)
  231119. {
  231120. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  231121. int keyCode = unmodified[0];
  231122. if (keyCode == 0x19) // (backwards-tab)
  231123. keyCode = '\t';
  231124. else if (keyCode == 0x03) // (enter)
  231125. keyCode = '\r';
  231126. else
  231127. keyCode = (int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  231128. if (([ev modifierFlags] & NSNumericPadKeyMask) != 0)
  231129. {
  231130. const int numPadConversions[] = { '0', KeyPress::numberPad0, '1', KeyPress::numberPad1,
  231131. '2', KeyPress::numberPad2, '3', KeyPress::numberPad3,
  231132. '4', KeyPress::numberPad4, '5', KeyPress::numberPad5,
  231133. '6', KeyPress::numberPad6, '7', KeyPress::numberPad7,
  231134. '8', KeyPress::numberPad8, '9', KeyPress::numberPad9,
  231135. '+', KeyPress::numberPadAdd, '-', KeyPress::numberPadSubtract,
  231136. '*', KeyPress::numberPadMultiply, '/', KeyPress::numberPadDivide,
  231137. '.', KeyPress::numberPadDecimalPoint, '=', KeyPress::numberPadEquals };
  231138. for (int i = 0; i < numElementsInArray (numPadConversions); i += 2)
  231139. if (keyCode == numPadConversions [i])
  231140. keyCode = numPadConversions [i + 1];
  231141. }
  231142. return keyCode;
  231143. }
  231144. static int64 getMouseTime (NSEvent* e)
  231145. {
  231146. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  231147. + (int64) ([e timestamp] * 1000.0);
  231148. }
  231149. static const Point<int> getMousePos (NSEvent* e, NSView* view)
  231150. {
  231151. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  231152. return Point<int> (roundToInt (p.x), roundToInt ([view frame].size.height - p.y));
  231153. }
  231154. static int getModifierForButtonNumber (const NSInteger num)
  231155. {
  231156. return num == 0 ? ModifierKeys::leftButtonModifier
  231157. : (num == 1 ? ModifierKeys::rightButtonModifier
  231158. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  231159. }
  231160. virtual void viewFocusGain();
  231161. virtual void viewFocusLoss();
  231162. bool isFocused() const;
  231163. void grabFocus();
  231164. void textInputRequired (const Point<int>& position);
  231165. void repaint (const Rectangle<int>& area);
  231166. void performAnyPendingRepaintsNow();
  231167. juce_UseDebuggingNewOperator
  231168. NSWindow* window;
  231169. JuceNSView* view;
  231170. bool isSharedWindow, fullScreen, insideDrawRect, usingCoreGraphics, recursiveToFrontCall;
  231171. static ModifierKeys currentModifiers;
  231172. static ComponentPeer* currentlyFocusedPeer;
  231173. static Array<int> keysCurrentlyDown;
  231174. };
  231175. END_JUCE_NAMESPACE
  231176. @implementation JuceNSView
  231177. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  231178. withFrame: (NSRect) frame
  231179. {
  231180. [super initWithFrame: frame];
  231181. owner = owner_;
  231182. stringBeingComposed = 0;
  231183. textWasInserted = false;
  231184. notificationCenter = [NSNotificationCenter defaultCenter];
  231185. [notificationCenter addObserver: self
  231186. selector: @selector (frameChanged:)
  231187. name: NSViewFrameDidChangeNotification
  231188. object: self];
  231189. if (! owner_->isSharedWindow)
  231190. {
  231191. [notificationCenter addObserver: self
  231192. selector: @selector (frameChanged:)
  231193. name: NSWindowDidMoveNotification
  231194. object: owner_->window];
  231195. }
  231196. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  231197. return self;
  231198. }
  231199. - (void) dealloc
  231200. {
  231201. [notificationCenter removeObserver: self];
  231202. delete stringBeingComposed;
  231203. [super dealloc];
  231204. }
  231205. - (void) drawRect: (NSRect) r
  231206. {
  231207. if (owner != 0)
  231208. owner->drawRect (r);
  231209. }
  231210. - (BOOL) isOpaque
  231211. {
  231212. return owner == 0 || owner->isOpaque();
  231213. }
  231214. - (void) mouseDown: (NSEvent*) ev
  231215. {
  231216. if (JUCEApplication::isStandaloneApp())
  231217. [self asyncMouseDown: ev];
  231218. else
  231219. // In some host situations, the host will stop modal loops from working
  231220. // correctly if they're called from a mouse event, so we'll trigger
  231221. // the event asynchronously..
  231222. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  231223. withObject: ev
  231224. waitUntilDone: NO];
  231225. }
  231226. - (void) asyncMouseDown: (NSEvent*) ev
  231227. {
  231228. if (owner != 0)
  231229. owner->redirectMouseDown (ev);
  231230. }
  231231. - (void) mouseUp: (NSEvent*) ev
  231232. {
  231233. if (! JUCEApplication::isStandaloneApp())
  231234. [self asyncMouseUp: ev];
  231235. else
  231236. // In some host situations, the host will stop modal loops from working
  231237. // correctly if they're called from a mouse event, so we'll trigger
  231238. // the event asynchronously..
  231239. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  231240. withObject: ev
  231241. waitUntilDone: NO];
  231242. }
  231243. - (void) asyncMouseUp: (NSEvent*) ev
  231244. {
  231245. if (owner != 0)
  231246. owner->redirectMouseUp (ev);
  231247. }
  231248. - (void) mouseDragged: (NSEvent*) ev
  231249. {
  231250. if (owner != 0)
  231251. owner->redirectMouseDrag (ev);
  231252. }
  231253. - (void) mouseMoved: (NSEvent*) ev
  231254. {
  231255. if (owner != 0)
  231256. owner->redirectMouseMove (ev);
  231257. }
  231258. - (void) mouseEntered: (NSEvent*) ev
  231259. {
  231260. if (owner != 0)
  231261. owner->redirectMouseEnter (ev);
  231262. }
  231263. - (void) mouseExited: (NSEvent*) ev
  231264. {
  231265. if (owner != 0)
  231266. owner->redirectMouseExit (ev);
  231267. }
  231268. - (void) rightMouseDown: (NSEvent*) ev
  231269. {
  231270. [self mouseDown: ev];
  231271. }
  231272. - (void) rightMouseDragged: (NSEvent*) ev
  231273. {
  231274. [self mouseDragged: ev];
  231275. }
  231276. - (void) rightMouseUp: (NSEvent*) ev
  231277. {
  231278. [self mouseUp: ev];
  231279. }
  231280. - (void) otherMouseDown: (NSEvent*) ev
  231281. {
  231282. [self mouseDown: ev];
  231283. }
  231284. - (void) otherMouseDragged: (NSEvent*) ev
  231285. {
  231286. [self mouseDragged: ev];
  231287. }
  231288. - (void) otherMouseUp: (NSEvent*) ev
  231289. {
  231290. [self mouseUp: ev];
  231291. }
  231292. - (void) scrollWheel: (NSEvent*) ev
  231293. {
  231294. if (owner != 0)
  231295. owner->redirectMouseWheel (ev);
  231296. }
  231297. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  231298. {
  231299. (void) ev;
  231300. return YES;
  231301. }
  231302. - (void) frameChanged: (NSNotification*) n
  231303. {
  231304. (void) n;
  231305. if (owner != 0)
  231306. owner->redirectMovedOrResized();
  231307. }
  231308. - (void) viewDidMoveToWindow
  231309. {
  231310. if (owner != 0)
  231311. owner->viewMovedToWindow();
  231312. }
  231313. - (void) asyncRepaint: (id) rect
  231314. {
  231315. NSRect* r = (NSRect*) [((NSData*) rect) bytes];
  231316. [self setNeedsDisplayInRect: *r];
  231317. }
  231318. - (void) keyDown: (NSEvent*) ev
  231319. {
  231320. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231321. textWasInserted = false;
  231322. if (target != 0)
  231323. [self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  231324. else
  231325. deleteAndZero (stringBeingComposed);
  231326. if ((! textWasInserted) && (owner == 0 || ! owner->redirectKeyDown (ev)))
  231327. [super keyDown: ev];
  231328. }
  231329. - (void) keyUp: (NSEvent*) ev
  231330. {
  231331. if (owner == 0 || ! owner->redirectKeyUp (ev))
  231332. [super keyUp: ev];
  231333. }
  231334. - (void) insertText: (id) aString
  231335. {
  231336. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  231337. NSString* newText = [aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString;
  231338. if ([newText length] > 0)
  231339. {
  231340. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231341. if (target != 0)
  231342. {
  231343. target->insertTextAtCaret (nsStringToJuce (newText));
  231344. textWasInserted = true;
  231345. }
  231346. }
  231347. deleteAndZero (stringBeingComposed);
  231348. }
  231349. - (void) doCommandBySelector: (SEL) aSelector
  231350. {
  231351. (void) aSelector;
  231352. }
  231353. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selectionRange
  231354. {
  231355. (void) selectionRange;
  231356. if (stringBeingComposed == 0)
  231357. stringBeingComposed = new String();
  231358. *stringBeingComposed = nsStringToJuce ([aString isKindOfClass:[NSAttributedString class]] ? [aString string] : aString);
  231359. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231360. if (target != 0)
  231361. {
  231362. const Range<int> currentHighlight (target->getHighlightedRegion());
  231363. target->insertTextAtCaret (*stringBeingComposed);
  231364. target->setHighlightedRegion (currentHighlight.withLength (stringBeingComposed->length()));
  231365. textWasInserted = true;
  231366. }
  231367. }
  231368. - (void) unmarkText
  231369. {
  231370. if (stringBeingComposed != 0)
  231371. {
  231372. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231373. if (target != 0)
  231374. {
  231375. target->insertTextAtCaret (*stringBeingComposed);
  231376. textWasInserted = true;
  231377. }
  231378. }
  231379. deleteAndZero (stringBeingComposed);
  231380. }
  231381. - (BOOL) hasMarkedText
  231382. {
  231383. return stringBeingComposed != 0;
  231384. }
  231385. - (long) conversationIdentifier
  231386. {
  231387. return (long) (pointer_sized_int) self;
  231388. }
  231389. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange
  231390. {
  231391. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231392. if (target != 0)
  231393. {
  231394. const Range<int> r ((int) theRange.location,
  231395. (int) (theRange.location + theRange.length));
  231396. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  231397. }
  231398. return nil;
  231399. }
  231400. - (NSRange) markedRange
  231401. {
  231402. return stringBeingComposed != 0 ? NSMakeRange (0, stringBeingComposed->length())
  231403. : NSMakeRange (NSNotFound, 0);
  231404. }
  231405. - (NSRange) selectedRange
  231406. {
  231407. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231408. if (target != 0)
  231409. {
  231410. const Range<int> highlight (target->getHighlightedRegion());
  231411. if (! highlight.isEmpty())
  231412. return NSMakeRange (highlight.getStart(), highlight.getLength());
  231413. }
  231414. return NSMakeRange (NSNotFound, 0);
  231415. }
  231416. - (NSRect) firstRectForCharacterRange: (NSRange) theRange
  231417. {
  231418. (void) theRange;
  231419. JUCE_NAMESPACE::Component* const comp = dynamic_cast <JUCE_NAMESPACE::Component*> (owner->findCurrentTextInputTarget());
  231420. if (comp == 0)
  231421. return NSMakeRect (0, 0, 0, 0);
  231422. const Rectangle<int> bounds (comp->getScreenBounds());
  231423. return NSMakeRect (bounds.getX(),
  231424. [[[NSScreen screens] objectAtIndex: 0] frame].size.height - bounds.getY(),
  231425. bounds.getWidth(),
  231426. bounds.getHeight());
  231427. }
  231428. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint
  231429. {
  231430. (void) thePoint;
  231431. return NSNotFound;
  231432. }
  231433. - (NSArray*) validAttributesForMarkedText
  231434. {
  231435. return [NSArray array];
  231436. }
  231437. - (void) flagsChanged: (NSEvent*) ev
  231438. {
  231439. if (owner != 0)
  231440. owner->redirectModKeyChange (ev);
  231441. }
  231442. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231443. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  231444. {
  231445. if (owner != 0 && owner->redirectPerformKeyEquivalent (ev))
  231446. return true;
  231447. return [super performKeyEquivalent: ev];
  231448. }
  231449. #endif
  231450. - (BOOL) becomeFirstResponder
  231451. {
  231452. if (owner != 0)
  231453. owner->viewFocusGain();
  231454. return true;
  231455. }
  231456. - (BOOL) resignFirstResponder
  231457. {
  231458. if (owner != 0)
  231459. owner->viewFocusLoss();
  231460. return true;
  231461. }
  231462. - (BOOL) acceptsFirstResponder
  231463. {
  231464. return owner != 0 && owner->canBecomeKeyWindow();
  231465. }
  231466. - (NSArray*) getSupportedDragTypes
  231467. {
  231468. return [NSArray arrayWithObjects: NSFilenamesPboardType, /*NSFilesPromisePboardType, NSStringPboardType,*/ nil];
  231469. }
  231470. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  231471. {
  231472. return owner != 0 && owner->sendDragCallback (type, sender);
  231473. }
  231474. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  231475. {
  231476. if ([self sendDragCallback: 0 sender: sender])
  231477. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  231478. else
  231479. return NSDragOperationNone;
  231480. }
  231481. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  231482. {
  231483. if ([self sendDragCallback: 0 sender: sender])
  231484. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  231485. else
  231486. return NSDragOperationNone;
  231487. }
  231488. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  231489. {
  231490. [self sendDragCallback: 1 sender: sender];
  231491. }
  231492. - (void) draggingExited: (id <NSDraggingInfo>) sender
  231493. {
  231494. [self sendDragCallback: 1 sender: sender];
  231495. }
  231496. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  231497. {
  231498. (void) sender;
  231499. return YES;
  231500. }
  231501. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  231502. {
  231503. return [self sendDragCallback: 2 sender: sender];
  231504. }
  231505. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  231506. {
  231507. (void) sender;
  231508. }
  231509. @end
  231510. @implementation JuceNSWindow
  231511. - (void) setOwner: (NSViewComponentPeer*) owner_
  231512. {
  231513. owner = owner_;
  231514. isZooming = false;
  231515. }
  231516. - (BOOL) canBecomeKeyWindow
  231517. {
  231518. return owner != 0 && owner->canBecomeKeyWindow();
  231519. }
  231520. - (void) becomeKeyWindow
  231521. {
  231522. [super becomeKeyWindow];
  231523. if (owner != 0)
  231524. owner->grabFocus();
  231525. }
  231526. - (BOOL) windowShouldClose: (id) window
  231527. {
  231528. (void) window;
  231529. return owner == 0 || owner->windowShouldClose();
  231530. }
  231531. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  231532. {
  231533. (void) screen;
  231534. if (owner != 0)
  231535. frameRect = owner->constrainRect (frameRect);
  231536. return frameRect;
  231537. }
  231538. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  231539. {
  231540. (void) window;
  231541. if (isZooming)
  231542. return proposedFrameSize;
  231543. NSRect frameRect = [self frame];
  231544. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  231545. frameRect.size = proposedFrameSize;
  231546. if (owner != 0)
  231547. frameRect = owner->constrainRect (frameRect);
  231548. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  231549. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  231550. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  231551. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  231552. return frameRect.size;
  231553. }
  231554. - (void) zoom: (id) sender
  231555. {
  231556. isZooming = true;
  231557. [super zoom: sender];
  231558. isZooming = false;
  231559. }
  231560. - (void) windowWillMove: (NSNotification*) notification
  231561. {
  231562. (void) notification;
  231563. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  231564. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  231565. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  231566. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  231567. }
  231568. @end
  231569. BEGIN_JUCE_NAMESPACE
  231570. ModifierKeys NSViewComponentPeer::currentModifiers;
  231571. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = 0;
  231572. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  231573. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  231574. {
  231575. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  231576. return true;
  231577. if (keyCode >= 'A' && keyCode <= 'Z'
  231578. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  231579. return true;
  231580. if (keyCode >= 'a' && keyCode <= 'z'
  231581. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  231582. return true;
  231583. return false;
  231584. }
  231585. void NSViewComponentPeer::updateModifiers (NSEvent* e)
  231586. {
  231587. int m = 0;
  231588. if (([e modifierFlags] & NSShiftKeyMask) != 0) m |= ModifierKeys::shiftModifier;
  231589. if (([e modifierFlags] & NSControlKeyMask) != 0) m |= ModifierKeys::ctrlModifier;
  231590. if (([e modifierFlags] & NSAlternateKeyMask) != 0) m |= ModifierKeys::altModifier;
  231591. if (([e modifierFlags] & NSCommandKeyMask) != 0) m |= ModifierKeys::commandModifier;
  231592. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (m);
  231593. }
  231594. void NSViewComponentPeer::updateKeysDown (NSEvent* ev, bool isKeyDown)
  231595. {
  231596. updateModifiers (ev);
  231597. int keyCode = getKeyCodeFromEvent (ev);
  231598. if (keyCode != 0)
  231599. {
  231600. if (isKeyDown)
  231601. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  231602. else
  231603. keysCurrentlyDown.removeValue (keyCode);
  231604. }
  231605. }
  231606. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  231607. {
  231608. return NSViewComponentPeer::currentModifiers;
  231609. }
  231610. void ModifierKeys::updateCurrentModifiers() throw()
  231611. {
  231612. currentModifiers = NSViewComponentPeer::currentModifiers;
  231613. }
  231614. NSViewComponentPeer::NSViewComponentPeer (Component* const component_,
  231615. const int windowStyleFlags,
  231616. NSView* viewToAttachTo)
  231617. : ComponentPeer (component_, windowStyleFlags),
  231618. window (0),
  231619. view (0),
  231620. isSharedWindow (viewToAttachTo != 0),
  231621. fullScreen (false),
  231622. insideDrawRect (false),
  231623. #if USE_COREGRAPHICS_RENDERING
  231624. usingCoreGraphics (true),
  231625. #else
  231626. usingCoreGraphics (false),
  231627. #endif
  231628. recursiveToFrontCall (false)
  231629. {
  231630. NSRect r = NSMakeRect (0, 0, (float) component->getWidth(),(float) component->getHeight());
  231631. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  231632. [view setPostsFrameChangedNotifications: YES];
  231633. if (isSharedWindow)
  231634. {
  231635. window = [viewToAttachTo window];
  231636. [viewToAttachTo addSubview: view];
  231637. setVisible (component->isVisible());
  231638. }
  231639. else
  231640. {
  231641. r.origin.x = (float) component->getX();
  231642. r.origin.y = (float) component->getY();
  231643. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  231644. unsigned int style = 0;
  231645. if ((windowStyleFlags & windowHasTitleBar) == 0)
  231646. style = NSBorderlessWindowMask;
  231647. else
  231648. style = NSTitledWindowMask;
  231649. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  231650. style |= NSMiniaturizableWindowMask;
  231651. if ((windowStyleFlags & windowHasCloseButton) != 0)
  231652. style |= NSClosableWindowMask;
  231653. if ((windowStyleFlags & windowIsResizable) != 0)
  231654. style |= NSResizableWindowMask;
  231655. window = [[JuceNSWindow alloc] initWithContentRect: r
  231656. styleMask: style
  231657. backing: NSBackingStoreBuffered
  231658. defer: YES];
  231659. [((JuceNSWindow*) window) setOwner: this];
  231660. [window orderOut: nil];
  231661. [window setDelegate: (JuceNSWindow*) window];
  231662. [window setOpaque: component->isOpaque()];
  231663. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  231664. if (component->isAlwaysOnTop())
  231665. [window setLevel: NSFloatingWindowLevel];
  231666. [window setContentView: view];
  231667. [window setAutodisplay: YES];
  231668. [window setAcceptsMouseMovedEvents: YES];
  231669. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  231670. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  231671. [window setReleasedWhenClosed: YES];
  231672. [window retain];
  231673. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  231674. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  231675. }
  231676. setTitle (component->getName());
  231677. }
  231678. NSViewComponentPeer::~NSViewComponentPeer()
  231679. {
  231680. view->owner = 0;
  231681. [view removeFromSuperview];
  231682. [view release];
  231683. if (! isSharedWindow)
  231684. {
  231685. [((JuceNSWindow*) window) setOwner: 0];
  231686. [window close];
  231687. [window release];
  231688. }
  231689. }
  231690. void* NSViewComponentPeer::getNativeHandle() const
  231691. {
  231692. return view;
  231693. }
  231694. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  231695. {
  231696. if (isSharedWindow)
  231697. {
  231698. [view setHidden: ! shouldBeVisible];
  231699. }
  231700. else
  231701. {
  231702. if (shouldBeVisible)
  231703. {
  231704. [window orderFront: nil];
  231705. handleBroughtToFront();
  231706. }
  231707. else
  231708. {
  231709. [window orderOut: nil];
  231710. }
  231711. }
  231712. }
  231713. void NSViewComponentPeer::setTitle (const String& title)
  231714. {
  231715. const ScopedAutoReleasePool pool;
  231716. if (! isSharedWindow)
  231717. [window setTitle: juceStringToNS (title)];
  231718. }
  231719. void NSViewComponentPeer::setPosition (int x, int y)
  231720. {
  231721. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  231722. }
  231723. void NSViewComponentPeer::setSize (int w, int h)
  231724. {
  231725. setBounds (component->getX(), component->getY(), w, h, false);
  231726. }
  231727. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  231728. {
  231729. fullScreen = isNowFullScreen;
  231730. NSRect r = NSMakeRect ((float) x, (float) y, (float) jmax (0, w), (float) jmax (0, h));
  231731. if (isSharedWindow)
  231732. {
  231733. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  231734. if ([view frame].size.width != r.size.width
  231735. || [view frame].size.height != r.size.height)
  231736. [view setNeedsDisplay: true];
  231737. [view setFrame: r];
  231738. }
  231739. else
  231740. {
  231741. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  231742. [window setFrame: [window frameRectForContentRect: r]
  231743. display: true];
  231744. }
  231745. }
  231746. const Rectangle<int> NSViewComponentPeer::getBounds (const bool global) const
  231747. {
  231748. NSRect r = [view frame];
  231749. if (global && [view window] != 0)
  231750. {
  231751. r = [view convertRect: r toView: nil];
  231752. NSRect wr = [[view window] frame];
  231753. r.origin.x += wr.origin.x;
  231754. r.origin.y += wr.origin.y;
  231755. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  231756. }
  231757. else
  231758. {
  231759. r.origin.y = [[view superview] frame].size.height - r.origin.y - r.size.height;
  231760. }
  231761. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y, (int) r.size.width, (int) r.size.height);
  231762. }
  231763. const Rectangle<int> NSViewComponentPeer::getBounds() const
  231764. {
  231765. return getBounds (! isSharedWindow);
  231766. }
  231767. const Point<int> NSViewComponentPeer::getScreenPosition() const
  231768. {
  231769. return getBounds (true).getPosition();
  231770. }
  231771. const Point<int> NSViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  231772. {
  231773. return relativePosition + getScreenPosition();
  231774. }
  231775. const Point<int> NSViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  231776. {
  231777. return screenPosition - getScreenPosition();
  231778. }
  231779. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  231780. {
  231781. if (constrainer != 0)
  231782. {
  231783. NSRect current = [window frame];
  231784. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  231785. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  231786. Rectangle<int> pos ((int) r.origin.x, (int) r.origin.y,
  231787. (int) r.size.width, (int) r.size.height);
  231788. Rectangle<int> original ((int) current.origin.x, (int) current.origin.y,
  231789. (int) current.size.width, (int) current.size.height);
  231790. constrainer->checkBounds (pos, original,
  231791. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  231792. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  231793. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  231794. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  231795. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  231796. r.origin.x = pos.getX();
  231797. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - pos.getY();
  231798. r.size.width = pos.getWidth();
  231799. r.size.height = pos.getHeight();
  231800. }
  231801. return r;
  231802. }
  231803. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  231804. {
  231805. if (! isSharedWindow)
  231806. {
  231807. if (shouldBeMinimised)
  231808. [window miniaturize: nil];
  231809. else
  231810. [window deminiaturize: nil];
  231811. }
  231812. }
  231813. bool NSViewComponentPeer::isMinimised() const
  231814. {
  231815. return window != 0 && [window isMiniaturized];
  231816. }
  231817. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  231818. {
  231819. if (! isSharedWindow)
  231820. {
  231821. Rectangle<int> r (lastNonFullscreenBounds);
  231822. setMinimised (false);
  231823. if (fullScreen != shouldBeFullScreen)
  231824. {
  231825. if (shouldBeFullScreen && (getStyleFlags() & windowHasTitleBar) != 0)
  231826. {
  231827. fullScreen = true;
  231828. [window performZoom: nil];
  231829. }
  231830. else
  231831. {
  231832. if (shouldBeFullScreen)
  231833. r = Desktop::getInstance().getMainMonitorArea();
  231834. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  231835. if (r != getComponent()->getBounds() && ! r.isEmpty())
  231836. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  231837. }
  231838. }
  231839. }
  231840. }
  231841. bool NSViewComponentPeer::isFullScreen() const
  231842. {
  231843. return fullScreen;
  231844. }
  231845. bool NSViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  231846. {
  231847. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  231848. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  231849. return false;
  231850. NSPoint p;
  231851. p.x = (float) position.getX();
  231852. p.y = (float) position.getY();
  231853. NSView* v = [view hitTest: p];
  231854. if (trueIfInAChildWindow)
  231855. return v != nil;
  231856. return v == view;
  231857. }
  231858. const BorderSize NSViewComponentPeer::getFrameSize() const
  231859. {
  231860. BorderSize b;
  231861. if (! isSharedWindow)
  231862. {
  231863. NSRect v = [view convertRect: [view frame] toView: nil];
  231864. NSRect w = [window frame];
  231865. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  231866. b.setBottom ((int) v.origin.y);
  231867. b.setLeft ((int) v.origin.x);
  231868. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  231869. }
  231870. return b;
  231871. }
  231872. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  231873. {
  231874. if (! isSharedWindow)
  231875. {
  231876. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  231877. : NSNormalWindowLevel];
  231878. }
  231879. return true;
  231880. }
  231881. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  231882. {
  231883. if (isSharedWindow)
  231884. {
  231885. [[view superview] addSubview: view
  231886. positioned: NSWindowAbove
  231887. relativeTo: nil];
  231888. }
  231889. if (window != 0 && component->isVisible())
  231890. {
  231891. if (makeActiveWindow)
  231892. [window makeKeyAndOrderFront: nil];
  231893. else
  231894. [window orderFront: nil];
  231895. if (! recursiveToFrontCall)
  231896. {
  231897. recursiveToFrontCall = true;
  231898. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  231899. handleBroughtToFront();
  231900. recursiveToFrontCall = false;
  231901. }
  231902. }
  231903. }
  231904. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  231905. {
  231906. NSViewComponentPeer* const otherPeer = dynamic_cast <NSViewComponentPeer*> (other);
  231907. jassert (otherPeer != 0); // wrong type of window?
  231908. if (otherPeer != 0)
  231909. {
  231910. if (isSharedWindow)
  231911. {
  231912. [[view superview] addSubview: view
  231913. positioned: NSWindowBelow
  231914. relativeTo: otherPeer->view];
  231915. }
  231916. else
  231917. {
  231918. [window orderWindow: NSWindowBelow
  231919. relativeTo: otherPeer->window != 0 ? [otherPeer->window windowNumber]
  231920. : nil ];
  231921. }
  231922. }
  231923. }
  231924. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  231925. {
  231926. // to do..
  231927. }
  231928. void NSViewComponentPeer::viewFocusGain()
  231929. {
  231930. if (currentlyFocusedPeer != this)
  231931. {
  231932. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  231933. currentlyFocusedPeer->handleFocusLoss();
  231934. currentlyFocusedPeer = this;
  231935. handleFocusGain();
  231936. }
  231937. }
  231938. void NSViewComponentPeer::viewFocusLoss()
  231939. {
  231940. if (currentlyFocusedPeer == this)
  231941. {
  231942. currentlyFocusedPeer = 0;
  231943. handleFocusLoss();
  231944. }
  231945. }
  231946. void juce_HandleProcessFocusChange()
  231947. {
  231948. NSViewComponentPeer::keysCurrentlyDown.clear();
  231949. if (NSViewComponentPeer::isValidPeer (NSViewComponentPeer::currentlyFocusedPeer))
  231950. {
  231951. if (Process::isForegroundProcess())
  231952. {
  231953. NSViewComponentPeer::currentlyFocusedPeer->handleFocusGain();
  231954. ComponentPeer::bringModalComponentToFront();
  231955. }
  231956. else
  231957. {
  231958. NSViewComponentPeer::currentlyFocusedPeer->handleFocusLoss();
  231959. // turn kiosk mode off if we lose focus..
  231960. Desktop::getInstance().setKioskModeComponent (0);
  231961. }
  231962. }
  231963. }
  231964. bool NSViewComponentPeer::isFocused() const
  231965. {
  231966. return isSharedWindow ? this == currentlyFocusedPeer
  231967. : (window != 0 && [window isKeyWindow]);
  231968. }
  231969. void NSViewComponentPeer::grabFocus()
  231970. {
  231971. if (window != 0)
  231972. {
  231973. [window makeKeyWindow];
  231974. [window makeFirstResponder: view];
  231975. viewFocusGain();
  231976. }
  231977. }
  231978. void NSViewComponentPeer::textInputRequired (const Point<int>&)
  231979. {
  231980. }
  231981. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  231982. {
  231983. String unicode (nsStringToJuce ([ev characters]));
  231984. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  231985. int keyCode = getKeyCodeFromEvent (ev);
  231986. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  231987. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  231988. if (unicode.isNotEmpty() || keyCode != 0)
  231989. {
  231990. if (isKeyDown)
  231991. {
  231992. bool used = false;
  231993. while (unicode.length() > 0)
  231994. {
  231995. juce_wchar textCharacter = unicode[0];
  231996. unicode = unicode.substring (1);
  231997. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  231998. textCharacter = 0;
  231999. used = handleKeyUpOrDown (true) || used;
  232000. used = handleKeyPress (keyCode, textCharacter) || used;
  232001. }
  232002. return used;
  232003. }
  232004. else
  232005. {
  232006. if (handleKeyUpOrDown (false))
  232007. return true;
  232008. }
  232009. }
  232010. return false;
  232011. }
  232012. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  232013. {
  232014. updateKeysDown (ev, true);
  232015. bool used = handleKeyEvent (ev, true);
  232016. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  232017. {
  232018. // for command keys, the key-up event is thrown away, so simulate one..
  232019. updateKeysDown (ev, false);
  232020. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  232021. }
  232022. // (If we're running modally, don't allow unused keystrokes to be passed
  232023. // along to other blocked views..)
  232024. if (Component::getCurrentlyModalComponent() != 0)
  232025. used = true;
  232026. return used;
  232027. }
  232028. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  232029. {
  232030. updateKeysDown (ev, false);
  232031. return handleKeyEvent (ev, false)
  232032. || Component::getCurrentlyModalComponent() != 0;
  232033. }
  232034. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  232035. {
  232036. keysCurrentlyDown.clear();
  232037. handleKeyUpOrDown (true);
  232038. updateModifiers (ev);
  232039. handleModifierKeysChange();
  232040. }
  232041. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  232042. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  232043. {
  232044. if ([ev type] == NSKeyDown)
  232045. return redirectKeyDown (ev);
  232046. else if ([ev type] == NSKeyUp)
  232047. return redirectKeyUp (ev);
  232048. return false;
  232049. }
  232050. #endif
  232051. void NSViewComponentPeer::sendMouseEvent (NSEvent* ev)
  232052. {
  232053. updateModifiers (ev);
  232054. handleMouseEvent (0, getMousePos (ev, view), currentModifiers, getMouseTime (ev));
  232055. }
  232056. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  232057. {
  232058. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  232059. sendMouseEvent (ev);
  232060. }
  232061. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  232062. {
  232063. currentModifiers = currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  232064. sendMouseEvent (ev);
  232065. showArrowCursorIfNeeded();
  232066. }
  232067. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  232068. {
  232069. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  232070. sendMouseEvent (ev);
  232071. }
  232072. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  232073. {
  232074. currentModifiers = currentModifiers.withoutMouseButtons();
  232075. sendMouseEvent (ev);
  232076. showArrowCursorIfNeeded();
  232077. }
  232078. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  232079. {
  232080. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  232081. currentModifiers = currentModifiers.withoutMouseButtons();
  232082. sendMouseEvent (ev);
  232083. }
  232084. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  232085. {
  232086. currentModifiers = currentModifiers.withoutMouseButtons();
  232087. sendMouseEvent (ev);
  232088. }
  232089. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  232090. {
  232091. updateModifiers (ev);
  232092. float x = 0, y = 0;
  232093. @try
  232094. {
  232095. x = [ev deviceDeltaX] * 0.5f;
  232096. y = [ev deviceDeltaY] * 0.5f;
  232097. }
  232098. @catch (...)
  232099. {}
  232100. if (x == 0 && y == 0)
  232101. {
  232102. x = [ev deltaX] * 10.0f;
  232103. y = [ev deltaY] * 10.0f;
  232104. }
  232105. handleMouseWheel (0, getMousePos (ev, view), getMouseTime (ev), x, y);
  232106. }
  232107. void NSViewComponentPeer::showArrowCursorIfNeeded()
  232108. {
  232109. MouseInputSource& mouse = Desktop::getInstance().getMainMouseSource();
  232110. if (mouse.getComponentUnderMouse() == 0
  232111. && Desktop::getInstance().findComponentAt (mouse.getScreenPosition()) == 0)
  232112. {
  232113. [[NSCursor arrowCursor] set];
  232114. }
  232115. }
  232116. BOOL NSViewComponentPeer::sendDragCallback (int type, id <NSDraggingInfo> sender)
  232117. {
  232118. NSString* bestType
  232119. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  232120. if (bestType == nil)
  232121. return false;
  232122. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  232123. const Point<int> pos ((int) p.x, (int) ([view frame].size.height - p.y));
  232124. StringArray files;
  232125. id list = [[sender draggingPasteboard] propertyListForType: bestType];
  232126. if (list == nil)
  232127. return false;
  232128. if ([list isKindOfClass: [NSArray class]])
  232129. {
  232130. NSArray* items = (NSArray*) list;
  232131. for (unsigned int i = 0; i < [items count]; ++i)
  232132. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  232133. }
  232134. if (files.size() == 0)
  232135. return false;
  232136. if (type == 0)
  232137. handleFileDragMove (files, pos);
  232138. else if (type == 1)
  232139. handleFileDragExit (files);
  232140. else if (type == 2)
  232141. handleFileDragDrop (files, pos);
  232142. return true;
  232143. }
  232144. bool NSViewComponentPeer::isOpaque()
  232145. {
  232146. return component == 0 || component->isOpaque();
  232147. }
  232148. void NSViewComponentPeer::drawRect (NSRect r)
  232149. {
  232150. if (r.size.width < 1.0f || r.size.height < 1.0f)
  232151. return;
  232152. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  232153. if (! component->isOpaque())
  232154. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  232155. #if USE_COREGRAPHICS_RENDERING
  232156. if (usingCoreGraphics)
  232157. {
  232158. CoreGraphicsContext context (cg, (float) [view frame].size.height);
  232159. insideDrawRect = true;
  232160. handlePaint (context);
  232161. insideDrawRect = false;
  232162. }
  232163. else
  232164. #endif
  232165. {
  232166. Image temp (getComponent()->isOpaque() ? Image::RGB : Image::ARGB,
  232167. (int) (r.size.width + 0.5f),
  232168. (int) (r.size.height + 0.5f),
  232169. ! getComponent()->isOpaque());
  232170. const int xOffset = -roundToInt (r.origin.x);
  232171. const int yOffset = -roundToInt ([view frame].size.height - (r.origin.y + r.size.height));
  232172. const NSRect* rects = 0;
  232173. NSInteger numRects = 0;
  232174. [view getRectsBeingDrawn: &rects count: &numRects];
  232175. const Rectangle<int> clipBounds (temp.getBounds());
  232176. RectangleList clip;
  232177. for (int i = 0; i < numRects; ++i)
  232178. {
  232179. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + xOffset,
  232180. roundToInt ([view frame].size.height - (rects[i].origin.y + rects[i].size.height)) + yOffset,
  232181. roundToInt (rects[i].size.width),
  232182. roundToInt (rects[i].size.height))));
  232183. }
  232184. if (! clip.isEmpty())
  232185. {
  232186. LowLevelGraphicsSoftwareRenderer context (temp, xOffset, yOffset, clip);
  232187. insideDrawRect = true;
  232188. handlePaint (context);
  232189. insideDrawRect = false;
  232190. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  232191. CGImageRef image = CoreGraphicsImage::createImage (temp, false, colourSpace);
  232192. CGColorSpaceRelease (colourSpace);
  232193. CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, temp.getWidth(), temp.getHeight()), image);
  232194. CGImageRelease (image);
  232195. }
  232196. }
  232197. }
  232198. const StringArray NSViewComponentPeer::getAvailableRenderingEngines()
  232199. {
  232200. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  232201. #if USE_COREGRAPHICS_RENDERING
  232202. s.add ("CoreGraphics Renderer");
  232203. #endif
  232204. return s;
  232205. }
  232206. int NSViewComponentPeer::getCurrentRenderingEngine() throw()
  232207. {
  232208. return usingCoreGraphics ? 1 : 0;
  232209. }
  232210. void NSViewComponentPeer::setCurrentRenderingEngine (int index)
  232211. {
  232212. #if USE_COREGRAPHICS_RENDERING
  232213. if (usingCoreGraphics != (index > 0))
  232214. {
  232215. usingCoreGraphics = index > 0;
  232216. [view setNeedsDisplay: true];
  232217. }
  232218. #endif
  232219. }
  232220. bool NSViewComponentPeer::canBecomeKeyWindow()
  232221. {
  232222. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  232223. }
  232224. bool NSViewComponentPeer::windowShouldClose()
  232225. {
  232226. if (! isValidPeer (this))
  232227. return YES;
  232228. handleUserClosingWindow();
  232229. return NO;
  232230. }
  232231. void NSViewComponentPeer::redirectMovedOrResized()
  232232. {
  232233. handleMovedOrResized();
  232234. }
  232235. void NSViewComponentPeer::viewMovedToWindow()
  232236. {
  232237. if (isSharedWindow)
  232238. window = [view window];
  232239. }
  232240. void Desktop::createMouseInputSources()
  232241. {
  232242. mouseSources.add (new MouseInputSource (0, true));
  232243. }
  232244. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  232245. {
  232246. // Very annoyingly, this function has to use the old SetSystemUIMode function,
  232247. // which is in Carbon.framework. But, because there's no Cocoa equivalent, it
  232248. // is apparently still available in 64-bit apps..
  232249. if (enableOrDisable)
  232250. {
  232251. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  232252. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  232253. }
  232254. else
  232255. {
  232256. SetSystemUIMode (kUIModeNormal, 0);
  232257. }
  232258. }
  232259. class AsyncRepaintMessage : public CallbackMessage
  232260. {
  232261. public:
  232262. NSViewComponentPeer* const peer;
  232263. const Rectangle<int> rect;
  232264. AsyncRepaintMessage (NSViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  232265. : peer (peer_), rect (rect_)
  232266. {
  232267. }
  232268. void messageCallback()
  232269. {
  232270. if (ComponentPeer::isValidPeer (peer))
  232271. peer->repaint (rect);
  232272. }
  232273. };
  232274. void NSViewComponentPeer::repaint (const Rectangle<int>& area)
  232275. {
  232276. if (insideDrawRect)
  232277. {
  232278. (new AsyncRepaintMessage (this, area))->post();
  232279. }
  232280. else
  232281. {
  232282. [view setNeedsDisplayInRect: NSMakeRect ((float) area.getX(), [view frame].size.height - (float) area.getBottom(),
  232283. (float) area.getWidth(), (float) area.getHeight())];
  232284. }
  232285. }
  232286. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  232287. {
  232288. [view displayIfNeeded];
  232289. }
  232290. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  232291. {
  232292. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  232293. }
  232294. const Image juce_createIconForFile (const File& file)
  232295. {
  232296. const ScopedAutoReleasePool pool;
  232297. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  232298. CoreGraphicsImage* result = new CoreGraphicsImage (Image::ARGB, (int) [image size].width, (int) [image size].height, true);
  232299. [NSGraphicsContext saveGraphicsState];
  232300. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithGraphicsPort: result->context flipped: false]];
  232301. [image drawAtPoint: NSMakePoint (0, 0)
  232302. fromRect: NSMakeRect (0, 0, [image size].width, [image size].height)
  232303. operation: NSCompositeSourceOver fraction: 1.0f];
  232304. [[NSGraphicsContext currentContext] flushGraphics];
  232305. [NSGraphicsContext restoreGraphicsState];
  232306. return Image (result);
  232307. }
  232308. const int KeyPress::spaceKey = ' ';
  232309. const int KeyPress::returnKey = 0x0d;
  232310. const int KeyPress::escapeKey = 0x1b;
  232311. const int KeyPress::backspaceKey = 0x7f;
  232312. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  232313. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  232314. const int KeyPress::upKey = NSUpArrowFunctionKey;
  232315. const int KeyPress::downKey = NSDownArrowFunctionKey;
  232316. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  232317. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  232318. const int KeyPress::endKey = NSEndFunctionKey;
  232319. const int KeyPress::homeKey = NSHomeFunctionKey;
  232320. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  232321. const int KeyPress::insertKey = -1;
  232322. const int KeyPress::tabKey = 9;
  232323. const int KeyPress::F1Key = NSF1FunctionKey;
  232324. const int KeyPress::F2Key = NSF2FunctionKey;
  232325. const int KeyPress::F3Key = NSF3FunctionKey;
  232326. const int KeyPress::F4Key = NSF4FunctionKey;
  232327. const int KeyPress::F5Key = NSF5FunctionKey;
  232328. const int KeyPress::F6Key = NSF6FunctionKey;
  232329. const int KeyPress::F7Key = NSF7FunctionKey;
  232330. const int KeyPress::F8Key = NSF8FunctionKey;
  232331. const int KeyPress::F9Key = NSF9FunctionKey;
  232332. const int KeyPress::F10Key = NSF10FunctionKey;
  232333. const int KeyPress::F11Key = NSF1FunctionKey;
  232334. const int KeyPress::F12Key = NSF12FunctionKey;
  232335. const int KeyPress::F13Key = NSF13FunctionKey;
  232336. const int KeyPress::F14Key = NSF14FunctionKey;
  232337. const int KeyPress::F15Key = NSF15FunctionKey;
  232338. const int KeyPress::F16Key = NSF16FunctionKey;
  232339. const int KeyPress::numberPad0 = 0x30020;
  232340. const int KeyPress::numberPad1 = 0x30021;
  232341. const int KeyPress::numberPad2 = 0x30022;
  232342. const int KeyPress::numberPad3 = 0x30023;
  232343. const int KeyPress::numberPad4 = 0x30024;
  232344. const int KeyPress::numberPad5 = 0x30025;
  232345. const int KeyPress::numberPad6 = 0x30026;
  232346. const int KeyPress::numberPad7 = 0x30027;
  232347. const int KeyPress::numberPad8 = 0x30028;
  232348. const int KeyPress::numberPad9 = 0x30029;
  232349. const int KeyPress::numberPadAdd = 0x3002a;
  232350. const int KeyPress::numberPadSubtract = 0x3002b;
  232351. const int KeyPress::numberPadMultiply = 0x3002c;
  232352. const int KeyPress::numberPadDivide = 0x3002d;
  232353. const int KeyPress::numberPadSeparator = 0x3002e;
  232354. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  232355. const int KeyPress::numberPadEquals = 0x30030;
  232356. const int KeyPress::numberPadDelete = 0x30031;
  232357. const int KeyPress::playKey = 0x30000;
  232358. const int KeyPress::stopKey = 0x30001;
  232359. const int KeyPress::fastForwardKey = 0x30002;
  232360. const int KeyPress::rewindKey = 0x30003;
  232361. #endif
  232362. /*** End of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  232363. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  232364. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232365. // compiled on its own).
  232366. #if JUCE_INCLUDED_FILE
  232367. #if JUCE_MAC
  232368. namespace MouseCursorHelpers
  232369. {
  232370. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  232371. {
  232372. NSImage* im = CoreGraphicsImage::createNSImage (image);
  232373. NSCursor* c = [[NSCursor alloc] initWithImage: im
  232374. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  232375. [im release];
  232376. return c;
  232377. }
  232378. static void* fromWebKitFile (const char* filename, float hx, float hy)
  232379. {
  232380. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  232381. BufferedInputStream buf (&fileStream, 4096, false);
  232382. PNGImageFormat pngFormat;
  232383. Image im (pngFormat.decodeImage (buf));
  232384. if (im.isValid())
  232385. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  232386. jassertfalse;
  232387. return 0;
  232388. }
  232389. }
  232390. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  232391. {
  232392. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  232393. }
  232394. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  232395. {
  232396. const ScopedAutoReleasePool pool;
  232397. NSCursor* c = 0;
  232398. switch (type)
  232399. {
  232400. case NormalCursor: c = [NSCursor arrowCursor]; break;
  232401. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  232402. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  232403. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  232404. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  232405. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  232406. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  232407. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  232408. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  232409. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  232410. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  232411. case UpDownResizeCursor:
  232412. case TopEdgeResizeCursor:
  232413. case BottomEdgeResizeCursor:
  232414. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  232415. case TopLeftCornerResizeCursor:
  232416. case BottomRightCornerResizeCursor:
  232417. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  232418. case TopRightCornerResizeCursor:
  232419. case BottomLeftCornerResizeCursor:
  232420. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  232421. case UpDownLeftRightResizeCursor:
  232422. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  232423. default:
  232424. jassertfalse;
  232425. break;
  232426. }
  232427. [c retain];
  232428. return c;
  232429. }
  232430. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  232431. {
  232432. [((NSCursor*) cursorHandle) release];
  232433. }
  232434. void MouseCursor::showInAllWindows() const
  232435. {
  232436. showInWindow (0);
  232437. }
  232438. void MouseCursor::showInWindow (ComponentPeer*) const
  232439. {
  232440. [((NSCursor*) getHandle()) set];
  232441. }
  232442. #else
  232443. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  232444. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  232445. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  232446. void MouseCursor::showInAllWindows() const {}
  232447. void MouseCursor::showInWindow (ComponentPeer*) const {}
  232448. #endif
  232449. #endif
  232450. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  232451. /*** Start of inlined file: juce_mac_NSViewComponent.mm ***/
  232452. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232453. // compiled on its own).
  232454. #if JUCE_INCLUDED_FILE
  232455. class NSViewComponentInternal : public ComponentMovementWatcher
  232456. {
  232457. Component* const owner;
  232458. NSViewComponentPeer* currentPeer;
  232459. bool wasShowing;
  232460. public:
  232461. NSView* const view;
  232462. NSViewComponentInternal (NSView* const view_, Component* const owner_)
  232463. : ComponentMovementWatcher (owner_),
  232464. owner (owner_),
  232465. currentPeer (0),
  232466. wasShowing (false),
  232467. view (view_)
  232468. {
  232469. [view_ retain];
  232470. if (owner_->isShowing())
  232471. componentPeerChanged();
  232472. }
  232473. ~NSViewComponentInternal()
  232474. {
  232475. [view removeFromSuperview];
  232476. [view release];
  232477. }
  232478. void componentMovedOrResized (Component& comp, bool wasMoved, bool wasResized)
  232479. {
  232480. ComponentMovementWatcher::componentMovedOrResized (comp, wasMoved, wasResized);
  232481. // The ComponentMovementWatcher version of this method avoids calling
  232482. // us when the top-level comp is resized, but for an NSView we need to know this
  232483. // because with inverted co-ords, we need to update the position even if the
  232484. // top-left pos hasn't changed
  232485. if (comp.isOnDesktop() && wasResized)
  232486. componentMovedOrResized (wasMoved, wasResized);
  232487. }
  232488. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  232489. {
  232490. Component* const topComp = owner->getTopLevelComponent();
  232491. if (topComp->getPeer() != 0)
  232492. {
  232493. const Point<int> pos (owner->relativePositionToOtherComponent (topComp, Point<int>()));
  232494. NSRect r = NSMakeRect ((float) pos.getX(), (float) pos.getY(), (float) owner->getWidth(), (float) owner->getHeight());
  232495. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  232496. [view setFrame: r];
  232497. }
  232498. }
  232499. void componentPeerChanged()
  232500. {
  232501. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner->getPeer());
  232502. if (currentPeer != peer)
  232503. {
  232504. [view removeFromSuperview];
  232505. currentPeer = peer;
  232506. if (peer != 0)
  232507. {
  232508. [peer->view addSubview: view];
  232509. componentMovedOrResized (false, false);
  232510. }
  232511. }
  232512. [view setHidden: ! owner->isShowing()];
  232513. }
  232514. void componentVisibilityChanged (Component&)
  232515. {
  232516. componentPeerChanged();
  232517. }
  232518. juce_UseDebuggingNewOperator
  232519. private:
  232520. NSViewComponentInternal (const NSViewComponentInternal&);
  232521. NSViewComponentInternal& operator= (const NSViewComponentInternal&);
  232522. };
  232523. NSViewComponent::NSViewComponent()
  232524. {
  232525. }
  232526. NSViewComponent::~NSViewComponent()
  232527. {
  232528. }
  232529. void NSViewComponent::setView (void* view)
  232530. {
  232531. if (view != getView())
  232532. {
  232533. if (view != 0)
  232534. info = new NSViewComponentInternal ((NSView*) view, this);
  232535. else
  232536. info = 0;
  232537. }
  232538. }
  232539. void* NSViewComponent::getView() const
  232540. {
  232541. return info == 0 ? 0 : info->view;
  232542. }
  232543. void NSViewComponent::paint (Graphics&)
  232544. {
  232545. }
  232546. #endif
  232547. /*** End of inlined file: juce_mac_NSViewComponent.mm ***/
  232548. /*** Start of inlined file: juce_mac_AppleRemote.mm ***/
  232549. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232550. // compiled on its own).
  232551. #if JUCE_INCLUDED_FILE
  232552. AppleRemoteDevice::AppleRemoteDevice()
  232553. : device (0),
  232554. queue (0),
  232555. remoteId (0)
  232556. {
  232557. }
  232558. AppleRemoteDevice::~AppleRemoteDevice()
  232559. {
  232560. stop();
  232561. }
  232562. static io_object_t getAppleRemoteDevice()
  232563. {
  232564. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  232565. io_iterator_t iter = 0;
  232566. io_object_t iod = 0;
  232567. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  232568. && iter != 0)
  232569. {
  232570. iod = IOIteratorNext (iter);
  232571. }
  232572. IOObjectRelease (iter);
  232573. return iod;
  232574. }
  232575. static bool createAppleRemoteInterface (io_object_t iod, void** device)
  232576. {
  232577. jassert (*device == 0);
  232578. io_name_t classname;
  232579. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  232580. {
  232581. IOCFPlugInInterface** cfPlugInInterface = 0;
  232582. SInt32 score = 0;
  232583. if (IOCreatePlugInInterfaceForService (iod,
  232584. kIOHIDDeviceUserClientTypeID,
  232585. kIOCFPlugInInterfaceID,
  232586. &cfPlugInInterface,
  232587. &score) == kIOReturnSuccess)
  232588. {
  232589. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  232590. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  232591. device);
  232592. (void) hr;
  232593. (*cfPlugInInterface)->Release (cfPlugInInterface);
  232594. }
  232595. }
  232596. return *device != 0;
  232597. }
  232598. bool AppleRemoteDevice::start (const bool inExclusiveMode)
  232599. {
  232600. if (queue != 0)
  232601. return true;
  232602. stop();
  232603. bool result = false;
  232604. io_object_t iod = getAppleRemoteDevice();
  232605. if (iod != 0)
  232606. {
  232607. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  232608. result = true;
  232609. else
  232610. stop();
  232611. IOObjectRelease (iod);
  232612. }
  232613. return result;
  232614. }
  232615. void AppleRemoteDevice::stop()
  232616. {
  232617. if (queue != 0)
  232618. {
  232619. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  232620. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  232621. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  232622. queue = 0;
  232623. }
  232624. if (device != 0)
  232625. {
  232626. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  232627. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  232628. device = 0;
  232629. }
  232630. }
  232631. bool AppleRemoteDevice::isActive() const
  232632. {
  232633. return queue != 0;
  232634. }
  232635. static void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  232636. {
  232637. if (result == kIOReturnSuccess)
  232638. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  232639. }
  232640. bool AppleRemoteDevice::open (const bool openInExclusiveMode)
  232641. {
  232642. Array <int> cookies;
  232643. CFArrayRef elements;
  232644. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  232645. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  232646. return false;
  232647. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  232648. {
  232649. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  232650. // get the cookie
  232651. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  232652. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  232653. continue;
  232654. long number;
  232655. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  232656. continue;
  232657. cookies.add ((int) number);
  232658. }
  232659. CFRelease (elements);
  232660. if ((*(IOHIDDeviceInterface**) device)
  232661. ->open ((IOHIDDeviceInterface**) device,
  232662. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  232663. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  232664. {
  232665. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  232666. if (queue != 0)
  232667. {
  232668. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  232669. for (int i = 0; i < cookies.size(); ++i)
  232670. {
  232671. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  232672. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  232673. }
  232674. CFRunLoopSourceRef eventSource;
  232675. if ((*(IOHIDQueueInterface**) queue)
  232676. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  232677. {
  232678. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  232679. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  232680. {
  232681. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  232682. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  232683. return true;
  232684. }
  232685. }
  232686. }
  232687. }
  232688. return false;
  232689. }
  232690. void AppleRemoteDevice::handleCallbackInternal()
  232691. {
  232692. int totalValues = 0;
  232693. AbsoluteTime nullTime = { 0, 0 };
  232694. char cookies [12];
  232695. int numCookies = 0;
  232696. while (numCookies < numElementsInArray (cookies))
  232697. {
  232698. IOHIDEventStruct e;
  232699. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  232700. break;
  232701. if ((int) e.elementCookie == 19)
  232702. {
  232703. remoteId = e.value;
  232704. buttonPressed (switched, false);
  232705. }
  232706. else
  232707. {
  232708. totalValues += e.value;
  232709. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  232710. }
  232711. }
  232712. cookies [numCookies++] = 0;
  232713. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  232714. static const char buttonPatterns[] =
  232715. {
  232716. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  232717. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  232718. 0x1f, 0x1d, 0x1c, 0x12, 0,
  232719. 0x1f, 0x1e, 0x1c, 0x12, 0,
  232720. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  232721. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  232722. 0x1f, 0x12, 0x04, 0x02, 0,
  232723. 0x1f, 0x12, 0x03, 0x02, 0,
  232724. 0x1f, 0x12, 0x1f, 0x12, 0,
  232725. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  232726. 19, 0
  232727. };
  232728. int buttonNum = (int) menuButton;
  232729. int i = 0;
  232730. while (i < numElementsInArray (buttonPatterns))
  232731. {
  232732. if (strcmp (cookies, buttonPatterns + i) == 0)
  232733. {
  232734. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  232735. break;
  232736. }
  232737. i += (int) strlen (buttonPatterns + i) + 1;
  232738. ++buttonNum;
  232739. }
  232740. }
  232741. #endif
  232742. /*** End of inlined file: juce_mac_AppleRemote.mm ***/
  232743. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  232744. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232745. // compiled on its own).
  232746. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  232747. #if JUCE_MAC
  232748. END_JUCE_NAMESPACE
  232749. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  232750. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  232751. {
  232752. CriticalSection* contextLock;
  232753. bool needsUpdate;
  232754. }
  232755. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  232756. - (bool) makeActive;
  232757. - (void) makeInactive;
  232758. - (void) reshape;
  232759. @end
  232760. @implementation ThreadSafeNSOpenGLView
  232761. - (id) initWithFrame: (NSRect) frameRect
  232762. pixelFormat: (NSOpenGLPixelFormat*) format
  232763. {
  232764. contextLock = new CriticalSection();
  232765. self = [super initWithFrame: frameRect pixelFormat: format];
  232766. if (self != nil)
  232767. [[NSNotificationCenter defaultCenter] addObserver: self
  232768. selector: @selector (_surfaceNeedsUpdate:)
  232769. name: NSViewGlobalFrameDidChangeNotification
  232770. object: self];
  232771. return self;
  232772. }
  232773. - (void) dealloc
  232774. {
  232775. [[NSNotificationCenter defaultCenter] removeObserver: self];
  232776. delete contextLock;
  232777. [super dealloc];
  232778. }
  232779. - (bool) makeActive
  232780. {
  232781. const ScopedLock sl (*contextLock);
  232782. if ([self openGLContext] == 0)
  232783. return false;
  232784. [[self openGLContext] makeCurrentContext];
  232785. if (needsUpdate)
  232786. {
  232787. [super update];
  232788. needsUpdate = false;
  232789. }
  232790. return true;
  232791. }
  232792. - (void) makeInactive
  232793. {
  232794. const ScopedLock sl (*contextLock);
  232795. [NSOpenGLContext clearCurrentContext];
  232796. }
  232797. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  232798. {
  232799. const ScopedLock sl (*contextLock);
  232800. needsUpdate = true;
  232801. }
  232802. - (void) update
  232803. {
  232804. const ScopedLock sl (*contextLock);
  232805. needsUpdate = true;
  232806. }
  232807. - (void) reshape
  232808. {
  232809. const ScopedLock sl (*contextLock);
  232810. needsUpdate = true;
  232811. }
  232812. @end
  232813. BEGIN_JUCE_NAMESPACE
  232814. class WindowedGLContext : public OpenGLContext
  232815. {
  232816. public:
  232817. WindowedGLContext (Component* const component,
  232818. const OpenGLPixelFormat& pixelFormat_,
  232819. NSOpenGLContext* sharedContext)
  232820. : renderContext (0),
  232821. pixelFormat (pixelFormat_)
  232822. {
  232823. jassert (component != 0);
  232824. NSOpenGLPixelFormatAttribute attribs [64];
  232825. int n = 0;
  232826. attribs[n++] = NSOpenGLPFADoubleBuffer;
  232827. attribs[n++] = NSOpenGLPFAAccelerated;
  232828. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  232829. attribs[n++] = NSOpenGLPFAColorSize;
  232830. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  232831. pixelFormat.greenBits,
  232832. pixelFormat.blueBits);
  232833. attribs[n++] = NSOpenGLPFAAlphaSize;
  232834. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  232835. attribs[n++] = NSOpenGLPFADepthSize;
  232836. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  232837. attribs[n++] = NSOpenGLPFAStencilSize;
  232838. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  232839. attribs[n++] = NSOpenGLPFAAccumSize;
  232840. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  232841. pixelFormat.accumulationBufferGreenBits,
  232842. pixelFormat.accumulationBufferBlueBits,
  232843. pixelFormat.accumulationBufferAlphaBits);
  232844. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  232845. attribs[n++] = NSOpenGLPFASampleBuffers;
  232846. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  232847. attribs[n++] = NSOpenGLPFAClosestPolicy;
  232848. attribs[n++] = NSOpenGLPFANoRecovery;
  232849. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  232850. NSOpenGLPixelFormat* format
  232851. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  232852. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  232853. pixelFormat: format];
  232854. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  232855. shareContext: sharedContext] autorelease];
  232856. const GLint swapInterval = 1;
  232857. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  232858. [view setOpenGLContext: renderContext];
  232859. [format release];
  232860. viewHolder = new NSViewComponentInternal (view, component);
  232861. }
  232862. ~WindowedGLContext()
  232863. {
  232864. deleteContext();
  232865. viewHolder = 0;
  232866. }
  232867. void deleteContext()
  232868. {
  232869. makeInactive();
  232870. [renderContext clearDrawable];
  232871. [renderContext setView: nil];
  232872. [view setOpenGLContext: nil];
  232873. renderContext = nil;
  232874. }
  232875. bool makeActive() const throw()
  232876. {
  232877. jassert (renderContext != 0);
  232878. if ([renderContext view] != view)
  232879. [renderContext setView: view];
  232880. [view makeActive];
  232881. return isActive();
  232882. }
  232883. bool makeInactive() const throw()
  232884. {
  232885. [view makeInactive];
  232886. return true;
  232887. }
  232888. bool isActive() const throw()
  232889. {
  232890. return [NSOpenGLContext currentContext] == renderContext;
  232891. }
  232892. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  232893. void* getRawContext() const throw() { return renderContext; }
  232894. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  232895. {
  232896. }
  232897. void swapBuffers()
  232898. {
  232899. [renderContext flushBuffer];
  232900. }
  232901. bool setSwapInterval (const int numFramesPerSwap)
  232902. {
  232903. [renderContext setValues: (const GLint*) &numFramesPerSwap
  232904. forParameter: NSOpenGLCPSwapInterval];
  232905. return true;
  232906. }
  232907. int getSwapInterval() const
  232908. {
  232909. GLint numFrames = 0;
  232910. [renderContext getValues: &numFrames
  232911. forParameter: NSOpenGLCPSwapInterval];
  232912. return numFrames;
  232913. }
  232914. void repaint()
  232915. {
  232916. // we need to invalidate the juce view that holds this gl view, to make it
  232917. // cause a repaint callback
  232918. NSView* v = (NSView*) viewHolder->view;
  232919. NSRect r = [v frame];
  232920. // bit of a bodge here.. if we only invalidate the area of the gl component,
  232921. // it's completely covered by the NSOpenGLView, so the OS throws away the
  232922. // repaint message, thus never causing our paint() callback, and never repainting
  232923. // the comp. So invalidating just a little bit around the edge helps..
  232924. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  232925. }
  232926. void* getNativeWindowHandle() const { return viewHolder->view; }
  232927. juce_UseDebuggingNewOperator
  232928. NSOpenGLContext* renderContext;
  232929. ThreadSafeNSOpenGLView* view;
  232930. private:
  232931. OpenGLPixelFormat pixelFormat;
  232932. ScopedPointer <NSViewComponentInternal> viewHolder;
  232933. WindowedGLContext (const WindowedGLContext&);
  232934. WindowedGLContext& operator= (const WindowedGLContext&);
  232935. };
  232936. OpenGLContext* OpenGLComponent::createContext()
  232937. {
  232938. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  232939. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  232940. return (c->renderContext != 0) ? c.release() : 0;
  232941. }
  232942. void* OpenGLComponent::getNativeWindowHandle() const
  232943. {
  232944. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  232945. : 0;
  232946. }
  232947. void juce_glViewport (const int w, const int h)
  232948. {
  232949. glViewport (0, 0, w, h);
  232950. }
  232951. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  232952. OwnedArray <OpenGLPixelFormat>& results)
  232953. {
  232954. /* GLint attribs [64];
  232955. int n = 0;
  232956. attribs[n++] = AGL_RGBA;
  232957. attribs[n++] = AGL_DOUBLEBUFFER;
  232958. attribs[n++] = AGL_ACCELERATED;
  232959. attribs[n++] = AGL_NO_RECOVERY;
  232960. attribs[n++] = AGL_NONE;
  232961. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  232962. while (p != 0)
  232963. {
  232964. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  232965. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  232966. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  232967. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  232968. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  232969. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  232970. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  232971. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  232972. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  232973. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  232974. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  232975. results.add (pf);
  232976. p = aglNextPixelFormat (p);
  232977. }*/
  232978. //jassertfalse // can't see how you do this in cocoa!
  232979. }
  232980. #else
  232981. END_JUCE_NAMESPACE
  232982. @interface JuceGLView : UIView
  232983. {
  232984. }
  232985. + (Class) layerClass;
  232986. @end
  232987. @implementation JuceGLView
  232988. + (Class) layerClass
  232989. {
  232990. return [CAEAGLLayer class];
  232991. }
  232992. @end
  232993. BEGIN_JUCE_NAMESPACE
  232994. class GLESContext : public OpenGLContext
  232995. {
  232996. public:
  232997. GLESContext (UIViewComponentPeer* peer,
  232998. Component* const component_,
  232999. const OpenGLPixelFormat& pixelFormat_,
  233000. const GLESContext* const sharedContext,
  233001. NSUInteger apiType)
  233002. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  233003. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  233004. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  233005. {
  233006. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  233007. view.opaque = YES;
  233008. view.hidden = NO;
  233009. view.backgroundColor = [UIColor blackColor];
  233010. view.userInteractionEnabled = NO;
  233011. glLayer = (CAEAGLLayer*) [view layer];
  233012. [peer->view addSubview: view];
  233013. if (sharedContext != 0)
  233014. context = [[EAGLContext alloc] initWithAPI: apiType
  233015. sharegroup: [sharedContext->context sharegroup]];
  233016. else
  233017. context = [[EAGLContext alloc] initWithAPI: apiType];
  233018. createGLBuffers();
  233019. }
  233020. ~GLESContext()
  233021. {
  233022. deleteContext();
  233023. [view removeFromSuperview];
  233024. [view release];
  233025. freeGLBuffers();
  233026. }
  233027. void deleteContext()
  233028. {
  233029. makeInactive();
  233030. [context release];
  233031. context = nil;
  233032. }
  233033. bool makeActive() const throw()
  233034. {
  233035. jassert (context != 0);
  233036. [EAGLContext setCurrentContext: context];
  233037. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  233038. return true;
  233039. }
  233040. void swapBuffers()
  233041. {
  233042. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  233043. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  233044. }
  233045. bool makeInactive() const throw()
  233046. {
  233047. return [EAGLContext setCurrentContext: nil];
  233048. }
  233049. bool isActive() const throw()
  233050. {
  233051. return [EAGLContext currentContext] == context;
  233052. }
  233053. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  233054. void* getRawContext() const throw() { return glLayer; }
  233055. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  233056. {
  233057. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  233058. if (lastWidth != w || lastHeight != h)
  233059. {
  233060. lastWidth = w;
  233061. lastHeight = h;
  233062. freeGLBuffers();
  233063. createGLBuffers();
  233064. }
  233065. }
  233066. bool setSwapInterval (const int numFramesPerSwap)
  233067. {
  233068. numFrames = numFramesPerSwap;
  233069. return true;
  233070. }
  233071. int getSwapInterval() const
  233072. {
  233073. return numFrames;
  233074. }
  233075. void repaint()
  233076. {
  233077. }
  233078. void createGLBuffers()
  233079. {
  233080. makeActive();
  233081. glGenFramebuffersOES (1, &frameBufferHandle);
  233082. glGenRenderbuffersOES (1, &colorBufferHandle);
  233083. glGenRenderbuffersOES (1, &depthBufferHandle);
  233084. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  233085. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  233086. GLint width, height;
  233087. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  233088. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  233089. if (useDepthBuffer)
  233090. {
  233091. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  233092. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  233093. }
  233094. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  233095. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  233096. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  233097. if (useDepthBuffer)
  233098. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  233099. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  233100. }
  233101. void freeGLBuffers()
  233102. {
  233103. if (frameBufferHandle != 0)
  233104. {
  233105. glDeleteFramebuffersOES (1, &frameBufferHandle);
  233106. frameBufferHandle = 0;
  233107. }
  233108. if (colorBufferHandle != 0)
  233109. {
  233110. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  233111. colorBufferHandle = 0;
  233112. }
  233113. if (depthBufferHandle != 0)
  233114. {
  233115. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  233116. depthBufferHandle = 0;
  233117. }
  233118. }
  233119. juce_UseDebuggingNewOperator
  233120. private:
  233121. Component::SafePointer<Component> component;
  233122. OpenGLPixelFormat pixelFormat;
  233123. JuceGLView* view;
  233124. CAEAGLLayer* glLayer;
  233125. EAGLContext* context;
  233126. bool useDepthBuffer;
  233127. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  233128. int numFrames;
  233129. int lastWidth, lastHeight;
  233130. GLESContext (const GLESContext&);
  233131. GLESContext& operator= (const GLESContext&);
  233132. };
  233133. OpenGLContext* OpenGLComponent::createContext()
  233134. {
  233135. ScopedAutoReleasePool pool;
  233136. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  233137. if (peer != 0)
  233138. return new GLESContext (peer, this, preferredPixelFormat,
  233139. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  233140. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  233141. return 0;
  233142. }
  233143. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  233144. OwnedArray <OpenGLPixelFormat>& /*results*/)
  233145. {
  233146. }
  233147. void juce_glViewport (const int w, const int h)
  233148. {
  233149. glViewport (0, 0, w, h);
  233150. }
  233151. #endif
  233152. #endif
  233153. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  233154. /*** Start of inlined file: juce_mac_MainMenu.mm ***/
  233155. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233156. // compiled on its own).
  233157. #if JUCE_INCLUDED_FILE
  233158. class JuceMainMenuHandler;
  233159. END_JUCE_NAMESPACE
  233160. using namespace JUCE_NAMESPACE;
  233161. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  233162. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  233163. @interface JuceMenuCallback : NSObject <NSMenuDelegate>
  233164. #else
  233165. @interface JuceMenuCallback : NSObject
  233166. #endif
  233167. {
  233168. JuceMainMenuHandler* owner;
  233169. }
  233170. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  233171. - (void) dealloc;
  233172. - (void) menuItemInvoked: (id) menu;
  233173. - (void) menuNeedsUpdate: (NSMenu*) menu;
  233174. @end
  233175. BEGIN_JUCE_NAMESPACE
  233176. class JuceMainMenuHandler : private MenuBarModel::Listener,
  233177. private DeletedAtShutdown
  233178. {
  233179. public:
  233180. static JuceMainMenuHandler* instance;
  233181. JuceMainMenuHandler()
  233182. : currentModel (0),
  233183. lastUpdateTime (0)
  233184. {
  233185. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  233186. }
  233187. ~JuceMainMenuHandler()
  233188. {
  233189. setMenu (0);
  233190. jassert (instance == this);
  233191. instance = 0;
  233192. [callback release];
  233193. }
  233194. void setMenu (MenuBarModel* const newMenuBarModel)
  233195. {
  233196. if (currentModel != newMenuBarModel)
  233197. {
  233198. if (currentModel != 0)
  233199. currentModel->removeListener (this);
  233200. currentModel = newMenuBarModel;
  233201. if (currentModel != 0)
  233202. currentModel->addListener (this);
  233203. menuBarItemsChanged (0);
  233204. }
  233205. }
  233206. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  233207. const String& name, const int menuId, const int tag)
  233208. {
  233209. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  233210. action: nil
  233211. keyEquivalent: @""];
  233212. [item setTag: tag];
  233213. NSMenu* sub = createMenu (child, name, menuId, tag);
  233214. [parent setSubmenu: sub forItem: item];
  233215. [sub setAutoenablesItems: false];
  233216. [sub release];
  233217. }
  233218. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  233219. const String& name, const int menuId, const int tag)
  233220. {
  233221. [parentItem setTag: tag];
  233222. NSMenu* menu = [parentItem submenu];
  233223. [menu setTitle: juceStringToNS (name)];
  233224. while ([menu numberOfItems] > 0)
  233225. [menu removeItemAtIndex: 0];
  233226. PopupMenu::MenuItemIterator iter (menuToCopy);
  233227. while (iter.next())
  233228. addMenuItem (iter, menu, menuId, tag);
  233229. [menu setAutoenablesItems: false];
  233230. [menu update];
  233231. }
  233232. void menuBarItemsChanged (MenuBarModel*)
  233233. {
  233234. lastUpdateTime = Time::getMillisecondCounter();
  233235. StringArray menuNames;
  233236. if (currentModel != 0)
  233237. menuNames = currentModel->getMenuBarNames();
  233238. NSMenu* menuBar = [NSApp mainMenu];
  233239. while ([menuBar numberOfItems] > 1 + menuNames.size())
  233240. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  233241. int menuId = 1;
  233242. for (int i = 0; i < menuNames.size(); ++i)
  233243. {
  233244. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  233245. if (i >= [menuBar numberOfItems] - 1)
  233246. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  233247. else
  233248. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  233249. }
  233250. }
  233251. static void flashMenuBar (NSMenu* menu)
  233252. {
  233253. if ([[menu title] isEqualToString: @"Apple"])
  233254. return;
  233255. [menu retain];
  233256. const unichar f35Key = NSF35FunctionKey;
  233257. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  233258. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  233259. action: nil
  233260. keyEquivalent: f35String];
  233261. [item setTarget: nil];
  233262. [menu insertItem: item atIndex: [menu numberOfItems]];
  233263. [item release];
  233264. if ([menu indexOfItem: item] >= 0)
  233265. {
  233266. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  233267. location: NSZeroPoint
  233268. modifierFlags: NSCommandKeyMask
  233269. timestamp: 0
  233270. windowNumber: 0
  233271. context: [NSGraphicsContext currentContext]
  233272. characters: f35String
  233273. charactersIgnoringModifiers: f35String
  233274. isARepeat: NO
  233275. keyCode: 0];
  233276. [menu performKeyEquivalent: f35Event];
  233277. if ([menu indexOfItem: item] >= 0)
  233278. [menu removeItem: item]; // (this throws if the item isn't actually in the menu)
  233279. }
  233280. [menu release];
  233281. }
  233282. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  233283. {
  233284. for (NSInteger i = [menu numberOfItems]; --i >= 0;)
  233285. {
  233286. NSMenuItem* m = [menu itemAtIndex: i];
  233287. if ([m tag] == info.commandID)
  233288. return m;
  233289. if ([m submenu] != 0)
  233290. {
  233291. NSMenuItem* found = findMenuItem ([m submenu], info);
  233292. if (found != 0)
  233293. return found;
  233294. }
  233295. }
  233296. return 0;
  233297. }
  233298. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  233299. {
  233300. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  233301. if (item != 0)
  233302. flashMenuBar ([item menu]);
  233303. }
  233304. void updateMenus()
  233305. {
  233306. if (Time::getMillisecondCounter() > lastUpdateTime + 500)
  233307. menuBarItemsChanged (0);
  233308. }
  233309. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  233310. {
  233311. if (currentModel != 0)
  233312. {
  233313. if (commandManager != 0)
  233314. {
  233315. ApplicationCommandTarget::InvocationInfo info (commandId);
  233316. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  233317. commandManager->invoke (info, true);
  233318. }
  233319. currentModel->menuItemSelected (commandId, topLevelIndex);
  233320. }
  233321. }
  233322. MenuBarModel* currentModel;
  233323. uint32 lastUpdateTime;
  233324. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  233325. const int topLevelMenuId, const int topLevelIndex)
  233326. {
  233327. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf ("<end>", false, true));
  233328. if (text == 0)
  233329. text = @"";
  233330. if (iter.isSeparator)
  233331. {
  233332. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  233333. }
  233334. else if (iter.isSectionHeader)
  233335. {
  233336. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233337. action: nil
  233338. keyEquivalent: @""];
  233339. [item setEnabled: false];
  233340. }
  233341. else if (iter.subMenu != 0)
  233342. {
  233343. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233344. action: nil
  233345. keyEquivalent: @""];
  233346. [item setTag: iter.itemId];
  233347. [item setEnabled: iter.isEnabled];
  233348. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  233349. [sub setDelegate: nil];
  233350. [menuToAddTo setSubmenu: sub forItem: item];
  233351. [sub release];
  233352. }
  233353. else
  233354. {
  233355. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233356. action: @selector (menuItemInvoked:)
  233357. keyEquivalent: @""];
  233358. [item setTag: iter.itemId];
  233359. [item setEnabled: iter.isEnabled];
  233360. [item setState: iter.isTicked ? NSOnState : NSOffState];
  233361. [item setTarget: (id) callback];
  233362. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  233363. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  233364. [item setRepresentedObject: info];
  233365. if (iter.commandManager != 0)
  233366. {
  233367. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  233368. ->getKeyPressesAssignedToCommand (iter.itemId));
  233369. if (keyPresses.size() > 0)
  233370. {
  233371. const KeyPress& kp = keyPresses.getReference(0);
  233372. if (kp.getKeyCode() != KeyPress::backspaceKey
  233373. && kp.getKeyCode() != KeyPress::deleteKey) // (adding these is annoying because it flashes the menu bar
  233374. // every time you press the key while editing text)
  233375. {
  233376. juce_wchar key = kp.getTextCharacter();
  233377. if (kp.getKeyCode() == KeyPress::backspaceKey)
  233378. key = NSBackspaceCharacter;
  233379. else if (kp.getKeyCode() == KeyPress::deleteKey)
  233380. key = NSDeleteCharacter;
  233381. else if (key == 0)
  233382. key = (juce_wchar) kp.getKeyCode();
  233383. unsigned int mods = 0;
  233384. if (kp.getModifiers().isShiftDown())
  233385. mods |= NSShiftKeyMask;
  233386. if (kp.getModifiers().isCtrlDown())
  233387. mods |= NSControlKeyMask;
  233388. if (kp.getModifiers().isAltDown())
  233389. mods |= NSAlternateKeyMask;
  233390. if (kp.getModifiers().isCommandDown())
  233391. mods |= NSCommandKeyMask;
  233392. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  233393. [item setKeyEquivalentModifierMask: mods];
  233394. }
  233395. }
  233396. }
  233397. }
  233398. }
  233399. JuceMenuCallback* callback;
  233400. private:
  233401. NSMenu* createMenu (const PopupMenu menu,
  233402. const String& menuName,
  233403. const int topLevelMenuId,
  233404. const int topLevelIndex)
  233405. {
  233406. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  233407. [m setAutoenablesItems: false];
  233408. [m setDelegate: callback];
  233409. PopupMenu::MenuItemIterator iter (menu);
  233410. while (iter.next())
  233411. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  233412. [m update];
  233413. return m;
  233414. }
  233415. };
  233416. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  233417. END_JUCE_NAMESPACE
  233418. @implementation JuceMenuCallback
  233419. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  233420. {
  233421. [super init];
  233422. owner = owner_;
  233423. return self;
  233424. }
  233425. - (void) dealloc
  233426. {
  233427. [super dealloc];
  233428. }
  233429. - (void) menuItemInvoked: (id) menu
  233430. {
  233431. NSMenuItem* item = (NSMenuItem*) menu;
  233432. if ([[item representedObject] isKindOfClass: [NSArray class]])
  233433. {
  233434. // 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
  233435. // our own components, which may have wanted to intercept it. So, rather than dispatching directly, we'll feed it back
  233436. // into the focused component and let it trigger the menu item indirectly.
  233437. NSEvent* e = [NSApp currentEvent];
  233438. if ([e type] == NSKeyDown || [e type] == NSKeyUp)
  233439. {
  233440. if (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent() != 0)
  233441. {
  233442. JUCE_NAMESPACE::NSViewComponentPeer* peer = dynamic_cast <JUCE_NAMESPACE::NSViewComponentPeer*> (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent()->getPeer());
  233443. if (peer != 0)
  233444. {
  233445. if ([e type] == NSKeyDown)
  233446. peer->redirectKeyDown (e);
  233447. else
  233448. peer->redirectKeyUp (e);
  233449. return;
  233450. }
  233451. }
  233452. }
  233453. NSArray* info = (NSArray*) [item representedObject];
  233454. owner->invoke ((int) [item tag],
  233455. (ApplicationCommandManager*) (pointer_sized_int)
  233456. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  233457. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  233458. }
  233459. }
  233460. - (void) menuNeedsUpdate: (NSMenu*) menu;
  233461. {
  233462. (void) menu;
  233463. if (JuceMainMenuHandler::instance != 0)
  233464. JuceMainMenuHandler::instance->updateMenus();
  233465. }
  233466. @end
  233467. BEGIN_JUCE_NAMESPACE
  233468. static NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName,
  233469. const PopupMenu* extraItems)
  233470. {
  233471. if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0)
  233472. {
  233473. PopupMenu::MenuItemIterator iter (*extraItems);
  233474. while (iter.next())
  233475. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  233476. [menu addItem: [NSMenuItem separatorItem]];
  233477. }
  233478. NSMenuItem* item;
  233479. // Services...
  233480. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil)
  233481. action: nil keyEquivalent: @""];
  233482. [menu addItem: item];
  233483. [item release];
  233484. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  233485. [menu setSubmenu: servicesMenu forItem: item];
  233486. [NSApp setServicesMenu: servicesMenu];
  233487. [servicesMenu release];
  233488. [menu addItem: [NSMenuItem separatorItem]];
  233489. // Hide + Show stuff...
  233490. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  233491. action: @selector (hide:) keyEquivalent: @"h"];
  233492. [item setTarget: NSApp];
  233493. [menu addItem: item];
  233494. [item release];
  233495. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil)
  233496. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  233497. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  233498. [item setTarget: NSApp];
  233499. [menu addItem: item];
  233500. [item release];
  233501. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil)
  233502. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  233503. [item setTarget: NSApp];
  233504. [menu addItem: item];
  233505. [item release];
  233506. [menu addItem: [NSMenuItem separatorItem]];
  233507. // Quit item....
  233508. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  233509. action: @selector (terminate:) keyEquivalent: @"q"];
  233510. [item setTarget: NSApp];
  233511. [menu addItem: item];
  233512. [item release];
  233513. return menu;
  233514. }
  233515. // Since our app has no NIB, this initialises a standard app menu...
  233516. static void rebuildMainMenu (const PopupMenu* extraItems)
  233517. {
  233518. // this can't be used in a plugin!
  233519. jassert (JUCEApplication::isStandaloneApp());
  233520. if (JUCEApplication::getInstance() != 0)
  233521. {
  233522. const ScopedAutoReleasePool pool;
  233523. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  233524. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  233525. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"];
  233526. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  233527. [mainMenu setSubmenu: appMenu forItem: item];
  233528. [NSApp setMainMenu: mainMenu];
  233529. createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  233530. [appMenu release];
  233531. [mainMenu release];
  233532. }
  233533. }
  233534. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  233535. const PopupMenu* extraAppleMenuItems)
  233536. {
  233537. if (getMacMainMenu() != newMenuBarModel)
  233538. {
  233539. const ScopedAutoReleasePool pool;
  233540. if (newMenuBarModel == 0)
  233541. {
  233542. delete JuceMainMenuHandler::instance;
  233543. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  233544. jassert (extraAppleMenuItems == 0); // you can't specify some extra items without also supplying a model
  233545. extraAppleMenuItems = 0;
  233546. }
  233547. else
  233548. {
  233549. if (JuceMainMenuHandler::instance == 0)
  233550. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  233551. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  233552. }
  233553. }
  233554. rebuildMainMenu (extraAppleMenuItems);
  233555. if (newMenuBarModel != 0)
  233556. newMenuBarModel->menuItemsChanged();
  233557. }
  233558. MenuBarModel* MenuBarModel::getMacMainMenu()
  233559. {
  233560. return JuceMainMenuHandler::instance != 0
  233561. ? JuceMainMenuHandler::instance->currentModel : 0;
  233562. }
  233563. void juce_initialiseMacMainMenu()
  233564. {
  233565. if (JuceMainMenuHandler::instance == 0)
  233566. rebuildMainMenu (0);
  233567. }
  233568. #endif
  233569. /*** End of inlined file: juce_mac_MainMenu.mm ***/
  233570. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  233571. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233572. // compiled on its own).
  233573. #if JUCE_INCLUDED_FILE
  233574. #if JUCE_MAC
  233575. END_JUCE_NAMESPACE
  233576. using namespace JUCE_NAMESPACE;
  233577. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  233578. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  233579. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  233580. #else
  233581. @interface JuceFileChooserDelegate : NSObject
  233582. #endif
  233583. {
  233584. StringArray* filters;
  233585. }
  233586. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  233587. - (void) dealloc;
  233588. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  233589. @end
  233590. @implementation JuceFileChooserDelegate
  233591. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  233592. {
  233593. [super init];
  233594. filters = filters_;
  233595. return self;
  233596. }
  233597. - (void) dealloc
  233598. {
  233599. delete filters;
  233600. [super dealloc];
  233601. }
  233602. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  233603. {
  233604. (void) sender;
  233605. const File f (nsStringToJuce (filename));
  233606. for (int i = filters->size(); --i >= 0;)
  233607. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  233608. return true;
  233609. return f.isDirectory();
  233610. }
  233611. @end
  233612. BEGIN_JUCE_NAMESPACE
  233613. void FileChooser::showPlatformDialog (Array<File>& results,
  233614. const String& title,
  233615. const File& currentFileOrDirectory,
  233616. const String& filter,
  233617. bool selectsDirectory,
  233618. bool selectsFiles,
  233619. bool isSaveDialogue,
  233620. bool warnAboutOverwritingExistingFiles,
  233621. bool selectMultipleFiles,
  233622. FilePreviewComponent* extraInfoComponent)
  233623. {
  233624. const ScopedAutoReleasePool pool;
  233625. StringArray* filters = new StringArray();
  233626. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  233627. filters->trim();
  233628. filters->removeEmptyStrings();
  233629. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  233630. [delegate autorelease];
  233631. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  233632. : [NSOpenPanel openPanel];
  233633. [panel setTitle: juceStringToNS (title)];
  233634. if (! isSaveDialogue)
  233635. {
  233636. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  233637. [openPanel setCanChooseDirectories: selectsDirectory];
  233638. [openPanel setCanChooseFiles: selectsFiles];
  233639. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  233640. }
  233641. [panel setDelegate: delegate];
  233642. if (isSaveDialogue || selectsDirectory)
  233643. [panel setCanCreateDirectories: YES];
  233644. String directory, filename;
  233645. if (currentFileOrDirectory.isDirectory())
  233646. {
  233647. directory = currentFileOrDirectory.getFullPathName();
  233648. }
  233649. else
  233650. {
  233651. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  233652. filename = currentFileOrDirectory.getFileName();
  233653. }
  233654. if ([panel runModalForDirectory: juceStringToNS (directory)
  233655. file: juceStringToNS (filename)]
  233656. == NSOKButton)
  233657. {
  233658. if (isSaveDialogue)
  233659. {
  233660. results.add (File (nsStringToJuce ([panel filename])));
  233661. }
  233662. else
  233663. {
  233664. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  233665. NSArray* urls = [openPanel filenames];
  233666. for (unsigned int i = 0; i < [urls count]; ++i)
  233667. {
  233668. NSString* f = [urls objectAtIndex: i];
  233669. results.add (File (nsStringToJuce (f)));
  233670. }
  233671. }
  233672. }
  233673. [panel setDelegate: nil];
  233674. }
  233675. #else
  233676. void FileChooser::showPlatformDialog (Array<File>& results,
  233677. const String& title,
  233678. const File& currentFileOrDirectory,
  233679. const String& filter,
  233680. bool selectsDirectory,
  233681. bool selectsFiles,
  233682. bool isSaveDialogue,
  233683. bool warnAboutOverwritingExistingFiles,
  233684. bool selectMultipleFiles,
  233685. FilePreviewComponent* extraInfoComponent)
  233686. {
  233687. const ScopedAutoReleasePool pool;
  233688. jassertfalse; //xxx to do
  233689. }
  233690. #endif
  233691. #endif
  233692. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  233693. /*** Start of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  233694. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233695. // compiled on its own).
  233696. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  233697. END_JUCE_NAMESPACE
  233698. #define NonInterceptingQTMovieView MakeObjCClassName(NonInterceptingQTMovieView)
  233699. @interface NonInterceptingQTMovieView : QTMovieView
  233700. {
  233701. }
  233702. - (id) initWithFrame: (NSRect) frame;
  233703. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent;
  233704. - (NSView*) hitTest: (NSPoint) p;
  233705. @end
  233706. @implementation NonInterceptingQTMovieView
  233707. - (id) initWithFrame: (NSRect) frame
  233708. {
  233709. self = [super initWithFrame: frame];
  233710. [self setNextResponder: [self superview]];
  233711. return self;
  233712. }
  233713. - (void) dealloc
  233714. {
  233715. [super dealloc];
  233716. }
  233717. - (NSView*) hitTest: (NSPoint) point
  233718. {
  233719. return [self isControllerVisible] ? [super hitTest: point] : nil;
  233720. }
  233721. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent
  233722. {
  233723. return YES;
  233724. }
  233725. @end
  233726. BEGIN_JUCE_NAMESPACE
  233727. #define theMovie (static_cast <QTMovie*> (movie))
  233728. QuickTimeMovieComponent::QuickTimeMovieComponent()
  233729. : movie (0)
  233730. {
  233731. setOpaque (true);
  233732. setVisible (true);
  233733. QTMovieView* view = [[NonInterceptingQTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  233734. setView (view);
  233735. [view release];
  233736. }
  233737. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  233738. {
  233739. closeMovie();
  233740. setView (0);
  233741. }
  233742. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  233743. {
  233744. return true;
  233745. }
  233746. static QTMovie* openMovieFromStream (InputStream* movieStream, File& movieFile)
  233747. {
  233748. // unfortunately, QTMovie objects can only be created on the main thread..
  233749. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  233750. QTMovie* movie = 0;
  233751. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  233752. if (fin != 0)
  233753. {
  233754. movieFile = fin->getFile();
  233755. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  233756. error: nil];
  233757. }
  233758. else
  233759. {
  233760. MemoryBlock temp;
  233761. movieStream->readIntoMemoryBlock (temp);
  233762. const char* const suffixesToTry[] = { ".mov", ".mp3", ".avi", ".m4a" };
  233763. for (int i = 0; i < numElementsInArray (suffixesToTry); ++i)
  233764. {
  233765. movie = [QTMovie movieWithDataReference: [QTDataReference dataReferenceWithReferenceToData: [NSData dataWithBytes: temp.getData()
  233766. length: temp.getSize()]
  233767. name: [NSString stringWithUTF8String: suffixesToTry[i]]
  233768. MIMEType: @""]
  233769. error: nil];
  233770. if (movie != 0)
  233771. break;
  233772. }
  233773. }
  233774. return movie;
  233775. }
  233776. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  233777. const bool isControllerVisible_)
  233778. {
  233779. return loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible_);
  233780. }
  233781. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  233782. const bool controllerVisible_)
  233783. {
  233784. closeMovie();
  233785. if (getPeer() == 0)
  233786. {
  233787. // To open a movie, this component must be visible inside a functioning window, so that
  233788. // the QT control can be assigned to the window.
  233789. jassertfalse;
  233790. return false;
  233791. }
  233792. movie = openMovieFromStream (movieStream, movieFile);
  233793. [theMovie retain];
  233794. QTMovieView* view = (QTMovieView*) getView();
  233795. [view setMovie: theMovie];
  233796. [view setControllerVisible: controllerVisible_];
  233797. setLooping (looping);
  233798. return movie != nil;
  233799. }
  233800. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  233801. const bool isControllerVisible_)
  233802. {
  233803. // unfortunately, QTMovie objects can only be created on the main thread..
  233804. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  233805. closeMovie();
  233806. if (getPeer() == 0)
  233807. {
  233808. // To open a movie, this component must be visible inside a functioning window, so that
  233809. // the QT control can be assigned to the window.
  233810. jassertfalse;
  233811. return false;
  233812. }
  233813. NSURL* url = [NSURL URLWithString: juceStringToNS (movieURL.toString (true))];
  233814. NSError* err;
  233815. if ([QTMovie canInitWithURL: url])
  233816. movie = [QTMovie movieWithURL: url error: &err];
  233817. [theMovie retain];
  233818. QTMovieView* view = (QTMovieView*) getView();
  233819. [view setMovie: theMovie];
  233820. [view setControllerVisible: controllerVisible];
  233821. setLooping (looping);
  233822. return movie != nil;
  233823. }
  233824. void QuickTimeMovieComponent::closeMovie()
  233825. {
  233826. stop();
  233827. QTMovieView* view = (QTMovieView*) getView();
  233828. [view setMovie: nil];
  233829. [theMovie release];
  233830. movie = 0;
  233831. movieFile = File::nonexistent;
  233832. }
  233833. bool QuickTimeMovieComponent::isMovieOpen() const
  233834. {
  233835. return movie != nil;
  233836. }
  233837. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  233838. {
  233839. return movieFile;
  233840. }
  233841. void QuickTimeMovieComponent::play()
  233842. {
  233843. [theMovie play];
  233844. }
  233845. void QuickTimeMovieComponent::stop()
  233846. {
  233847. [theMovie stop];
  233848. }
  233849. bool QuickTimeMovieComponent::isPlaying() const
  233850. {
  233851. return movie != 0 && [theMovie rate] != 0;
  233852. }
  233853. void QuickTimeMovieComponent::setPosition (const double seconds)
  233854. {
  233855. if (movie != 0)
  233856. {
  233857. QTTime t;
  233858. t.timeValue = (uint64) (100000.0 * seconds);
  233859. t.timeScale = 100000;
  233860. t.flags = 0;
  233861. [theMovie setCurrentTime: t];
  233862. }
  233863. }
  233864. double QuickTimeMovieComponent::getPosition() const
  233865. {
  233866. if (movie == 0)
  233867. return 0.0;
  233868. QTTime t = [theMovie currentTime];
  233869. return t.timeValue / (double) t.timeScale;
  233870. }
  233871. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  233872. {
  233873. [theMovie setRate: newSpeed];
  233874. }
  233875. double QuickTimeMovieComponent::getMovieDuration() const
  233876. {
  233877. if (movie == 0)
  233878. return 0.0;
  233879. QTTime t = [theMovie duration];
  233880. return t.timeValue / (double) t.timeScale;
  233881. }
  233882. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  233883. {
  233884. looping = shouldLoop;
  233885. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  233886. forKey: QTMovieLoopsAttribute];
  233887. }
  233888. bool QuickTimeMovieComponent::isLooping() const
  233889. {
  233890. return looping;
  233891. }
  233892. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  233893. {
  233894. [theMovie setVolume: newVolume];
  233895. }
  233896. float QuickTimeMovieComponent::getMovieVolume() const
  233897. {
  233898. return movie != 0 ? [theMovie volume] : 0.0f;
  233899. }
  233900. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  233901. {
  233902. width = 0;
  233903. height = 0;
  233904. if (movie != 0)
  233905. {
  233906. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  233907. width = (int) s.width;
  233908. height = (int) s.height;
  233909. }
  233910. }
  233911. void QuickTimeMovieComponent::paint (Graphics& g)
  233912. {
  233913. if (movie == 0)
  233914. g.fillAll (Colours::black);
  233915. }
  233916. bool QuickTimeMovieComponent::isControllerVisible() const
  233917. {
  233918. return controllerVisible;
  233919. }
  233920. void QuickTimeMovieComponent::goToStart()
  233921. {
  233922. setPosition (0.0);
  233923. }
  233924. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  233925. const RectanglePlacement& placement)
  233926. {
  233927. int normalWidth, normalHeight;
  233928. getMovieNormalSize (normalWidth, normalHeight);
  233929. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  233930. {
  233931. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  233932. placement.applyTo (x, y, w, h,
  233933. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  233934. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  233935. if (w > 0 && h > 0)
  233936. {
  233937. setBounds (roundToInt (x), roundToInt (y),
  233938. roundToInt (w), roundToInt (h));
  233939. }
  233940. }
  233941. else
  233942. {
  233943. setBounds (spaceToFitWithin);
  233944. }
  233945. }
  233946. #if ! (JUCE_MAC && JUCE_64BIT)
  233947. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  233948. {
  233949. if (movieStream == 0)
  233950. return false;
  233951. File file;
  233952. QTMovie* movie = openMovieFromStream (movieStream, file);
  233953. if (movie != nil)
  233954. result = [movie quickTimeMovie];
  233955. return movie != nil;
  233956. }
  233957. #endif
  233958. #endif
  233959. /*** End of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  233960. /*** Start of inlined file: juce_mac_AudioCDBurner.mm ***/
  233961. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233962. // compiled on its own).
  233963. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  233964. const int kilobytesPerSecond1x = 176;
  233965. END_JUCE_NAMESPACE
  233966. #define OpenDiskDevice MakeObjCClassName(OpenDiskDevice)
  233967. @interface OpenDiskDevice : NSObject
  233968. {
  233969. @public
  233970. DRDevice* device;
  233971. NSMutableArray* tracks;
  233972. bool underrunProtection;
  233973. }
  233974. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device;
  233975. - (void) dealloc;
  233976. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  233977. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  233978. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed;
  233979. @end
  233980. #define AudioTrackProducer MakeObjCClassName(AudioTrackProducer)
  233981. @interface AudioTrackProducer : NSObject
  233982. {
  233983. JUCE_NAMESPACE::AudioSource* source;
  233984. int readPosition, lengthInFrames;
  233985. }
  233986. - (AudioTrackProducer*) init: (int) lengthInFrames;
  233987. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  233988. - (void) dealloc;
  233989. - (void) setupTrackProperties: (DRTrack*) track;
  233990. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  233991. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  233992. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  233993. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  233994. toMedia:(NSDictionary*)mediaInfo;
  233995. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  233996. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  233997. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  233998. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  233999. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  234000. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  234001. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  234002. ioFlags:(uint32_t*)flags;
  234003. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  234004. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  234005. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  234006. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  234007. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  234008. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  234009. ioFlags:(uint32_t*)flags;
  234010. @end
  234011. @implementation OpenDiskDevice
  234012. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device_
  234013. {
  234014. [super init];
  234015. device = device_;
  234016. tracks = [[NSMutableArray alloc] init];
  234017. underrunProtection = true;
  234018. return self;
  234019. }
  234020. - (void) dealloc
  234021. {
  234022. [tracks release];
  234023. [super dealloc];
  234024. }
  234025. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  234026. {
  234027. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  234028. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  234029. [p setupTrackProperties: t];
  234030. [tracks addObject: t];
  234031. [t release];
  234032. [p release];
  234033. }
  234034. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  234035. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed
  234036. {
  234037. DRBurn* burn = [DRBurn burnForDevice: device];
  234038. if (! [device acquireExclusiveAccess])
  234039. {
  234040. *error = "Couldn't open or write to the CD device";
  234041. return;
  234042. }
  234043. [device acquireMediaReservation];
  234044. NSMutableDictionary* d = [[burn properties] mutableCopy];
  234045. [d autorelease];
  234046. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  234047. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  234048. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount) forKey: DRBurnCompletionActionKey];
  234049. if (burnSpeed > 0)
  234050. [d setObject: [NSNumber numberWithFloat: burnSpeed * JUCE_NAMESPACE::kilobytesPerSecond1x] forKey: DRBurnRequestedSpeedKey];
  234051. if (! underrunProtection)
  234052. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnUnderrunProtectionKey];
  234053. [burn setProperties: d];
  234054. [burn writeLayout: tracks];
  234055. for (;;)
  234056. {
  234057. JUCE_NAMESPACE::Thread::sleep (300);
  234058. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  234059. if (listener != 0 && listener->audioCDBurnProgress (progress))
  234060. {
  234061. [burn abort];
  234062. *error = "User cancelled the write operation";
  234063. break;
  234064. }
  234065. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  234066. {
  234067. *error = "Write operation failed";
  234068. break;
  234069. }
  234070. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  234071. {
  234072. break;
  234073. }
  234074. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  234075. objectForKey: DRErrorStatusErrorStringKey];
  234076. if ([err length] > 0)
  234077. {
  234078. *error = JUCE_NAMESPACE::String::fromUTF8 ([err UTF8String]);
  234079. break;
  234080. }
  234081. }
  234082. [device releaseMediaReservation];
  234083. [device releaseExclusiveAccess];
  234084. }
  234085. @end
  234086. @implementation AudioTrackProducer
  234087. - (AudioTrackProducer*) init: (int) lengthInFrames_
  234088. {
  234089. lengthInFrames = lengthInFrames_;
  234090. readPosition = 0;
  234091. return self;
  234092. }
  234093. - (void) setupTrackProperties: (DRTrack*) track
  234094. {
  234095. NSMutableDictionary* p = [[track properties] mutableCopy];
  234096. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  234097. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  234098. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  234099. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  234100. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  234101. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  234102. [track setProperties: p];
  234103. [p release];
  234104. }
  234105. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  234106. {
  234107. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  234108. if (s != nil)
  234109. s->source = source_;
  234110. return s;
  234111. }
  234112. - (void) dealloc
  234113. {
  234114. if (source != 0)
  234115. {
  234116. source->releaseResources();
  234117. delete source;
  234118. }
  234119. [super dealloc];
  234120. }
  234121. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  234122. {
  234123. }
  234124. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  234125. {
  234126. return true;
  234127. }
  234128. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  234129. {
  234130. return lengthInFrames;
  234131. }
  234132. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  234133. toMedia: (NSDictionary*) mediaInfo
  234134. {
  234135. if (source != 0)
  234136. source->prepareToPlay (44100 / 75, 44100);
  234137. readPosition = 0;
  234138. return true;
  234139. }
  234140. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  234141. {
  234142. if (source != 0)
  234143. source->prepareToPlay (44100 / 75, 44100);
  234144. return true;
  234145. }
  234146. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  234147. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  234148. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  234149. {
  234150. if (source != 0)
  234151. {
  234152. const int numSamples = JUCE_NAMESPACE::jmin ((int) bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  234153. if (numSamples > 0)
  234154. {
  234155. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  234156. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  234157. info.buffer = &tempBuffer;
  234158. info.startSample = 0;
  234159. info.numSamples = numSamples;
  234160. source->getNextAudioBlock (info);
  234161. typedef JUCE_NAMESPACE::AudioData::Pointer <JUCE_NAMESPACE::AudioData::Int16,
  234162. JUCE_NAMESPACE::AudioData::LittleEndian,
  234163. JUCE_NAMESPACE::AudioData::Interleaved,
  234164. JUCE_NAMESPACE::AudioData::NonConst> CDSampleFormat;
  234165. typedef JUCE_NAMESPACE::AudioData::Pointer <JUCE_NAMESPACE::AudioData::Float32,
  234166. JUCE_NAMESPACE::AudioData::NativeEndian,
  234167. JUCE_NAMESPACE::AudioData::NonInterleaved,
  234168. JUCE_NAMESPACE::AudioData::Const> SourceSampleFormat;
  234169. CDSampleFormat left (buffer, 2);
  234170. left.convertSamples (SourceSampleFormat (tempBuffer.getSampleData (0)), numSamples);
  234171. CDSampleFormat right (buffer + 2, 2);
  234172. right.convertSamples (SourceSampleFormat (tempBuffer.getSampleData (1)), numSamples);
  234173. readPosition += numSamples;
  234174. }
  234175. return numSamples * 4;
  234176. }
  234177. return 0;
  234178. }
  234179. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  234180. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  234181. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  234182. ioFlags: (uint32_t*) flags
  234183. {
  234184. zeromem (buffer, bufferLength);
  234185. return bufferLength;
  234186. }
  234187. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  234188. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  234189. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  234190. {
  234191. return true;
  234192. }
  234193. @end
  234194. BEGIN_JUCE_NAMESPACE
  234195. class AudioCDBurner::Pimpl : public Timer
  234196. {
  234197. public:
  234198. Pimpl (AudioCDBurner& owner_, const int deviceIndex)
  234199. : device (0), owner (owner_)
  234200. {
  234201. DRDevice* dev = [[DRDevice devices] objectAtIndex: deviceIndex];
  234202. if (dev != 0)
  234203. {
  234204. device = [[OpenDiskDevice alloc] initWithDRDevice: dev];
  234205. lastState = getDiskState();
  234206. startTimer (1000);
  234207. }
  234208. }
  234209. ~Pimpl()
  234210. {
  234211. stopTimer();
  234212. [device release];
  234213. }
  234214. void timerCallback()
  234215. {
  234216. const DiskState state = getDiskState();
  234217. if (state != lastState)
  234218. {
  234219. lastState = state;
  234220. owner.sendChangeMessage (&owner);
  234221. }
  234222. }
  234223. DiskState getDiskState() const
  234224. {
  234225. if ([device->device isValid])
  234226. {
  234227. NSDictionary* status = [device->device status];
  234228. NSString* state = [status objectForKey: DRDeviceMediaStateKey];
  234229. if ([state isEqualTo: DRDeviceMediaStateNone])
  234230. {
  234231. if ([[status objectForKey: DRDeviceIsTrayOpenKey] boolValue])
  234232. return trayOpen;
  234233. return noDisc;
  234234. }
  234235. if ([state isEqualTo: DRDeviceMediaStateMediaPresent])
  234236. {
  234237. if ([[[status objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceMediaBlocksFreeKey] intValue] > 0)
  234238. return writableDiskPresent;
  234239. else
  234240. return readOnlyDiskPresent;
  234241. }
  234242. }
  234243. return unknown;
  234244. }
  234245. bool openTray() { return [device->device isValid] && [device->device ejectMedia]; }
  234246. const Array<int> getAvailableWriteSpeeds() const
  234247. {
  234248. Array<int> results;
  234249. if ([device->device isValid])
  234250. {
  234251. NSArray* speeds = [[[device->device status] objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceBurnSpeedsKey];
  234252. for (unsigned int i = 0; i < [speeds count]; ++i)
  234253. {
  234254. const int kbPerSec = [[speeds objectAtIndex: i] intValue];
  234255. results.add (kbPerSec / kilobytesPerSecond1x);
  234256. }
  234257. }
  234258. return results;
  234259. }
  234260. bool setBufferUnderrunProtection (const bool shouldBeEnabled)
  234261. {
  234262. if ([device->device isValid])
  234263. {
  234264. device->underrunProtection = shouldBeEnabled;
  234265. return shouldBeEnabled && [[[device->device status] objectForKey: DRDeviceCanUnderrunProtectCDKey] boolValue];
  234266. }
  234267. return false;
  234268. }
  234269. int getNumAvailableAudioBlocks() const
  234270. {
  234271. return [[[[device->device status] objectForKey: DRDeviceMediaInfoKey]
  234272. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  234273. }
  234274. OpenDiskDevice* device;
  234275. private:
  234276. DiskState lastState;
  234277. AudioCDBurner& owner;
  234278. };
  234279. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  234280. {
  234281. pimpl = new Pimpl (*this, deviceIndex);
  234282. }
  234283. AudioCDBurner::~AudioCDBurner()
  234284. {
  234285. }
  234286. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  234287. {
  234288. ScopedPointer <AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  234289. if (b->pimpl->device == 0)
  234290. b = 0;
  234291. return b.release();
  234292. }
  234293. static NSArray* findDiskBurnerDevices()
  234294. {
  234295. NSMutableArray* results = [NSMutableArray array];
  234296. NSArray* devs = [DRDevice devices];
  234297. if (devs != 0)
  234298. {
  234299. int num = [devs count];
  234300. int i;
  234301. for (i = 0; i < num; ++i)
  234302. {
  234303. NSDictionary* dic = [[devs objectAtIndex: i] info];
  234304. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  234305. if (name != nil)
  234306. [results addObject: name];
  234307. }
  234308. }
  234309. return results;
  234310. }
  234311. const StringArray AudioCDBurner::findAvailableDevices()
  234312. {
  234313. NSArray* names = findDiskBurnerDevices();
  234314. StringArray s;
  234315. for (unsigned int i = 0; i < [names count]; ++i)
  234316. s.add (String::fromUTF8 ([[names objectAtIndex: i] UTF8String]));
  234317. return s;
  234318. }
  234319. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  234320. {
  234321. return pimpl->getDiskState();
  234322. }
  234323. bool AudioCDBurner::isDiskPresent() const
  234324. {
  234325. return getDiskState() == writableDiskPresent;
  234326. }
  234327. bool AudioCDBurner::openTray()
  234328. {
  234329. return pimpl->openTray();
  234330. }
  234331. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  234332. {
  234333. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  234334. DiskState oldState = getDiskState();
  234335. DiskState newState = oldState;
  234336. while (newState == oldState && Time::currentTimeMillis() < timeout)
  234337. {
  234338. newState = getDiskState();
  234339. Thread::sleep (100);
  234340. }
  234341. return newState;
  234342. }
  234343. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  234344. {
  234345. return pimpl->getAvailableWriteSpeeds();
  234346. }
  234347. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  234348. {
  234349. return pimpl->setBufferUnderrunProtection (shouldBeEnabled);
  234350. }
  234351. int AudioCDBurner::getNumAvailableAudioBlocks() const
  234352. {
  234353. return pimpl->getNumAvailableAudioBlocks();
  234354. }
  234355. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  234356. {
  234357. if ([pimpl->device->device isValid])
  234358. {
  234359. [pimpl->device addSourceTrack: source numSamples: numSamps];
  234360. return true;
  234361. }
  234362. return false;
  234363. }
  234364. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  234365. bool ejectDiscAfterwards,
  234366. bool performFakeBurnForTesting,
  234367. int writeSpeed)
  234368. {
  234369. String error ("Couldn't open or write to the CD device");
  234370. if ([pimpl->device->device isValid])
  234371. {
  234372. error = String::empty;
  234373. [pimpl->device burn: listener
  234374. errorString: &error
  234375. ejectAfterwards: ejectDiscAfterwards
  234376. isFake: performFakeBurnForTesting
  234377. speed: writeSpeed];
  234378. }
  234379. return error;
  234380. }
  234381. #endif
  234382. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  234383. void AudioCDReader::ejectDisk()
  234384. {
  234385. const ScopedAutoReleasePool p;
  234386. [[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: juceStringToNS (volumeDir.getFullPathName())];
  234387. }
  234388. #endif
  234389. /*** End of inlined file: juce_mac_AudioCDBurner.mm ***/
  234390. /*** Start of inlined file: juce_mac_AudioCDReader.mm ***/
  234391. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234392. // compiled on its own).
  234393. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  234394. namespace CDReaderHelpers
  234395. {
  234396. inline const XmlElement* getElementForKey (const XmlElement& xml, const String& key)
  234397. {
  234398. forEachXmlChildElementWithTagName (xml, child, "key")
  234399. if (child->getAllSubText().trim() == key)
  234400. return child->getNextElement();
  234401. return 0;
  234402. }
  234403. static int getIntValueForKey (const XmlElement& xml, const String& key, int defaultValue = -1)
  234404. {
  234405. const XmlElement* const block = getElementForKey (xml, key);
  234406. return block != 0 ? block->getAllSubText().trim().getIntValue() : defaultValue;
  234407. }
  234408. // Get the track offsets for a CD given an XmlElement representing its TOC.Plist.
  234409. // Returns NULL on success, otherwise a const char* representing an error.
  234410. static const char* getTrackOffsets (XmlDocument& xmlDocument, Array<int>& offsets)
  234411. {
  234412. const ScopedPointer<XmlElement> xml (xmlDocument.getDocumentElement());
  234413. if (xml == 0)
  234414. return "Couldn't parse XML in file";
  234415. const XmlElement* const dict = xml->getChildByName ("dict");
  234416. if (dict == 0)
  234417. return "Couldn't get top level dictionary";
  234418. const XmlElement* const sessions = getElementForKey (*dict, "Sessions");
  234419. if (sessions == 0)
  234420. return "Couldn't find sessions key";
  234421. const XmlElement* const session = sessions->getFirstChildElement();
  234422. if (session == 0)
  234423. return "Couldn't find first session";
  234424. const int leadOut = getIntValueForKey (*session, "Leadout Block");
  234425. if (leadOut < 0)
  234426. return "Couldn't find Leadout Block";
  234427. const XmlElement* const trackArray = getElementForKey (*session, "Track Array");
  234428. if (trackArray == 0)
  234429. return "Couldn't find Track Array";
  234430. forEachXmlChildElement (*trackArray, track)
  234431. {
  234432. const int trackValue = getIntValueForKey (*track, "Start Block");
  234433. if (trackValue < 0)
  234434. return "Couldn't find Start Block in the track";
  234435. offsets.add (trackValue * AudioCDReader::samplesPerFrame - 88200);
  234436. }
  234437. offsets.add (leadOut * AudioCDReader::samplesPerFrame - 88200);
  234438. return 0;
  234439. }
  234440. static void findDevices (Array<File>& cds)
  234441. {
  234442. File volumes ("/Volumes");
  234443. volumes.findChildFiles (cds, File::findDirectories, false);
  234444. for (int i = cds.size(); --i >= 0;)
  234445. if (! cds.getReference(i).getChildFile (".TOC.plist").exists())
  234446. cds.remove (i);
  234447. }
  234448. struct TrackSorter
  234449. {
  234450. static int getCDTrackNumber (const File& file)
  234451. {
  234452. return file.getFileName().initialSectionContainingOnly ("0123456789").getIntValue();
  234453. }
  234454. static int compareElements (const File& first, const File& second)
  234455. {
  234456. const int firstTrack = getCDTrackNumber (first);
  234457. const int secondTrack = getCDTrackNumber (second);
  234458. jassert (firstTrack > 0 && secondTrack > 0);
  234459. return firstTrack - secondTrack;
  234460. }
  234461. };
  234462. }
  234463. const StringArray AudioCDReader::getAvailableCDNames()
  234464. {
  234465. Array<File> cds;
  234466. CDReaderHelpers::findDevices (cds);
  234467. StringArray names;
  234468. for (int i = 0; i < cds.size(); ++i)
  234469. names.add (cds.getReference(i).getFileName());
  234470. return names;
  234471. }
  234472. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  234473. {
  234474. Array<File> cds;
  234475. CDReaderHelpers::findDevices (cds);
  234476. if (cds[index].exists())
  234477. return new AudioCDReader (cds[index]);
  234478. return 0;
  234479. }
  234480. AudioCDReader::AudioCDReader (const File& volume)
  234481. : AudioFormatReader (0, "CD Audio"),
  234482. volumeDir (volume),
  234483. currentReaderTrack (-1),
  234484. reader (0)
  234485. {
  234486. sampleRate = 44100.0;
  234487. bitsPerSample = 16;
  234488. numChannels = 2;
  234489. usesFloatingPointData = false;
  234490. refreshTrackLengths();
  234491. }
  234492. AudioCDReader::~AudioCDReader()
  234493. {
  234494. }
  234495. void AudioCDReader::refreshTrackLengths()
  234496. {
  234497. tracks.clear();
  234498. trackStartSamples.clear();
  234499. lengthInSamples = 0;
  234500. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, "*.aiff");
  234501. CDReaderHelpers::TrackSorter sorter;
  234502. tracks.sort (sorter);
  234503. const File toc (volumeDir.getChildFile (".TOC.plist"));
  234504. if (toc.exists())
  234505. {
  234506. XmlDocument doc (toc);
  234507. const char* error = CDReaderHelpers::getTrackOffsets (doc, trackStartSamples);
  234508. (void) error; // could be logged..
  234509. lengthInSamples = trackStartSamples.getLast() - trackStartSamples.getFirst();
  234510. }
  234511. }
  234512. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  234513. int64 startSampleInFile, int numSamples)
  234514. {
  234515. while (numSamples > 0)
  234516. {
  234517. int track = -1;
  234518. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  234519. {
  234520. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  234521. {
  234522. track = i;
  234523. break;
  234524. }
  234525. }
  234526. if (track < 0)
  234527. return false;
  234528. if (track != currentReaderTrack)
  234529. {
  234530. reader = 0;
  234531. FileInputStream* const in = tracks [track].createInputStream();
  234532. if (in != 0)
  234533. {
  234534. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  234535. AiffAudioFormat format;
  234536. reader = format.createReaderFor (bin, true);
  234537. if (reader == 0)
  234538. currentReaderTrack = -1;
  234539. else
  234540. currentReaderTrack = track;
  234541. }
  234542. }
  234543. if (reader == 0)
  234544. return false;
  234545. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  234546. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  234547. reader->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer, startPos, numAvailable);
  234548. numSamples -= numAvailable;
  234549. startSampleInFile += numAvailable;
  234550. }
  234551. return true;
  234552. }
  234553. bool AudioCDReader::isCDStillPresent() const
  234554. {
  234555. return volumeDir.exists();
  234556. }
  234557. bool AudioCDReader::isTrackAudio (int trackNum) const
  234558. {
  234559. return tracks [trackNum].hasFileExtension (".aiff");
  234560. }
  234561. void AudioCDReader::enableIndexScanning (bool b)
  234562. {
  234563. // any way to do this on a Mac??
  234564. }
  234565. int AudioCDReader::getLastIndex() const
  234566. {
  234567. return 0;
  234568. }
  234569. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  234570. {
  234571. return Array <int>();
  234572. }
  234573. #endif
  234574. /*** End of inlined file: juce_mac_AudioCDReader.mm ***/
  234575. /*** Start of inlined file: juce_mac_MessageManager.mm ***/
  234576. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234577. // compiled on its own).
  234578. #if JUCE_INCLUDED_FILE
  234579. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  234580. for example having more than one juce plugin loaded into a host, then when a
  234581. method is called, the actual code that runs might actually be in a different module
  234582. than the one you expect... So any calls to library functions or statics that are
  234583. made inside obj-c methods will probably end up getting executed in a different DLL's
  234584. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  234585. To work around this insanity, I'm only allowing obj-c methods to make calls to
  234586. virtual methods of an object that's known to live inside the right module's space.
  234587. */
  234588. class AppDelegateRedirector
  234589. {
  234590. public:
  234591. AppDelegateRedirector()
  234592. {
  234593. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4
  234594. runLoop = CFRunLoopGetMain();
  234595. #else
  234596. runLoop = CFRunLoopGetCurrent();
  234597. #endif
  234598. CFRunLoopSourceContext sourceContext;
  234599. zerostruct (sourceContext);
  234600. sourceContext.info = this;
  234601. sourceContext.perform = runLoopSourceCallback;
  234602. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  234603. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  234604. }
  234605. virtual ~AppDelegateRedirector()
  234606. {
  234607. CFRunLoopRemoveSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  234608. CFRunLoopSourceInvalidate (runLoopSource);
  234609. CFRelease (runLoopSource);
  234610. }
  234611. virtual NSApplicationTerminateReply shouldTerminate()
  234612. {
  234613. if (JUCEApplication::getInstance() != 0)
  234614. {
  234615. JUCEApplication::getInstance()->systemRequestedQuit();
  234616. if (! MessageManager::getInstance()->hasStopMessageBeenSent())
  234617. return NSTerminateCancel;
  234618. }
  234619. return NSTerminateNow;
  234620. }
  234621. virtual void willTerminate()
  234622. {
  234623. JUCEApplication::appWillTerminateByForce();
  234624. }
  234625. virtual BOOL openFile (NSString* filename)
  234626. {
  234627. if (JUCEApplication::getInstance() != 0)
  234628. {
  234629. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  234630. return YES;
  234631. }
  234632. return NO;
  234633. }
  234634. virtual void openFiles (NSArray* filenames)
  234635. {
  234636. StringArray files;
  234637. for (unsigned int i = 0; i < [filenames count]; ++i)
  234638. {
  234639. String filename (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  234640. if (filename.containsChar (' '))
  234641. filename = filename.quoted('"');
  234642. files.add (filename);
  234643. }
  234644. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  234645. {
  234646. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (" "));
  234647. }
  234648. }
  234649. virtual void focusChanged()
  234650. {
  234651. juce_HandleProcessFocusChange();
  234652. }
  234653. struct CallbackMessagePayload
  234654. {
  234655. MessageCallbackFunction* function;
  234656. void* parameter;
  234657. void* volatile result;
  234658. bool volatile hasBeenExecuted;
  234659. };
  234660. virtual void performCallback (CallbackMessagePayload* pl)
  234661. {
  234662. pl->result = (*pl->function) (pl->parameter);
  234663. pl->hasBeenExecuted = true;
  234664. }
  234665. virtual void deleteSelf()
  234666. {
  234667. delete this;
  234668. }
  234669. void postMessage (Message* const m)
  234670. {
  234671. messages.add (m);
  234672. CFRunLoopSourceSignal (runLoopSource);
  234673. CFRunLoopWakeUp (runLoop);
  234674. }
  234675. private:
  234676. CFRunLoopRef runLoop;
  234677. CFRunLoopSourceRef runLoopSource;
  234678. OwnedArray <Message, CriticalSection> messages;
  234679. void runLoopCallback()
  234680. {
  234681. int numDispatched = 0;
  234682. do
  234683. {
  234684. Message* const nextMessage = messages.removeAndReturn (0);
  234685. if (nextMessage == 0)
  234686. return;
  234687. const ScopedAutoReleasePool pool;
  234688. MessageManager::getInstance()->deliverMessage (nextMessage);
  234689. } while (++numDispatched <= 4);
  234690. CFRunLoopSourceSignal (runLoopSource);
  234691. CFRunLoopWakeUp (runLoop);
  234692. }
  234693. static void runLoopSourceCallback (void* info)
  234694. {
  234695. static_cast <AppDelegateRedirector*> (info)->runLoopCallback();
  234696. }
  234697. };
  234698. END_JUCE_NAMESPACE
  234699. using namespace JUCE_NAMESPACE;
  234700. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  234701. @interface JuceAppDelegate : NSObject
  234702. {
  234703. @private
  234704. id oldDelegate;
  234705. @public
  234706. AppDelegateRedirector* redirector;
  234707. }
  234708. - (JuceAppDelegate*) init;
  234709. - (void) dealloc;
  234710. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  234711. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  234712. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  234713. - (void) applicationWillTerminate: (NSNotification*) aNotification;
  234714. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  234715. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  234716. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  234717. - (void) performCallback: (id) info;
  234718. - (void) dummyMethod;
  234719. @end
  234720. @implementation JuceAppDelegate
  234721. - (JuceAppDelegate*) init
  234722. {
  234723. [super init];
  234724. redirector = new AppDelegateRedirector();
  234725. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  234726. if (JUCEApplication::isStandaloneApp())
  234727. {
  234728. oldDelegate = [NSApp delegate];
  234729. [NSApp setDelegate: self];
  234730. }
  234731. else
  234732. {
  234733. oldDelegate = 0;
  234734. [center addObserver: self selector: @selector (applicationDidResignActive:)
  234735. name: NSApplicationDidResignActiveNotification object: NSApp];
  234736. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  234737. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  234738. [center addObserver: self selector: @selector (applicationWillUnhide:)
  234739. name: NSApplicationWillUnhideNotification object: NSApp];
  234740. }
  234741. return self;
  234742. }
  234743. - (void) dealloc
  234744. {
  234745. if (oldDelegate != 0)
  234746. [NSApp setDelegate: oldDelegate];
  234747. redirector->deleteSelf();
  234748. [super dealloc];
  234749. }
  234750. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  234751. {
  234752. (void) app;
  234753. return redirector->shouldTerminate();
  234754. }
  234755. - (void) applicationWillTerminate: (NSNotification*) aNotification
  234756. {
  234757. (void) aNotification;
  234758. redirector->willTerminate();
  234759. }
  234760. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  234761. {
  234762. (void) app;
  234763. return redirector->openFile (filename);
  234764. }
  234765. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  234766. {
  234767. (void) sender;
  234768. return redirector->openFiles (filenames);
  234769. }
  234770. - (void) applicationDidBecomeActive: (NSNotification*) notification
  234771. {
  234772. (void) notification;
  234773. redirector->focusChanged();
  234774. }
  234775. - (void) applicationDidResignActive: (NSNotification*) notification
  234776. {
  234777. (void) notification;
  234778. redirector->focusChanged();
  234779. }
  234780. - (void) applicationWillUnhide: (NSNotification*) notification
  234781. {
  234782. (void) notification;
  234783. redirector->focusChanged();
  234784. }
  234785. - (void) performCallback: (id) info
  234786. {
  234787. if ([info isKindOfClass: [NSData class]])
  234788. {
  234789. AppDelegateRedirector::CallbackMessagePayload* pl
  234790. = (AppDelegateRedirector::CallbackMessagePayload*) [((NSData*) info) bytes];
  234791. if (pl != 0)
  234792. redirector->performCallback (pl);
  234793. }
  234794. else
  234795. {
  234796. jassertfalse; // should never get here!
  234797. }
  234798. }
  234799. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  234800. @end
  234801. BEGIN_JUCE_NAMESPACE
  234802. static JuceAppDelegate* juceAppDelegate = 0;
  234803. void MessageManager::runDispatchLoop()
  234804. {
  234805. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  234806. {
  234807. const ScopedAutoReleasePool pool;
  234808. // must only be called by the message thread!
  234809. jassert (isThisTheMessageThread());
  234810. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  234811. @try
  234812. {
  234813. [NSApp run];
  234814. }
  234815. @catch (NSException* e)
  234816. {
  234817. // An AppKit exception will kill the app, but at least this provides a chance to log it.,
  234818. std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
  234819. JUCEApplication::sendUnhandledException (&ex, __FILE__, __LINE__);
  234820. }
  234821. @finally
  234822. {
  234823. }
  234824. #else
  234825. [NSApp run];
  234826. #endif
  234827. }
  234828. }
  234829. void MessageManager::stopDispatchLoop()
  234830. {
  234831. quitMessagePosted = true;
  234832. [NSApp stop: nil];
  234833. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  234834. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  234835. }
  234836. static bool isEventBlockedByModalComps (NSEvent* e)
  234837. {
  234838. if (Component::getNumCurrentlyModalComponents() == 0)
  234839. return false;
  234840. NSWindow* const w = [e window];
  234841. if (w == 0 || [w worksWhenModal])
  234842. return false;
  234843. bool isKey = false, isInputAttempt = false;
  234844. switch ([e type])
  234845. {
  234846. case NSKeyDown:
  234847. case NSKeyUp:
  234848. isKey = isInputAttempt = true;
  234849. break;
  234850. case NSLeftMouseDown:
  234851. case NSRightMouseDown:
  234852. case NSOtherMouseDown:
  234853. isInputAttempt = true;
  234854. break;
  234855. case NSLeftMouseDragged:
  234856. case NSRightMouseDragged:
  234857. case NSLeftMouseUp:
  234858. case NSRightMouseUp:
  234859. case NSOtherMouseUp:
  234860. case NSOtherMouseDragged:
  234861. if (Desktop::getInstance().getDraggingMouseSource(0) != 0)
  234862. return false;
  234863. break;
  234864. case NSMouseMoved:
  234865. case NSMouseEntered:
  234866. case NSMouseExited:
  234867. case NSCursorUpdate:
  234868. case NSScrollWheel:
  234869. case NSTabletPoint:
  234870. case NSTabletProximity:
  234871. break;
  234872. default:
  234873. return false;
  234874. }
  234875. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  234876. {
  234877. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  234878. NSView* const compView = (NSView*) peer->getNativeHandle();
  234879. if ([compView window] == w)
  234880. {
  234881. if (isKey)
  234882. {
  234883. if (compView == [w firstResponder])
  234884. return false;
  234885. }
  234886. else
  234887. {
  234888. NSViewComponentPeer* nsViewPeer = dynamic_cast<NSViewComponentPeer*> (peer);
  234889. if ((nsViewPeer == 0 || ! nsViewPeer->isSharedWindow)
  234890. ? NSPointInRect ([e locationInWindow], NSMakeRect (0, 0, [w frame].size.width, [w frame].size.height))
  234891. : NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil], [compView bounds]))
  234892. return false;
  234893. }
  234894. }
  234895. }
  234896. if (isInputAttempt)
  234897. {
  234898. if (! [NSApp isActive])
  234899. [NSApp activateIgnoringOtherApps: YES];
  234900. Component* const modal = Component::getCurrentlyModalComponent (0);
  234901. if (modal != 0)
  234902. modal->inputAttemptWhenModal();
  234903. }
  234904. return true;
  234905. }
  234906. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  234907. {
  234908. jassert (isThisTheMessageThread()); // must only be called by the message thread
  234909. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  234910. while (! quitMessagePosted)
  234911. {
  234912. const ScopedAutoReleasePool pool;
  234913. CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.001, true);
  234914. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  234915. untilDate: [NSDate dateWithTimeIntervalSinceNow: 0.001]
  234916. inMode: NSDefaultRunLoopMode
  234917. dequeue: YES];
  234918. if (e != 0 && ! isEventBlockedByModalComps (e))
  234919. [NSApp sendEvent: e];
  234920. if (Time::getMillisecondCounter() >= endTime)
  234921. break;
  234922. }
  234923. return ! quitMessagePosted;
  234924. }
  234925. void MessageManager::doPlatformSpecificInitialisation()
  234926. {
  234927. if (juceAppDelegate == 0)
  234928. juceAppDelegate = [[JuceAppDelegate alloc] init];
  234929. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  234930. // correctly (needed prior to 10.5)
  234931. if (! [NSThread isMultiThreaded])
  234932. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  234933. toTarget: juceAppDelegate
  234934. withObject: nil];
  234935. }
  234936. void MessageManager::doPlatformSpecificShutdown()
  234937. {
  234938. if (juceAppDelegate != 0)
  234939. {
  234940. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  234941. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  234942. [juceAppDelegate release];
  234943. juceAppDelegate = 0;
  234944. }
  234945. }
  234946. bool juce_postMessageToSystemQueue (Message* message)
  234947. {
  234948. juceAppDelegate->redirector->postMessage (message);
  234949. return true;
  234950. }
  234951. void MessageManager::broadcastMessage (const String& value)
  234952. {
  234953. }
  234954. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  234955. {
  234956. if (isThisTheMessageThread())
  234957. {
  234958. return (*callback) (data);
  234959. }
  234960. else
  234961. {
  234962. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  234963. // deadlock because the message manager is blocked from running, so can never
  234964. // call your function..
  234965. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  234966. const ScopedAutoReleasePool pool;
  234967. AppDelegateRedirector::CallbackMessagePayload cmp;
  234968. cmp.function = callback;
  234969. cmp.parameter = data;
  234970. cmp.result = 0;
  234971. cmp.hasBeenExecuted = false;
  234972. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  234973. withObject: [NSData dataWithBytesNoCopy: &cmp
  234974. length: sizeof (cmp)
  234975. freeWhenDone: NO]
  234976. waitUntilDone: YES];
  234977. return cmp.result;
  234978. }
  234979. }
  234980. #endif
  234981. /*** End of inlined file: juce_mac_MessageManager.mm ***/
  234982. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  234983. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234984. // compiled on its own).
  234985. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  234986. #if JUCE_MAC
  234987. END_JUCE_NAMESPACE
  234988. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  234989. @interface DownloadClickDetector : NSObject
  234990. {
  234991. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  234992. }
  234993. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  234994. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  234995. request: (NSURLRequest*) request
  234996. frame: (WebFrame*) frame
  234997. decisionListener: (id<WebPolicyDecisionListener>) listener;
  234998. @end
  234999. @implementation DownloadClickDetector
  235000. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  235001. {
  235002. [super init];
  235003. ownerComponent = ownerComponent_;
  235004. return self;
  235005. }
  235006. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  235007. request: (NSURLRequest*) request
  235008. frame: (WebFrame*) frame
  235009. decisionListener: (id <WebPolicyDecisionListener>) listener
  235010. {
  235011. (void) sender;
  235012. (void) request;
  235013. (void) frame;
  235014. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  235015. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  235016. [listener use];
  235017. else
  235018. [listener ignore];
  235019. }
  235020. @end
  235021. BEGIN_JUCE_NAMESPACE
  235022. class WebBrowserComponentInternal : public NSViewComponent
  235023. {
  235024. public:
  235025. WebBrowserComponentInternal (WebBrowserComponent* owner)
  235026. {
  235027. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  235028. frameName: @""
  235029. groupName: @""];
  235030. setView (webView);
  235031. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  235032. [webView setPolicyDelegate: clickListener];
  235033. }
  235034. ~WebBrowserComponentInternal()
  235035. {
  235036. [webView setPolicyDelegate: nil];
  235037. [clickListener release];
  235038. setView (0);
  235039. }
  235040. void goToURL (const String& url,
  235041. const StringArray* headers,
  235042. const MemoryBlock* postData)
  235043. {
  235044. NSMutableURLRequest* r
  235045. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  235046. cachePolicy: NSURLRequestUseProtocolCachePolicy
  235047. timeoutInterval: 30.0];
  235048. if (postData != 0 && postData->getSize() > 0)
  235049. {
  235050. [r setHTTPMethod: @"POST"];
  235051. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  235052. length: postData->getSize()]];
  235053. }
  235054. if (headers != 0)
  235055. {
  235056. for (int i = 0; i < headers->size(); ++i)
  235057. {
  235058. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  235059. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  235060. [r setValue: juceStringToNS (headerValue)
  235061. forHTTPHeaderField: juceStringToNS (headerName)];
  235062. }
  235063. }
  235064. stop();
  235065. [[webView mainFrame] loadRequest: r];
  235066. }
  235067. void goBack()
  235068. {
  235069. [webView goBack];
  235070. }
  235071. void goForward()
  235072. {
  235073. [webView goForward];
  235074. }
  235075. void stop()
  235076. {
  235077. [webView stopLoading: nil];
  235078. }
  235079. void refresh()
  235080. {
  235081. [webView reload: nil];
  235082. }
  235083. private:
  235084. WebView* webView;
  235085. DownloadClickDetector* clickListener;
  235086. };
  235087. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  235088. : browser (0),
  235089. blankPageShown (false),
  235090. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  235091. {
  235092. setOpaque (true);
  235093. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  235094. }
  235095. WebBrowserComponent::~WebBrowserComponent()
  235096. {
  235097. deleteAndZero (browser);
  235098. }
  235099. void WebBrowserComponent::goToURL (const String& url,
  235100. const StringArray* headers,
  235101. const MemoryBlock* postData)
  235102. {
  235103. lastURL = url;
  235104. lastHeaders.clear();
  235105. if (headers != 0)
  235106. lastHeaders = *headers;
  235107. lastPostData.setSize (0);
  235108. if (postData != 0)
  235109. lastPostData = *postData;
  235110. blankPageShown = false;
  235111. browser->goToURL (url, headers, postData);
  235112. }
  235113. void WebBrowserComponent::stop()
  235114. {
  235115. browser->stop();
  235116. }
  235117. void WebBrowserComponent::goBack()
  235118. {
  235119. lastURL = String::empty;
  235120. blankPageShown = false;
  235121. browser->goBack();
  235122. }
  235123. void WebBrowserComponent::goForward()
  235124. {
  235125. lastURL = String::empty;
  235126. browser->goForward();
  235127. }
  235128. void WebBrowserComponent::refresh()
  235129. {
  235130. browser->refresh();
  235131. }
  235132. void WebBrowserComponent::paint (Graphics&)
  235133. {
  235134. }
  235135. void WebBrowserComponent::checkWindowAssociation()
  235136. {
  235137. if (isShowing())
  235138. {
  235139. if (blankPageShown)
  235140. goBack();
  235141. }
  235142. else
  235143. {
  235144. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  235145. {
  235146. // when the component becomes invisible, some stuff like flash
  235147. // carries on playing audio, so we need to force it onto a blank
  235148. // page to avoid this, (and send it back when it's made visible again).
  235149. blankPageShown = true;
  235150. browser->goToURL ("about:blank", 0, 0);
  235151. }
  235152. }
  235153. }
  235154. void WebBrowserComponent::reloadLastURL()
  235155. {
  235156. if (lastURL.isNotEmpty())
  235157. {
  235158. goToURL (lastURL, &lastHeaders, &lastPostData);
  235159. lastURL = String::empty;
  235160. }
  235161. }
  235162. void WebBrowserComponent::parentHierarchyChanged()
  235163. {
  235164. checkWindowAssociation();
  235165. }
  235166. void WebBrowserComponent::resized()
  235167. {
  235168. browser->setSize (getWidth(), getHeight());
  235169. }
  235170. void WebBrowserComponent::visibilityChanged()
  235171. {
  235172. checkWindowAssociation();
  235173. }
  235174. bool WebBrowserComponent::pageAboutToLoad (const String&)
  235175. {
  235176. return true;
  235177. }
  235178. #else
  235179. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  235180. {
  235181. }
  235182. WebBrowserComponent::~WebBrowserComponent()
  235183. {
  235184. }
  235185. void WebBrowserComponent::goToURL (const String& url,
  235186. const StringArray* headers,
  235187. const MemoryBlock* postData)
  235188. {
  235189. }
  235190. void WebBrowserComponent::stop()
  235191. {
  235192. }
  235193. void WebBrowserComponent::goBack()
  235194. {
  235195. }
  235196. void WebBrowserComponent::goForward()
  235197. {
  235198. }
  235199. void WebBrowserComponent::refresh()
  235200. {
  235201. }
  235202. void WebBrowserComponent::paint (Graphics& g)
  235203. {
  235204. }
  235205. void WebBrowserComponent::checkWindowAssociation()
  235206. {
  235207. }
  235208. void WebBrowserComponent::reloadLastURL()
  235209. {
  235210. }
  235211. void WebBrowserComponent::parentHierarchyChanged()
  235212. {
  235213. }
  235214. void WebBrowserComponent::resized()
  235215. {
  235216. }
  235217. void WebBrowserComponent::visibilityChanged()
  235218. {
  235219. }
  235220. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  235221. {
  235222. return true;
  235223. }
  235224. #endif
  235225. #endif
  235226. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  235227. /*** Start of inlined file: juce_mac_CoreAudio.cpp ***/
  235228. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  235229. // compiled on its own).
  235230. #if JUCE_INCLUDED_FILE
  235231. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  235232. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  235233. #endif
  235234. #undef log
  235235. #if JUCE_COREAUDIO_LOGGING_ENABLED
  235236. #define log(a) Logger::writeToLog (a)
  235237. #else
  235238. #define log(a)
  235239. #endif
  235240. #undef OK
  235241. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  235242. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  235243. {
  235244. if (err == noErr)
  235245. return true;
  235246. Logger::writeToLog ("CoreAudio error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  235247. jassertfalse;
  235248. return false;
  235249. }
  235250. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  235251. #else
  235252. #define OK(a) (a == noErr)
  235253. #endif
  235254. class CoreAudioInternal : public Timer
  235255. {
  235256. public:
  235257. CoreAudioInternal (AudioDeviceID id)
  235258. : inputLatency (0),
  235259. outputLatency (0),
  235260. callback (0),
  235261. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  235262. audioProcID (0),
  235263. #endif
  235264. isSlaveDevice (false),
  235265. deviceID (id),
  235266. started (false),
  235267. sampleRate (0),
  235268. bufferSize (512),
  235269. numInputChans (0),
  235270. numOutputChans (0),
  235271. callbacksAllowed (true),
  235272. numInputChannelInfos (0),
  235273. numOutputChannelInfos (0)
  235274. {
  235275. jassert (deviceID != 0);
  235276. updateDetailsFromDevice();
  235277. AudioObjectPropertyAddress pa;
  235278. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235279. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235280. pa.mElement = kAudioObjectPropertyElementWildcard;
  235281. AudioObjectAddPropertyListener (deviceID, &pa, deviceListenerProc, this);
  235282. }
  235283. ~CoreAudioInternal()
  235284. {
  235285. AudioObjectPropertyAddress pa;
  235286. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235287. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235288. pa.mElement = kAudioObjectPropertyElementWildcard;
  235289. AudioObjectRemovePropertyListener (deviceID, &pa, deviceListenerProc, this);
  235290. stop (false);
  235291. }
  235292. void allocateTempBuffers()
  235293. {
  235294. const int tempBufSize = bufferSize + 4;
  235295. audioBuffer.calloc ((numInputChans + numOutputChans) * tempBufSize);
  235296. tempInputBuffers.calloc (numInputChans + 2);
  235297. tempOutputBuffers.calloc (numOutputChans + 2);
  235298. int i, count = 0;
  235299. for (i = 0; i < numInputChans; ++i)
  235300. tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
  235301. for (i = 0; i < numOutputChans; ++i)
  235302. tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
  235303. }
  235304. // returns the number of actual available channels
  235305. void fillInChannelInfo (const bool input)
  235306. {
  235307. int chanNum = 0;
  235308. UInt32 size;
  235309. AudioObjectPropertyAddress pa;
  235310. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  235311. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235312. pa.mElement = kAudioObjectPropertyElementMaster;
  235313. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235314. {
  235315. HeapBlock <AudioBufferList> bufList;
  235316. bufList.calloc (size, 1);
  235317. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  235318. {
  235319. const int numStreams = bufList->mNumberBuffers;
  235320. for (int i = 0; i < numStreams; ++i)
  235321. {
  235322. const AudioBuffer& b = bufList->mBuffers[i];
  235323. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  235324. {
  235325. String name;
  235326. {
  235327. char channelName [256];
  235328. zerostruct (channelName);
  235329. UInt32 nameSize = sizeof (channelName);
  235330. UInt32 channelNum = chanNum + 1;
  235331. pa.mSelector = kAudioDevicePropertyChannelName;
  235332. if (AudioObjectGetPropertyData (deviceID, &pa, sizeof (channelNum), &channelNum, &nameSize, channelName) == noErr)
  235333. name = String::fromUTF8 (channelName, nameSize);
  235334. }
  235335. if (input)
  235336. {
  235337. if (activeInputChans[chanNum])
  235338. {
  235339. inputChannelInfo [numInputChannelInfos].streamNum = i;
  235340. inputChannelInfo [numInputChannelInfos].dataOffsetSamples = j;
  235341. inputChannelInfo [numInputChannelInfos].dataStrideSamples = b.mNumberChannels;
  235342. ++numInputChannelInfos;
  235343. }
  235344. if (name.isEmpty())
  235345. name << "Input " << (chanNum + 1);
  235346. inChanNames.add (name);
  235347. }
  235348. else
  235349. {
  235350. if (activeOutputChans[chanNum])
  235351. {
  235352. outputChannelInfo [numOutputChannelInfos].streamNum = i;
  235353. outputChannelInfo [numOutputChannelInfos].dataOffsetSamples = j;
  235354. outputChannelInfo [numOutputChannelInfos].dataStrideSamples = b.mNumberChannels;
  235355. ++numOutputChannelInfos;
  235356. }
  235357. if (name.isEmpty())
  235358. name << "Output " << (chanNum + 1);
  235359. outChanNames.add (name);
  235360. }
  235361. ++chanNum;
  235362. }
  235363. }
  235364. }
  235365. }
  235366. }
  235367. void updateDetailsFromDevice()
  235368. {
  235369. stopTimer();
  235370. if (deviceID == 0)
  235371. return;
  235372. const ScopedLock sl (callbackLock);
  235373. Float64 sr;
  235374. UInt32 size = sizeof (Float64);
  235375. AudioObjectPropertyAddress pa;
  235376. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  235377. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235378. pa.mElement = kAudioObjectPropertyElementMaster;
  235379. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &sr)))
  235380. sampleRate = sr;
  235381. UInt32 framesPerBuf;
  235382. size = sizeof (framesPerBuf);
  235383. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  235384. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &framesPerBuf)))
  235385. {
  235386. bufferSize = framesPerBuf;
  235387. allocateTempBuffers();
  235388. }
  235389. bufferSizes.clear();
  235390. pa.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  235391. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235392. {
  235393. HeapBlock <AudioValueRange> ranges;
  235394. ranges.calloc (size, 1);
  235395. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  235396. {
  235397. bufferSizes.add ((int) ranges[0].mMinimum);
  235398. for (int i = 32; i < 2048; i += 32)
  235399. {
  235400. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  235401. {
  235402. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  235403. {
  235404. bufferSizes.addIfNotAlreadyThere (i);
  235405. break;
  235406. }
  235407. }
  235408. }
  235409. if (bufferSize > 0)
  235410. bufferSizes.addIfNotAlreadyThere (bufferSize);
  235411. }
  235412. }
  235413. if (bufferSizes.size() == 0 && bufferSize > 0)
  235414. bufferSizes.add (bufferSize);
  235415. sampleRates.clear();
  235416. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  235417. String rates;
  235418. pa.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  235419. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235420. {
  235421. HeapBlock <AudioValueRange> ranges;
  235422. ranges.calloc (size, 1);
  235423. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  235424. {
  235425. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  235426. {
  235427. bool ok = false;
  235428. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  235429. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  235430. ok = true;
  235431. if (ok)
  235432. {
  235433. sampleRates.add (possibleRates[i]);
  235434. rates << possibleRates[i] << ' ';
  235435. }
  235436. }
  235437. }
  235438. }
  235439. if (sampleRates.size() == 0 && sampleRate > 0)
  235440. {
  235441. sampleRates.add (sampleRate);
  235442. rates << sampleRate;
  235443. }
  235444. log ("sr: " + rates);
  235445. inputLatency = 0;
  235446. outputLatency = 0;
  235447. UInt32 lat;
  235448. size = sizeof (lat);
  235449. pa.mSelector = kAudioDevicePropertyLatency;
  235450. pa.mScope = kAudioDevicePropertyScopeInput;
  235451. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  235452. inputLatency = (int) lat;
  235453. pa.mScope = kAudioDevicePropertyScopeOutput;
  235454. size = sizeof (lat);
  235455. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  235456. outputLatency = (int) lat;
  235457. log ("lat: " + String (inputLatency) + " " + String (outputLatency));
  235458. inChanNames.clear();
  235459. outChanNames.clear();
  235460. inputChannelInfo.calloc (numInputChans + 2);
  235461. numInputChannelInfos = 0;
  235462. outputChannelInfo.calloc (numOutputChans + 2);
  235463. numOutputChannelInfos = 0;
  235464. fillInChannelInfo (true);
  235465. fillInChannelInfo (false);
  235466. }
  235467. const StringArray getSources (bool input)
  235468. {
  235469. StringArray s;
  235470. HeapBlock <OSType> types;
  235471. const int num = getAllDataSourcesForDevice (deviceID, types);
  235472. for (int i = 0; i < num; ++i)
  235473. {
  235474. AudioValueTranslation avt;
  235475. char buffer[256];
  235476. avt.mInputData = &(types[i]);
  235477. avt.mInputDataSize = sizeof (UInt32);
  235478. avt.mOutputData = buffer;
  235479. avt.mOutputDataSize = 256;
  235480. UInt32 transSize = sizeof (avt);
  235481. AudioObjectPropertyAddress pa;
  235482. pa.mSelector = kAudioDevicePropertyDataSourceNameForID;
  235483. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235484. pa.mElement = kAudioObjectPropertyElementMaster;
  235485. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &transSize, &avt)))
  235486. {
  235487. DBG (buffer);
  235488. s.add (buffer);
  235489. }
  235490. }
  235491. return s;
  235492. }
  235493. int getCurrentSourceIndex (bool input) const
  235494. {
  235495. OSType currentSourceID = 0;
  235496. UInt32 size = sizeof (currentSourceID);
  235497. int result = -1;
  235498. AudioObjectPropertyAddress pa;
  235499. pa.mSelector = kAudioDevicePropertyDataSource;
  235500. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235501. pa.mElement = kAudioObjectPropertyElementMaster;
  235502. if (deviceID != 0)
  235503. {
  235504. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &currentSourceID)))
  235505. {
  235506. HeapBlock <OSType> types;
  235507. const int num = getAllDataSourcesForDevice (deviceID, types);
  235508. for (int i = 0; i < num; ++i)
  235509. {
  235510. if (types[num] == currentSourceID)
  235511. {
  235512. result = i;
  235513. break;
  235514. }
  235515. }
  235516. }
  235517. }
  235518. return result;
  235519. }
  235520. void setCurrentSourceIndex (int index, bool input)
  235521. {
  235522. if (deviceID != 0)
  235523. {
  235524. HeapBlock <OSType> types;
  235525. const int num = getAllDataSourcesForDevice (deviceID, types);
  235526. if (((unsigned int) index) < (unsigned int) num)
  235527. {
  235528. AudioObjectPropertyAddress pa;
  235529. pa.mSelector = kAudioDevicePropertyDataSource;
  235530. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235531. pa.mElement = kAudioObjectPropertyElementMaster;
  235532. OSType typeId = types[index];
  235533. OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (typeId), &typeId));
  235534. }
  235535. }
  235536. }
  235537. const String reopen (const BigInteger& inputChannels,
  235538. const BigInteger& outputChannels,
  235539. double newSampleRate,
  235540. int bufferSizeSamples)
  235541. {
  235542. String error;
  235543. log ("CoreAudio reopen");
  235544. callbacksAllowed = false;
  235545. stopTimer();
  235546. stop (false);
  235547. activeInputChans = inputChannels;
  235548. activeInputChans.setRange (inChanNames.size(),
  235549. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  235550. false);
  235551. activeOutputChans = outputChannels;
  235552. activeOutputChans.setRange (outChanNames.size(),
  235553. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  235554. false);
  235555. numInputChans = activeInputChans.countNumberOfSetBits();
  235556. numOutputChans = activeOutputChans.countNumberOfSetBits();
  235557. // set sample rate
  235558. AudioObjectPropertyAddress pa;
  235559. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  235560. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235561. pa.mElement = kAudioObjectPropertyElementMaster;
  235562. Float64 sr = newSampleRate;
  235563. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (sr), &sr)))
  235564. {
  235565. error = "Couldn't change sample rate";
  235566. }
  235567. else
  235568. {
  235569. // change buffer size
  235570. UInt32 framesPerBuf = bufferSizeSamples;
  235571. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  235572. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (framesPerBuf), &framesPerBuf)))
  235573. {
  235574. error = "Couldn't change buffer size";
  235575. }
  235576. else
  235577. {
  235578. // Annoyingly, after changing the rate and buffer size, some devices fail to
  235579. // correctly report their new settings until some random time in the future, so
  235580. // after calling updateDetailsFromDevice, we need to manually bodge these values
  235581. // to make sure we're using the correct numbers..
  235582. updateDetailsFromDevice();
  235583. sampleRate = newSampleRate;
  235584. bufferSize = bufferSizeSamples;
  235585. if (sampleRates.size() == 0)
  235586. error = "Device has no available sample-rates";
  235587. else if (bufferSizes.size() == 0)
  235588. error = "Device has no available buffer-sizes";
  235589. else if (inputDevice != 0)
  235590. error = inputDevice->reopen (inputChannels,
  235591. outputChannels,
  235592. newSampleRate,
  235593. bufferSizeSamples);
  235594. }
  235595. }
  235596. callbacksAllowed = true;
  235597. return error;
  235598. }
  235599. bool start (AudioIODeviceCallback* cb)
  235600. {
  235601. if (! started)
  235602. {
  235603. callback = 0;
  235604. if (deviceID != 0)
  235605. {
  235606. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235607. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, this)))
  235608. #else
  235609. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, this, &audioProcID)))
  235610. #endif
  235611. {
  235612. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  235613. {
  235614. started = true;
  235615. }
  235616. else
  235617. {
  235618. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235619. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  235620. #else
  235621. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  235622. audioProcID = 0;
  235623. #endif
  235624. }
  235625. }
  235626. }
  235627. }
  235628. if (started)
  235629. {
  235630. const ScopedLock sl (callbackLock);
  235631. callback = cb;
  235632. }
  235633. if (inputDevice != 0)
  235634. return started && inputDevice->start (cb);
  235635. else
  235636. return started;
  235637. }
  235638. void stop (bool leaveInterruptRunning)
  235639. {
  235640. {
  235641. const ScopedLock sl (callbackLock);
  235642. callback = 0;
  235643. }
  235644. if (started
  235645. && (deviceID != 0)
  235646. && ! leaveInterruptRunning)
  235647. {
  235648. OK (AudioDeviceStop (deviceID, audioIOProc));
  235649. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  235650. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  235651. #else
  235652. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  235653. audioProcID = 0;
  235654. #endif
  235655. started = false;
  235656. { const ScopedLock sl (callbackLock); }
  235657. // wait until it's definately stopped calling back..
  235658. for (int i = 40; --i >= 0;)
  235659. {
  235660. Thread::sleep (50);
  235661. UInt32 running = 0;
  235662. UInt32 size = sizeof (running);
  235663. AudioObjectPropertyAddress pa;
  235664. pa.mSelector = kAudioDevicePropertyDeviceIsRunning;
  235665. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235666. pa.mElement = kAudioObjectPropertyElementMaster;
  235667. OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &running));
  235668. if (running == 0)
  235669. break;
  235670. }
  235671. const ScopedLock sl (callbackLock);
  235672. }
  235673. if (inputDevice != 0)
  235674. inputDevice->stop (leaveInterruptRunning);
  235675. }
  235676. double getSampleRate() const
  235677. {
  235678. return sampleRate;
  235679. }
  235680. int getBufferSize() const
  235681. {
  235682. return bufferSize;
  235683. }
  235684. void audioCallback (const AudioBufferList* inInputData,
  235685. AudioBufferList* outOutputData)
  235686. {
  235687. int i;
  235688. const ScopedLock sl (callbackLock);
  235689. if (callback != 0)
  235690. {
  235691. if (inputDevice == 0)
  235692. {
  235693. for (i = numInputChans; --i >= 0;)
  235694. {
  235695. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  235696. float* dest = tempInputBuffers [i];
  235697. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  235698. + info.dataOffsetSamples;
  235699. const int stride = info.dataStrideSamples;
  235700. if (stride != 0) // if this is zero, info is invalid
  235701. {
  235702. for (int j = bufferSize; --j >= 0;)
  235703. {
  235704. *dest++ = *src;
  235705. src += stride;
  235706. }
  235707. }
  235708. }
  235709. }
  235710. if (! isSlaveDevice)
  235711. {
  235712. if (inputDevice == 0)
  235713. {
  235714. callback->audioDeviceIOCallback (const_cast<const float**> (tempInputBuffers.getData()),
  235715. numInputChans,
  235716. tempOutputBuffers,
  235717. numOutputChans,
  235718. bufferSize);
  235719. }
  235720. else
  235721. {
  235722. jassert (inputDevice->bufferSize == bufferSize);
  235723. // Sometimes the two linked devices seem to get their callbacks in
  235724. // parallel, so we need to lock both devices to stop the input data being
  235725. // changed while inside our callback..
  235726. const ScopedLock sl2 (inputDevice->callbackLock);
  235727. callback->audioDeviceIOCallback (const_cast<const float**> (inputDevice->tempInputBuffers.getData()),
  235728. inputDevice->numInputChans,
  235729. tempOutputBuffers,
  235730. numOutputChans,
  235731. bufferSize);
  235732. }
  235733. for (i = numOutputChans; --i >= 0;)
  235734. {
  235735. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  235736. const float* src = tempOutputBuffers [i];
  235737. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  235738. + info.dataOffsetSamples;
  235739. const int stride = info.dataStrideSamples;
  235740. if (stride != 0) // if this is zero, info is invalid
  235741. {
  235742. for (int j = bufferSize; --j >= 0;)
  235743. {
  235744. *dest = *src++;
  235745. dest += stride;
  235746. }
  235747. }
  235748. }
  235749. }
  235750. }
  235751. else
  235752. {
  235753. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  235754. {
  235755. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  235756. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  235757. + info.dataOffsetSamples;
  235758. const int stride = info.dataStrideSamples;
  235759. if (stride != 0) // if this is zero, info is invalid
  235760. {
  235761. for (int j = bufferSize; --j >= 0;)
  235762. {
  235763. *dest = 0.0f;
  235764. dest += stride;
  235765. }
  235766. }
  235767. }
  235768. }
  235769. }
  235770. // called by callbacks
  235771. void deviceDetailsChanged()
  235772. {
  235773. if (callbacksAllowed)
  235774. startTimer (100);
  235775. }
  235776. void timerCallback()
  235777. {
  235778. stopTimer();
  235779. log ("CoreAudio device changed callback");
  235780. const double oldSampleRate = sampleRate;
  235781. const int oldBufferSize = bufferSize;
  235782. updateDetailsFromDevice();
  235783. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  235784. {
  235785. callbacksAllowed = false;
  235786. stop (false);
  235787. updateDetailsFromDevice();
  235788. callbacksAllowed = true;
  235789. }
  235790. }
  235791. CoreAudioInternal* getRelatedDevice() const
  235792. {
  235793. UInt32 size = 0;
  235794. ScopedPointer <CoreAudioInternal> result;
  235795. AudioObjectPropertyAddress pa;
  235796. pa.mSelector = kAudioDevicePropertyRelatedDevices;
  235797. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235798. pa.mElement = kAudioObjectPropertyElementMaster;
  235799. if (deviceID != 0
  235800. && AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size) == noErr
  235801. && size > 0)
  235802. {
  235803. HeapBlock <AudioDeviceID> devs;
  235804. devs.calloc (size, 1);
  235805. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, devs)))
  235806. {
  235807. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  235808. {
  235809. if (devs[i] != deviceID && devs[i] != 0)
  235810. {
  235811. result = new CoreAudioInternal (devs[i]);
  235812. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  235813. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  235814. if (thisIsInput != otherIsInput
  235815. || (inChanNames.size() + outChanNames.size() == 0)
  235816. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  235817. break;
  235818. result = 0;
  235819. }
  235820. }
  235821. }
  235822. }
  235823. return result.release();
  235824. }
  235825. juce_UseDebuggingNewOperator
  235826. int inputLatency, outputLatency;
  235827. BigInteger activeInputChans, activeOutputChans;
  235828. StringArray inChanNames, outChanNames;
  235829. Array <double> sampleRates;
  235830. Array <int> bufferSizes;
  235831. AudioIODeviceCallback* callback;
  235832. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  235833. AudioDeviceIOProcID audioProcID;
  235834. #endif
  235835. ScopedPointer<CoreAudioInternal> inputDevice;
  235836. bool isSlaveDevice;
  235837. private:
  235838. CriticalSection callbackLock;
  235839. AudioDeviceID deviceID;
  235840. bool started;
  235841. double sampleRate;
  235842. int bufferSize;
  235843. HeapBlock <float> audioBuffer;
  235844. int numInputChans, numOutputChans;
  235845. bool callbacksAllowed;
  235846. struct CallbackDetailsForChannel
  235847. {
  235848. int streamNum;
  235849. int dataOffsetSamples;
  235850. int dataStrideSamples;
  235851. };
  235852. int numInputChannelInfos, numOutputChannelInfos;
  235853. HeapBlock <CallbackDetailsForChannel> inputChannelInfo, outputChannelInfo;
  235854. HeapBlock <float*> tempInputBuffers, tempOutputBuffers;
  235855. CoreAudioInternal (const CoreAudioInternal&);
  235856. CoreAudioInternal& operator= (const CoreAudioInternal&);
  235857. static OSStatus audioIOProc (AudioDeviceID /*inDevice*/,
  235858. const AudioTimeStamp* /*inNow*/,
  235859. const AudioBufferList* inInputData,
  235860. const AudioTimeStamp* /*inInputTime*/,
  235861. AudioBufferList* outOutputData,
  235862. const AudioTimeStamp* /*inOutputTime*/,
  235863. void* device)
  235864. {
  235865. static_cast <CoreAudioInternal*> (device)->audioCallback (inInputData, outOutputData);
  235866. return noErr;
  235867. }
  235868. static OSStatus deviceListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  235869. {
  235870. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  235871. switch (pa->mSelector)
  235872. {
  235873. case kAudioDevicePropertyBufferSize:
  235874. case kAudioDevicePropertyBufferFrameSize:
  235875. case kAudioDevicePropertyNominalSampleRate:
  235876. case kAudioDevicePropertyStreamFormat:
  235877. case kAudioDevicePropertyDeviceIsAlive:
  235878. intern->deviceDetailsChanged();
  235879. break;
  235880. case kAudioDevicePropertyBufferSizeRange:
  235881. case kAudioDevicePropertyVolumeScalar:
  235882. case kAudioDevicePropertyMute:
  235883. case kAudioDevicePropertyPlayThru:
  235884. case kAudioDevicePropertyDataSource:
  235885. case kAudioDevicePropertyDeviceIsRunning:
  235886. break;
  235887. }
  235888. return noErr;
  235889. }
  235890. static int getAllDataSourcesForDevice (AudioDeviceID deviceID, HeapBlock <OSType>& types)
  235891. {
  235892. AudioObjectPropertyAddress pa;
  235893. pa.mSelector = kAudioDevicePropertyDataSources;
  235894. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235895. pa.mElement = kAudioObjectPropertyElementMaster;
  235896. UInt32 size = 0;
  235897. if (deviceID != 0
  235898. && OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235899. {
  235900. types.calloc (size, 1);
  235901. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, types)))
  235902. return size / (int) sizeof (OSType);
  235903. }
  235904. return 0;
  235905. }
  235906. };
  235907. class CoreAudioIODevice : public AudioIODevice
  235908. {
  235909. public:
  235910. CoreAudioIODevice (const String& deviceName,
  235911. AudioDeviceID inputDeviceId,
  235912. const int inputIndex_,
  235913. AudioDeviceID outputDeviceId,
  235914. const int outputIndex_)
  235915. : AudioIODevice (deviceName, "CoreAudio"),
  235916. inputIndex (inputIndex_),
  235917. outputIndex (outputIndex_),
  235918. isOpen_ (false),
  235919. isStarted (false)
  235920. {
  235921. CoreAudioInternal* device = 0;
  235922. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  235923. {
  235924. jassert (inputDeviceId != 0);
  235925. device = new CoreAudioInternal (inputDeviceId);
  235926. }
  235927. else
  235928. {
  235929. device = new CoreAudioInternal (outputDeviceId);
  235930. if (inputDeviceId != 0)
  235931. {
  235932. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  235933. device->inputDevice = secondDevice;
  235934. secondDevice->isSlaveDevice = true;
  235935. }
  235936. }
  235937. internal = device;
  235938. AudioObjectPropertyAddress pa;
  235939. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235940. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235941. pa.mElement = kAudioObjectPropertyElementWildcard;
  235942. AudioObjectAddPropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  235943. }
  235944. ~CoreAudioIODevice()
  235945. {
  235946. AudioObjectPropertyAddress pa;
  235947. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235948. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235949. pa.mElement = kAudioObjectPropertyElementWildcard;
  235950. AudioObjectRemovePropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  235951. }
  235952. const StringArray getOutputChannelNames()
  235953. {
  235954. return internal->outChanNames;
  235955. }
  235956. const StringArray getInputChannelNames()
  235957. {
  235958. if (internal->inputDevice != 0)
  235959. return internal->inputDevice->inChanNames;
  235960. else
  235961. return internal->inChanNames;
  235962. }
  235963. int getNumSampleRates()
  235964. {
  235965. return internal->sampleRates.size();
  235966. }
  235967. double getSampleRate (int index)
  235968. {
  235969. return internal->sampleRates [index];
  235970. }
  235971. int getNumBufferSizesAvailable()
  235972. {
  235973. return internal->bufferSizes.size();
  235974. }
  235975. int getBufferSizeSamples (int index)
  235976. {
  235977. return internal->bufferSizes [index];
  235978. }
  235979. int getDefaultBufferSize()
  235980. {
  235981. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  235982. if (getBufferSizeSamples(i) >= 512)
  235983. return getBufferSizeSamples(i);
  235984. return 512;
  235985. }
  235986. const String open (const BigInteger& inputChannels,
  235987. const BigInteger& outputChannels,
  235988. double sampleRate,
  235989. int bufferSizeSamples)
  235990. {
  235991. isOpen_ = true;
  235992. if (bufferSizeSamples <= 0)
  235993. bufferSizeSamples = getDefaultBufferSize();
  235994. lastError = internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  235995. isOpen_ = lastError.isEmpty();
  235996. return lastError;
  235997. }
  235998. void close()
  235999. {
  236000. isOpen_ = false;
  236001. internal->stop (false);
  236002. }
  236003. bool isOpen()
  236004. {
  236005. return isOpen_;
  236006. }
  236007. int getCurrentBufferSizeSamples()
  236008. {
  236009. return internal != 0 ? internal->getBufferSize() : 512;
  236010. }
  236011. double getCurrentSampleRate()
  236012. {
  236013. return internal != 0 ? internal->getSampleRate() : 0;
  236014. }
  236015. int getCurrentBitDepth()
  236016. {
  236017. return 32; // no way to find out, so just assume it's high..
  236018. }
  236019. const BigInteger getActiveOutputChannels() const
  236020. {
  236021. return internal != 0 ? internal->activeOutputChans : BigInteger();
  236022. }
  236023. const BigInteger getActiveInputChannels() const
  236024. {
  236025. BigInteger chans;
  236026. if (internal != 0)
  236027. {
  236028. chans = internal->activeInputChans;
  236029. if (internal->inputDevice != 0)
  236030. chans |= internal->inputDevice->activeInputChans;
  236031. }
  236032. return chans;
  236033. }
  236034. int getOutputLatencyInSamples()
  236035. {
  236036. if (internal == 0)
  236037. return 0;
  236038. // this seems like a good guess at getting the latency right - comparing
  236039. // this with a round-trip measurement, it gets it to within a few millisecs
  236040. // for the built-in mac soundcard
  236041. return internal->outputLatency + internal->getBufferSize() * 2;
  236042. }
  236043. int getInputLatencyInSamples()
  236044. {
  236045. if (internal == 0)
  236046. return 0;
  236047. return internal->inputLatency + internal->getBufferSize() * 2;
  236048. }
  236049. void start (AudioIODeviceCallback* callback)
  236050. {
  236051. if (internal != 0 && ! isStarted)
  236052. {
  236053. if (callback != 0)
  236054. callback->audioDeviceAboutToStart (this);
  236055. isStarted = true;
  236056. internal->start (callback);
  236057. }
  236058. }
  236059. void stop()
  236060. {
  236061. if (isStarted && internal != 0)
  236062. {
  236063. AudioIODeviceCallback* const lastCallback = internal->callback;
  236064. isStarted = false;
  236065. internal->stop (true);
  236066. if (lastCallback != 0)
  236067. lastCallback->audioDeviceStopped();
  236068. }
  236069. }
  236070. bool isPlaying()
  236071. {
  236072. if (internal->callback == 0)
  236073. isStarted = false;
  236074. return isStarted;
  236075. }
  236076. const String getLastError()
  236077. {
  236078. return lastError;
  236079. }
  236080. int inputIndex, outputIndex;
  236081. juce_UseDebuggingNewOperator
  236082. private:
  236083. ScopedPointer<CoreAudioInternal> internal;
  236084. bool isOpen_, isStarted;
  236085. String lastError;
  236086. static OSStatus hardwareListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  236087. {
  236088. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  236089. switch (pa->mSelector)
  236090. {
  236091. case kAudioHardwarePropertyDevices:
  236092. intern->deviceDetailsChanged();
  236093. break;
  236094. case kAudioHardwarePropertyDefaultOutputDevice:
  236095. case kAudioHardwarePropertyDefaultInputDevice:
  236096. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  236097. break;
  236098. }
  236099. return noErr;
  236100. }
  236101. CoreAudioIODevice (const CoreAudioIODevice&);
  236102. CoreAudioIODevice& operator= (const CoreAudioIODevice&);
  236103. };
  236104. class CoreAudioIODeviceType : public AudioIODeviceType
  236105. {
  236106. public:
  236107. CoreAudioIODeviceType()
  236108. : AudioIODeviceType ("CoreAudio"),
  236109. hasScanned (false)
  236110. {
  236111. }
  236112. ~CoreAudioIODeviceType()
  236113. {
  236114. }
  236115. void scanForDevices()
  236116. {
  236117. hasScanned = true;
  236118. inputDeviceNames.clear();
  236119. outputDeviceNames.clear();
  236120. inputIds.clear();
  236121. outputIds.clear();
  236122. UInt32 size;
  236123. AudioObjectPropertyAddress pa;
  236124. pa.mSelector = kAudioHardwarePropertyDevices;
  236125. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236126. pa.mElement = kAudioObjectPropertyElementMaster;
  236127. if (OK (AudioObjectGetPropertyDataSize (kAudioObjectSystemObject, &pa, 0, 0, &size)))
  236128. {
  236129. HeapBlock <AudioDeviceID> devs;
  236130. devs.calloc (size, 1);
  236131. if (OK (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, devs)))
  236132. {
  236133. const int num = size / (int) sizeof (AudioDeviceID);
  236134. for (int i = 0; i < num; ++i)
  236135. {
  236136. char name [1024];
  236137. size = sizeof (name);
  236138. pa.mSelector = kAudioDevicePropertyDeviceName;
  236139. if (OK (AudioObjectGetPropertyData (devs[i], &pa, 0, 0, &size, name)))
  236140. {
  236141. const String nameString (String::fromUTF8 (name, (int) strlen (name)));
  236142. const int numIns = getNumChannels (devs[i], true);
  236143. const int numOuts = getNumChannels (devs[i], false);
  236144. if (numIns > 0)
  236145. {
  236146. inputDeviceNames.add (nameString);
  236147. inputIds.add (devs[i]);
  236148. }
  236149. if (numOuts > 0)
  236150. {
  236151. outputDeviceNames.add (nameString);
  236152. outputIds.add (devs[i]);
  236153. }
  236154. }
  236155. }
  236156. }
  236157. }
  236158. inputDeviceNames.appendNumbersToDuplicates (false, true);
  236159. outputDeviceNames.appendNumbersToDuplicates (false, true);
  236160. }
  236161. const StringArray getDeviceNames (bool wantInputNames) const
  236162. {
  236163. jassert (hasScanned); // need to call scanForDevices() before doing this
  236164. if (wantInputNames)
  236165. return inputDeviceNames;
  236166. else
  236167. return outputDeviceNames;
  236168. }
  236169. int getDefaultDeviceIndex (bool forInput) const
  236170. {
  236171. jassert (hasScanned); // need to call scanForDevices() before doing this
  236172. AudioDeviceID deviceID;
  236173. UInt32 size = sizeof (deviceID);
  236174. // if they're asking for any input channels at all, use the default input, so we
  236175. // get the built-in mic rather than the built-in output with no inputs..
  236176. AudioObjectPropertyAddress pa;
  236177. pa.mSelector = forInput ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice;
  236178. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236179. pa.mElement = kAudioObjectPropertyElementMaster;
  236180. if (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, &deviceID) == noErr)
  236181. {
  236182. if (forInput)
  236183. {
  236184. for (int i = inputIds.size(); --i >= 0;)
  236185. if (inputIds[i] == deviceID)
  236186. return i;
  236187. }
  236188. else
  236189. {
  236190. for (int i = outputIds.size(); --i >= 0;)
  236191. if (outputIds[i] == deviceID)
  236192. return i;
  236193. }
  236194. }
  236195. return 0;
  236196. }
  236197. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  236198. {
  236199. jassert (hasScanned); // need to call scanForDevices() before doing this
  236200. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  236201. if (d == 0)
  236202. return -1;
  236203. return asInput ? d->inputIndex
  236204. : d->outputIndex;
  236205. }
  236206. bool hasSeparateInputsAndOutputs() const { return true; }
  236207. AudioIODevice* createDevice (const String& outputDeviceName,
  236208. const String& inputDeviceName)
  236209. {
  236210. jassert (hasScanned); // need to call scanForDevices() before doing this
  236211. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  236212. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  236213. String deviceName (outputDeviceName);
  236214. if (deviceName.isEmpty())
  236215. deviceName = inputDeviceName;
  236216. if (index >= 0)
  236217. return new CoreAudioIODevice (deviceName,
  236218. inputIds [inputIndex],
  236219. inputIndex,
  236220. outputIds [outputIndex],
  236221. outputIndex);
  236222. return 0;
  236223. }
  236224. juce_UseDebuggingNewOperator
  236225. private:
  236226. StringArray inputDeviceNames, outputDeviceNames;
  236227. Array <AudioDeviceID> inputIds, outputIds;
  236228. bool hasScanned;
  236229. static int getNumChannels (AudioDeviceID deviceID, bool input)
  236230. {
  236231. int total = 0;
  236232. UInt32 size;
  236233. AudioObjectPropertyAddress pa;
  236234. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  236235. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  236236. pa.mElement = kAudioObjectPropertyElementMaster;
  236237. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  236238. {
  236239. HeapBlock <AudioBufferList> bufList;
  236240. bufList.calloc (size, 1);
  236241. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  236242. {
  236243. const int numStreams = bufList->mNumberBuffers;
  236244. for (int i = 0; i < numStreams; ++i)
  236245. {
  236246. const AudioBuffer& b = bufList->mBuffers[i];
  236247. total += b.mNumberChannels;
  236248. }
  236249. }
  236250. }
  236251. return total;
  236252. }
  236253. CoreAudioIODeviceType (const CoreAudioIODeviceType&);
  236254. CoreAudioIODeviceType& operator= (const CoreAudioIODeviceType&);
  236255. };
  236256. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio()
  236257. {
  236258. return new CoreAudioIODeviceType();
  236259. }
  236260. #undef log
  236261. #endif
  236262. /*** End of inlined file: juce_mac_CoreAudio.cpp ***/
  236263. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  236264. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  236265. // compiled on its own).
  236266. #if JUCE_INCLUDED_FILE
  236267. #if JUCE_MAC
  236268. namespace CoreMidiHelpers
  236269. {
  236270. static bool logError (const OSStatus err, const int lineNum)
  236271. {
  236272. if (err == noErr)
  236273. return true;
  236274. Logger::writeToLog ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  236275. jassertfalse;
  236276. return false;
  236277. }
  236278. #undef CHECK_ERROR
  236279. #define CHECK_ERROR(a) CoreMidiHelpers::logError (a, __LINE__)
  236280. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  236281. {
  236282. String result;
  236283. CFStringRef str = 0;
  236284. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  236285. if (str != 0)
  236286. {
  236287. result = PlatformUtilities::cfStringToJuceString (str);
  236288. CFRelease (str);
  236289. str = 0;
  236290. }
  236291. MIDIEntityRef entity = 0;
  236292. MIDIEndpointGetEntity (endpoint, &entity);
  236293. if (entity == 0)
  236294. return result; // probably virtual
  236295. if (result.isEmpty())
  236296. {
  236297. // endpoint name has zero length - try the entity
  236298. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  236299. if (str != 0)
  236300. {
  236301. result += PlatformUtilities::cfStringToJuceString (str);
  236302. CFRelease (str);
  236303. str = 0;
  236304. }
  236305. }
  236306. // now consider the device's name
  236307. MIDIDeviceRef device = 0;
  236308. MIDIEntityGetDevice (entity, &device);
  236309. if (device == 0)
  236310. return result;
  236311. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  236312. if (str != 0)
  236313. {
  236314. const String s (PlatformUtilities::cfStringToJuceString (str));
  236315. CFRelease (str);
  236316. // if an external device has only one entity, throw away
  236317. // the endpoint name and just use the device name
  236318. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  236319. {
  236320. result = s;
  236321. }
  236322. else if (! result.startsWithIgnoreCase (s))
  236323. {
  236324. // prepend the device name to the entity name
  236325. result = (s + " " + result).trimEnd();
  236326. }
  236327. }
  236328. return result;
  236329. }
  236330. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  236331. {
  236332. String result;
  236333. // Does the endpoint have connections?
  236334. CFDataRef connections = 0;
  236335. int numConnections = 0;
  236336. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  236337. if (connections != 0)
  236338. {
  236339. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  236340. if (numConnections > 0)
  236341. {
  236342. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  236343. for (int i = 0; i < numConnections; ++i, ++pid)
  236344. {
  236345. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  236346. MIDIObjectRef connObject;
  236347. MIDIObjectType connObjectType;
  236348. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  236349. if (err == noErr)
  236350. {
  236351. String s;
  236352. if (connObjectType == kMIDIObjectType_ExternalSource
  236353. || connObjectType == kMIDIObjectType_ExternalDestination)
  236354. {
  236355. // Connected to an external device's endpoint (10.3 and later).
  236356. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  236357. }
  236358. else
  236359. {
  236360. // Connected to an external device (10.2) (or something else, catch-all)
  236361. CFStringRef str = 0;
  236362. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  236363. if (str != 0)
  236364. {
  236365. s = PlatformUtilities::cfStringToJuceString (str);
  236366. CFRelease (str);
  236367. }
  236368. }
  236369. if (s.isNotEmpty())
  236370. {
  236371. if (result.isNotEmpty())
  236372. result += ", ";
  236373. result += s;
  236374. }
  236375. }
  236376. }
  236377. }
  236378. CFRelease (connections);
  236379. }
  236380. if (result.isNotEmpty())
  236381. return result;
  236382. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  236383. return getEndpointName (endpoint, false);
  236384. }
  236385. static MIDIClientRef getGlobalMidiClient()
  236386. {
  236387. static MIDIClientRef globalMidiClient = 0;
  236388. if (globalMidiClient == 0)
  236389. {
  236390. String name ("JUCE");
  236391. if (JUCEApplication::getInstance() != 0)
  236392. name = JUCEApplication::getInstance()->getApplicationName();
  236393. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  236394. CHECK_ERROR (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  236395. CFRelease (appName);
  236396. }
  236397. return globalMidiClient;
  236398. }
  236399. class MidiPortAndEndpoint
  236400. {
  236401. public:
  236402. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  236403. : port (port_), endPoint (endPoint_)
  236404. {
  236405. }
  236406. ~MidiPortAndEndpoint()
  236407. {
  236408. if (port != 0)
  236409. MIDIPortDispose (port);
  236410. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  236411. MIDIEndpointDispose (endPoint);
  236412. }
  236413. void send (const MIDIPacketList* const packets)
  236414. {
  236415. if (port != 0)
  236416. MIDISend (port, endPoint, packets);
  236417. else
  236418. MIDIReceived (endPoint, packets);
  236419. }
  236420. MIDIPortRef port;
  236421. MIDIEndpointRef endPoint;
  236422. };
  236423. class MidiPortAndCallback;
  236424. static CriticalSection callbackLock;
  236425. static Array<MidiPortAndCallback*> activeCallbacks;
  236426. class MidiPortAndCallback
  236427. {
  236428. public:
  236429. MidiPortAndCallback (MidiInputCallback& callback_)
  236430. : input (0), active (false), callback (callback_), concatenator (2048)
  236431. {
  236432. }
  236433. ~MidiPortAndCallback()
  236434. {
  236435. active = false;
  236436. {
  236437. const ScopedLock sl (callbackLock);
  236438. activeCallbacks.removeValue (this);
  236439. }
  236440. if (portAndEndpoint != 0 && portAndEndpoint->port != 0)
  236441. CHECK_ERROR (MIDIPortDisconnectSource (portAndEndpoint->port, portAndEndpoint->endPoint));
  236442. }
  236443. void handlePackets (const MIDIPacketList* const pktlist)
  236444. {
  236445. const double time = Time::getMillisecondCounterHiRes() * 0.001;
  236446. const ScopedLock sl (callbackLock);
  236447. if (activeCallbacks.contains (this) && active)
  236448. {
  236449. const MIDIPacket* packet = &pktlist->packet[0];
  236450. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  236451. {
  236452. concatenator.pushMidiData (packet->data, (int) packet->length, time,
  236453. input, callback);
  236454. packet = MIDIPacketNext (packet);
  236455. }
  236456. }
  236457. }
  236458. MidiInput* input;
  236459. ScopedPointer<MidiPortAndEndpoint> portAndEndpoint;
  236460. volatile bool active;
  236461. private:
  236462. MidiInputCallback& callback;
  236463. MidiDataConcatenator concatenator;
  236464. };
  236465. static void midiInputProc (const MIDIPacketList* pktlist, void* readProcRefCon, void* /*srcConnRefCon*/)
  236466. {
  236467. static_cast <MidiPortAndCallback*> (readProcRefCon)->handlePackets (pktlist);
  236468. }
  236469. }
  236470. const StringArray MidiOutput::getDevices()
  236471. {
  236472. StringArray s;
  236473. const ItemCount num = MIDIGetNumberOfDestinations();
  236474. for (ItemCount i = 0; i < num; ++i)
  236475. {
  236476. MIDIEndpointRef dest = MIDIGetDestination (i);
  236477. if (dest != 0)
  236478. {
  236479. String name (CoreMidiHelpers::getConnectedEndpointName (dest));
  236480. if (name.isEmpty())
  236481. name = "<error>";
  236482. s.add (name);
  236483. }
  236484. else
  236485. {
  236486. s.add ("<error>");
  236487. }
  236488. }
  236489. return s;
  236490. }
  236491. int MidiOutput::getDefaultDeviceIndex()
  236492. {
  236493. return 0;
  236494. }
  236495. MidiOutput* MidiOutput::openDevice (int index)
  236496. {
  236497. MidiOutput* mo = 0;
  236498. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  236499. {
  236500. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  236501. CFStringRef pname;
  236502. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  236503. {
  236504. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  236505. MIDIPortRef port;
  236506. if (client != 0 && CHECK_ERROR (MIDIOutputPortCreate (client, pname, &port)))
  236507. {
  236508. mo = new MidiOutput();
  236509. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (port, endPoint);
  236510. }
  236511. CFRelease (pname);
  236512. }
  236513. }
  236514. return mo;
  236515. }
  236516. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  236517. {
  236518. MidiOutput* mo = 0;
  236519. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  236520. MIDIEndpointRef endPoint;
  236521. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  236522. if (client != 0 && CHECK_ERROR (MIDISourceCreate (client, name, &endPoint)))
  236523. {
  236524. mo = new MidiOutput();
  236525. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (0, endPoint);
  236526. }
  236527. CFRelease (name);
  236528. return mo;
  236529. }
  236530. MidiOutput::~MidiOutput()
  236531. {
  236532. delete static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  236533. }
  236534. void MidiOutput::reset()
  236535. {
  236536. }
  236537. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  236538. {
  236539. return false;
  236540. }
  236541. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  236542. {
  236543. }
  236544. void MidiOutput::sendMessageNow (const MidiMessage& message)
  236545. {
  236546. CoreMidiHelpers::MidiPortAndEndpoint* const mpe = static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  236547. if (message.isSysEx())
  236548. {
  236549. const int maxPacketSize = 256;
  236550. int pos = 0, bytesLeft = message.getRawDataSize();
  236551. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  236552. HeapBlock <MIDIPacketList> packets;
  236553. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  236554. packets->numPackets = numPackets;
  236555. MIDIPacket* p = packets->packet;
  236556. for (int i = 0; i < numPackets; ++i)
  236557. {
  236558. p->timeStamp = 0;
  236559. p->length = jmin (maxPacketSize, bytesLeft);
  236560. memcpy (p->data, message.getRawData() + pos, p->length);
  236561. pos += p->length;
  236562. bytesLeft -= p->length;
  236563. p = MIDIPacketNext (p);
  236564. }
  236565. mpe->send (packets);
  236566. }
  236567. else
  236568. {
  236569. MIDIPacketList packets;
  236570. packets.numPackets = 1;
  236571. packets.packet[0].timeStamp = 0;
  236572. packets.packet[0].length = message.getRawDataSize();
  236573. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  236574. mpe->send (&packets);
  236575. }
  236576. }
  236577. const StringArray MidiInput::getDevices()
  236578. {
  236579. StringArray s;
  236580. const ItemCount num = MIDIGetNumberOfSources();
  236581. for (ItemCount i = 0; i < num; ++i)
  236582. {
  236583. MIDIEndpointRef source = MIDIGetSource (i);
  236584. if (source != 0)
  236585. {
  236586. String name (CoreMidiHelpers::getConnectedEndpointName (source));
  236587. if (name.isEmpty())
  236588. name = "<error>";
  236589. s.add (name);
  236590. }
  236591. else
  236592. {
  236593. s.add ("<error>");
  236594. }
  236595. }
  236596. return s;
  236597. }
  236598. int MidiInput::getDefaultDeviceIndex()
  236599. {
  236600. return 0;
  236601. }
  236602. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  236603. {
  236604. jassert (callback != 0);
  236605. using namespace CoreMidiHelpers;
  236606. MidiInput* newInput = 0;
  236607. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  236608. {
  236609. MIDIEndpointRef endPoint = MIDIGetSource (index);
  236610. if (endPoint != 0)
  236611. {
  236612. CFStringRef name;
  236613. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &name)))
  236614. {
  236615. MIDIClientRef client = getGlobalMidiClient();
  236616. if (client != 0)
  236617. {
  236618. MIDIPortRef port;
  236619. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  236620. if (CHECK_ERROR (MIDIInputPortCreate (client, name, midiInputProc, mpc, &port)))
  236621. {
  236622. if (CHECK_ERROR (MIDIPortConnectSource (port, endPoint, 0)))
  236623. {
  236624. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  236625. newInput = new MidiInput (getDevices() [index]);
  236626. mpc->input = newInput;
  236627. newInput->internal = mpc;
  236628. const ScopedLock sl (callbackLock);
  236629. activeCallbacks.add (mpc.release());
  236630. }
  236631. else
  236632. {
  236633. CHECK_ERROR (MIDIPortDispose (port));
  236634. }
  236635. }
  236636. }
  236637. }
  236638. CFRelease (name);
  236639. }
  236640. }
  236641. return newInput;
  236642. }
  236643. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  236644. {
  236645. jassert (callback != 0);
  236646. using namespace CoreMidiHelpers;
  236647. MidiInput* mi = 0;
  236648. MIDIClientRef client = getGlobalMidiClient();
  236649. if (client != 0)
  236650. {
  236651. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  236652. mpc->active = false;
  236653. MIDIEndpointRef endPoint;
  236654. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  236655. if (CHECK_ERROR (MIDIDestinationCreate (client, name, midiInputProc, mpc, &endPoint)))
  236656. {
  236657. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  236658. mi = new MidiInput (deviceName);
  236659. mpc->input = mi;
  236660. mi->internal = mpc;
  236661. const ScopedLock sl (callbackLock);
  236662. activeCallbacks.add (mpc.release());
  236663. }
  236664. CFRelease (name);
  236665. }
  236666. return mi;
  236667. }
  236668. MidiInput::MidiInput (const String& name_)
  236669. : name (name_)
  236670. {
  236671. }
  236672. MidiInput::~MidiInput()
  236673. {
  236674. delete static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal);
  236675. }
  236676. void MidiInput::start()
  236677. {
  236678. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  236679. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = true;
  236680. }
  236681. void MidiInput::stop()
  236682. {
  236683. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  236684. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = false;
  236685. }
  236686. #undef CHECK_ERROR
  236687. #else // Stubs for iOS...
  236688. MidiOutput::~MidiOutput() {}
  236689. void MidiOutput::reset() {}
  236690. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/) { return false; }
  236691. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/) {}
  236692. void MidiOutput::sendMessageNow (const MidiMessage& message) {}
  236693. const StringArray MidiOutput::getDevices() { return StringArray(); }
  236694. MidiOutput* MidiOutput::openDevice (int index) { return 0; }
  236695. const StringArray MidiInput::getDevices() { return StringArray(); }
  236696. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback) { return 0; }
  236697. #endif
  236698. #endif
  236699. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  236700. /*** Start of inlined file: juce_mac_CameraDevice.mm ***/
  236701. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  236702. // compiled on its own).
  236703. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  236704. #if ! JUCE_QUICKTIME
  236705. #error "On the Mac, cameras use Quicktime, so if you turn on JUCE_USE_CAMERA, you also need to enable JUCE_QUICKTIME"
  236706. #endif
  236707. #define QTCaptureCallbackDelegate MakeObjCClassName(QTCaptureCallbackDelegate)
  236708. class QTCameraDeviceInteral;
  236709. END_JUCE_NAMESPACE
  236710. @interface QTCaptureCallbackDelegate : NSObject
  236711. {
  236712. @public
  236713. CameraDevice* owner;
  236714. QTCameraDeviceInteral* internal;
  236715. int64 firstPresentationTime;
  236716. int64 averageTimeOffset;
  236717. }
  236718. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner internalDev: (QTCameraDeviceInteral*) d;
  236719. - (void) dealloc;
  236720. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  236721. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  236722. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236723. fromConnection: (QTCaptureConnection*) connection;
  236724. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  236725. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236726. fromConnection: (QTCaptureConnection*) connection;
  236727. @end
  236728. BEGIN_JUCE_NAMESPACE
  236729. class QTCameraDeviceInteral
  236730. {
  236731. public:
  236732. QTCameraDeviceInteral (CameraDevice* owner, int index)
  236733. {
  236734. const ScopedAutoReleasePool pool;
  236735. session = [[QTCaptureSession alloc] init];
  236736. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  236737. device = (QTCaptureDevice*) [devs objectAtIndex: index];
  236738. input = 0;
  236739. audioInput = 0;
  236740. audioDevice = 0;
  236741. fileOutput = 0;
  236742. imageOutput = 0;
  236743. callbackDelegate = [[QTCaptureCallbackDelegate alloc] initWithOwner: owner
  236744. internalDev: this];
  236745. NSError* err = 0;
  236746. [device retain];
  236747. [device open: &err];
  236748. if (err == 0)
  236749. {
  236750. input = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  236751. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  236752. [session addInput: input error: &err];
  236753. if (err == 0)
  236754. {
  236755. resetFile();
  236756. imageOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
  236757. [imageOutput setDelegate: callbackDelegate];
  236758. if (err == 0)
  236759. {
  236760. [session startRunning];
  236761. return;
  236762. }
  236763. }
  236764. }
  236765. openingError = nsStringToJuce ([err description]);
  236766. DBG (openingError);
  236767. }
  236768. ~QTCameraDeviceInteral()
  236769. {
  236770. [session stopRunning];
  236771. [session removeOutput: imageOutput];
  236772. [session release];
  236773. [input release];
  236774. [device release];
  236775. [audioDevice release];
  236776. [audioInput release];
  236777. [fileOutput release];
  236778. [imageOutput release];
  236779. [callbackDelegate release];
  236780. }
  236781. void resetFile()
  236782. {
  236783. [fileOutput recordToOutputFileURL: nil];
  236784. [session removeOutput: fileOutput];
  236785. [fileOutput release];
  236786. fileOutput = [[QTCaptureMovieFileOutput alloc] init];
  236787. [session removeInput: audioInput];
  236788. [audioInput release];
  236789. audioInput = 0;
  236790. [audioDevice release];
  236791. audioDevice = 0;
  236792. [fileOutput setDelegate: callbackDelegate];
  236793. }
  236794. void addDefaultAudioInput()
  236795. {
  236796. NSError* err = nil;
  236797. audioDevice = [QTCaptureDevice defaultInputDeviceWithMediaType: QTMediaTypeSound];
  236798. if ([audioDevice open: &err])
  236799. [audioDevice retain];
  236800. else
  236801. audioDevice = nil;
  236802. if (audioDevice != 0)
  236803. {
  236804. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: audioDevice];
  236805. [session addInput: audioInput error: &err];
  236806. }
  236807. }
  236808. void addListener (CameraDevice::Listener* listenerToAdd)
  236809. {
  236810. const ScopedLock sl (listenerLock);
  236811. if (listeners.size() == 0)
  236812. [session addOutput: imageOutput error: nil];
  236813. listeners.addIfNotAlreadyThere (listenerToAdd);
  236814. }
  236815. void removeListener (CameraDevice::Listener* listenerToRemove)
  236816. {
  236817. const ScopedLock sl (listenerLock);
  236818. listeners.removeValue (listenerToRemove);
  236819. if (listeners.size() == 0)
  236820. [session removeOutput: imageOutput];
  236821. }
  236822. void callListeners (CIImage* frame, int w, int h)
  236823. {
  236824. CoreGraphicsImage* cgImage = new CoreGraphicsImage (Image::ARGB, w, h, false);
  236825. Image image (cgImage);
  236826. CIContext* cic = [CIContext contextWithCGContext: cgImage->context options: nil];
  236827. [cic drawImage: frame inRect: CGRectMake (0, 0, w, h) fromRect: CGRectMake (0, 0, w, h)];
  236828. CGContextFlush (cgImage->context);
  236829. const ScopedLock sl (listenerLock);
  236830. for (int i = listeners.size(); --i >= 0;)
  236831. {
  236832. CameraDevice::Listener* const l = listeners[i];
  236833. if (l != 0)
  236834. l->imageReceived (image);
  236835. }
  236836. }
  236837. QTCaptureDevice* device;
  236838. QTCaptureDeviceInput* input;
  236839. QTCaptureDevice* audioDevice;
  236840. QTCaptureDeviceInput* audioInput;
  236841. QTCaptureSession* session;
  236842. QTCaptureMovieFileOutput* fileOutput;
  236843. QTCaptureDecompressedVideoOutput* imageOutput;
  236844. QTCaptureCallbackDelegate* callbackDelegate;
  236845. String openingError;
  236846. Array<CameraDevice::Listener*> listeners;
  236847. CriticalSection listenerLock;
  236848. };
  236849. END_JUCE_NAMESPACE
  236850. @implementation QTCaptureCallbackDelegate
  236851. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner_
  236852. internalDev: (QTCameraDeviceInteral*) d
  236853. {
  236854. [super init];
  236855. owner = owner_;
  236856. internal = d;
  236857. firstPresentationTime = 0;
  236858. averageTimeOffset = 0;
  236859. return self;
  236860. }
  236861. - (void) dealloc
  236862. {
  236863. [super dealloc];
  236864. }
  236865. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  236866. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  236867. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236868. fromConnection: (QTCaptureConnection*) connection
  236869. {
  236870. if (internal->listeners.size() > 0)
  236871. {
  236872. const ScopedAutoReleasePool pool;
  236873. internal->callListeners ([CIImage imageWithCVImageBuffer: videoFrame],
  236874. CVPixelBufferGetWidth (videoFrame),
  236875. CVPixelBufferGetHeight (videoFrame));
  236876. }
  236877. }
  236878. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  236879. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  236880. fromConnection: (QTCaptureConnection*) connection
  236881. {
  236882. const Time now (Time::getCurrentTime());
  236883. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  236884. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: QTSampleBufferHostTimeAttribute];
  236885. #else
  236886. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: @"hostTime"];
  236887. #endif
  236888. int64 presentationTime = (hosttime != nil)
  236889. ? ((int64) AudioConvertHostTimeToNanos ([hosttime unsignedLongLongValue]) / 1000000 + 40)
  236890. : (([sampleBuffer presentationTime].timeValue * 1000) / [sampleBuffer presentationTime].timeScale + 50);
  236891. const int64 timeDiff = now.toMilliseconds() - presentationTime;
  236892. if (firstPresentationTime == 0)
  236893. {
  236894. firstPresentationTime = presentationTime;
  236895. averageTimeOffset = timeDiff;
  236896. }
  236897. else
  236898. {
  236899. averageTimeOffset = (averageTimeOffset * 120 + timeDiff * 8) / 128;
  236900. }
  236901. }
  236902. @end
  236903. BEGIN_JUCE_NAMESPACE
  236904. class QTCaptureViewerComp : public NSViewComponent
  236905. {
  236906. public:
  236907. QTCaptureViewerComp (CameraDevice* const cameraDevice, QTCameraDeviceInteral* const internal)
  236908. {
  236909. const ScopedAutoReleasePool pool;
  236910. captureView = [[QTCaptureView alloc] init];
  236911. [captureView setCaptureSession: internal->session];
  236912. setSize (640, 480); // xxx need to somehow get the movie size - how?
  236913. setView (captureView);
  236914. }
  236915. ~QTCaptureViewerComp()
  236916. {
  236917. setView (0);
  236918. [captureView setCaptureSession: nil];
  236919. [captureView release];
  236920. }
  236921. QTCaptureView* captureView;
  236922. };
  236923. CameraDevice::CameraDevice (const String& name_, int index)
  236924. : name (name_)
  236925. {
  236926. isRecording = false;
  236927. internal = new QTCameraDeviceInteral (this, index);
  236928. }
  236929. CameraDevice::~CameraDevice()
  236930. {
  236931. stopRecording();
  236932. delete static_cast <QTCameraDeviceInteral*> (internal);
  236933. internal = 0;
  236934. }
  236935. Component* CameraDevice::createViewerComponent()
  236936. {
  236937. return new QTCaptureViewerComp (this, static_cast <QTCameraDeviceInteral*> (internal));
  236938. }
  236939. const String CameraDevice::getFileExtension()
  236940. {
  236941. return ".mov";
  236942. }
  236943. void CameraDevice::startRecordingToFile (const File& file, int quality)
  236944. {
  236945. stopRecording();
  236946. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  236947. d->callbackDelegate->firstPresentationTime = 0;
  236948. file.deleteFile();
  236949. // In some versions of QT (e.g. on 10.5), if you record video without audio, the speed comes
  236950. // out wrong, so we'll put some audio in there too..,
  236951. d->addDefaultAudioInput();
  236952. [d->session addOutput: d->fileOutput error: nil];
  236953. NSEnumerator* connectionEnumerator = [[d->fileOutput connections] objectEnumerator];
  236954. for (;;)
  236955. {
  236956. QTCaptureConnection* connection = [connectionEnumerator nextObject];
  236957. if (connection == 0)
  236958. break;
  236959. QTCompressionOptions* options = 0;
  236960. NSString* mediaType = [connection mediaType];
  236961. if ([mediaType isEqualToString: QTMediaTypeVideo])
  236962. options = [QTCompressionOptions compressionOptionsWithIdentifier:
  236963. quality >= 1 ? @"QTCompressionOptionsSD480SizeH264Video"
  236964. : @"QTCompressionOptions240SizeH264Video"];
  236965. else if ([mediaType isEqualToString: QTMediaTypeSound])
  236966. options = [QTCompressionOptions compressionOptionsWithIdentifier: @"QTCompressionOptionsHighQualityAACAudio"];
  236967. [d->fileOutput setCompressionOptions: options forConnection: connection];
  236968. }
  236969. [d->fileOutput recordToOutputFileURL: [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]];
  236970. isRecording = true;
  236971. }
  236972. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  236973. {
  236974. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  236975. if (d->callbackDelegate->firstPresentationTime != 0)
  236976. return Time (d->callbackDelegate->firstPresentationTime + d->callbackDelegate->averageTimeOffset);
  236977. return Time();
  236978. }
  236979. void CameraDevice::stopRecording()
  236980. {
  236981. if (isRecording)
  236982. {
  236983. static_cast <QTCameraDeviceInteral*> (internal)->resetFile();
  236984. isRecording = false;
  236985. }
  236986. }
  236987. void CameraDevice::addListener (Listener* listenerToAdd)
  236988. {
  236989. if (listenerToAdd != 0)
  236990. static_cast <QTCameraDeviceInteral*> (internal)->addListener (listenerToAdd);
  236991. }
  236992. void CameraDevice::removeListener (Listener* listenerToRemove)
  236993. {
  236994. if (listenerToRemove != 0)
  236995. static_cast <QTCameraDeviceInteral*> (internal)->removeListener (listenerToRemove);
  236996. }
  236997. const StringArray CameraDevice::getAvailableDevices()
  236998. {
  236999. const ScopedAutoReleasePool pool;
  237000. StringArray results;
  237001. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  237002. for (int i = 0; i < (int) [devs count]; ++i)
  237003. {
  237004. QTCaptureDevice* dev = (QTCaptureDevice*) [devs objectAtIndex: i];
  237005. results.add (nsStringToJuce ([dev localizedDisplayName]));
  237006. }
  237007. return results;
  237008. }
  237009. CameraDevice* CameraDevice::openDevice (int index,
  237010. int minWidth, int minHeight,
  237011. int maxWidth, int maxHeight)
  237012. {
  237013. ScopedPointer <CameraDevice> d (new CameraDevice (getAvailableDevices() [index], index));
  237014. if (static_cast <QTCameraDeviceInteral*> (d->internal)->openingError.isEmpty())
  237015. return d.release();
  237016. return 0;
  237017. }
  237018. #endif
  237019. /*** End of inlined file: juce_mac_CameraDevice.mm ***/
  237020. #endif
  237021. #endif
  237022. END_JUCE_NAMESPACE
  237023. #endif
  237024. /*** End of inlined file: juce_mac_NativeCode.mm ***/
  237025. #endif
  237026. #endif